From 7d7d8e18c35007846ee239d8a6fde7b2cf3b1d02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 06:44:07 +0900 Subject: [PATCH 1/7] [AUTOMATED] Add the engine hooks a differential checker needs A rule cap that counts rule applications per thread and can stop one rule after its first n, checked once per rule attempt in ActionPool::process_op and inert unless armed; Funcdata::vararg_folded, the register-save stores the varargsave fold removes; kuna_narrowext::rules_for for a given mode; IfaceStatus::last_command; and interface::quote_filename, moved from kuna-cli so other callers can reach it. With every hook unset kuna's output is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../crates/kuna-cli/src/decompile/script.rs | 9 +- .../crates/kuna-console/src/interface.rs | 15 ++++ .../crates/kuna-decomp/src/infra/action.rs | 7 ++ .../kuna-decomp/src/infra/kuna_rulecap.rs | 89 +++++++++++++++++++ .../crates/kuna-decomp/src/infra/mod.rs | 1 + .../src/p4_calls/kuna_narrowext.rs | 9 +- .../src/p4_calls/kuna_varargsave.rs | 27 ++++++ .../kuna-decomp/src/substrate/funcdata.rs | 8 ++ docs/spec/00-overview.md | 11 +++ docs/spec/04-calls-and-prototypes.md | 7 +- 10 files changed, 172 insertions(+), 11 deletions(-) create mode 100644 decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs diff --git a/decompiler/crates/kuna-cli/src/decompile/script.rs b/decompiler/crates/kuna-cli/src/decompile/script.rs index 7e6e252aa0..c917e5d56d 100644 --- a/decompiler/crates/kuna-cli/src/decompile/script.rs +++ b/decompiler/crates/kuna-cli/src/decompile/script.rs @@ -3,6 +3,7 @@ use std::borrow::Cow; use std::path::Path; use kuna_console::engine::EntrySelector; +pub(super) use kuna_console::interface::quote_filename as console_path; use super::DecompileArgs; /// An addressed VMA, excluding section coordinates and invalid numbers. @@ -23,14 +24,6 @@ fn selected_vma(target: &str, by_address: bool) -> Option { u64::from_str_radix(digits, 16).ok() } -/// Borrow ordinary paths; quote only characters the console would split. -pub(super) fn console_path(path: &str) -> Cow<'_, str> { - if !path.as_bytes().iter().any(|b| b.is_ascii_whitespace() || *b == b'"') { - return Cow::Borrowed(path); - } - Cow::Owned(format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\""))) -} - /// The line-based transport cannot carry embedded newlines, even when quoted. pub(super) fn reject_unquotable(what: &str, path: &str) -> Result<(), String> { match path.find(['\n', '\r']) { diff --git a/decompiler/crates/kuna-console/src/interface.rs b/decompiler/crates/kuna-console/src/interface.rs index c7137a36ba..6517033f12 100644 --- a/decompiler/crates/kuna-console/src/interface.rs +++ b/decompiler/crates/kuna-console/src/interface.rs @@ -182,6 +182,14 @@ pub struct CommandStream { eof: bool, } +/// Encode a filename for [`CommandStream::read_filename`]. +pub fn quote_filename(path: &str) -> std::borrow::Cow<'_, str> { + if !path.as_bytes().iter().any(|b| b.is_ascii_whitespace() || *b == b'"') { + return std::borrow::Cow::Borrowed(path); + } + std::borrow::Cow::Owned(format!("\"{}\"", path.replace('\\', "\\\\").replace('"', "\\\""))) +} + impl CommandStream { /// Construct a stream over the given command line (C++ /// `istringstream is(line)`). @@ -851,6 +859,9 @@ pub struct IfaceStatus { /// a `map`, a `kassert`) silently invalidates the reuse rather than needing /// its own invalidation hook. pub command_seq: u64, + /// The words of the last command line resolved to a registered command, + /// abbreviations expanded; empty when the line resolved to none. + pub last_command: Vec, } /// An open bulk-output redirect (`openfile`/`openfile append`). @@ -889,6 +900,7 @@ impl IfaceStatus { datamap: BTreeMap::new(), source, command_seq: 0, + last_command: Vec::new(), } } @@ -1142,6 +1154,7 @@ impl IfaceStatus { let mut source = std::mem::replace(&mut self.source, Box::new(DetachedSource)); let line = source.read_line(self); self.source = source; + self.last_command.clear(); if line.is_empty() { return Ok(false); } @@ -1153,6 +1166,7 @@ impl IfaceStatus { let mut expand: Vec = Vec::new(); let (mut first, mut last) = (0usize, self.comlist.len()); let mat = self.expand_com(&mut expand, &mut is, &mut first, &mut last); + self.last_command.clear(); if mat == 0 { self.out("ERROR: Invalid command\n"); @@ -1178,6 +1192,7 @@ impl IfaceStatus { Box::new(DummyAction), ); self.command_seq = self.command_seq.wrapping_add(1); + self.last_command = self.comlist[first].com.clone(); let res = action.execute(self, &mut is); self.comlist[first].action = action; res?; diff --git a/decompiler/crates/kuna-decomp/src/infra/action.rs b/decompiler/crates/kuna-decomp/src/infra/action.rs index 2e2acb4f58..f171ad7c72 100644 --- a/decompiler/crates/kuna-decomp/src/infra/action.rs +++ b/decompiler/crates/kuna-decomp/src/infra/action.rs @@ -1351,9 +1351,16 @@ impl ActionPool { if far_only && !self.allrules[rl_idx].rule.walks_far() { continue; } + let capped_at = crate::kuna_rulecap::armed().then(|| data.obank().get(op).map_or(0, |o| o.get_addr().get_offset())); + if capped_at.is_some() && !crate::kuna_rulecap::allows(&self.allrules[rl_idx].state.name) { + continue; + } self.allrules[rl_idx].state.count_tests += 1; let res = self.allrules[rl_idx].rule.apply_op(op, data); if res > 0 { + if let Some(addr) = capped_at { + crate::kuna_rulecap::note(&self.allrules[rl_idx].state.name, addr); + } far_only = false; if self.allrules[rl_idx].rule.removes_dead_ops() && data.obank().get(op).is_none_or(|o| o.is_dead()) diff --git a/decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs b/decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs new file mode 100644 index 0000000000..555b9deca4 --- /dev/null +++ b/decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs @@ -0,0 +1,89 @@ +//! (kuna) Counting and capping rule applications in one decompile, for a +//! differential checker that looks for the rule application after which the +//! decompiled function computes something else (`docs/spec/00-overview.md`). +//! +//! Unarmed, the default, every rule applies as usual and the only cost is one +//! thread-local flag read per rule attempt. Armed, every application is +//! counted by rule name, and [`Mode::Limit`] lets one rule apply only its first +//! `allow` times; every other rule and every action runs as usual, so the +//! decompile completes. The address of that rule's last application is kept. + +use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Mode { + Observe, + Limit { rule: String, allow: u64 }, +} + +/// What an armed decompile applied. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Record { + /// Applications per rule name. + pub counts: BTreeMap, + /// [`Mode::Limit`]: the op address of the limited rule's last application. + pub last: Option, + /// Every application's rule, in the order they were made. + pub sequence: Vec, +} + +thread_local! { + static ARMED: Cell = const { Cell::new(false) }; + static STATE: RefCell<(Option, Record)> = const { RefCell::new((None, Record { counts: BTreeMap::new(), last: None, sequence: Vec::new() })) }; +} + +pub fn arm(mode: Mode) { + STATE.with(|s| *s.borrow_mut() = (Some(mode), Record::default())); + ARMED.with(|a| a.set(true)); +} + +pub fn disarm() -> Record { + ARMED.with(|a| a.set(false)); + STATE.with(|s| std::mem::take(&mut s.borrow_mut().1)) +} + +#[inline] +pub(crate) fn armed() -> bool { + ARMED.with(Cell::get) +} + +/// Whether `rule` may apply once more. +pub(crate) fn allows(rule: &str) -> bool { + STATE.with(|s| match &s.borrow().0 { + Some(Mode::Limit { rule: r, allow }) if r == rule => s.borrow().1.counts.get(rule).copied().unwrap_or(0) < *allow, + _ => true, + }) +} + +pub(crate) fn note(rule: &str, addr: u64) { + STATE.with(|s| { + let mut s = s.borrow_mut(); + *s.1.counts.entry(rule.to_string()).or_default() += 1; + s.1.sequence.push(rule.to_string()); + if matches!(&s.0, Some(Mode::Limit { rule: r, .. }) if r == rule) { + s.1.last = Some(addr); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_limit_stops_one_rule_and_counts_all() { + assert!(!armed()); + arm(Mode::Limit { rule: "RuleX".into(), allow: 1 }); + assert!(armed() && allows("RuleX")); + note("RuleX", 0x40); + note("RuleY", 0x44); + assert!(!allows("RuleX") && allows("RuleY")); + let r = disarm(); + assert_eq!(r.counts.get("RuleX"), Some(&1)); + assert_eq!(r.counts.get("RuleY"), Some(&1)); + assert_eq!(r.last, Some(0x40)); + assert_eq!(r.sequence, ["RuleX", "RuleY"]); + assert!(!armed()); + } +} diff --git a/decompiler/crates/kuna-decomp/src/infra/mod.rs b/decompiler/crates/kuna-decomp/src/infra/mod.rs index b3a84d2167..d481d41a48 100644 --- a/decompiler/crates/kuna-decomp/src/infra/mod.rs +++ b/decompiler/crates/kuna-decomp/src/infra/mod.rs @@ -10,6 +10,7 @@ pub mod kuna_decodekit; pub mod remote_provider; pub mod decompile_drive; pub mod kuna_fnmemory; +pub mod kuna_rulecap; pub mod kuna_fasthash; pub mod kuna_hostmem; pub mod capability; diff --git a/decompiler/crates/kuna-decomp/src/p4_calls/kuna_narrowext.rs b/decompiler/crates/kuna-decomp/src/p4_calls/kuna_narrowext.rs index 6082fdcc4f..aa5a6e3912 100644 --- a/decompiler/crates/kuna-decomp/src/p4_calls/kuna_narrowext.rs +++ b/decompiler/crates/kuna-decomp/src/p4_calls/kuna_narrowext.rs @@ -85,10 +85,15 @@ pub struct Rules { /// The rules for `arch` under its `narrowext` value. pub fn rules(arch: &Architecture) -> Rules { + rules_for(arch, arch.narrow_ext) +} + +/// The rules for `arch` under `mode`. +pub fn rules_for(arch: &Architecture, mode: NarrowExtMode) -> Rules { let id = arch.archid.as_str(); - let compiler = arch.narrow_ext == NarrowExtMode::Compiler; + let compiler = mode == NarrowExtMode::Compiler; let gated = |w, documented: bool| (compiler || documented).then_some(w); - match arch.narrow_ext { + match mode { NarrowExtMode::Off => Rules::default(), _ if id.starts_with("RISCV:") || id.starts_with("Loongarch:") => Rules { input: Some(Widen::Register), diff --git a/decompiler/crates/kuna-decomp/src/p4_calls/kuna_varargsave.rs b/decompiler/crates/kuna-decomp/src/p4_calls/kuna_varargsave.rs index d9cf5a8c4e..ddde049f08 100644 --- a/decompiler/crates/kuna-decomp/src/p4_calls/kuna_varargsave.rs +++ b/decompiler/crates/kuna-decomp/src/p4_calls/kuna_varargsave.rs @@ -81,6 +81,8 @@ const XMM_ARGS: [&str; 8] = [ ]; /// Bytes of the general-register part of the save area. const GP_AREA: i64 = 48; +/// Bytes of the whole save area: six general and eight vector registers. +pub const SAVE_AREA: i64 = GP_AREA + 16 * 8; /// Bytes of a `va_list` before its `reg_save_area` field, and of the field. const VA_LIST_HEAD: i64 = 16; const VA_LIST_FIELD: i64 = 8; @@ -100,6 +102,21 @@ struct Plan { guard: BlockId, edge: int4, gp_stores: Vec, + folded: Folded, +} + +/// The stores a fold removed, so a reader of the function can put back what +/// `va_start` means: each register at the incoming stack pointer plus a frame +/// offset, the vector registers only when the incoming `al` is nonzero. +#[derive(Clone, Debug, Default)] +pub struct Folded { + /// The save area's offset from the incoming stack pointer; it spans + /// [`SAVE_AREA`] bytes. + pub area: i64, + /// The `al` register: offset and size in the register space. + pub al: (u64, u32), + /// `(register offset, register size, frame offset, vector)` per store. + pub stores: Vec<(u64, u32, i64, bool)>, } /// Fold the prologue of `fd` when it matches; called once, right after the @@ -124,6 +141,7 @@ pub(crate) fn fold(fd: &mut Funcdata) -> bool { } } fd.kuna_vararg_save = true; + fd.kuna_vararg_folded = Some(plan.folded); true } @@ -600,10 +618,19 @@ fn find(fd: &Funcdata) -> Option { if body_reads_save_area(fd, &fr, sp, area, &saved) { return None; } + let place = |r: &Reg| (r.offset, r.size as u32); + let mut stores: Vec<(u64, u32, i64, bool)> = gp_saves + .iter() + .map(|&(k, _)| (place(&gp[k as usize]), area + 8 * k as i64, false)) + .chain(xmm_saves.iter().map(|&(j, off)| (place(&xmm[j as usize]), off, true))) + .map(|((o, n), f, v)| (o, n, f, v)) + .collect(); + stores.sort_unstable_by_key(|s| s.2); Some(Plan { guard: candidate, edge: blocks.block(candidate).get_out_index(save_block), gp_stores: gp_saves.into_iter().map(|(_, op)| op).collect(), + folded: Folded { area, al: place(&al), stores }, }) } diff --git a/decompiler/crates/kuna-decomp/src/substrate/funcdata.rs b/decompiler/crates/kuna-decomp/src/substrate/funcdata.rs index 7b43169083..618b828d77 100644 --- a/decompiler/crates/kuna-decomp/src/substrate/funcdata.rs +++ b/decompiler/crates/kuna-decomp/src/substrate/funcdata.rs @@ -190,6 +190,7 @@ pub struct Funcdata { /// (kuna `varargsave`) Set when the first heritage pass folded this /// function's variadic register-save prologue (`p4_calls/kuna_varargsave.rs`). pub(crate) kuna_vararg_save: bool, + pub(crate) kuna_vararg_folded: Option, /// (kuna) The argument registers the first heritage saw spilled to their /// Windows x64 home slots (`p4_calls/kuna_homespill.rs`). pub(crate) kuna_home_spills: Vec<(Address, int4)>, @@ -904,6 +905,7 @@ impl Funcdata { kuna_x87_empty_returns: Vec::new(), kuna_flag_tests: Box::default(), kuna_vararg_save: false, + kuna_vararg_folded: None, kuna_home_spills: Vec::new(), kuna_flow_ranges: Vec::new(), kuna_unoptimized: None, @@ -2684,6 +2686,11 @@ impl Funcdata { self.heritage.num_heritage_passes(spc) } + /// (kuna `varargsave`) The register-save stores the fold removed. + pub fn vararg_folded(&self) -> Option<&crate::kuna_varargsave::Folded> { + self.kuna_vararg_folded.as_ref() + } + /// Overall count of heritage passes (C++ `Funcdata::getHeritagePass`, /// `funcdata.hh:239` — `heritage.getPass()`). pub fn get_heritage_pass(&self) -> int4 { @@ -4862,6 +4869,7 @@ impl Funcdata { self.kuna_x87_empty_returns.clear(); *self.kuna_flag_tests = Default::default(); self.kuna_vararg_save = false; + self.kuna_vararg_folded = None; self.kuna_home_spills.clear(); self.kuna_flow_ranges.clear(); self.kuna_unoptimized = None; diff --git a/docs/spec/00-overview.md b/docs/spec/00-overview.md index 627851edae..a10825641a 100644 --- a/docs/spec/00-overview.md +++ b/docs/spec/00-overview.md @@ -4253,6 +4253,17 @@ a partial clone beside it. The root label is set where the variant is selected point: it changes nothing the engine emits, and with the variable unset it costs one cached read per `apply`. +A rule pool also answers to a per-thread rule cap +(`decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs`), for a differential +checker that looks for the rule application after which a decompile computes +something other than the binary. Armed, every rule application is counted by +rule name, in order, with the address of the op it rewrote. One named rule can +be limited to its first `n` applications (`ActionPool::process_op` skips it +after that), while every other rule and every action runs as usual, so the +decompile still completes. Unarmed, the default and the only state the `kuna` +binary uses, the pool reads one thread-local flag per rule attempt and nothing +else changes. + ## 0.7 Feedback edges The pipeline is a fixpoint machine wearing a pipeline's clothes. Beyond the diff --git a/docs/spec/04-calls-and-prototypes.md b/docs/spec/04-calls-and-prototypes.md index de857cf053..7ff2e04c13 100644 --- a/docs/spec/04-calls-and-prototypes.md +++ b/docs/spec/04-calls-and-prototypes.md @@ -9064,7 +9064,12 @@ parameters, and `ActionInputPrototype` gives the recovered prototype its `...` (mark_variadic)`); a prototype with no named parameter prints `(...)`. The `va_list` field initialisations stay as assignments (`v1 = 8; v3 = 0x30; v4 = __builtin_dwarf_cfa(); v5 = v2;`), and `va_arg` in a function's own body -is not recognised. `protoorder` still declines a variadic recovered prototype +is not recognised. The fold keeps a record of the stores it removed, the save +area's offset from the entry stack pointer and each register with its slot +(`Funcdata::vararg_folded`), so a reader of the IR can put back what `va_start` +means (a checker that runs the IR fills the save area from it, as `va_start` +would). +`protoorder` still declines a variadic recovered prototype (`Decline::Variadic`), so callers recover their own arguments to such a function. `tests/stages/kuna-varargsave.xml` checks two folded functions, the two refused shapes and the option off. Windows x64 and every other target are untouched. From 78ae1ba676869de0b320367879841d1b7dec5d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 07:18:27 +0900 Subject: [PATCH 2/7] [AUTOMATED] Add kuna-verify, a differential check of the final IR against the machine code kuna-verify runs a function's SLEIGH p-code and kuna's final Funcdata from the same random machine state, and compares the calls each makes and their arguments, the memory written outside the frame and the value returned. `check` runs it on functions of a binary, `corpus` on every decompile the datatest corpus makes, and `mutate` plants faults on kuna's side to measure how many the check catches. Slices C1, C2 and C4 of the diffverify proposal. Rule localization, concolic inputs, single-instruction (Tier L) and symbolic (Tier S) checks, the function oracle, the calling-convention model check and the CI baseline come in their own changes. Every corpus verdict matches the unsplit tool's on the same base. Co-Authored-By: Claude Opus 5.5 --- decompiler/Cargo.lock | 17 + decompiler/crates/kuna-verify/AGENTS.md | 129 ++ decompiler/crates/kuna-verify/CLAUDE.md | 1 + decompiler/crates/kuna-verify/Cargo.toml | 40 + .../crates/kuna-verify/src/abi/calls.rs | 568 +++++++ .../crates/kuna-verify/src/abi/contract.rs | 252 ++++ .../crates/kuna-verify/src/abi/divergence.rs | 199 +++ decompiler/crates/kuna-verify/src/abi/mod.rs | 288 ++++ .../crates/kuna-verify/src/bin/kuna-verify.rs | 873 +++++++++++ .../crates/kuna-verify/src/compare/check.rs | 730 +++++++++ .../crates/kuna-verify/src/compare/mod.rs | 6 + .../crates/kuna-verify/src/compare/observe.rs | 475 ++++++ .../crates/kuna-verify/src/compare/returns.rs | 179 +++ .../crates/kuna-verify/src/compare/setup.rs | 225 +++ .../crates/kuna-verify/src/graph/mod.rs | 703 +++++++++ .../crates/kuna-verify/src/graph/program.rs | 425 ++++++ decompiler/crates/kuna-verify/src/lib.rs | 186 +++ .../crates/kuna-verify/src/machine/mod.rs | 1200 +++++++++++++++ .../kuna-verify/src/machine/rep_copy.rs | 106 ++ .../crates/kuna-verify/src/machine/tests.rs | 37 + .../crates/kuna-verify/src/machine/thunk.rs | 145 ++ .../crates/kuna-verify/src/report/mod.rs | 167 +++ .../crates/kuna-verify/src/semantics/mod.rs | 6 + .../kuna-verify/src/semantics/storage.rs | 81 + .../crates/kuna-verify/src/semantics/value.rs | 552 +++++++ .../crates/kuna-verify/src/semantics/x87.rs | 206 +++ decompiler/crates/kuna-verify/src/session.rs | 314 ++++ .../crates/kuna-verify/src/state/mem.rs | 187 +++ .../crates/kuna-verify/src/state/mod.rs | 1309 +++++++++++++++++ .../kuna-verify/src/state/stack_inputs.rs | 64 + .../crates/kuna-verify/src/state/tests.rs | 108 ++ .../crates/kuna-verify/src/tools/mod.rs | 3 + .../crates/kuna-verify/src/tools/mutate.rs | 315 ++++ .../crates/kuna-verify/tests/call_effects.rs | 74 + .../kuna-verify/tests/datatest_isolation.rs | 31 + .../crates/kuna-verify/tests/integration.rs | 8 + .../kuna-verify/tests/stage_verdicts.rs | 214 +++ .../kuna-verify/tests/verdict_guards.rs | 878 +++++++++++ .../crates/kuna-verify/tests/zext_pair.rs | 130 ++ docs/agents.md | 3 +- docs/features/diffverify/README.md | 393 +++++ docs/features/diffverify/analysis.md | 3 +- docs/features/diffverify/c1-results.md | 134 ++ docs/features/diffverify/c2-results.md | 118 ++ .../diffverify/c4-decbench-results.md | 235 +++ docs/features/diffverify/c4-results.md | 404 +++++ docs/features/diffverify/mutation.md | 108 ++ docs/features/diffverify/proposal.md | 101 +- docs/features/diffverify/record.json | 154 ++ docs/features/diffverify/triage.md | 162 ++ 50 files changed, 13216 insertions(+), 30 deletions(-) create mode 100644 decompiler/crates/kuna-verify/AGENTS.md create mode 120000 decompiler/crates/kuna-verify/CLAUDE.md create mode 100644 decompiler/crates/kuna-verify/Cargo.toml create mode 100644 decompiler/crates/kuna-verify/src/abi/calls.rs create mode 100644 decompiler/crates/kuna-verify/src/abi/contract.rs create mode 100644 decompiler/crates/kuna-verify/src/abi/divergence.rs create mode 100644 decompiler/crates/kuna-verify/src/abi/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/bin/kuna-verify.rs create mode 100644 decompiler/crates/kuna-verify/src/compare/check.rs create mode 100644 decompiler/crates/kuna-verify/src/compare/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/compare/observe.rs create mode 100644 decompiler/crates/kuna-verify/src/compare/returns.rs create mode 100644 decompiler/crates/kuna-verify/src/compare/setup.rs create mode 100644 decompiler/crates/kuna-verify/src/graph/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/graph/program.rs create mode 100644 decompiler/crates/kuna-verify/src/lib.rs create mode 100644 decompiler/crates/kuna-verify/src/machine/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/machine/rep_copy.rs create mode 100644 decompiler/crates/kuna-verify/src/machine/tests.rs create mode 100644 decompiler/crates/kuna-verify/src/machine/thunk.rs create mode 100644 decompiler/crates/kuna-verify/src/report/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/semantics/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/semantics/storage.rs create mode 100644 decompiler/crates/kuna-verify/src/semantics/value.rs create mode 100644 decompiler/crates/kuna-verify/src/semantics/x87.rs create mode 100644 decompiler/crates/kuna-verify/src/session.rs create mode 100644 decompiler/crates/kuna-verify/src/state/mem.rs create mode 100644 decompiler/crates/kuna-verify/src/state/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/state/stack_inputs.rs create mode 100644 decompiler/crates/kuna-verify/src/state/tests.rs create mode 100644 decompiler/crates/kuna-verify/src/tools/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/tools/mutate.rs create mode 100644 decompiler/crates/kuna-verify/tests/call_effects.rs create mode 100644 decompiler/crates/kuna-verify/tests/datatest_isolation.rs create mode 100644 decompiler/crates/kuna-verify/tests/integration.rs create mode 100644 decompiler/crates/kuna-verify/tests/stage_verdicts.rs create mode 100644 decompiler/crates/kuna-verify/tests/verdict_guards.rs create mode 100644 decompiler/crates/kuna-verify/tests/zext_pair.rs create mode 100644 docs/features/diffverify/README.md create mode 100644 docs/features/diffverify/c1-results.md create mode 100644 docs/features/diffverify/c2-results.md create mode 100644 docs/features/diffverify/c4-decbench-results.md create mode 100644 docs/features/diffverify/c4-results.md create mode 100644 docs/features/diffverify/mutation.md create mode 100644 docs/features/diffverify/triage.md diff --git a/decompiler/Cargo.lock b/decompiler/Cargo.lock index 941dbd5121..2775b0a799 100644 --- a/decompiler/Cargo.lock +++ b/decompiler/Cargo.lock @@ -408,6 +408,23 @@ dependencies = [ "kuna-num", ] +[[package]] +name = "kuna-verify" +version = "0.1.0" +dependencies = [ + "kuna-base", + "kuna-console", + "kuna-decomp", + "kuna-num", + "kuna-sleigh", + "object", + "regex", + "serde_json", + "sha2", + "slotmap", + "tempfile", +] + [[package]] name = "kuna-wasm" version = "0.1.0" diff --git a/decompiler/crates/kuna-verify/AGENTS.md b/decompiler/crates/kuna-verify/AGENTS.md new file mode 100644 index 0000000000..330da0ccce --- /dev/null +++ b/decompiler/crates/kuna-verify/AGENTS.md @@ -0,0 +1,129 @@ +# kuna-verify — agent notes + +`kuna-verify` is a dev-only tool: it runs kuna's final IR and the machine code from one +state and compares them. Read `docs/features/diffverify/README.md` before changing it, and +`docs/features/diffverify/triage.md` before naming the cause of a `DIFFERS`. The root +`AGENTS.md` still applies. + +## Rules + +- **A `DIFFERS` is not a kuna bug until the harness is ruled out.** Most false ones so + far were the checker's, not the decompiler's. Follow `triage.md`: the cause can be + kuna, the SLEIGH spec, the reference emulator, the checker's evaluator or the harness. +- **Cross-check against an external tool wherever one can run the same thing.** The + machine side and kuna's side share the p-code semantics and the SLEIGH specs, so an + error there is the same on both and this check cannot see it. Run the instruction, + function or input through an independent tool as well (Unicorn or QEMU, as Tier L does; + real hardware; a compiler's own output) and compare. When they disagree, do not assume + either side is right: decide whether the external tool, our evaluator or the spec is + wrong, from the architecture manual or a third run, and write down which (`triage.md`). +- **A harness change must not move verdicts it did not mean to move.** Before committing, + compare every verdict on the corpus, `ls` (`O2`, `O0`) and `find` against the previous + build, and explain each one that moved. +- **`docs/baseline-verify.json` is re-recorded only for a reason the commit names** (new + stage tests from main, a deliberate harness change), never to absorb a regression. +- **Fault injections into the engine stay local.** Plant them to test the check, then + revert; mutants (`kuna-verify mutate`) change only kuna's side, never the machine side. +- **New work goes in its folder** (`README.md` §5): a comparison in `compare/`, a fact + about calls in `abi/`, a tool in `tools/`, a later tier in a folder of its own. Keep + the old paths re-exported from `lib.rs`. +- **Recheck decbench functions by address, or leave out names a binary defines twice.** + Two functions of one binary can share a name, and `load function NAME` picks one. + +## Regressions + +One entry per trap an agent fell into here. Date, model and PR say when it was true; an +entry that no longer applies can be removed. + +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + Treated a `CALL_RETURN` flow override as "does not return". It also turns a branch + into a tail call, so gh8471's test became a false `DIFFERS`. Only a `CALL_RETURN` on a + call instruction is a no-return cut. +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + Read `RDI` at every nested call to decide whether `error(status, ...)` returns. LiveIn + tracking counted that read as the callee reading `RDI`, a false `DIFFERS` in + `calleefloatreads`. Read the status only for the `error` names, with tracking off. +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + Took every PLT thunk as an external call. That exposed an out-of-bounds frame pointer + (`ls` `O0` `group_number`) the check cannot yet judge. Keep it to the no-return check + until that has a design. +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + Followed pointers stored in a passed frame object (transitive escape), which reached a + `va_list`'s register save area. kuna's `varargsave` folds the stores that fill it, so + about 160 variadic functions stopped agreeing. kuna's side now fills the area as + `va_start` does, from `Funcdata::vararg_folded`. +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + Merged a by-name decbench recheck into an `--all` run keyed by name. Functions sharing + a name were mixed up, and four `libedit` functions looked fixed by a main merge when + they were not. +- 2026-11-24 · Claude Opus 5.5 · PR #1830 + The first `drop-arg` mutant shortened the call and left the prototype, so the check + caught it by construction and recall read too high. A mutant must leave kuna's facts + as a real fault would. +- 2026-11-25 · Claude Opus 5.5 · PR #1830 + Stopped the machine at a no-return call kuna thinks returns, to catch the missed + no-return. A callee that aborts only on some inputs then made `hash_insert` and others + `DIFFERS`, though kuna's C calls the same callee and stops too. Code after a call that + never returns is unreachable on both sides; missing that is not a semantic difference. +- 2026-11-25 · Claude Opus 5.5 · PR #1830 + Counted every argument suspect as a doubt that keeps a run from agreeing. A callee + reading a register its declared prototype does not take (Go's context register) is not + an argument kuna dropped; only a recovered prototype's suspect is a doubt. +- 2026-11-25 · Claude Opus 5.5 · PR #1830 + Compared a system call's arguments to the syscall registers by position. kuna's + `x64syscall` passes only the registers the block provably sets, in order, so a pass + that leaves one out became a false `DIFFERS` (`kuna-x64syscall` `pointer_before`). + They are matched in order from the first argument register; a match only as a + subsequence, with a register skipped in the middle, is `UNKNOWN`, since kuna's C then + passes the later values in the wrong registers. +- 2026-11-26 · Claude Opus 5.5 · PR #1830 + Skipped every comparison of a run in which kuna's `memcpy` overlapped. A fault before + the copy then read as the declared `copy-overlap`. A declared divergence cuts only + what follows it; what came before is compared. +- 2026-11-26 · Claude Opus 5.5 · PR #1830 + Took a system-call register the machine never touched as matching any value. It + holds its starting value, which the machine side now records at the call. +- 2026-11-26 · Claude Opus 5.5 · PR #1830 + Put back, after a callee run for real, every register the callee's prototype does + not list as killed. The x86-64 cspec lists only RAX, RDX and XMM0, so RDI, RSI, RCX + and R8-R11 came back too, and kuna's C keeping a value in R11 across a call that + changes it agreed (`ghangr-rust-probestack` `probe_observes_r11`). Only the model's + `unaffected` registers are put back now. A first try that instead stopped putting + anything back moved verdicts for that same reason; read the cspec lists before + blaming the rerun. + +- 2026-11-26 · Claude Opus 5.5 · PR #1830 + Took a top-level `RETURN` to an address other than the run's return address as a + return when the target was unmapped or kuna made no branch there. A function that + returns past its return address then agreed. Such a return is `UNKNOWN` now, but only + in a run that made no call: with calls, a stub's stack effect can move the stack + pointer (Go, `kuna-gobounds`), and refusing those broke pinned verdicts. Do not "fix" + the runs this leaves by stubbing every indirect call to a non-entry: that also stubs + real pointers the image holds and import slots (README §9). +- 2026-11-30 · Claude Opus 5.5 · PR #1830 + Put back after a callee every register the cspec lists as `unaffected`. ARM's lists + `lr` and `pc`, so a callee's own `bl` or return read as changing them, and about a + hundred ARM functions became `UNKNOWN(abi-violation)`. The link register and the + program counter are left out. Of the rest, 28 were a callee returning with + `ldr pc, [sp], #8`: the machine took that indirect branch to the call's continuation + as a jump inside the callee and ran the caller on as the callee, epilogue included. A + jump to the continuation is a return now. That also moved `_dtoa_r` from `AGREES` to + `UNKNOWN(budget)`: its body had been running on the callee's step pool. +- 2026-11-30 · Claude Opus 5.5 · PR #1830 + Checked a narrowed argument (`(int4)p` in `x0`) only where `Site::args` has a + storage. A recovered callee's argument is a trial with no prototype parameter, so + `args` holds `None` there and the review's AArch64 veneer still agreed silently; the + check reads `input_storage` too. A first version also counted that suspect as a + doubt, which would have turned a run that differs because of the cut into `UNKNOWN`. +- 2026-11-30 · Claude Opus 5.5 · PR #1830 + Pinned the narrowed-argument test on the review's AArch64 veneer, a case that was a + kuna bug. Main's `kuna_wholeinputarg` (#2035) then passed the stated pointer whole, + the suspect went away, and the test failed only on CI's merge with main. Pin a check + on a cut kuna makes by design (a recovered `int` forwarded in the low half of `RDI`), + and run the suite on a merge with main before pushing. +- 2026-12-02 · Claude Opus 5.5 · PR #1830 + Took `corpus --jobs 1` and `--jobs N` as the same run. `option` exports a load-time + value (`ppc32picimports abi`) to the process environment, and in one process it reached + the next file's first `load file`: `kuna-ppc32picimports-runtime`'s first `check` + agreed after the abi test and was `UNKNOWN` alone. `load_datatest` now hands back a + `LoadEnv` that puts the environment back; hold it until the script has run. diff --git a/decompiler/crates/kuna-verify/CLAUDE.md b/decompiler/crates/kuna-verify/CLAUDE.md new file mode 120000 index 0000000000..47dc3e3d86 --- /dev/null +++ b/decompiler/crates/kuna-verify/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/decompiler/crates/kuna-verify/Cargo.toml b/decompiler/crates/kuna-verify/Cargo.toml new file mode 100644 index 0000000000..0d0e6ad262 --- /dev/null +++ b/decompiler/crates/kuna-verify/Cargo.toml @@ -0,0 +1,40 @@ +[package] +autotests = false +name = "kuna-verify" +description = "kuna dev-only differential semantic checking: the machine's lifted code against the decompiled function (diffverify)" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +kuna-base.workspace = true +kuna-num.workspace = true +kuna-sleigh.workspace = true +kuna-decomp.workspace = true +kuna-console.workspace = true +object.workspace = true +regex.workspace = true +serde_json = "1" +sha2 = "0.11" +slotmap.workspace = true +tempfile = "3.27" + +[dev-dependencies] +object = { workspace = true, features = ["write"] } + +[lints] +workspace = true + +[[bin]] +name = "kuna-verify" +path = "src/bin/kuna-verify.rs" + +[[test]] +name = "integration" +path = "tests/integration.rs" + +[[test]] +name = "datatest_isolation" +path = "tests/datatest_isolation.rs" diff --git a/decompiler/crates/kuna-verify/src/abi/calls.rs b/decompiler/crates/kuna-verify/src/abi/calls.rs new file mode 100644 index 0000000000..cef952e085 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/abi/calls.rs @@ -0,0 +1,568 @@ +//! What kuna says about each call the function makes, shared by both sides so +//! a call has one effect whichever side makes it. +//! +//! A call kills the registers its prototype model lists as killed-by-call and +//! every register an output can occupy, pops `extrapop` bytes of stack, and +//! may write the image's writable data and memory near the pointers passed to +//! it (`State::call`). Where kuna has no call at an instruction that calls code +//! in the image, kuna inlined, injected or dropped it: the machine runs the +//! callee for real, so a deliberate removal agrees and a wrong one shows in +//! what the callee does. A call kuna lacks to code outside the image gets a +//! stub with the function's own model, and the comparison reports it. + +use std::collections::{BTreeMap, BTreeSet}; + +use kuna_decomp::fspec::{effect_type, FuncProto, EXTRAPOP_UNKNOWN}; +use kuna_decomp::context::VarnodeId; +use kuna_decomp::funcdata::Funcdata; +use kuna_num::opcodes::OpCode; + +use crate::state::{Effect, Env, Writes}; +use crate::value::Halt; + +/// Calls one run may make before it is given up as `UNKNOWN(budget)`: each +/// call keeps a snapshot of the memory its callee could read. +pub const MAX_CALLS: usize = 256; + +/// Keep a call's record, or end the run when there have been too many. +pub fn record(records: &mut Vec, r: Record) -> Result<(), Halt> { + if records.len() >= MAX_CALLS { + return Err(Halt::Budget); + } + records.push(r); + Ok(()) +} +use crate::storage::Storage; + +/// Where an argument is passed: the callee prototype's parameter storage. A +/// stack location is relative to the stack pointer the callee starts with. An +/// argument past the prototype's parameters (a variadic one) has no known +/// storage, and the input varnode's own storage is where the value was +/// computed, not where it is passed, so it is not compared. +#[derive(Clone, Debug)] +pub struct Arg { + pub storage: Storage, + pub callee_frame: bool, +} + +#[derive(Clone, Debug)] +pub struct Site { + /// The callee kuna names, when it is a known address. + pub target: Option, + /// Bytes of stack the call removes, the return address included; `None` + /// when kuna does not know. + pub extrapop: Option, + pub noreturn: bool, + /// The compiler left none of the function after the call: evidence the + /// call does not return that does not come from kuna. + pub laid_out_noreturn: bool, + /// Register ranges the call kills, as kuna's IR has it: the calling + /// convention's, less what kuna found the callee preserves. + pub killed: Vec<(u64, u32)>, + /// The calling convention's alone. A callee run for real keeps only the + /// other registers, so a register kuna wrongly thinks preserved differs. + pub abi_killed: Vec<(u64, u32)>, + /// The registers the calling convention's model says a callee preserves + /// (`unaffected`), not kuna's prototype: all a callee run for real gets + /// put back. + pub preserved: Vec<(u64, u32)>, + /// Where each of kuna's arguments is passed, by input slot; `None` where + /// it is not machine state. + pub args: Vec>, + /// The callee's parameters are declared, not recovered: an argument that + /// differs is a difference, not a doubtful prototype. + pub locked: bool, + /// How many parameters the prototype kuna gives the callee has. + pub params: usize, + /// Where the callee's prototype returns its value. + pub output: Option, + pub(crate) output_float: bool, + /// kuna bound the call past a PLT stub or replaced it with an injection: + /// its target comes from relocations or a fixup the machine does not run. + pub resolved: bool, + /// The PLT stub kuna bound the call past: the machine's call goes there. + pub plt_stub: Option, + /// Where each CALL input lives for the callee: its prototype parameter, + /// or the trial kuna's recovery matched it to. + pub input_storage: Vec>, + /// An unlocked x86-32 cdecl call. + cdecl_stack: bool, + /// How the ABI extends that value across its register, which a stub + /// keeps (a 32-bit `int` in a 64-bit RISC-V register is sign-extended). + pub ret_ext: Option, +} + +#[derive(Clone)] +pub struct Calls { + /// By the address of the call instruction. + pub by_addr: BTreeMap, + pub default: Site, + /// Every instruction kuna kept an op of, and where its blocks start: a + /// branch there stays in the function. + pub inside: BTreeSet, + /// Instructions kuna made an indirect jump: a CALLIND the machine lifts + /// there is executed as one (an option reclassified it). + pub jumps: BTreeSet, + /// Instructions kuna ends in a branch and not a return: a RETURN the + /// machine lifts there is followed (kuna resolved where it goes). + pub branches: BTreeSet, + /// The convention's argument registers, pointer-sized: where the machine + /// looks for a frame object a callee without a recovered prototype gets. + pub pointer_regs: Vec, + /// The convention's argument registers, whole: `(offset, size)`. + pub input_regs: Vec<(u64, u32)>, + /// Its general-purpose argument registers, in the order it assigns them. + pub int_regs: Vec, + /// The registers it returns values in. + pub output_regs: Vec<(u64, u32)>, +} + +/// A system call or a trap, as a side reached it: an operation outside the +/// program that both sides must reach in the same order with the same inputs. +#[derive(Clone, Debug)] +pub struct UserEvent { + pub at: u64, + pub name: String, + pub ins: Vec, + /// The machine's side: its register file there, `(offset, byte)`. + pub file: Vec<(u64, u8)>, +} + +/// User ops that enter the operating system and come back: an uninterpreted +/// function of their inputs whose output, if any, both sides get alike. What +/// the kernel does to registers is not modeled. +pub const SYSTEM_USEROPS: &[&str] = &["syscall", "swi", "software_interrupt", "ecall", "CallSupervisor"]; + +/// User ops that trap and do not come back: the run ends there. +pub const TRAP_USEROPS: &[&str] = &["SoftwareBreakpoint", "UndefinedInstructionException"]; + +/// The value a system call's output gets: fixed by the run and its index. +/// What a system call reads and writes, in the registers kuna's `syscallregs` +/// and `x64syscall` give it: the number register then the argument registers, +/// in the order kuna attaches them, the result register, and the register +/// the kernel flags a failure in. +#[derive(Default)] +pub struct SyscallAbi { + pub inputs: Vec, + pub result: Option, + pub error: Option, +} + +impl SyscallAbi { + /// The target's system-call registers; empty for a target neither models. + pub fn of(prog: &kuna_console::engine::ConsoleProgram) -> Self { + use kuna_decomp::{kuna_syscallregs::SyscallFamily, kuna_x64syscall}; + let arch = prog.arch(); + let Some(lookup) = arch.manage().register_lookup() else { return Self::default() }; + let reg = |nm: &str| { + let st = lookup.probe_register(nm)?; + Some(Storage::new(st.space.as_ref()?, st.offset, st.size)) + }; + let (names, result, error): (Vec<&str>, &str, Option<&str>) = match SyscallFamily::from_archid(&arch.archid) { + Some(f) => (f.inputs(reg(f.result()).is_some_and(|r| r.size == 8)).to_vec(), f.result(), f.error_flag()), + None if reg(kuna_x64syscall::NUM_REGISTER).is_some_and(|r| r.size == 8) => ( + std::iter::once(kuna_x64syscall::NUM_REGISTER).chain(kuna_x64syscall::ARG_REGISTERS).collect(), + kuna_x64syscall::NUM_REGISTER, + None, + ), + None => return Self::default(), + }; + let Some(inputs) = names.iter().map(|nm| reg(nm)).collect::>>() else { return Self::default() }; + SyscallAbi { inputs, result: reg(result), error: error.and_then(reg) } + } +} + +/// The value the kernel flags system call `index` with, in both runs. +pub fn syscall_error_value(run: u32, index: usize, size: u32) -> u128 { + crate::graph::scramble(0x0e77_f1a6, run, index as u64) & crate::value::mask(size) +} + +pub fn userop_value(run: u32, index: usize, size: u32) -> u128 { + crate::graph::scramble(0x05ca_11ed, run, index as u64) & crate::value::mask(size) +} + +/// One call as a side made it. +#[derive(Clone, Debug)] +pub struct Record { + /// The address of the call instruction. + pub at: u64, + pub target: Option, + /// The target was computed (CALLIND, an indirect tail jump) rather than + /// encoded in the instruction. + pub indirect: bool, + pub args: Vec, + /// Memory the callee can read: what this side wrote since its last call. + pub writes: Writes, + /// What the callee did when the machine ran it for real. + pub effect: Option, + /// The frame bytes that callee read, when the machine ran it for real: + /// only those of the frame objects it was given are compared. + pub frame_reads: Option, + /// The argument-register bytes that callee read before writing, with + /// the machine's values: what kuna's call must pass there. + pub live_in: Option>, + pub(crate) stack_in: Option, + /// The machine side's whole argument register, per argument kuna passes + /// in only part of one: the bytes it leaves out. + pub(crate) whole: Vec>, +} + +impl Site { + pub(crate) fn stack_input(&self, index: usize) -> Option<&Storage> { + let st = self.input_storage.get(index)?.as_ref()?; + (self.cdecl_stack + && st.space.get_type() == kuna_base::space::spacetype::IPTR_SPACEBASE + && (4..=u64::from(u32::MAX)).contains(&st.off) + && (1..=16).contains(&st.size)) + .then_some(st) + } +} + +impl Calls { + pub fn site(&self, at: u64) -> &Site { + self.by_addr.get(&at).unwrap_or(&self.default) + } + + pub fn known(&self, at: u64) -> bool { + self.by_addr.contains_key(&at) + } + + /// A branch at `at` to `target` that kuna turned into a call. + pub fn tail(&self, at: u64, target: u64) -> bool { + self.known(at) && !self.inside.contains(&target) + } +} + +/// Whether flow planted a no-return halt after the call at `at`, or a +/// `CALL_RETURN` override cuts the flow after a call instruction (`error (1, +/// ...)`): a callee kuna knows does not return by name, by its own body or by +/// the call's arguments, not by prototype. The same override on a branch only +/// makes it a tail call. +fn halts_after(fd: &Funcdata, env: &Env, at: &kuna_base::address::Address) -> bool { + let cut = fd.get_override().get_flow_override(at) == kuna_decomp::overrides::flow_type::CALL_RETURN + && crate::machine::lift(env, at.get_offset()) + .is_ok_and(|i| i.ops.iter().any(|o| matches!(o.opc, OpCode::CPUI_CALL | OpCode::CPUI_CALLIND))); + cut || fd + .obank() + .iter_at(at) + .any(|(_, o)| fd.obank().get(o).is_some_and(|o| o.get_halt_type() & kuna_decomp::op::pcodeop_flags::noreturn != 0)) +} + +/// Callees that do not return by their definition, whatever kuna inferred. +pub const KNOWN_NORETURN: &[&str] = &[ + "exit", "_exit", "_Exit", "quick_exit", "abort", "__assert_fail", "__assert_rtn", "__assert", "__stack_chk_fail", + "__fortify_fail", "__chk_fail", "__libc_fatal", "longjmp", "_longjmp", "siglongjmp", "__longjmp_chk", "err", "errx", + "verr", "verrx", "pthread_exit", "thrd_exit", "__cxa_throw", "__cxa_rethrow", "__cxa_bad_cast", "__cxa_bad_typeid", + "_Unwind_Resume", "ExitProcess", "ExitThread", "TerminateProcess", "RaiseException", "_CxxThrowException", +]; + +/// Ghidra's curated lists of functions that do not return, by platform and +/// language: data about names, not anything kuna inferred about this binary. +const NORETURN_LISTS: [&str; 5] = [ + include_str!("../../../kuna-analysis/data/ElfFunctionsThatDoNotReturn"), + include_str!("../../../kuna-analysis/data/PEFunctionsThatDoNotReturn"), + include_str!("../../../kuna-analysis/data/PeMacFunctionsThatDoNotReturn"), + include_str!("../../../kuna-analysis/data/RustFunctionsThatDoNotReturn"), + include_str!("../../../kuna-analysis/data/GolangFunctionsThatDoNotReturn"), +]; + +fn listed(plain: &str) -> bool { + NORETURN_LISTS.iter().flat_map(|l| l.lines()).map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).any(|l| { + let entry = l.trim_start_matches('_'); + match entry.strip_suffix('*') { + Some(prefix) => plain.starts_with(prefix), + None => plain == entry, + } + }) +} + +/// Whether `name` does not return by definition: a name on Ghidra's lists or +/// this one, or `error` and `error_at_line` with a nonzero `status`. +pub fn known_noreturn(name: &str, first_arg: Option) -> bool { + NameNoReturn::of(name).with_status(first_arg) +} + +/// What a callee's name alone says about whether it returns. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum NameNoReturn { + No, + Always, + /// `error` and `error_at_line`: only with a nonzero `status`. + IfStatus, +} + +impl NameNoReturn { + pub fn of(name: &str) -> Self { + let bare = name.split('@').next().unwrap_or(name); + let plain = bare.trim_start_matches('_'); + if KNOWN_NORETURN.iter().any(|&k| k == bare || k.trim_start_matches('_') == plain) + || listed(plain) + || kuna_decomp::kuna_noreturn_externmatch::is_known_noreturn_name(bare) + { + NameNoReturn::Always + } else if matches!(plain, "error" | "error_at_line") { + NameNoReturn::IfStatus + } else { + NameNoReturn::No + } + } + + pub fn with_status(self, first_arg: Option) -> bool { + match self { + NameNoReturn::Always => true, + NameNoReturn::IfStatus => first_arg.is_some_and(|s| s as u32 != 0), + NameNoReturn::No => false, + } + } +} + +/// Whether only padding (instructions with no effect, or zero bytes) lies +/// between the call at `at` and the start of another function: the compiler left none of this function's code after the call, so +/// it does not return (`error (1, ...)`, a fatal wrapper no name marks). +fn falls_into_another(fd: &Funcdata, env: &Env, at: u64) -> bool { + let own = fd.get_address().get_offset(); + let Ok(call) = crate::machine::lift(env, at) else { return false }; + let mut next = at.wrapping_add(call.len); + for _ in 0..16 { + if next != own && env.function_starts_at(next) { + return true; + } + match crate::machine::lift(env, next) { + Ok(i) if no_effect(env, &i) || (0..i.len).all(|k| env.image_byte(next.wrapping_add(k)) == Some(0)) => { + next = next.wrapping_add(i.len) + } + _ => return false, + } + } + false +} + +/// Padding: an instruction that writes only temporaries and does not branch. +fn no_effect(env: &Env, insn: &crate::machine::Insn) -> bool { + insn.ops.iter().all(|o| { + !matches!( + o.opc, + OpCode::CPUI_STORE | OpCode::CPUI_BRANCH | OpCode::CPUI_CBRANCH | OpCode::CPUI_BRANCHIND | OpCode::CPUI_CALL + | OpCode::CPUI_CALLIND | OpCode::CPUI_CALLOTHER | OpCode::CPUI_RETURN + ) && o.out.as_ref().is_none_or(|v| env.unique.as_ref().zip(v.space.as_ref()).is_some_and(|(u, s)| u.get_index() == s.get_index())) + }) +} + +/// The registers a stub for `proto` kills: those its effect list says a call +/// kills, the call's own overrides first (what kuna proved about the callee), +/// and its output registers, unless the call is known to leave them alone. +/// The model's `unaffected` registers, less the link register and the program +/// counter: a cspec may list them (ARM does), but the call itself rewrites the +/// one and a return the other, so no caller holds a value in them. +fn preserved(env: &Env, proto: &FuncProto) -> Vec<(u64, u32)> { + let reg = env.register.get_index(); + let control = |off: u64, size: u32| { + let name = Storage::new(&env.register, off, size).name(env.prog).to_ascii_lowercase(); + matches!(name.as_str(), "lr" | "pc" | "ra" | "x30") + }; + let mut out: Vec<(u64, u32)> = proto + .model() + .effect_list() + .iter() + .filter(|e| e.get_type() == effect_type::UNAFFECTED) + .filter_map(|e| { + let a = e.get_address(); + (a.get_space()?.get_index() == reg).then(|| (a.get_offset(), e.get_size() as u32)) + }) + .filter(|&(off, size)| !control(off, size)) + .collect(); + out.sort_unstable(); + out.dedup(); + out +} + +fn killed(env: &Env, proto: &FuncProto) -> Vec<(u64, u32)> { + let reg = env.register.get_index(); + let model = proto.model(); + let mut out: Vec<(u64, u32)> = proto + .effect_list() + .iter() + .filter(|e| e.get_type() == effect_type::KILLEDBYCALL) + .filter_map(|e| { + let a = e.get_address(); + (a.get_space()?.get_index() == reg).then(|| (a.get_offset(), e.get_size() as u32)) + }) + .collect(); + out.extend( + model + .output() + .get_entry() + .iter() + .filter(|e| e.get_space().get_index() == reg) + .map(|e| (e.get_base(), e.get_size() as u32)), + ); + out.retain(|&(off, size)| { + let at = kuna_base::address::Address::new(std::rc::Rc::clone(&env.register), off); + proto.has_effect(&at, size as i32) != effect_type::UNAFFECTED + }); + out.sort_unstable(); + out.dedup(); + out +} + +/// The register, or registers joined, a call's value is copied or cast into, +/// for a call whose prototype has no output yet keeps its value in a temporary. +fn copied_to_register(fd: &Funcdata, env: &Env, out: Option) -> Option { + let v = fd.vbank().get(out?)?; + v.descend_iter().filter_map(|d| fd.obank().get(d)).find_map(|d| { + if !matches!(d.code(), OpCode::CPUI_COPY | OpCode::CPUI_CAST) { + return None; + } + let w = fd.vbank().get(d.get_out()?)?; + let st = Storage::at(w.get_addr(), w.get_size() as u32)?; + st.pieces(env.prog).iter().all(|p| p.space.get_index() == env.register.get_index()).then_some(st) + }) +} + +fn extrapop(pop: i32) -> Option { + (pop != EXTRAPOP_UNKNOWN).then_some(pop) +} + +/// Every call site of `fd`, keyed by its instruction address. +pub fn sites(fd: &Funcdata, env: &Env) -> Calls { + let mut by_addr = BTreeMap::new(); + let x86_cdecl_stack = env.prog.arch().archid.starts_with("x86:LE:32:"); + for i in 0..fd.num_calls() { + let fc = fd.get_call_specs(i); + let Some(op) = fd.obank().get(fc.get_op()) else { continue }; + let proto = fc.proto(); + let pop = extrapop(fc.get_effective_extra_pop()).or_else(|| extrapop(fc.get_extra_pop())); + let sp = Storage::new(&env.register, env.sp.0, env.sp.1); + let active = fc.active_input(); + let input_storage = (1..op.num_input()) + .map(|k| { + if let Some(p) = proto.get_param(k - 1) { + return Storage::at(&p.get_address(), p.get_size() as u32); + } + (active.get_num_trials() > (k as i32) - 1).then(|| { + let t = active.get_trial_for_input_varnode(k as i32); + Storage::at(t.get_address(), t.get_size() as u32) + })? + }) + .collect(); + let args = (1..op.num_input()) + .map(|k| { + let p = proto.get_param(k - 1)?; + let storage = Storage::at(&p.get_address(), p.get_size() as u32)?; + (!storage.overlaps(&sp)).then_some(Arg { storage, callee_frame: true }) + }) + .collect(); + let entry = fc.get_entry_address(); + let target = (!entry.is_invalid()).then(|| entry.get_offset()); + by_addr.insert( + op.get_addr().get_offset(), + Site { + target, + extrapop: pop, + noreturn: proto.is_no_return() || halts_after(fd, env, op.get_addr()) || falls_into_another(fd, env, op.get_addr().get_offset()), + laid_out_noreturn: falls_into_another(fd, env, op.get_addr().get_offset()), + abi_killed: killed(env, proto), + preserved: preserved(env, proto), + killed: killed(env, proto) + .into_iter() + .filter(|&(off, size)| { + let at = kuna_base::address::Address::new(std::rc::Rc::clone(&env.register), off); + !kuna_decomp::kuna_calleepreserves::callee_preserves_range(fd, fc, &at, size as i32) + }) + .collect(), + args, + locked: proto.is_input_locked(), + params: proto.num_params().max(0) as usize, + output: (proto.get_output().get_size() > 0) + .then(|| Storage::at(&proto.get_output().get_address(), proto.get_output().get_size() as u32)) + .flatten() + .or_else(|| copied_to_register(fd, env, op.get_out())), + output_float: proto.get_output_type().is_some_and(|t| t.get_metatype() == kuna_decomp::dtype::type_metatype::TYPE_FLOAT), + ret_ext: crate::abi::return_extension(env, proto), + input_storage, + cdecl_stack: x86_cdecl_stack && proto.get_model_name() == "__cdecl" && !proto.is_input_locked(), + resolved: fc.plt_stub().is_some() || proto.get_inject_id() >= 0, + plt_stub: fc.plt_stub().map(|a| a.get_offset()), + }, + ); + } + let own = fd.get_func_proto(); + let default = Site { + target: None, + extrapop: extrapop(own.model().get_extra_pop()), + noreturn: false, + laid_out_noreturn: false, + killed: killed(env, own), + abi_killed: killed(env, own), + preserved: preserved(env, own), + args: Vec::new(), + locked: false, + params: 0, + output: None, + output_float: false, + ret_ext: None, + input_storage: Vec::new(), + cdecl_stack: false, + resolved: false, + plt_stub: None, + }; + let graph = fd.bblocks_ref(); + let blocks: Vec<_> = (0..fd.bblocks_get_size()).map(|i| fd.bblocks_get_block(i)).collect(); + let inside = blocks + .iter() + .map(|&b| kuna_decomp::block::block_get_start(&graph.arena, b).get_offset()) + .chain(blocks.iter().flat_map(|&b| fd.bb_ops(b)).filter_map(|op| fd.obank().get(op).map(|o| o.get_addr().get_offset()))) + .collect(); + use kuna_num::opcodes::OpCode; + let ops: Vec<_> = blocks.iter().flat_map(|&b| fd.bb_ops(b)).filter_map(|op| fd.obank().get(op)).collect(); + let at = |codes: &[OpCode]| -> BTreeSet { + ops.iter().filter(|o| codes.contains(&o.code())).map(|o| o.get_addr().get_offset()).collect() + }; + let jumps = at(&[OpCode::CPUI_BRANCHIND]); + let returns = at(&[OpCode::CPUI_RETURN]); + let branches = at(&[OpCode::CPUI_BRANCH, OpCode::CPUI_CBRANCH, OpCode::CPUI_BRANCHIND]) + .into_iter() + .filter(|a| !returns.contains(a)) + .collect(); + let width = u32::from(env.ram.get_addr_size()).min(8); + let pointer_regs = own + .model() + .input() + .get_entry() + .iter() + .filter(|e| e.get_space().get_index() == env.register.get_index() && e.get_size() as u32 >= width) + .map(|e| { + let low = if env.register.is_big_endian() { e.get_base() + u64::from(e.get_size() as u32 - width) } else { e.get_base() }; + Storage::new(&env.register, low, width) + }) + .collect(); + let input_regs = own + .model() + .input() + .get_entry() + .iter() + .filter(|e| e.get_space().get_index() == env.register.get_index() && e.get_base() != env.sp.0) + .map(|e| (e.get_base(), e.get_size() as u32)) + .collect(); + let int_regs = own + .model() + .input() + .get_entry() + .iter() + .filter(|e| { + e.get_space().get_index() == env.register.get_index() + && e.get_type() == kuna_decomp::dtype::type_class::TYPECLASS_GENERAL + && e.get_base() != env.sp.0 + }) + .map(|e| Storage::new(&env.register, e.get_base(), e.get_size() as u32)) + .collect(); + let output_regs = own + .model() + .output() + .get_entry() + .iter() + .filter(|e| e.get_space().get_index() == env.register.get_index()) + .map(|e| (e.get_base(), e.get_size() as u32)) + .collect(); + Calls { by_addr, default, inside, jumps, branches, pointer_regs, input_regs, int_regs, output_regs } +} diff --git a/decompiler/crates/kuna-verify/src/abi/contract.rs b/decompiler/crates/kuna-verify/src/abi/contract.rs new file mode 100644 index 0000000000..e4295c056f --- /dev/null +++ b/decompiler/crates/kuna-verify/src/abi/contract.rs @@ -0,0 +1,252 @@ +//! Typed contracts: the function's real return type, read from C source. +//! +//! Only what the return comparison needs is parsed: the declared return type of +//! the named function, through the file's typedefs. + +use std::collections::BTreeMap; + +use regex::Regex; + +/// The sizes of C's integer types on the target. +#[derive(Debug, Clone, Copy)] +pub struct CSizes { + pub int: u32, + pub long: u32, + pub long_long: u32, + pub pointer: u32, + /// Plain `char` is signed: x86 yes; ARM, AArch64, PowerPC, RISC-V and + /// s390 System V ABIs no. Spell `signed char` or `unsigned char` where a + /// target's compiler differs (Apple's and Windows' ARM ABIs sign it). + pub char_signed: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CKind { + Integer, + Boolean, + Pointer, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CType { + /// The type as written in the source. + pub spelling: String, + /// `0` for `void`. + pub size: u32, + pub signed: bool, + pub kind: CKind, +} + +impl CType { + pub fn is_void(&self) -> bool { + self.size == 0 + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Contract { + pub ret: CType, + /// The declaration line the contract was read from. + pub declaration: String, + pub source: String, +} + +/// A contract that names the compiler's `-fsigned-char` or +/// `-funsigned-char` (in a comment) overrides the target's plain `char`. +fn char_override(src: &str, sizes: CSizes) -> CSizes { + let signed = src.contains("-fsigned-char"); + let unsigned = src.contains("-funsigned-char"); + match (signed, unsigned) { + (true, false) => CSizes { char_signed: true, ..sizes }, + (false, true) => CSizes { char_signed: false, ..sizes }, + _ => sizes, + } +} + +fn strip_comments(src: &str) -> String { + let block = Regex::new(r"(?s)/\*.*?\*/").expect("regex"); + let line = Regex::new(r"//[^\n]*").expect("regex"); + line.replace_all(&block.replace_all(src, " "), "").into_owned() +} + +/// Typedefs by name. A name defined twice with different types (one per +/// preprocessor branch, say) maps to `None`: which one the binary was built +/// with is not known here. +fn typedefs(src: &str) -> BTreeMap> { + let re = Regex::new(r"typedef\s+([^;{}()]+?)\s+(\w+)\s*;").expect("regex"); + let mut defs: BTreeMap> = BTreeMap::new(); + for c in re.captures_iter(src) { + let ty = c[1].split_whitespace().collect::>().join(" "); + defs.entry(c[2].to_string()) + .and_modify(|d| { + if d.as_deref() != Some(ty.as_str()) { + *d = None; + } + }) + .or_insert(Some(ty)); + } + defs +} + +fn base_type(words: &[&str], sizes: CSizes) -> Option<(u32, bool)> { + let has = |w: &str| words.contains(&w); + let unsigned = has("unsigned"); + if has("__int128") { + return Some((16, !unsigned)); + } + let longs = words.iter().filter(|&&w| w == "long").count(); + let fixed = |w: &str| -> Option<(u32, bool)> { + Some(match w { + "void" => (0, false), + "int8_t" => (1, true), + "uint8_t" => (1, false), + "int16_t" => (2, true), + "uint16_t" => (2, false), + "int32_t" => (4, true), + "uint32_t" => (4, false), + "int64_t" => (8, true), + "uint64_t" => (8, false), + "__int128_t" => (16, true), + "__uint128_t" => (16, false), + "size_t" | "uintptr_t" => (sizes.pointer, false), + "ssize_t" | "intptr_t" | "ptrdiff_t" => (sizes.pointer, true), + _ => return None, + }) + }; + if let Some(found) = words.iter().find_map(|w| fixed(w)) { + return Some(found); + } + if words.iter().any(|w| !matches!(*w, "unsigned" | "signed" | "long" | "short" | "int" | "char")) { + return None; + } + let size = if has("char") { + 1 + } else if has("short") { + 2 + } else if longs >= 2 { + sizes.long_long + } else if longs == 1 { + sizes.long + } else if has("int") || unsigned || has("signed") { + sizes.int + } else { + return None; + }; + let plain_char = has("char") && !unsigned && !has("signed"); + Some((size, if plain_char { sizes.char_signed } else { !unsigned })) +} + +/// The size, signedness and kind of a spelled type, through typedefs; an error +/// names a typedef defined more than one way. +fn resolve(spelling: &str, defs: &BTreeMap>, sizes: CSizes, depth: u32) -> Result, String> { + if spelling.contains('*') { + return Ok(Some((sizes.pointer, false, CKind::Pointer))); + } + let words: Vec<&str> = spelling + .split_whitespace() + .filter(|w| !matches!(*w, "const" | "volatile" | "static" | "inline" | "extern" | "register")) + .collect(); + if words.len() == 1 && depth < 8 { + match defs.get(words[0]) { + Some(Some(inner)) => return resolve(inner, defs, sizes, depth + 1), + Some(None) => return Err(format!("typedef `{}` is defined more than one way", words[0])), + None => {} + } + } + if matches!(words.as_slice(), ["_Bool" | "bool"]) { + return Ok(Some((1, false, CKind::Boolean))); + } + Ok(base_type(&words, sizes).map(|(size, signed)| (size, signed, CKind::Integer))) +} + +/// Read `function`'s return type from C source. +pub fn from_source(src: &str, function: &str, source: &str, sizes: CSizes) -> Result { + let sizes = char_override(src, sizes); + let clean = strip_comments(src); + let defs = typedefs(&clean); + let re = Regex::new(&format!( + r"(?m)(^|[;{{}}])\s*((?:[A-Za-z_]\w*[\s*]+)+?)\b{}\s*\(([^)]*)\)", + regex::escape(function) + )) + .expect("regex"); + let found: Vec<_> = re + .captures_iter(&clean) + .filter(|c| !c[2].split_whitespace().any(|w| matches!(w, "return" | "else" | "case" | "goto"))) + .collect(); + let caps = found.first().ok_or_else(|| format!("{source}: no declaration of {function}"))?; + let words = |c: ®ex::Captures| c[2].split_whitespace().filter(|w| !matches!(*w, "static" | "inline" | "extern")).collect::>().join(" "); + let spelling = caps[2].split_whitespace().collect::>().join(" "); + let first = words(caps); + if let Some(other) = found.iter().map(words).find(|o| *o != first) { + return Err(format!("{source}: {function} is declared returning both `{first}` and `{other}`")); + } + let (size, signed, kind) = resolve(&spelling, &defs, sizes, 0) + .map_err(|e| format!("{source}: return type of {function}: {e}"))? + .ok_or_else(|| format!("{source}: cannot size return type `{spelling}` of {function}"))?; + let declaration = format!("{} {}({})", spelling, function, caps[3].split_whitespace().collect::>().join(" ")); + Ok(Contract { ret: CType { spelling, size, signed, kind }, declaration, source: source.to_string() }) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ARM: CSizes = CSizes { int: 4, long: 4, long_long: 8, pointer: 4, char_signed: false }; + + #[test] + fn return_types_resolve_through_typedefs() { + let src = "typedef unsigned long long u64;\n/* u32 f() */\nu64 ins16(unsigned a, unsigned short b) { return 0; }\n"; + let c = from_source(src, "ins16", "ins16.c", ARM).unwrap(); + assert_eq!(c.ret, CType { spelling: "u64".into(), size: 8, signed: false, kind: CKind::Integer }); + assert_eq!(c.declaration, "u64 ins16(unsigned a, unsigned short b)"); + } + + #[test] + fn builtin_and_pointer_returns() { + let src = "static int f(void);\nconst char *g(int x);\nvoid h(void) {}\nlong k(void);"; + assert_eq!(from_source(src, "f", "s", ARM).unwrap().ret.size, 4); + assert!(from_source(src, "f", "s", ARM).unwrap().ret.signed); + assert_eq!(from_source(src, "g", "s", ARM).unwrap().ret.size, 4); + assert_eq!(from_source(src, "g", "s", ARM).unwrap().ret.kind, CKind::Pointer); + assert_eq!(from_source(src, "f", "s", ARM).unwrap().ret.kind, CKind::Integer); + assert!(from_source(src, "h", "s", ARM).unwrap().ret.is_void()); + assert_eq!(from_source(src, "k", "s", ARM).unwrap().ret.size, 4); + assert!(from_source(src, "missing", "s", ARM).is_err()); + let wide = "unsigned __int128 m(unsigned long a);\nNI unsigned q(int x);"; + assert_eq!(from_source(wide, "m", "s", ARM).unwrap().ret.size, 16); + assert!(from_source(wide, "q", "s", ARM).is_err()); + } + + /// A typedef each preprocessor branch defines its own way, or a function + /// declared with two return types, gives no contract: which one the binary + /// was built with is not known. + #[test] + fn ambiguous_return_types_are_refused() { + let src = "#ifdef TARGET_64\ntypedef uint64_t result_t;\n#else\ntypedef uint32_t result_t;\n#endif\nresult_t f(void);\n"; + let e = from_source(src, "f", "s", ARM).unwrap_err(); + assert!(e.contains("typedef `result_t` is defined more than one way"), "{e}"); + let same = "typedef unsigned int u32;\ntypedef unsigned int u32;\nu32 g(void);\n"; + assert_eq!(from_source(same, "g", "s", ARM).unwrap().ret.size, 4); + let two = "#if A\nlong h(void);\n#else\nshort h(void);\n#endif\n"; + assert!(from_source(two, "h", "s", ARM).unwrap_err().contains("declared returning both")); + let decl_and_def = "static int k(void);\nint k(void) { return 1; }\n"; + assert_eq!(from_source(decl_and_def, "k", "s", ARM).unwrap().ret.size, 4); + } + + /// Plain `char` takes the target's signedness; spelled out, it does not. + #[test] + fn plain_char_follows_the_target() { + let src = "char a(void); +signed char b(void); +unsigned char c(void);"; + let x86 = CSizes { char_signed: true, ..ARM }; + assert!(!from_source(src, "a", "s", ARM).unwrap().ret.signed); + assert!(from_source(src, "a", "s", x86).unwrap().ret.signed); + assert!(from_source(src, "b", "s", ARM).unwrap().ret.signed); + assert!(!from_source(src, "c", "s", x86).unwrap().ret.signed); + let flagged = format!("/* built with -fsigned-char */\n{src}"); + assert!(from_source(&flagged, "a", "s", ARM).unwrap().ret.signed); + let flagged = format!("// -funsigned-char\n{src}"); + assert!(!from_source(&flagged, "a", "s", x86).unwrap().ret.signed); + } +} diff --git a/decompiler/crates/kuna-verify/src/abi/divergence.rs b/decompiler/crates/kuna-verify/src/abi/divergence.rs new file mode 100644 index 0000000000..5acc5604b8 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/abi/divergence.rs @@ -0,0 +1,199 @@ +//! Declared divergences: defaults that knowingly trade fidelity for +//! readability. +//! +//! An entry is a predicate over the option, the architecture, the observable it +//! changes and the pattern of the difference, never an option name alone, so a +//! different difference under the same option is still `DIFFERS`. + +/// A return-value difference against a typed contract. +pub struct ReturnMismatch<'a> { + pub arch: &'a str, + pub contract_size: u32, + pub kuna_size: u32, + pub machine: u128, + pub kuna: u128, +} + +pub struct Divergence { + pub id: &'static str, + /// The option that makes the trade, or the always-on check that does. + pub option: &'static str, + /// The architecture id prefix it applies to; empty for every target. + pub arch: &'static str, + pub observable: &'static str, + pub pattern: &'static str, + matches: fn(&ReturnMismatch) -> bool, +} + +/// `switchrunon` cuts the rows of a bounds-free jump table that run on into the +/// next functions and dispatches none of them. A selector those rows served is +/// one the source never passes (a Rust enum's byte, C's unreachable default), +/// and on it the machine runs a neighbouring function's code. Matched when a +/// switch meets a selector no row carries and the machine's indirect branch +/// lands outside every block of the decompiled function. +pub const SWITCH_RUNON: Divergence = Divergence { + id: "switchrunon-cut-row", + option: "switchrunon (always on)", + arch: "", + observable: "the path a switch takes", + pattern: "the selector matches no row of a table whose run-on rows were cut", + matches: |_| false, +}; + +/// Options that print code as a call that is not in the binary: +/// `msvcstrappend` folds MSVC's inlined `std::string` appends into a call with +/// no address, `outline` a region into a call at no instruction. The machine +/// runs the code; kuna's call has no counterpart. +pub const SYNTHESIZED_CALL: Divergence = Divergence { + id: "synthesized-call", + option: "msvcstrappend, outline", + arch: "", + observable: "the calls a function makes", + pattern: "kuna calls a function that has no address, or from no instruction", + matches: |_| false, +}; + +/// `gowritebarrier` folds Go's write-barrier block, its call to +/// `runtime.gcWriteBarrier*` included, into the plain store it guards. +pub const GO_WRITE_BARRIER: Divergence = Divergence { + id: "gowritebarrier", + option: "gowritebarrier", + arch: "", + observable: "the calls a function makes", + pattern: "the machine calls runtime.gcWriteBarrier*, which kuna folded away", + matches: |_| false, +}; + +/// `gobounds` (Go) and `securitycheck` (Rust) remove the branch to a +/// bounds, slice or division check's panic helper, keeping the access it +/// guards. On an input that fails the check the machine calls the helper. +pub const PANIC_CHECK: Divergence = Divergence { + id: "panic-check", + option: "gobounds, securitycheck", + arch: "", + observable: "the calls a function makes", + pattern: "the machine calls a Go or Rust check's panic helper, whose branch kuna removed", + matches: |_| false, +}; + +/// `ptrauthtrap` cuts an arm64e pointer-authentication check: the bit test of +/// an authenticated return address and its `brk #0xc470..0xc473`, which an +/// authentic pointer never reaches. The machine does not authenticate (SLEIGH +/// hides `autibsp`), so the address it tests is whatever was loaded. +pub const PTRAUTH_TRAP: Divergence = Divergence { + id: "ptrauth-trap", + option: "ptrauthtrap", + arch: "AARCH64", + observable: "whether the function traps", + pattern: "the machine reaches a pointer-authentication brk whose check kuna cut", + matches: |_| false, +}; + +/// `repstring` (the default) prints a `rep movs` as `memcpy`, which the +/// instruction is not when the destination starts inside the source, ahead of +/// it: the instruction then repeats the bytes it copied first, as an LZ77 +/// decoder's match copy relies on. Matched on a run whose `memcpy` builtin +/// meets that overlap. +pub const COPY_OVERLAP: Divergence = Divergence { + id: "copy-overlap", + option: "repstring", + arch: "x86", + observable: "memory a `rep movs` writes", + pattern: "a memcpy builtin whose destination lies inside its source, ahead of it", + matches: |_| false, +}; + +/// ARM and AArch64 define a division by zero as 0; C leaves it undefined, so +/// kuna's `/` for `udiv`/`sdiv` traps where the machine goes on. Always on: +/// every decompiler prints the instruction as C's division. Matched on a run +/// where the machine, on those targets, divided by zero and kuna's side traps +/// dividing by zero. +pub const DIVIDE_BY_ZERO: Divergence = Divergence { + id: "divide-by-zero", + option: "(always on)", + arch: "ARM", + observable: "a division's result", + pattern: "the divisor is zero: the machine's result is 0 and kuna's C divides by zero", + matches: |_| false, +}; + +/// `nanignore compare` (the default) treats a float conversion round trip as +/// the identity, as upstream does, so a signalling NaN comes back as it went in +/// where the machine's conversions return it quieted. +pub const NAN_QUIETING: Divergence = Divergence { + id: "nan-quieting", + option: "nanignore", + arch: "", + observable: "a float return", + pattern: "both sides return a NaN that differs only in its quiet bit", + matches: |_| false, +}; + +/// `syscallregs auto` (the default) gives a system call its result register +/// only on an image the loader identified as an operating system's user-space +/// program; on any other image the call writes nothing, as upstream models it. +/// The machine is then run the same way, and this is declared when a kernel +/// writing the result register, as Linux and the BSDs do, would change what +/// the function returns, writes or calls. +pub const SYSCALL_RESULT: Divergence = Divergence { + id: "syscall-result", + option: "syscallregs", + arch: "", + observable: "a system call's result", + pattern: "on an image that names no operating system, the result the kernel would return changes an observable", + matches: |_| false, +}; + +/// Whether two float values of `size` bytes are NaNs that differ only in the +/// quiet bit. +pub fn nan_quieting(size: u32, a: u128, b: u128) -> bool { + let (quiet, exp, frac) = match size { + 4 => (1u128 << 22, 0xffu128 << 23, (1u128 << 23) - 1), + 8 => (1u128 << 51, 0x7ffu128 << 52, (1u128 << 52) - 1), + _ => return false, + }; + let nan = |v: u128| v & exp == exp && v & frac != 0; + a != b && nan(a) && nan(b) && a ^ b == quiet +} + +impl Divergence { + pub fn matches(&self, m: &ReturnMismatch) -> bool { + m.arch.starts_with(self.arch) && (self.matches)(m) + } +} + +pub const DECLARED: &[Divergence] = &[Divergence { + id: "returnpair-rdx-zero", + option: "returnpair", + arch: "x86:LE:64", + observable: "the RDX half of a 16-byte return", + pattern: "machine RDX = 0 and RAX agrees", + matches: |m| { + m.contract_size == 16 && m.kuna_size == 8 && (m.machine >> 64) == 0 && m.machine as u64 == m.kuna as u64 + }, +}]; + +pub fn find(m: &ReturnMismatch) -> Option<&'static Divergence> { + DECLARED.iter().find(|d| d.matches(m)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rdx_trim_matches_only_its_pattern() { + let m = |arch, machine: u128, kuna: u128| ReturnMismatch { arch, contract_size: 16, kuna_size: 8, machine, kuna }; + assert!(find(&m("x86:LE:64:default", 0x8000_0000, 0xffff_ffff_ffff_ffff_0000_0000_8000_0000)).is_some()); + assert!(find(&m("x86:LE:64:default", 1u128 << 64, 0)).is_none()); + assert!(find(&m("x86:LE:64:default", 5, 6)).is_none()); + assert!(find(&m("ARM:LE:32:v8", 0x8000_0000, 0x8000_0000)).is_none()); + } + + #[test] + fn nan_quieting_is_the_quiet_bit_alone() { + assert!(nan_quieting(4, 0xffc5_7572, 0xff85_7572)); + assert!(!nan_quieting(4, 0x7fc0_0000, 0x7fc0_0001)); + assert!(!nan_quieting(4, 0x3f80_0000, 0x3fc0_0000)); + } +} diff --git a/decompiler/crates/kuna-verify/src/abi/mod.rs b/decompiler/crates/kuna-verify/src/abi/mod.rs new file mode 100644 index 0000000000..d5daaf087b --- /dev/null +++ b/decompiler/crates/kuna-verify/src/abi/mod.rs @@ -0,0 +1,288 @@ +//! What kuna claims about a function's interface, and what the calling +//! convention promises regardless of the claim. + +pub mod calls; +pub mod contract; +pub mod divergence; + +use std::rc::Rc; + +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::dtype::{type_metatype, Datatype}; +use kuna_decomp::fspec::{ParameterPieces, PrototypePieces}; +use kuna_base::space::spacetype; +use kuna_decomp::funcdata::Funcdata; +use kuna_num::opcodes::OpCode; + +use crate::contract::{CKind, CSizes, CType}; +use crate::state::{Env, Extension}; +use crate::storage::Storage; +use crate::value::mask; + +/// kuna's prototype for the function: its return storage and signedness, its +/// parameters, and the text the report prints. +pub struct Claim { + pub storage: Option, + pub signed: bool, + /// The claimed return is a float. + pub float: bool, + pub text: String, + pub params: Vec<(String, Storage)>, +} + +fn is_signed(t: &Datatype) -> bool { + matches!(t.get_metatype(), type_metatype::TYPE_INT | type_metatype::TYPE_ENUM_INT) +} + +/// What the function claims to return, and where. A return kuna folded to a +/// constant keeps the storage its model gives the return type. +pub fn claim(prog: &ConsoleProgram, fd: &Funcdata) -> Claim { + let proto = fd.get_func_proto(); + let out = proto.get_output(); + let out_type = proto.get_output_type(); + let meta = out_type.map(|t| t.get_metatype()).unwrap_or(type_metatype::TYPE_VOID); + let addr = out.get_address(); + let storage = match meta { + type_metatype::TYPE_VOID => None, + _ if !addr.is_invalid() && out.get_size() > 0 => Storage::at(&addr, out.get_size() as u32), + _ => None, + }; + let storage = match (storage, out_type) { + (Some(st), Some(t)) if matches!(st.space.get_type(), spacetype::IPTR_CONSTANT | spacetype::IPTR_INTERNAL) => { + Some(model_output(prog, fd, t.clone(), st.size).unwrap_or(st)) + } + (st, _) => st, + }; + let type_name = |t: Option<&Rc>| { + t.map(|t| t.get_display_name().to_string()).filter(|n| !n.is_empty()).unwrap_or_else(|| "?".into()) + }; + let mut params = Vec::new(); + let mut decl = Vec::new(); + for i in 0..proto.num_params() { + let Some(p) = proto.get_param(i) else { continue }; + let pname = if p.get_name().is_empty() { format!("a{i}") } else { p.get_name().to_string() }; + decl.push(format!("{} {}", type_name(p.get_type()), pname)); + if let Some(st) = Storage::at(&p.get_address(), p.get_size() as u32) { + params.push((pname, st)); + } + } + let ret = if storage.is_none() { "void".to_string() } else { type_name(out_type) }; + Claim { + storage, + signed: out_type.is_some_and(|t| is_signed(t)), + float: meta == type_metatype::TYPE_FLOAT, + text: format!("{} {}({})", ret, fd.get_name(), decl.join(", ")), + params, + } +} + +/// The C integer sizes the contract reader needs, from the program's types. +/// Whether plain `char` is signed on the target `archid` names +/// (`AARCH64:LE:64:AppleSilicon:default`): the System V ABIs of ARM, AArch64, +/// PowerPC, RISC-V and s390 make it unsigned; Apple's and Windows' ARM ABIs +/// and x86 make it signed. A contract can override it (`-funsigned-char`). +pub fn char_signed(archid: &str) -> bool { + let mut parts = archid.split(':'); + let processor = parts.next().unwrap_or(""); + let rest: Vec<&str> = parts.collect(); + let signs_on_arm = rest.iter().any(|p| *p == "AppleSilicon" || *p == "windows"); + let unsigned_family = ["ARM", "AARCH64", "PowerPC", "RISCV", "s390"].iter().any(|p| processor.starts_with(p)); + !unsigned_family || signs_on_arm +} + +pub fn c_sizes(prog: &ConsoleProgram) -> CSizes { + let t = prog.arch().types(); + CSizes { + int: t.get_size_of_int() as u32, + long: t.get_size_of_long() as u32, + long_long: t.get_size_of_long_long() as u32, + pointer: t.get_size_of_pointer() as u32, + char_signed: char_signed(&prog.arch().archid), + } +} + +/// Where the function's prototype model returns a value of this type: an +/// integer, or a pointer, which some conventions return elsewhere. +pub fn return_storage(prog: &ConsoleProgram, fd: &Funcdata, ty: &CType) -> Result { + let arch = prog.arch(); + let types = arch.types(); + let dt = if ty.kind == CKind::Pointer { + let word = arch.manage().get_default_data_space().map_or(1, |s| s.get_word_size()); + types + .get_type_void() + .and_then(|v| types.get_type_pointer(ty.size as i32, v, word)) + .map_err(|e| format!("no {}-byte pointer type: {}", ty.size, e.explain()))? + } else { + let meta = match (&ty.kind, ty.signed) { + (CKind::Boolean, _) => type_metatype::TYPE_BOOL, + (_, true) => type_metatype::TYPE_INT, + (_, false) => type_metatype::TYPE_UINT, + }; + types + .get_base(ty.size as i32, meta) + .map_err(|e| format!("no {}-byte scalar type: {}", ty.size, e.explain()))? + }; + model_output(prog, fd, dt, ty.size).map_err(|e| format!("`{}`: {e}", ty.spelling)) +} + +/// Where the function's prototype model returns a value of type `dt`. +fn model_output(prog: &ConsoleProgram, fd: &Funcdata, dt: Rc, size: u32) -> Result { + let arch = prog.arch(); + let pieces = PrototypePieces { outtype: Some(dt), first_var_arg_slot: -1, ..Default::default() }; + let mut res: Vec = Vec::new(); + fd.get_func_proto() + .model() + .assign_parameter_storage(&pieces, &mut res, false, arch.types(), arch.manage()) + .map_err(|e| format!("model assigns no storage: {}", e.explain()))?; + let p = res.first().ok_or("model assigned no output")?; + Storage::at(&p.addr, size).ok_or_else(|| "model output has no space".to_string()) +} + +/// C's conversion of kuna's claimed return to the contract type: extend by the +/// claimed type's signedness, or truncate. +pub fn convert(v: u128, from: u32, signed: bool, to: u32) -> u128 { + let v = v & mask(from); + let negative = signed && from > 0 && from < 16 && (v >> (from * 8 - 1)) & 1 == 1; + let ext = if negative { v | !mask(from) } else { v }; + ext & mask(to) +} + +/// The extensions the calling convention promises for the claimed parameters: +/// a 32-bit `int` in a 64-bit RISC-V or MIPS register arrives sign-extended. +/// Inputs that break the promise are not inputs a conforming caller can pass, +/// so both sides start from inputs that keep it. The rule is the one the ABI +/// documents (`narrowext abi`), whatever the run's own `narrowext` value, so a +/// run with the option off is checked against the real convention. +pub fn extensions(fd: &Funcdata, env: &Env, prog: &ConsoleProgram) -> Vec { + use kuna_decomp::kuna_narrowext::{or_model, rules_for, NarrowExtMode}; + let proto = fd.get_func_proto(); + let rule = rules_for(prog.arch(), NarrowExtMode::Abi).input; + let list = proto.model().input(); + let mut out = Vec::new(); + for i in 0..proto.num_params() { + let Some(p) = proto.get_param(i) else { continue }; + let addr = p.get_address(); + let Some(space) = addr.get_space() else { continue }; + if space.get_index() != env.register.get_index() { + continue; + } + let size = p.get_size(); + let mut res = kuna_num::pcoderaw::VarnodeData::default(); + let (ext, _) = or_model(rule, list, &addr, size, p.get_type().map(|t| t.as_ref()), &mut res); + let signed = match ext { + OpCode::CPUI_INT_SEXT => true, + OpCode::CPUI_INT_ZEXT => false, + OpCode::CPUI_PIECE => p.get_type().is_some_and(|t| is_signed(t)), + _ => continue, + }; + let same_space = res.space.as_ref().is_some_and(|s| s.get_index() == space.get_index()); + if same_space && res.size > size as u32 { + out.push(Extension { + space: space.get_index(), + container: (res.offset, res.size), + param: (addr.get_offset(), size as u32), + signed, + boolean: false, + }); + } + } + out +} + +/// The extension the ABI promises for a callee's return value in a register +/// wider than it, as `narrowext abi` documents it. +pub fn return_extension(env: &Env, proto: &kuna_decomp::fspec::FuncProto) -> Option { + use kuna_decomp::kuna_narrowext::{or_model, rules_for, NarrowExtMode}; + let rule = rules_for(env.prog.arch(), NarrowExtMode::Abi).output; + let out = proto.get_output(); + let addr = out.get_address(); + let space = addr.get_space()?; + let size = out.get_size(); + if space.get_index() != env.register.get_index() || size <= 0 { + return None; + } + let mut res = kuna_num::pcoderaw::VarnodeData::default(); + let (ext, _) = or_model(rule, proto.model().output(), &addr, size, out.get_type().map(|t| t.as_ref()), &mut res); + let boolean = out.get_type().is_some_and(|t| t.get_metatype() == kuna_decomp::dtype::type_metatype::TYPE_BOOL); + let signed = match ext { + OpCode::CPUI_INT_SEXT => true, + OpCode::CPUI_INT_ZEXT => false, + OpCode::CPUI_PIECE => out.get_type().is_some_and(|t| is_signed(t)), + _ if boolean => false, + _ => return None, + }; + let param = (addr.get_offset(), size as u32); + let wider = res.space.as_ref().is_some_and(|s| s.get_index() == space.get_index()) && res.size > size as u32; + (wider || boolean).then(|| Extension { + space: space.get_index(), + container: if wider { (res.offset, res.size) } else { param }, + param, + signed, + boolean, + }) +} + +/// Input registers the body reads that no declared parameter covers (#875's +/// shape). Reported, never a verdict: a custom ABI reads them legitimately. +pub fn unclaimed_inputs(prog: &ConsoleProgram, env: &Env, fd: &Funcdata, claim: &Claim) -> Vec { + unclaimed_input_storage(prog, env, fd, claim) + .iter() + .map(|s| format!("reads {}, which no declared parameter covers", s.name(prog))) + .collect() +} + +/// The registers the body reads at entry that no claimed parameter covers. +pub fn unclaimed_input_storage(prog: &ConsoleProgram, env: &Env, fd: &Funcdata, claim: &Claim) -> Vec { + let params: Vec = claim.params.iter().flat_map(|(_, s)| s.pieces(prog)).collect(); + let sp = Storage::new(&env.register, env.sp.0, env.sp.1); + let mut found: Vec = Vec::new(); + for i in 0..fd.bblocks_get_size() { + for op in fd.bb_ops(fd.bblocks_get_block(i)) { + let Some(o) = fd.obank().get(op) else { continue }; + for k in 0..o.num_input() { + let Some(v) = o.get_in(k).and_then(|id| fd.vbank().get(id)) else { continue }; + if !v.is_input() { + continue; + } + let Some(st) = Storage::at(v.get_addr(), v.get_size() as u32) else { continue }; + if st.space.get_index() != env.register.get_index() + || st.overlaps(&sp) + || params.iter().any(|p| p.covers(&st)) + || found.iter().any(|f| f.covers(&st)) + { + continue; + } + found.push(st); + } + } + } + found +} + +#[cfg(test)] +mod char_tests { + use super::char_signed; + + #[test] + fn plain_char_by_target() { + assert!(char_signed("x86:LE:64:default:gcc")); + assert!(!char_signed("AARCH64:LE:64:v8A:default")); + assert!(!char_signed("ARM:LE:32:v8:default")); + assert!(char_signed("AARCH64:LE:64:AppleSilicon:default")); + assert!(char_signed("AARCH64:LE:64:v8A:windows")); + assert!(!char_signed("PowerPC:BE:64:default:default")); + assert!(!char_signed("RISCV:LE:64:RV64GC:gcc")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn conversion_follows_the_claimed_signedness() { + assert_eq!(convert(0x8000_0000, 4, true, 8), 0xffff_ffff_8000_0000); + assert_eq!(convert(0x8000_0000, 4, false, 8), 0x8000_0000); + assert_eq!(convert(0x1_2345_6789, 8, true, 4), 0x2345_6789); + } +} diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs new file mode 100644 index 0000000000..e8437c406f --- /dev/null +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -0,0 +1,873 @@ +//! `kuna-verify`: differential semantic checking (diffverify, Tier C). +//! +//! ```text +//! kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... +//! kuna-verify corpus ... [--jobs N] [--file-seconds S] +//! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] +//! common: [--runs N] [--seed S] [--budget OPS] [--json] [--sleighpath DIR] +//! ``` +//! +//! `corpus --jobs N` checks N files at a time, each in a worker process of +//! this binary (`shard`) that prints one JSON line, so a file's verdicts do +//! not depend on the files checked before it and a crash costs only its own. +//! A worker still running after `--file-seconds` (1200) is killed and its file +//! is an error, as a crash is. +//! `check --jobs N` splits the functions into fixed chunks and checks N chunks +//! at a time, each in a worker process (`chunk`) that prints a line as each +//! function is done; rows print as they arrive. A function with no verdict +//! after `--fn-seconds` (600) is `UNKNOWN(timeout)`, and the rest of its +//! chunk goes to a fresh worker. +//! +//! Exit status: 1 when a function differs, 3 when a file could not be checked, +//! 2 for a usage error, else 0. + +use std::collections::BTreeMap; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, ExitCode, Stdio}; +use std::time::Instant; + +use kuna_verify::{check_binary_each, check_datatest, session, Options, Report, Row, Verdict}; +use serde_json::{json, Value}; + + +const USAGE: &str = "usage: + kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... + kuna-verify corpus ... [--jobs N] [--file-seconds S] + kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] +options: --runs N (256) --seed S --budget OPS (200000) --call-reruns N (4) --json --trace --sleighpath DIR"; + +struct Args { + positional: Vec, + contract: Option, + options: Vec<(String, String)>, + opts: Options, + sleighpath: Option, + json: bool, + all: bool, + jobs: Option, + fn_seconds: u64, + file_seconds: u64, + /// `--fn-seconds` or `--file-seconds` was given: every check then runs in + /// a worker process, which is what a time limit can stop. + timed: bool, + per_function: usize, + /// Flags a worker process gets again. + forward: Vec, +} + +fn parse(argv: &[String]) -> Result { + let mut a = Args { + positional: Vec::new(), + contract: None, + options: Vec::new(), + opts: Options::default(), + sleighpath: None, + json: false, + all: false, + jobs: None, + fn_seconds: 600, + file_seconds: 1200, + timed: false, + per_function: 6, + forward: Vec::new(), + }; + let mut it = argv.iter(); + let num = |v: Option<&String>, flag: &str| -> Result { + let v = v.ok_or(format!("{flag} needs a value"))?; + let r = match v.strip_prefix("0x") { + Some(h) => u64::from_str_radix(h, 16), + None => v.parse(), + }; + r.map_err(|_| format!("{flag}: not a number: {v}")) + }; + while let Some(arg) = it.next() { + match arg.as_str() { + "--contract" => a.contract = Some(it.next().ok_or("--contract needs a file")?.clone()), + "--option" => { + let n = it.next().ok_or("--option needs NAME VALUE")?; + let v = it.next().ok_or("--option needs NAME VALUE")?; + a.options.push((n.clone(), v.clone())); + } + "--call-reruns" => { + let v = it.next(); + a.opts.call_reruns = u32::try_from(num(v, "--call-reruns")?).map_err(|_| "--call-reruns: too large")?; + a.forward.extend(["--call-reruns".to_string(), v.cloned().unwrap_or_default()]); + } + "--runs" | "--seed" | "--budget" => { + let v = it.next(); + let n = num(v, arg)?; + match arg.as_str() { + "--runs" => { + a.opts.runs = u32::try_from(n).ok().filter(|&r| r > 0).ok_or("--runs takes a count from 1 to 4294967295")? + } + "--seed" => a.opts.seed = n, + _ => a.opts.budget = n, + } + a.forward.extend([arg.clone(), v.cloned().unwrap_or_default()]); + } + "--sleighpath" => { + let v = it.next().ok_or("--sleighpath needs a directory")?.clone(); + a.forward.extend(["--sleighpath".to_string(), v.clone()]); + a.sleighpath = Some(v); + } + "--jobs" => a.jobs = Some(num(it.next(), "--jobs")? as usize), + "--fn-seconds" => { + a.fn_seconds = num(it.next(), "--fn-seconds")?.max(1); + a.timed = true; + } + "--file-seconds" => { + a.file_seconds = num(it.next(), "--file-seconds")?.max(1); + a.timed = true; + } + "--per-function" => a.per_function = num(it.next(), "--per-function")?.max(1) as usize, + "--json" => a.json = true, + "--all" => a.all = true, + "--trace" => { + a.opts.trace = true; + a.forward.push("--trace".to_string()); + } + s if s.starts_with("--") => return Err(format!("unknown flag {s}")), + _ => a.positional.push(arg.clone()), + } + } + Ok(a) +} + +fn spec_roots(sleighpath: Option<&str>) -> Vec { + if let Some(p) = sleighpath { + return vec![p.to_string()]; + } + let mut roots = Vec::new(); + for var in ["KUNA_SPECS", "SLEIGHHOME"] { + if let Ok(v) = std::env::var(var) { + if !v.is_empty() && !roots.contains(&v) { + roots.push(v); + } + } + } + for dir in spec_search_dirs() { + let p = dir.to_string_lossy().into_owned(); + if dir.join("Ghidra").join("Processors").is_dir() && !roots.contains(&p) { + roots.push(p); + } + } + roots +} + +/// Where specs are looked for, as `kuna` looks: the checkout's `specs/` when +/// this binary runs from its `decompiler/target/`, then `specs/` beside the +/// binary, beside its directory, and in the current directory. Never the +/// directory it was built in. +fn spec_search_dirs() -> Vec { + let mut dirs = Vec::new(); + if let Some(exe) = std::env::current_exe().ok().and_then(|e| e.canonicalize().ok()) { + let dir = exe.parent().map(Path::to_path_buf).unwrap_or_default(); + let target = dir.ancestors().find(|d| { + d.file_name().is_some_and(|n| n == "target") && d.parent().and_then(Path::file_name).is_some_and(|n| n == "decompiler") + }); + if let Some(root) = target.and_then(Path::parent).and_then(Path::parent) { + dirs.push(root.join("specs")); + } + dirs.push(dir.join("specs")); + if let Some(parent) = dir.parent() { + dirs.push(parent.join("specs")); + } + } + if let Ok(cwd) = std::env::current_dir() { + dirs.push(cwd.join("specs")); + } + dirs +} + +fn run_check(a: &Args) -> Result { + let [binary, named @ ..] = a.positional.as_slice() else { + return Err(USAGE.to_string()); + }; + let roots = spec_roots(a.sleighpath.as_deref()); + let cannot = |e: String| { + eprintln!("kuna-verify: {binary}: {e}"); + Ok(ExitCode::from(3)) + }; + let (functions, chunks) = if a.all { + let extents = match session::function_extents(binary, &a.options, &roots) { + Ok(x) => x, + Err(e) => return cannot(e), + }; + let sized: Vec<(String, u64)> = extents.into_iter().map(|(at, n)| (format!("{at:#x}"), n)).collect(); + (sized.iter().map(|(f, _)| f.clone()).collect::>(), chunks_by_size(&sized)) + } else { + (named.to_vec(), named.chunks(CHUNK).map(<[String]>::to_vec).collect()) + }; + if functions.is_empty() && a.all { + return cannot("no functions found to check".to_string()); + } + if functions.is_empty() { + return Err(USAGE.to_string()); + } + let jobs = a.jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())).max(1); + let started = Instant::now(); + let source = match &a.contract { + Some(f) => Some((std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"))?, f.clone())), + None => None, + }; + let rows = if !a.timed && (jobs == 1 || functions.len() <= CHUNK) { + let mut rows = Vec::new(); + let got = check_binary_each( + binary, + &functions, + &a.options, + &roots, + source.as_ref().map(|(s, n)| (s.as_str(), n.as_str())), + &a.opts, + |_, r| { + let row = Row::from(&r); + print_row(a, &row); + rows.push(row); + }, + ); + match got { + Ok(()) => rows, + Err(e) => return cannot(e), + } + } else { + match run_chunks(a, binary, chunks, jobs) { + Ok(rows) => rows, + Err(e) => return cannot(e), + } + }; + if a.all { + let wall = (functions.len() > CHUNK && jobs > 1).then(|| (0, started.elapsed().as_secs_f64())); + print_summary(a, &[], &rows, wall); + } + let crashed = rows.iter().filter(|r| r.label.starts_with("UNKNOWN(harness: worker exited")).count(); + Ok(exit_code(&rows, crashed)) +} + +/// Functions a `check` worker process takes at a time. Fixed, so which +/// functions share a process does not depend on `--jobs`. +const CHUNK: usize = 32; + +fn print_row(a: &Args, row: &Row) { + let mut out = std::io::stdout().lock(); + let _ = if a.json { writeln!(out, "{}", row.to_json()) } else { write!(out, "{}", row.render()) }; + let _ = out.flush(); +} + +/// The flags a `chunk` worker needs to check as this process would. +fn chunk_flags(a: &Args) -> Vec { + let mut v = a.forward.clone(); + for (n, val) in &a.options { + v.extend(["--option".to_string(), n.clone(), val.clone()]); + } + if let Some(c) = &a.contract { + v.extend(["--contract".to_string(), c.clone()]); + } + v +} + +/// Check `functions` in chunks across `jobs` worker processes, printing each +/// row as it arrives. +/// Chunks whose functions' total size is about the same, largest first: a +/// big function gets a worker of its own early instead of holding up the end +/// of the run. A chunk still holds at most [`CHUNK`] functions, and the +/// chunks depend only on the functions, never on `--jobs`. +fn chunks_by_size(functions: &[(String, u64)]) -> Vec> { + let mut sorted: Vec<&(String, u64)> = functions.iter().collect(); + sorted.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + let total: u64 = sorted.iter().map(|f| f.1.max(1)).sum(); + let target = total.div_ceil(functions.len().div_ceil(CHUNK).max(1) as u64); + let mut out = Vec::new(); + let (mut cur, mut acc) = (Vec::new(), 0u64); + for (f, n) in sorted { + cur.push(f.clone()); + acc += (*n).max(1); + if acc >= target || cur.len() == CHUNK { + out.push(std::mem::take(&mut cur)); + acc = 0; + } + } + if !cur.is_empty() { + out.push(cur); + } + out +} + +fn run_chunks(a: &Args, binary: &str, chunks: Vec>, jobs: usize) -> Result, String> { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let flags = chunk_flags(a); + let workers = jobs.min(chunks.len()); + let queue = std::sync::Mutex::new(chunks.into_iter().collect::>()); + let rows = std::sync::Mutex::new(Vec::new()); + let fatal = std::sync::Mutex::new(None); + std::thread::scope(|scope| { + for _ in 0..workers { + scope.spawn(|| loop { + let Some(chunk) = queue.lock().unwrap_or_else(|e| e.into_inner()).pop_front() else { break }; + let got = run_chunk(&exe, &flags, binary, &chunk, a.fn_seconds, |row| { + print_row(a, &row); + rows.lock().unwrap_or_else(|e| e.into_inner()).push(row); + }); + match got { + Ok(Some(rest)) => queue.lock().unwrap_or_else(|e| e.into_inner()).push_back(rest), + Ok(None) => {} + Err(e) => { + fatal.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(e); + break; + } + } + }); + } + }); + if let Some(e) = fatal.into_inner().unwrap_or_else(|e| e.into_inner()) { + return Err(e); + } + Ok(rows.into_inner().unwrap_or_else(|e| e.into_inner())) +} + +/// One worker over `chunk`. `Ok(Some(rest))` when it stopped early: the first +/// function without a verdict is reported, and `rest` is still to check. +fn run_chunk( + exe: &Path, + flags: &[String], + binary: &str, + chunk: &[String], + fn_seconds: u64, + mut on_row: impl FnMut(Row), +) -> Result>, String> { + let mut child = Command::new(exe) + .arg("chunk") + .args(flags) + .arg(binary) + .args(chunk) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|e| e.to_string())?; + let stdout = child.stdout.take().ok_or("worker without stdout")?; + let (tx, rx) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + for line in std::io::BufRead::lines(std::io::BufReader::new(stdout)).map_while(Result::ok) { + if tx.send(line).is_err() { + break; + } + } + }); + let mut seen = vec![false; chunk.len()]; + let stopped = loop { + match rx.recv_timeout(std::time::Duration::from_secs(fn_seconds)) { + Ok(line) => { + let Ok(v) = serde_json::from_str::(&line) else { continue }; + if let Some(e) = v.get("error").and_then(Value::as_str) { + let _ = child.kill(); + let _ = child.wait(); + return Err(e.to_string()); + } + let pos = v.get("pos").and_then(Value::as_u64).map(|p| p as usize); + if let (Some(pos), Some(row)) = (pos.filter(|&p| p < chunk.len()), v.get("row").and_then(Row::from_json)) { + seen[pos] = true; + on_row(row); + } + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + let _ = child.kill(); + break format!("UNKNOWN(timeout: no verdict in {fn_seconds} s)"); + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break String::new(), + } + }; + let status = child.wait().map_err(|e| e.to_string())?; + let _ = reader.join(); + let Some(first) = seen.iter().position(|s| !s) else { return Ok(None) }; + let label = if stopped.is_empty() { format!("UNKNOWN(harness: worker exited ({status}))") } else { stopped }; + let report = Report { + function: chunk[first].clone(), + verdict: Verdict::Unknown(label), + lines: Vec::new(), + suspects: Vec::new(), + elapsed: std::time::Duration::ZERO, + }; + on_row(Row::from(&report)); + let rest: Vec = chunk.iter().zip(&seen).skip(first + 1).filter(|(_, s)| !**s).map(|(f, _)| f.clone()).collect(); + Ok((!rest.is_empty()).then_some(rest)) +} + +/// The `check` worker: print `{"pos", "row"}` as each function is done, or +/// `{"error"}` when the binary cannot be loaded. +fn run_chunk_worker(a: &Args) -> Result { + let [binary, functions @ ..] = a.positional.as_slice() else { + return Err(USAGE.to_string()); + }; + let roots = spec_roots(a.sleighpath.as_deref()); + let line = |v: Value| { + let mut out = std::io::stdout().lock(); + let _ = writeln!(out, "{v}"); + let _ = out.flush(); + }; + let source = match &a.contract { + Some(f) => match std::fs::read_to_string(f) { + Ok(s) => Some((s, f.clone())), + Err(e) => { + line(json!({"error": format!("{f}: {e}")})); + return Ok(ExitCode::SUCCESS); + } + }, + None => None, + }; + let got = check_binary_each( + binary, + functions, + &a.options, + &roots, + source.as_ref().map(|(s, n)| (s.as_str(), n.as_str())), + &a.opts, + |pos, r| line(json!({"pos": pos, "row": Row::from(&r).to_json()})), + ); + if let Err(e) = got { + line(json!({"error": e})); + } + Ok(ExitCode::SUCCESS) +} + +/// 1 when a function differs, 3 when a file could not be checked (a worker +/// crash included), 2 for a usage error, else 0. `UNKNOWN` is not a failure: +/// it says what the model could not check. +fn exit_code(rows: &[Row], file_errors: usize) -> ExitCode { + if rows.iter().any(|r| r.class == "DIFFERS") { + ExitCode::from(1) + } else if file_errors > 0 { + ExitCode::from(3) + } else { + ExitCode::SUCCESS + } +} + +fn collect(path: &Path, out: &mut Vec) -> Result<(), String> { + if path.is_dir() { + let mut entries = Vec::new(); + for e in std::fs::read_dir(path).map_err(|e| format!("{}: {e}", path.display()))? { + entries.push(e.map_err(|e| format!("{}: {e}", path.display()))?.path()); + } + entries.sort(); + for e in entries { + collect(&e, out)?; + } + } else if path.extension().is_some_and(|x| x == "xml") { + out.push(path.to_path_buf()); + } + Ok(()) +} + +/// One datatest file's verdicts. +struct FileRows { + rows: Vec, + error: Option, +} + +fn file_json(index: usize, rows: &[Row], error: Option<&str>, wall_ms: f64) -> Value { + json!({ + "index": index, + "rows": rows.iter().map(Row::to_json).collect::>(), + "error": error, + "wall_ms": wall_ms, + }) +} + +/// The worker: check each listed `index=path` and print one JSON line per file. +fn run_shard(a: &Args) -> Result { + let roots = spec_roots(a.sleighpath.as_deref()); + let mut out = std::io::stdout().lock(); + for item in &a.positional { + let (index, path) = item.split_once('=').ok_or("shard items are index=path")?; + let index: usize = index.parse().map_err(|_| "bad shard index")?; + let res = check_datatest(path, &roots, &a.opts); + let rows: Vec = res.reports.iter().map(Row::from).collect(); + let line = file_json(index, &rows, res.error.as_deref(), res.wall.as_secs_f64() * 1e3); + writeln!(out, "{line}").map_err(|e| e.to_string())?; + out.flush().map_err(|e| e.to_string())?; + } + Ok(ExitCode::SUCCESS) +} + +fn parse_file_line(line: &str) -> Option<(usize, FileRows)> { + let v: Value = serde_json::from_str(line).ok()?; + let index = v.get("index")?.as_u64()? as usize; + let rows = v.get("rows")?.as_array()?.iter().map(Row::from_json).collect::>>()?; + let error = v.get("error").and_then(Value::as_str).map(str::to_string); + Some((index, FileRows { rows, error })) +} + +/// Run `files` across `jobs` threads, each file in a worker process of its +/// own: a file's verdicts never depend on what the same process checked +/// before it, and a crash costs only that file. +fn run_workers(a: &Args, files: &[PathBuf], jobs: usize) -> Result, String> { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let next = std::sync::atomic::AtomicUsize::new(0); + let results: Vec>> = (0..files.len()).map(|_| std::sync::Mutex::new(None)).collect(); + std::thread::scope(|scope| { + for _ in 0..jobs { + scope.spawn(|| loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(file) = files.get(i) else { break }; + let got = check_in_worker(&exe, &a.forward, i, file, a.file_seconds); + *results[i].lock().unwrap_or_else(|e| e.into_inner()) = Some(got); + }); + } + }); + Ok(results + .into_iter() + .map(|r| r.into_inner().unwrap_or_else(|e| e.into_inner()).expect("every file is checked")) + .collect()) +} + +/// Check one datatest file in a worker process; a worker that has not +/// finished after `seconds` is killed and its file reported as an error. +fn check_in_worker(exe: &Path, forward: &[String], index: usize, file: &Path, seconds: u64) -> FileRows { + let child = Command::new(exe) + .arg("shard") + .args(forward) + .arg(format!("{index}={}", file.to_string_lossy())) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn(); + let mut child = match child { + Ok(c) => c, + Err(e) => return FileRows { rows: Vec::new(), error: Some(e.to_string()) }, + }; + let Some(mut stdout) = child.stdout.take() else { + let _ = child.kill(); + return FileRows { rows: Vec::new(), error: Some("worker has no output".to_string()) }; + }; + let (tx, rx) = std::sync::mpsc::channel(); + let reader = std::thread::spawn(move || { + let mut text = String::new(); + let _ = std::io::Read::read_to_string(&mut stdout, &mut text); + let _ = tx.send(text); + }); + let Ok(text) = rx.recv_timeout(std::time::Duration::from_secs(seconds)) else { + let _ = child.kill(); + let _ = child.wait(); + let _ = reader.join(); + return FileRows { rows: Vec::new(), error: Some(format!("timeout: no verdicts in {seconds} s")) }; + }; + let status = child.wait().map(|s| s.to_string()).unwrap_or_else(|e| e.to_string()); + let _ = reader.join(); + text.lines() + .find_map(parse_file_line) + .map(|(_, rows)| rows) + .unwrap_or_else(|| FileRows { rows: Vec::new(), error: Some(format!("worker exited ({status})")) }) +} + +fn run_corpus(a: &Args) -> Result { + if a.positional.is_empty() { + return Err(USAGE.to_string()); + } + let mut files = Vec::new(); + for p in &a.positional { + let path = Path::new(p); + if !path.exists() { + return Err(format!("{p}: no such file or directory")); + } + collect(path, &mut files)?; + } + if files.is_empty() { + return Err("no datatest .xml files under the given paths".to_string()); + } + let started = Instant::now(); + let jobs = a + .jobs + .unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())) + .clamp(1, files.len().max(1)); + let results: Vec = if jobs == 1 && !a.timed { + let roots = spec_roots(a.sleighpath.as_deref()); + files + .iter() + .map(|f| { + let res = check_datatest(&f.to_string_lossy(), &roots, &a.opts); + FileRows { rows: res.reports.iter().map(Row::from).collect(), error: res.error } + }) + .collect() + } else { + run_workers(a, &files, jobs)? + }; + let names: Vec = files + .iter() + .map(|f| f.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default()) + .collect(); + if !a.json { + println!("| test | function | verdict | check ms |"); + println!("|---|---|---|---:|"); + } + let mut all_rows = Vec::new(); + let mut errors = Vec::new(); + for (name, res) in names.iter().zip(&results) { + for r in &res.rows { + if a.json { + let mut v = r.to_json(); + v["test"] = json!(name); + println!("{v}"); + } else { + println!("| {name} | {} | {} | {:.2} |", r.function, r.label, r.ms); + if r.class == "DIFFERS" || !r.suspects.is_empty() { + for l in r.render().lines().skip(1) { + println!("| | | `{}` | |", l.trim()); + } + } + } + all_rows.push((name.clone(), r.clone())); + } + if let Some(e) = &res.error { + errors.push((name.clone(), e.clone())); + if a.json { + println!("{}", json!({"test": name, "error": e})); + } else { + println!("| {name} | — | file error: {} | |", e.replace('|', "/")); + } + } + } + let rows: Vec = all_rows.iter().map(|(_, r)| r.clone()).collect(); + let slowest: Vec<(f64, String)> = { + let mut v: Vec<_> = all_rows.iter().map(|(n, r)| (r.ms, format!("{n}/{}", r.function))).collect(); + v.sort_by(|x, y| y.0.total_cmp(&x.0)); + v.truncate(5); + v + }; + print_summary(a, &slowest, &rows, Some((files.len(), started.elapsed().as_secs_f64()))); + if !errors.is_empty() && !a.json { + println!("file errors {}", errors.len()); + } + Ok(exit_code(&rows, errors.len())) +} + +/// `corpus`: the file count and the wall time of the whole run; a file count +/// of 0 is a `check` run over workers, which has a wall time but no files. +fn print_summary(a: &Args, slowest: &[(f64, String)], rows: &[Row], corpus: Option<(usize, f64)>) { + let mut counts: BTreeMap<&str, u32> = BTreeMap::new(); + let mut reasons: BTreeMap = BTreeMap::new(); + for r in rows { + *counts.entry(r.class.as_str()).or_default() += 1; + if let Some(k) = r.reason() { + *reasons.entry(k).or_default() += 1; + } + } + let check_s: f64 = rows.iter().map(|r| r.ms).sum::() / 1e3; + if a.json { + println!( + "{}", + json!({"summary": {"files": corpus.map(|c| c.0).filter(|&f| f > 0), "functions": rows.len(), "verdicts": counts, + "reasons": reasons, "check_seconds": check_s, "wall_seconds": corpus.map(|c| c.1), + "runs": a.opts.runs}}) + ); + return; + } + println!(); + match corpus { + Some((files, _)) if files > 0 => println!("files {files} functions {}", rows.len()), + _ => println!("functions {}", rows.len()), + } + for (k, v) in &counts { + println!(" {k:<9} {v}"); + } + for (k, v) in &reasons { + println!(" {k} {v}"); + } + match corpus { + Some((_, wall)) => println!("check time {check_s:.3} s wall time {wall:.3} s (runs {})", a.opts.runs), + None => println!("check time {check_s:.3} s (runs {})", a.opts.runs), + } + for (ms, n) in slowest { + println!(" slowest {n} {ms:.1} ms"); + } +} + +fn main() -> ExitCode { + let argv: Vec = std::env::args().skip(1).collect(); + let Some((cmd, rest)) = argv.split_first() else { + eprintln!("{USAGE}"); + return ExitCode::from(2); + }; + let result = parse(rest).and_then(|a| match cmd.as_str() { + "check" => run_check(&a), + "corpus" => run_corpus(&a), + "shard" => run_shard(&a), + "chunk" => run_chunk_worker(&a), + "mutate" => run_mutate(&a), + _ => Err(USAGE.to_string()), + }); + match result { + Ok(code) => code, + Err(e) => { + eprintln!("kuna-verify: {e}"); + ExitCode::from(2) + } + } +} + +fn mutant_json(o: &kuna_verify::mutate::Outcome) -> Value { + json!({ + "function": o.function, + "operator": o.operator.name(), + "what": o.what, + "verdict": o.verdict.label(), + "killed": o.killed(), + "reached": o.reached, + "ms": o.ms, + }) +} + +/// `mutate`: plant mutants in kuna's side of functions that agree and report +/// which the check catches. With `--jobs` above 1, each datatest file or each +/// chunk of a binary's functions runs in a worker process of its own. +fn run_mutate(a: &Args) -> Result { + let roots = spec_roots(a.sleighpath.as_deref()); + let Some(first) = a.positional.first() else { return Err(USAGE.to_string()) }; + let datatests = first.ends_with(".xml") || Path::new(first).is_dir(); + let jobs = a.jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(1, |n| n.get())).max(1); + let mut tasks: Vec> = Vec::new(); + if datatests { + let mut files = Vec::new(); + for p in &a.positional { + collect(Path::new(p), &mut files)?; + } + tasks.extend(files.iter().map(|f| vec![f.to_string_lossy().into_owned()])); + } else { + let chunks: Vec> = if a.all { + let extents = match session::function_extents(first, &a.options, &roots) { + Ok(extents) => extents, + Err(e) => { + eprintln!("kuna-verify: {first}: {e}"); + return Ok(ExitCode::from(3)); + } + }; + let sized: Vec<(String, u64)> = extents.into_iter().map(|(at, n)| (format!("{at:#x}"), n)).collect(); + chunks_by_size(&sized) + } else { + a.positional[1..].chunks(CHUNK).map(<[String]>::to_vec).collect() + }; + tasks.extend(chunks.into_iter().map(|c| std::iter::once(first.clone()).chain(c).collect())); + } + if tasks.is_empty() { + return Err(USAGE.to_string()); + } + let failed = std::sync::atomic::AtomicBool::new(false); + let fail = |path: &str, error: &dyn std::fmt::Display| { + failed.store(true, std::sync::atomic::Ordering::Relaxed); + eprintln!("kuna-verify: {path}: {error}"); + }; + let rows: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); + let print = |v: Value| { + if a.json { + println!("{v}"); + } + rows.lock().unwrap_or_else(|e| e.into_inner()).push(v); + }; + if jobs == 1 && !a.timed { + for t in &tasks { + let emit = |o: kuna_verify::mutate::Outcome| print(mutant_json(&o)); + let result = if datatests { + kuna_verify::mutate_datatest(&t[0], &roots, &a.opts, a.per_function, emit) + } else { + kuna_verify::mutate_binary(&t[0], &t[1..], &a.options, &roots, &a.opts, a.per_function, emit) + }; + if let Err(e) = result { + fail(&t[0], &e); + } + } + } else { + let exe = std::env::current_exe().map_err(|e| e.to_string())?; + let mut flags = chunk_flags(a); + flags.extend(["--per-function".to_string(), a.per_function.to_string(), "--jobs".to_string(), "1".to_string(), "--json".to_string()]); + let next = std::sync::atomic::AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..jobs.min(tasks.len().max(1)) { + scope.spawn(|| loop { + let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let Some(t) = tasks.get(i) else { break }; + let (status, out) = match output_within(Command::new(&exe).arg("mutate").args(t).args(&flags), a.file_seconds) { + Ok(result) => result, + Err(e) => { + fail(&t[0], &e); + continue; + } + }; + if !status.success() { + fail(&t[0], &format_args!("mutation worker exited with {status}")); + } + for l in out.lines() { + if let Ok(mut v) = serde_json::from_str::(l) { + if v.get("operator").is_some() { + v["file"] = Value::from(t[0].as_str()); + print(v); + } + } + } + }); + } + }); + } + let rows = rows.into_inner().unwrap_or_else(|e| e.into_inner()); + print_mutation_summary(&rows, a.json); + Ok(if failed.into_inner() { ExitCode::from(3) } else { ExitCode::SUCCESS }) +} + +/// Run `cmd` and collect its output, killing it if it runs past `seconds`. +fn output_within(cmd: &mut Command, seconds: u64) -> Result<(std::process::ExitStatus, String), String> { + let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| e.to_string())?; + let mut stdout = child.stdout.take().ok_or("worker without stdout")?; + let reader = std::thread::spawn(move || { + let mut out = String::new(); + std::io::Read::read_to_string(&mut stdout, &mut out).map(|_| out) + }); + let started = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Ok(status), + Ok(None) if started.elapsed().as_secs() < seconds => std::thread::sleep(std::time::Duration::from_millis(50)), + Ok(None) => break Err(format!("mutation worker timed out after {seconds} s")), + Err(e) => break Err(e.to_string()), + } + }; + if status.is_err() { + let _ = child.kill(); + let _ = child.wait(); + } + let output = reader.join(); + Ok((status?, output.map_err(|_| "mutation worker's output reader panicked")?.map_err(|e| e.to_string())?)) +} + +fn print_mutation_summary(rows: &[Value], json: bool) { + let mut by: std::collections::BTreeMap = std::collections::BTreeMap::new(); + for r in rows { + let e = by.entry(r["operator"].as_str().unwrap_or("?").to_string()).or_default(); + e[0] += 1; + if r["reached"].as_bool() == Some(true) { + e[1] += 1; + if r["killed"].as_bool() == Some(true) { + e[2] += 1; + } else if r["verdict"].as_str().is_some_and(|v| v.starts_with("UNKNOWN")) { + e[3] += 1; + } + } + } + let total = by.values().fold([0usize; 4], |acc, e| [acc[0] + e[0], acc[1] + e[1], acc[2] + e[2], acc[3] + e[3]]); + let recall = |e: &[usize; 4]| if e[1] == 0 { 0.0 } else { 100.0 * e[2] as f64 / e[1] as f64 }; + if json { + let ops: serde_json::Map = by + .iter() + .map(|(k, e)| (k.clone(), json!({"mutants": e[0], "reached": e[1], "killed": e[2], "unknown": e[3], "recall": recall(e)}))) + .collect(); + println!("{}", json!({"mutation_summary": {"operators": ops, "mutants": total[0], "reached": total[1], "killed": total[2], "unknown": total[3], "recall": recall(&total)}})); + return; + } + println!("{:<12} {:>8} {:>8} {:>8} {:>8} {:>7}", "operator", "mutants", "reached", "killed", "unknown", "recall"); + for (k, e) in by.iter().chain(std::iter::once((&"all".to_string(), &total))) { + println!("{:<12} {:>8} {:>8} {:>8} {:>8} {:>6.1}%", k, e[0], e[1], e[2], e[3], recall(e)); + } + let survived: Vec<&Value> = rows + .iter() + .filter(|r| r["reached"].as_bool() == Some(true) && r["killed"].as_bool() != Some(true) && !r["verdict"].as_str().is_some_and(|v| v.starts_with("UNKNOWN"))) + .collect(); + for r in survived.iter().take(20) { + println!("survived {} {} {}", r["function"].as_str().unwrap_or(""), r["what"].as_str().unwrap_or(""), r["verdict"].as_str().unwrap_or("")); + } +} diff --git a/decompiler/crates/kuna-verify/src/compare/check.rs b/decompiler/crates/kuna-verify/src/compare/check.rs new file mode 100644 index 0000000000..f532bef95f --- /dev/null +++ b/decompiler/crates/kuna-verify/src/compare/check.rs @@ -0,0 +1,730 @@ +//! Tier C: run both sides of one function and compare what they do. +//! +//! A run compares, in order: each call (its target, kuna's arguments, and the +//! memory the callee can read), whether the function returns at all, the return +//! value, and the memory left outside the stack. The return value is compared +//! under the physical ABI (the bytes kuna's claimed return occupies) and, when a +//! typed contract is given, at the contract's width with kuna's value converted +//! to the contract type by C's rules. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::time::Instant; + +use kuna_base::space::spacetype; +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::funcdata::Funcdata; + +use crate::abi::{self, Claim}; +use crate::contract::{CKind, CType, Contract}; +use crate::divergence; +use crate::calls::{self, Calls, Record}; +use crate::program::{self, Program}; +use crate::report::{Report, Verdict}; +use crate::state::{Env, State}; +use crate::storage::{hex, Storage}; +use crate::value::Halt; +use crate::{graph, machine}; +use super::observe::*; +use super::returns::{Compare, Outcome}; +use super::setup::*; +#[derive(Debug, Clone, Copy)] +pub struct Options { + pub runs: u32, + pub seed: u64, + /// Ops per side per run. + pub budget: u64, + /// Runs that may exhaust the budget before the function is given up as + /// `UNKNOWN(budget)`: a loop bounded by an argument exhausts it on almost + /// every random input. + pub budget_runs: u32, + /// Add both sides' calls to a `DIFFERS` report. + pub trace: bool, + /// Calls per run whose callee read an argument kuna passes otherwise + /// that get a machine rerun with kuna's value. A run with more is not + /// counted as agreeing. + pub call_reruns: u32, +} + +impl Default for Options { + fn default() -> Self { + Options { runs: 256, seed: 0x6b75_6e61, budget: 200_000, budget_runs: 4, trace: false, call_reruns: 4 } + } +} + +/// Upper return registers the machine sets to the same value on every run while +/// kuna's claimed return leaves them out (#794's shape). +struct UpperWatch { + extra: Vec, + value: Option>, + every_run: bool, +} + +impl UpperWatch { + fn new(prog: &ConsoleProgram, fd: &Funcdata, claim: &Claim) -> Option { + let out = claim.storage.as_ref()?; + let wide = abi::return_storage(prog, fd, &CType { spelling: String::new(), size: out.size * 2, signed: false, kind: CKind::Integer }).ok()?; + let pieces = wide.pieces(prog); + let extra: Vec = pieces.iter().filter(|p| !p.overlaps(out)).cloned().collect(); + (!extra.is_empty() && pieces.iter().any(|p| p.covers(out))).then_some(UpperWatch { + extra, + value: None, + every_run: true, + }) + } + + fn observe(&mut self, ms: &mut State) { + let mut vals = Vec::with_capacity(self.extra.len()); + for p in &self.extra { + if !ms.wrote(&p.space, p.off, p.size) { + self.every_run = false; + return; + } + match ms.read_storage(&p.space, p.off, p.size) { + Ok(v) => vals.push(v), + Err(_) => { + self.every_run = false; + return; + } + } + } + match &self.value { + None => self.value = Some(vals), + Some(prev) if *prev != vals => self.every_run = false, + _ => {} + } + } + + fn suspects(self, prog: &ConsoleProgram) -> Vec { + let Some(vals) = self.value.filter(|_| self.every_run) else { return Vec::new() }; + self.extra + .iter() + .zip(vals) + .map(|(p, v)| { + format!( + "the machine sets {} to {} on every run; the claimed return leaves it out", + p.name(prog), + hex(v, p.size) + ) + }) + .collect() + } +} + +/// Runs that may stop on an operation the model cannot run before the +/// function is given up as `UNKNOWN(unsupported-op)`: such a function is +/// `UNKNOWN` whatever its other runs show, unless one of them differs, and +/// later runs mostly take the same path into the same operation. +const UNSUPPORTED_RUNS: u32 = 16; + +/// Runs that are repeated with other values in the storage kuna's C never +/// assigns. +const PERTURBED_RUNS: u32 = 16; + +/// Runs that may run past the op budget on both sides, counted apart, before +/// the function stops being run: each costs two full budgets. A run past it on +/// one side only still makes the function `UNKNOWN(budget)`: one side may loop +/// where the other does not. +const BUDGET_RUNS_APART: u32 = 64; + +/// Once `budget_runs` runs have run past the budget on both sides, later runs +/// get this fraction of it: a run is only cut off sooner, never compared +/// differently. One that then runs past it on one side only is run again with +/// the whole budget before it counts as one side looping. +const SHORT_BUDGET: u64 = 8; + +/// Runs of the pass that gives a parameter kuna's recovered prototype types +/// `bool` any value: the 0-or-1 domain is kuna's claim, not the program's. +const DOMAIN_RUNS: u32 = 64; + +/// A function's machine-side setup, built once and shared by the checks of +/// its mutants: the environment, kuna's claim and the call sites. +pub struct Prepared<'p> { + env: Env<'p>, + claim: Claim, + machine_calls: Calls, + assumed: bool, +} + +/// What the checks of one function's mutants share: its setup, and the +/// machine's unmodified runs, which no mutant of kuna's side changes. +pub struct Shared<'e, 'p> { + prepared: &'e Prepared<'p>, + machines: RefCell, Halt>>>, +} + +impl<'e, 'p> Shared<'e, 'p> { + pub fn new(prepared: &'e Prepared<'p>) -> Self { + Shared { prepared, machines: RefCell::default() } + } +} + +fn early(fd: &Funcdata, started: Instant, verdict: Verdict) -> Report { + Report { function: fd.get_name().to_string(), verdict, lines: Vec::new(), suspects: Vec::new(), elapsed: started.elapsed() } +} + +/// Build `fd`'s machine-side setup; a report when the function cannot be +/// checked at all. +pub fn prepare<'p>(prog: &'p ConsoleProgram, fd: &'p Funcdata, opts: &Options, free_domain: bool) -> Result, Report> { + let started = Instant::now(); + let mut env = Env::new(prog, opts.seed).map_err(|h| early(fd, started, Verdict::from_halt(&h)))?; + env.fd = Some(fd); + let claim = abi::claim(prog, fd); + if let Some(out) = claim + .storage + .as_ref() + .filter(|o| matches!(o.space.get_type(), spacetype::IPTR_INTERNAL | spacetype::IPTR_CONSTANT)) + { + let at = format!("{}:{:#x}", out.space.get_name(), out.off); + return Err(early(fd, started, Verdict::Unknown(format!("UNKNOWN(return storage {at} is not machine state)")))); + } + env.extensions = abi::extensions(fd, &env, prog); + env.tracked = tracked(prog, fd, &mut env); + env.booleans = booleans(fd, &env); + let assumed = !fd.get_func_proto().is_input_locked() && !env.booleans.is_empty(); + if free_domain { + env.booleans.clear(); + } + env.kernel.set(kernel_returns(prog)); + let machine_calls = calls::sites(fd, &env); + env.arg_regs = machine_calls.input_regs.clone(); + env.scratch_regs = veneer_registers(prog); + Ok(Prepared { env, claim, machine_calls, assumed }) +} + +pub fn check_function(prog: &ConsoleProgram, fd: &Funcdata, contract: Option<&Contract>, opts: &Options) -> Report { + let started = Instant::now(); + let mut report = match prepare(prog, fd, opts, false) { + Ok(p) => check_prepared(prog, fd, contract, opts, &Shared::new(&p), false), + Err(r) => r, + }; + report.elapsed = started.elapsed(); + report +} + +/// `check_function` on a shared setup, keeping the machine's runs for the +/// checks of mutants that follow. +pub fn check_shared(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, shared: &Shared) -> Report { + check_prepared(prog, fd, None, opts, shared, true) +} + +fn check_prepared(prog: &ConsoleProgram, fd: &Funcdata, contract: Option<&Contract>, opts: &Options, shared: &Shared, keep: bool) -> Report { + let mut report = check_runs(prog, fd, contract, opts, None, &mut None, shared, keep); + if shared.prepared.assumed && matches!(report.verdict, Verdict::Agrees(_)) { + let free = Options { runs: opts.runs.min(DOMAIN_RUNS), ..*opts }; + let wide = match prepare(prog, fd, &free, true) { + Ok(p) => check_runs(prog, fd, contract, &free, None, &mut None, &Shared::new(&p), false), + Err(r) => r, + }; + if matches!(wide.verdict, Verdict::Differs { .. }) { + report.verdict = Verdict::Unknown( + "UNKNOWN(assumed-domain: agrees only while a parameter kuna's recovered prototype types bool holds 0 or 1)".into(), + ); + report.lines = wide.lines; + report.suspects = wide.suspects; + } else if let Verdict::Agrees(n) = wide.verdict { + report.lines.push(format!("note a parameter kuna's recovered prototype types bool also took any byte, in {n} runs that agree")); + } else { + report.lines.push(format!("note with any byte in a parameter kuna's recovered prototype types bool, the check ended {}", wide.verdict.label())); + report.verdict = match wide.verdict { + d @ Verdict::Diverges(_) => d, + _ => Verdict::Unknown( + "UNKNOWN(assumed-domain: agrees while a parameter kuna's recovered prototype types bool holds 0 or 1; with any byte the check could not tell)".into(), + ), + }; + } + } + report +} + +/// Check `fd` with mutant `m` planted on kuna's side: the report, what the +/// mutant changed, and whether a run reached it. `None` when it does not apply. +pub fn check_mutant(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, m: crate::mutate::Mutation) -> Option<(Report, String, bool)> { + let p = prepare(prog, fd, opts, false).ok()?; + check_mutant_shared(prog, fd, opts, m, &Shared::new(&p)) +} + +/// `check_mutant` on a shared setup, reusing the machine's runs. +pub fn check_mutant_shared(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, m: crate::mutate::Mutation, shared: &Shared) -> Option<(Report, String, bool)> { + let mut got = None; + let reached = std::rc::Rc::new(std::cell::Cell::new(false)); + let report = check_runs(prog, fd, None, opts, Some((m, std::rc::Rc::clone(&reached))), &mut got, shared, true); + got.map(|what| (report, what, reached.get())) +} + +fn check_runs<'e, 'p>( + prog: &ConsoleProgram, + fd: &Funcdata, + contract: Option<&Contract>, + opts: &Options, + mutation: Option<(crate::mutate::Mutation, std::rc::Rc>)>, + mutated: &mut Option, + shared: &Shared<'e, 'p>, + keep: bool, +) -> Report { + let started = Instant::now(); + let finish = |verdict: Verdict, lines: Vec, suspects: Vec| { + Report { function: fd.get_name().to_string(), verdict, lines, suspects, elapsed: started.elapsed() } + }; + let env: &'e Env<'p> = &shared.prepared.env; + let claim = &shared.prepared.claim; + let contract_storage = match contract.filter(|c| !c.ret.is_void()) { + Some(c) => match abi::return_storage(prog, fd, &c.ret) { + Ok(s) => Some(s), + Err(e) => return finish(Verdict::Unknown(format!("UNKNOWN(contract: {e})")), Vec::new(), Vec::new()), + }, + None => None, + }; + let compare = Compare { prog, claim, contract: contract.zip(contract_storage.as_ref()) }; + let mut upper = UpperWatch::new(prog, fd, claim); + let mut machine_calls = std::borrow::Cow::Borrowed(&shared.prepared.machine_calls); + let mut calls = machine_calls.as_ref().clone(); + let mut program: Program = program::compile(prog, fd, &calls); + let mut noreturn_site = None; + if let Some((m, reached)) = mutation { + program.reached = reached; + match crate::mutate::apply(&mut program, &mut calls, env, m) { + Some(what) => { + if m.operator == crate::mutate::Operator::NoReturn { + let at = program.blocks[m.block].ops[m.op].at; + if let Some(s) = machine_calls.to_mut().by_addr.get_mut(&at) { + s.noreturn = true; + } + noreturn_site = Some(at); + } + *mutated = Some(what) + } + None => return finish(Verdict::Unknown("UNKNOWN(mutant does not apply)".into()), Vec::new(), Vec::new()), + } + } + let machine_calls: &Calls = &machine_calls; + let entry = fd.get_address().get_offset(); + let base_machine = |run: u32, budget: u64| -> Result, Halt> { + if !keep { + return machine::run(env, run, entry, budget, machine_calls, None); + } + let kept = shared.machines.borrow().get(&(run, budget)).cloned(); + match (kept, noreturn_site) { + (Some(r), None) => r, + (Some(Ok(mo)), Some(at)) if !mo.sites_reached.contains(&at) => Ok(mo), + (_, Some(_)) => machine::run(env, run, entry, budget, machine_calls, None), + (None, None) => { + let r = machine::run(env, run, entry, budget, machine_calls, None); + shared.machines.borrow_mut().insert((run, budget), r.clone()); + r + } + } + }; + let calls = calls; + let program = program; + let left_cfg = |mo: &machine::Outcome| mo.indirect.iter().any(|t| !program.starts.contains(t)); + let mut agreed = 0u32; + let mut unverified_runs = 0u32; + let mut unrerun_runs = 0u32; + let mut trapped_runs = 0u32; + let mut trapped: Option = None; + let mut budget_runs = 0u32; + let mut both_budget_runs = 0u32; + let mut unsupported_runs = 0u32; + let mut unknown: Option = None; + let mut diverged: Option<&'static str> = None; + let mut call_suspects: Vec = Vec::new(); + let perturb = unassigned(prog, env, fd, claim, &program, &calls); + let mut perturbed_runs = 0u32; + let mut kernel_shows = false; + for run in 0..opts.runs { + let short = both_budget_runs >= opts.budget_runs; + let run_budget = if short { opts.budget / SHORT_BUDGET } else { opts.budget }; + let mut m = base_machine(run, run_budget); + let mut g = graph::run(env, &program, run, run_budget, &calls, m.as_ref().map(|mo| mo.calls.as_slice()).unwrap_or(&[]), None); + if short && matches!(m, Err(Halt::Budget)) != matches!(g, Err(Halt::Budget)) { + m = base_machine(run, opts.budget); + g = graph::run(env, &program, run, opts.budget, &calls, m.as_ref().map(|mo| mo.calls.as_slice()).unwrap_or(&[]), None); + } + let overlap = g.as_ref().ok().and_then(|go| go.overlapping_copy); + let rerun_machine = |with_args: Option<&machine::WithArgs>| match overlap { + Some(copy) => machine::run_before_copy(env, run, entry, opts.budget, machine_calls, with_args, copy.checkpoint), + None => machine::run(env, run, entry, opts.budget, machine_calls, with_args), + }; + if overlap.is_some() && m.is_ok() { + m = rerun_machine(None); + } + let (mo, go) = match (m, g) { + (Err(Halt::Trap(t)), Err(Halt::Trap(_))) => { + trapped.get_or_insert(t); + trapped_runs += 1; + continue; + } + (Ok(_), Err(Halt::Trap(t))) if env.divide_by_zero_is_zero && t.contains("ivide by 0") => { + diverged.get_or_insert(divergence::DIVIDE_BY_ZERO.id); + continue; + } + (Err(Halt::Trap(t)), Ok(_)) if t.starts_with(crate::state::READONLY_STORE) => { + trapped.get_or_insert(t); + trapped_runs += 1; + continue; + } + (Ok(mo), Err(Halt::NoRow(_))) if left_cfg(&mo) => { + diverged.get_or_insert(divergence::SWITCH_RUNON.id); + continue; + } + (Err(Halt::Budget), Err(Halt::Budget)) => { + both_budget_runs += 1; + if both_budget_runs >= BUDGET_RUNS_APART || (agreed == 0 && both_budget_runs >= 4 * opts.budget_runs) { + break; + } + continue; + } + (Err(h), _) | (_, Err(h)) => { + match h { + Halt::Budget => budget_runs += 1, + Halt::Unsupported(_) | Halt::UnexpectedReturn(_) => unsupported_runs += 1, + _ => {} + } + unknown.get_or_insert(h); + if budget_runs >= opts.budget_runs || unsupported_runs >= UNSUPPORTED_RUNS { + break; + } + continue; + } + (Ok(mo), Ok(go)) => { + if diverged.is_none() && !env.kernel.get() && mo.events.iter().any(|e| calls::SYSTEM_USEROPS.contains(&e.name.as_str())) { + env.kernel.set(true); + let alt = rerun_machine(None); + env.kernel.set(false); + if alt.is_ok_and(|alt| matches!(machine_differs(prog, env, run, machine_calls, &compare, &mo, &alt), Ok(Some(_)))) { + kernel_shows = true; + } + } + if go.unmatched_switch && left_cfg(&mo) { + diverged.get_or_insert(divergence::SWITCH_RUNON.id); + continue; + } + (mo, go) + } + }; + let entry_callee = |at: u64| mo.calls.iter().any(|r| r.at == at && r.target.is_some_and(|t| env.is_entry(t))); + if let Some(&(at, o)) = mo + .convention + .iter() + .find(|(at, o)| entry_callee(*at) && calls.site(*at).preserved.iter().any(|&(p, s)| *o >= p && *o < p + u64::from(s))) + { + env.keep_clobbers.set(true); + let alt = rerun_machine(None); + env.keep_clobbers.set(false); + if let Some(d) = alt.and_then(|alt| machine_differs(prog, env, run, machine_calls, &compare, &mo, &alt)) + .unwrap_or_else(|h| Some(Verdict::from_halt(&h).label())) { + let reg = Storage::new(&env.register, o & !(u64::from(env.sp.1) - 1), env.sp.1).name(prog); + unknown.get_or_insert(Halt::AbiViolation(format!( + "the callee at {at:#x} changes {reg}, which the calling convention says it preserves; with the change kept, the machine's {d}" + ))); + continue; + } + } + let differs = |mut lines: Vec| { + let at = usize::from(lines.first().is_some_and(|l| l.starts_with("contract"))); + lines.insert(at, input_line(prog, env, run, claim)); + for (site, callee) in &mo.followed { + lines.push(format!("note the machine ran {callee:#x} from {site:#x} itself: kuna has no call there")); + } + if opts.trace { + for (side, recs) in [("machine", &mo.calls), ("kuna ", &go.calls)] { + for c in recs.iter() { + let known = &calls.site(c.at).args; + let args: Vec = c + .args + .iter() + .enumerate() + .map(|(i, a)| if matches!(known.get(i), Some(Some(_))) { format!("{a:#x}") } else { "?".into() }) + .collect(); + lines.push(format!("trace {side} call at {:#x} to {} ({})", c.at, target(c.target), args.join(", "))); + } + } + } + lines + }; + for &(at, o) in &mo.convention { + if call_suspects.len() >= 4 { + break; + } + let reg = Storage::new(&env.register, o & !(u64::from(env.sp.1) - 1), env.sp.1).name(prog); + let s = format!("the callee at {at:#x} changes {reg}, which the calling convention says it preserves"); + if !call_suspects.contains(&s) { + call_suspects.push(s); + } + } + if ptrauth_trap(&mo.events, &go.events) { + diverged.get_or_insert(divergence::PTRAUTH_TRAP.id); + continue; + } + let (graph_calls, graph_events) = if mo.bad_return.is_some() { + (&go.calls[..go.calls.len().min(mo.calls.len())], &go.events[..go.events.len().min(mo.events.len())]) + } else { + (go.calls.as_slice(), go.events.as_slice()) + }; + let mut cc = compare_calls(prog, env, run, &calls, &mo.calls, graph_calls); + let mut rerun_failed = None; + let unchecked = go.call_inputs.len().saturating_sub(opts.call_reruns as usize) + go.unkept_inputs; + for ci in go.call_inputs.iter().take(opts.call_reruns as usize) { + if cc.differs.is_some() || cc.stop { + break; + } + let observe = |with: &machine::WithArgs| -> Result, String> { + let alt = rerun_machine(Some(with)).map_err(|h| format!("the machine could not be rerun with kuna's arguments: {}", h.render()))?; + let callee_difference = callee_differs( + prog, machine_calls, with.call.and_then(|k| mo.calls.get(k)), + with.call.and_then(|k| alt.calls.get(k)), !with.stack_bytes.is_empty(), + ).map_err(str::to_string)?; + match machine_differs(prog, env, run, machine_calls, &compare, &mo, &alt) { + Ok(d) => Ok(d.or(callee_difference)), + Err(_) if callee_difference.is_some() => Ok(callee_difference), + Err(h) => Err(format!("the return could not be compared: {}", h.render())), + } + }; + let difference = match observe(&ci.with) { + Ok(d) => d, + Err(reason) => { + let witness = if ci.omitted_register_bytes.is_empty() { + None + } else { + let mut with = ci.with.clone(); + for (off, b) in &mut with.bytes { + if ci.omitted_register_bytes.contains(off) { + *b = 0; + } + } + observe(&with).ok().flatten() + }; + if witness.is_none() { + rerun_failed.get_or_insert_with(|| format!("{}; {reason}", ci.msg)); + } + witness.map(|d| format!("{d} with zero in the omitted argument bytes")) + } + }; + if let Some(d) = difference { + let l = format!("{}; given kuna's arguments, the machine's {d}", ci.msg); + if ci.locked { + cc.suspects.push(format!("{l}; the callee's declared prototype does not take it")); + } else { + cc.differs = Some(vec![l]); + } + } + } + if cc.differs.is_none() && !cc.stop { + cc.differs = compare_events(prog, &mo.events, graph_events); + if let Some((copy, actual)) = overlap.zip(mo.copy_operands).filter(|_| cc.differs.is_none()) { + cc.differs = compare_writes(env, run, &mo.state.writes(), &go.writes, None) + .map(|d| vec![format!("memory before overlapping copy: {d}")]) + .or_else(|| (actual != copy.operands).then(|| vec![format!( + "overlapping copy at {:#x}: machine {actual}; kuna {}", + copy.checkpoint.at, copy.operands, + )])); + } + } + let canary = cc.suspects.iter().any(|s| s.starts_with("canary: ")); + if canary { + unknown.get_or_insert(Halt::Undefined("a call the model let write the frame changed the stack canary".into())); + continue; + } + let suspect = cc.suspects.iter().any(|s| !s.ends_with(super::observe::NARROWED)); + let argument_doubt = cc.suspects.iter().find(|s| s.ends_with("may not take it")).cloned(); + let narrowing = mo.narrowed && { + env.stub_recovered.set(true); + let alt = rerun_machine(None); + env.stub_recovered.set(false); + !matches!(alt.and_then(|alt| machine_differs(prog, env, run, machine_calls, &compare, &mo, &alt)), Ok(None)) + }; + let doubtful = suspect || mo.guessed || narrowing; + let doubt = |lines: &[String]| if suspect { Halt::Doubtful(lines.join("; ")) } else { Halt::Guessed(lines.join("; ")) }; + let undefined = (go.read_uninitialized && (mo.state.read_uninitialized || mo.state.read_saved)) || smashed(env, &mo.state); + for s in cc.suspects { + if call_suspects.len() < 4 && !call_suspects.contains(&s) { + call_suspects.push(s); + } + } + if let Some(id) = cc.declared { + diverged.get_or_insert(id); + if cc.stop { + continue; + } + } + if let Some(lines) = cc.differs { + if undefined { + unknown.get_or_insert(Halt::Undefined(lines.join("; "))); + continue; + } + if doubtful { + unknown.get_or_insert(doubt(&lines)); + continue; + } + return finish(Verdict::Differs { run, of: opts.runs }, differs(lines), call_suspects); + } + if let Some(msg) = rerun_failed { + unknown.get_or_insert(Halt::CalleeReplay(msg)); + continue; + } + if let Some(halt) = mo.bad_return { + unknown.get_or_insert(halt); + unsupported_runs += 1; + if unsupported_runs >= UNSUPPORTED_RUNS { + break; + } + continue; + } + if let Some(gap) = crate::compare::observe::event_gap(prog, &mo.events, &go.events) { + unknown.get_or_insert(Halt::Unsupported(gap)); + continue; + } + if overlap.is_some() { + match argument_doubt.clone() { + Some(s) => { + unknown.get_or_insert(Halt::Doubtful(s)); + } + None if unchecked > 0 => { + unknown.get_or_insert_with(|| Halt::CallReruns(format!("{unchecked} unchecked call argument comparisons before the overlapping copy"))); + } + None => { + diverged.get_or_insert(divergence::COPY_OVERLAP.id); + } + } + continue; + } + if mo.noreturn != go.noreturn && (doubtful || undefined) { + unknown.get_or_insert(doubt(&["one side returns".to_string()])); + continue; + } + if mo.noreturn != go.noreturn { + let which = if mo.noreturn { "the machine stops in a no-return call, kuna returns" } else { "kuna stops in a no-return call, the machine returns" }; + return finish(Verdict::Differs { run, of: opts.runs }, differs(vec![which.to_string()]), Vec::new()); + } + if mo.noreturn && mo.unverified_noreturn { + unverified_runs += 1; + continue; + } + if let Some(s) = argument_doubt { + unknown.get_or_insert(Halt::Doubtful(s)); + continue; + } + let mut ms = mo.state; + let outcome = if mo.noreturn { Ok(Outcome::Same) } else { compare.run(&mut ms, go.ret) }; + let outcome = match outcome { + Ok(o @ (Outcome::Same | Outcome::Declared(_))) => match compare_writes(env, run, &ms.writes(), &go.writes, None) { + Some(d) => Ok(Outcome::Differs(vec![format!("memory at exit: {d}")])), + None => Ok(o), + }, + other => other, + }; + match outcome { + Err(h) => { + unknown.get_or_insert(h); + continue; + } + Ok(Outcome::Declared(id)) => { + diverged.get_or_insert(id); + } + Ok(Outcome::Differs(lines)) if undefined => { + unknown.get_or_insert(Halt::Undefined(lines.join("; "))); + continue; + } + Ok(Outcome::Differs(lines)) if doubtful => { + unknown.get_or_insert(doubt(&lines)); + continue; + } + Ok(Outcome::Differs(lines)) => { + return finish(Verdict::Differs { run, of: opts.runs }, differs(lines), call_suspects); + } + Ok(Outcome::Same) => {} + } + if kernel_shows { + diverged.get_or_insert(divergence::SYSCALL_RESULT.id); + } + if let Some(w) = upper.as_mut().filter(|_| !mo.noreturn) { + w.observe(&mut ms); + } + if perturbed_runs < PERTURBED_RUNS && !undefined && !perturb.is_empty() { + perturbed_runs += 1; + let replay: &[Record] = mo.calls.as_slice(); + for u in &perturb { + let d = match graph::run(env, &program, run, opts.budget, &calls, replay, Some(&u.perturb)) { + Ok(gp) => match depends(prog, env, run, &calls, claim, &go, &gp) { + Some(d) => d, + None => continue, + }, + Err(Halt::Trap(t)) => format!("whether it traps ({t})"), + Err(h) => { + let why = format!("with other values in {}, kuna's side ends {}", u.names, Verdict::from_halt(&h).label()); + unknown.get_or_insert(Halt::Undefined(why)); + continue; + } + }; + if u.shared { + let with = if u.entry.is_empty() { + machine::WithArgs { call: None, bytes: Vec::new(), stack_bytes: Vec::new(), kill_salt: 0x5a5a_5a5a } + } else { + machine::WithArgs { call: None, bytes: entry_bytes(env, u, run), stack_bytes: Vec::new(), kill_salt: 0 } + }; + let base = base_machine(run, opts.budget); + let alt = machine::run(env, run, entry, opts.budget, machine_calls, Some(&with)); + match (base, alt) { + (Ok(b), Ok(a)) if matches!(machine_differs(prog, env, run, machine_calls, &compare, &b, &a), Ok(None)) => {} + _ => continue, + } + } + let lines = vec![format!("kuna's result depends on {}, which its C never assigns: {d}", u.names)]; + return finish(Verdict::Differs { run, of: opts.runs }, differs(lines), call_suspects); + } + } + if unchecked > 0 { + unrerun_runs += 1; + continue; + } + agreed += 1; + } + let mut suspects = abi::unclaimed_inputs(prog, env, fd, claim); + suspects.extend(call_suspects); + if agreed >= opts.runs { + if let Some(w) = upper { + suspects.extend(w.suspects(prog)); + } + } + let verdict = match (unknown, diverged, trapped) { + (Some(h), _, _) => Verdict::from_halt(&h), + (None, None, None) if agreed == 0 && both_budget_runs > 0 => Verdict::from_halt(&Halt::Budget), + (None, None, None) if agreed == 0 && unverified_runs > 0 => Verdict::Unknown( + "UNKNOWN(noreturn-unverified: every run ended at a call only kuna says does not return)".to_string(), + ), + (None, Some(d), _) => Verdict::Diverges(d), + (None, None, Some(t)) if agreed == 0 => Verdict::from_halt(&Halt::Trap(t)), + (None, None, None) if agreed == 0 && unrerun_runs > 0 => Verdict::Unknown(format!( + "UNKNOWN(call-reruns: every run had more than {} calls whose callee reads an argument kuna passes otherwise)", + opts.call_reruns + )), + (None, None, _) => Verdict::Agrees(agreed), + }; + let mut lines = match contract { + Some(c) if matches!(verdict, Verdict::Agrees(_)) => vec![format!("contract {} ({})", c.declaration, c.source)], + _ => Vec::new(), + }; + if unverified_runs > 0 && matches!(verdict, Verdict::Agrees(_)) { + lines.push(format!( + "note {unverified_runs} runs ended at a call only kuna says does not return, with no name, layout or run to show it; they are not counted" + )); + } + if unrerun_runs > 0 && matches!(verdict, Verdict::Agrees(_)) { + lines.push(format!( + "note {unrerun_runs} runs had more than {} calls whose callee reads an argument kuna passes otherwise; the machine was not rerun for the rest, so they are not counted", + opts.call_reruns + )); + } + if both_budget_runs > 0 && matches!(verdict, Verdict::Agrees(_)) { + lines.push(format!( + "note {both_budget_runs} runs ran past the op budget on both sides; they are not compared" + )); + } + if trapped_runs > 0 && matches!(verdict, Verdict::Agrees(_)) { + lines.push(format!( + "note {trapped_runs} runs trapped on both sides or stored into read-only memory; C leaves them undefined, so they are not compared" + )); + } + finish(verdict, lines, suspects) +} diff --git a/decompiler/crates/kuna-verify/src/compare/mod.rs b/decompiler/crates/kuna-verify/src/compare/mod.rs new file mode 100644 index 0000000000..1dcda4aee6 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/compare/mod.rs @@ -0,0 +1,6 @@ +//! The comparison of the two sides' runs and the verdict (`check`). + +pub mod check; +pub mod observe; +mod returns; +pub mod setup; diff --git a/decompiler/crates/kuna-verify/src/compare/observe.rs b/decompiler/crates/kuna-verify/src/compare/observe.rs new file mode 100644 index 0000000000..eb09119c0a --- /dev/null +++ b/decompiler/crates/kuna-verify/src/compare/observe.rs @@ -0,0 +1,475 @@ +//! What the two sides did, compared: calls, memory, system calls and traps, +//! and the reruns that check whether a difference shows on the machine. + +//! Tier C: run both sides of one function and compare what they do. +//! +//! A run compares, in order: each call (its target, kuna's arguments, and the +//! memory the callee can read), whether the function returns at all, the return +//! value, and the memory left outside the stack. The return value is compared +//! under the physical ABI (the bytes kuna's claimed return occupies) and, when a +//! typed contract is given, at the contract's width with kuna's value converted +//! to the contract type by C's rules. + +use std::collections::HashMap; +use std::rc::Rc; + +use kuna_base::space::spacetype; +use kuna_console::engine::ConsoleProgram; + +use crate::abi::{self}; +use crate::divergence::{self}; +use crate::calls::{Calls, Record, UserEvent}; +use crate::state::{Env, State, Writes}; +use crate::storage::{hex, Storage}; +use crate::value::{mask, Halt}; +use crate::{graph, machine}; +use super::returns::{Compare, ReturnValue}; + +/// The first byte the two sides left different, of the memory either wrote. +/// `read`: the frame bytes a callee run for real read, when only those count. +pub(crate) fn compare_writes(env: &Env, run: u32, machine: &Writes, kuna: &Writes, read: Option<&crate::state::FrameReads>) -> Option { + let manage = env.prog.arch().manage(); + let ram = env.ram.get_index(); + let compared = |sp: i32, off: u64| { + let both = |o: &(u64, u64)| off >= o.0 && off < o.1 && kuna.objects.contains(o); + let past = |o: &(u64, u64)| off >= o.1 && off < env.sp0 && kuna.objects.contains(o); + let reached = machine.objects.iter().any(both) || read.is_some_and(|r| r.contains(&off) && machine.objects.iter().any(past)); + !(sp == ram && env.in_stack(off, 1)) + || (reached && read.is_none_or(|r| r.contains(&off)) && !machine.skip.contains(&off) && !kuna.skip.contains(&off)) + }; + let mut first = None; + let mut differ = 0usize; + let mut ms = machine.bytes.iter().peekable(); + let mut ks = kuna.bytes.iter().peekable(); + loop { + let (key, m, k) = match (ms.peek(), ks.peek()) { + (None, None) => break, + (Some(&(&mk, &mv)), Some(&(&kk, &kv))) if mk == kk => { + ms.next(); + ks.next(); + (mk, Some(mv), Some(kv)) + } + (Some(&(&mk, &mv)), Some(&(&kk, _))) if mk < kk => { + ms.next(); + (mk, Some(mv), None) + } + (Some(&(&mk, &mv)), None) => { + ms.next(); + (mk, Some(mv), None) + } + (_, Some(&(&kk, &kv))) => { + ks.next(); + (kk, None, Some(kv)) + } + }; + let (sp, off) = key; + if !compared(sp, off) { + continue; + } + let Some(space) = manage.get_space(sp) else { continue }; + let m = m.unwrap_or_else(|| env.base_byte(run, machine.epoch, &machine.escaped, space, off)); + let k = k.unwrap_or_else(|| env.base_byte(run, kuna.epoch, &kuna.escaped, space, off)); + if m != k { + differ += 1; + first.get_or_insert(format!("{}:{off:#x}: machine 0x{m:02x}, kuna 0x{k:02x}", space.get_name())); + } + } + first.map(|f| if differ > 1 { format!("{f} ({differ} bytes differ)") } else { f }) +} + +/// A computed call target as an address in the code space: wrapped to its +/// size, and without the ARM or MIPS instruction-set bit. +pub(crate) fn code_target(env: &Env, t: Option) -> Option { + let id = &env.prog.arch().archid; + let isa_bit = id.starts_with("ARM") || id.starts_with("MIPS"); + t.map(|t| env.code.wrap_offset(t) & if isa_bit { !1 } else { !0 }) +} + +pub(crate) fn target(t: Option) -> String { + t.map_or_else(|| "?".to_string(), |t| format!("{t:#x}")) +} + +/// Stack-protector failure handlers, without leading underscores. A call to one +/// on the machine side only means a call the model let rewrite the frame hit +/// the canary. +pub(crate) const STACK_PROTECTOR: &[&str] = &["stack_chk_fail", "security_check_cookie", "report_gsfailure"]; + +/// How the two sides' calls compare: the first difference, a declared +/// divergence among them, whether it ends what the run can compare, and the +/// arguments a recovered callee prototype may have wrong. +pub(crate) struct CallCompare { + pub(crate) differs: Option>, + pub(crate) declared: Option<&'static str>, + /// The declared divergence changes what follows it (a check the machine + /// fails and panics in), so the rest of the run is not compared. + pub(crate) stop: bool, + pub(crate) suspects: Vec, +} + +/// Compare the calls in order. A call kuna synthesized, and a Go write +/// barrier the machine calls where kuna stores directly, are declared: what +/// either side does after one is not comparable (a stub stands where the +/// other side ran code), so the calls before the first are compared and the +/// rest of the run is not. +pub(crate) fn compare_calls(prog: &ConsoleProgram, env: &Env, run: u32, calls: &Calls, m: &[Record], g: &[Record]) -> CallCompare { + let mut suspects = Vec::new(); + let synthesized = g.iter().position(|c| c.at == 0 || (!c.indirect && c.target.is_none())); + let barrier = m.iter().position(|c| { + c.target.and_then(|t| prog.function_named_at(t)).is_some_and(|n| n.starts_with("runtime.gcWriteBarrier")) + && !g.iter().any(|k| k.at == c.at) + }); + let declared = match (synthesized, barrier) { + (Some(s), Some(b)) if b < s => Some((b, divergence::GO_WRITE_BARRIER.id)), + (Some(s), _) => Some((s, divergence::SYNTHESIZED_CALL.id)), + (None, Some(b)) => Some((b, divergence::GO_WRITE_BARRIER.id)), + (None, None) => None, + }; + let cut = declared.map_or(usize::MAX, |(k, _)| k); + let (m, g) = (&m[..cut.min(m.len())], &g[..cut.min(g.len())]); + let declared = declared.map(|(_, id)| id); + let stop = declared.is_some(); + let differs = |lines: Vec, suspects: Vec| CallCompare { differs: Some(lines), declared: None, stop: false, suspects }; + for k in 0..m.len().max(g.len()) { + let n = k + 1; + let (mc, gc) = match (m.get(k), g.get(k)) { + (Some(mc), Some(gc)) => (mc, gc), + (Some(mc), None) => { + let name = mc.target.and_then(|t| prog.function_named_at(t)).unwrap_or_default(); + if kuna_decomp::kuna_gobounds::is_go_check_name(&name) || kuna_decomp::kuna_securitycheck::is_security_check_name(&name) { + return CallCompare { differs: None, declared: Some(divergence::PANIC_CHECK.id), stop: true, suspects }; + } + let l = format!("call {n} at {:#x} to {}: the machine makes it, kuna does not", mc.at, target(mc.target)); + if STACK_PROTECTOR.contains(&name.trim_start_matches('_')) { + return CallCompare { differs: None, declared, stop, suspects: vec![format!("canary: {l}")] }; + } + return differs(vec![l], suspects); + } + (None, Some(gc)) => { + let l = format!("call {n} at {:#x} to {}: kuna makes it, the machine does not", gc.at, target(gc.target)); + return differs(vec![l], suspects); + } + (None, None) => break, + }; + if mc.at != gc.at { + return differs(vec![format!("call {n}: the machine calls from {:#x}, kuna from {:#x}", mc.at, gc.at)], suspects); + } + let (mr, kr) = (code_target(env, mc.target), code_target(env, gc.target)); + let (mt, kt) = (mr.map(|t| machine::transparent_target(env, t)), kr.map(|t| machine::transparent_target(env, t))); + let direct = !mc.indirect && !gc.indirect && !calls.site(gc.at).resolved; + let code_or_outside = |t: u64| env.is_code(t) || !env.code_mapped(t); + let both = |a: Option, b: Option| a.zip(b).is_some_and(|(m, k)| code_or_outside(m) && code_or_outside(k)); + let comparable = both(mr, kr) || both(mt, kt); + let resolved = calls.site(gc.at).resolved; + let both_code = mt.zip(kt).is_some_and(|(m, k)| env.is_code(m) && env.is_code(k)); + let mixed = mc.indirect != gc.indirect && !resolved && both_code; + let compared = (mc.indirect && gc.indirect) || (direct && comparable) || mixed; + let same = mr == kr || (mt == kt && mt.is_some_and(|t| env.is_code(t))); + if compared && !same { + let l = format!("call {n} at {:#x}: the machine calls {}, kuna calls {}", gc.at, target(mc.target), target(gc.target)); + return differs(vec![l], suspects); + } + let site = calls.site(gc.at); + if let Some(stub) = site.plt_stub.filter(|&s| !mc.indirect && !reaches_stub(env, mc.target, s)) { + let l = format!("call {n} at {:#x}: the machine calls {}, kuna binds the call past the PLT stub at {stub:#x}", gc.at, target(mc.target)); + return differs(vec![l], suspects); + } + if gc.args.len() < site.params { + let l = format!( + "call {n} to {}: kuna passes {} arguments, and the prototype it gives the callee takes {}", + target(gc.target), + gc.args.len(), + site.params + ); + return differs(vec![l], suspects); + } + if !site.locked && mc.live_in.is_none() { + for (i, st) in site.input_storage.iter().enumerate() { + let st = site.args.get(i).and_then(Option::as_ref).map(|a| &a.storage).or(st.as_ref()); + let Some(l) = st.and_then(|st| narrowed(prog, mc, i, st)) else { continue }; + let s = format!("call {n} to {}, argument {}: {l}", target(gc.target), i + 1); + if !suspects.contains(&s) { + suspects.push(s); + } + } + } + for (i, ((ma, ka), arg)) in mc.args.iter().zip(&gc.args).zip(&site.args).enumerate() { + let Some(st) = arg.as_ref().map(|a| &a.storage) else { continue }; + if ma & mask(st.size) == ka & mask(st.size) { + continue; + } + if same && site.stack_input(i).is_some_and(|s| { + s.off == st.off && s.size == st.size && s.space.get_index() == st.space.get_index() + && mc.stack_in.as_ref().is_some_and(|reads| reads.contains(s.off, s.size)) + }) { + continue; + } + let l = format!( + "call {n} to {}, argument {} ({}): machine {}, kuna {}", + target(gc.target), + i + 1, + st.name(prog), + hex(*ma & mask(st.size), st.size), + hex(*ka & mask(st.size), st.size) + ); + if site.locked { + return differs(vec![l], suspects); + } + let s = format!("{l}; the callee's recovered prototype may not take it"); + if !suspects.contains(&s) { + suspects.push(s); + } + } + if let Some(d) = compare_writes(env, run, &mc.writes, &gc.writes, mc.frame_reads.as_ref()) { + return differs(vec![format!("memory before call {n} to {}: {d}", target(gc.target))], suspects); + } + } + CallCompare { differs: None, declared, stop, suspects } +} + +/// When kuna passes argument `i` in part of a register and the machine's +/// register holds more than that part extended: the bytes kuna's C drops, which +/// a stub callee never reads, so the comparison never sees them. +fn narrowed(prog: &ConsoleProgram, mc: &Record, i: usize, st: &Storage) -> Option { + let (r, v) = mc.whole.get(i)?.as_ref()?; + if !r.covers(st) { + return None; + } + let be = st.space.is_big_endian(); + let low = if be { r.off + u64::from(r.size) == st.off + u64::from(st.size) } else { r.off == st.off }; + if !low || r.size > 16 { + return None; + } + let part = v & mask(st.size); + let high = (v & mask(r.size)) >> (8 * st.size); + let ones = mask(r.size - st.size); + let negative = part >> (8 * st.size - 1) & 1 == 1; + if high == 0 || (negative && high == ones) { + return None; + } + Some(format!("kuna passes {} bytes of {}, {NARROWED}", st.size, r.name(prog))) +} + +/// How a narrowed argument's suspect ends. It is a lead, not a doubt: a run +/// that differs after it still differs, since kuna's cut can be the cause. +pub(crate) const NARROWED: &str = "whose other bytes the machine sets"; + +/// Compare the recorded effects of two completed runs of the same callee. +pub(super) fn callee_differs( + prog: &ConsoleProgram, calls: &Calls, a: Option<&Record>, b: Option<&Record>, stack: bool, +) -> Result, &'static str> { + let (Some(a), Some(b)) = (a, b) else { return Err("the callee was not reached in both runs") }; + if a.at != b.at || a.target != b.target { + return Err("the replay reached a different callee"); + } + let (Some(ea), Some(eb)) = (&a.effect, &b.effect) else { return Err("the callee did not complete a concrete replay") }; + if stack && (a.stack_in.is_none() || b.stack_in.is_none()) { + return Err("the callee did not complete a concrete stack-argument replay"); + } + let site = calls.site(a.at); + if let Some(out) = site.output.as_ref().filter(|o| o.space.get_type() == spacetype::IPTR_PROCESSOR) { + let value = ReturnValue::new(prog, out, site.output_float); + let st = value.physical(); + let within = |r: &&(u64, u8)| r.0 >= st.off && r.0 < st.off + u64::from(st.size); + let (ra, rb): (Vec<_>, Vec<_>) = (ea.regs.iter().filter(within).collect(), eb.regs.iter().filter(within).collect()); + if ra != rb { + let get = |regs: &[&(u64, u8)]| -> Option { + if st.size > 16 { + return None; + } + let mut raw = 0u128; + for pos in 0..u64::from(st.size) { + let (_, b) = regs.iter().find(|r| r.0 == st.off + pos)?; + let i = if st.space.is_big_endian() { u64::from(st.size) - pos - 1 } else { pos }; + raw |= u128::from(*b) << (8 * i); + } + Some(value.normalize(raw)) + }; + if !get(&ra).zip(get(&rb)).is_some_and(|(a, b)| value.agrees(a, b)) { + return Ok(Some(format!("callee returns another {}", out.name(prog)))); + } + } + } + let writes = |e: &crate::state::Effect| -> Vec<(i32, u64, u8)> { + e.events.iter().filter_map(|ev| if let crate::state::Event::Write(s, o, b) = ev { Some((*s, *o, *b)) } else { None }).collect() + }; + Ok((writes(ea) != writes(eb)).then(|| "callee writes other memory".to_string())) +} + +/// The machine stopped in a pointer-authentication trap kuna does not reach. +pub(crate) fn ptrauth_trap(m: &[UserEvent], g: &[UserEvent]) -> bool { + m.last().is_some_and(|e| { + e.name.as_bytes() == kuna_decomp::kuna_ptrauthtrap::BREAKPOINT_USEROP + && e.ins.first().is_some_and(|&i| kuna_decomp::kuna_ptrauthtrap::is_ptrauth_trap_immediate(i as u64)) + && !g.iter().any(|k| k.at == e.at) + }) +} + +/// The machine's call goes to `stub`, directly or through thunks. +pub(crate) fn reaches_stub(env: &Env, machine: Option, stub: u64) -> bool { + machine == Some(stub) + || code_target(env, machine).is_some_and(|m| m == stub || machine::transparent_target(env, m) == machine::transparent_target(env, stub)) +} + +/// The first system call or trap the two sides reach differently. +pub(crate) fn compare_events(prog: &ConsoleProgram, m: &[UserEvent], g: &[UserEvent]) -> Option> { + let regs = if g.iter().any(|e| crate::calls::SYSTEM_USEROPS.contains(&e.name.as_str())) { + crate::calls::SyscallAbi::of(prog).inputs + } else { + Vec::new() + }; + let show = |e: Option<&UserEvent>| { + e.map_or_else( + || "none".to_string(), + |e| { + let ins: Vec = e.ins.iter().map(|v| format!("{v:#x}")).collect(); + format!("{} at {:#x} ({})", e.name, e.at, ins.join(", ")) + }, + ) + }; + let n = (0..m.len().max(g.len())).find(|&k| match (m.get(k), g.get(k)) { + (Some(a), Some(b)) => !same_event(a, b, ®s), + _ => true, + })?; + Some(vec![format!("user op {}: machine {}, kuna {}", n + 1, show(m.get(n)), show(g.get(n)))]) +} + +/// How kuna's system-call inputs match the machine's registers. +#[derive(PartialEq)] +enum EventMatch { + Same, + /// The values match registers in order, but not the first ones: kuna's + /// IR skips a register, and the order its C passes them in does not say + /// which. + Gap, + Differs, +} + +/// Same op at the same place with the same inputs. Past the machine op's own +/// inputs kuna attaches the registers a system call reads: the number register +/// and then some of the argument registers in order, each matched against +/// what the machine's register file holds in it. +pub(crate) fn same_event(m: &UserEvent, g: &UserEvent, regs: &[Storage]) -> bool { + match_event(m, g, regs) != EventMatch::Differs +} + +fn match_event(m: &UserEvent, g: &UserEvent, regs: &[Storage]) -> EventMatch { + if m.at != g.at || m.name != g.name || g.ins.len() < m.ins.len() || m.ins[..] != g.ins[..m.ins.len()] { + return EventMatch::Differs; + } + let extra = &g.ins[m.ins.len()..]; + if extra.is_empty() || regs.is_empty() || !crate::calls::SYSTEM_USEROPS.contains(&m.name.as_str()) { + return if extra.is_empty() || !crate::calls::SYSTEM_USEROPS.contains(&m.name.as_str()) { EventMatch::Same } else { EventMatch::Differs }; + } + let file: HashMap = m.file.iter().copied().collect(); + let held = |st: &Storage| -> Option { + let big = st.space.is_big_endian(); + let mut v = 0u128; + for i in 0..st.size as u64 { + let b = *file.get(&(st.off + i))? as u128; + let shift = if big { (st.size as u64 - 1 - i) * 8 } else { i * 8 }; + v |= b << shift; + } + Some(v) + }; + let fits = |v: u128, st: &Storage| held(st).is_some_and(|h| h == v & crate::value::mask(st.size)); + if extra.len() > regs.len() || !fits(extra[0], ®s[0]) { + return EventMatch::Differs; + } + if extra[1..].iter().zip(®s[1..]).all(|(&v, st)| fits(v, st)) { + return EventMatch::Same; + } + let mut left = regs[1..].iter(); + if extra[1..].iter().all(|&v| left.any(|st| fits(v, st))) { + EventMatch::Gap + } else { + EventMatch::Differs + } +} + +/// The first system call whose inputs kuna takes from the registers with a +/// gap: its IR reads them, but its C's argument order does not say which. +pub(crate) fn event_gap(prog: &ConsoleProgram, m: &[UserEvent], g: &[UserEvent]) -> Option { + if !g.iter().any(|e| crate::calls::SYSTEM_USEROPS.contains(&e.name.as_str())) { + return None; + } + let regs = crate::calls::SyscallAbi::of(prog).inputs; + m.iter().zip(g).find(|(a, b)| match_event(a, b, ®s) == EventMatch::Gap).map(|(a, b)| { + format!( + "system call at {:#x}: kuna passes {} of its argument registers, not the first ones in order, so its C does not say which it reads", + a.at, + b.ins.len().saturating_sub(a.ins.len() + 1) + ) + }) +} + +/// The first observable two machine runs differ in. +pub(super) fn machine_differs( + prog: &ConsoleProgram, + env: &Env, + run: u32, + calls: &Calls, + compare: &Compare, + a: &machine::Outcome, + b: &machine::Outcome, +) -> Result, Halt> { + if a.noreturn != b.noreturn { + return Ok(Some("run differs in whether it returns".into())); + } + if a.bad_return.is_some() != b.bad_return.is_some() { + return Ok(Some("run differs in whether it reaches the return address".into())); + } + if !a.noreturn && a.copy_operands.is_none() && b.copy_operands.is_none() && a.bad_return.is_none() { + if let Some(d) = compare.machine_return_diff(&mut a.state.clone(), &mut b.state.clone())? { + return Ok(Some(d)); + } + } + if let Some(l) = compare_calls(prog, env, run, calls, &a.calls, &b.calls).differs { + return Ok(Some(format!("calls differ: {}", l.join("; ")))); + } + if let Some(l) = compare_events(prog, &a.events, &b.events) { + return Ok(Some(format!("system calls differ: {}", l.join("; ")))); + } + if a.copy_operands != b.copy_operands { + return Ok(Some("overlapping copy operands differ".to_string())); + } + Ok(compare_writes(env, run, &a.state.writes(), &b.state.writes(), None).map(|d| format!("memory at exit differs: {d}"))) +} + +/// The first observable two runs of kuna's side differ in. +pub(crate) fn depends( + prog: &ConsoleProgram, + env: &Env, + run: u32, + calls: &Calls, + claim: &abi::Claim, + a: &graph::Outcome, + b: &graph::Outcome, +) -> Option { + if a.noreturn != b.noreturn { + return Some("whether it returns".into()); + } + if let (Some(out), Some(x), Some(y)) = (&claim.storage, a.ret, b.ret) { + let value = ReturnValue::new(prog, out, claim.float); + if !value.agrees(x & mask(out.size), y & mask(out.size)) { + return Some(format!("its return {} or {}", hex(x, out.size), hex(y, out.size))); + } + } + if let Some(l) = compare_calls(prog, env, run, calls, &a.calls, &b.calls).differs { + return Some(l.join("; ")); + } + if let Some(l) = compare_events(prog, &a.events, &b.events) { + return Some(format!("its system calls: {}", l.join("; "))); + } + compare_writes(env, run, &a.writes, &b.writes, None).map(|d| format!("memory at exit {d}")) +} + +/// Whether the machine overwrote the return address the function started +/// with: past the frame C defines, as an overrun of a local does. +pub(crate) fn smashed(env: &Env, ms: &State) -> bool { + let Some(ret) = env.ret_addr else { return false }; + env.tracked + .iter() + .filter(|&&(sp, _, _, v)| v == ret && sp == env.ram.get_index()) + .filter_map(|&(sp, off, size, _)| env.prog.arch().manage().get_space(sp).map(|s| (Rc::clone(s), off, size))) + .any(|(s, off, size)| ms.wrote(&s, off, size)) +} diff --git a/decompiler/crates/kuna-verify/src/compare/returns.rs b/decompiler/crates/kuna-verify/src/compare/returns.rs new file mode 100644 index 0000000000..6a094eb53d --- /dev/null +++ b/decompiler/crates/kuna-verify/src/compare/returns.rs @@ -0,0 +1,179 @@ +//! Return observations shared by the main check and replay comparisons. + +use kuna_console::engine::ConsoleProgram; + +use crate::abi::{self, Claim}; +use crate::contract::{CKind, Contract}; +use crate::divergence::{self, ReturnMismatch}; +use crate::state::State; +use crate::storage::{hex, Storage}; +use crate::value::{mask, Halt}; + +/// The whole of x87's 80-bit `ST0` when `out` is it, where a `float` or +/// `double` return lives in the 80-bit format: the machine's value is rounded +/// to the claimed size before it is compared. +fn x87_register(prog: &ConsoleProgram, out: &Storage) -> Option { + if !(out.size == 4 || out.size == 8) || !prog.arch().archid.starts_with("x86") { + return None; + } + let [piece] = out.pieces(prog).try_into().ok()?; + let st0 = prog.arch().translate().get_register_data("ST0").ok()?; + let space = st0.space.as_ref()?; + (piece.space.get_index() == space.get_index() && piece.off == st0.offset && st0.size == 10) + .then(|| Storage::new(space, st0.offset, st0.size)) +} + +pub(super) struct ReturnValue<'a> { + logical: &'a Storage, + x87: Option, + float: bool, +} + +impl<'a> ReturnValue<'a> { + pub(super) fn new(prog: &ConsoleProgram, logical: &'a Storage, float: bool) -> Self { + Self { logical, x87: float.then(|| x87_register(prog, logical)).flatten(), float } + } + + pub(super) fn physical(&self) -> &Storage { + self.x87.as_ref().unwrap_or(self.logical) + } + + pub(super) fn normalize(&self, raw: u128) -> u128 { + if self.x87.is_some() { crate::x87::to_ieee(raw, self.logical.size) } else { raw & mask(self.logical.size) } + } + + pub(super) fn agrees(&self, a: u128, b: u128) -> bool { + a == b || self.float && divergence::nan_quieting(self.logical.size, a, b) + } + + fn read(&self, machine: &mut State) -> Result { + let s = self.physical(); + machine.read_storage(&s.space, s.off, s.size).map(|v| self.normalize(v)) + } +} + +/// One run's comparison: the report lines when the two sides differ. +pub(super) struct Compare<'a> { + pub(super) prog: &'a ConsoleProgram, + pub(super) claim: &'a Claim, + pub(super) contract: Option<(&'a Contract, &'a Storage)>, +} + +pub(super) enum Outcome { + Same, + Differs(Vec), + Declared(&'static str), +} + +impl Compare<'_> { + pub(super) fn run(&self, ms: &mut State, ret: Option) -> Result { + let mut lines = Vec::new(); + if let Some(out) = &self.claim.storage { + let k = ret.ok_or_else(|| Halt::Harness("RETURN without the prototype's value".into()))?; + let value = ReturnValue::new(self.prog, out, self.claim.float); + let mv = value.read(ms)?; + let k = k & mask(out.size); + if mv != k { + if value.agrees(mv, k) { + return Ok(Outcome::Declared(divergence::NAN_QUIETING.id)); + } + return Ok(Outcome::Differs(vec![ + format!("machine {} = {}", out.name(self.prog), hex(mv, out.size)), + format!("kuna {} = {}", self.claim.text, hex(k, out.size)), + ])); + } + } + let Some((c, cs)) = self.contract else { return Ok(Outcome::Same) }; + let mv = ms.read_storage(&cs.space, cs.off, cs.size)?; + let kuna = match (&self.claim.storage, ret) { + (Some(out), Some(k)) => { + let value = if c.ret.kind == CKind::Boolean { + let value = k & mask(out.size); + let nonzero = if self.claim.float { + match out.size { + 4 => f32::from_bits(value as u32) != 0.0, + 8 => f64::from_bits(value as u64) != 0.0, + _ => return Err(Halt::Unsupported(format!("{}-byte float conversion to _Bool", out.size))), + } + } else { + value != 0 + }; + u128::from(nonzero) + } else { + abi::convert(k, out.size, self.claim.signed, cs.size) + }; + Some((out.size, value)) + } + _ => None, + }; + if kuna.is_some_and(|(_, kv)| kv == mv) { + return Ok(Outcome::Same); + } + if let Some((ks, kv)) = kuna { + let m = ReturnMismatch { arch: &self.prog.arch().archid, contract_size: cs.size, kuna_size: ks, machine: mv, kuna: kv }; + if let Some(d) = divergence::find(&m) { + return Ok(Outcome::Declared(d.id)); + } + } + lines.push(format!("contract {} ({})", c.declaration, c.source)); + lines.push(format!("machine {} = {}", cs.name(self.prog), hex(mv, cs.size))); + match (&self.claim.storage, ret, kuna) { + (Some(out), Some(k), Some((_, kv))) => lines.push(format!( + "kuna {} = {}; as {} {}", + self.claim.text, + hex(k, out.size), + c.ret.spelling, + hex(kv, cs.size) + )), + _ => lines.push(format!("kuna {} returns no value", self.claim.text)), + } + Ok(Outcome::Differs(lines)) + } + + pub(super) fn machine_return_diff(&self, a: &mut State, b: &mut State) -> Result, Halt> { + let abi = self.claim.storage.as_ref().map(|out| ReturnValue::new(self.prog, out, self.claim.float)); + let contract = self.contract.map(|(_, out)| ReturnValue::new(self.prog, out, false)); + for value in abi.into_iter().chain(contract) { + let (x, y) = (value.read(a)?, value.read(b)?); + if !value.agrees(x, y) { + let size = value.logical.size; + return Ok(Some(format!("return is {} instead of {}", hex(y, size), hex(x, size)))); + } + } + Ok(None) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn x87_return_uses_the_claimed_precision_on_replay() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.."); + let specs = vec![root.join("specs").to_string_lossy().into_owned()]; + let path = root.join("tests/datatests/retstruct.xml"); + let (prog, _, _load_env) = crate::session::load_datatest(&path.to_string_lossy(), &specs).unwrap(); + let env = crate::state::Env::new(&prog, 0).unwrap(); + let st0 = prog.arch().translate().get_register_data("ST0").unwrap(); + let claim = Claim { + storage: Some(Storage::new(st0.space.as_ref().unwrap(), st0.offset, 4)), + signed: false, + float: true, + text: "float f()".into(), + params: Vec::new(), + }; + let compare = Compare { prog: &prog, claim: &claim, contract: None }; + let mut a = State::new(&env, 0); + let mut b = State::new(&env, 0); + let space = st0.space.as_ref().unwrap(); + let one = (0x3fffu128 << 64) | (1 << 63); + a.write_storage(space, st0.offset, 10, one).unwrap(); + b.write_storage(space, st0.offset, 10, one + 1).unwrap(); + assert!(matches!(compare.run(&mut a, Some(u128::from(1.0f32.to_bits()))), Ok(Outcome::Same))); + assert_eq!(compare.machine_return_diff(&mut a, &mut b).unwrap(), None); + b.write_storage(space, st0.offset, 10, one + (1u128 << 64)).unwrap(); + assert_eq!(compare.machine_return_diff(&mut a, &mut b).unwrap().as_deref(), + Some("return is 0x40000000 instead of 0x3f800000")); + } +} diff --git a/decompiler/crates/kuna-verify/src/compare/setup.rs b/decompiler/crates/kuna-verify/src/compare/setup.rs new file mode 100644 index 0000000000..f38a541219 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/compare/setup.rs @@ -0,0 +1,225 @@ +//! The run's starting state and what it watches: tracked and boolean inputs, +//! storage kuna never assigns, veneer registers, the input line. + +//! Tier C: run both sides of one function and compare what they do. +//! +//! A run compares, in order: each call (its target, kuna's arguments, and the +//! memory the callee can read), whether the function returns at all, the return +//! value, and the memory left outside the stack. The return value is compared +//! under the physical ABI (the bytes kuna's claimed return occupies) and, when a +//! typed contract is given, at the contract's width with kuna's value converted +//! to the contract type by C's rules. + + +use kuna_base::space::spacetype; +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::funcdata::Funcdata; + +use crate::abi::{self, Claim}; +use crate::calls::Calls; +use crate::state::{Env, State}; +use crate::storage::{hex, Storage}; +use crate::value::mask; +use crate::graph; + +/// The parameters kuna's prototype types `bool`, in a register or in the +/// caller's stack. +pub(crate) fn booleans(fd: &Funcdata, env: &Env) -> Vec<(i32, u64, u32)> { + let proto = fd.get_func_proto(); + (0..proto.num_params()) + .filter_map(|i| proto.get_param(i)) + .filter(|p| p.get_type().is_some_and(|t| t.get_metatype() == kuna_decomp::dtype::type_metatype::TYPE_BOOL)) + .filter_map(|p| Storage::at(&p.get_address(), p.get_size() as u32)) + .filter_map(|st| { + if st.space.get_index() == env.register.get_index() { + Some((st.space.get_index(), st.off, st.size)) + } else if st.space.get_type() == spacetype::IPTR_SPACEBASE { + Some((env.ram.get_index(), env.ram.wrap_offset(env.sp0.wrapping_add(st.off)), st.size)) + } else { + None + } + }) + .collect() +} + +/// The storage whose value is known at the function's entry: what the context +/// tracks, what the loader seeds (a PowerPC TOC from a descriptor, MIPS t9), +/// x86's segment bases, and the return address, which gets an address nothing maps so a RETURN to +/// it is told apart from a branch. +pub(crate) fn tracked(prog: &ConsoleProgram, fd: &Funcdata, env: &mut Env) -> Vec<(i32, u64, u32, u64)> { + let entry = fd.get_address(); + let arch = prog.arch(); + let to = |t: &kuna_sleigh::globalcontext::TrackedContext| { + let sp = t.loc.space.as_ref()?; + (t.loc.size <= 8).then(|| (sp.get_index(), t.loc.offset, t.loc.size, t.val)) + }; + let mut out: Vec<(i32, u64, u32, u64)> = arch.with_context_db(|db| db.get_tracked_set(entry).iter().filter_map(to).collect()); + if let Some(set) = arch.loader_entry_tracks.get(entry) { + out.extend(set.iter().filter_map(to)); + } + if let Some((vn, probe)) = &arch.loader_mips_t9 { + if let (Some(sp), Some(v)) = (vn.space.as_ref(), probe(entry)) { + if !out.iter().any(|&(s, o, _, _)| s == sp.get_index() && o == vn.offset) { + out.push((sp.get_index(), vn.offset, vn.size, v)); + } + } + } + let ret = fd + .get_func_proto() + .model() + .effect_list() + .iter() + .find(|e| e.get_type() == kuna_decomp::fspec::effect_type::RETURN_ADDRESS) + .and_then(|e| Storage::at(&e.get_address(), e.get_size() as u32)); + if let Some(st) = ret.filter(|st| st.size <= 8) { + let sentinel = env.ram.wrap_offset(env.sp0.wrapping_add(0x800)); + let at = if st.space.get_type() == spacetype::IPTR_SPACEBASE { + Some((env.ram.get_index(), env.ram.wrap_offset(env.sp0.wrapping_add(st.off)))) + } else { + Some((st.space.get_index(), st.off)) + }; + if let Some((sp, off)) = at { + out.push((sp, off, st.size, sentinel)); + env.ret_addr = Some(sentinel); + if st.space.get_type() == spacetype::IPTR_SPACEBASE { + env.ret_slot = st.size; + } + } + } + let tls = env.ram.wrap_offset(env.sp0 / 2) & !0xfff; + for name in SEGMENT_BASES { + if let Ok(vn) = arch.translate().get_register_data(name) { + if let Some(sp) = vn.space.as_ref().filter(|_| vn.size <= 8) { + if !out.iter().any(|&(s, o, _, _)| s == sp.get_index() && o == vn.offset) { + out.push((sp.get_index(), vn.offset, vn.size, tls)); + } + } + } + } + out +} + +/// x86's segment bases: a thread's TLS or TEB, which is neither the image +/// nor the stack, so the stack-protector guard at `fs:0x28` stays put. +pub(crate) const SEGMENT_BASES: [&str; 2] = ["FS_OFFSET", "GS_OFFSET"]; + +/// What kuna's C never assigns but its IR reads: argument or scratch +/// registers read at entry with no parameter for them, and registers a call +/// kills that are read after it. Registers a caller leaves meaningful values +/// in (segment bases, PIC and frame registers, the stack pointer) are not +/// among them. `None` when there is none, so the second run is skipped. +pub(crate) fn unassigned( + prog: &ConsoleProgram, + env: &Env, + fd: &Funcdata, + claim: &abi::Claim, + program: &crate::program::Program, + calls: &Calls, +) -> Vec { + let tracked: Vec = env + .tracked + .iter() + .filter(|t| t.0 == env.register.get_index()) + .map(|t| Storage::new(&env.register, t.1, t.2)) + .collect(); + let scratch: Vec<(u64, u32)> = calls.input_regs.iter().copied().chain(calls.default.killed.iter().copied()).collect(); + let inputs: Vec = abi::unclaimed_input_storage(prog, env, fd, claim) + .into_iter() + .filter(|s| !tracked.iter().any(|t| t.overlaps(s)) && !env.booleans.iter().any(|b| b.1 == s.off)) + .filter(|s| scratch.iter().any(|&(o, n)| s.off >= o && s.off + u64::from(s.size) <= o + u64::from(n))) + .collect(); + let killed = program.blocks.iter().flat_map(|b| &b.ops).any(|o| matches!(o.kind, crate::program::Kind::Indirect(crate::program::Effect::Killed))); + let salt = env.seed ^ 0x7a1e_5eed; + let mut out = Vec::new(); + if killed { + out.push(Unassigned { + perturb: graph::Perturb { salt, inputs: Vec::new(), killed: Some(true) }, + names: "a call's output register it never connects".to_string(), + entry: Vec::new(), + shared: false, + }); + out.push(Unassigned { + perturb: graph::Perturb { salt, inputs: Vec::new(), killed: Some(false) }, + names: "a register a call kills, read after the call".to_string(), + entry: Vec::new(), + shared: true, + }); + } + if !inputs.is_empty() && !fd.get_func_proto().is_input_locked() { + out.push(Unassigned { + perturb: graph::Perturb { salt, inputs: inputs.iter().map(|s| (s.off, s.size)).collect(), killed: None }, + names: inputs.iter().map(|s| s.name(prog)).collect::>().join(", "), + entry: inputs.iter().map(|s| (s.off, s.size)).collect(), + shared: true, + }); + } + out +} + +/// One second run of kuna's side with other values in storage its C never +/// assigns. `entry`: registers read at entry, which the machine gets too, so +/// one the binary itself reads is told apart from one only kuna reads. +pub(crate) struct Unassigned { + pub(crate) perturb: graph::Perturb, + pub(crate) names: String, + pub(crate) entry: Vec<(u64, u32)>, + /// A dependence the machine shares, given the same values, is the + /// binary's own and not kuna's. Not so for a call's output register: + /// the binary reads what the callee returned there. + pub(crate) shared: bool, +} + +/// The bytes of the perturbed entry registers for one run. +pub(crate) fn entry_bytes(env: &Env, u: &Unassigned, run: u32) -> Vec<(u64, u8)> { + let be = env.register.is_big_endian(); + let mut out = Vec::new(); + for &(off, size) in &u.entry { + let v = graph::scramble(u.perturb.salt, run, off) & mask(size); + for i in 0..u64::from(size) { + let shift = if be { u64::from(size) - 1 - i } else { i }; + out.push((off + i, (v >> (8 * shift)) as u8)); + } + } + out +} + +/// Whether the machine's system calls write the kernel's result registers: +/// everywhere but where `syscallregs auto` leaves them unwritten, on an image +/// that names no operating system. +pub(crate) fn kernel_returns(prog: &ConsoleProgram) -> bool { + use kuna_decomp::kuna_syscallregs::{SyscallFamily, SyscallRegsMode}; + let arch = prog.arch(); + SyscallFamily::from_archid(&arch.archid).is_none() || arch.image_os_userland || arch.syscall_regs != SyscallRegsMode::Auto +} + +pub(crate) fn input_line(prog: &ConsoleProgram, env: &Env, run: u32, claim: &Claim) -> String { + let mut init = State::new(env, run); + let inputs: Vec = claim + .params + .iter() + .map(|(n, st)| match init.read_storage(&st.space, st.off, st.size) { + Ok(v) => format!("{n}={} ({})", hex(v, st.size), st.name(prog)), + Err(_) => format!("{n}=? ({})", st.name(prog)), + }) + .collect(); + let input = if inputs.is_empty() { "no declared parameters".to_string() } else { inputs.join(" ") }; + format!("input {input}") +} + +/// Check one decompiled function. `contract`, when given, is the function's +/// real type. +/// The registers the ABI reserves for veneers and PLT stubs, which a callee +/// may not expect to hold anything at its entry: ARM's `ip` (`r12`), AArch64's +/// `x16` and `x17`. A transparent thunk may write only these. +pub(crate) fn veneer_registers(prog: &ConsoleProgram) -> Vec<(u64, u32)> { + let arch = prog.arch(); + let names: &[&str] = if arch.archid.starts_with("AARCH64") { + &["x16", "x17"] + } else if arch.archid.starts_with("ARM") { + &["r12"] + } else { + &[] + }; + let Some(lookup) = arch.manage().register_lookup() else { return Vec::new() }; + names.iter().filter_map(|n| lookup.probe_register(n)).map(|r| (r.offset, r.size)).collect() +} diff --git a/decompiler/crates/kuna-verify/src/graph/mod.rs b/decompiler/crates/kuna-verify/src/graph/mod.rs new file mode 100644 index 0000000000..e6aed0b7fc --- /dev/null +++ b/decompiler/crates/kuna-verify/src/graph/mod.rs @@ -0,0 +1,703 @@ +//! The decompiled side: an interpreter over the compiled `Funcdata`. +//! +//! It walks the basic blocks from the entry, evaluates each block's MULTIEQUALs +//! together on the incoming edge, then the block's ops in order. A CBRANCH takes +//! out-edge 1 when its condition, flipped by `boolean_flip`, holds. A varnode +//! that is neither constant nor written reads its storage: an input from the +//! run's initial state, any other from the current one. LOAD and STORE use the +//! same memory model as the machine side, and a call has the same stub. + +pub mod program; + +use kuna_base::space::AddrSpace; +use kuna_num::opcodes::get_opname; + +use crate::calls::{Calls, Record}; +use crate::machine::{Checkpoint, CopyOperands}; +use crate::program::{Arg, Effect, Kind, Op, Operand, Out, Program}; +use crate::state::{Env, State, Writes}; +use crate::value::{eval, mask, Halt}; + +/// What the decompiled function returned: `None` when its RETURN carries no +/// value. +pub type Returned = Option; + +#[derive(Clone, Copy)] +pub(crate) struct CopyOverlap { + pub(crate) checkpoint: Checkpoint, + pub(crate) operands: CopyOperands, +} + +/// How the decompiled run ended. +pub struct Outcome { + pub ret: Returned, + /// A switch met a selector no row of its table carries. + pub unmatched_switch: bool, + /// The run stopped before a forward overlapping copy. + pub(crate) overlapping_copy: Option, + pub calls: Vec, + /// The run ended in a call kuna says does not return. + pub noreturn: bool, + /// Memory written outside the stack since the last call. + pub writes: Writes, + /// It read a byte of its own frame that nothing wrote. + pub read_uninitialized: bool, + /// The calls, up to [`CALL_INPUTS`] of them, where a callee the machine + /// ran for real read argument bytes kuna's call does not pass the same + /// values in. + pub call_inputs: Vec, + /// Calls past [`CALL_INPUTS`] whose argument reads differ. + pub unkept_inputs: usize, + /// System calls and traps, in order. + pub events: Vec, +} + +/// Calls per run whose differing argument reads are kept for a rerun; more +/// are only counted ([`Outcome::unkept_inputs`]). +pub const CALL_INPUTS: usize = 64; + +/// A call whose callee reads argument bytes kuna passes otherwise: +/// the report, and kuna's bytes (a stand-in where it passes none) for a +/// machine run that gives them to the callee. +#[derive(Clone, Debug)] +pub struct CallInput { + pub msg: String, + pub with: crate::machine::WithArgs, + /// Omitted bytes that can be tried with zero if the first stand-in fails. + pub(crate) omitted_register_bytes: Vec, + /// The callee's prototype is declared: kuna's call follows it. + pub locked: bool, +} + +/// Storage kuna's C never assigns, given other values for a second run: the +/// registers it reads at entry without a parameter for them, and registers a +/// call kills that it reads afterwards without a call output for them. +#[derive(Clone, Debug)] +pub struct Perturb { + pub salt: u64, + pub inputs: Vec<(u64, u32)>, + /// Also give registers a call kills, read after it, other values: the + /// output registers (`Some(true)`) or the others (`Some(false)`). + pub killed: Option, +} + +/// The largest copy, fill or compare a builtin runs; a longer one spends the +/// budget, as the loop it replaces would. +const MAX_BUILTIN_BYTES: u64 = 1 << 20; + +struct Run<'e, 'p, 'c> { + calls: &'c Calls, + perturb: Option<&'c Perturb>, + call_inputs: Vec, + unkept_inputs: usize, + events: Vec, + /// The machine's calls, whose recorded effects this side replays. + replay: &'c [Record], + state: State<'e, 'p>, + initial: State<'e, 'p>, + values: Vec>, + unmatched_switch: bool, + records: Vec, + /// Steps a memory builtin took, charged to the budget like the loop it + /// replaces. + charged: u64, + copies: std::collections::BTreeMap, +} + +enum Flow { + Next, + Edge(i32), + Overlap(CopyOverlap), + Return(Returned), + NoReturn, +} + +impl Run<'_, '_, '_> { + /// Whether the machine's callee is kuna's, so its recorded effect may be + /// replayed: the same address, the same code through thunks, a call kuna + /// bound past the PLT stub the machine calls, an injection, or a target of + /// kuna's that is not code in the image (an import, a PIC GOT slot), which + /// the call check leaves alone. + fn same_callee(&self, machine: Option, kuna: Option, site: &crate::calls::Site) -> bool { + let env = self.state.env; + if let Some(stub) = site.plt_stub { + return crate::compare::observe::reaches_stub(env, machine, stub); + } + let (m, k) = (crate::compare::observe::code_target(env, machine), crate::compare::observe::code_target(env, kuna)); + site.resolved + || m == k + || k.is_none_or(|k| !env.is_code(k)) + || m.zip(k).is_some_and(|(m, k)| crate::machine::transparent_target(env, m) == crate::machine::transparent_target(env, k)) + } + + /// Fill the register save area as `va_start` does: the stores kuna's + /// `varargsave` folded, the vector ones only when the incoming `al` is set. + fn va_start(&mut self, env: &Env, f: &kuna_decomp::kuna_varargsave::Folded) -> Result<(), Halt> { + let al = self.initial.read_storage(&env.register, f.al.0, f.al.1)?; + for &(reg, size, frame, vector) in &f.stores { + if vector && al == 0 { + continue; + } + let v = self.initial.read_storage(&env.register, reg, size)?; + self.state.write_storage(&env.ram, env.sp0.wrapping_add(frame as u64), size, v)?; + } + Ok(()) + } + + fn value(&mut self, a: &Arg) -> Result { + match &a.op { + Operand::Const(v) => Ok(*v), + Operand::Slot(slot, at) => self.values[*slot] + .ok_or_else(|| Halt::Harness(format!("read of {at} before its definition"))), + Operand::Memory(st) => self.state.read_storage(&st.space, st.off, a.size), + Operand::Input(st) => match self.perturb.filter(|p| self.unassigned(p, st)) { + Some(p) => Ok(scramble(p.salt, self.state.run, st.off) & mask(a.size)), + None => self.initial.read_storage(&st.space, st.off, a.size), + }, + Operand::Free(st) => self.state.read_storage(&st.space, st.off, a.size), + Operand::TooWide => Err(Halt::Unsupported(format!("{}-byte varnode", a.size))), + Operand::Missing => Err(Halt::Harness("op lacks an input".into())), + } + } + + /// Whether an op writes a register the convention returns values in. + fn is_output(&self, op: &Op) -> bool { + op.out.as_ref().and_then(|o| o.storage.as_ref()).is_some_and(|st| { + st.space.get_index() == self.state.env.register.get_index() + && self.calls.output_regs.iter().any(|&(o, n)| st.off < o + u64::from(n) && o < st.off + u64::from(st.size)) + }) + } + + /// Whether input storage `st` is one kuna's C never assigns. + fn unassigned(&self, p: &Perturb, st: &crate::storage::Storage) -> bool { + st.space.get_index() == self.state.env.register.get_index() + && p.inputs.iter().any(|&(o, n)| st.off < o + u64::from(n) && o < st.off + u64::from(st.size)) + } + + /// Compare what a callee the machine ran for real read with what kuna's + /// call passes there. + fn check_inputs(&mut self, op: &Op, k: usize) -> Result<(), Halt> { + let Some(live) = self.replay.get(k).filter(|r| r.at == op.at).and_then(|r| r.live_in.clone()) else { return Ok(()) }; + let env = self.state.env; + let reg = env.register.get_index(); + let be = env.register.is_big_endian(); + let params = &self.calls.site(op.at).input_storage; + let int_regs = &self.calls.int_regs; + let mut next = 0usize; + let mut placed: Vec> = Vec::with_capacity(op.ins.len()); + for (k, a) in op.ins.iter().enumerate().skip(1) { + let entry_reg = match &a.op { + crate::program::Operand::Input(st) => int_regs.iter().position(|r| r.covers(st)).map(|i| (i, st.clone())), + _ => None, + }; + let float_reg = a.storage.clone().filter(|st| { + st.space.get_index() == reg + && !int_regs.iter().any(|r| r.overlaps(st)) + && self.calls.input_regs.iter().any(|&(o, n)| st.off >= o && st.off + u64::from(st.size) <= o + u64::from(n)) + }); + let st = match (params.get(k - 1).cloned().flatten(), entry_reg) { + (Some(p), _) => Some(p), + (None, Some((i, st))) => { + next = next.max(i + 1); + Some(st) + } + (None, None) if float_reg.is_some() => float_reg, + (None, None) => { + let r = int_regs.get(next).cloned(); + next += 1; + r + } + }; + if let Some(i) = st.as_ref().and_then(|s| int_regs.iter().position(|r| r.covers(s))) { + next = next.max(i + 1); + } + placed.push(st); + } + let mut bytes = Vec::new(); + let mut omitted_register_bytes = Vec::new(); + let mut first = None; + for (off, m) in live { + let (o, n) = self.calls.input_regs.iter().copied().find(|&(o, n)| off >= o && off < o + u64::from(n)).unwrap_or((off, 1)); + let mut kuna = None; + let mut passes_part = false; + 'inputs: for (a, st) in op.ins.iter().skip(1).zip(&placed) { + let Some(st) = st.as_ref() else { continue }; + let pieces = st.pieces(env.prog); + let mut low = 0u64; + for p in pieces.iter().rev() { + let here = low; + low += u64::from(p.size); + if p.space.get_index() != reg { + continue; + } + passes_part |= p.off < o + u64::from(n) && o < p.off + u64::from(p.size); + if off >= p.off && off < p.off + u64::from(p.size) { + let v = self.value(a)?; + let pos = if be { p.off + u64::from(p.size) - 1 - off } else { off - p.off }; + kuna = Some((v >> (8 * (here + pos))) as u8); + break 'inputs; + } + } + } + if kuna == Some(m) || (kuna.is_none() && passes_part) { + continue; + } + bytes.push((off, kuna.unwrap_or_else(|| !m))); + if kuna.is_none() { + omitted_register_bytes.push(off); + } + if first.is_none() { + let name = crate::storage::Storage::new(&env.register, o, n).name(env.prog); + let target = self.calls.site(op.at).target.map_or_else(|| "?".to_string(), |t| format!("{t:#x}")); + let what = match kuna { + Some(kb) => format!("kuna passes 0x{kb:02x} there"), + None => "kuna's call passes nothing there".to_string(), + }; + first = Some(format!( + "call at {:#x} to {target}: the callee reads {name} (byte {:#x}) = 0x{m:02x}; {what}", + op.at, + off - o + )); + } + } + let (stack_bytes, stack_msg) = self.stack_arguments(op.at, k); + if let Some(msg) = first.or(stack_msg) { + if self.call_inputs.len() < CALL_INPUTS { + let locked = self.calls.site(op.at).locked; + self.call_inputs.push(CallInput { + msg, with: crate::machine::WithArgs { call: Some(k), bytes, stack_bytes, kill_salt: 0 }, + omitted_register_bytes, locked, + }); + } else { + self.unkept_inputs += 1; + } + } + Ok(()) + } + + fn stack_arguments(&self, at: u64, k: usize) -> (Vec<(u64, u8)>, Option) { + let site = self.calls.site(at); + let machine = &self.replay[k]; + let Some(stack) = machine.stack_in.as_ref().filter(|_| self.same_callee(machine.target, self.records[k].target, site)) else { + return (Vec::new(), None); + }; + let args = &self.records[k].args; + let mut bytes = Vec::new(); + let mut first = None; + for (off, read) in stack.bytes() { + let kuna = args.iter().enumerate().find_map(|(i, &v)| { + let st = site.stack_input(i)?; + let byte = off.checked_sub(st.off).filter(|&byte| byte < u64::from(st.size))?; + Some((v >> (8 * byte)) as u8) + }); + if let Some(m) = read.filter(|&m| kuna != Some(m)) { + bytes.push((off, kuna.unwrap_or(!m))); + if first.is_none() { + let what = kuna.map_or_else(|| "kuna's call passes nothing there".to_string(), |b| format!("kuna passes 0x{b:02x} there")); + first = Some(format!("call at {at:#x}: the callee reads stack[{off:#x}] = 0x{m:02x}; {what}")); + } + } else if let Some(b) = kuna { + bytes.push((off, b)); + } + } + if first.is_none() { + bytes.clear(); + } + (bytes, first) + } + + fn input(&mut self, op: &Op, k: usize) -> Result { + match op.ins.get(k) { + Some(a) => self.value(a), + None => Err(Halt::Harness(format!("op lacks input {k}"))), + } + } + + fn set(&mut self, out: &Out, val: u128) -> Result<(), Halt> { + self.values[out.slot] = Some(val); + if let Some(st) = &out.backing { + self.state.write_storage(&st.space, st.off, out.size, val)?; + } + Ok(()) + } + + fn set_out(&mut self, op: &Op, val: u128) -> Result<(), Halt> { + let out = op.out.as_ref().ok_or_else(|| Halt::Harness("op without output".into()))?; + self.set(out, val) + } + + /// The value an output's storage holds now. + fn stored(&mut self, op: &Op) -> Result { + let out = op.out.as_ref().ok_or_else(|| Halt::Harness("op without output".into()))?; + let st = out.storage.clone().ok_or_else(|| Halt::Harness("output without storage".into()))?; + self.state.read_storage(&st.space, st.off, out.size) + } + + fn address(&mut self, space: &Option>, op: &Op) -> Result<(std::rc::Rc, u64), Halt> { + let spc = space.clone().ok_or_else(|| Halt::Harness("bad LOAD space id".into()))?; + let ptr = self.input(op, 0)? as u64; + let addr = spc.wrap_offset(AddrSpace::address_to_byte(ptr, spc.get_word_size())); + Ok((spc, addr)) + } + + /// kuna's memory builtins, byte by byte: `memcpy(dst, src, bytes)` (as + /// `memmove`, so an overlap kuna's `memcpy` does not allow shows), + /// `memset(dst, byte, bytes)`, `memset16`/`32`/`64(dst, value, count)` and + /// `r = memcmp(a, b, bytes)`, whose sign says which first differing byte + /// is smaller. + fn memory_builtin(&mut self, op: &Op, name: &str, at: u64) -> Result { + let ram = std::rc::Rc::clone(&self.state.env.ram); + let ptr = |v: u128| ram.wrap_offset(v as u64); + let width: u64 = match name { + "memset16" => 2, + "memset32" => 4, + "memset64" => 8, + "memcpy" | "memset" | "memcmp" => 1, + _ => return Err(Halt::Unsupported(format!("{name} at {at:#x}"))), + }; + let (a, b, n) = (self.input(op, 1)?, self.input(op, 2)?, self.input(op, 3)?); + let bytes = u64::try_from(n).ok().and_then(|n| n.checked_mul(width)).filter(|&n| n <= MAX_BUILTIN_BYTES).ok_or(Halt::Budget)?; + self.charged = bytes; + let dst = ptr(a); + match name { + "memcpy" => { + let src = ptr(b); + let visits = self.copies.entry(at).or_default(); + *visits += 1; + if dst > src && dst - src < bytes { + self.charged = 0; + return Ok(Flow::Overlap(CopyOverlap { + checkpoint: Checkpoint { at, visit: *visits }, + operands: CopyOperands { dest: dst, src, bytes: u128::from(bytes), backwards: false }, + })); + } + let mut data = Vec::with_capacity(bytes as usize); + for i in 0..bytes { + data.push(self.state.read(&ram, ram.wrap_offset(src.wrapping_add(i)), 1)?); + } + for (i, v) in data.into_iter().enumerate() { + self.state.write(&ram, ram.wrap_offset(dst.wrapping_add(i as u64)), 1, v)?; + } + } + "memcmp" => { + let other = ptr(b); + let mut r = 0i64; + for i in 0..bytes { + let x = self.state.read(&ram, ram.wrap_offset(dst.wrapping_add(i)), 1)?; + let y = self.state.read(&ram, ram.wrap_offset(other.wrapping_add(i)), 1)?; + if x != y { + r = if x < y { -1 } else { 1 }; + break; + } + } + let size = op.out.as_ref().map_or(4, |o| o.size); + self.set_out(op, (r as i128 as u128) & mask(size))?; + } + _ => { + let value = if name == "memset" { b & 0xff } else { b }; + for i in 0..bytes / width { + self.state.write(&ram, ram.wrap_offset(dst.wrapping_add(i * width)), width as u32, value & mask(width as u32))?; + } + } + } + Ok(Flow::Next) + } + + fn exec(&mut self, op: &Op) -> Result { + let at = op.at; + match &op.kind { + Kind::Branch => Ok(Flow::Edge(0)), + Kind::CBranch { flip } => { + let cond = self.input(op, 1)?; + Ok(Flow::Edge(if (cond != 0) != *flip { 1 } else { 0 })) + } + Kind::Return { halt } => { + if *halt { + return Err(Halt::Unsupported(format!("the decompiled flow halts at {at:#x}"))); + } + if op.ins.len() > 1 { + Ok(Flow::Return(Some(self.input(op, 1)?))) + } else { + Ok(Flow::Return(None)) + } + } + Kind::BranchInd { switch, targets } => { + let v = self.input(op, 0)?; + let vsize = op.ins[0].size; + let edge = match switch { + Some(sw) => { + match sw.rows.iter().find(|(label, _)| u128::from(*label) & mask(vsize) == v) { + Some((_, Some(e))) => Some(*e), + Some((_, None)) => { + return Err(Halt::Unsupported(format!("BRANCHIND at {at:#x}: the row for {v:#x} reaches no out-edge"))); + } + None => { + self.unmatched_switch = true; + sw.default + } + } + } + None => targets.iter().position(|&t| u128::from(t) == v).map(|e| e as i32), + }; + if edge.is_none() && self.unmatched_switch { + return Err(Halt::NoRow(format!("BRANCHIND at {at:#x} on {v:#x}"))); + } + edge.map(Flow::Edge) + .ok_or_else(|| Halt::Unsupported(format!("BRANCHIND at {at:#x} on {v:#x}, which no out-edge takes"))) + } + Kind::Call { direct } => { + let target = match direct { + Some(_) => self.calls.site(at).target, + None => Some(self.input(op, 0)? as u64), + }; + let mut args = Vec::with_capacity(op.ins.len().saturating_sub(1)); + for k in 1..op.ins.len() { + args.push(self.input(op, k)?); + } + let indirect = direct.is_none(); + let wide = target.is_some_and(|t| self.state.env.code_mapped(t)); + let writes = self.state.writes_at_call(&args, wide); + crate::calls::record(&mut self.records, Record { at, target, indirect, args, writes, effect: None, frame_reads: None, live_in: None, stack_in: None, whole: Vec::new() })?; + let site = self.calls.site(at); + if site.noreturn { + return Ok(Flow::NoReturn); + } + let k = self.records.len() - 1; + self.check_inputs(op, k)?; + let real = self.replay.get(k).filter(|r| r.at == at && self.same_callee(r.target, target, site)).and_then(|r| r.effect.clone()); + match real { + Some(effect) => self.state.replay(&effect), + None => { + let killed = site.killed.clone(); + let args: Vec = self.records[k] + .args + .iter() + .zip(&site.args) + .filter(|(_, a)| a.is_some()) + .map(|(&v, _)| v) + .collect(); + self.state.call(&killed, &args, site.ret_ext.as_ref()); + } + } + if let Some(out) = op.out.as_ref() { + let physical = out.storage.as_ref().is_some_and(|st| { + matches!( + st.space.get_type(), + kuna_base::space::spacetype::IPTR_PROCESSOR + | kuna_base::space::spacetype::IPTR_SPACEBASE + | kuna_base::space::spacetype::IPTR_JOIN + ) + }); + let v = match (physical, self.calls.site(at).output.clone()) { + (false, Some(st)) => self.state.read_storage(&st.space, st.off, out.size.min(st.size))?, + _ => self.stored(op)?, + }; + self.set_out(op, v)?; + } + Ok(Flow::Next) + } + Kind::CallOther { name, builtin } => { + if let Some(b) = builtin { + return self.memory_builtin(op, b, at); + } + let system = crate::calls::SYSTEM_USEROPS.contains(&name.as_str()); + let trap = crate::calls::TRAP_USEROPS.contains(&name.as_str()); + if system || trap { + let mut ins = Vec::with_capacity(op.ins.len().saturating_sub(1)); + for k in 1..op.ins.len() { + ins.push(self.input(op, k)?); + } + let k = self.events.len(); + self.events.push(crate::calls::UserEvent { at, name: name.clone(), ins, file: Vec::new() }); + if trap { + return Ok(Flow::NoReturn); + } + if let Some(out) = op.out.as_ref() { + self.set(out, crate::calls::userop_value(self.state.run, k, out.size))?; + } + return Ok(Flow::Next); + } + if name == crate::program::SYSCALL_ERROR { + if let (Some(out), Some(k)) = (op.out.as_ref(), self.events.len().checked_sub(1)) { + self.set(out, crate::calls::syscall_error_value(self.state.run, k, out.size))?; + return Ok(Flow::Next); + } + } + if let (Some(out), Some(v)) = (op.out.as_ref(), crate::machine::constant_userop(name)) { + self.set(out, v)?; + return Ok(Flow::Next); + } + let quiet = crate::machine::EXIT_ONLY_USEROPS.contains(&name.as_str()) || crate::machine::NO_EFFECT_USEROPS.contains(&name.as_str()); + if op.out.is_some() || !quiet { + return Err(Halt::Unsupported(format!("CALLOTHER {name} at {at:#x}"))); + } + Ok(Flow::Next) + } + Kind::Store(space) => { + let (spc, addr) = self.address(space, op)?; + let size = op.ins.get(1).map(|a| a.size).ok_or_else(|| Halt::Harness("STORE lacks a value".into()))?; + let v = self.input(op, 1)?; + self.state.write(&spc, addr, size, v)?; + Ok(Flow::Next) + } + Kind::Load(space) => { + let (spc, addr) = self.address(space, op)?; + let size = op.out.as_ref().map(|o| o.size).ok_or_else(|| Halt::Unsupported("op without output".into()))?; + let v = if spc.get_type() == kuna_base::space::spacetype::IPTR_CONSTANT { + u128::from(addr) & mask(size) + } else { + self.state.read(&spc, addr, size)? + }; + self.set_out(op, v)?; + Ok(Flow::Next) + } + Kind::Indirect(effect) => { + let v = match effect { + Effect::Keep => self.input(op, 0)?, + Effect::Killed if self.perturb.and_then(|p| p.killed).is_some_and(|outputs| outputs == self.is_output(op)) => { + let (size, slot) = op.out.as_ref().map_or((0, 0), |o| (o.size, o.slot as u64)); + scramble(self.perturb.map_or(0, |p| p.salt), self.state.run, op.at ^ (slot << 40) ^ 0x5bd1_e995) & mask(size) + } + Effect::Killed | Effect::Memory => self.stored(op)?, + }; + self.set_out(op, v)?; + Ok(Flow::Next) + } + Kind::IndirectBefore => { + let v = self.input(op, 0)?; + let out = op.out.as_ref().ok_or_else(|| Halt::Harness("op without output".into()))?; + if let Some(st) = &out.storage { + self.state.write_storage(&st.space, st.off, out.size, v)?; + } + Ok(Flow::Next) + } + Kind::StrayPhi => Err(Halt::Harness("MULTIEQUAL after a block's head".into())), + Kind::Nop => Ok(Flow::Next), + Kind::Eval(opc) => { + let size = op.out.as_ref().map(|o| o.size).ok_or_else(|| Halt::Unsupported("op without output".into()))?; + let mut ins = crate::value::Inputs::default(); + for a in &op.ins { + ins.push((self.value(a)?, a.size)); + } + let v = eval(*opc, size, ins.as_slice()).map_err(|h| match h { + Halt::Unsupported(s) if s == get_opname(*opc) => Halt::Unsupported(format!("{s} at {at:#x}")), + other => other, + })?; + self.set_out(op, v)?; + Ok(Flow::Next) + } + } + } + + fn finish(self, ret: Returned, noreturn: bool, overlapping_copy: Option) -> Outcome { + Outcome { + ret, + unmatched_switch: self.unmatched_switch, + overlapping_copy, + writes: self.state.writes(), + read_uninitialized: self.state.read_uninitialized, + call_inputs: self.call_inputs, + unkept_inputs: self.unkept_inputs, + events: self.events, + calls: self.records, + noreturn, + } + } +} + +/// Run the decompiled function from its entry block on the run's initial state. +/// A value for storage kuna never assigns, other than the run's own. +pub(crate) fn scramble(salt: u64, run: u32, key: u64) -> u128 { + let mut z = salt ^ u64::from(run).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ key.wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^= z >> 31; + u128::from(z) | (u128::from(z.rotate_left(17)) << 64) +} + +pub fn run( + env: &Env, + program: &Program, + run: u32, + budget: u64, + calls: &Calls, + replay: &[Record], + perturb: Option<&Perturb>, +) -> Result { + if program.blocks.is_empty() { + return Err(Halt::Harness("no basic blocks".into())); + } + let mut r = Run { + calls, + perturb, + call_inputs: Vec::new(), + unkept_inputs: 0, + events: Vec::new(), + replay, + state: State::new(env, run), + initial: State::new(env, run), + values: vec![None; program.slots], + unmatched_switch: false, + records: Vec::new(), + charged: 0, + copies: std::collections::BTreeMap::new(), + }; + if let Some(f) = &program.vararg { + r.va_start(env, f)?; + } + let mut bl = 0usize; + let mut slot: Option = None; + let mut steps = 0u64; + loop { + let block = &program.blocks[bl]; + steps += 1; + if steps > budget { + return Err(Halt::Budget); + } + if !block.phis.is_empty() { + let s = slot.ok_or_else(|| Halt::Harness("MULTIEQUAL in the entry block".into()))?; + let mut vals = Vec::with_capacity(block.phis.len()); + for phi in &block.phis { + let a = phi.ins.get(s as usize).ok_or_else(|| Halt::Harness(format!("op lacks input {s}")))?; + vals.push(r.value(a)?); + } + for (phi, v) in block.phis.iter().zip(vals) { + let out = phi.out.as_ref().ok_or_else(|| Halt::Harness("op without output".into()))?; + r.set(out, v)?; + } + } + let mut edge = 0; + for (k, op) in block.ops.iter().enumerate() { + if program.watch == Some((bl, k)) { + program.reached.set(true); + } + steps += 1; + if steps > budget { + return Err(Halt::Budget); + } + let flow = r.exec(op)?; + steps += std::mem::take(&mut r.charged); + if steps > budget { + return Err(Halt::Budget); + } + match flow { + Flow::Next => {} + Flow::Edge(e) => { + edge = e; + break; + } + Flow::Overlap(at) => return Ok(r.finish(None, false, Some(at))), + Flow::Return(ret) => return Ok(r.finish(ret, false, None)), + Flow::NoReturn => return Ok(r.finish(None, true, None)), + } + } + let Some(&(next, rev)) = block.outs.get(edge as usize).filter(|_| edge >= 0) else { + return Err(Halt::Harness(format!("block {} has no out-edge {edge}", block.index))); + }; + if next == usize::MAX { + return Err(Halt::Harness(format!("block {} leaves the block list", block.index))); + } + slot = Some(rev); + bl = next; + } +} diff --git a/decompiler/crates/kuna-verify/src/graph/program.rs b/decompiler/crates/kuna-verify/src/graph/program.rs new file mode 100644 index 0000000000..38837499b5 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/graph/program.rs @@ -0,0 +1,425 @@ +//! The decompiled function compiled once for repeated runs. +//! +//! Every written varnode gets a slot in a flat value array, operands are +//! resolved to a constant, a slot, or a storage location to read, and each +//! switch's rows are mapped to out-edges ahead of time. A run then touches +//! neither the op bank nor the varnode bank. Anything that cannot be modeled is +//! kept as data and reported only when a run reaches it, so a path no run takes +//! never decides the verdict. + +use std::collections::{BTreeMap, BTreeSet}; +use std::rc::Rc; + +use kuna_base::space::{spacetype, AddrSpace}; +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::context::{BlockId, OpId, VarnodeId}; +use kuna_decomp::funcdata::Funcdata; +use kuna_decomp::jumptable::NO_LABEL; +use kuna_num::opcodes::OpCode; + +use crate::calls::Calls; +use crate::storage::Storage; +use crate::value::{mask, MAX_SIZE}; + +#[derive(Clone, Debug)] +pub enum Operand { + Const(u128), + /// A written varnode's slot, and the address offset its error names. + Slot(usize, u64), + /// A varnode tied to a stack or memory location: the location now, as the + /// printed C reads the variable. A STORE through a pointer the IR did not + /// guard still shows. + Memory(Storage), + /// An input varnode: its storage at entry. + Input(Storage), + /// Neither written nor an input: its storage now. + Free(Storage), + /// A varnode the value model cannot hold. + TooWide, + Missing, +} + +#[derive(Clone, Debug)] +pub struct Arg { + pub op: Operand, + pub size: u32, + /// Where the varnode lives, for a CALL's inputs: the storage a callee + /// reads the argument from. + pub storage: Option, +} + +/// Where a written varnode lives: its slot, its storage, and the memory a later +/// LOAD of the same bytes reads when the varnode is a stack or memory location. +#[derive(Clone, Debug)] +pub struct Out { + pub slot: usize, + pub size: u32, + pub storage: Option, + pub backing: Option, +} + +/// What an INDIRECT's output holds once the op it guards has run. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Effect { + /// The op leaves the storage alone: the output is the input. + Keep, + /// A register the guarded call kills. + Killed, + /// Memory: whatever the store or the call left there. + Memory, +} + +#[derive(Clone, Debug)] +pub struct Switch { + /// Labelled rows: label, and the out-edge their address starts. + pub rows: Vec<(u64, Option)>, + pub default: Option, +} + +#[derive(Clone, Debug)] +pub enum Kind { + Eval(OpCode), + Load(Option>), + Store(Option>), + Branch, + CBranch { flip: bool }, + Return { halt: bool }, + /// A switch's rows, or `None` when the input is a code address; and the + /// start address of each out-edge's block. + BranchInd { switch: Option, targets: Vec }, + /// `direct`: the target of a CALL; a CALLIND reads its input. + Call { direct: Option }, + CallOther { name: String, builtin: Option<&'static str> }, + Indirect(Effect), + /// A memory INDIRECT at its own place, before the op it guards: its input + /// is what the storage holds when that op runs. + IndirectBefore, + StrayPhi, + /// Does nothing: what a mutant leaves of a dropped store. + Nop, +} + +#[derive(Clone, Debug)] +pub struct Op { + pub kind: Kind, + pub ins: Vec, + pub out: Option, + pub at: u64, +} + +#[derive(Clone, Debug)] +pub struct Phi { + pub out: Option, + pub ins: Vec, +} + +#[derive(Clone, Debug)] +pub struct Block { + pub index: i32, + pub start: u64, + pub phis: Vec, + pub ops: Vec, + /// Successor block position, and this edge's input slot in it. + pub outs: Vec<(usize, i32)>, +} + +pub struct Program { + pub blocks: Vec, + pub slots: usize, + pub starts: BTreeSet, + /// A mutant's op, `(block, op)`, and whether a run reached it. + pub watch: Option<(usize, usize)>, + pub reached: std::rc::Rc>, + /// The register-save stores kuna's `varargsave` folded away: what the + /// printed `va_list` setup means by `va_start`, run at entry. + pub vararg: Option, +} + +/// The decompiler's built-in user ops that read or write memory. +pub fn memory_builtin(index: u64) -> Option<&'static str> { + use kuna_decomp::userop::*; + let index = u32::try_from(index).ok()?; + [ + (BUILTIN_STRINGDATA, "stringdata"), + (BUILTIN_VOLATILE_READ, "volatile read"), + (BUILTIN_VOLATILE_WRITE, "volatile write"), + (BUILTIN_MEMCPY, "memcpy"), + (BUILTIN_STRNCPY, "strncpy"), + (BUILTIN_WCSNCPY, "wcsncpy"), + (BUILTIN_MEMSET, "memset"), + (BUILTIN_MEMSET16, "memset16"), + (BUILTIN_MEMSET32, "memset32"), + (BUILTIN_MEMSET64, "memset64"), + (BUILTIN_MEMCMP, "memcmp"), + (BUILTIN_STRLEN, "strlen"), + ] + .into_iter() + .find(|&(id, _)| id == index) + .map(|(_, name)| name) +} + +/// The name the decompiler's `syscall_error()` builtin is checked under. +pub const SYSCALL_ERROR: &str = "syscall_error"; + +pub fn userop_name(prog: &ConsoleProgram, index: u64) -> String { + if index == u64::from(kuna_decomp::userop::BUILTIN_SYSCALL_ERROR) { + return SYSCALL_ERROR.to_string(); + } + let mut names = Vec::new(); + prog.arch().translate().get_user_op_names(&mut names); + names.get(index as usize).cloned().unwrap_or_else(|| format!("#{index}")) +} + +struct Compiler<'a> { + prog: &'a ConsoleProgram, + fd: &'a Funcdata, + calls: &'a Calls, + register: i32, + slots: BTreeMap, +} + +/// The op an INDIRECT guards, from the iop constant that names it. +fn guarded_op(fd: &Funcdata, indirect: OpId) -> Option { + let o = fd.obank().get(indirect)?; + let v = fd.vbank().get(o.get_in(1)?)?; + let space = v.get_addr().get_space()?; + (space.get_type() == spacetype::IPTR_IOP).then(|| OpId::from(slotmap::KeyData::from_ffi(v.get_offset()))) +} + +impl Compiler<'_> { + fn slot(&mut self, vn: VarnodeId) -> usize { + let n = self.slots.len(); + *self.slots.entry(vn).or_insert(n) + } + + fn arg(&mut self, vn: Option) -> Arg { + let Some(id) = vn else { return Arg { op: Operand::Missing, size: 0, storage: None } }; + let Some(v) = self.fd.vbank().get(id) else { return Arg { op: Operand::Missing, size: 0, storage: None } }; + let size = v.get_size() as u32; + let op = if size > MAX_SIZE { + Operand::TooWide + } else if v.is_constant() { + Operand::Const(u128::from(v.get_offset()) & mask(size)) + } else if let Some(st) = + Storage::at(v.get_addr(), size).filter(|st| v.is_addr_tied() && self.memory(st)) + { + if v.is_written() { + self.slot(id); + } + Operand::Memory(st) + } else if v.is_written() { + Operand::Slot(self.slot(id), v.get_addr().get_offset()) + } else { + match Storage::at(v.get_addr(), size) { + Some(st) if v.is_input() => Operand::Input(st), + Some(st) => Operand::Free(st), + None => Operand::Missing, + } + }; + let storage = (!v.is_constant()).then(|| Storage::at(v.get_addr(), size)).flatten(); + Arg { op, size, storage } + } + + fn out(&mut self, vn: Option) -> Option { + let id = vn?; + let v = self.fd.vbank().get(id)?; + let size = v.get_size() as u32; + let storage = Storage::at(v.get_addr(), size); + let backing = storage.clone().filter(|st| self.memory(st)); + Some(Out { slot: self.slot(id), size, storage, backing }) + } + + fn memory(&self, st: &Storage) -> bool { + st.space.get_type() == spacetype::IPTR_SPACEBASE + || (st.space.get_type() == spacetype::IPTR_PROCESSOR && st.space.get_index() != self.register) + } + + fn effect(&self, indirect: OpId, out: Option) -> Effect { + let Some(st) = out.and_then(|o| self.fd.vbank().get(o)).and_then(|v| Storage::at(v.get_addr(), v.get_size() as u32)) + else { + return Effect::Keep; + }; + if self.memory(&st) { + return Effect::Memory; + } + let call = guarded_op(self.fd, indirect) + .and_then(|g| self.fd.obank().get(g)) + .filter(|g| matches!(g.code(), OpCode::CPUI_CALL | OpCode::CPUI_CALLIND)); + let killed = call.is_some_and(|c| { + st.space.get_index() == self.register + && self.calls.site(c.get_addr().get_offset()).killed.iter().any(|&(off, size)| { + st.off < off + u64::from(size) && off < st.off + u64::from(st.size) + }) + }); + if killed { + Effect::Killed + } else { + Effect::Keep + } + } + + /// A labelled switch's rows, each mapped to the out-edge whose block the + /// table sends it to. + fn switch(&self, op: OpId, succ: &[BlockId]) -> Option { + let jt = self.fd.find_jump_table(op).filter(|jt| jt.is_labelled())?; + let mut edge_of: BTreeMap = BTreeMap::new(); + for (e, &bl) in succ.iter().enumerate() { + let n = jt.num_indices_by_block(self.fd, bl).unwrap_or(0); + for i in 0..n { + if let Ok(idx) = jt.get_index_by_block(self.fd, bl, i) { + edge_of.entry(idx).or_insert(e as i32); + } + } + } + let rows = (0..jt.num_entries()) + .filter_map(|i| { + let label = jt.get_label_by_index(i); + (label != NO_LABEL).then(|| (label, edge_of.get(&i).copied())) + }) + .collect(); + let default = (jt.get_default_block() >= 0).then(|| jt.get_default_block()); + Some(Switch { rows, default }) + } + + fn op(&mut self, id: OpId, out_starts: &[u64], succ: &[BlockId]) -> Option { + let o = self.fd.obank().get(id)?; + let opc = o.code(); + let at = o.get_addr().get_offset(); + let ins_ids: Vec> = (0..o.num_input()).map(|k| o.get_in(k)).collect(); + let out_id = o.get_out(); + let flip = o.is_boolean_flip(); + let halt = o.get_halt_type() != 0; + let mut ins: Vec = ins_ids.iter().map(|&v| self.arg(v)).collect(); + let kind = match opc { + OpCode::CPUI_BRANCH => Kind::Branch, + OpCode::CPUI_CBRANCH => Kind::CBranch { flip }, + OpCode::CPUI_RETURN => Kind::Return { halt }, + OpCode::CPUI_BRANCHIND => { + Kind::BranchInd { switch: self.switch(id, succ), targets: out_starts.to_vec() } + } + OpCode::CPUI_CALL => { + let direct = ins_ids.first().copied().flatten().and_then(|v| self.fd.vbank().get(v)).map(|v| v.get_offset()); + Kind::Call { direct } + } + OpCode::CPUI_CALLIND => Kind::Call { direct: None }, + OpCode::CPUI_STORE => { + let space = match ins.first().map(|a| &a.op) { + Some(Operand::Const(idx)) => self.prog.arch().manage().get_space(*idx as i32).cloned(), + _ => None, + }; + ins.remove(0); + Kind::Store(space) + } + OpCode::CPUI_INDIRECT => Kind::Indirect(self.effect(id, out_id)), + OpCode::CPUI_MULTIEQUAL => Kind::StrayPhi, + OpCode::CPUI_LOAD => { + let space = match ins.first().map(|a| &a.op) { + Some(Operand::Const(idx)) => self.prog.arch().manage().get_space(*idx as i32).cloned(), + _ => None, + }; + ins.remove(0); + Kind::Load(space) + } + OpCode::CPUI_CALLOTHER => { + let index = match ins.first().map(|a| &a.op) { + Some(Operand::Const(i)) => *i as u64, + _ => u64::MAX, + }; + Kind::CallOther { name: userop_name(self.prog, index), builtin: memory_builtin(index) } + } + other => Kind::Eval(other), + }; + let out = self.out(out_id); + Some(Op { kind, ins, out, at }) + } +} + +/// Where a body op runs: as itself, or as the two halves of an INDIRECT that +/// was moved. +#[derive(Clone, Copy)] +enum Place { + Op(OpId), + Before(OpId), +} + +/// An INDIRECT stands just before the op whose effect it describes, and its +/// output is the value after that op: its input, with whatever the op wrote on +/// top. Each one is moved just after its op, and leaves a `Before` half in its +/// own place that puts the input in memory for the op to overwrite. +fn after_their_effects(fd: &Funcdata, body: &[OpId]) -> Vec { + let guarded: BTreeMap = body + .iter() + .filter(|&&op| fd.obank().get(op).is_some_and(|o| o.code() == OpCode::CPUI_INDIRECT)) + .filter_map(|&op| guarded_op(fd, op).filter(|g| body.contains(g)).map(|g| (op, g))) + .collect(); + let mut out = Vec::with_capacity(body.len() + guarded.len()); + for &op in body { + if guarded.contains_key(&op) { + out.push(Place::Before(op)); + continue; + } + out.push(Place::Op(op)); + out.extend(body.iter().filter(|&&i| guarded.get(&i) == Some(&op)).map(|&i| Place::Op(i))); + } + out +} + +/// Whether an INDIRECT's input was computed by an op. An entry value, or +/// another guard's output on the same storage, only passes the location's +/// value along, so writing it back before the guarded op would undo a write +/// the IR did not guard. +fn computed_input(fd: &Funcdata, indirect: OpId) -> bool { + let Some(v) = fd.obank().get(indirect).and_then(|o| o.get_in(0)).and_then(|v| fd.vbank().get(v)) else { + return false; + }; + let def = v.get_def().and_then(|d| fd.obank().get(d)); + def.is_some_and(|d| d.code() != OpCode::CPUI_INDIRECT) +} + +/// Compile the final `Funcdata`. +pub fn compile(prog: &ConsoleProgram, fd: &Funcdata, calls: &Calls) -> Program { + let graph = fd.bblocks_ref(); + let n = fd.bblocks_get_size(); + let ids: Vec<_> = (0..n).map(|i| fd.bblocks_get_block(i)).collect(); + let position: BTreeMap<_, usize> = ids.iter().enumerate().map(|(i, &b)| (b, i)).collect(); + let start_of = |b| kuna_decomp::block::block_get_start(&graph.arena, b).get_offset(); + let register = prog.arch().manage().get_space_by_name("register").map_or(-1, |r| r.get_index()); + let mut c = Compiler { prog, fd, calls, register, slots: BTreeMap::new() }; + let mut blocks = Vec::with_capacity(ids.len()); + for &bl in &ids { + let block = graph.block(bl); + let succ: Vec<_> = (0..block.size_out()).map(|e| block.get_out(e)).collect(); + let out_starts: Vec = succ.iter().map(|&b| start_of(b)).collect(); + let outs = (0..block.size_out()) + .map(|e| (position.get(&succ[e as usize]).copied().unwrap_or(usize::MAX), block.get_out_rev_index(e))) + .collect(); + let mut phis = Vec::new(); + let mut body = Vec::new(); + for op in fd.bb_ops(bl) { + let Some(o) = fd.obank().get(op) else { continue }; + if o.code() == OpCode::CPUI_MULTIEQUAL && body.is_empty() { + let ins = (0..o.num_input()).map(|k| c.arg(o.get_in(k))).collect(); + let out = c.out(o.get_out()); + phis.push(Phi { out, ins }); + } else { + body.push(op); + } + } + let ops = after_their_effects(fd, &body) + .into_iter() + .filter_map(|place| match place { + Place::Op(op) => c.op(op, &out_starts, &succ), + Place::Before(op) => c + .op(op, &out_starts, &succ) + .filter(|o| matches!(o.kind, Kind::Indirect(Effect::Memory)) && computed_input(fd, op)) + .map(|mut o| { + o.kind = Kind::IndirectBefore; + o + }), + }) + .collect(); + blocks.push(Block { index: block.get_index(), start: start_of(bl), phis, ops, outs }); + } + let starts = blocks.iter().map(|b| b.start).collect(); + Program { blocks, slots: c.slots.len(), starts, watch: None, reached: Default::default(), vararg: fd.vararg_folded().cloned() } +} diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs new file mode 100644 index 0000000000..baa9c70c58 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -0,0 +1,186 @@ +//! diffverify: does kuna's decompiled function compute what the machine code +//! computes? `docs/features/diffverify/README.md` is the guide. +//! +//! Both sides start from the same raw machine state. The machine side runs the +//! function's SLEIGH p-code (`machine`); the decompiled side runs the final +//! `Funcdata` (`graph`). Calls run the same stub on both (`calls`). Each call, +//! the memory outside the stack, and the return value are compared, the last +//! under the physical ABI and, when one is given, a typed contract (`check`). +//! Design and scope: +//! `docs/features/diffverify/proposal.md`. +//! +//! Development only: the release binary does not link this crate. + +pub mod abi; +pub mod compare; +pub mod graph; +pub mod machine; +pub mod report; +pub mod semantics; +pub mod session; +pub mod state; +pub mod tools; + +pub use abi::{calls, contract, divergence}; +pub use compare::check; +pub use graph::program; +pub use semantics::{storage, value, x87}; +pub use tools::mutate; + +use std::time::{Duration, Instant}; + +pub use check::{check_function, Options}; +pub use report::{Report, Row, Verdict}; + +/// Check `functions` (names, or `0x` addresses) in an object file. +/// `contract_source` is C source to read each function's return type from. A +/// function whose decompile fails is reported as `UNKNOWN`, and the rest go on. +pub fn check_binary( + path: &str, + functions: &[String], + options: &[(String, String)], + spec_roots: &[String], + contract_source: Option<(&str, &str)>, + opts: &Options, +) -> Result, String> { + let mut found = Vec::new(); + check_binary_each(path, functions, options, spec_roots, contract_source, opts, |pos, r| found.push((pos, r)))?; + found.sort_by_key(|(pos, _)| *pos); + Ok(found.into_iter().map(|(_, r)| r).collect()) +} + +/// [`check_binary`], handing each function's report to `emit` as soon as it is +/// known, with the function's position in `functions`. +pub fn check_binary_each( + path: &str, + functions: &[String], + options: &[(String, String)], + spec_roots: &[String], + contract_source: Option<(&str, &str)>, + opts: &Options, + mut emit: impl FnMut(usize, Report), +) -> Result<(), String> { + let script = session::binary_script(path, functions, options); + let first = session::load_lines(path, options).len(); + let mut load_error = None; + let mut failure = None; + let mut done = std::collections::BTreeSet::new(); + session::run_steps(script, None, spec_roots, true, None, |step| match step { + session::Step::Failed { line, msg } if line < first => { + load_error.get_or_insert_with(|| msg.to_string()); + } + session::Step::Failed { line, msg } => { + let pos = (line - first) / 2; + if done.insert(pos) { + let report = Report { + function: functions.get(pos).cloned().unwrap_or_default(), + verdict: Verdict::Unknown(format!("UNKNOWN(decompile: {msg})")), + lines: Vec::new(), + suspects: Vec::new(), + elapsed: Duration::ZERO, + }; + emit(pos, report); + } + } + session::Step::Decompiled { line, prog, fd } => { + if line < first || load_error.is_some() { + return; + } + let contract = match contract_source { + Some((src, name)) => match contract::from_source(src, fd.get_name(), name, abi::c_sizes(prog)) { + Ok(c) => Some(c), + Err(e) => { + failure.get_or_insert(e); + return; + } + }, + None => None, + }; + let pos = (line - first) / 2; + done.insert(pos); + emit(pos, check_function(prog, fd, contract.as_ref(), opts)); + } + })?; + if let Some(e) = load_error.or(failure) { + return Err(e); + } + Ok(()) +} + +/// One datatest file's reports, and the time its decompiles and checks took. +pub struct FileResult { + pub reports: Vec, + pub error: Option, + pub wall: Duration, +} + +/// Check every function a datatest's script decompiles, under the options its +/// script sets. +/// A command the script expects to fail (a datatest that checks an error +/// message) is passed over, as `kuna test` does; a file none of whose +/// decompiles could be checked is an error. +pub fn check_datatest(path: &str, spec_roots: &[String], opts: &Options) -> FileResult { + let start = Instant::now(); + let mut reports = Vec::new(); + let error = match session::load_datatest(path, spec_roots) { + Ok((prog, commands, _env)) => { + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + session::run(commands, Some(prog), spec_roots, true, None, |prog, fd| { + reports.push(check_function(prog, fd, None, opts)); + }) + })); + match run { + Ok(Ok((_, failures))) if reports.is_empty() && !failures.is_empty() => Some(failures[0].1.clone()), + Ok(Ok(_)) => None, + Ok(Err(e)) => Some(e), + Err(_) => Some("panicked".to_string()), + } + } + Err(e) => Some(e), + }; + FileResult { reports, error, wall: start.elapsed() } +} + +/// Plant mutants in each function a datatest decompiles (`mutate`), up to +/// `per_function` each, and hand each outcome to `emit`. +pub fn mutate_datatest( + path: &str, + spec_roots: &[String], + opts: &Options, + per_function: usize, + mut emit: impl FnMut(mutate::Outcome), +) -> Result<(), String> { + let (prog, commands, _env) = session::load_datatest(path, spec_roots)?; + let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + session::drive(commands, Some(prog), spec_roots, |prog, fd| { + for o in mutate::mutate_function(prog, fd, opts, per_function) { + emit(o); + } + }) + })); + match run { + Ok(r) => r, + Err(_) => Err("panicked".to_string()), + } +} + +/// [`mutate_datatest`] for functions of an object file. +pub fn mutate_binary( + path: &str, + functions: &[String], + options: &[(String, String)], + spec_roots: &[String], + opts: &Options, + per_function: usize, + mut emit: impl FnMut(mutate::Outcome), +) -> Result<(), String> { + let script = session::binary_script(path, functions, options); + let (_, failures) = session::run(script, None, spec_roots, true, None, |prog, fd| { + for o in mutate::mutate_function(prog, fd, opts, per_function) { + emit(o); + } + })?; + if failures.is_empty() { Ok(()) } else { + Err(failures.into_iter().map(|(_, msg)| msg).collect::>().join("\n")) + } +} diff --git a/decompiler/crates/kuna-verify/src/machine/mod.rs b/decompiler/crates/kuna-verify/src/machine/mod.rs new file mode 100644 index 0000000000..de5a036bc0 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/machine/mod.rs @@ -0,0 +1,1200 @@ +//! The machine side: the function's own instructions, lifted by the program's +//! SLEIGH translator one at a time and executed op by op from its entry until +//! it returns. +//! +//! A `RETURN`, or an indirect branch to an address the image does not map (the +//! random return address), ends the run. A call runs a stub instead of the +//! callee (`calls.rs`): it is recorded with its arguments and the memory the +//! callee could read, then has its effect. A branch out of the function from an +//! instruction kuna treats as a call is a tail call: the stub runs, and the +//! function returns. Where kuna has no call, a callee in the image is run for +//! real, and its RETURN comes back to the caller. + +mod rep_copy; +#[cfg(test)] +mod tests; +mod thunk; + +pub(crate) use rep_copy::CopyOperands; +pub use thunk::*; + +use std::rc::Rc; + +use kuna_base::address::Address; +use kuna_base::space::{spacetype, AddrSpace}; +use kuna_num::opcodes::{get_opname, OpCode}; +use kuna_num::pcoderaw::VarnodeData; +use kuna_sleigh::translate::PcodeEmit; + +use crate::calls::{Calls, Record}; +use crate::state::{Env, State}; +use crate::storage::Storage; +use crate::value::{eval, mask, Halt}; + +pub struct RawOp { + pub opc: OpCode, + pub out: Option, + pub ins: Vec, +} + +pub struct Insn { + pub len: u64, + pub ops: Vec, +} + +struct Collect(Vec); + +impl PcodeEmit for Collect { + fn dump(&mut self, _addr: &Address, opc: OpCode, outvar: Option<&VarnodeData>, vars: &[VarnodeData]) { + self.0.push(RawOp { opc, out: outvar.cloned(), ins: vars.to_vec() }); + } +} + +pub(crate) fn lift(env: &Env, addr: u64) -> Result, Halt> { + if let Some(i) = env.insns.borrow().get(&addr) { + return Ok(Rc::clone(i)); + } + let mut emit = Collect(Vec::new()); + let len = env + .prog + .arch() + .translate() + .one_instruction(&mut emit, &Address::new(Rc::clone(&env.code), addr)) + .map_err(|e| Halt::Unsupported(format!("lift at {addr:#x}: {}", e.explain())))?; + let insn = Rc::new(Insn { len: len.max(1) as u64, ops: emit.0 }); + env.insns.borrow_mut().insert(addr, Rc::clone(&insn)); + Ok(insn) +} + +fn space(vn: &VarnodeData) -> Result<&Rc, Halt> { + vn.space.as_ref().ok_or_else(|| Halt::Harness("varnode without a space".into())) +} + +fn read(state: &mut State, vn: &VarnodeData) -> Result { + let spc = space(vn)?; + if spc.get_type() == spacetype::IPTR_CONSTANT { + return Ok(u128::from(vn.offset) & mask(vn.size)); + } + state.read(spc, vn.offset, vn.size) +} + +fn write(state: &mut State, vn: &VarnodeData, val: u128) -> Result<(), Halt> { + state.write(space(vn)?, vn.offset, vn.size, val) +} + +fn mem_space(env: &Env, vn: &VarnodeData) -> Result, Halt> { + vn.get_space_from_const(env.prog.arch().manage()) + .ok_or_else(|| Halt::Harness("bad LOAD/STORE space id".into())) +} + +/// User ops that only switch the instruction set for the next instruction. Before +/// the function's exit they change nothing either side can observe; before a +/// branch inside the function they would change the decode, which is refused +/// unless the target already decodes in the mode switched to. +pub const EXIT_ONLY_USEROPS: &[&str] = &["setISAMode"]; + +/// User ops with no effect on one thread's values: memory barriers, x86's +/// `lock` prefix, ARM's exclusive monitor, which one thread always holds, and +/// Cortex-M's interrupt masks and base priority, which no read sees changed. +pub const NO_EFFECT_USEROPS: &[&str] = &[ + "LOCK", + "UNLOCK", + "DataMemoryBarrier", + "DataSynchronizationBarrier", + "InstructionSynchronizationBarrier", + "ExclusiveAccess", + "ClearExclusiveLocal", + "setBasePriority", + "enableIRQinterrupts", + "disableIRQinterrupts", + "enableFIQinterrupts", + "disableFIQinterrupts", + "setThreadModePrivileged", +]; + +/// User ops that answer a question about the processor's state with a value +/// both sides read alike: ARM's `strex` asks whether this thread still holds +/// the exclusive monitor (one thread always does), and Cortex-M's `mrs` reads +/// a system register. The code runs privileged; the masks, base priority and +/// exception number read 0, and writes to them (`NO_EFFECT_USEROPS`) change +/// nothing either side reads back. +pub const CONSTANT_USEROPS: &[(&str, u128)] = &[ + ("hasExclusiveAccess", 1), + ("isCurrentModePrivileged", 1), + ("isThreadModePrivileged", 1), + ("getBasePriority", 0), + ("getCurrentExceptionNumber", 0), + ("isIRQinterruptsEnabled", 0), + ("isFIQinterruptsEnabled", 0), +]; + +pub fn constant_userop(name: &str) -> Option { + CONSTANT_USEROPS.iter().find(|(n, _)| *n == name).map(|&(_, v)| v) +} + +/// Whether code at `target` decodes in instruction-set mode `mode` (ARM's +/// `TMode`, 1 for Thumb): a switch to the mode the target is in anyway, as +/// every `bx` on a Thumb-only core is, changes nothing. +fn decodes_in(env: &Env, target: u64, mode: Option) -> bool { + let Some(mode) = mode else { return false }; + let at = Address::new(Rc::clone(&env.code), target & !1); + env.prog.arch().with_context_db(|db| { + let Ok(var) = db.get_variable(b"TMode") else { return false }; + let word = var.get_word() as usize; + let mask = var.get_mask() << var.get_shift(); + db.get_context(&at).get(word).is_some_and(|w| u128::from((w & mask) >> var.get_shift()) == mode & 1) + }) +} + +/// How far past a call a callee may return: a delay slot (MIPS, SPARC) puts +/// the return address one instruction further. +const RETURN_SLACK: u64 = 8; + +/// How far from the call's a callee's stack pointer may be when it returns +/// (`_chkstk`-style probes move it); further, it switched stacks. +const STACK_SWITCH: u64 = 1 << 20; + +/// How the machine run ended. +#[derive(Clone)] +pub struct Outcome<'e, 'p> { + pub state: State<'e, 'p>, + /// Every indirect branch target taken inside the image. + pub indirect: Vec, + pub calls: Vec, + /// The run ended in a call kuna says does not return. + pub noreturn: bool, + pub(crate) copy_operands: Option, + pub(crate) bad_return: Option, + /// It ended in one only kuna says does not return: no known name, no + /// layout evidence, and no in-image callee that ran to its return. + pub unverified_noreturn: bool, + /// Calls kuna does not make that the machine ran for real: call address + /// and callee. + pub followed: Vec<(u64, u64)>, + /// Register offsets a callee changed against the calling convention. + pub convention: Vec<(u64, u64)>, + /// An in-image callee given a frame object got the stub's guessed effect. + pub guessed: bool, + /// A stubbed call killed registers kuna's IR says the callee preserves: + /// kuna's word for them is unchecked. + pub narrowed: bool, + /// System calls and traps, in order. + pub events: Vec, + /// Every call site the run reached, a discarded callee run's included. + pub sites_reached: Vec, +} + +struct Machine<'e, 'p, 'c> { + env: &'e Env<'p>, + calls: &'c Calls, + /// Stubs given so far: a callee that ran to its return through one may + /// only have returned because the stub did. + stubs: u32, + unverified_noreturn: bool, + /// A callee run for real reached a call that does not return by its + /// definition. + proved_noreturn: bool, + /// A callee runs to test kuna's no-return claim: a call it makes through + /// a PLT stub that leads out of the code is a call out of the image. + checking_noreturn: bool, + state: State<'e, 'p>, + records: Vec, + indirect: Vec, + followed: Vec<(u64, u64)>, + steps: u64, + budget: u64, + /// Steps left for callees run for real; theirs do not count against the + /// function's budget, which the decompiled side never spends on them. + callee_pool: u64, + in_callee: bool, + /// Where each enclosing call returns, innermost last. + returns: Vec, + /// System calls and traps, in order. + events: Vec, + /// Argument bytes to give one call's callee instead of the + /// machine's own: kuna's, to see whether the callee cares. + with_args: Option<&'c WithArgs>, + stop_before: Option, + /// An in-image callee given a frame object fell back to the stub. + guessed: bool, + narrowed: bool, + /// Temporaries this instruction copied a callee-saved entry value to: + /// (temporary offset, register offset, size). + copies: Vec<(u64, u64, u32)>, + /// Temporaries this instruction loaded a spilled entry value into, with + /// the register it came from, until a copy restores it. + restoring: Vec<(u64, u64)>, + /// Register offsets a callee run for real changed although the calling + /// convention says the call preserves them, by call address. + convention: Vec<(u64, u64)>, + sites_reached: Vec, +} + +/// The state restored when a concrete execution is discarded. Steps spent +/// and the remaining callee budget belong to the enclosing run. +struct MachineCheckpoint<'e, 'p> { + state: State<'e, 'p>, + records: usize, + indirect: usize, + followed: usize, + events: usize, + convention: usize, + stubs: u32, + unverified_noreturn: bool, + proved_noreturn: bool, + guessed: bool, + narrowed: bool, + copies: Vec<(u64, u64, u32)>, + restoring: Vec<(u64, u64)>, +} + +impl<'e, 'p> MachineCheckpoint<'e, 'p> { + fn new(m: &Machine<'e, 'p, '_>) -> Self { + Self { + state: m.state.clone(), + records: m.records.len(), + indirect: m.indirect.len(), + followed: m.followed.len(), + events: m.events.len(), + convention: m.convention.len(), + stubs: m.stubs, + unverified_noreturn: m.unverified_noreturn, + proved_noreturn: m.proved_noreturn, + guessed: m.guessed, + narrowed: m.narrowed, + copies: m.copies.clone(), + restoring: m.restoring.clone(), + } + } + + fn restore(self, m: &mut Machine<'e, 'p, '_>) { + m.state = self.state; + m.records.truncate(self.records); + m.indirect.truncate(self.indirect); + m.followed.truncate(self.followed); + m.events.truncate(self.events); + m.convention.truncate(self.convention); + m.stubs = self.stubs; + m.unverified_noreturn = self.unverified_noreturn; + m.proved_noreturn = self.proved_noreturn; + m.guessed = self.guessed; + m.narrowed = self.narrowed; + m.copies = self.copies; + m.restoring = self.restoring; + } +} + +impl<'e, 'p, 'c> Machine<'e, 'p, 'c> { + fn new(env: &'e Env<'p>, calls: &'c Calls, run: u32, budget: u64, with_args: Option<&'c WithArgs>, stop_before: Option) -> Self { + Self { + with_args, + stop_before, + env, + calls, + state: State::new(env, run), + records: Vec::new(), + indirect: Vec::new(), + followed: Vec::new(), + steps: 0, + budget, + callee_pool: budget, + in_callee: false, + returns: Vec::new(), + events: Vec::new(), + guessed: false, + narrowed: false, + stubs: 0, + unverified_noreturn: false, + proved_noreturn: false, + checking_noreturn: false, + copies: Vec::new(), + restoring: Vec::new(), + convention: Vec::new(), + sites_reached: Vec::new(), + } + } + + fn sp(&self) -> Storage { + Storage::new(&self.env.register, self.env.sp.0, self.env.sp.1) + } + + /// An argument's value at the call. + fn arg(&mut self, a: &crate::calls::Arg) -> Result { + if !a.callee_frame { + return self.state.read_storage(&a.storage.space, a.storage.off, a.storage.size); + } + let mut acc = 0u128; + for p in a.storage.pieces(self.env.prog) { + let v = if p.space.get_type() == spacetype::IPTR_SPACEBASE { + let base = self.sp_value()?; + let ram = Rc::clone(&self.env.ram); + self.state.read(&ram, ram.wrap_offset(base.wrapping_add(p.off)), p.size)? + } else { + self.state.read_storage(&p.space, p.off, p.size)? + }; + acc = if p.size >= 16 { v } else { (acc << (p.size * 8)) | v }; + } + Ok(acc & mask(a.storage.size)) + } + + /// Record one of the function's own calls for the comparison, with kuna's + /// arguments as the machine holds them. + fn record(&mut self, at: u64, target: Option, indirect: bool) -> Result, Halt> { + if !self.sites_reached.contains(&at) { + self.sites_reached.push(at); + } + let site = self.calls.site(at).clone(); + let mut args = Vec::with_capacity(site.args.len()); + for a in &site.args { + args.push(match a { + Some(a) => self.arg(a)?, + None => 0, + }); + } + let mut given: Vec = args.iter().zip(&site.args).filter(|(_, a)| a.is_some()).map(|(&v, _)| v).collect(); + for st in &self.calls.pointer_regs { + given.push(self.state.read_storage(&st.space, st.off, st.size)?); + } + let mut whole = Vec::with_capacity(site.input_storage.len()); + for (i, a) in site.input_storage.iter().enumerate() { + let st = match site.args.get(i).and_then(Option::as_ref) { + Some(a) => (!a.callee_frame).then_some(&a.storage), + None => a.as_ref(), + }; + let r = st.and_then(|st| self.calls.int_regs.iter().find(|r| r.covers(st) && r.size > st.size)); + let live = self.state.live.take(); + whole.push(r.and_then(|r| Some((r.clone(), self.state.read_storage(&r.space, r.off, r.size).ok()?)))); + self.state.live = live; + } + let writes = self.state.writes_at_call(&given, target.is_some_and(|t| self.env.code_mapped(t))); + let r = Record { at, target, indirect, args: args.clone(), writes, effect: None, frame_reads: None, live_in: None, stack_in: None, whole }; + crate::calls::record(&mut self.records, r)?; + if let Some(o) = self.with_args.filter(|o| o.call == Some(self.records.len() - 1)) { + let register = std::rc::Rc::clone(&self.env.register); + for &(off, b) in &o.bytes { + self.state.write(®ister, off, 1, u128::from(b))?; + } + } + Ok(args) + } + + /// One of the function's tail calls: record it, then run an in-image + /// callee for real or give it the stub. The function then returns. + /// Whether `target` does not return by its definition (`known_noreturn`), + /// reading `error`'s `status` from the convention's first argument register. + fn known_noreturn(&mut self, target: u64) -> Result { + let kind = noreturn_name(self.env, target); + let first = match self.calls.int_regs.first().filter(|_| kind == crate::calls::NameNoReturn::IfStatus) { + Some(r) => { + let live = self.state.live.take(); + let v = self.state.read_storage(&r.space, r.off, r.size); + self.state.live = live; + Some(v?) + } + None => None, + }; + Ok(kind.with_status(first)) + } + + /// For a call kuna says does not return: `None` when the machine stops + /// there too, or the callee's exit when it ran for real and returned + /// without a stub on the way, so kuna's claim is false. The machine stops + /// on evidence of its own (a known name, the layout) or, with none, on + /// kuna's word, which the run records. + fn stops_at(&mut self, at: u64, target: u64, args: &[u128]) -> Result, Halt> { + let site = self.calls.site(at); + if site.laid_out_noreturn { + return Ok(None); + } + if noreturn_name(self.env, target).with_status(args.first().copied()) { + return Ok(None); + } + if self.env.code_mapped(target & !1) && !leads_out(self.env, target) && !self.in_callee { + let saved = MachineCheckpoint::new(self); + self.proved_noreturn = false; + self.checking_noreturn = true; + let ran = self.real(at, target); + self.checking_noreturn = false; + let ran = ran?; + if let Some(e @ Exit::Return) = ran.filter(|_| self.stubs == saved.stubs) { + return Ok(Some(e)); + } + let proved = self.proved_noreturn; + saved.restore(self); + if let Some(r) = self.records.last_mut() { + r.effect = None; + r.frame_reads = None; + r.live_in = None; + r.stack_in = None; + } + if proved { + return Ok(None); + } + } + self.unverified_noreturn = true; + Ok(None) + } + + fn tail_call(&mut self, at: u64, target: u64, indirect: bool) -> Result { + let args = self.record(at, Some(target), indirect)?; + if self.calls.site(at).noreturn { + return Ok(match self.stops_at(at, target, &args)? { + Some(_) => Exit::Return, + None => Exit::NoReturn, + }); + } + let in_image = self.env.code_mapped(target); + if in_image { + match self.real(at, target)? { + Some(e @ Exit::Unwind(_)) => return Ok(e), + Some(_) => return Ok(Exit::Return), + None => {} + } + } + self.guess_if_frame(in_image, &args); + self.stub(at, &args)?; + Ok(Exit::Return) + } + + /// Record a call and give it the stub's effect. `true` when it does not + /// return. + fn call(&mut self, at: u64, target: Option, indirect: bool) -> Result { + let args = self.record(at, target, indirect)?; + if self.calls.site(at).noreturn { + return Ok(true); + } + self.stub(at, &args)?; + Ok(false) + } + + /// An in-image callee the model could not run gets the stub, whose effect + /// on a frame object it was given is a guess where kuna may know better + /// (a callee that only reads it): differences after it are doubtful. + fn guess_if_frame(&mut self, in_image: bool, args: &[u128]) { + if in_image && args.iter().any(|&a| self.env.in_stack(a as u64, 1) && self.env.stack_object(a as u64).is_some()) { + self.guessed = true; + } + } + + /// The stub's effect: kill, let the arguments escape, pop the stack. + fn stub(&mut self, at: u64, args: &[u128]) -> Result<(), Halt> { + self.stubs += 1; + let site = self.calls.site(at).clone(); + let pop = site.extrapop.ok_or_else(|| Halt::Unsupported(format!("call at {at:#x} with unknown stack cleanup")))?; + if site.killed != site.abi_killed { + self.narrowed = true; + } + let killed = if self.env.stub_recovered.get() { &site.killed } else { &site.abi_killed }; + self.state.call(killed, args, site.ret_ext.as_ref()); + let sp = self.sp(); + let v = self.state.read(&sp.space, sp.off, sp.size)?; + let after = v.wrapping_add(pop as i64 as u128) & mask(sp.size); + self.state.write(&sp.space, sp.off, sp.size, after)?; + self.state.forget_below(after as u64); + Ok(()) + } + + /// The callee-saved register whose entry value `vn` holds: the register + /// itself, or a temporary this instruction copied it to. + fn entry_value_of(&self, vn: &VarnodeData) -> Option { + let env = self.env; + let sp = space(vn).ok()?; + if sp.get_index() != env.register.get_index() { + return self.copies.iter().find(|&&(u, _, n)| u == vn.offset && n == vn.size).map(|&(_, r, _)| r); + } + let saved = vn.offset != env.sp.0 + && !self.calls.default.killed.iter().any(|&(o, n)| vn.offset < o + u64::from(n) && o < vn.offset + u64::from(vn.size)) + && !self.state.wrote(&env.register, vn.offset, vn.size); + saved.then_some(vn.offset) + } + + /// A load of spilled entry values reads them as a value unless it restores + /// the register they came from, directly or through a temporary this + /// instruction then copies there. + fn note_load(&mut self, at: u64, out: &VarnodeData) { + let regs = self.state.saved_in(at, out.size); + let [reg] = regs[..] else { + self.state.read_saved |= !regs.is_empty(); + return; + }; + match space(out).map(|s| s.get_type()) { + Ok(spacetype::IPTR_INTERNAL) => self.restoring.push((out.offset, reg)), + _ => self.state.read_saved |= out.offset != reg, + } + } + + /// A stack store of a callee-saved register's entry value: the register. + fn spill_of_entry(&self, spc: &AddrSpace, at: u64, val: &VarnodeData) -> Option { + let env = self.env; + if spc.get_index() != env.ram.get_index() || !env.in_stack(at, u64::from(val.size)) { + return None; + } + self.entry_value_of(val) + } + + /// The stack pointer's value now. + fn sp_value(&mut self) -> Result { + let sp = self.sp(); + Ok(self.state.read(&sp.space, sp.off, sp.size)? as u64) + } + + fn continuation(&self, at: u64, target: u64, sp: u64, insn: &Insn) -> Continuation { + let verify = self.env.ret_addr.is_some() && insn.ops.iter().any(|op| match op.opc { + OpCode::CPUI_CALL => true, + OpCode::CPUI_CALLIND => self.env.is_entry(target), + _ => false, + }); + Continuation { at: at.wrapping_add(insn.len), sp, verify } + } + + /// The function's call at `at` returned from a callee run for real: keep + /// what it did for the decompiled side to replay. Writes into the callee's + /// own frame, below the stack pointer at the call, are dead and dropped. + fn close_effect(&mut self, at: u64, call_sp: u64) { + let Some(events) = self.state.log.take() else { return }; + let env = self.env; + let ram = env.ram.get_index(); + let events = events + .into_iter() + .filter(|ev| match ev { + crate::state::Event::Write(sp, off, _) => !(*sp == ram && env.in_stack(*off, 1) && *off < call_sp), + crate::state::Event::Call(..) => true, + }) + .collect(); + let killed = self.calls.site(at).killed.clone(); + let regs = self.state.register_bytes(&killed); + if let Some(r) = self.records.last_mut() { + r.effect = Some(crate::state::Effect { events, regs }); + } + } + + /// Run the callee of the function's call at `at` for real and keep its + /// effect for the decompiled side. `None`, with nothing changed, when the + /// callee does something the model cannot run or outruns its budget: the + /// call then gets the stub. + fn real(&mut self, at: u64, target: u64) -> Result, Halt> { + let outer = !self.in_callee; + let limit = if outer { CALLEE_STEPS.min(self.callee_pool) } else { CALLEE_STEPS }; + if limit == 0 { + return Ok(None); + } + let saved = MachineCheckpoint::new(self); + let (steps, budget) = (self.steps, self.budget); + let call_sp = self.sp_value()?; + let back = lift(self.env, at).ok().map(|i| self.continuation(at, target, call_sp, &i)); + if outer { + self.state.frame_reads = Some(crate::state::FrameReads::default()); + let mut live = crate::state::LiveIn::new(self.calls.input_regs.clone()); + if back.is_some_and(|c| c.verify) { + live.stack = crate::state::StackInputs::new(self.env, self.calls.site(at), call_sp); + } + if let Some(stack) = &live.stack { + if let Some(args) = self.with_args.filter(|o| o.call == saved.records.checked_sub(1)) { + for &(off, b) in &args.stack_bytes { + if stack.contains(off, 1) { + self.state.write(&self.env.ram, call_sp + off, 1, u128::from(b))?; + } + } + } + } + self.state.live = Some(live); + } + self.state.log = Some(Vec::new()); + self.budget = if outer { steps + limit } else { budget.min(steps + limit) }; + self.in_callee = true; + let ran = exec(self, target, Mode::Opaque, 1, back); + self.in_callee = !outer; + let reads = if outer { self.state.frame_reads.take() } else { None }; + let (live, stack) = if outer { + self.state.live.take().map(|mut l| { + l.instruction(); + (Some(l.read.into_iter().collect::>()), l.stack) + }).unwrap_or_default() + } else { + (None, None) + }; + self.budget = budget; + if outer { + self.callee_pool -= (self.steps - steps).min(self.callee_pool); + self.steps = steps; + } + match ran { + Err(h @ Halt::UnexpectedReturn(_)) => Err(h), + Err(Halt::Budget) if !outer && self.steps > budget => Err(Halt::Budget), + Ok(exit @ (Exit::Return | Exit::Leave | Exit::Unwind(_))) => { + let site = self.calls.site(at); + let changed = if matches!(exit, Exit::Return) && self.env.keep_clobbers.get() { + Vec::new() + } else if matches!(exit, Exit::Return) { + let sp = self.env.sp; + let regs: Vec<(u64, u32)> = site.preserved.iter().copied().filter(|&(o, s)| o + u64::from(s) <= sp.0 || o >= sp.0 + u64::from(sp.1)).collect(); + self.state.restore_registers(&saved.state, ®s) + } else { + let mut keep = site.abi_killed.clone(); + keep.push(self.env.sp); + self.state.preserve_registers(&saved.state, &keep) + }; + for o in changed { + if !self.convention.contains(&(at, o)) { + self.convention.push((at, o)); + } + } + self.close_effect(at, call_sp); + let sp = self.sp_value()?; + if let Some(r) = self.records.last_mut() { + r.frame_reads = reads; + r.live_in = live; + r.stack_in = stack.filter(|_| matches!(exit, Exit::Return) && self.stubs == saved.stubs && sp == call_sp + 4); + } + self.state.forget_below(sp.min(call_sp.wrapping_add(u64::from(self.env.ret_slot)))); + Ok(Some(exit)) + } + outcome => { + let proved = self.checking_noreturn && self.proved_noreturn && matches!(outcome, Ok(Exit::NoReturn)); + saved.restore(self); + self.proved_noreturn |= proved; + Ok(None) + } + } + } + + fn finish(self, exit: Exit) -> Outcome<'e, 'p> { + Outcome { + state: self.state, + indirect: self.indirect, + calls: self.records, + noreturn: matches!(exit, Exit::NoReturn), + copy_operands: match exit { + Exit::Checkpoint(operands) => Some(operands), + _ => None, + }, + bad_return: match exit { + Exit::BadReturn { at, target } => Some(wrong_return(at, target)), + _ => None, + }, + unverified_noreturn: self.unverified_noreturn, + followed: self.followed, + guessed: self.guessed, + narrowed: self.narrowed, + events: self.events, + convention: self.convention, + sites_reached: self.sites_reached, + } + } +} + +fn branch( + env: &Env, + state: &mut State, + target: &VarnodeData, + i: &mut usize, + addr: &mut u64, + insn: &mut Rc, +) -> Result<(), Halt> { + if space(target)?.get_type() == spacetype::IPTR_CONSTANT { + *i = (target.offset as u32).wrapping_add(*i as u32) as i32 as usize; + if *i > insn.ops.len() { + return Err(Halt::Harness("bad intra-instruction branch".into())); + } + } else { + *addr = target.offset; + *insn = lift(env, *addr)?; + *i = 0; + state.end_instruction(); + } + Ok(()) +} + +/// What the name of the function `target` leads to, directly or through +/// thunks, says about whether it returns; cached per target in `env`. +fn noreturn_name(env: &Env, target: u64) -> crate::calls::NameNoReturn { + if let Some(&k) = env.noreturn_names.borrow().get(&target) { + return k; + } + let prog = env.prog; + let k = prog + .function_named_at(target) + .or_else(|| prog.function_named_at(through_thunks(env, target))) + .map_or(crate::calls::NameNoReturn::No, |name| crate::calls::NameNoReturn::of(&name)); + env.noreturn_names.borrow_mut().insert(target, k); + k +} + +/// Steps a callee run for real may take before the call falls back to a stub. +const CALLEE_STEPS: u64 = 50_000; + +/// Calls nested inside a callee run for real. +const MAX_DEPTH: u32 = 32; + +/// How an execution ended. +#[derive(Clone, Copy)] +enum Exit { + Return, + NoReturn, + Checkpoint(CopyOperands), + BadReturn { at: u64, target: u64 }, + /// A callee returned to where an enclosing call returns (libgcc's float + /// routines reach a shared tail with `bl` and pop their caller's frame): + /// every frame up to that call's ends. + Unwind(u64), + /// A callee returned straight to the function's caller (a trampoline). + Leave, +} + +/// What is executing: the function itself, a callee kuna inlined or dropped +/// (its calls are kuna's too), or a callee run for real that kuna only calls. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Mode { + Top, + Inline, + Opaque, +} + +#[derive(Clone, Copy)] +struct Continuation { + at: u64, + sp: u64, + verify: bool, +} + +/// Execute from `entry` until a RETURN. `top` is the function itself: only its +/// calls are recorded and compared, and only it has tail calls and an exit +/// through the random return address. Anywhere else is a callee run for real. +/// `back` is where a callee should return, just past the call that entered +/// it, and the stack pointer at that call. A callee that returns elsewhere, +/// into other code of the image or on another stack (an RTOS's context switch +/// to another thread, a `longjmp`), did not return to its caller, and the +/// model cannot follow it. A return elsewhere on the same stack outside the +/// image (a pointer authentication the model does not run, eBPF's `exit`) is +/// taken as a return, as before. +fn exec(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option) -> Result { + let outer = m.state.in_callee_code; + m.state.in_callee_code = mode != Mode::Top; + if let Some(back) = back { + m.returns.push(back.at & !1); + } + let exit = exec_body(m, entry, mode, depth, back); + if back.is_some() { + m.returns.pop(); + } + m.state.in_callee_code = outer; + exit.map(|e| match (e, back) { + (Exit::Unwind(t), Some(back)) if returns_to(t, back.at) => Exit::Return, + (e, _) => e, + }) +} + +/// Whether a return to `target` is a return to `back`, a call's fallthrough. +fn returns_to(target: u64, back: u64) -> bool { + (target & !1).wrapping_sub(back & !1) <= RETURN_SLACK +} + +fn wrong_return(at: u64, target: u64) -> Halt { + Halt::Unsupported(format!("return at {at:#x} to {target:#x}, not to the return address, where kuna returns")) +} + +fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option) -> Result { + let top = mode == Mode::Top; + if depth > MAX_DEPTH { + return Err(Halt::Unsupported("calls nested too deep".into())); + } + let env = m.env; + let calls = m.calls; + let entry_stubs = m.stubs; + let mut addr = entry; + let mut insn = lift(env, addr)?; + let mut i = 0usize; + let mut mode_switch: Option<(String, Option)> = None; + let mut called_here = false; + let mut previous_addr = None; + loop { + if top { + if let Some(stop) = m.stop_before.as_mut() { + if i == 0 && addr == stop.at && previous_addr != Some(addr) { + stop.visit -= 1; + if stop.visit == 0 { + return rep_copy::operands(&mut m.state, addr, &insn).map(Exit::Checkpoint); + } + } + previous_addr = Some(addr); + } + } + if i >= insn.ops.len() { + addr = env.code.wrap_offset(addr.wrapping_add(insn.len)); + insn = lift(env, addr)?; + i = 0; + m.state.end_instruction(); + m.steps += 1; + if m.steps > m.budget { + return Err(Halt::Budget); + } + continue; + } + m.steps += 1; + if m.steps > m.budget { + return Err(Halt::Budget); + } + if i == 0 { + called_here = false; + m.copies.clear(); + m.state.read_saved |= !m.restoring.is_empty(); + m.restoring.clear(); + if let Some(l) = m.state.live.as_mut() { + l.instruction(); + } + } + if let Some(l) = m.state.live.as_mut() { + l.op(); + } + let cur = Rc::clone(&insn); + let op = &cur.ops[i]; + let arg = |k: usize| op.ins.get(k).ok_or_else(|| Halt::Harness(format!("{} lacks input {k}", get_opname(op.opc)))); + let tail = |at: u64, t: u64| top && !called_here && calls.tail(at, t); + match op.opc { + OpCode::CPUI_BRANCH => { + let t = arg(0)?; + let relative = space(t)?.get_type() == spacetype::IPTR_CONSTANT; + if !relative && tail(addr, t.offset) { + return m.tail_call(addr, t.offset, false); + } + if let Some((name, _)) = mode_switch.take().filter(|(_, v)| !relative && !decodes_in(env, t.offset, *v)) { + return Err(Halt::Unsupported(format!("CALLOTHER {name} before a branch at {addr:#x}"))); + } + branch(env, &mut m.state, t, &mut i, &mut addr, &mut insn)?; + } + OpCode::CPUI_CBRANCH => { + let c = read(&mut m.state, arg(1)?)?; + if c != 0 { + let t = arg(0)?; + if space(t)?.get_type() != spacetype::IPTR_CONSTANT && tail(addr, t.offset) { + return m.tail_call(addr, t.offset, false); + } + branch(env, &mut m.state, t, &mut i, &mut addr, &mut insn)?; + } else { + i += 1; + } + } + OpCode::CPUI_BRANCHIND => { + let target = read(&mut m.state, arg(0)?)? as u64; + if tail(addr, target) { + return m.tail_call(addr, target, true); + } + if !top && back.as_ref().is_some_and(|c| returns_to(target, c.at)) { + return Ok(Exit::Return); + } + if top && !env.code_mapped(target) { + if env.ret_addr.is_none_or(|r| r == target) { + return Ok(Exit::Return); + } + return Err(Halt::Unsupported(format!( + "indirect jump at {addr:#x} out of the image to {target:#x}, not to the return address, and kuna makes no call there" + ))); + } + if top { + m.indirect.push(target); + } + if let Some((name, _)) = mode_switch.take().filter(|(_, v)| !decodes_in(env, target, *v)) { + return Err(Halt::Unsupported(format!("CALLOTHER {name} before a branch at {addr:#x}"))); + } + addr = target; + insn = lift(env, addr)?; + i = 0; + m.state.end_instruction(); + } + OpCode::CPUI_RETURN => { + let target = read(&mut m.state, arg(0)?)? as u64; + if env.ret_addr == Some(target) { + return Ok(if top { Exit::Return } else { Exit::Leave }); + } + if !top { + if let Some(Continuation { at: b, sp: call_sp, verify }) = back { + if depth == 1 && target != b { + if let Some(live) = m.state.live.as_mut() { + live.stack = None; + } + } + let elsewhere = !returns_to(target, b); + let sp = m.sp_value()?; + let switched = sp.wrapping_sub(call_sp).wrapping_add(STACK_SWITCH) > 2 * STACK_SWITCH; + if elsewhere && !switched && m.returns.iter().rev().skip(1).any(|&r| returns_to(target, r)) { + return Ok(Exit::Unwind(target)); + } + if elsewhere && (switched || env.code_mapped(target & !1)) { + return Err(Halt::Unsupported(format!("a callee returned to {target:#x}, not to {b:#x} after its call"))); + } + if elsewhere && verify && m.stubs == entry_stubs { + return Err(Halt::UnexpectedReturn(format!( + "a callee returned to unmapped address {target:#x}; its call resumes at {b:#x}" + ))); + } + } + return Ok(Exit::Return); + } + if tail(addr, target) { + return m.tail_call(addr, target, true); + } + if !calls.branches.contains(&addr) || !env.code_mapped(target) { + if env.ret_addr.is_none() { + return Ok(Exit::Return); + } + if m.records.is_empty() { + return Err(wrong_return(addr, target)); + } + if m.stubs == entry_stubs { + return Ok(Exit::BadReturn { at: addr, target }); + } + return Ok(Exit::Return); + } + addr = target; + insn = lift(env, addr)?; + i = 0; + m.state.end_instruction(); + } + OpCode::CPUI_CALL | OpCode::CPUI_CALLIND => { + let target = if op.opc == OpCode::CPUI_CALL { + arg(0)?.offset + } else { + read(&mut m.state, arg(0)?)? as u64 + }; + let indirect = op.opc == OpCode::CPUI_CALLIND; + let own = mode != Mode::Opaque && calls.known(addr); + if indirect && mode != Mode::Opaque && !own && calls.jumps.contains(&addr) { + addr = target; + insn = lift(env, addr)?; + i = 0; + m.state.end_instruction(); + continue; + } + let in_image = env.code_mapped(target) && !(m.checking_noreturn && leads_out(env, target)); + if own { + let args = m.record(addr, Some(target), indirect)?; + if calls.site(addr).noreturn { + match m.stops_at(addr, target, &args)? { + None => return Ok(Exit::NoReturn), + Some(_) => { + called_here = true; + i += 1; + continue; + } + } + } + match if in_image { m.real(addr, target)? } else { None } { + Some(e @ (Exit::Leave | Exit::Unwind(_))) => return Ok(e), + Some(_) => {} + None => { + m.guess_if_frame(in_image, &args); + m.stub(addr, &args)? + } + } + } else if mode == Mode::Opaque && m.known_noreturn(target)? { + m.proved_noreturn = true; + return Ok(Exit::NoReturn); + } else if in_image { + if top && !m.followed.contains(&(addr, target)) { + m.followed.push((addr, target)); + } + let inner = if mode == Mode::Opaque { Mode::Opaque } else { Mode::Inline }; + let sp = m.sp_value()?; + let back = Some(m.continuation(addr, target, sp, &insn)); + match exec(m, target, inner, depth + 1, back)? { + Exit::NoReturn => return Ok(Exit::NoReturn), + e @ (Exit::Leave | Exit::Unwind(_)) => return Ok(e), + Exit::Return => {} + Exit::Checkpoint(_) | Exit::BadReturn { .. } => unreachable!("only the top frame can stop here"), + } + } else if mode != Mode::Opaque { + if m.call(addr, Some(target), indirect)? { + return Ok(Exit::NoReturn); + } + } else { + m.stub(addr, &[])?; + } + called_here = true; + i += 1; + } + OpCode::CPUI_CALLOTHER => { + let name = crate::program::userop_name(env.prog, arg(0)?.offset); + let system = crate::calls::SYSTEM_USEROPS.contains(&name.as_str()); + let trap = crate::calls::TRAP_USEROPS.contains(&name.as_str()); + if (system && mode != Mode::Opaque) || (trap && top) { + let mut ins = Vec::with_capacity(op.ins.len().saturating_sub(1)); + for vn in op.ins.iter().skip(1) { + ins.push(read(&mut m.state, vn)?); + } + let k = m.events.len(); + let file = if system { m.state.register_file_with(&crate::calls::SyscallAbi::of(env.prog).inputs) } else { m.state.register_file() }; + m.events.push(crate::calls::UserEvent { at: addr, name, ins, file }); + if trap { + return Ok(Exit::NoReturn); + } + let run = m.state.run; + if let Some(out) = op.out.as_ref() { + write(&mut m.state, out, crate::calls::userop_value(run, k, out.size))?; + } else if env.kernel.get() { + let abi = crate::calls::SyscallAbi::of(env.prog); + if let Some(r) = abi.result.as_ref().filter(|_| !abi.inputs.is_empty()) { + m.state.write_storage(&r.space, r.off, r.size, crate::calls::userop_value(run, k, r.size))?; + } + if let Some(e) = abi.error.as_ref() { + m.state.write_storage(&e.space, e.off, e.size, crate::calls::syscall_error_value(run, k, e.size))?; + } + } + i += 1; + continue; + } + if op.out.is_none() && NO_EFFECT_USEROPS.contains(&name.as_str()) { + i += 1; + continue; + } + if let (Some(out), Some(v)) = (op.out.as_ref(), constant_userop(&name)) { + write(&mut m.state, out, v)?; + i += 1; + continue; + } + if !(op.out.is_none() && EXIT_ONLY_USEROPS.contains(&name.as_str())) { + return Err(Halt::Unsupported(format!("CALLOTHER {name} at {addr:#x}"))); + } + let to = match op.ins.get(1) { + Some(vn) => Some(read(&mut m.state, vn)?), + None => None, + }; + mode_switch = Some((name, to)); + i += 1; + } + OpCode::CPUI_LOAD => { + let spc = mem_space(env, arg(0)?)?; + let ptr = read(&mut m.state, arg(1)?)? as u64; + let at = spc.wrap_offset(AddrSpace::address_to_byte(ptr, spc.get_word_size())); + let out = op.out.as_ref().ok_or_else(|| Halt::Harness("LOAD without output".into()))?; + let v = if spc.get_type() == spacetype::IPTR_CONSTANT { + u128::from(ptr) & mask(out.size) + } else { + if spc.get_index() == env.ram.get_index() { + m.note_load(at, out); + } + m.state.read(&spc, at, out.size)? + }; + write(&mut m.state, out, v)?; + i += 1; + } + OpCode::CPUI_STORE => { + let spc = mem_space(env, arg(0)?)?; + let ptr = read(&mut m.state, arg(1)?)? as u64; + let at = spc.wrap_offset(AddrSpace::address_to_byte(ptr, spc.get_word_size())); + let val = arg(2)?; + if let Some(l) = m.state.live.as_mut() { + l.op(); + } + let v = read(&mut m.state, val)?; + if spc.get_index() == env.ram.get_index() && env.in_stack(at, u64::from(val.size)) { + let unique = space(val).is_ok_and(|s| s.get_type() == spacetype::IPTR_INTERNAL).then_some(val.offset); + if let Some(l) = m.state.live.as_mut() { + l.spilled(unique); + } + } + m.state.write(&spc, at, val.size, v)?; + if let Some(reg) = m.spill_of_entry(&spc, at, val) { + m.state.mark_saved(at, val.size, reg); + } + i += 1; + } + opc => { + let out = op.out.as_ref().ok_or_else(|| Halt::Unsupported(get_opname(opc).to_string()))?; + let mut ins = crate::value::Inputs::default(); + for vn in &op.ins { + let v = read(&mut m.state, vn)?; + ins.push((v, vn.size)); + } + let by_zero = matches!(opc, OpCode::CPUI_INT_DIV | OpCode::CPUI_INT_SDIV) + && env.divide_by_zero_is_zero + && ins.as_slice().get(1).is_some_and(|&(d, _)| d == 0); + let v = if by_zero { 0 } else { eval(opc, out.size, ins.as_slice())? }; + if opc == OpCode::CPUI_COPY { + let src = &op.ins[0]; + if space(out).is_ok_and(|s| s.get_type() == spacetype::IPTR_INTERNAL) { + if let Some(l) = m.state.live.as_mut() { + l.copied(out.offset); + } + if let Some(reg) = m.entry_value_of(src) { + m.copies.push((out.offset, reg, out.size)); + } + } else if space(src).is_ok_and(|s| s.get_type() == spacetype::IPTR_INTERNAL) { + m.restoring.retain(|&(u, r)| !(u == src.offset && r == out.offset)); + } + } + write(&mut m.state, out, v)?; + i += 1; + } + } + } +} + +/// Run the function at `entry` from the run's initial state. +/// The argument bytes the callee of the `call`-th call gets. +#[derive(Clone, Debug)] +pub struct WithArgs { + /// The call by index, or `None` for the function's own entry. + pub call: Option, + pub bytes: Vec<(u64, u8)>, + /// Stack argument bytes by offset from the callee's entry stack pointer. + pub(crate) stack_bytes: Vec<(u64, u8)>, + /// Nonzero: other values in the registers stubs kill. + pub kill_salt: u32, +} + +/// The entry to the Nth execution of a machine instruction. +#[derive(Clone, Copy)] +pub(crate) struct Checkpoint { + pub(crate) at: u64, + pub(crate) visit: usize, +} + +pub fn run<'e, 'p>( + env: &'e Env<'p>, + run: u32, + entry: u64, + budget: u64, + calls: &Calls, + with_args: Option<&WithArgs>, +) -> Result, Halt> { + run_inner(env, run, entry, budget, calls, with_args, None) +} + +pub(crate) fn run_before_copy<'e, 'p>( + env: &'e Env<'p>, + run: u32, + entry: u64, + budget: u64, + calls: &Calls, + with_args: Option<&WithArgs>, + stop: Checkpoint, +) -> Result, Halt> { + let out = run_inner(env, run, entry, budget, calls, with_args, Some(stop))?; + if out.copy_operands.is_some() { + Ok(out) + } else { + Err(Halt::Unsupported(format!("the machine did not reach copy {} at {:#x}", stop.visit, stop.at))) + } +} + +fn run_inner<'e, 'p>( + env: &'e Env<'p>, + run: u32, + entry: u64, + budget: u64, + calls: &Calls, + with_args: Option<&WithArgs>, + stop_before: Option, +) -> Result, Halt> { + let mut m = Machine::new(env, calls, run, budget, with_args, stop_before); + m.state.kill_salt = with_args.map_or(0, |o| o.kill_salt); + m.state.kill_salt_skip = calls.output_regs.clone(); + if let Some(o) = with_args.filter(|o| o.call.is_none()) { + let register = std::rc::Rc::clone(&env.register); + for &(off, b) in &o.bytes { + m.state.write(®ister, off, 1, u128::from(b))?; + } + } + let exit = exec(&mut m, entry, Mode::Top, 0, None)?; + Ok(m.finish(exit)) +} diff --git a/decompiler/crates/kuna-verify/src/machine/rep_copy.rs b/decompiler/crates/kuna-verify/src/machine/rep_copy.rs new file mode 100644 index 0000000000..6e4b7d55cd --- /dev/null +++ b/decompiler/crates/kuna-verify/src/machine/rep_copy.rs @@ -0,0 +1,106 @@ +//! The operands of x86 REP MOVS at the entry to its lifted repeat loop. + +use kuna_base::space::spacetype; +use kuna_num::opcodes::OpCode; +use kuna_num::pcoderaw::VarnodeData; + +use super::{mem_space, read, Insn, RawOp}; +use crate::state::State; +use crate::value::Halt; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) struct CopyOperands { + pub(crate) dest: u64, + pub(crate) src: u64, + pub(crate) bytes: u128, + pub(crate) backwards: bool, +} + +impl std::fmt::Display for CopyOperands { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let direction = if self.backwards { "backward" } else { "forward" }; + write!(f, "dest={:#x}, src={:#x}, {} bytes ({direction})", self.dest, self.src, self.bytes) + } +} + +fn in_space(vn: &VarnodeData, ty: spacetype) -> bool { + vn.space.as_ref().is_some_and(|space| space.get_type() == ty) +} + +fn constant(vn: &VarnodeData, value: u64) -> bool { + in_space(vn, spacetype::IPTR_CONSTANT) && vn.offset == value +} + +/// The register whose entry value supplies a memory address. The lift copies +/// the address before advancing the string register. +fn entry_pointer<'a>(ops: &'a [RawOp], index: usize) -> Option<&'a VarnodeData> { + let pointer = ops[index].ins.get(1)?; + let (register, before) = if in_space(pointer, spacetype::IPTR_INTERNAL) { + let defined = ops[..index].iter().rposition(|op| op.out.as_ref() == Some(pointer))?; + let copy = &ops[defined]; + if copy.opc != OpCode::CPUI_COPY { + return None; + } + (copy.ins.first()?, defined) + } else { + (pointer, index) + }; + if !in_space(register, spacetype::IPTR_PROCESSOR) || register.size != pointer.size { + return None; + } + let overwritten = ops[..before].iter().filter_map(|op| op.out.as_ref()).any(|out| { + let same_space = out.space.as_ref().zip(register.space.as_ref()).is_some_and(|(a, b)| a.get_index() == b.get_index()); + same_space && out.offset < register.offset + u64::from(register.size) && register.offset < out.offset + u64::from(out.size) + }); + (!overwritten).then_some(register) +} + +fn lift_operands(insn: &Insn, at: u64) -> Option<(&VarnodeData, &VarnodeData, &VarnodeData, u32)> { + let [test, guard, decrement, .., back] = insn.ops.as_slice() else { return None }; + let [count, zero] = test.ins.as_slice() else { return None }; + let [_, test_result] = guard.ins.as_slice() else { return None }; + let [previous_count, one] = decrement.ins.as_slice() else { return None }; + if test.opc != OpCode::CPUI_INT_EQUAL || !constant(zero, 0) || !in_space(count, spacetype::IPTR_PROCESSOR) + || guard.opc != OpCode::CPUI_CBRANCH || test.out.as_ref() != Some(test_result) + || decrement.opc != OpCode::CPUI_INT_SUB || decrement.out.as_ref() != Some(count) || previous_count != count || !constant(one, 1) + || back.opc != OpCode::CPUI_BRANCH || !back.ins.first().is_some_and(|target| target.offset == at && !in_space(target, spacetype::IPTR_CONSTANT)) + { + return None; + } + let mut memory = insn.ops.iter().enumerate().filter(|(_, op)| matches!(op.opc, OpCode::CPUI_LOAD | OpCode::CPUI_STORE)); + let [(src_index, load), (dest_index, store)] = [memory.next()?, memory.next()?]; + if load.opc != OpCode::CPUI_LOAD || store.opc != OpCode::CPUI_STORE || memory.next().is_some() + || load.ins.first() != store.ins.first() + { + return None; + } + let loaded = load.out.as_ref()?; + let stored = store.ins.get(2)?; + let copies_load = insn.ops[src_index + 1..dest_index].iter().any(|op| { + op.opc == OpCode::CPUI_COPY && op.ins.first() == Some(loaded) && op.out.as_ref() == Some(stored) + }); + if !matches!(loaded.size, 1 | 2 | 4 | 8) || stored.size != loaded.size || (loaded != stored && !copies_load) { + return None; + } + Some((entry_pointer(&insn.ops, dest_index)?, entry_pointer(&insn.ops, src_index)?, count, loaded.size)) +} + +pub(super) fn operands(state: &mut State, at: u64, insn: &Insn) -> Result { + let env = state.env; + let unsupported = || Halt::Unsupported(format!("cannot read REP MOVS operands at {at:#x}")); + if !env.prog.arch().archid.starts_with("x86") { + return Err(unsupported()); + } + let (dest, src, count, width) = lift_operands(insn, at).ok_or_else(unsupported)?; + let load = insn.ops.iter().find(|op| op.opc == OpCode::CPUI_LOAD).ok_or_else(unsupported)?; + if mem_space(env, &load.ins[0])?.get_index() != env.ram.get_index() { + return Err(unsupported()); + } + let df = env.prog.arch().translate().get_register_data("DF").map_err(|_| unsupported())?; + Ok(CopyOperands { + dest: env.ram.wrap_offset(read(state, dest)? as u64), + src: env.ram.wrap_offset(read(state, src)? as u64), + bytes: read(state, count)? * u128::from(width), + backwards: read(state, &df)? != 0, + }) +} diff --git a/decompiler/crates/kuna-verify/src/machine/tests.rs b/decompiler/crates/kuna-verify/src/machine/tests.rs new file mode 100644 index 0000000000..c10b5cabef --- /dev/null +++ b/decompiler/crates/kuna-verify/src/machine/tests.rs @@ -0,0 +1,37 @@ +use super::*; + +#[test] +fn failed_concrete_callee_restores_state_and_metadata() { + let image = br#" + b800300000c60001e8f30f00000f0b + e8fbfeffffc3 + + "#; + let mut store = kuna_base::xml::DocumentStorage::new(); + let root = store.parse_document(image).unwrap().get_root().clone(); + let specs = vec![format!("{}/../../../specs", env!("CARGO_MANIFEST_DIR"))]; + let prog = kuna_console::engine::bootstrap_program(root, "x86:LE:64:default:gcc", &specs).unwrap(); + let commands = vec!["load function caller".into(), "decompile".into()]; + crate::session::drive(commands, Some(prog), &specs, |prog, fd| { + let env = Env::new(prog, 0).unwrap(); + let mut calls = crate::calls::sites(fd, &env); + calls.default.killed.clear(); + let run = || { + let mut m = Machine::new(&env, &calls, 0, 1000, None, None); + let key = (env.ram.get_index(), 0x3000); + m.state.write(&env.ram, key.1, 1, 1).unwrap(); + m + }; + let mut probe = run(); + assert!(exec(&mut probe, 0x1000, Mode::Opaque, 1, None).is_err()); + assert_eq!(probe.stubs, 1); + assert!(probe.narrowed); + + let mut m = run(); + assert!(m.real(0x1100, 0x1000).unwrap().is_none()); + assert_eq!(m.stubs, 0); + assert!(!m.narrowed); + assert_eq!(m.state.epoch, 0); + assert!(m.callee_pool < 1000); + }).unwrap(); +} diff --git a/decompiler/crates/kuna-verify/src/machine/thunk.rs b/decompiler/crates/kuna-verify/src/machine/thunk.rs new file mode 100644 index 0000000000..4fd781e557 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/machine/thunk.rs @@ -0,0 +1,145 @@ +//! Thunks: where a call really goes once jumps, PLT slots and veneers are followed. + +use super::*; + +/// Where a call to `target` really goes: through a thunk (a jump, a PLT +/// slot's `jmp [got]`, an `endbr64` before it) to what it jumps to, when two +/// runs from different states reach the same place without storing or +/// calling. A target that is no thunk is its own answer. +pub fn through_thunks(env: &Env, target: u64) -> u64 { + if let Some(&t) = env.thunks.borrow().get(&target) { + return t; + } + let t = follow_thunks(env, target); + env.thunks.borrow_mut().insert(target, t); + t +} + +/// Whether `target` is a thunk that leads out of the image's code: a PLT +/// stub whose GOT slot the file leaves zero or points outside. Running it +/// would jump to no code, so its call is a call out of the image. +pub fn leads_out(env: &Env, target: u64) -> bool { + let t = through_thunks(env, target); + t != target && !env.is_code(t) +} + +/// Where a call to `target` goes through thunks that change nothing a callee +/// can see: each hop writes only temporaries and the registers the ABI keeps +/// for veneers ([`Env::scratch_regs`]), reads no register it did not write +/// itself, stores nothing and leaves the stack pointer and flags alone. So the +/// destination depends only on the code and the image's bytes, never on the +/// state at the call. A PLT slot's `jmp [got]` and a +/// plain `jmp f` are such thunks; one that sets or pushes an argument, or +/// moves the stack pointer, is not. Two calls are the same call when they +/// reach the same code this way. +pub fn transparent_target(env: &Env, target: u64) -> u64 { + if let Some(&t) = env.transparent.borrow().get(&target) { + return t; + } + let t = follow(env, target, true); + env.transparent.borrow_mut().insert(target, t); + t +} + +pub(super) fn follow_thunks(env: &Env, target: u64) -> u64 { + follow(env, target, false) +} + +pub(super) fn follow(env: &Env, target: u64, strict: bool) -> u64 { + let mut t = target; + for _ in 0..4 { + let a = thunk_hop(env, t, 0, strict); + let b = thunk_hop(env, t, 1, strict); + match (a, b) { + (Some(x), Some(y)) if x == y && x != t => t = x, + _ => break, + } + } + t +} + +/// Whether `out` is an argument register the calling convention reads. +pub(super) fn writes_argument(env: &Env, out: &VarnodeData) -> bool { + space(out).is_ok_and(|s| s.get_index() == env.register.get_index()) + && env.arg_regs.iter().any(|&(o, n)| out.offset < o + u64::from(n) && o < out.offset + u64::from(out.size)) +} + +/// Whether a `strict` hop may write `out`: a temporary or a veneer register. +pub(super) fn hidden(env: &Env, out: &VarnodeData) -> bool { + let Ok(s) = space(out) else { return false }; + s.get_type() == spacetype::IPTR_INTERNAL + || (s.get_index() == env.register.get_index() + && env.scratch_regs.iter().any(|&(o, n)| out.offset >= o && out.offset + u64::from(out.size) <= o + u64::from(n))) +} + +/// Where the thunk at `at` jumps, run from state `run`; `None` when the code +/// there stores anywhere but the stack (a lazy PLT entry pushes its index), +/// writes an argument register, calls, tests or does not jump within a few +/// instructions. `strict` also refuses every store and any write but to a +/// temporary or a scratch register ([`transparent_target`]). +pub(super) fn thunk_hop(env: &Env, at: u64, run: u32, strict: bool) -> Option { + let mut state = State::new(env, 0x7fff_0000 + run); + let mut addr = at; + let mut written: Vec<(u64, u32)> = Vec::new(); + let is_reg = |vn: &VarnodeData| space(vn).is_ok_and(|s| s.get_index() == env.register.get_index()); + for _ in 0..3 { + let insn = lift(env, addr).ok()?; + for op in &insn.ops { + if strict { + let unset = op.ins.iter().filter(|vn| is_reg(vn)).any(|vn| { + !written.iter().any(|&(o, n)| vn.offset >= o && vn.offset + u64::from(vn.size) <= o + u64::from(n)) + }); + if unset { + return None; + } + if let Some(out) = op.out.as_ref().filter(|o| is_reg(o)) { + written.push((out.offset, out.size)); + } + } + match op.opc { + OpCode::CPUI_BRANCH => { + let t = op.ins.first()?; + if space(t).ok()?.get_type() == spacetype::IPTR_CONSTANT { + return None; + } + return Some(t.offset); + } + OpCode::CPUI_BRANCHIND => return Some(read(&mut state, op.ins.first()?).ok()? as u64), + OpCode::CPUI_LOAD => { + let spc = mem_space(env, op.ins.first()?).ok()?; + let ptr = read(&mut state, op.ins.get(1)?).ok()? as u64; + let out = op.out.as_ref().filter(|o| !writes_argument(env, o) && (!strict || hidden(env, o)))?; + let v = state.read(&spc, spc.wrap_offset(ptr), out.size).ok()?; + write(&mut state, out, v).ok()?; + } + OpCode::CPUI_STORE if strict => return None, + OpCode::CPUI_STORE => { + let spc = mem_space(env, op.ins.first()?).ok()?; + let ptr = read(&mut state, op.ins.get(1)?).ok()? as u64; + let val = op.ins.get(2)?; + if spc.get_index() != env.ram.get_index() || !env.in_stack(ptr, u64::from(val.size)) { + return None; + } + let v = read(&mut state, val).ok()?; + state.write(&spc, spc.wrap_offset(ptr), val.size, v).ok()?; + } + OpCode::CPUI_CALL + | OpCode::CPUI_CALLIND + | OpCode::CPUI_CBRANCH + | OpCode::CPUI_CALLOTHER + | OpCode::CPUI_RETURN => return None, + opc => { + let out = op.out.as_ref().filter(|o| !writes_argument(env, o) && (!strict || hidden(env, o)))?; + let mut ins = Vec::with_capacity(op.ins.len()); + for vn in &op.ins { + ins.push((read(&mut state, vn).ok()?, vn.size)); + } + let v = eval(opc, out.size, &ins).ok()?; + write(&mut state, out, v).ok()?; + } + } + } + addr = env.code.wrap_offset(addr.wrapping_add(insn.len)); + } + None +} diff --git a/decompiler/crates/kuna-verify/src/report/mod.rs b/decompiler/crates/kuna-verify/src/report/mod.rs new file mode 100644 index 0000000000..f4c2e64247 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/report/mod.rs @@ -0,0 +1,167 @@ +//! Verdicts and how they are printed: as text for a person, as JSON for a +//! script or an agent. + + +use std::time::Duration; + +use serde_json::{json, Value}; + +use crate::value::Halt; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Verdict { + Agrees(u32), + Differs { run: u32, of: u32 }, + Diverges(&'static str), + Unknown(String), + Skipped(String), +} + +impl Verdict { + pub fn label(&self) -> String { + match self { + Verdict::Agrees(n) => format!("AGREES({n})"), + Verdict::Differs { .. } => "DIFFERS".to_string(), + Verdict::Diverges(id) => format!("DIVERGES({id})"), + Verdict::Unknown(s) | Verdict::Skipped(s) => s.clone(), + } + } + + pub fn class(&self) -> &'static str { + match self { + Verdict::Agrees(_) => "AGREES", + Verdict::Differs { .. } => "DIFFERS", + Verdict::Diverges(_) => "DIVERGES", + Verdict::Unknown(_) => "UNKNOWN", + Verdict::Skipped(_) => "SKIPPED", + } + } + + pub fn from_halt(h: &Halt) -> Verdict { + Verdict::Unknown(h.render()) + } +} + +#[derive(Debug, Clone)] +pub struct Report { + pub function: String, + pub verdict: Verdict, + pub lines: Vec, + pub suspects: Vec, + pub elapsed: Duration, +} + +impl Report { + pub fn render(&self) -> String { + Row::from(self).render() + } +} + +/// A report reduced to what printing and aggregation need, so it can cross a +/// process boundary as one JSON line. +#[derive(Debug, Clone, PartialEq)] +pub struct Row { + pub function: String, + pub class: String, + pub label: String, + /// `DIFFERS` only: the failing run and how many were planned. + pub run: Option<(u32, u32)>, + pub lines: Vec, + pub suspects: Vec, + pub ms: f64, +} + +impl From<&Report> for Row { + fn from(r: &Report) -> Self { + Row { + function: r.function.clone(), + class: r.verdict.class().to_string(), + label: r.verdict.label(), + run: match r.verdict { + Verdict::Differs { run, of } => Some((run, of)), + _ => None, + }, + lines: r.lines.clone(), + suspects: r.suspects.clone(), + ms: r.elapsed.as_secs_f64() * 1e3, + } + } +} + +impl Row { + pub fn render(&self) -> String { + let mut s = match self.run { + Some((run, of)) => format!("{} DIFFERS (run {} of {})\n", self.function, run + 1, of), + None => format!("{} {}\n", self.function, self.label), + }; + for l in &self.lines { + s.push_str(" "); + s.push_str(l); + s.push('\n'); + } + for p in &self.suspects { + s.push_str(&format!(" PROTOTYPE_SUSPECT({p})\n")); + } + s + } + + /// The reason a verdict is `UNKNOWN` or `SKIPPED`, without addresses: what + /// the summary counts. + pub fn reason(&self) -> Option { + matches!(self.class.as_str(), "UNKNOWN" | "SKIPPED").then(|| { + self.label.split(':').next().unwrap_or(&self.label).trim_end_matches(')').to_string() + }) + } + + pub fn to_json(&self) -> Value { + json!({ + "function": self.function, + "verdict": self.class, + "label": self.label, + "run": self.run.map(|(r, of)| json!({"run": r + 1, "of": of})), + "lines": self.lines, + "suspects": self.suspects, + "ms": self.ms, + }) + } + + pub fn from_json(v: &Value) -> Option { + let strings = |k: &str| -> Option> { + v.get(k)?.as_array()?.iter().map(|x| x.as_str().map(str::to_string)).collect() + }; + let run = match v.get("run") { + Some(Value::Object(o)) => Some((o.get("run")?.as_u64()? as u32 - 1, o.get("of")?.as_u64()? as u32)), + _ => None, + }; + Some(Row { + function: v.get("function")?.as_str()?.to_string(), + class: v.get("verdict")?.as_str()?.to_string(), + label: v.get("label")?.as_str()?.to_string(), + run, + lines: strings("lines")?, + suspects: strings("suspects")?, + ms: v.get("ms")?.as_f64()?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_round_trip_through_json() { + let r = Report { + function: "ins16".into(), + verdict: Verdict::Differs { run: 2, of: 256 }, + lines: vec!["machine r1:r0 = 0x1".into()], + suspects: vec!["reads r2".into()], + elapsed: Duration::from_micros(1500), + }; + let row = Row::from(&r); + assert_eq!(Row::from_json(&row.to_json()), Some(row.clone())); + assert!(row.render().starts_with("ins16 DIFFERS (run 3 of 256)\n")); + let skipped = Row { class: "SKIPPED".into(), label: "SKIPPED(memory: store at 0x10)".into(), ..row }; + assert_eq!(skipped.reason().as_deref(), Some("SKIPPED(memory")); + } +} diff --git a/decompiler/crates/kuna-verify/src/semantics/mod.rs b/decompiler/crates/kuna-verify/src/semantics/mod.rs new file mode 100644 index 0000000000..b50d1f57a0 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/semantics/mod.rs @@ -0,0 +1,6 @@ +//! P-code values and their semantics, shared by both sides: `value` evaluates +//! an op, `x87` the 80-bit floats, `storage` names a varnode's place. + +pub mod storage; +pub mod value; +pub mod x87; diff --git a/decompiler/crates/kuna-verify/src/semantics/storage.rs b/decompiler/crates/kuna-verify/src/semantics/storage.rs new file mode 100644 index 0000000000..74e310062e --- /dev/null +++ b/decompiler/crates/kuna-verify/src/semantics/storage.rs @@ -0,0 +1,81 @@ +//! Storage locations that varnodes and prototypes name, and how to print them. + +use std::rc::Rc; + +use kuna_base::address::Address; +use kuna_base::space::{spacetype, AddrSpace}; +use kuna_console::engine::ConsoleProgram; + +#[derive(Clone, Debug)] +pub struct Storage { + pub space: Rc, + pub off: u64, + pub size: u32, +} + +impl Storage { + pub fn new(space: &Rc, off: u64, size: u32) -> Self { + Storage { space: Rc::clone(space), off, size } + } + + pub fn at(addr: &Address, size: u32) -> Option { + addr.get_space().map(|s| Storage::new(s, addr.get_offset(), size)) + } + + pub fn overlaps(&self, o: &Storage) -> bool { + self.space.get_index() == o.space.get_index() + && self.off < o.off.wrapping_add(u64::from(o.size)) + && o.off < self.off.wrapping_add(u64::from(self.size)) + } + + pub fn covers(&self, inner: &Storage) -> bool { + self.space.get_index() == inner.space.get_index() + && inner.off >= self.off + && inner.off + u64::from(inner.size) <= self.off + u64::from(self.size) + } + + /// The physical pieces of a joined location, most significant first; the + /// location itself otherwise. + pub fn pieces(&self, prog: &ConsoleProgram) -> Vec { + if self.space.get_type() != spacetype::IPTR_JOIN { + return vec![self.clone()]; + } + match prog.arch().manage().find_join(self.off) { + Ok(rec) => (0..rec.num_pieces()) + .filter_map(|i| { + let p = rec.get_piece(i); + p.space.as_ref().map(|s| Storage::new(s, p.offset, p.size)) + }) + .collect(), + Err(_) => vec![self.clone()], + } + } + + pub fn name(&self, prog: &ConsoleProgram) -> String { + let parts: Vec = self + .pieces(prog) + .iter() + .map(|p| { + if p.space.get_type() == spacetype::IPTR_SPACEBASE { + return format!("stack[{:#x}]", p.off); + } + let name = prog + .arch() + .translate() + .as_sleigh() + .map(|s| s.base().get_register_name(&p.space, p.off, p.size as i32)) + .unwrap_or_default(); + if name.is_empty() { + format!("{}:{:#x}", p.space.get_name(), p.off) + } else { + String::from_utf8_lossy(&name).into_owned() + } + }) + .collect(); + parts.join(":") + } +} + +pub fn hex(v: u128, size: u32) -> String { + format!("0x{:0width$x}", v, width = (size.max(1) * 2) as usize) +} diff --git a/decompiler/crates/kuna-verify/src/semantics/value.rs b/decompiler/crates/kuna-verify/src/semantics/value.rs new file mode 100644 index 0000000000..5342e1b114 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/semantics/value.rs @@ -0,0 +1,552 @@ +//! Concrete p-code value semantics, shared by both sides of a check. +//! +//! Every op on values of at most eight bytes is evaluated through kuna's own +//! `OpBehavior` table, the one `EmulatePcodeCache` uses, so the two sides cannot +//! disagree on what an `INT_SRIGHT` means. Integer ops on wider values, up to +//! sixteen bytes (a 64-bit multiply-high widens to 128 bits), and the +//! decompiler-only ops (`CAST`, `PTRADD`, `PTRSUB`) are defined here. Floating +//! point runs on IEEE single and double, through the same table; other float +//! encodings and anything wider are refused, never approximated. + +use std::rc::Rc; + +use kuna_num::float::FloatFormat; +use kuna_num::opbehavior::{register_instructions, FloatFormatProvider, OpBehavior}; +use kuna_num::opcodes::{get_opname, OpCode}; + +/// Why a run stopped before it could be compared. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Halt { + /// An op or value the interpreter does not model: `UNKNOWN(unsupported-op)`. + Unsupported(String), + /// A concrete callee returned out of the image at an unexpected address. + UnexpectedReturn(String), + /// The step budget ran out: `UNKNOWN(budget)`. + Budget, + /// The sides differ after an in-image callee the model could not run got + /// the stub, with a frame object it may only have read. + Guessed(String), + /// The op itself has no defined result (division by zero). + Trap(String), + /// The harness could not set the run up: `UNKNOWN(harness)`. + Harness(String), + /// A switch met a selector no row of its table carries, and the table has + /// no default. + NoRow(String), + /// The sides differ after a call whose argument a recovered callee + /// prototype may have wrong: the prototype, not the body, may be at fault. + Doubtful(String), + /// The callee could not be rerun with the graph's arguments. + CalleeReplay(String), + /// The run reached a declared copy divergence with pending argument checks. + CallReruns(String), + /// The sides differ after the decompiled function read a local nothing + /// wrote: C does not define the value. + Undefined(String), + /// A callee run for real changed a register the calling convention says it + /// preserves, and the run's result depends on it: kuna's C, which follows + /// the convention, cannot say what the program does. + AbiViolation(String), +} + +impl Halt { + pub fn render(&self) -> String { + match self { + Halt::Unsupported(s) | Halt::UnexpectedReturn(s) => format!("UNKNOWN(unsupported-op: {s})"), + Halt::Budget => "UNKNOWN(budget)".to_string(), + Halt::Trap(s) => format!("UNKNOWN(trap: {s})"), + Halt::Harness(s) => format!("UNKNOWN(harness: {s})"), + Halt::NoRow(s) => format!("UNKNOWN(no switch row: {s})"), + Halt::Doubtful(s) => format!("UNKNOWN(prototype-suspect: {s})"), + Halt::CalleeReplay(s) => format!("UNKNOWN(callee-replay: {s})"), + Halt::CallReruns(s) => format!("UNKNOWN(call-reruns: {s})"), + Halt::Undefined(s) => format!("UNKNOWN(uninitialized-local: {s})"), + Halt::Guessed(s) => format!("UNKNOWN(guessed-callee: {s})"), + Halt::AbiViolation(s) => format!("UNKNOWN(abi-violation: {s})"), + } + } +} + +/// The widest value either side models. +pub const MAX_SIZE: u32 = 16; + +pub fn mask(size: u32) -> u128 { + if size >= 16 { + u128::MAX + } else { + (1u128 << (size * 8)) - 1 + } +} + +/// IEEE single and double: the float formats both sides evaluate with. +struct Ieee { + single: FloatFormat, + double: FloatFormat, +} + +impl FloatFormatProvider for Ieee { + fn get_float_format(&self, size: i32) -> Option<&FloatFormat> { + match size { + 4 => Some(&self.single), + 8 => Some(&self.double), + _ => None, + } + } +} + +/// Results the behavior table does not give as the hardware does: sign +/// operations on the bits, NaN conversions that keep the payload, and +/// arithmetic on a NaN, which returns the first NaN operand quieted (x86 SSE, +/// and ARM with default-NaN mode off). +fn ieee_bits(opc: OpCode, out: u32, ins: &[(u128, u32)]) -> Option { + let &(a, size) = ins.first()?; + let sign = |n: u32| 1u128 << (n * 8 - 1); + match (opc, size) { + (OpCode::CPUI_FLOAT_NEG, 4 | 8) if out == size => Some((a ^ sign(size)) & mask(size)), + (OpCode::CPUI_FLOAT_ABS, 4 | 8) if out == size => Some(a & !sign(size) & mask(size)), + (OpCode::CPUI_FLOAT_ADD | OpCode::CPUI_FLOAT_SUB | OpCode::CPUI_FLOAT_MULT | OpCode::CPUI_FLOAT_DIV, 4 | 8) + if out == size && ins.iter().any(|&(v, s)| s == size && is_nan(v, s)) => + { + let &(nan, _) = ins.iter().find(|&&(v, s)| s == size && is_nan(v, s))?; + let quiet = if size == 4 { 1u128 << 22 } else { 1u128 << 51 }; + Some(nan | quiet) + } + (OpCode::CPUI_FLOAT_FLOAT2FLOAT, 4) if out == 8 && is_nan(a, 4) => { + let (s, frac) = ((a >> 31) & 1, a & 0x7f_ffff); + Some((s << 63) | (0x7ff << 52) | (frac << 29) | (1 << 51)) + } + (OpCode::CPUI_FLOAT_FLOAT2FLOAT, 8) if out == 4 && is_nan(a, 8) => { + let (s, frac) = ((a >> 63) & 1, a & 0xf_ffff_ffff_ffff); + Some((s << 31) | (0xff << 23) | (frac >> 29) | (1 << 22)) + } + _ => None, + } +} + +fn is_nan(v: u128, size: u32) -> bool { + match size { + 4 => (v >> 23) & 0xff == 0xff && v & 0x7f_ffff != 0, + 8 => (v >> 52) & 0x7ff == 0x7ff && v & 0xf_ffff_ffff_ffff != 0, + _ => false, + } +} + +fn is_float(opc: OpCode) -> bool { + (OpCode::CPUI_FLOAT_EQUAL as u32..=OpCode::CPUI_FLOAT_ROUND as u32).contains(&(opc as u32)) +} + +thread_local! { + static BEHAVIORS: Vec>> = { + let mut inst = Vec::new(); + let provider: Rc = Rc::new(Ieee { single: FloatFormat::new(4), double: FloatFormat::new(8) }); + register_instructions(&mut inst, &provider); + inst + }; +} + +fn signed(v: u128, size: u32) -> i128 { + let bits = size * 8; + if bits >= 128 { + v as i128 + } else { + ((v << (128 - bits)) as i128) >> (128 - bits) + } +} + +/// Integer semantics on values of up to sixteen bytes. +fn eval_wide(opc: OpCode, out: u32, ins: &[(u128, u32)]) -> Result { + let m = mask(out); + let (a, asz) = ins[0]; + let (b, bsz) = ins.get(1).copied().unwrap_or((0, 0)); + let abits = u128::from(asz * 8); + let bool_of = |x: bool| u128::from(x); + let r = match opc { + OpCode::CPUI_COPY | OpCode::CPUI_CAST | OpCode::CPUI_INT_ZEXT => a, + OpCode::CPUI_INT_SEXT => signed(a, asz) as u128, + OpCode::CPUI_INT_ADD => a.wrapping_add(b), + OpCode::CPUI_INT_SUB => a.wrapping_sub(b), + OpCode::CPUI_INT_MULT => a.wrapping_mul(b), + OpCode::CPUI_INT_AND => a & b, + OpCode::CPUI_INT_OR => a | b, + OpCode::CPUI_INT_XOR => a ^ b, + OpCode::CPUI_INT_NEGATE => !a, + OpCode::CPUI_INT_2COMP => a.wrapping_neg(), + OpCode::CPUI_INT_LEFT => if b >= abits { 0 } else { a << b }, + OpCode::CPUI_INT_RIGHT => if b >= abits { 0 } else { (a & mask(asz)) >> b }, + OpCode::CPUI_INT_SRIGHT => { + let s = signed(a, asz); + (if b >= abits { s >> 127 } else { s >> b }) as u128 + } + OpCode::CPUI_SUBPIECE => if b >= 16 { 0 } else { a >> (b * 8) }, + OpCode::CPUI_PIECE => if bsz >= 16 { b } else { (a << (bsz * 8)) | b }, + OpCode::CPUI_INT_EQUAL => bool_of(a == b), + OpCode::CPUI_INT_NOTEQUAL => bool_of(a != b), + OpCode::CPUI_INT_LESS => bool_of(a < b), + OpCode::CPUI_INT_LESSEQUAL => bool_of(a <= b), + OpCode::CPUI_INT_SLESS => bool_of(signed(a, asz) < signed(b, asz)), + OpCode::CPUI_INT_SLESSEQUAL => bool_of(signed(a, asz) <= signed(b, asz)), + OpCode::CPUI_INT_CARRY => bool_of(a.wrapping_add(b) & mask(asz) < a), + OpCode::CPUI_INT_SCARRY => { + let r = signed(a.wrapping_add(b) & mask(asz), asz); + let (x, y) = (signed(a, asz), signed(b, asz)); + bool_of((x < 0) == (y < 0) && (r < 0) != (x < 0)) + } + OpCode::CPUI_INT_SBORROW => { + let r = signed(a.wrapping_sub(b) & mask(asz), asz); + let (x, y) = (signed(a, asz), signed(b, asz)); + bool_of((x < 0) != (y < 0) && (r < 0) != (x < 0)) + } + OpCode::CPUI_INT_DIV | OpCode::CPUI_INT_REM | OpCode::CPUI_INT_SDIV | OpCode::CPUI_INT_SREM if b == 0 => { + return Err(Halt::Trap(format!("{}: divide by 0", get_opname(opc)))); + } + OpCode::CPUI_INT_DIV => a / b, + OpCode::CPUI_INT_REM => a % b, + OpCode::CPUI_INT_SDIV => signed(a, asz).wrapping_div(signed(b, asz)) as u128, + OpCode::CPUI_INT_SREM => signed(a, asz).wrapping_rem(signed(b, asz)) as u128, + OpCode::CPUI_POPCOUNT => u128::from(a.count_ones()), + OpCode::CPUI_LZCOUNT => u128::from(a.leading_zeros()) - (128 - abits), + OpCode::CPUI_BOOL_NEGATE => bool_of(a == 0), + OpCode::CPUI_BOOL_AND => bool_of(a != 0 && b != 0), + OpCode::CPUI_BOOL_OR => bool_of(a != 0 || b != 0), + OpCode::CPUI_BOOL_XOR => bool_of((a != 0) != (b != 0)), + _ => return Err(Halt::Unsupported(format!("{} wider than 8 bytes", get_opname(opc)))), + }; + Ok(r & m) +} + +/// Ops whose output and inputs are one size. Anything else is ill-formed IR, +/// and truncating it would invent a value. +fn same_size(opc: OpCode) -> bool { + matches!( + opc, + OpCode::CPUI_INT_ADD + | OpCode::CPUI_INT_SUB + | OpCode::CPUI_INT_MULT + | OpCode::CPUI_INT_DIV + | OpCode::CPUI_INT_SDIV + | OpCode::CPUI_INT_REM + | OpCode::CPUI_INT_SREM + | OpCode::CPUI_INT_AND + | OpCode::CPUI_INT_OR + | OpCode::CPUI_INT_XOR + | OpCode::CPUI_INT_NEGATE + | OpCode::CPUI_INT_2COMP + ) +} + +/// An op's input values and sizes, kept inline for the usual one to four +/// inputs so evaluating an op allocates nothing. +#[derive(Default)] +pub struct Inputs { + inline: [(u128, u32); 4], + len: usize, + spill: Vec<(u128, u32)>, +} + +impl Inputs { + pub fn push(&mut self, v: (u128, u32)) { + if self.len < self.inline.len() && self.spill.is_empty() { + self.inline[self.len] = v; + self.len += 1; + } else { + if self.spill.is_empty() { + self.spill.extend_from_slice(&self.inline[..self.len]); + } + self.spill.push(v); + } + } + + pub fn as_slice(&self) -> &[(u128, u32)] { + if self.spill.is_empty() { &self.inline[..self.len] } else { &self.spill } + } +} + +/// Evaluate a value-producing op. `ins` holds each input's value and size. +pub fn eval(opc: OpCode, out_size: u32, ins: &[(u128, u32)]) -> Result { + match eval_int(opc, out_size, ins) { + Some(v) => Ok(v), + None => eval_any(opc, out_size, ins), + } +} + +/// The integer ops runs spend most of their time in, on operands of at most +/// eight bytes: the behavior table's arithmetic, step for step, without its +/// dispatch. `None` for anything else, which `eval_any` decides. +fn eval_int(opc: OpCode, out: u32, ins: &[(u128, u32)]) -> Option { + use kuna_base::address::{calc_mask, sign_extend_sized, signbit_negative, uintb_negate}; + use OpCode::*; + let small = |s: u32| (1..=8).contains(&s); + if !small(out) || !ins.iter().all(|&(_, s)| small(s)) || (same_size(opc) && ins.iter().any(|&(_, s)| s != out)) { + return None; + } + let (a, sa) = ins.first().map(|&(v, s)| (v as u64, s as i32))?; + let so = out as i32; + let b = || ins.get(1).map(|&(v, _)| v as u64); + let sign = |v: u64| (v.wrapping_shr((sa * 8 - 1) as u32) & 1) as u32; + let signed_less = |b: u64, or_equal: bool| { + let m = 0x80u64.wrapping_shl((8 * (sa - 1)) as u32); + let (x, y) = (a & m, b & m); + u64::from(if x != y { x != 0 } else if or_equal { a <= b } else { a < b }) + }; + let r = match opc { + CPUI_INT_ADD => a.wrapping_add(b()?) & calc_mask(so), + CPUI_INT_SUB => a.wrapping_sub(b()?) & calc_mask(so), + CPUI_INT_MULT => a.wrapping_mul(b()?) & calc_mask(so), + CPUI_INT_AND | CPUI_BOOL_AND => a & b()?, + CPUI_INT_OR | CPUI_BOOL_OR => a | b()?, + CPUI_INT_XOR | CPUI_BOOL_XOR => a ^ b()?, + CPUI_INT_EQUAL => u64::from(a == b()?), + CPUI_INT_NOTEQUAL => u64::from(a != b()?), + CPUI_INT_LESS => u64::from(a < b()?), + CPUI_INT_LESSEQUAL => u64::from(a <= b()?), + CPUI_INT_SLESS => signed_less(b()?, false), + CPUI_INT_SLESSEQUAL => signed_less(b()?, true), + CPUI_INT_ZEXT => a, + CPUI_INT_SEXT => sign_extend_sized(a, sa, so), + CPUI_INT_CARRY => u64::from(a > (a.wrapping_add(b()?) & calc_mask(sa))), + CPUI_INT_SCARRY => { + let b = b()?; + u64::from((sign(a.wrapping_add(b)) ^ sign(a)) & (sign(a) ^ sign(b) ^ 1)) + } + CPUI_INT_SBORROW => { + let b = b()?; + let r = sign(a.wrapping_sub(b)); + u64::from((sign(a) ^ r) & (r ^ sign(b) ^ 1)) + } + CPUI_INT_2COMP => uintb_negate(a.wrapping_sub(1), sa), + CPUI_INT_NEGATE => uintb_negate(a, sa), + CPUI_BOOL_NEGATE => a ^ 1, + CPUI_INT_LEFT => { + let b = b()?; + if b >= (so * 8) as u64 { 0 } else { a.wrapping_shl(b as u32) & calc_mask(so) } + } + CPUI_INT_RIGHT => { + let b = b()?; + if b >= (so * 8) as u64 { 0 } else { (a & calc_mask(so)).wrapping_shr(b as u32) } + } + CPUI_INT_SRIGHT => { + let b = b()?; + let negative = signbit_negative(a, sa); + if b >= (so * 8) as u64 { + if negative { calc_mask(so) } else { 0 } + } else if negative { + let m = calc_mask(sa); + a.wrapping_shr(b as u32) | (m.wrapping_shr(b as u32) ^ m) + } else { + a.wrapping_shr(b as u32) + } + } + CPUI_PIECE => a.wrapping_shl((so - sa).wrapping_mul(8) as u32) | b()?, + CPUI_SUBPIECE => { + let b = b()?; + if b >= 8 { 0 } else { a.wrapping_shr((b * 8) as u32) & calc_mask(so) } + } + _ => return None, + }; + Some(u128::from(r) & mask(out)) +} + +/// Evaluate any value-producing op. +fn eval_any(opc: OpCode, out_size: u32, ins: &[(u128, u32)]) -> Result { + if out_size > MAX_SIZE || ins.iter().any(|&(_, s)| s > MAX_SIZE) { + return Err(Halt::Unsupported(format!("{} wider than {MAX_SIZE} bytes", get_opname(opc)))); + } + if is_float(opc) && (out_size == 10 || ins.iter().any(|&(_, s)| s == 10)) { + return crate::x87::eval(opc, out_size, ins).ok_or_else(|| Halt::Unsupported(format!("{} on x87's 80-bit format", get_opname(opc)))); + } + if let (OpCode::CPUI_FLOAT_INT2FLOAT, 4 | 8, Some(&(v, size))) = (opc, out_size, ins.first()) { + if size > 8 && size <= MAX_SIZE { + let n = signed(v, size); + return Ok(if out_size == 4 { u128::from((n as f32).to_bits()) } else { u128::from((n as f64).to_bits()) }); + } + } + if is_float(opc) && (out_size > 8 || ins.iter().any(|&(_, s)| s > 8)) { + return Err(Halt::Unsupported(get_opname(opc).to_string())); + } + if let Some(v) = ieee_bits(opc, out_size, ins) { + return Ok(v); + } + let arg = |i: usize| -> Result<(u128, u32), Halt> { + ins.get(i) + .copied() + .ok_or_else(|| Halt::Harness(format!("{} lacks input {i}", get_opname(opc)))) + }; + let m = mask(out_size); + match opc { + OpCode::CPUI_COPY | OpCode::CPUI_CAST => return Ok(arg(0)?.0 & m), + OpCode::CPUI_PTRADD => { + let (base, _) = arg(0)?; + let (index, _) = arg(1)?; + let (scale, _) = arg(2)?; + return Ok(base.wrapping_add(index.wrapping_mul(scale)) & m); + } + OpCode::CPUI_PTRSUB => return Ok(arg(0)?.0.wrapping_add(arg(1)?.0) & m), + _ => {} + } + arg(0)?; + if same_size(opc) && (ins.iter().any(|&(_, s)| s != out_size)) { + return Err(Halt::Unsupported(format!("{} with operands of mixed size", get_opname(opc)))); + } + if out_size > 8 || ins.iter().any(|&(_, s)| s > 8) { + return eval_wide(opc, out_size, ins); + } + BEHAVIORS.with(|table| { + let behave = table + .get(opc as usize) + .and_then(Option::as_ref) + .filter(|b| !b.is_special()) + .ok_or_else(|| Halt::Unsupported(get_opname(opc).to_string()))?; + let (a, asize) = arg(0)?; + let result = if behave.is_unary() { + behave.evaluate_unary(out_size as i32, asize as i32, a as u64) + } else { + let (b, _) = arg(1)?; + behave.evaluate_binary(out_size as i32, asize as i32, a as u64, b as u64) + }; + result.map(|v| u128::from(v) & m).map_err(|e| { + let why = format!("{}: {}", get_opname(opc), e.explain()); + if is_float(opc) { + Halt::Unsupported(why) + } else { + Halt::Trap(why) + } + }) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_unsigned_word_converts_through_a_wider_integer() { + let big = u128::from(u64::MAX); + assert_eq!(eval(OpCode::CPUI_FLOAT_INT2FLOAT, 4, &[(big, 9)]).unwrap(), u128::from((u64::MAX as f32).to_bits())); + assert_eq!(eval(OpCode::CPUI_FLOAT_INT2FLOAT, 8, &[(big, 9)]).unwrap(), u128::from((u64::MAX as f64).to_bits())); + } + + #[test] + fn decompiler_only_ops_are_defined_here() { + assert_eq!(eval(OpCode::CPUI_PTRADD, 4, &[(0x100, 4), (3, 4), (4, 4)]), Ok(0x10c)); + assert_eq!(eval(OpCode::CPUI_PTRSUB, 4, &[(0xfffffff0, 4), (0x20, 4)]), Ok(0x10)); + assert_eq!(eval(OpCode::CPUI_CAST, 2, &[(0x12345, 4)]), Ok(0x2345)); + } + + #[test] + fn the_integer_fast_path_matches_the_behavior_table() { + use OpCode::*; + let ops = [ + CPUI_INT_ADD, CPUI_INT_SUB, CPUI_INT_MULT, CPUI_INT_AND, CPUI_INT_OR, CPUI_INT_XOR, CPUI_BOOL_AND, + CPUI_BOOL_OR, CPUI_BOOL_XOR, CPUI_INT_EQUAL, CPUI_INT_NOTEQUAL, CPUI_INT_LESS, CPUI_INT_LESSEQUAL, + CPUI_INT_SLESS, CPUI_INT_SLESSEQUAL, CPUI_INT_ZEXT, CPUI_INT_SEXT, CPUI_INT_CARRY, CPUI_INT_SCARRY, + CPUI_INT_SBORROW, CPUI_INT_2COMP, CPUI_INT_NEGATE, CPUI_BOOL_NEGATE, CPUI_INT_LEFT, CPUI_INT_RIGHT, + CPUI_INT_SRIGHT, CPUI_PIECE, CPUI_SUBPIECE, + ]; + let mut z = 0x6b75_6e61u64; + let mut next = || { + z = z.wrapping_add(0x9e37_79b9_7f4a_7c15); + let mut x = z; + x = (x ^ (x >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + x = (x ^ (x >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + x ^ (x >> 31) + }; + let edges = [0u64, 1, 7, 8, 31, 32, 63, 64, 0x7f, 0x80, 0xff, 0x7fff_ffff, 0x8000_0000, u64::MAX]; + let mut checked = 0; + for opc in ops { + for out in 1..=8u32 { + for sa in 1..=8u32 { + for sb in [sa, 1, 4, 8] { + for k in 0..64 { + let pick = |r: u64, k: usize| if k % 3 == 0 { edges[(r % edges.len() as u64) as usize] } else { r }; + let (r1, r2) = (next(), next()); + let ins = [(u128::from(pick(r1, k)), sa), (u128::from(pick(r2, k / 2)), sb)]; + let Some(fast) = eval_int(opc, out, &ins) else { continue }; + assert_eq!(Ok(fast), eval_any(opc, out, &ins), "{opc:?} out {out} ins {ins:x?}"); + checked += 1; + } + } + } + } + } + assert!(checked > 50_000, "{checked}"); + } + + #[test] + fn sleigh_ops_use_the_behavior_table() { + assert_eq!(eval(OpCode::CPUI_INT_SEXT, 8, &[(0x80000000, 4)]), Ok(0xffffffff80000000)); + assert_eq!(eval(OpCode::CPUI_INT_SRIGHT, 4, &[(0x80000000, 4), (31, 4)]), Ok(0xffffffff)); + assert_eq!(eval(OpCode::CPUI_PIECE, 8, &[(1, 4), (2, 4)]), Ok(0x100000002)); + } + + #[test] + fn multiply_high_widens_to_sixteen_bytes() { + let x = eval(OpCode::CPUI_INT_SEXT, 16, &[(u128::from(u64::MAX), 8)]).unwrap(); + assert_eq!(x, u128::MAX); + let p = eval(OpCode::CPUI_INT_MULT, 16, &[(0x5555_5555_5555_5556, 16), (x, 16)]).unwrap(); + assert_eq!(eval(OpCode::CPUI_SUBPIECE, 8, &[(p, 16), (8, 4)]), Ok(u128::from(u64::MAX))); + } + + /// The wide evaluator agrees with the behavior table wherever both apply. + #[test] + fn wide_semantics_match_the_behavior_table_at_eight_bytes() { + let ops = [ + OpCode::CPUI_INT_ADD, + OpCode::CPUI_INT_SUB, + OpCode::CPUI_INT_MULT, + OpCode::CPUI_INT_LEFT, + OpCode::CPUI_INT_RIGHT, + OpCode::CPUI_INT_SRIGHT, + OpCode::CPUI_INT_LESS, + OpCode::CPUI_INT_SLESS, + OpCode::CPUI_INT_SLESSEQUAL, + OpCode::CPUI_INT_CARRY, + OpCode::CPUI_INT_SCARRY, + OpCode::CPUI_INT_SBORROW, + OpCode::CPUI_INT_DIV, + OpCode::CPUI_INT_SDIV, + OpCode::CPUI_INT_REM, + OpCode::CPUI_INT_SREM, + ]; + let vals = [0u128, 1, 3, 7, 31, 32, 0x7fff_ffff, 0x8000_0000, 0xffff_ffff, 0x1234_5678]; + for size in [1u32, 2, 4] { + for &op in &ops { + for &a in &vals { + for &b in &vals { + let (a, b) = (a & mask(size), b & mask(size)); + let out = if matches!( + op, + OpCode::CPUI_INT_LESS + | OpCode::CPUI_INT_SLESS + | OpCode::CPUI_INT_SLESSEQUAL + | OpCode::CPUI_INT_CARRY + | OpCode::CPUI_INT_SCARRY + | OpCode::CPUI_INT_SBORROW + ) { + 1 + } else { + size + }; + let table = eval(op, out, &[(a, size), (b, size)]); + let wide = eval_wide(op, out, &[(a, size), (b, size)]); + match (&table, &wide) { + (Err(Halt::Trap(_)), Err(Halt::Trap(_))) => {} + _ => assert_eq!(table, wide, "{} size {size} a={a:#x} b={b:#x}", get_opname(op)), + } + } + } + } + } + } + + #[test] + fn ieee_floats_run_and_division_by_zero_stops() { + let (one, two, three) = (1.0f32.to_bits().into(), 2.0f32.to_bits().into(), 3.0f32.to_bits().into()); + assert_eq!(eval(OpCode::CPUI_FLOAT_ADD, 4, &[(one, 4), (two, 4)]), Ok(three)); + let half = 1.5f64.to_bits().into(); + assert_eq!(eval(OpCode::CPUI_FLOAT_MULT, 8, &[(half, 8), (2.0f64.to_bits().into(), 8)]), Ok(3.0f64.to_bits().into())); + assert!(matches!(eval(OpCode::CPUI_FLOAT_ADD, 2, &[(0, 2), (0, 2)]), Err(Halt::Unsupported(_)))); + assert!(matches!(eval(OpCode::CPUI_FLOAT_ADD, 16, &[(0, 16), (0, 16)]), Err(Halt::Unsupported(_)))); + assert!(matches!(eval(OpCode::CPUI_INT_DIV, 4, &[(1, 4), (0, 4)]), Err(Halt::Trap(_)))); + assert!(matches!(eval(OpCode::CPUI_INT_DIV, 16, &[(1, 16), (0, 16)]), Err(Halt::Trap(_)))); + } +} diff --git a/decompiler/crates/kuna-verify/src/semantics/x87.rs b/decompiler/crates/kuna-verify/src/semantics/x87.rs new file mode 100644 index 0000000000..18405dd23c --- /dev/null +++ b/decompiler/crates/kuna-verify/src/semantics/x87.rs @@ -0,0 +1,206 @@ +//! x87's 80-bit extended format, for the operations that are exact without an +//! 80-bit arithmetic unit: conversions in from integers and IEEE single and +//! double, out to them with round-to-nearest-even, sign operations, +//! comparisons, the NaN test and truncation to an integer. Arithmetic on the +//! format stays unsupported. +//! +//! A value is the low 80 bits of a `u128`: sign (bit 79), a 15-bit biased +//! exponent, and a 64-bit significand whose top bit is the explicit integer bit. + +use kuna_num::opcodes::OpCode; + +const BIAS: i32 = 16383; +const EXP_MAX: u128 = 0x7fff; + +fn parts(v: u128) -> (bool, u128, u128) { + ((v >> 79) & 1 == 1, (v >> 64) & EXP_MAX, v & u128::from(u64::MAX)) +} + +fn pack(neg: bool, exp: u128, sig: u128) -> u128 { + (u128::from(neg) << 79) | (exp << 64) | sig +} + +fn is_nan(v: u128) -> bool { + let (_, e, m) = parts(v); + e == EXP_MAX && m & !(1u128 << 63) != 0 +} + +/// An integer magnitude, exactly: every integer of up to 64 bits fits. +fn from_int(neg: bool, mag: u128) -> u128 { + if mag == 0 { + return pack(neg, 0, 0); + } + let top = 127 - mag.leading_zeros() as i32; + let sig = if top >= 63 { mag >> (top - 63) } else { mag << (63 - top) }; + pack(neg, (BIAS + top) as u128, sig & u128::from(u64::MAX)) +} + +/// An IEEE value of `size` bytes, exactly. +fn from_ieee(v: u128, size: u32) -> u128 { + let (ebits, fbits) = if size == 4 { (8, 23) } else { (11, 52) }; + let neg = (v >> (ebits + fbits)) & 1 == 1; + let e = (v >> fbits) & ((1 << ebits) - 1); + let f = v & ((1 << fbits) - 1); + let emax = (1 << ebits) - 1; + let bias = (1i32 << (ebits - 1)) - 1; + if e == emax { + return pack(neg, EXP_MAX, (1 << 63) | (f << (63 - fbits))); + } + if e == 0 { + if f == 0 { + return pack(neg, 0, 0); + } + let top = 127 - f.leading_zeros() as i32; + let exp = 1 - bias - fbits as i32 + top; + return pack(neg, (BIAS + exp) as u128, (f << (63 - top)) & u128::from(u64::MAX)); + } + pack(neg, (e as i32 - bias + BIAS) as u128, (1 << 63) | (f << (63 - fbits))) +} + +/// To an IEEE value of `size` bytes, rounding to nearest, ties to even. +pub fn to_ieee(v: u128, size: u32) -> u128 { + let (ebits, fbits) = if size == 4 { (8u32, 23i32) } else { (11, 52) }; + let (neg, e, m) = parts(v); + let sign = u128::from(neg) << (ebits as i32 + fbits); + let emax = (1u128 << ebits) - 1; + if e == EXP_MAX { + let rest = m & !(1 << 63); + let frac = if rest != 0 { (rest >> (63 - fbits)) | (1 << (fbits - 1)) } else { 0 }; + return sign | (emax << fbits) | frac; + } + if m == 0 { + return sign; + } + let bias = (1i32 << (ebits - 1)) - 1; + let scale = e.max(1) as i32 - BIAS - 63; + let top = 127 - m.leading_zeros() as i32; + let quantum = (scale + top - fbits).max(1 - bias - fbits); + let drop = quantum - scale; + let mut sig = if drop <= 0 { + m << (-drop) + } else if drop >= 66 { + 0 + } else { + let kept = m >> drop; + let rest = m & ((1u128 << drop) - 1); + let half = 1u128 << (drop - 1); + kept + u128::from(rest > half || (rest == half && kept & 1 == 1)) + }; + let mut quantum = quantum; + if sig >> (fbits + 1) != 0 { + sig >>= 1; + quantum += 1; + } + if sig >> fbits != 0 { + let field = (quantum + fbits + bias) as u128; + if field >= emax { + return sign | (emax << fbits); + } + sign | (field << fbits) | (sig & ((1 << fbits) - 1)) + } else { + sign | sig + } +} + +/// A key that orders non-NaN values as the numbers they are; zeros of either +/// sign are equal. +fn order(v: u128) -> i128 { + let (neg, e, m) = parts(v); + let mag = if m == 0 { 0 } else { ((e << 64) | m) as i128 }; + if neg { -mag } else { mag } +} + +/// Truncate toward zero to a signed integer of `size` bytes; out of range or +/// NaN gives x87's integer indefinite, the smallest integer. +fn trunc(v: u128, size: u32) -> u128 { + let bits = size * 8; + let indefinite = 1u128 << (bits - 1); + let (neg, e, m) = parts(v); + if e == EXP_MAX { + return indefinite; + } + let shift = e as i32 - BIAS - 63; + let mag = if shift >= 0 { + if shift > 64 || (m << shift) >> (bits - 1) != 0 && !(neg && m << shift == indefinite) { + return indefinite; + } + m << shift + } else if shift <= -64 { + 0 + } else { + m >> (-shift) + }; + if mag >> (bits - 1) != 0 && !(neg && mag == indefinite) { + return indefinite; + } + let mask = if bits >= 128 { u128::MAX } else { (1u128 << bits) - 1 }; + (if neg { mag.wrapping_neg() } else { mag }) & mask +} + +/// Evaluate `opc` when an input or the output is the 10-byte format; `None` +/// for an operation this module does not do exactly. +pub fn eval(opc: OpCode, out: u32, ins: &[(u128, u32)]) -> Option { + let &(a, asz) = ins.first()?; + let ext = |(v, s): (u128, u32)| match s { + 10 => Some(v & ((1u128 << 80) - 1)), + 4 | 8 => Some(from_ieee(v, s)), + _ => None, + }; + let sign = 1u128 << 79; + match opc { + OpCode::CPUI_FLOAT_INT2FLOAT if out == 10 && asz <= 8 => { + let bits = asz * 8; + let s = ((a << (128 - bits)) as i128) >> (128 - bits); + Some(from_int(s < 0, s.unsigned_abs())) + } + OpCode::CPUI_FLOAT_FLOAT2FLOAT if out == 10 => ext((a, asz)), + OpCode::CPUI_FLOAT_FLOAT2FLOAT if asz == 10 && (out == 4 || out == 8) => Some(to_ieee(a, out)), + OpCode::CPUI_FLOAT_NEG if asz == 10 && out == 10 => Some(a ^ sign), + OpCode::CPUI_FLOAT_ABS if asz == 10 && out == 10 => Some(a & !sign), + OpCode::CPUI_FLOAT_NAN if asz == 10 => Some(u128::from(is_nan(a))), + OpCode::CPUI_FLOAT_TRUNC if asz == 10 && out <= 8 => Some(trunc(a, out)), + OpCode::CPUI_FLOAT_EQUAL | OpCode::CPUI_FLOAT_NOTEQUAL | OpCode::CPUI_FLOAT_LESS | OpCode::CPUI_FLOAT_LESSEQUAL + if ins.iter().any(|&(_, s)| s == 10) => + { + let (x, y) = (ext(a_in(ins, 0)?)?, ext(a_in(ins, 1)?)?); + let unordered = is_nan(x) || is_nan(y); + let (kx, ky) = (order(x), order(y)); + Some(u128::from(match opc { + OpCode::CPUI_FLOAT_EQUAL => !unordered && kx == ky, + OpCode::CPUI_FLOAT_NOTEQUAL => unordered || kx != ky, + OpCode::CPUI_FLOAT_LESS => !unordered && kx < ky, + _ => !unordered && kx <= ky, + })) + } + _ => None, + } +} + +fn a_in(ins: &[(u128, u32)], k: usize) -> Option<(u128, u32)> { + ins.get(k).copied() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn doubles_round_trip_and_integers_are_exact() { + for d in [0.0f64, -0.0, 1.0, -2.5, 1e300, 5e-324, 2.2250738585072014e-308, f64::INFINITY, 0.1] { + let x = from_ieee(u128::from(d.to_bits()), 8); + assert_eq!(to_ieee(x, 8), u128::from(d.to_bits()), "{d}"); + } + let one = from_int(false, 1); + assert_eq!(one, (16383u128 << 64) | (1 << 63)); + assert_eq!(to_ieee(from_int(false, (1 << 53) + 1), 8), u128::from(9007199254740992f64.to_bits())); + assert_eq!(to_ieee(from_int(false, (1 << 53) + 3), 8), u128::from(9007199254740996f64.to_bits())); + assert_eq!(to_ieee(from_int(true, 3), 4), u128::from((-3.0f32).to_bits())); + assert_eq!(trunc(from_ieee(u128::from((-7.9f64).to_bits()), 8), 4), (-7i32) as u32 as u128); + assert_eq!(trunc(from_ieee(u128::from(1e30f64.to_bits()), 8), 4), 0x8000_0000); + let nan = from_ieee(u128::from(f64::NAN.to_bits()), 8); + assert!(is_nan(nan)); + assert_eq!(eval(OpCode::CPUI_FLOAT_LESS, 1, &[(from_int(true, 1), 10), (0, 10)]), Some(1)); + assert_eq!(eval(OpCode::CPUI_FLOAT_EQUAL, 1, &[(pack(true, 0, 0), 10), (0, 10)]), Some(1)); + assert_eq!(eval(OpCode::CPUI_FLOAT_EQUAL, 1, &[(nan, 10), (nan, 10)]), Some(0)); + } +} diff --git a/decompiler/crates/kuna-verify/src/session.rs b/decompiler/crates/kuna-verify/src/session.rs new file mode 100644 index 0000000000..997619a1b1 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/session.rs @@ -0,0 +1,314 @@ +//! Driving the decompiler console in-process, so each `decompile` hands its +//! finished `Funcdata` to the check before the next command replaces it. + +use std::rc::Rc; + +use kuna_base::xml::DocumentStorage; +use kuna_console::engine::{bootstrap_program, ConsoleProgram}; +use kuna_console::ifacedecomp::{ + execute, register_console_commands, register_decomp_commands, IfaceDecompData, DECOMPILE_MODULE, +}; +use kuna_console::ifaceterm::ConsoleCommands; +use kuna_console::interface::{quote_filename, IfaceStatus}; +use kuna_console::kuna_console::register_kuna_commands; +use kuna_decomp::funcdata::Funcdata; +use kuna_decomp::kuna_loadoptions::EnvSnapshot; + +fn dcp(console: &IfaceStatus) -> Option<&IfaceDecompData> { + console + .get_data(DECOMPILE_MODULE) + .and_then(|d| d.as_any().downcast_ref::()) +} + +fn dcp_mut(console: &mut IfaceStatus) -> Option<&mut IfaceDecompData> { + console + .get_data_mut(DECOMPILE_MODULE) + .and_then(|d| d.as_any_mut().downcast_mut::()) +} + +/// A command that failed in a script that keeps going: its index and message. +pub type Failure = (usize, String); + +/// The wall-clock budget of a capped decompile: without a rule some actions +/// never settle. +const CAPPED_BUDGET: std::time::Duration = std::time::Duration::from_secs(5); + +/// Rule applications counted, or one rule's limited, in one decompile: the +/// `decompile`-th one [`run`] reports (`kuna_rulecap`). The run stops after it. +pub struct Cap { + pub decompile: usize, + pub mode: kuna_decomp::kuna_rulecap::Mode, + pub result: Option, +} + +/// Run `commands`, calling `on_decompile` after every `decompile` that +/// succeeds, however the line abbreviates it, except one after a failed +/// `load`: the function it would decompile is the one loaded before. `conf` preloads a program (the datatest ``). The first +/// failing command ends the run unless `keep_going`, which records it and goes +/// on. Returns the console, so the caller can read the program the script +/// loaded, and the failures it went past. +pub fn run( + commands: Vec, + conf: Option, + spec_roots: &[String], + keep_going: bool, + cap: Option<&mut Cap>, + mut on_decompile: impl FnMut(&ConsoleProgram, &Funcdata), +) -> Result<(IfaceStatus, Vec), String> { + run_steps(commands, conf, spec_roots, keep_going, cap, |step| { + if let Step::Decompiled { prog, fd, .. } = step { + on_decompile(prog, fd); + } + }) +} + +/// What [`run_steps`] reports as it goes, with the index of the command. +pub enum Step<'a> { + Decompiled { line: usize, prog: &'a ConsoleProgram, fd: &'a Funcdata }, + Failed { line: usize, msg: &'a str }, +} + +/// [`run`], reporting each failure as it happens too. +pub fn run_steps( + commands: Vec, + conf: Option, + spec_roots: &[String], + keep_going: bool, + mut cap: Option<&mut Cap>, + mut on_step: impl FnMut(Step<'_>), +) -> Result<(IfaceStatus, Vec), String> { + let mut console = ConsoleCommands::into_status(commands.clone()); + register_decomp_commands(&mut console); + register_kuna_commands(&mut console); + register_console_commands(&mut console); + console.set_error_is_done(true); + if let Some(d) = dcp_mut(&mut console) { + d.spec_roots = spec_roots.to_vec(); + if conf.is_some() { + d.conf = conf; + } + } + let mut idx = 0usize; + let mut failures = Vec::new(); + let mut stale = false; + let mut decompiles = 0usize; + let result = loop { + if console.is_stream_finished() { + break Ok(()); + } + let capped = cap.as_deref().is_some_and(|c| c.decompile == decompiles); + if let Some(c) = cap.as_deref().filter(|_| capped) { + if let Some(prog) = dcp_mut(&mut console).and_then(|d| d.conf.as_mut()) { + prog.arch_mut().kuna_fn_budget = Some(CAPPED_BUDGET); + } + kuna_decomp::kuna_rulecap::arm(c.mode.clone()); + } + execute(&mut console); + let applied = capped.then(kuna_decomp::kuna_rulecap::disarm); + let line = commands.get(idx).map(|s| s.trim().to_string()).unwrap_or_default(); + idx += 1; + let command = console.last_command.first().cloned().unwrap_or_default(); + if console.is_in_error() { + if command == "load" { + stale = true; + } + let said: Vec<&str> = console + .optr + .lines() + .map(str::trim) + .filter(|l| !l.is_empty() && *l != "Aborting process") + .collect(); + let msg = format!("`{line}` failed: {}", said.last().copied().unwrap_or("no message")); + if !keep_going { + break Err(msg); + } + on_step(Step::Failed { line: idx - 1, msg: &msg }); + failures.push((idx - 1, msg)); + console.inerror = false; + console.done = false; + } else if command == "load" && dcp(&console).is_some_and(|d| d.conf.is_none()) { + let said: Vec<&str> = console.optr.lines().map(str::trim).filter(|l| !l.is_empty()).collect(); + let why = said.iter().rev().find(|l| **l != "Could not create architecture").copied().unwrap_or("no message"); + let msg = format!("`{line}` loaded no image: {why}"); + stale = true; + if !keep_going { + break Err(msg); + } + on_step(Step::Failed { line: idx - 1, msg: &msg }); + failures.push((idx - 1, msg)); + } else if command == "load" { + stale = false; + } else if command == "decompile" && !stale { + if let Some(d) = dcp(&console) { + if let (Some(prog), Some(fd)) = (d.conf.as_ref(), d.fd.as_ref()) { + if let (Some(c), Some(a)) = (cap.as_deref_mut(), applied) { + c.result = Some(a); + } + on_step(Step::Decompiled { line: idx - 1, prog, fd }); + decompiles += 1; + } + } + if capped { + break Ok(()); + } + } + console.optr.clear(); + if let Some(f) = console.fileoptr.as_mut() { + f.contents.clear(); + } + }; + kuna_decomp::kuna_rulecap::disarm(); + result.map(|()| (console, failures)) +} + +/// [`run`], keeping only whether it succeeded. +pub fn drive( + commands: Vec, + conf: Option, + spec_roots: &[String], + on_decompile: impl FnMut(&ConsoleProgram, &Funcdata), +) -> Result<(), String> { + run(commands, conf, spec_roots, false, None, on_decompile).map(|_| ()) +} + +pub fn load_lines(path: &str, options: &[(String, String)]) -> Vec { + let mut lines = vec![format!("load file {}", quote_filename(path)), "option readonly on".to_string()]; + let named = |name: &str| options.iter().any(|(n, _)| n == name); + lines.extend( + driver_defaults(non_x86_64(path)) + .into_iter() + .filter(|(n, _)| !named(n)) + .map(|(n, v)| format!("option {n} {v}")), + ); + lines.extend(options.iter().map(|(n, v)| format!("option {n} {v}"))); + lines.push("read symbols".to_string()); + lines +} + +/// The options `kuna decompile` turns on for an object file unless named, so +/// the function checked is the one it prints: the Listing that call-graph +/// no-return propagation reads, and off x86-64 the discovery passes. The +/// instruction-budget truncation it also turns on is left off: a truncated +/// body is not the function. +fn driver_defaults(non_x86_64: bool) -> Vec<(&'static str, &'static str)> { + let mut on = vec![("listing", "on")]; + if non_x86_64 { + on.extend([("funcstart_patterns", "on"), ("aif", "on")]); + } + on +} + +/// Whether an ELF, PE or Mach-O header names a machine other than x86-64. +/// Anything else is taken as x86-64, as `kuna` takes an image it cannot parse. +fn non_x86_64(path: &str) -> bool { + let Ok(bytes) = std::fs::read(path) else { return false }; + let u16_at = |o: usize| bytes.get(o..o + 2).map(|b| u16::from_le_bytes([b[0], b[1]])); + let u32_at = |o: usize| bytes.get(o..o + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])); + if bytes.starts_with(b"\x7fELF") { + let machine = if bytes.get(5) == Some(&2) { u16_at(18).map(u16::swap_bytes) } else { u16_at(18) }; + return machine.is_some_and(|m| m != 62); + } + if bytes.starts_with(b"MZ") { + return u32_at(0x3c).and_then(|pe| u16_at(pe as usize + 4)).is_some_and(|m| m != 0x8664); + } + match u32_at(0) { + Some(0xfeed_facf | 0xfeed_face) => u32_at(4).is_some_and(|cpu| cpu != 0x0100_0007), + _ => false, + } +} + +/// The entry address of every function with code in an object file. +pub fn function_entries(path: &str, options: &[(String, String)], spec_roots: &[String]) -> Result, String> { + Ok(function_extents(path, options, spec_roots)?.into_iter().map(|(at, _)| at).collect()) +} + +/// [`function_entries`] with each function's byte extent, 0 where unknown. +pub fn function_extents(path: &str, options: &[(String, String)], spec_roots: &[String]) -> Result, String> { + let (console, _) = run(load_lines(path, options), None, spec_roots, false, None, |_, _| {})?; + let prog = dcp(&console).and_then(|d| d.conf.as_ref()).ok_or("no program loaded")?; + Ok(prog + .function_entries_executable() + .into_iter() + .filter(|e| prog.entry_bytes_mapped(&e.addr)) + .map(|e| (e.addr.get_offset(), e.size)) + .collect()) +} + +/// Load an object file and hand its program to `f`. +pub fn with_program( + path: &str, + options: &[(String, String)], + spec_roots: &[String], + f: impl FnOnce(&ConsoleProgram) -> R, +) -> Result { + let (console, _) = run(load_lines(path, options), None, spec_roots, false, None, |_, _| {})?; + let prog = dcp(&console).and_then(|d| d.conf.as_ref()).ok_or("no program loaded")?; + Ok(f(prog)) +} + +/// The console script that decompiles `functions` from an object file. A +/// function is a name, or an address written `0x...`. +pub fn binary_script(path: &str, functions: &[String], options: &[(String, String)]) -> Vec { + let mut lines = load_lines(path, options); + for f in functions { + let verb = if f.starts_with("0x") { "addr" } else { "function" }; + lines.push(format!("load {verb} {f}")); + lines.push("decompile".to_string()); + } + lines +} + +/// The load-option environment as a datatest found it, put back on drop. An +/// `option` command exports its load-time value to the process environment for +/// a later `load file` of its own script; without this the next datatest run in +/// the same process loads under it, and its verdicts depend on what ran before. +#[must_use = "the environment is put back when this drops"] +pub struct LoadEnv(EnvSnapshot); + +impl Drop for LoadEnv { + fn drop(&mut self) { + self.0.restore(); + } +} + +/// A datatest's program and script, and the environment to put back once the +/// script has run: hold the [`LoadEnv`] until then. +pub fn load_datatest(path: &str, spec_roots: &[String]) -> Result<(ConsoleProgram, Vec, LoadEnv), String> { + let env = LoadEnv(EnvSnapshot::capture()); + let mut store = DocumentStorage::new(); + let doc = store.open_document(path).map_err(|e| e.explain().to_string())?; + let root = doc.get_root().clone(); + if root.get_name() != "decompilertest" { + return Err(format!("{path}: not a ")); + } + let mut prog = None; + let mut commands = Vec::new(); + for child in root.get_children() { + match child.get_name() { + "binaryimage" => { + let arch = child + .get_attribute_value("arch") + .map_err(|e| format!("{path}: : {e}"))?; + let arch = String::from_utf8_lossy(arch).into_owned(); + prog = Some( + bootstrap_program(Rc::clone(child), &arch, spec_roots) + .map_err(|e| format!("{path}: {}", e.explain()))?, + ); + } + "script" => { + for com in child.get_children() { + let text: String = com + .get_content() + .iter() + .filter(|&&c| c != b'\r') + .map(|&c| if c == b'\n' { ' ' } else { c as char }) + .collect(); + commands.push(text); + } + } + _ => {} + } + } + let prog = prog.ok_or_else(|| format!("{path}: no "))?; + Ok((prog, commands, env)) +} diff --git a/decompiler/crates/kuna-verify/src/state/mem.rs b/decompiler/crates/kuna-verify/src/state/mem.rs new file mode 100644 index 0000000000..db01657894 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/state/mem.rs @@ -0,0 +1,187 @@ +//! Memory by 64-byte copy-on-write pages, temporaries by value, and the hasher both use. + +use super::*; + +/// The frame bytes a callee run for real reads. +pub type FrameReads = HashSet>; + +/// Memory this side wrote, in 64-byte pages each with a mask of the bytes set. +/// Every reader that needs an order collects into a sorted map, so the pages +/// need none. +#[derive(Clone, Default)] +pub(super) struct Mem { + /// Shared until written: cloning a state to run a callee for real copies + /// the page pointers, not the pages. + pub(super) pages: HashMap<(i32, u64), Rc, BuildHasherDefault>, +} + +#[derive(Clone)] +pub(super) struct Page { + pub(super) bytes: [u8; 64], + pub(super) set: u64, +} + +impl Mem { + pub(super) fn get(&self, sp: i32, off: u64) -> Option { + let p = self.pages.get(&(sp, off >> 6))?; + let i = off & 63; + (p.set >> i & 1 == 1).then(|| p.bytes[i as usize]) + } + + pub(super) fn contains(&self, sp: i32, off: u64) -> bool { + self.get(sp, off).is_some() + } + + pub(super) fn insert(&mut self, sp: i32, off: u64, b: u8) { + let p = Rc::make_mut(self.pages.entry((sp, off >> 6)).or_insert_with(|| Rc::new(Page { bytes: [0; 64], set: 0 }))); + let i = off & 63; + p.bytes[i as usize] = b; + p.set |= 1 << i; + } + + /// Every byte, in no order. + pub(super) fn iter(&self) -> impl Iterator + '_ { + self.pages.iter().flat_map(|(&(sp, page), p)| { + (0..64u64).filter(move |i| p.set >> i & 1 == 1).map(move |i| ((sp, page << 6 | i), p.bytes[i as usize])) + }) + } + + /// Every byte, in address order: the pages sorted, which are 64 times + /// fewer than the bytes, so a map built from them needs no sort of its own. + pub(super) fn iter_sorted(&self) -> impl Iterator + '_ { + let mut pages: Vec<_> = self.pages.iter().collect(); + pages.sort_unstable_by_key(|(k, _)| **k); + pages.into_iter().flat_map(|(&(sp, page), p)| { + (0..64u64).filter(move |i| p.set >> i & 1 == 1).map(move |i| ((sp, page << 6 | i), p.bytes[i as usize])) + }) + } + + /// The bytes of `sp` in `[start, end)`, in no order: the range's pages + /// looked up, or every page scanned when there are fewer of those. + pub(super) fn range(&self, sp: i32, start: u64, end: u64) -> Vec<(u64, u8)> { + if end <= start { + return Vec::new(); + } + let (first, last) = (start >> 6, (end - 1) >> 6); + let inside = |off: u64| off >= start && off < end; + if last - first < self.pages.len() as u64 { + (first..=last) + .filter_map(|page| self.pages.get(&(sp, page)).map(|p| (page, p))) + .flat_map(|(page, p)| (0..64u64).filter(move |i| p.set >> i & 1 == 1).map(move |i| (page << 6 | i, p.bytes[i as usize]))) + .filter(|&(off, _)| inside(off)) + .collect() + } else { + self.iter().filter(|&((s, off), _)| s == sp && inside(off)).map(|((_, off), b)| (off, b)).collect() + } + } + + /// The `size`-byte word at `off` when every byte of it is set: one page + /// lookup when it lies in one page. + pub(super) fn word(&self, sp: i32, off: u64, size: u64, big: bool) -> Option { + let i = off & 63; + let assemble = |byte: &dyn Fn(u64) -> Option| { + let mut v = 0u64; + for k in 0..size { + let shift = if big { size - 1 - k } else { k }; + v |= u64::from(byte(k)?) << (shift * 8); + } + Some(v) + }; + if i + size <= 64 { + let p = self.pages.get(&(sp, off >> 6))?; + let want = if size >= 64 { u64::MAX } else { ((1u64 << size) - 1) << i }; + if p.set & want != want { + return None; + } + return assemble(&|k| Some(p.bytes[(i + k) as usize])); + } + assemble(&|k| self.get(sp, off + k)) + } + + /// [`Self::retain`], asking `page_drops` first for the mask of a page's + /// bytes to drop, so a page it can answer for is not walked byte by byte. + pub(super) fn retain_pages(&mut self, mut page_drops: impl FnMut(i32, u64) -> Option, mut keep: impl FnMut(i32, u64) -> bool) { + self.pages.retain(|&(sp, page), p| { + let gone = match page_drops(sp, page) { + Some(m) => p.set & m, + None => (0..64u64).filter(|&i| p.set >> i & 1 == 1 && !keep(sp, page << 6 | i)).fold(0u64, |m, i| m | 1 << i), + }; + if gone != 0 { + Rc::make_mut(p).set &= !gone; + } + p.set != 0 + }); + } + + pub(super) fn retain(&mut self, mut keep: impl FnMut(i32, u64) -> bool) { + self.pages.retain(|&(sp, page), p| { + let gone = (0..64u64).filter(|&i| p.set >> i & 1 == 1 && !keep(sp, page << 6 | i)).fold(0u64, |m, i| m | 1 << i); + if gone != 0 { + Rc::make_mut(p).set &= !gone; + } + p.set != 0 + }); + } +} + +/// The temporaries of the current instruction, one entry per value written: +/// p-code reads a temporary as it wrote it, so a read is usually one lookup. +#[derive(Clone, Default)] +pub(super) struct Temps { + pub(super) entries: Vec<(u64, u32, u128, bool)>, +} + +impl Temps { + pub(super) fn exact(&self, off: u64, size: u32) -> Option { + self.entries.iter().rev().find(|e| e.0 == off && e.1 == size).map(|e| e.2) + } + + pub(super) fn byte(&self, off: u64) -> Option { + self.entries.iter().rev().find(|e| off >= e.0 && off - e.0 < u64::from(e.1)).map(|&(at, size, v, big)| { + let i = off - at; + let shift = if big { u64::from(size) - 1 - i } else { i }; + (v >> (shift * 8)) as u8 + }) + } + + pub(super) fn set(&mut self, off: u64, size: u32, v: u128, big: bool) { + let end = off + u64::from(size); + if self.entries.iter().any(|e| e.0 < end && off < e.0 + u64::from(e.1)) { + let old = std::mem::take(&mut self.entries); + for (at, n, val, b) in old { + if at < end && off < at + u64::from(n) { + for i in 0..u64::from(n) { + let o = at + i; + if o < off || o >= end { + let shift = if b { u64::from(n) - 1 - i } else { i }; + self.entries.push((o, 1, (val >> (shift * 8)) & 0xff, b)); + } + } + } else { + self.entries.push((at, n, val, b)); + } + } + } + self.entries.push((off, size, v & crate::value::mask(size), big)); + } +} + +/// A multiplicative hasher for the temporaries' byte offsets: they are +/// cleared every instruction, so the map keeps its capacity and its hashing +/// costs one multiply. +#[derive(Default, Clone, Copy)] +pub struct Fast(u64); + +impl std::hash::Hasher for Fast { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = (self.0.rotate_left(5) ^ u64::from(b)).wrapping_mul(0x51_7cc1_b727_220a_95); + } + } + fn write_u64(&mut self, n: u64) { + self.0 = (self.0.rotate_left(5) ^ n).wrapping_mul(0x51_7cc1_b727_220a_95); + } +} diff --git a/decompiler/crates/kuna-verify/src/state/mod.rs b/decompiler/crates/kuna-verify/src/state/mod.rs new file mode 100644 index 0000000000..79cb009959 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/state/mod.rs @@ -0,0 +1,1309 @@ +//! The raw machine state both sides start from. +//! +//! A run's initial state is a pure function of (seed, run, space, offset), so +//! the machine side and the decompiled side read the same register, stack and +//! memory values without either copying from the other. Registers and stack get +//! random words, the first runs and one word in eight are edge values, the stack +//! pointer is fixed, and image-backed memory reads the load image. Each side then +//! keeps its own writes on top. + +mod mem; +mod stack_inputs; +#[cfg(test)] +mod tests; + +pub(crate) use stack_inputs::StackInputs; +pub use mem::*; + +use std::cell::{Cell, RefCell}; +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::hash::BuildHasherDefault; +use std::rc::Rc; + +use kuna_base::address::{Address, RangeList}; +use kuna_base::space::{spacetype, AddrSpace}; +use kuna_console::engine::ConsoleProgram; + +use crate::value::{mask, Halt, MAX_SIZE}; + +/// Runs whose every register word is an edge value. +pub const EDGE_RUNS: u32 = 16; + +/// The stack below the entry stack pointer: room for a large frame. +const STACK_BELOW: u64 = 0x80_0000; + +/// How far past an escaped pointer a call may write. +const ESCAPE_WINDOW: u64 = 0x1000; +const STACK_ABOVE: u64 = 0x1000; + +/// A register the ABI promises is extended: an argument the caller passes, or +/// a value a callee returns. Bytes of `container` outside the value repeat its +/// sign, or are zero. +#[derive(Debug, Clone)] +pub struct Extension { + pub space: i32, + pub container: (u64, u32), + pub param: (u64, u32), + pub signed: bool, + /// A `bool` return: the callee leaves 0 or 1 in `param`. + pub boolean: bool, +} + +/// Pointer-sized values passed to calls so far, and the bytes a callee +/// given them can reach, as sorted, disjoint `[first, last]` ranges. +#[derive(Clone, Debug, Default)] +pub struct Escaped { + pointers: Vec, + reach: Vec<(u64, u64)>, +} + +impl Escaped { + pub fn add(&mut self, env: &Env, pointers: impl Iterator) { + let before = self.pointers.len(); + self.pointers.extend(pointers); + self.pointers.sort_unstable(); + self.pointers.dedup(); + if self.pointers.len() == before { + return; + } + let mut reach = Vec::with_capacity(self.pointers.len()); + for &p in &self.pointers { + env.reach_of(p, &mut reach); + } + self.reach = merge_ranges(reach); + } + + pub fn reaches(&self, off: u64) -> bool { + let i = self.reach.partition_point(|r| r.0 <= off); + i > 0 && self.reach[i - 1].1 >= off + } + + /// The bytes of the 64-byte page at `base` that are reached, as a mask. + fn page_mask(&self, base: u64) -> u64 { + let last = base + 63; + let mut m = 0u64; + let mut i = self.reach.partition_point(|r| r.1 < base); + while let Some(&(first, end)) = self.reach.get(i).filter(|r| r.0 <= last) { + let (lo, hi) = (first.max(base) - base, end.min(last) - base); + m |= if hi - lo == 63 { u64::MAX } else { ((1u64 << (hi - lo + 1)) - 1) << lo }; + i += 1; + } + m + } +} + +/// The trap a store into read-only memory or code raises. +pub const READONLY_STORE: &str = "store to read-only memory"; + +/// `[first, last]` ranges sorted, with overlapping and adjacent ones joined. +fn merge_ranges(mut ranges: Vec<(u64, u64)>) -> Vec<(u64, u64)> { + ranges.sort_unstable(); + let mut out: Vec<(u64, u64)> = Vec::with_capacity(ranges.len()); + for (first, last) in ranges { + match out.last_mut() { + Some(prev) if first <= prev.1.saturating_add(1) => prev.1 = prev.1.max(last), + _ => out.push((first, last)), + } + } + out +} + +/// What a run needs to know about the program: its spaces, the stack layout, +/// the image, and the argument extensions the calling convention promises. +pub struct Env<'p> { + pub prog: &'p ConsoleProgram, + pub seed: u64, + pub register: Rc, + pub ram: Rc, + pub code: Rc, + pub unique: Option>, + /// The stack pointer's register storage. + pub sp: (u64, u32), + /// The stack pointer's value at entry. + pub sp0: u64, + granule: u32, + edges: Vec, + readonly: Vec<(u64, u64)>, + /// The image's code sections, `[first, last]`, merged; empty without a + /// section table. + code_sections: Vec<(u64, u64)>, + pub extensions: Vec, + /// Storage the context or the loader gives a known value at the + /// function's entry (a PowerPC TOC, a MIPS t9, AVR's zero register, the + /// return address): space, offset, size, value. + pub tracked: Vec<(i32, u64, u32, u64)>, + /// The return address the function starts with, when the model names + /// where it is: a RETURN to it leaves the function. + pub ret_addr: Option, + /// Bytes a call pushes for its return address on the stack (0 when the + /// model keeps it in a register). + pub ret_slot: u32, + /// Register parameters of type `bool`: a caller passes 0 or 1. + pub booleans: Vec<(i32, u64, u32)>, + /// The machine's system calls write the kernel's result registers. + pub kernel: Cell, + /// A stub kills only the registers kuna's IR says the callee does not + /// preserve, instead of the calling convention's: the rerun that tells + /// whether kuna's preservation claim decides a run. + pub stub_recovered: Cell, + /// A callee run for real that returns keeps the registers the convention + /// says it preserves, as it left them: the rerun that tells whether a + /// violation decides a run. + pub keep_clobbers: Cell, + /// ARM and AArch64 divide by zero to 0 instead of trapping. + pub divide_by_zero_is_zero: bool, + /// Image pages by base address; `None` for a page not mapped whole. + image: RefCell>, BuildHasherDefault>>, + /// The loader's segments and sections, `[first, last]`: no image byte lies + /// outside them. `None` when the loader lists no segments. + mapped: Option>, + /// Bytes of the pages not mapped whole. + image_bytes: RefCell, BuildHasherDefault>>, + /// Where a call to each target goes once thunks are followed. + pub(crate) thunks: RefCell>, + /// The calling convention's argument registers: a thunk that writes one + /// changes the call, so it is no thunk. + pub arg_regs: Vec<(u64, u32)>, + /// The registers the ABI reserves for veneers (ARM's `ip`, AArch64's + /// `x16`/`x17`): the only ones a transparent thunk may write. + pub scratch_regs: Vec<(u64, u32)>, + /// Where a call to each target goes through transparent thunks only. + pub(crate) transparent: RefCell>, + pub(crate) insns: RefCell, BuildHasherDefault>>, + entries: std::cell::OnceCell>, + stack: Rc, + /// The decompiled function, whose local symbols give the extent of a + /// stack object whose address escapes. + pub fd: Option<&'p kuna_decomp::funcdata::Funcdata>, + locals: RefCell, BuildHasherDefault>>, + /// What the name of the function each call target leads to says about + /// whether it returns: looked up once per target, not at every call. + pub(crate) noreturn_names: RefCell>>, +} + +fn splitmix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +fn edge_values(granule: u32) -> Vec { + let bits = granule * 8; + let m = mask(granule) as u64; + let mut v = vec![ + 0, + 1, + 2, + m, + 1u64 << (bits - 1), + m >> 1, + 0x7f, + 0x80, + 0xff, + 0x7fff, + 0x8000, + 0xffff, + 0x1_0000, + 0x7fff_ffff, + 0x8000_0000, + 0xffff_ffff, + 7, + 8, + 15, + 16, + 31, + 32, + 63, + 64, + ]; + for x in &mut v { + *x &= m; + } + v.sort_unstable(); + v.dedup(); + v +} + +impl<'p> Env<'p> { + pub fn new(prog: &'p ConsoleProgram, seed: u64) -> Result { + let manage = prog.arch().manage(); + let register = manage + .get_space_by_name("register") + .cloned() + .ok_or_else(|| Halt::Harness("no register space".into()))?; + let data = manage + .get_default_data_space() + .cloned() + .ok_or_else(|| Halt::Harness("no default data space".into()))?; + let code = manage + .get_default_code_space() + .cloned() + .ok_or_else(|| Halt::Harness("no default code space".into()))?; + let unique = manage.get_unique_space().cloned(); + let stack = manage + .get_stack_space() + .ok_or_else(|| Halt::Harness("no stack space".into()))?; + let base = stack + .get_spacebase(0) + .map_err(|e| Halt::Harness(format!("stack pointer: {}", e.explain())))?; + let ram = stack.get_contain().cloned().unwrap_or(data); + let ram_mask = ram.get_highest(); + let mut sp0 = (ram_mask >> 1) & !0xffff; + if sp0 == 0 { + sp0 = (ram_mask >> 1) & !0xff; + } + let granule = ram.get_addr_size().clamp(1, 8); + let mut ranges = RangeList::new(); + prog.arch().translate().loader_rc().borrow().get_readonly(&mut ranges); + let readonly = ranges + .iter() + .filter(|r| r.get_space().get_index() == ram.get_index() || r.get_space().get_index() == code.get_index()) + .map(|r| (r.get_first(), r.get_last())) + .collect::>(); + let readonly = merge_ranges(readonly); + let segments = prog.segments(); + let mapped = (!segments.is_empty()).then(|| { + let spans = segments.into_iter().chain(prog.sections()).filter(|&(_, size, _)| size > 0); + merge_ranges(spans.map(|(start, size, _)| (start, start.saturating_add(size - 1))).collect()) + }); + let code_sections = prog + .sections() + .into_iter() + .filter(|&(_, size, flags)| size > 0 && flags & kuna_sleigh::loadimage::section_flags::CODE != 0) + .map(|(start, size, _)| (start, start.saturating_add(size - 1))) + .collect(); + let code_sections = merge_ranges(code_sections); + Ok(Env { + prog, + seed, + register, + ram, + code, + unique, + sp: (base.offset, base.size), + sp0, + granule, + edges: edge_values(granule), + readonly, + code_sections, + extensions: Vec::new(), + tracked: Vec::new(), + ret_addr: None, + ret_slot: 0, + booleans: Vec::new(), + kernel: Cell::new(true), + stub_recovered: Cell::new(false), + keep_clobbers: Cell::new(false), + divide_by_zero_is_zero: ["ARM", "AARCH64"].iter().any(|a| prog.arch().archid.starts_with(a)), + image: RefCell::new(HashMap::default()), + mapped, + image_bytes: RefCell::new(HashMap::default()), + thunks: RefCell::new(HashMap::new()), + arg_regs: Vec::new(), + scratch_regs: Vec::new(), + transparent: RefCell::new(HashMap::new()), + insns: RefCell::new(HashMap::default()), + entries: std::cell::OnceCell::new(), + stack: Rc::clone(stack), + fd: None, + locals: RefCell::new(HashMap::default()), + noreturn_names: RefCell::new(HashMap::default()), + }) + } + + pub fn in_stack(&self, addr: u64, size: u64) -> bool { + let below = STACK_BELOW.min(self.sp0 / 2); + addr >= self.sp0.wrapping_sub(below) && addr.wrapping_add(size) <= self.sp0.wrapping_add(STACK_ABOVE) + } + + fn is_readonly(&self, addr: u64, size: u64) -> bool { + let last = addr.wrapping_add(size.saturating_sub(1)); + let i = self.readonly.partition_point(|r| r.0 <= addr); + last >= addr && i > 0 && self.readonly[i - 1].1 >= last + } + + /// A function entry the program knows, not code an arbitrary pointer + /// lands in. + pub fn is_entry(&self, addr: u64) -> bool { + self.entries().contains(&addr) + } + + fn entries(&self) -> &BTreeSet { + self.entries.get_or_init(|| self.prog.function_entries_canonical().iter().map(|e| e.addr.get_offset()).collect()) + } + + /// Whether a function the program knows starts at `addr`. + pub fn function_starts_at(&self, addr: u64) -> bool { + self.entries().contains(&addr) + } + + /// A function other than the one at `addr`: the next one, or the first. + pub fn another_function(&self, addr: u64) -> Option { + let e = self.entries(); + e.range(addr.wrapping_add(1)..).next().or_else(|| e.iter().next()).copied().filter(|&f| f != addr) + } + + pub fn code_mapped(&self, addr: u64) -> bool { + self.prog.entry_bytes_mapped(&Address::new(Rc::clone(&self.code), addr)) + } + + /// Whether `addr` lies in a section the loader marks as code: no callee + /// writes there, literal pools included. + fn in_code_section(&self, addr: u64) -> bool { + let i = self.code_sections.partition_point(|r| r.0 <= addr); + i > 0 && self.code_sections[i - 1].1 >= addr + } + + /// Whether `addr` is mapped code: in a section the loader marks as code, + /// or anywhere mapped in an image without a section table. + pub fn is_code(&self, addr: u64) -> bool { + self.code_mapped(addr) + && (self.code_sections.is_empty() || self.in_code_section(addr)) + } + + /// A byte of the loaded image, read a page at a time. A page the loader + /// does not map whole is read a byte at a time, as each byte is asked for: + /// a random pointer lands in one far more often than in the image. + pub(crate) fn image_byte(&self, addr: u64) -> Option { + if let Some(m) = &self.mapped { + let i = m.partition_point(|r| r.0 <= addr); + if i == 0 || m[i - 1].1 < addr { + return None; + } + } + let page = addr & !(IMAGE_PAGE - 1); + let at = (addr - page) as usize; + let known = self.image.borrow().get(&page).map(|p| p.as_ref().map(|bytes| bytes[at])); + match known { + Some(Some(b)) => return Some(b), + Some(None) => {} + None => { + let base = Address::new(Rc::clone(&self.ram), page); + let whole = self + .prog + .read_bytes_at(&base, IMAGE_PAGE as usize) + .filter(|v| v.len() == IMAGE_PAGE as usize) + .map(Vec::into_boxed_slice); + let b = whole.as_ref().map(|bytes| bytes[at]); + self.image.borrow_mut().insert(page, whole); + if b.is_some() { + return b; + } + } + } + if let Some(b) = self.image_bytes.borrow().get(&addr) { + return *b; + } + let b = self.prog.read_bytes_at(&Address::new(Rc::clone(&self.ram), addr), 1).map(|v| v[0]); + self.image_bytes.borrow_mut().insert(addr, b); + b + } + + fn word(&self, run: u32, space: i32, index: u64) -> u64 { + let h = splitmix( + self.seed + ^ u64::from(run).wrapping_mul(0xd6e8_feb8_6659_fd93) + ^ ((space as u64) << 56) + ^ index.wrapping_mul(0xc2b2_ae3d_27d4_eb4f), + ); + let v = if run < EDGE_RUNS || h.is_multiple_of(8) { + self.edges[(h >> 8) as usize % self.edges.len()] + } else { + splitmix(h) + }; + v & mask(self.granule) as u64 + } + + fn byte_of(word: u64, pos: u64, width: u64, big: bool) -> u8 { + let shift = if big { width - 1 - pos } else { pos }; + (word >> (shift * 8)) as u8 + } + + fn random_byte(&self, run: u32, space: &AddrSpace, off: u64) -> u8 { + let g = u64::from(self.granule); + Self::byte_of(self.word(run, space.get_index(), off / g), off % g, g, space.is_big_endian()) + } + + fn extended_byte(&self, run: u32, space: &AddrSpace, off: u64) -> Option { + let x = self.extensions.iter().find(|x| { + let (c, cs) = x.container; + let (p, ps) = x.param; + x.space == space.get_index() && off >= c && off < c + u64::from(cs) && !(off >= p && off < p + u64::from(ps)) + })?; + let (p, ps) = x.param; + let mut v = 0u128; + for i in 0..u64::from(ps) { + let b = u128::from(self.random_byte(run, space, p + i)); + v = if space.is_big_endian() { (v << 8) | b } else { v | (b << (8 * i)) }; + } + let negative = x.signed && (v >> (ps * 8 - 1)) & 1 == 1; + let ext = if negative { v | !mask(ps) } else { v }; + let (c, cs) = x.container; + let pos = off - c; + let shift = if space.is_big_endian() { u64::from(cs) - 1 - pos } else { pos }; + Some((ext >> (shift * 8)) as u8) + } + + /// A byte of writable memory after the `epoch`-th call: the callee may + /// have written any of it. + fn clobbered_byte(&self, run: u32, epoch: u32, space: &AddrSpace, off: u64) -> u8 { + let h = splitmix( + self.seed + ^ u64::from(run).wrapping_mul(0xd6e8_feb8_6659_fd93) + ^ u64::from(epoch).wrapping_mul(0x9e37_79b9_7f4a_7c15) + ^ ((space.get_index() as u64) << 56) + ^ off.wrapping_mul(0xc2b2_ae3d_27d4_eb4f), + ); + h as u8 + } + + fn is_memory(&self, space: &AddrSpace) -> bool { + space.get_index() != self.register.get_index() + && !self.unique.as_ref().is_some_and(|u| u.get_index() == space.get_index()) + } + + /// Memory either side's caller can observe after the function: anything + /// but registers, temporaries and the stack. + pub fn observable(&self, space: &AddrSpace, off: u64) -> bool { + self.is_memory(space) && !(space.get_index() == self.ram.get_index() && self.in_stack(off, 1)) + } + + /// Memory a call can write: the image's writable data, and the bytes near + /// a pointer that escaped into an earlier call, never read-only data or code. This + /// is no more than kuna itself treats as changed by a call, so a value it + /// keeps across one stays equal unless kuna is wrong to keep it. + pub fn callee_writable(&self, escaped: &Escaped, space: &AddrSpace, off: u64) -> bool { + if !self.is_memory(space) || self.is_readonly(off, 1) || self.in_code_section(off) { + return false; + } + escaped.reaches(off) || (space.get_index() == self.ram.get_index() && !self.in_stack(off, 1) && self.image_byte(off).is_some()) + } + + /// The bytes of the 64-byte page at `base` that are [`Self::callee_writable`], + /// as a mask, where the page decides it at once: on a frame page, or + /// outside `ram`, they are what an escaped pointer reaches, unless the + /// page also holds read-only data or code. `None` asks byte by byte. + fn callee_writable_page(&self, escaped: &Escaped, space: &AddrSpace, base: u64) -> Option { + if !self.is_memory(space) { + return Some(0); + } + let last = base.checked_add(63)?; + if space.get_index() == self.ram.get_index() && !self.in_stack(base, 64) { + return None; + } + let reached = escaped.page_mask(base); + let any = |r: &[(u64, u64)]| { + let i = r.partition_point(|x| x.0 <= last); + i > 0 && r[i - 1].1 >= base + }; + (reached == 0 || !(any(&self.readonly) || any(&self.code_sections))).then_some(reached) + } + + /// The bytes a callee given `p` reaches, `[first, last]`: the local object + /// kuna gives `p` when it points into the frame, else a window past it. + fn reach_of(&self, p: u64, out: &mut Vec<(u64, u64)>) { + if self.in_stack(p, 1) { + if let Some((start, end)) = self.stack_object(p).filter(|(s, e)| e > s) { + out.push((start, end - 1)); + } + return; + } + let last = p.wrapping_add(ESCAPE_WINDOW - 1); + if last >= p { + out.push((p, last)); + } else { + out.push((p, u64::MAX)); + out.push((0, last)); + } + } + + /// The `[start, end)` of the local symbol of kuna's that holds frame + /// address `p`, or of the register save area when `varargsave` folded it: + /// the bytes `va_start` defines, not the padding kuna's symbol may take in. + pub fn stack_object(&self, p: u64) -> Option<(u64, u64)> { + if let Some(hit) = self.locals.borrow().get(&p) { + return *hit; + } + let found = self.fd.and_then(|fd| { + if let Some(f) = fd.vararg_folded() { + let start = self.ram.wrap_offset(self.sp0.wrapping_add(f.area as u64)); + let end = start.wrapping_add(kuna_decomp::kuna_varargsave::SAVE_AREA as u64); + if p >= start && p < end { + return Some((start, end)); + } + } + let local = fd.get_scope_local()?; + let db = local.database(); + let at = Address::new(Rc::clone(&self.stack), self.stack.wrap_offset(p.wrapping_sub(self.sp0))); + let entry = db.entry(local.scope_id(), db.find_container_ignore_usepoint(local.scope_id(), &at, 1)?); + let start = self.ram.wrap_offset(self.sp0.wrapping_add(entry.get_first())); + let size = u64::try_from(entry.get_size()).ok().filter(|&s| s > 0)?; + start.checked_add(size).map(|end| (start, end)) + }); + self.locals.borrow_mut().insert(p, found); + found + } + + /// The byte at `off` with no write by a side since its last call: the + /// initial state before any call, what the calls left after one. + pub fn base_byte(&self, run: u32, epoch: u32, escaped: &Escaped, space: &AddrSpace, off: u64) -> u8 { + if epoch > 0 && self.callee_writable(escaped, space, off) { + self.clobbered_byte(run, epoch, space, off) + } else { + self.initial_byte(run, space, off) + } + } + + /// The value a call leaves in a register byte it kills. + pub fn killed_byte(&self, run: u32, call: u32, off: u64) -> u8 { + self.clobbered_byte(run, call + 1, &self.register, off) + } + + pub fn initial_byte(&self, run: u32, space: &AddrSpace, off: u64) -> u8 { + let idx = space.get_index(); + if let Some(&(_, t, size, val)) = + self.tracked.iter().find(|&&(sp, t, size, _)| sp == idx && off >= t && off < t + u64::from(size)) + { + return Self::byte_of(val, off - t, u64::from(size), space.is_big_endian()); + } + if let Some(&(_, b, size)) = + self.booleans.iter().find(|&&(sp, b, size)| sp == idx && off >= b && off < b + u64::from(size)) + { + let low = if space.is_big_endian() { b + u64::from(size) - 1 } else { b }; + return if off == low { self.random_byte(run, space, off) & 1 } else { 0 }; + } + if self.unique.as_ref().is_some_and(|u| u.get_index() == idx) { + return 0; + } + if idx == self.register.get_index() { + let (sp_off, sp_size) = self.sp; + if off >= sp_off && off < sp_off + u64::from(sp_size) { + return Self::byte_of(self.sp0, off - sp_off, u64::from(sp_size), space.is_big_endian()); + } + if let Some(b) = self.extended_byte(run, space, off) { + return b; + } + } else if idx == self.ram.get_index() && !self.in_stack(off, 1) { + if let Some(b) = self.image_byte(off) { + return b; + } + } + self.random_byte(run, space, off) + } +} + +/// Register offsets past this go through the sparse map. +const DENSE_REGISTERS: u64 = 1 << 20; + +/// Bytes of the image read at once. +const IMAGE_PAGE: u64 = 256; + +const PRESENT: u8 = 1; +const WRITTEN: u8 = 2; + +/// One side's view: the run's initial state plus that side's writes. +/// +/// Registers live in a dense file that memoizes their initial bytes on first +/// read; temporaries and memory keep only the bytes this side wrote. +#[derive(Clone)] +pub struct State<'e, 'p> { + pub env: &'e Env<'p>, + pub run: u32, + regs: Vec, + flags: Vec, + unique: Temps, + mem: Mem, + /// Calls made so far. + pub epoch: u32, + /// Pointer-sized values passed to calls so far. + pub escaped: Escaped, + /// While a callee runs for real: what it does to memory, in order. + pub log: Option>, + /// This side read a byte of the function's own frame that nothing wrote: + /// an uninitialized local, whose value C does not define. + pub read_uninitialized: bool, + /// Stack bytes that hold a callee-saved register's entry value, by the + /// register offset they came from: the prologue's spills. + saved: BTreeMap, + /// This side read a spilled entry value back into anything but the + /// register it came from: what C sees there is uninitialized too. + pub read_saved: bool, + /// While a callee runs for real: the frame bytes it reads. + pub frame_reads: Option, + /// Code other than the function's own is running (a callee run for real + /// or followed); what it writes in the frame is not the function's. + pub in_callee_code: bool, + /// While a callee runs for real: the argument-register bytes it reads + /// before writing them. + pub live: Option, + /// Frame objects a call received a pointer to so far. + passed_objects: Vec<(u64, u64)>, + /// Varies what a stub leaves in the registers it kills. + pub kill_salt: u32, + /// Registers `kill_salt` leaves alone. + pub kill_salt_skip: Vec<(u64, u32)>, + /// Frame bytes last written by such code: a frame object's comparison at + /// a call leaves them out, as a helper's leftovers in a buffer C never + /// initialized. + callee_written: HashSet>, +} + +/// The argument-register bytes a callee run for real reads before writing +/// them: what it takes from its caller. A read whose value only goes to a +/// stack store (a spill, a `push`, a varargs prologue) is not one. +#[derive(Clone, Debug)] +pub struct LiveIn { + /// Per register byte up to the last argument register's end: an + /// argument register's byte, and whether the callee wrote it. + tracked: Vec, + written: Vec, + pub read: BTreeMap, + pub(crate) stack: Option, + /// Reads by the current op, committed when the next op starts. + last: Vec<(u64, u8)>, + /// Reads a COPY moved into a temporary this instruction, by its offset. + pending: Vec<(u64, Vec<(u64, u8)>)>, +} + +impl LiveIn { + pub fn new(regs: Vec<(u64, u32)>) -> Self { + let end = regs.iter().map(|&(o, n)| (o + u64::from(n)) as usize).max().unwrap_or(0).min(DENSE_REGISTERS as usize); + let mut tracked = vec![false; end]; + for &(o, n) in ®s { + for at in o..o + u64::from(n) { + if let Some(t) = tracked.get_mut(at as usize) { + *t = true; + } + } + } + LiveIn { written: vec![false; end], tracked, read: BTreeMap::new(), stack: None, last: Vec::new(), pending: Vec::new() } + } + + fn saw(&mut self, off: u64, b: u8) { + let i = off as usize; + if self.tracked.get(i) == Some(&true) && !self.written[i] && !self.read.contains_key(&off) { + self.last.push((off, b)); + } + } + + fn wrote(&mut self, off: u64) { + if let Some(w) = self.written.get_mut(off as usize) { + *w = true; + } + } + + /// An op starts: what the previous op read is an input. + pub fn op(&mut self) { + for (off, b) in self.last.drain(..) { + self.read.entry(off).or_insert(b); + } + } + + /// The current op copied what it read into temporary `u`. + pub fn copied(&mut self, u: u64) { + let reads = std::mem::take(&mut self.last); + self.pending.push((u, reads)); + } + + /// The current op stored what it read, or temporary `u`, to the stack. + pub fn spilled(&mut self, u: Option) { + self.last.clear(); + if let Some(u) = u { + self.pending.retain(|(t, _)| *t != u); + } + } + + /// An instruction ends: copies it did not spill are inputs. + pub fn instruction(&mut self) { + self.op(); + for (_, reads) in std::mem::take(&mut self.pending) { + for (off, b) in reads { + self.read.entry(off).or_insert(b); + } + } + } +} + +/// One thing a callee run for real did to memory. +#[derive(Clone, Debug)] +pub enum Event { + Write(i32, u64, u8), + /// A call it made in turn, with the killed registers, its arguments and + /// the extension of its return value. + Call(Vec<(u64, u32)>, Vec, Option), +} + +/// What a callee in the image did when the machine ran it, for the decompiled +/// side to replay: its memory events, and the bytes it left in the registers +/// the call kills. +#[derive(Clone, Debug, Default)] +pub struct Effect { + pub events: Vec, + pub regs: Vec<(u64, u8)>, +} + +/// The memory a side wrote outside the stack since its last call, and how many +/// calls preceded it: what a callee, or the caller after the return, can read. +#[derive(Clone, Debug, Default)] +pub struct Writes { + pub bytes: BTreeMap<(i32, u64), u8>, + /// Frame bytes a callee's code left in an object this side passes: not + /// compared on either side. + pub skip: BTreeSet, + /// The frame objects, `[start, end)`, this side passes to the call. Only + /// those both sides pass are compared. + pub objects: Vec<(u64, u64)>, + pub epoch: u32, + pub escaped: Escaped, +} + +impl<'e, 'p> State<'e, 'p> { + pub fn new(env: &'e Env<'p>, run: u32) -> Self { + State { + env, + run, + regs: Vec::new(), + flags: Vec::new(), + unique: Temps::default(), + mem: Mem::default(), + epoch: 0, + escaped: Escaped::default(), + log: None, + read_uninitialized: false, + saved: BTreeMap::new(), + read_saved: false, + frame_reads: None, + in_callee_code: false, + callee_written: HashSet::default(), + live: None, + passed_objects: Vec::new(), + kill_salt: 0, + kill_salt_skip: Vec::new(), + } + } + + /// Mark a stack store as the spill of a callee-saved register's entry value. + pub fn mark_saved(&mut self, at: u64, size: u32, reg: u64) { + for i in 0..u64::from(size) { + self.saved.insert(at.wrapping_add(i), reg); + } + } + + /// The callee-saved registers whose spilled entry values the range holds. + pub fn saved_in(&self, at: u64, size: u32) -> Vec { + if self.saved.is_empty() || size == 0 { + return Vec::new(); + } + let mut regs: Vec = self.saved.range(at..=at.saturating_add(u64::from(size) - 1)).map(|(_, &r)| r).collect(); + regs.dedup(); + regs + } + + /// Forget what this side wrote to the stack below `sp`: after a call + /// returns, what is there (its return address, its frame) is no local. + pub fn forget_below(&mut self, sp: u64) { + let ram = self.env.ram.get_index(); + let below = STACK_BELOW.min(self.env.sp0 / 2); + let lo = self.env.sp0.wrapping_sub(below); + if sp <= lo { + return; + } + self.mem.retain(|s, off| s != ram || off < lo || off >= sp); + let dead: Vec = self.saved.range(lo..sp).map(|(k, _)| *k).collect(); + for k in dead { + self.saved.remove(&k); + } + } + + fn is_register(&self, space: &AddrSpace, off: u64) -> bool { + space.get_index() == self.env.register.get_index() && off < DENSE_REGISTERS + } + + /// C5: whether the byte at `off` still holds the run's initial value: this + /// side has not written it, and for memory, no call has run yet. + pub fn untouched(&self, space: &AddrSpace, off: u64) -> bool { + if self.is_register(space, off) { + return self.flags.get(off as usize).is_none_or(|f| f & WRITTEN == 0); + } + if self.is_unique(space) { + return false; + } + self.epoch == 0 && !self.mem.contains(space.get_index(), off) + } + + fn is_unique(&self, space: &AddrSpace) -> bool { + self.env.unique.as_ref().is_some_and(|u| u.get_index() == space.get_index()) + } + + fn grow(&mut self, end: usize) { + if self.regs.len() < end { + self.regs.resize(end, 0); + self.flags.resize(end, 0); + } + } + + fn byte(&mut self, space: &AddrSpace, off: u64) -> u8 { + if self.is_register(space, off) { + let i = off as usize; + self.grow(i + 1); + if self.flags[i] & PRESENT == 0 { + self.regs[i] = self.env.initial_byte(self.run, space, off); + self.flags[i] |= PRESENT; + } + let b = self.regs[i]; + if let Some(l) = self.live.as_mut() { + l.saw(off, b); + } + return b; + } + let found = if self.is_unique(space) { self.unique.byte(off) } else { self.mem.get(space.get_index(), off) }; + if let Some(reads) = self.frame_reads.as_mut() { + if space.get_index() == self.env.ram.get_index() && self.env.in_stack(off, 1) { + reads.insert(off); + } + } + if found.is_none() + && space.get_index() == self.env.ram.get_index() + && off < self.env.sp0 + && self.env.in_stack(off, 1) + { + self.read_uninitialized = true; + } + let b = found.unwrap_or_else(|| self.env.base_byte(self.run, self.epoch, &self.escaped, space, off)); + if let Some(stack) = self.live.as_mut().and_then(|l| l.stack.as_mut()) { + if space.get_index() == self.env.ram.get_index() { + stack.read(off, b); + } + } + b + } + + fn put(&mut self, space: &AddrSpace, off: u64, b: u8) { + if self.is_register(space, off) { + let i = off as usize; + self.grow(i + 1); + self.regs[i] = b; + self.flags[i] |= PRESENT | WRITTEN; + if let Some(l) = self.live.as_mut() { + l.wrote(off); + } + } else if self.is_unique(space) { + self.unique.set(off, 1, u128::from(b), false); + } else { + if let Some(log) = self.log.as_mut() { + log.push(Event::Write(space.get_index(), off, b)); + } + self.mem.insert(space.get_index(), off, b); + if let Some(stack) = self.live.as_mut().and_then(|l| l.stack.as_mut()) { + if space.get_index() == self.env.ram.get_index() { + stack.write(off); + } + } + if space.get_index() == self.env.ram.get_index() && self.env.in_stack(off, 1) { + if self.in_callee_code { + self.callee_written.insert(off); + } else if !self.callee_written.is_empty() { + self.callee_written.remove(&off); + } + } + } + } + + /// Do what a callee did when the machine ran it. + pub fn replay(&mut self, effect: &Effect) { + let manage = self.env.prog.arch().manage(); + for ev in &effect.events { + match ev { + Event::Write(sp, off, b) => { + if let Some(space) = manage.get_space(*sp).cloned() { + self.put(&space, *off, *b); + } + } + Event::Call(killed, args, ext) => self.call(killed, args, ext.as_ref()), + } + } + let register = Rc::clone(&self.env.register); + for &(off, b) in &effect.regs { + self.put(®ister, off, b); + } + } + + /// The bytes now in the given register ranges. + pub fn register_bytes(&mut self, ranges: &[(u64, u32)]) -> Vec<(u64, u8)> { + let register = Rc::clone(&self.env.register); + ranges + .iter() + .flat_map(|&(off, size)| (0..u64::from(size)).map(move |i| off + i)) + .map(|o| (o, self.byte(®ister, o))) + .collect() + } + + /// Every register byte this side holds, written or read: `(offset, byte)`. + pub fn register_file(&self) -> Vec<(u64, u8)> { + self.flags.iter().enumerate().filter(|(_, f)| **f & PRESENT != 0).map(|(i, _)| (i as u64, self.regs[i])).collect() + } + + /// The register file, with the bytes of `regs` nothing has read or written + /// yet added at the value they start the run with, without reading them. + pub fn register_file_with(&self, regs: &[crate::storage::Storage]) -> Vec<(u64, u8)> { + let mut file = self.register_file(); + for st in regs.iter().filter(|st| st.space.get_index() == self.env.register.get_index()) { + for off in st.off..st.off + u64::from(st.size) { + if self.flags.get(off as usize).is_none_or(|f| f & PRESENT == 0) { + file.push((off, self.env.initial_byte(self.run, &self.env.register, off))); + } + } + } + file + } + + /// Put back every register byte `before` held, except those in `keep`: + /// a callee run for real leaves the registers the calling convention says + /// it preserves as they were. Returns the offsets the callee had changed. + /// Put back the bytes of `regs` to what `before` held. Returns the + /// offsets the callee had changed. + pub fn restore_registers(&mut self, before: &State, regs: &[(u64, u32)]) -> Vec { + let mut changed = Vec::new(); + for &(off, size) in regs { + for o in off..off + u64::from(size) { + let i = o as usize; + let (b, f) = (before.regs.get(i).copied().unwrap_or(0), before.flags.get(i).copied().unwrap_or(0)); + self.grow(i + 1); + let present_now = self.flags[i] & PRESENT != 0; + if present_now && f & PRESENT != 0 && self.regs[i] != b { + changed.push(o); + } + if present_now || f & PRESENT != 0 { + self.regs[i] = b; + self.flags[i] = f; + } + } + } + changed + } + + pub fn preserve_registers(&mut self, before: &State, keep: &[(u64, u32)]) -> Vec { + let mut changed = Vec::new(); + let n = self.regs.len().max(before.regs.len()); + self.grow(n); + let mut kept = vec![false; n]; + for &(off, size) in keep { + let lo = (off as usize).min(n); + let hi = (off as usize).saturating_add(size as usize).min(n); + kept[lo..hi].fill(true); + } + for i in 0..n { + let o = i as u64; + if kept[i] { + continue; + } + let (b, f) = (before.regs.get(i).copied().unwrap_or(0), before.flags.get(i).copied().unwrap_or(0)); + let present_now = self.flags[i] & PRESENT != 0; + if present_now && f & PRESENT != 0 && self.regs[i] != b { + changed.push(o); + } + if present_now || f & PRESENT != 0 { + self.regs[i] = b; + self.flags[i] = f; + } + } + changed + } + + /// What this side wrote outside the stack since its last call. + pub fn writes(&self) -> Writes { + let manage = self.env.prog.arch().manage(); + let bytes = self.mem.iter_sorted().filter(|((sp, off), _)| manage.get_space(*sp).is_some_and(|s| self.env.observable(s, *off))).collect(); + Writes { bytes, epoch: self.epoch, escaped: self.escaped.clone(), skip: BTreeSet::new(), objects: Vec::new() } + } + + /// [`Self::writes`] at a call passing `args`, plus the frame objects a + /// callee can reach: one an argument points to, one whose address this side + /// stored outside the frame (`global = &x`) or in an object already + /// reachable (`h.p = &x; f(&h)`), and one an earlier call could reach. + /// `wide` (a callee in the image, which may run for real) adds the frame + /// bytes above the lowest such object that lie in one of kuna's locals, + /// so a callee reading past an object kuna sized too small is compared + /// there too. + pub fn writes_at_call(&mut self, args: &[u128], wide: bool) -> Writes { + let mut w = self.writes(); + let ram = self.env.ram.get_index(); + let mut found: Vec = args.iter().map(|&a| a as u64).collect(); + let env = self.env; + found.extend(self.stored_pointers(|off| !env.in_stack(off, 1))); + let mut scanned = 0; + loop { + for &a in &found { + let Some(o) = self.env.stack_object(a).filter(|_| self.env.in_stack(a, 1)) else { continue }; + if !self.passed_objects.contains(&o) { + self.passed_objects.push(o); + } + } + if scanned == self.passed_objects.len() { + break; + } + let objects = self.passed_objects[scanned..].to_vec(); + scanned = self.passed_objects.len(); + found = self.stored_pointers(|off| objects.iter().any(|&(s, e)| off >= s && off < e)); + } + for &(start, end) in &self.passed_objects { + if w.objects.contains(&(start, end)) { + continue; + } + w.objects.push((start, end)); + } + let low = w.objects.iter().map(|o| o.0).min(); + let take = |w: &mut Writes, start: u64, end: u64, any: bool| { + for (off, v) in self.mem.range(ram, start, end) { + if any && self.env.stack_object(off).is_none() { + continue; + } + if self.callee_written.contains(&off) { + w.skip.insert(off); + } else { + w.bytes.insert((ram, off), v); + } + } + }; + match low.filter(|_| wide) { + Some(low) => take(&mut w, low, self.env.sp0, true), + None => { + for (start, end) in w.objects.clone() { + take(&mut w, start, end, false); + } + } + } + w + } + + /// The stack addresses held by pointer-sized words this side wrote in RAM + /// at offsets `keep` accepts, aligned or not: a packed structure can hold + /// a pointer at any offset. + fn stored_pointers(&self, keep: impl Fn(u64) -> bool) -> Vec { + let ram = self.env.ram.get_index(); + let size = u64::from(self.env.ram.get_addr_size()).clamp(1, 8); + let big = self.env.ram.is_big_endian(); + let mut words = Vec::new(); + for ((sp, off), _) in self.mem.iter() { + if sp != ram || !keep(off) { + continue; + } + if let Some(v) = self.mem.word(ram, off, size, big).filter(|&v| self.env.in_stack(v, 1)) { + words.push(v); + } + } + words + } + + /// Extend the value in `x.param` across `x.container`, as the ABI says a + /// callee leaves its return value. + fn extend(&mut self, x: &Extension) { + let Some(space) = self.env.prog.arch().manage().get_space(x.space) else { return }; + let (p, ps) = x.param; + let (c, cs) = x.container; + let Ok(v) = self.read(&space, p, ps) else { return }; + let v = if x.boolean { v & 1 } else { v }; + let negative = x.signed && ps > 0 && (v >> (ps * 8 - 1)) & 1 == 1; + let ext = if negative { v | !mask(ps) } else { v & mask(ps) }; + let _ = self.write(&space, c, cs, ext & mask(cs)); + } + + /// A call's effect: it kills the registers in `killed`, `args` escape into + /// it, and it may write any memory it can reach. The memory is written + /// lazily: every byte this side did not write since reads what + /// [`Env::base_byte`] says for the new epoch. + pub fn call(&mut self, killed: &[(u64, u32)], args: &[u128], ret: Option<&Extension>) { + if let Some(log) = self.log.as_mut() { + log.push(Event::Call(killed.to_vec(), args.to_vec(), ret.cloned())); + } + let call = self.epoch; + let register = Rc::clone(&self.env.register); + for &(off, size) in killed { + for i in 0..u64::from(size) { + let salt = if self.kill_salt_skip.iter().any(|&(o, n)| off + i >= o && off + i < o + u64::from(n)) { 0 } else { self.kill_salt }; + let b = self.env.killed_byte(self.run ^ salt, call, off + i); + self.put(®ister, off + i, b); + } + } + if let Some(x) = ret { + self.extend(x); + } + let size = u64::from(self.env.ram.get_addr_size()).min(8); + let ptr_mask = if size >= 8 { u64::MAX } else { (1u64 << (size * 8)) - 1 }; + self.escaped.add(self.env, args.iter().map(|&a| a as u64 & ptr_mask).filter(|&p| p > 0xffff)); + let env = self.env; + let escaped = std::mem::take(&mut self.escaped); + let manage = env.prog.arch().manage(); + self.mem.retain_pages( + |sp, page| manage.get_space(sp).map_or(Some(u64::MAX), |s| env.callee_writable_page(&escaped, s, page << 6)), + |sp, off| manage.get_space(sp).is_some_and(|s| !env.callee_writable(&escaped, s, off)), + ); + self.escaped = escaped; + self.epoch += 1; + } + + /// Forget the temporaries: they live for one instruction. + pub fn end_instruction(&mut self) { + self.unique.entries.clear(); + } + + /// Read a processor or temporary space value of up to sixteen bytes. + pub fn read(&mut self, space: &AddrSpace, off: u64, size: u32) -> Result { + if size > MAX_SIZE { + return Err(Halt::Unsupported(format!("{size}-byte value"))); + } + if self.is_unique(space) { + if let Some(v) = self.unique.exact(off, size) { + return Ok(v); + } + } + let end = off.wrapping_add(u64::from(size)); + if self.is_register(space, off) && end <= DENSE_REGISTERS && end > off { + self.grow(end as usize); + for i in off as usize..end as usize { + if self.flags[i] & PRESENT == 0 { + self.regs[i] = self.env.initial_byte(self.run, space, i as u64); + self.flags[i] |= PRESENT; + } + if let Some(l) = self.live.as_mut() { + l.saw(i as u64, self.regs[i]); + } + } + let bytes = &self.regs[off as usize..end as usize]; + let fold = |v: u128, &b: &u8| (v << 8) | u128::from(b); + return Ok(if space.is_big_endian() { bytes.iter().fold(0, fold) } else { bytes.iter().rev().fold(0, fold) }); + } + let mut v = 0u128; + for i in 0..u64::from(size) { + let b = self.byte(space, space.wrap_offset(off.wrapping_add(i))); + if space.is_big_endian() { + v = (v << 8) | u128::from(b); + } else { + v |= u128::from(b) << (8 * i); + } + } + Ok(v) + } + + /// Store `size` bytes. A store that changes the image's read-only data or + /// code traps, as it does on the target; one that leaves it as it is (the + /// decompiler's value of a global, kept across a call) does nothing. + pub fn write(&mut self, space: &AddrSpace, off: u64, size: u32, val: u128) -> Result<(), Halt> { + if !self.saved.is_empty() && space.get_index() == self.env.ram.get_index() { + let dead: Vec = self.saved.range(off..=off.saturating_add(u64::from(size).max(1) - 1)).map(|(k, _)| *k).collect(); + for k in dead { + self.saved.remove(&k); + } + } + if size > MAX_SIZE { + return Err(Halt::Unsupported(format!("{size}-byte value"))); + } + if self.is_unique(space) { + self.unique.set(off, size, val, space.is_big_endian()); + return Ok(()); + } + let end = off.wrapping_add(u64::from(size)); + if self.is_register(space, off) && end <= DENSE_REGISTERS && end > off { + self.grow(end as usize); + for i in 0..u64::from(size) { + let shift = if space.is_big_endian() { u64::from(size) - 1 - i } else { i }; + let at = (off + i) as usize; + self.regs[at] = (val >> (shift * 8)) as u8; + self.flags[at] |= PRESENT | WRITTEN; + if let Some(l) = self.live.as_mut() { + l.wrote(at as u64); + } + } + return Ok(()); + } + if space.get_index() == self.env.ram.get_index() + && (self.env.is_readonly(off, size.into()) || self.env.in_code_section(off)) + { + if self.read(space, off, size)? == val & crate::value::mask(size) { + return Ok(()); + } + return Err(Halt::Trap(format!("{READONLY_STORE} at {off:#x}"))); + } + for i in 0..u64::from(size) { + let shift = if space.is_big_endian() { u64::from(size) - 1 - i } else { i }; + self.put(space, space.wrap_offset(off.wrapping_add(i)), (val >> (shift * 8)) as u8); + } + Ok(()) + } + + /// Whether every byte of the range was written by this side. + pub fn wrote(&self, space: &AddrSpace, off: u64, size: u32) -> bool { + (0..u64::from(size)).all(|i| { + let at = space.wrap_offset(off.wrapping_add(i)); + if self.is_register(space, at) { + self.flags.get(at as usize).is_some_and(|f| f & WRITTEN != 0) + } else if self.is_unique(space) { + self.unique.byte(at).is_some() + } else { + self.mem.contains(space.get_index(), at) + } + }) + } + + fn join(&self, off: u64) -> Result, Halt> { + self.env + .prog + .arch() + .manage() + .find_join(off) + .map_err(|e| Halt::Harness(format!("join: {}", e.explain()))) + } + + /// Read any storage a varnode or prototype can name, up to sixteen bytes: + /// constants, the stack space (relative to the entry stack pointer), joined + /// registers (most significant piece first), and processor spaces. + pub fn read_storage(&mut self, space: &Rc, off: u64, size: u32) -> Result { + let m = mask(size); + match space.get_type() { + spacetype::IPTR_CONSTANT => Ok(u128::from(off) & m), + spacetype::IPTR_SPACEBASE => { + let ram = Rc::clone(&self.env.ram); + let addr = ram.wrap_offset(self.env.sp0.wrapping_add(off)); + self.read(&ram, addr, size) + } + spacetype::IPTR_JOIN => { + let rec = self.join(off)?; + let mut acc = 0u128; + for i in 0..rec.num_pieces() { + let p = rec.get_piece(i); + let ps = p.space.clone().ok_or_else(|| Halt::Harness("join piece without space".into()))?; + let v = self.read_storage(&ps, p.offset, p.size)?; + acc = if p.size >= 16 { v } else { (acc << (p.size * 8)) | v }; + } + Ok(acc & m) + } + spacetype::IPTR_PROCESSOR | spacetype::IPTR_INTERNAL => self.read(space, off, size), + other => Err(Halt::Harness(format!("storage in a {other:?} space"))), + } + } + + /// Write storage a varnode can name: the inverse of [`Self::read_storage`]. + pub fn write_storage(&mut self, space: &Rc, off: u64, size: u32, val: u128) -> Result<(), Halt> { + match space.get_type() { + spacetype::IPTR_SPACEBASE => { + let ram = Rc::clone(&self.env.ram); + let addr = ram.wrap_offset(self.env.sp0.wrapping_add(off)); + self.write(&ram, addr, size, val) + } + spacetype::IPTR_JOIN => { + let rec = self.join(off)?; + let mut rest = val; + for i in (0..rec.num_pieces()).rev() { + let p = rec.get_piece(i); + let ps = p.space.clone().ok_or_else(|| Halt::Harness("join piece without space".into()))?; + self.write_storage(&ps, p.offset, p.size, rest & mask(p.size))?; + rest = if p.size >= 16 { 0 } else { rest >> (p.size * 8) }; + } + Ok(()) + } + spacetype::IPTR_PROCESSOR | spacetype::IPTR_INTERNAL => self.write(space, off, size, val), + other => Err(Halt::Harness(format!("storage in a {other:?} space"))), + } + } +} diff --git a/decompiler/crates/kuna-verify/src/state/stack_inputs.rs b/decompiler/crates/kuna-verify/src/state/stack_inputs.rs new file mode 100644 index 0000000000..ffd5b49240 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/state/stack_inputs.rs @@ -0,0 +1,64 @@ +//! Reads of incoming stack argument bytes before the callee overwrites them. + +use std::collections::BTreeMap; + +use crate::calls::Site; +use crate::state::Env; + +#[derive(Clone, Copy, Debug)] +enum Access { + Pending, + Written, + Read(u8), +} + +#[derive(Clone, Debug)] +pub(crate) struct StackInputs { + base: u64, + bytes: BTreeMap, +} + +impl StackInputs { + pub(crate) fn new(env: &Env, site: &Site, base: u64) -> Option { + if env.ret_slot != 4 || site.resolved || !env.in_stack(base, 4) { + return None; + } + let mut bytes = BTreeMap::new(); + for st in (0..site.input_storage.len()).filter_map(|i| site.stack_input(i)) { + let size = u64::from(st.size); + let addr = base + st.off; + let last = addr + size - 1; + if !env.in_stack(addr, size) || last != env.ram.wrap_offset(last) { + continue; + } + for off in st.off..st.off + size { + if bytes.insert(off, Access::Pending).is_some() { + return None; + } + } + } + (!bytes.is_empty()).then_some(Self { base, bytes }) + } + + pub(crate) fn read(&mut self, addr: u64, value: u8) { + if let Some(access @ Access::Pending) = self.bytes.get_mut(&addr.wrapping_sub(self.base)) { + *access = Access::Read(value); + } + } + + pub(crate) fn write(&mut self, addr: u64) { + if let Some(access @ Access::Pending) = self.bytes.get_mut(&addr.wrapping_sub(self.base)) { + *access = Access::Written; + } + } + + pub(crate) fn contains(&self, off: u64, size: u32) -> bool { + (off..off + u64::from(size)).all(|off| self.bytes.contains_key(&off)) + } + + pub(crate) fn bytes(&self) -> impl Iterator)> + '_ { + self.bytes.iter().map(|(&off, access)| { + (off, if let Access::Read(value) = access { Some(*value) } else { None }) + }) + } +} diff --git a/decompiler/crates/kuna-verify/src/state/tests.rs b/decompiler/crates/kuna-verify/src/state/tests.rs new file mode 100644 index 0000000000..83a9f29934 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/state/tests.rs @@ -0,0 +1,108 @@ +use super::*; + +fn with_env(check: impl FnOnce(&mut Env)) { + let image = br#" + 31c0c3 + 0102030405060708 + + "#; + let mut store = kuna_base::xml::DocumentStorage::new(); + let root = store.parse_document(image).unwrap().get_root().clone(); + let specs = vec![format!("{}/../../../specs", env!("CARGO_MANIFEST_DIR"))]; + let prog = kuna_console::engine::bootstrap_program(root, "x86:LE:64:default:gcc", &specs).unwrap(); + let mut env = Env::new(&prog, 0).unwrap(); + check(&mut env); +} + +fn escaped(reach: &[(u64, u64)]) -> Escaped { + Escaped { pointers: Vec::new(), reach: reach.to_vec() } +} + +/// Ranges that start, end and stop one byte short of each edge of the page +/// at `base`, cover it whole, and span several pages. +fn reaches_around(base: u64) -> Vec> { + let b = base; + let at = |d: i64| b.wrapping_add(d as u64); + let mut sets = vec![ + vec![], + vec![(at(0), at(0))], + vec![(at(63), at(63))], + vec![(at(-64), at(-1))], + vec![(at(64), at(127))], + vec![(at(-8), at(3))], + vec![(at(60), at(70))], + vec![(at(0), at(63))], + vec![(at(-4096), at(4096))], + vec![(at(2), at(5)), (at(9), at(9)), (at(20), at(40)), (at(62), at(200))], + ]; + sets.retain(|s| s.iter().all(|r| r.0 <= r.1) && s.windows(2).all(|w| w[0].1 < w[1].0)); + sets +} + +#[test] +fn a_page_mask_holds_the_bytes_an_escaped_pointer_reaches() { + let top = u64::MAX - 63; + for base in [0, 0x40, 0x7fff_ffff_ffff_ffc0, top] { + let mut sets = reaches_around(base); + if base == top { + sets.push(vec![(u64::MAX - 5, u64::MAX)]); + } + for reach in sets { + let e = escaped(&reach); + let m = e.page_mask(base); + for i in 0..64 { + assert_eq!(m >> i & 1 == 1, e.reaches(base + i), "base {base:#x} byte {i} reach {reach:x?}"); + } + } + } +} + +#[test] +fn a_page_decided_at_once_agrees_with_each_of_its_bytes() { + with_env(|env| { + let frame = env.sp0 & !63; + let below = STACK_BELOW.min(env.sp0 / 2); + let low = env.sp0.wrapping_sub(below) & !63; + let high = env.sp0.wrapping_add(STACK_ABOVE) & !63; + let bases = [ + frame, frame - 64, frame + 64, low, low.wrapping_sub(64), high, high.wrapping_sub(64), 0x1000, 0x1fc0, 0x2000, + 0x40_0000, 0, u64::MAX - 63, + ]; + let ram = Rc::clone(&env.ram); + let register = Rc::clone(&env.register); + let stack = Rc::clone(&env.stack); + let layouts: [(Vec<(u64, u64)>, Vec<(u64, u64)>); 3] = [ + (env.readonly.clone(), env.code_sections.clone()), + (vec![(frame + 16, frame + 31)], vec![]), + (vec![], vec![(frame - 64 + 40, frame + 100)]), + ]; + let mut decided = 0; + for (readonly, code) in layouts { + env.readonly = readonly; + env.code_sections = code; + for base in bases { + for reach in reaches_around(base) { + let e = escaped(&reach); + for space in [&ram, ®ister, &stack] { + let Some(mask) = env.callee_writable_page(&e, space, base) else { continue }; + decided += 1; + for i in 0..64 { + assert_eq!( + mask >> i & 1 == 1, + env.callee_writable(&e, space, base + i), + "space {} base {base:#x} byte {i} reach {reach:x?} readonly {:x?} code {:x?}", + space.get_name(), env.readonly, env.code_sections, + ); + } + } + } + } + } + assert!(decided > 200, "{decided}"); + env.readonly.clear(); + env.code_sections.clear(); + let e = escaped(&[(frame + 8, frame + 15)]); + assert_eq!(env.callee_writable_page(&e, &ram, frame), Some(0xff00)); + assert_eq!(env.callee_writable_page(&e, &ram, 0x2000), None, "an image page outside the stack is asked byte by byte"); + }); +} diff --git a/decompiler/crates/kuna-verify/src/tools/mod.rs b/decompiler/crates/kuna-verify/src/tools/mod.rs new file mode 100644 index 0000000000..3b60cb58cb --- /dev/null +++ b/decompiler/crates/kuna-verify/src/tools/mod.rs @@ -0,0 +1,3 @@ +//! Tools built on the check: mutation testing. + +pub mod mutate; diff --git a/decompiler/crates/kuna-verify/src/tools/mutate.rs b/decompiler/crates/kuna-verify/src/tools/mutate.rs new file mode 100644 index 0000000000..dbdc2393c0 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/tools/mutate.rs @@ -0,0 +1,315 @@ +//! Mutation testing of the check itself: plant one semantic fault in kuna's +//! side of a function that agrees, and see whether the check reports it. +//! +//! A mutant changes one op of the compiled decompiled side (`program`) or one +//! call site's target, which is what the printed C names a direct callee by. +//! The machine side is untouched. A mutant whose op no run reaches cannot be +//! seen by any check, so recall counts only the mutants a run reached. + +use std::time::Instant; + +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::funcdata::Funcdata; +use kuna_num::opcodes::OpCode; + +use crate::calls::Calls; +use crate::check::Options; +use crate::program::{Kind, Operand, Program}; +use crate::report::Verdict; +use crate::state::Env; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Operator { + /// An arithmetic, logic, comparison or extension op becomes a near one. + Opcode, + /// A constant input's lowest bit is flipped. + Constant, + /// The inputs of an op that does not commute trade places. + Swap, + /// A conditional branch goes the other way. + Branch, + /// A store does nothing. + DropStore, + /// A direct call goes to another function. + CallTarget, + /// A call loses its last argument: a recovered prototype loses it too, as + /// when kuna recovers one parameter too few; a declared one keeps it. + DropArg, + /// A call that returns is said not to. This is kuna's claim about the call, + /// which both sides read; the machine side has to find it false itself. + NoReturn, +} + +pub const OPERATORS: [Operator; 8] = [ + Operator::Opcode, + Operator::Constant, + Operator::Swap, + Operator::Branch, + Operator::DropStore, + Operator::CallTarget, + Operator::DropArg, + Operator::NoReturn, +]; + +impl Operator { + pub fn name(self) -> &'static str { + match self { + Operator::Opcode => "opcode", + Operator::Constant => "constant", + Operator::Swap => "swap", + Operator::Branch => "branch", + Operator::DropStore => "drop-store", + Operator::CallTarget => "call-target", + Operator::DropArg => "drop-arg", + Operator::NoReturn => "noreturn", + } + } +} + +/// One mutant: the op at `op` in block `block`, changed by `operator`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Mutation { + pub block: usize, + pub op: usize, + pub operator: Operator, +} + +fn near(opc: OpCode) -> Option { + use OpCode::*; + Some(match opc { + CPUI_INT_ADD => CPUI_INT_SUB, + CPUI_INT_SUB => CPUI_INT_ADD, + CPUI_INT_AND => CPUI_INT_OR, + CPUI_INT_OR => CPUI_INT_AND, + CPUI_INT_XOR => CPUI_INT_OR, + CPUI_INT_MULT => CPUI_INT_ADD, + CPUI_INT_LESS => CPUI_INT_SLESS, + CPUI_INT_SLESS => CPUI_INT_LESS, + CPUI_INT_LESSEQUAL => CPUI_INT_LESS, + CPUI_INT_SLESSEQUAL => CPUI_INT_SLESS, + CPUI_INT_EQUAL => CPUI_INT_NOTEQUAL, + CPUI_INT_NOTEQUAL => CPUI_INT_EQUAL, + CPUI_INT_RIGHT => CPUI_INT_SRIGHT, + CPUI_INT_SRIGHT => CPUI_INT_RIGHT, + CPUI_INT_LEFT => CPUI_INT_RIGHT, + CPUI_INT_ZEXT => CPUI_INT_SEXT, + CPUI_INT_SEXT => CPUI_INT_ZEXT, + CPUI_INT_DIV => CPUI_INT_SDIV, + CPUI_INT_SDIV => CPUI_INT_DIV, + CPUI_INT_REM => CPUI_INT_SREM, + CPUI_INT_SREM => CPUI_INT_REM, + _ => return None, + }) +} + +fn ordered(opc: OpCode) -> bool { + use OpCode::*; + matches!( + opc, + CPUI_INT_SUB + | CPUI_INT_LESS + | CPUI_INT_SLESS + | CPUI_INT_LESSEQUAL + | CPUI_INT_SLESSEQUAL + | CPUI_INT_DIV + | CPUI_INT_SDIV + | CPUI_INT_REM + | CPUI_INT_SREM + ) +} + +/// Every mutant `p` and `calls` allow, in program order. +pub fn mutants(p: &Program, calls: &Calls) -> Vec { + let mut out = Vec::new(); + for (b, block) in p.blocks.iter().enumerate() { + for (k, op) in block.ops.iter().enumerate() { + let mut add = |operator| out.push(Mutation { block: b, op: k, operator }); + match &op.kind { + Kind::Eval(opc) => { + if near(*opc).is_some() { + add(Operator::Opcode); + } + if op.ins.iter().any(|a| matches!(a.op, Operand::Const(_))) { + add(Operator::Constant); + } + if ordered(*opc) && op.ins.len() == 2 && op.ins[0].size == op.ins[1].size { + add(Operator::Swap); + } + } + Kind::CBranch { .. } => add(Operator::Branch), + Kind::Store(_) => add(Operator::DropStore), + Kind::Call { direct: Some(_) } => { + if calls.site(op.at).target.is_some() { + add(Operator::CallTarget); + } + if !calls.site(op.at).noreturn { + add(Operator::NoReturn); + } + if op.ins.len() > 1 { + add(Operator::DropArg); + } + if stack_constant(op, calls.site(op.at)).is_some() { + add(Operator::Constant); + } + } + Kind::Call { direct: None } if op.ins.len() > 1 => add(Operator::DropArg), + _ => {} + } + } + } + out +} + +fn stack_constant(op: &crate::program::Op, site: &crate::calls::Site) -> Option { + op.ins.iter().skip(1).enumerate().find_map(|(i, a)| { + (matches!(a.op, Operand::Const(_)) && site.stack_input(i).is_some()).then_some(i + 1) + }) +} + +/// Apply `m` to `p` and `calls`; a description of what changed, or `None` +/// when the mutant does not apply. +pub fn apply(p: &mut Program, calls: &mut Calls, env: &Env, m: Mutation) -> Option { + let op = p.blocks.get_mut(m.block)?.ops.get_mut(m.op)?; + let at = op.at; + let what = match (m.operator, &mut op.kind) { + (Operator::Opcode, Kind::Eval(opc)) => { + let to = near(*opc)?; + let s = format!("{opc:?} -> {to:?}"); + *opc = to; + s + } + (Operator::Constant, Kind::Eval(_)) => { + let a = op.ins.iter_mut().find(|a| matches!(a.op, Operand::Const(_)))?; + let Operand::Const(c) = &mut a.op else { return None }; + let was = *c; + *c ^= 1; + format!("constant {was:#x} -> {:#x}", *c) + } + (Operator::Constant, Kind::Call { .. }) => { + let index = stack_constant(op, calls.site(at))?; + let Operand::Const(c) = &mut op.ins[index].op else { return None }; + let was = *c; + *c ^= 1; + format!("stack argument {index} constant {was:#x} -> {:#x}", *c) + } + (Operator::Swap, Kind::Eval(opc)) => { + let s = format!("{opc:?} inputs swapped"); + op.ins.swap(0, 1); + s + } + (Operator::Branch, Kind::CBranch { flip }) => { + *flip = !*flip; + "branch inverted".to_string() + } + (Operator::DropStore, Kind::Store(_)) => { + op.kind = Kind::Nop; + "store dropped".to_string() + } + (Operator::CallTarget, Kind::Call { .. }) => { + let site = calls.by_addr.get_mut(&at)?; + let was = site.target?; + let to = env.another_function(was)?; + site.target = Some(to); + let place = |t: u64| if env.is_code(t) { "code" } else if env.code_mapped(t) { "mapped" } else { "unmapped" }; + let resolved = if site.resolved { ", resolved site" } else { "" }; + format!("call target {was:#x} -> {to:#x} [{} -> {}{resolved}]", place(was), place(to)) + } + (Operator::DropArg, Kind::Call { .. }) => { + let k = op.ins.len() - 1; + let site = calls.by_addr.get_mut(&at)?; + let class = match site.args.get(k - 1) { + Some(Some(_)) => "register", + Some(None) => "not in a register", + None => "beyond the prototype", + }; + op.ins.pop(); + site.args.truncate(k - 1); + site.input_storage.truncate(k - 1); + let proto = if site.locked { + "declared prototype kept" + } else { + site.params = site.params.min(k - 1); + "recovered prototype shrunk" + }; + format!("last call argument dropped [{class}, {proto}]") + } + (Operator::NoReturn, Kind::Call { .. }) => { + let site = calls.by_addr.get_mut(&at)?; + site.noreturn = true; + let place = site.target.map_or("indirect", |t| if env.code_mapped(t) { "callee in the image" } else { "callee outside the image" }); + format!("call said not to return [{place}]") + } + _ => return None, + }; + p.watch = Some((m.block, m.op)); + Some(format!("{what} at {at:#x}")) +} + +/// How one mutant fared. +#[derive(Clone, Debug)] +pub struct Outcome { + pub function: String, + pub operator: Operator, + pub what: String, + pub verdict: Verdict, + /// A run reached the mutated op. + pub reached: bool, + pub ms: f64, +} + +impl Outcome { + pub fn killed(&self) -> bool { + matches!(self.verdict, Verdict::Differs { .. }) + } +} + +/// Up to `per_function` mutants of `fd`, taking each operator in turn so every +/// kind is tried; none when the unmutated function does not agree. The +/// machine side is the same for every mutant, so its runs are made once. +pub fn mutate_function(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, per_function: usize) -> Vec { + let Ok(prepared) = crate::check::prepare(prog, fd, opts, false) else { return Vec::new() }; + let shared = crate::check::Shared::new(&prepared); + let base = crate::check::check_shared(prog, fd, opts, &shared); + if !matches!(base.verdict, Verdict::Agrees(_)) { + return Vec::new(); + } + let Ok(env) = Env::new(prog, opts.seed) else { return Vec::new() }; + let calls = crate::calls::sites(fd, &env); + let program = crate::program::compile(prog, fd, &calls); + let all = mutants(&program, &calls); + let mut picked = Vec::new(); + let mut by_kind: Vec> = OPERATORS.iter().map(|o| all.iter().filter(|m| m.operator == *o).copied().collect()).collect(); + for v in &mut by_kind { + let n = v.len(); + if n > 1 { + let start = (opts.seed as usize ^ fd.get_address().get_offset() as usize) % n; + v.rotate_left(start); + } + } + let mut round = 0; + while picked.len() < per_function && by_kind.iter().any(|v| round < v.len()) { + for v in &by_kind { + if let Some(&m) = v.get(round) { + if picked.len() < per_function { + picked.push(m); + } + } + } + round += 1; + } + picked + .into_iter() + .filter_map(|m| { + let started = Instant::now(); + let (report, what, reached) = crate::check::check_mutant_shared(prog, fd, opts, m, &shared)?; + Some(Outcome { + function: fd.get_name().to_string(), + operator: m.operator, + what, + verdict: report.verdict, + reached, + ms: started.elapsed().as_secs_f64() * 1e3, + }) + }) + .collect() +} diff --git a/decompiler/crates/kuna-verify/tests/call_effects.rs b/decompiler/crates/kuna-verify/tests/call_effects.rs new file mode 100644 index 0000000000..8f4e40ae7f --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/call_effects.rs @@ -0,0 +1,74 @@ +//! Calls and memory (slice C2) on x86-64, from clang -O2 -fno-pic: +//! +//! ```c +//! int counter = 5; +//! extern void tick(void); +//! int twice(void) { int a = counter; tick(); return a + counter; } +//! void bump(int *p) { *p += 1; tick(); *p += 2; } +//! ``` +//! +//! `tick` is outside the image, so both sides run its stub: it may write +//! `counter` and what `p` points to. kuna reloads both after the call, so both +//! functions agree; a kuna that kept `counter` across the call would differ. + +use std::path::PathBuf; + +use kuna_verify::{check_binary, Options, Verdict}; +use object::write::{Object, Relocation, Symbol, SymbolSection}; +use object::{ + Architecture, BinaryFormat, Endianness, RelocationFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope, +}; + +const TEXT: &str = "538b1d00000000e800000000031d0000000089d85bc3662e0f1f840000000000534889fbff07e8000000008303025bc3"; + +fn object() -> PathBuf { + let text: Vec = (0..TEXT.len()).step_by(2).map(|i| u8::from_str_radix(&TEXT[i..i + 2], 16).unwrap()).collect(); + let mut obj = Object::new(BinaryFormat::Elf, Architecture::X86_64, Endianness::Little); + let code = obj.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text); + obj.append_section_data(code, &text, 16); + let data = obj.add_section(Vec::new(), b".data".to_vec(), SectionKind::Data); + obj.append_section_data(data, &5u32.to_le_bytes(), 4); + let sym = |obj: &mut Object, name: &str, value, size, kind, section| { + obj.add_symbol(Symbol { + name: name.as_bytes().to_vec(), + value, + size, + kind, + scope: SymbolScope::Linkage, + weak: false, + section, + flags: SymbolFlags::None, + }) + }; + sym(&mut obj, "twice", 0, 22, SymbolKind::Text, SymbolSection::Section(code)); + sym(&mut obj, "bump", 0x20, 16, SymbolKind::Text, SymbolSection::Section(code)); + let counter = sym(&mut obj, "counter", 0, 4, SymbolKind::Data, SymbolSection::Section(data)); + let tick = sym(&mut obj, "tick", 0, 0, SymbolKind::Text, SymbolSection::Undefined); + for (offset, symbol, r_type) in [(3, counter, 2), (8, tick, 4), (0xe, counter, 2), (0x27, tick, 4)] { + obj.add_relocation(code, Relocation { offset, symbol, addend: -4, flags: RelocationFlags::Elf { r_type } }) + .unwrap(); + } + let dir = std::env::temp_dir().join(format!("kuna-verify-calls-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("callmem.o"); + crate::zext_pair::write_whole(&path, &obj.write().unwrap()); + path +} + +#[test] +fn a_global_and_a_pointee_are_reloaded_after_a_call() { + let specs = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../specs").canonicalize().unwrap(); + let functions = vec!["twice".to_string(), "bump".to_string()]; + let reports = check_binary( + &object().to_string_lossy(), + &functions, + &[], + &[specs.to_string_lossy().into_owned()], + None, + &Options { runs: 64, ..Options::default() }, + ) + .unwrap(); + for r in &reports { + assert_eq!(r.verdict, Verdict::Agrees(64), "{}", r.render()); + } +} diff --git a/decompiler/crates/kuna-verify/tests/datatest_isolation.rs b/decompiler/crates/kuna-verify/tests/datatest_isolation.rs new file mode 100644 index 0000000000..f82719c565 --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/datatest_isolation.rs @@ -0,0 +1,31 @@ +//! One datatest's `option` commands never reach the next datatest run in the +//! same process. `kuna-ppc32picimports-abi` ends on `option ppc32picimports +//! abi`, a load-time option the console exports to the environment; the runtime +//! test loads its first image before it sets the option itself, so a leak made +//! its first `check` agree in `corpus --jobs 1` and stay `UNKNOWN` in a worker +//! process of its own. Its own `[[test]]`, since it changes the environment and +//! the working directory: the scripts name their images from the repository root. + +use std::path::PathBuf; + +use kuna_decomp::kuna_loadoptions::EnvSnapshot; +use kuna_verify::{check_datatest, Options}; + +fn labels(test: &str) -> Vec<(String, String)> { + let repo = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..").canonicalize().unwrap(); + std::env::set_current_dir(&repo).unwrap(); + let specs = repo.join("specs").to_string_lossy().into_owned(); + let path = repo.join("tests/stages").join(format!("{test}.xml")); + let res = check_datatest(&path.to_string_lossy(), &[specs], &Options::default()); + assert_eq!(res.error, None, "{test}"); + res.reports.iter().map(|r| (r.function.clone(), r.verdict.label())).collect() +} + +#[test] +fn a_datatest_does_not_load_under_the_previous_ones_options() { + let env = EnvSnapshot::capture(); + let alone = labels("kuna-ppc32picimports-runtime"); + labels("kuna-ppc32picimports-abi"); + assert_eq!(EnvSnapshot::capture(), env, "a datatest's options stayed in the environment"); + assert_eq!(labels("kuna-ppc32picimports-runtime"), alone); +} diff --git a/decompiler/crates/kuna-verify/tests/integration.rs b/decompiler/crates/kuna-verify/tests/integration.rs new file mode 100644 index 0000000000..655e3302dc --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/integration.rs @@ -0,0 +1,8 @@ +#[path = "zext_pair.rs"] +mod zext_pair; +#[path = "stage_verdicts.rs"] +mod stage_verdicts; +#[path = "call_effects.rs"] +mod call_effects; +#[path = "verdict_guards.rs"] +mod verdict_guards; diff --git a/decompiler/crates/kuna-verify/tests/stage_verdicts.rs b/decompiler/crates/kuna-verify/tests/stage_verdicts.rs new file mode 100644 index 0000000000..919caa69b7 --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/stage_verdicts.rs @@ -0,0 +1,214 @@ +//! Verdicts on stage tests that pin harness behavior. Each of these was once a +//! false `DIFFERS` or a wrong `AGREES`, so a change that brings one back fails +//! here instead of reading as a kuna bug. + +use std::path::PathBuf; + +use kuna_verify::{check_datatest, Options}; + +fn repo() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../..").canonicalize().unwrap() +} + +/// `(function, verdict label)` for every function the test's script decompiles. +fn verdicts(test: &str) -> Vec<(String, String)> { + let specs = repo().join("specs").to_string_lossy().into_owned(); + let path = repo().join("tests/stages").join(format!("{test}.xml")); + let res = check_datatest(&path.to_string_lossy(), &[specs], &Options::default()); + assert_eq!(res.error, None, "{test}"); + res.reports.iter().map(|r| (r.function.clone(), r.verdict.label())).collect() +} + +fn of<'a>(v: &'a [(String, String)], names: &[&str]) -> Vec<&'a str> { + v.iter().filter(|(f, _)| names.contains(&f.as_str())).map(|(_, l)| l.as_str()).collect() +} + +/// The first pass sets `narrowext off`, the bug the test pins; the second is the +/// fix. Inputs keep the documented RV64 extension in both. +#[test] +fn narrowext_bug_pass_differs_and_fix_pass_agrees() { + let v = verdicts("kuna-narrowext"); + let all = "AGREES(256)"; + assert_eq!( + of(&v, &["pi", "pus", "pu", "psc"]), + ["DIFFERS", all, "DIFFERS", "DIFFERS", all, all, all, all] + ); +} + +#[test] +fn an_alternative_for_omitted_register_bytes_can_prove_a_difference() { + let v = verdicts("gh1922-pushpad-caller-readarg-thumb"); + assert_eq!(of(&v, &["vsend", "vsendz"]), ["DIFFERS"; 2]); +} + +/// A 32-bit `int` argument in a 64-bit RISC-V register arrives sign-extended. +#[test] +fn riscv_arguments_keep_their_abi_extension() { + let v = verdicts("kuna-constptrdeclared-riscv"); + assert_eq!(of(&v, &["rq", "ru", "rl"]), ["AGREES(256)"; 3]); +} + +/// A stack slot kuna writes as a varnode is the memory a later LOAD reads. +#[test] +fn stack_varnode_writes_reach_loads() { + let v = verdicts("kuna-arrayextent"); + let agree = of(&v, &["h_clang", "h_gcc", "m_clang", "m_gcc"]); + assert!(!agree.is_empty() && agree.iter().all(|l| *l == "AGREES(256)"), "{agree:?}"); +} + +/// Cut run-on rows are a declared divergence, and the placeholder label of a +/// table's default row never matches a selector. +#[test] +fn run_on_switch_rows_are_declared() { + let v = verdicts("kuna-switchrunonguard"); + assert_eq!(of(&v, &["pick", "pick2"]), ["DIVERGES(switchrunon-cut-row)"; 2]); +} + +/// A return kept in a temporary is compared at the register the model +/// returns its type in. +#[test] +fn return_in_a_temporary_is_compared_at_the_model_register() { + let v = verdicts("kuna-gobool"); + assert_eq!(of(&v, &["is_one"]), ["AGREES(256)"; 2]); +} + +/// A switch row goes to the out-edge its table entry reaches, never silently to +/// the default. +#[test] +fn switch_rows_follow_their_table_entries() { + let v = verdicts("regionstructure-switch"); + assert_eq!(of(&v, &["dispatch"]), ["AGREES(256)"; 2]); +} + +/// A `bool` passed on the stack is 0 or 1 in its low byte, as one in a register. +#[test] +fn stack_bool_parameters_are_zero_or_one() { + let v = verdicts("kuna-stackobjects"); + let checked = of(&v, &["param_reuse", "param_pair", "param_scalar_escaped"]); + assert!(!checked.is_empty() && checked.iter().all(|l| *l == "AGREES(256)"), "{checked:?}"); +} + +/// A return kuna folded to a constant is compared at the register the model +/// returns it in. +#[test] +fn constant_returns_are_compared_at_the_model_register() { + let v = verdicts("kuna-bejoin-sparc"); + let checked = of(&v, &["same", "one_after", "zero_after", "keep_zero"]); + assert!(!checked.is_empty() && checked.iter().all(|l| l.starts_with("AGREES(")), "{checked:?}"); +} + +/// A call whose prototype has no output keeps its value in a temporary that a +/// copy moves to a register: the value is the register's after the call. +#[test] +fn a_call_value_cast_into_a_register_is_the_registers() { + let v = verdicts("ghdec-realtypes-pointee"); + let checked = of(&v, &["acl_calc_mask"]); + assert!(!checked.is_empty() && checked.iter().all(|l| *l == "AGREES(256)"), "{checked:?}"); +} + +/// Reading past an array into a callee-saved register's spill is undefined in +/// C: kuna never stores the spill, so its side reads uninitialized stack, and +/// the run is not a difference. +#[test] +fn reading_a_register_spill_past_an_array_is_undefined() { + let v = verdicts("kuna-arrayextent"); + let checked = of(&v, &["q_clang", "w_clang"]); + assert!(!checked.is_empty() && checked.iter().all(|l| l.starts_with("UNKNOWN")), "{checked:?}"); +} + +/// A system call writes the kernel's result register: `on` agrees, `off` (the +/// bug the test pins) differs, and `auto` on an image that names no operating +/// system leaves the register unwritten, which is declared. +#[test] +fn system_call_result_follows_the_kernel() { + let v = verdicts("kuna-syscallregs-arm"); + assert_eq!(of(&v, &["pair"]), ["AGREES(256)", "DIFFERS", "DIVERGES(syscall-result)"]); + let v = verdicts("kuna-x64syscall"); + assert_eq!(of(&v, &["kernel_call"]), ["DIFFERS", "AGREES(256)", "AGREES(256)"]); + assert_eq!(of(&verdicts("kuna-ownreturn"), &["sys2nr"]), ["DIVERGES(syscall-result)"]); +} + +/// A removed Go bounds-check panic and a cut arm64e pointer-authentication +/// trap are declared; the checks kuna keeps agree. +#[test] +fn removed_checks_are_declared() { + let v = verdicts("kuna-gobounds"); + assert_eq!(of(&v, &["pick"]), ["AGREES(256)", "DIVERGES(panic-check)", "AGREES(256)"]); + let specs = repo().join("specs").to_string_lossy().into_owned(); + let path = repo().join("tests/stages/kuna-ptrauthtrap.xml"); + let res = check_datatest(&path.to_string_lossy(), &[specs], &Options::default()); + let v: Vec<_> = res.reports.iter().map(|r| (r.function.clone(), r.verdict.label())).collect(); + assert_eq!(of(&v, &["x30check", "x30forged"]), ["DIVERGES(ptrauth-trap)", "AGREES(256)"]); +} + +/// A call kuna knows does not return only by its callee's name (flow plants a +/// halt after it) ends the run as kuna's does, instead of running on past it. +#[test] +fn a_call_flow_halts_after_does_not_return() { + let v = verdicts("ghangr-noreturn_extern"); + let victim = of(&v, &["victim"]); + assert!(!victim.is_empty() && victim.iter().all(|l| *l == "AGREES(256)"), "{v:?}"); +} + +/// x86's segment bases point at a TLS block, not into the image: the +/// stack-protector guard at `fs:0x28` reads the same before and after a call. +#[test] +fn the_stack_guard_survives_a_call() { + let specs = repo().join("specs").to_string_lossy().into_owned(); + let path = repo().join("decompiler/crates/kuna-analysis/tests/fixtures/katavm_level1_x86_64"); + let reports = + kuna_verify::check_binary(&path.to_string_lossy(), &["sub_12d0".into()], &[], &[specs], None, &Options::default()).unwrap(); + let labels: Vec = reports.iter().map(|r| r.verdict.label()).collect(); + assert_eq!(labels, ["AGREES(256)"]); +} + +/// A Thumb `bx` to Thumb code switches to the mode the target decodes in +/// anyway, and barriers and the exclusive monitor change nothing on one thread. +#[test] +fn thumb_interworking_and_barriers_run() { + for (test, names) in [("kuna-veneer-tailcall", &["ret_veneer", "plain_veneer"][..]), ("kuna-syscallregs-arm", &["fence"])] { + let v = verdicts(test); + let got = of(&v, names); + assert!(!got.is_empty() && got.iter().all(|l| *l == "AGREES(256)"), "{test}: {v:?}"); + } +} + +/// x87: `fild`, `fld1` and a spill to a `float` slot run in the 80-bit format, +/// and a `double` returned in `ST0` is rounded from it before the compare. +#[test] +fn x87_extended_values_run_and_return() { + let v = verdicts("kuna-integer-float-rounding-x87"); + assert_eq!(of(&v, &["cmpf", "lt1", "l2d2f"]), ["AGREES(256)", "AGREES(256)", "AGREES(256)"]); +} + +/// A parameter kuna's recovered prototype types `bool` keeps both sides to 0 +/// and 1, which is kuna's claim, not the program's; a second pass gives it any +/// byte, and `flagparam` agrees there too. +#[test] +fn an_inferred_bool_parameter_is_also_checked_with_any_byte() { + let specs = repo().join("specs").to_string_lossy().into_owned(); + let path = repo().join("tests/stages/kuna-boolbyte.xml"); + let res = check_datatest(&path.to_string_lossy(), &[specs], &Options::default()); + let rows: Vec<_> = res.reports.iter().filter(|r| r.function == "flagparam").collect(); + let all: String = rows.iter().map(|r| r.render()).collect(); + assert!(rows.iter().all(|r| r.verdict.label() == "AGREES(256)"), "{all}"); + assert!(rows.iter().any(|r| r.lines.iter().any(|l| l.contains("types bool also took any byte"))), "{all}"); +} + +/// `f` keeps a register over a call kuna's IR says the callee preserves; the +/// callee is stubbed, so the machine kills it as the convention allows, and +/// whether `f` agrees then rests on kuna's unchecked claim: not AGREES. +#[test] +fn a_preservation_kuna_claims_for_a_stubbed_callee_is_not_agreement() { + let v = verdicts("kuna-calleescratchbody"); + let f = of(&v, &["f"]); + assert!(f.iter().all(|l| l.starts_with("UNKNOWN(guessed-callee")), "{v:?}"); +} + +/// An indirect jump out of the image to anything but the return address, +/// where kuna makes no call, is not taken for a return. +#[test] +fn an_indirect_jump_out_of_the_image_is_not_a_return() { + let v = verdicts("kuna-gottailcall"); + assert!(of(&v, &["notfn"]).iter().all(|l| l.contains("indirect jump") && l.contains("out of the image")), "{v:?}"); +} diff --git a/decompiler/crates/kuna-verify/tests/verdict_guards.rs b/decompiler/crates/kuna-verify/tests/verdict_guards.rs new file mode 100644 index 0000000000..702fadd05e --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/verdict_guards.rs @@ -0,0 +1,878 @@ +//! What a verdict may claim. A run that traps on both sides is not an +//! agreement, a loop of empty blocks spends the budget, a store to a local +//! a callee is given is compared at the call, and the CLI never reports success +//! for work it did not do. The x86-64 fixtures: +//! +//! ```c +//! int quot(int a, int b) { return a / b; } // mov eax,edi; cdq; idiv esi; ret +//! void spin(void) { for (;;) ; } // jmp spin +//! void give(void) { int x = 1; sink(&x); } // sub rsp,24; mov [rsp+12],1; lea rdi,[rsp+12]; call sink; ... +//! ``` + +use std::path::PathBuf; +use std::process::Command; + +use kuna_verify::{check_binary, Options, Verdict}; +use object::write::{Object, Relocation, Symbol, SymbolSection}; +use object::{ + Architecture, BinaryFormat, Endianness, RelocationFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope, +}; + +fn specs() -> String { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../specs").canonicalize().unwrap().to_string_lossy().into_owned() +} + +/// An object holding `.text` with the given functions, `(name, offset, size)`, +/// and a call to the undefined function named at each offset in `calls`. +fn object(name: &str, text: &[u8], functions: &[(&str, u64, u64)], calls: &[(u64, &str)]) -> PathBuf { + object_for(Architecture::X86_64, name, text, functions, calls) +} + +fn object_for(arch: Architecture, name: &str, text: &[u8], functions: &[(&str, u64, u64)], calls: &[(u64, &str)]) -> PathBuf { + let mut obj = Object::new(BinaryFormat::Elf, arch, Endianness::Little); + let code = obj.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text); + obj.append_section_data(code, text, 16); + let sym = |obj: &mut Object, name: &str, value, size, section| { + obj.add_symbol(Symbol { + name: name.as_bytes().to_vec(), + value, + size, + kind: SymbolKind::Text, + scope: SymbolScope::Linkage, + weak: false, + section, + flags: SymbolFlags::None, + }) + }; + for &(f, at, size) in functions { + sym(&mut obj, f, at, size, SymbolSection::Section(code)); + } + let mut externs: Vec<(&str, object::write::SymbolId)> = Vec::new(); + for &(offset, callee) in calls { + let symbol = match externs.iter().find(|(n, _)| *n == callee) { + Some(&(_, id)) => id, + None => { + let id = sym(&mut obj, callee, 0, 0, SymbolSection::Undefined); + externs.push((callee, id)); + id + } + }; + obj.add_relocation(code, Relocation { offset, symbol, addend: -4, flags: RelocationFlags::Elf { r_type: 4 } }) + .unwrap(); + } + let dir = std::env::temp_dir().join(format!("kuna-verify-guards-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join(format!("{name}.o")); + crate::zext_pair::write_whole(&path, &obj.write().unwrap()); + path +} + +fn quot() -> PathBuf { + object("quot", &[0x89, 0xf8, 0x99, 0xf7, 0xfe, 0xc3], &[("quot", 0, 6)], &[]) +} + +fn check(path: &PathBuf, functions: &[&str], opts: &Options) -> Vec { + let functions: Vec = functions.iter().map(|f| f.to_string()).collect(); + check_binary(&path.to_string_lossy(), &functions, &[], &[specs()], None, opts).unwrap() +} + +#[test] +fn runs_that_trap_on_both_sides_are_not_counted_as_agreeing() { + let reports = check("(), &["quot"], &Options { runs: 64, ..Options::default() }); + let r = &reports[0]; + let Verdict::Agrees(n) = r.verdict else { panic!("{}", r.render()) }; + assert!(n > 0 && n < 64, "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("trapped on both sides")), "{}", r.render()); +} + +#[test] +fn a_loop_of_empty_blocks_spends_the_budget() { + let spin = object("spin", &[0xeb, 0xfe], &[("spin", 0, 2)], &[]); + let reports = check(&spin, &["spin"], &Options { runs: 1, budget: 1000, ..Options::default() }); + assert_eq!(reports[0].verdict.label(), "UNKNOWN(budget)", "{}", reports[0].render()); +} + +/// The local a callee receives is compared at the call; the default build +/// stores it as the machine does. +#[test] +fn a_local_a_callee_receives_is_compared_at_the_call() { + let text = [ + 0x48, 0x83, 0xec, 0x18, 0xc7, 0x44, 0x24, 0x0c, 0x01, 0, 0, 0, 0x48, 0x8d, 0x7c, 0x24, 0x0c, 0xe8, 0, 0, 0, 0, 0x48, + 0x83, 0xc4, 0x18, 0xc3, + ]; + let give = object("give", &text, &[("give", 0, text.len() as u64)], &[(18, "sink")]); + let reports = check(&give, &["give"], &Options { runs: 16, ..Options::default() }); + assert_eq!(reports[0].verdict, Verdict::Agrees(16), "{}", reports[0].render()); +} + +/// A local whose address an earlier call kept is compared at later calls: +/// `save(&x); x = 1; consume();`. +#[test] +fn a_local_an_earlier_call_kept_is_compared_later() { + let text = [ + 0x48, 0x83, 0xec, 0x18, 0x48, 0x8d, 0x7c, 0x24, 0x0c, 0xe8, 0, 0, 0, 0, 0xc7, 0x44, 0x24, 0x0c, 0x01, 0, 0, 0, 0xe8, + 0, 0, 0, 0, 0x48, 0x83, 0xc4, 0x18, 0xc3, + ]; + let kept = object("kept", &text, &[("kept", 0, text.len() as u64)], &[(10, "save"), (23, "consume")]); + let reports = check(&kept, &["kept"], &Options { runs: 16, ..Options::default() }); + assert_eq!(reports[0].verdict, Verdict::Agrees(16), "{}", reports[0].render()); +} + +/// A function that fails to load gets its own verdict, and never a second +/// check of the function loaded before it. +#[test] +fn a_failed_load_does_not_check_the_previous_function_again() { + let reports = check("(), &["quot", "missing"], &Options { runs: 4, ..Options::default() }); + let names: Vec<&str> = reports.iter().map(|r| r.function.as_str()).collect(); + assert_eq!(names, ["quot", "missing"], "{reports:?}"); +} + +#[test] +fn check_opens_a_binary_whose_path_contains_spaces() { + let path = object("with space", &[0xb8, 7, 0, 0, 0, 0xc3], &[("f", 0, 6)], &[]); + let out = verify(&["check", &path.to_string_lossy(), "f", "--runs", "1", "--sleighpath", &specs()]); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + assert!(String::from_utf8_lossy(&out.stdout).contains("f AGREES(1)")); +} + +#[test] +fn mutate_reports_load_failures_in_process_and_in_workers() { + let binary = quot(); + let missing = binary.with_file_name("nonexistent.o"); + for jobs in ["1", "2"] { + for (path, name, diagnostic) in [(&missing, "quot", "No load image present"), (&binary, "nonexistent", "no function matches")] { + let out = verify(&["mutate", &path.to_string_lossy(), name, "--jobs", jobs, "--runs", "1", "--sleighpath", &specs()]); + let stderr = String::from_utf8_lossy(&out.stderr); + assert_eq!(out.status.code(), Some(3), "{stderr}"); + assert!(stderr.contains(diagnostic), "{stderr}"); + } + } +} + +#[test] +fn a_boolean_contract_converts_the_whole_return_value() { + let path = object("bool contract", &[0xb8, 0, 1, 0, 0, 0xc3], &[("f", 0, 6)], &[]); + let opts = Options { runs: 1, ..Options::default() }; + let functions = ["f".to_string()]; + for source in ["_Bool f(void);", "typedef _Bool result;\nresult f(void);"] { + let reports = check_binary(&path.to_string_lossy(), &functions, &[], &[specs()], Some((source, "prototype.c")), &opts).unwrap(); + let r = &reports[0]; + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.ends_with(" 0x01")), "{}", r.render()); + } +} + +/// `dec` is `decompile`: an abbreviated command is checked too. +#[test] +fn an_abbreviated_decompile_is_checked() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../tests/datatests/pointersub.xml"); + let res = kuna_verify::check_datatest(&path.to_string_lossy(), &[specs()], &Options { runs: 4, ..Options::default() }); + assert!(res.reports.iter().any(|r| r.function == "getOuter"), "{:?}", res.error); +} + +#[test] +fn a_missing_corpus_path_is_a_usage_error() { + let out = verify(&["corpus", "no-such-directory", "--jobs", "1"]); + assert_eq!(out.status.code(), Some(2), "{}", String::from_utf8_lossy(&out.stderr)); +} + +fn verify(args: &[&str]) -> std::process::Output { + Command::new(env!("CARGO_BIN_EXE_kuna-verify")).args(args).output().unwrap() +} + +#[test] +fn zero_runs_is_a_usage_error() { + let out = verify(&["check", "nothing.o", "f", "--runs", "0"]); + assert_eq!(out.status.code(), Some(2), "{}", String::from_utf8_lossy(&out.stderr)); +} + +#[test] +fn a_file_that_cannot_be_checked_fails_the_corpus() { + let dir = std::env::temp_dir().join(format!("kuna-verify-badxml-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let bad = dir.join("broken.xml"); + std::fs::write(&bad, "").unwrap(); + let out = verify(&["corpus", &bad.to_string_lossy(), "--sleighpath", &specs(), "--jobs", "1"]); + assert_eq!(out.status.code(), Some(3), "{}", String::from_utf8_lossy(&out.stdout)); +} + +/// `check` over worker processes reports each function once, with the +/// verdict it gets in one process. +#[test] +fn chunked_workers_give_the_verdicts_of_one_process() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../kuna-analysis/tests/fixtures/regglobal_fmt_x86_64"); + let path = path.to_string_lossy().into_owned(); + let entries = kuna_verify::session::function_entries(&path, &[], &[specs()]).unwrap(); + let functions: Vec = entries.iter().take(40).map(|e| format!("{e:#x}")).collect(); + let rows = |jobs: &str| { + let mut args = vec!["check", path.as_str()]; + args.extend(functions.iter().map(String::as_str)); + args.extend(["--json", "--runs", "2", "--jobs", jobs, "--sleighpath"]); + let specs = specs(); + args.push(&specs); + let out = verify(&args); + let mut v: Vec = String::from_utf8_lossy(&out.stdout) + .lines() + .filter(|l| l.starts_with("{\"function")) + .map(|l| { + let j: serde_json::Value = serde_json::from_str(l).unwrap(); + format!("{} {}", j["function"], j["label"]) + }) + .collect(); + v.sort(); + v + }; + let one = rows("1"); + assert_eq!(one.len(), 40); + assert_eq!(rows("3"), one); +} + +/// A call followed only by padding and then another function does not +/// return, whatever its callee: `die(1);` then `g`. The machine stops at it as +/// kuna's flow does, instead of running on into `g`. +#[test] +fn a_call_with_only_padding_after_it_does_not_return() { + let text = [ + 0xbf, 0x01, 0, 0, 0, 0xe8, 0, 0, 0, 0, 0x0f, 0x1f, 0x00, 0x66, 0x90, 0x90, 0xb8, 0x05, 0, 0, 0, 0xc3, + ]; + let path = object("padded", &text, &[("f", 0, 16), ("g", 16, 6)], &[(6, "die")]); + let reports = check(&path, &["f"], &Options { runs: 16, ..Options::default() }); + assert_eq!(reports[0].verdict, Verdict::Agrees(16), "{}", reports[0].render()); +} + +/// A corpus worker still running after `--file-seconds` is killed and its +/// file reported as an error, so one stuck file cannot hold a run up. +#[test] +fn a_corpus_worker_past_its_time_is_killed() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../tests/datatests"); + let files = [dir.join("pointersub.xml"), dir.join("ccmp.xml")].map(|p| p.to_string_lossy().into_owned()); + let specs = specs(); + let started = std::time::Instant::now(); + let out = verify(&[ + "corpus", &files[0], &files[1], "--jobs", "2", "--runs", "2000000", "--file-seconds", "1", "--sleighpath", &specs, + ]); + let text = String::from_utf8_lossy(&out.stdout); + assert_eq!(out.status.code(), Some(3), "{text}"); + assert!(text.contains("timeout: no verdicts in 1 s"), "{text}"); + assert!(started.elapsed() < std::time::Duration::from_secs(60)); +} + +fn mutants(test: &str) -> Vec { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../tests").join(test).to_string_lossy().into_owned(); + let specs = specs(); + let out = verify(&["mutate", &path, "--jobs", "1", "--json", "--sleighpath", &specs]); + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str::(l).ok()).filter(|v| v.get("operator").is_some()).collect() +} + +/// A direct call kuna names another function for is a difference, also where +/// the callee is outside the image (the datatest's bytes end before it). +#[test] +fn a_mutant_call_target_is_caught() { + let rows = mutants("datatests/concat.xml"); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert!(!targets.is_empty()); + assert!(targets.iter().all(|r| r["killed"] == true), "{targets:?}"); +} + +/// A call that passes fewer arguments than the declared prototype kuna gives +/// its callee is a difference (Noelo-Lab/kuna#1922's shape). +#[test] +fn a_call_short_of_its_declared_prototype_is_caught() { + let rows = mutants("stages/kuna-narrowext.xml"); + let dropped: Vec<_> = rows + .iter() + .filter(|r| r["operator"] == "drop-arg" && r["reached"] == true && r["what"].as_str().unwrap_or("").contains("declared prototype kept")) + .collect(); + assert!(!dropped.is_empty()); + assert!(dropped.iter().all(|r| r["killed"] == true), "{dropped:?}"); +} + +/// The caller returns callee(7) + 3. The callee reads its first cdecl slot, +/// then either doubles it or masks off its low bit before returning. +#[test] +fn a_cdecl_stack_argument_is_replayed_for_a_real_callee() { + use kuna_verify::mutate::Operator; + + let opts = Options { runs: 8, ..Options::default() }; + let caller = [0x6a, 7, 0xe8, 7, 0, 0, 0, 0x83, 0xc4, 4, 0x83, 0xc0, 3, 0xc3]; + for (name, calc, differs) in [("twice", [0x6b, 0xc0, 2], true), ("even", [0x83, 0xe0, 0xfe], false)] { + let text = [caller.as_slice(), &[0x8b, 0x44, 0x24, 4], &calc, &[0xc3]].concat(); + let path = object_for(Architecture::I386, name, &text, &[("caller", 0, 14), ("callee", 14, 8)], &[]); + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["caller".to_string()], &[]); + let mut checked = false; + kuna_verify::session::drive(script, None, &[specs()], |prog, fd| { + let r = kuna_verify::check::check_function(prog, fd, None, &opts); + assert_eq!(r.verdict, Verdict::Agrees(8), "{}", r.render()); + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + let mutants = kuna_verify::mutate::mutants(&program, &calls); + let constant = mutants.iter().copied().find(|m| { + m.operator == Operator::Constant && matches!(program.blocks[m.block].ops[m.op].kind, kuna_verify::program::Kind::Call { .. }) + }).expect("a mutant of the cdecl stack argument"); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, constant).unwrap(); + assert!(reached); + if differs { + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("reads stack[0x4] = 0x07; kuna passes 0x06")), "{}", r.render()); + let no_replay = Options { call_reruns: 0, ..opts }; + let (r, _, _) = kuna_verify::check::check_mutant(prog, fd, &no_replay, constant).unwrap(); + assert!(r.verdict.label().starts_with("UNKNOWN(call-reruns"), "{}", r.render()); + let dropped = mutants.into_iter().find(|m| m.operator == Operator::DropArg).unwrap(); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, dropped).unwrap(); + assert!(reached); + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("reads stack[0x4] = 0x07; kuna's call passes nothing")), "{}", r.render()); + } else { + assert_eq!(r.verdict, Verdict::Agrees(8), "{}", r.render()); + } + checked = true; + }).unwrap(); + assert!(checked); + } +} + +/// `report(int tag, const char *fmt, ...)` from `kuna-varargsave` (gcc -O2) +/// hands its `va_list` to `vsink`, declared and outside the image, so the save +/// area is compared at the call. kuna's `varargsave` folds the stores that fill +/// it; the decompiled side fills it as `va_start` does, so both passes agree. +#[test] +fn a_folded_register_save_area_is_filled_as_va_start_does() { + let text = "4881ecd8000000488954243048894c24384c894424404c894c244884c074370f\ +294424500f294c24600f295424700f299c24800000000f29a424900000000f29\ +ac24a00000000f29b424b00000000f29bc24c0000000488d8424e0000000488d\ +542408c7442408100000004889442410488d442420c744240c30000000488944\ +2418e869ffffff4881c4d8000000c390"; + let pass = "lo fu reportdecompile"; + let xml = format!( + "\ +{text}\ +\ +" + ); + let dir = std::env::temp_dir().join(format!("kuna-verify-guards-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("vararg-report.xml"); + std::fs::write(&path, xml).unwrap(); + let res = kuna_verify::check_datatest(&path.to_string_lossy(), &[specs()], &Options { runs: 32, ..Options::default() }); + assert_eq!(res.error, None); + let labels: Vec = res.reports.iter().map(|r| r.verdict.label()).collect(); + assert_eq!(labels, ["AGREES(32)", "AGREES(32)"], "{}", res.reports.iter().map(|r| r.render()).collect::()); +} + +/// `int thunk(int a) { return target(a, 0); }` as `xor esi,esi; jmp target`: +/// kuna recovers `a` as the low half of `RDI` and passes only that half on, so +/// the four bytes of `RDI` the callee could still read are a suspect. (The +/// review's AArch64 veneer case no longer narrows: kuna now passes a stated +/// pointer whole.) +#[test] +fn an_argument_cut_to_part_of_its_register_is_a_suspect() { + let xml = "\ +f30f1efa4885f67402893e893def1f00008d447f01c3662e0f1f840000000000f30f1efa31f6ebd80f1f840000000000f30f1efa8935c61f00000faff28d043e\ +c30f1f400066662e0f1f840000000000f30f1efa83c601ebd70f1f8000000000f30f1efabf01000000ba03000000e8adffffffbe0200000089c1e8d1ffffff01\ +c8c30f1f0066662e0f1f840000000000f30f1efabf01000000ba03000000e87dffffffbe02000000eba6\ +\ +"; + let dir = std::env::temp_dir().join(format!("kuna-verify-guards-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("narrowed-thunk.xml"); + std::fs::write(&path, xml).unwrap(); + let res = kuna_verify::check_datatest(&path.to_string_lossy(), &[specs()], &Options { runs: 32, ..Options::default() }); + assert_eq!(res.error, None); + let r = &res.reports[0]; + assert_eq!(r.verdict.label(), "AGREES(32)", "{}", r.render()); + assert_eq!(r.suspects, ["call 1 to 0x401000, argument 1: kuna passes 4 bytes of RDI, whose other bytes the machine sets"], "{}", r.render()); +} + +/// A call the machine makes through a register and kuna prints direct +/// (`lea rax,[rip+one]; call rax` as `one()`) has its target compared, and the +/// machine's callee effect is replayed only for the same callee: a mutant that +/// names `two` instead is caught. +#[test] +fn a_devirtualized_call_to_the_wrong_function_is_caught() { + let text = [ + 0xb8, 0x01, 0, 0, 0, 0xc3, 0xb8, 0x02, 0, 0, 0, 0xc3, 0x48, 0x83, 0xec, 0x08, 0x48, 0x8d, 0x05, 0xe9, 0xff, 0xff, 0xff, + 0xff, 0xd0, 0x83, 0xc0, 0x0a, 0x48, 0x83, 0xc4, 0x08, 0xc3, + ]; + let path = object("devirt", &text, &[("one", 0, 6), ("two", 6, 6), ("callvia", 12, 21)], &[]); + let specs = specs(); + let out = verify(&["mutate", &path.to_string_lossy(), "callvia", "--json", "--sleighpath", &specs]); + let rows: Vec = + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|v: &serde_json::Value| v.get("operator").is_some()).collect(); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert!(!targets.is_empty(), "{rows:?}"); + assert!(targets.iter().all(|r| r["killed"] == true), "{targets:?}"); +} + +/// A frame address stored at an unaligned address (a packed structure's +/// pointer field) still makes the object it points to reachable by a callee: +/// `x = 1; *(int **)0x600001 = &x; sink();` with `x = 0` planted is caught. +#[test] +fn a_pointer_stored_unaligned_still_escapes() { + let text = [ + 0x48, 0x83, 0xec, 0x28, 0xc7, 0x44, 0x24, 0x14, 0x01, 0, 0, 0, 0x48, 0x8d, 0x44, 0x24, 0x14, 0x3e, 0x48, 0x89, 0x04, 0x25, + 0x01, 0x00, 0x60, 0x00, 0xe8, 0, 0, 0, 0, 0x48, 0x83, 0xc4, 0x28, 0xc3, + ]; + let path = object("unaligned", &text, &[("give", 0, text.len() as u64)], &[(27, "sink")]); + let specs = specs(); + let out = verify(&["mutate", &path.to_string_lossy(), "give", "--per-function", "20", "--json", "--sleighpath", &specs]); + let rows: Vec = + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|v: &serde_json::Value| v.get("operator").is_some()).collect(); + let planted: Vec<_> = rows.iter().filter(|r| r["what"].as_str().unwrap_or("").starts_with("constant 0x1 -> 0x0")).collect(); + assert_eq!(planted.len(), 1, "{rows:?}"); + assert_eq!(planted[0]["killed"], true, "{planted:?}"); +} + +/// A binary that cannot be loaded is a file that could not be checked (3), not +/// a usage error (2). +#[test] +fn a_binary_that_cannot_be_loaded_exits_3() { + let missing = std::env::temp_dir().join(format!("kuna-verify-missing-{}.o", std::process::id())); + let specs = specs(); + let out = verify(&["check", &missing.to_string_lossy(), "f", "--sleighpath", &specs]); + assert_eq!(out.status.code(), Some(3), "{}", String::from_utf8_lossy(&out.stderr)); +} + +/// Two thunks that reach the same function are the same call only when they +/// leave the arguments alone: `add edi,1; jmp f` and `add edi,2; jmp f` are +/// not, so a mutant that calls the second instead of the first is caught. +#[test] +fn thunks_that_change_an_argument_are_different_calls() { + let text = [ + 0x89, 0xf8, 0xc3, 0x83, 0xc7, 0x01, 0xeb, 0xf8, 0x83, 0xc7, 0x02, 0xeb, 0xf3, 0x48, 0x83, 0xec, 0x08, 0xe8, 0xed, 0xff, 0xff, + 0xff, 0x48, 0x83, 0xc4, 0x08, 0xc3, + ]; + let path = object("thunks", &text, &[("f", 0, 3), ("plus1", 3, 5), ("plus2", 8, 5), ("caller", 13, 14)], &[]); + let specs = specs(); + let out = verify(&["mutate", &path.to_string_lossy(), "caller", "--json", "--sleighpath", &specs]); + let rows: Vec = + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|v: &serde_json::Value| v.get("operator").is_some()).collect(); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert!(!targets.is_empty(), "{rows:?}"); + assert!(targets.iter().all(|r| r["killed"] == true), "{targets:?}"); +} + +/// A callee that reads past the object kuna gives it (kuna types `[rsp]` as +/// four bytes, the callee reads `[rdi+4]`) is compared there too, when the +/// bytes are another of kuna's locals: `v2 = 4` planted for `v2 = 5` is caught. +#[test] +fn a_callee_reading_past_kuna_s_object_is_compared() { + let text = [ + 0x8b, 0x47, 0x04, 0xc3, 0x48, 0x83, 0xec, 0x18, 0xc6, 0x04, 0x24, 0x07, 0xc7, 0x44, 0x24, 0x04, 0x05, 0, 0, 0, 0x48, 0x89, + 0xe7, 0xe8, 0xe4, 0xff, 0xff, 0xff, 0x48, 0x83, 0xc4, 0x18, 0xc3, + ]; + let path = object("pastobject", &text, &[("reader", 0, 4), ("give", 4, 29)], &[]); + let specs = specs(); + let out = verify(&["mutate", &path.to_string_lossy(), "give", "--per-function", "20", "--json", "--sleighpath", &specs]); + let rows: Vec = + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|v: &serde_json::Value| v.get("operator").is_some()).collect(); + let planted: Vec<_> = rows.iter().filter(|r| r["what"].as_str().unwrap_or("").starts_with("constant 0x5 -> 0x4")).collect(); + assert_eq!(planted.len(), 1, "{rows:?}"); + assert_eq!(planted[0]["killed"], true, "{planted:?}"); +} + +fn mutant_rows(path: &std::path::Path, function: &str) -> Vec { + let specs = specs(); + let out = verify(&["mutate", &path.to_string_lossy(), function, "--per-function", "20", "--json", "--sleighpath", &specs]); + String::from_utf8_lossy(&out.stdout).lines().filter_map(|l| serde_json::from_str(l).ok()).filter(|v: &serde_json::Value| v.get("operator").is_some()).collect() +} + +/// Thunks that push a different argument before `jmp f` (`push 1; jmp f`, +/// `push 2; jmp f`, where `f` pops and returns it) are different calls: a +/// store or a stack-pointer change is never transparent. +#[test] +fn thunks_that_push_an_argument_are_different_calls() { + let text = [ + 0x58, 0x59, 0x51, 0xc3, 0x6a, 0x01, 0xeb, 0xf8, 0x6a, 0x02, 0xeb, 0xf4, 0x48, 0x83, 0xec, 0x08, 0xe8, 0xef, 0xff, 0xff, + 0xff, 0x48, 0x83, 0xc4, 0x08, 0xc3, + ]; + let path = object("pushthunks", &text, &[("f", 0, 4), ("push1", 4, 4), ("push2", 8, 4), ("caller", 12, 14)], &[]); + let rows = mutant_rows(&path, "caller"); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert!(!targets.is_empty(), "{rows:?}"); + assert!(targets.iter().all(|r| r["killed"] == true), "{targets:?}"); +} + +/// A thunk that only jumps is transparent: calling `f` instead of `jt` +/// (`jt: jmp f`) is the same call, so that mutant is not reported. +#[test] +fn a_jump_only_thunk_is_the_function_it_jumps_to() { + let text = [0xeb, 0x00, 0x89, 0xf8, 0xc3, 0x48, 0x83, 0xec, 0x08, 0xe8, 0xf2, 0xff, 0xff, 0xff, 0x48, 0x83, 0xc4, 0x08, 0xc3]; + let path = object("jumpthunk", &text, &[("jt", 0, 2), ("f", 2, 3), ("caller", 5, 14)], &[]); + let rows = mutant_rows(&path, "caller"); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert_eq!(targets.len(), 1, "{rows:?}"); + assert!(targets[0]["what"].as_str().unwrap_or("").contains("0x400000 -> 0x400002"), "{targets:?}"); + assert_eq!(targets[0]["killed"], false, "{targets:?}"); +} + +/// A loop bounded by its argument (`while (n) { r++; n--; }`) runs past the op +/// budget on both sides for a large `n`; those runs are counted apart, and the +/// runs that finish are compared. +#[test] +fn runs_past_the_budget_on_both_sides_are_counted_apart() { + let text = [0x31, 0xc0, 0x85, 0xff, 0x74, 0x08, 0x83, 0xc0, 0x01, 0x83, 0xef, 0x01, 0xeb, 0xf4, 0xc3]; + let path = object("countdown", &text, &[("countdown", 0, text.len() as u64)], &[]); + let reports = check(&path, &["countdown"], &Options { runs: 64, budget: 20_000, ..Options::default() }); + let r = &reports[0]; + let Verdict::Agrees(n) = r.verdict else { panic!("{}", r.render()) }; + assert!(n > 0 && n < 64, "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("on both sides; they are not compared")), "{}", r.render()); +} + +/// Thunks that set a scratch register the callee then reads (`mov r10d,1; +/// jmp helper` against `mov r10d,2; jmp helper`, `helper: mov eax,r10d`) are +/// different calls: only the ABI's veneer registers may be written by a +/// transparent thunk. +#[test] +fn thunks_that_set_a_scratch_register_are_different_calls() { + let text = [ + 0x44, 0x89, 0xd0, 0xc3, 0x41, 0xba, 0x01, 0, 0, 0, 0xeb, 0xf4, 0x41, 0xba, 0x02, 0, 0, 0, 0xeb, 0xec, 0x48, 0x83, 0xec, + 0x08, 0xe8, 0xe7, 0xff, 0xff, 0xff, 0x48, 0x83, 0xc4, 0x08, 0xc3, + ]; + let path = object("scratchthunks", &text, &[("helper", 0, 4), ("set1", 4, 8), ("set2", 12, 8), ("caller", 20, 14)], &[]); + let rows = mutant_rows(&path, "caller"); + let targets: Vec<_> = rows.iter().filter(|r| r["operator"] == "call-target" && r["reached"] == true).collect(); + assert!(!targets.is_empty(), "{rows:?}"); + assert!(targets.iter().all(|r| r["killed"] == true), "{targets:?}"); +} + +/// `gap`: `mov eax,1; mov edi,2; mov edx,3; syscall; ret`. kuna's IR reads +/// RAX, RDI and RDX and skips RSI, so the order its C passes them in does not +/// say which registers the kernel gets: the check cannot tell, and says so +/// instead of agreeing. +#[test] +fn a_system_call_that_skips_a_register_is_not_an_agreement() { + let text = [0xb8, 1, 0, 0, 0, 0xbf, 2, 0, 0, 0, 0xba, 3, 0, 0, 0, 0x0f, 0x05, 0xc3]; + let path = object("gap", &text, &[("gap", 0, text.len() as u64)], &[]); + let r = &check(&path, &["gap"], &Options::default())[0]; + let label = r.verdict.label(); + assert!(label.starts_with("UNKNOWN(unsupported-op: system call at 0x"), "{}", r.render()); + assert!(label.contains("not the first ones in order"), "{}", r.render()); +} + +/// An overlap after a call whose argument must be replayed: if the +/// replay budget leaves the argument unverified, the run cannot be called a +/// copy-overlap divergence, because a real argument mismatch may hide before it. +#[test] +fn an_overlap_with_unchecked_argument_replay_is_unknown() { + let text = [ + 0x53, 0x55, 0x48, 0x89, 0xfb, 0x89, 0xf5, // save the copy inputs + 0xc7, 0x43, 0x40, 7, 0, 0, 0, // mov dword ptr [rbx+64], 7 + 0xbf, 7, 0, 0, 0, // mov edi, 7 + 0xe8, 21, 0, 0, 0, // call callee + 0x83, 0xe5, 7, 0x48, 0x89, 0xde, // and ebp, 7; mov rsi, rbx + 0x48, 0x8d, 0x7c, 0x2b, 1, // lea rdi, [rbx+rbp+1] + 0xb9, 16, 0, 0, 0, // mov ecx, 16 + 0xf3, 0xa4, 0x5d, 0x5b, 0xc3, // rep movsb; pop rbp; pop rbx; ret + 0x89, 0x3d, 0, 1, 0, 0, 0xc3, // callee: mov [rip+256], edi; ret + ]; + let path = object("overlap_unchecked", &text, &[("caller", 0, 45), ("callee", 45, 7)], &[]); + let opts = Options { runs: 8, ..Options::default() }; + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["caller".to_string()], &[]); + let mut checked = false; + kuna_verify::session::drive(script, None, &[specs()], |prog, fd| { + let r = kuna_verify::check::check_function(prog, fd, None, &opts); + assert_eq!(r.verdict.label(), "DIVERGES(copy-overlap)", "{}", r.render()); + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + let mutants = kuna_verify::mutate::mutants(&program, &calls); + let dropped = mutants + .iter() + .copied() + .find(|m| m.operator == kuna_verify::mutate::Operator::DropArg) + .expect("a mutant of the callee argument"); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, dropped).unwrap(); + assert!(reached); + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + let no_replay = Options { call_reruns: 0, ..opts }; + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &no_replay, dropped).unwrap(); + assert!(reached); + assert!(r.verdict.label().starts_with("UNKNOWN(call-reruns"), "{}", r.render()); + checked = true; + }) + .unwrap(); + assert!(checked); +} + +/// The caller overwrites EAX after the call. When a missing argument takes +/// the callee through an unsupported instruction, the stub still lets the +/// caller return zero. That zero gives no evidence about the callee. +#[test] +fn a_register_argument_replay_that_falls_back_to_a_stub_is_unknown() { + use kuna_verify::mutate::Operator; + + let text = [ + 0x31, 0xff, // xor edi, edi + 0xe8, 3, 0, 0, 0, // call callee + 0x31, 0xc0, 0xc3, // xor eax, eax; ret + 0x85, 0xff, 0x75, 1, // callee: test edi, edi; jne unsupported + 0xc3, 0x0f, 0x0b, // ret; ud2 + ]; + let path = object("register_replay_stub", &text, &[("caller", 0, 10), ("callee", 10, 7)], &[]); + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["caller".to_string()], &[]); + let opts = Options { runs: 8, ..Options::default() }; + let mut checked = false; + kuna_verify::session::drive(script, None, &[specs()], |prog, fd| { + let r = kuna_verify::check::check_function(prog, fd, None, &opts); + assert_eq!(r.verdict, Verdict::Agrees(8), "{}", r.render()); + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + let drop = kuna_verify::mutate::mutants(&program, &calls).into_iter() + .find(|m| m.operator == Operator::DropArg).expect("a callee register argument"); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, drop).unwrap(); + assert!(reached); + assert!(r.verdict.label().starts_with("UNKNOWN(callee-replay"), "{}", r.render()); + assert!(r.verdict.label().contains("did not complete a concrete replay"), "{}", r.render()); + checked = true; + }).unwrap(); + assert!(checked); +} + +/// `g(p, n)`: `p[16] = 7` (an int), `sink()`, then `rep movsb` of 16 bytes +/// from `p` to `p + (n & 7) + 1`, an overlap kuna's `memcpy` does not define +/// and kuna cannot see. The copy is a declared divergence, but what the run did +/// before it is still compared: a mutant of the store dies at the call. +#[test] +fn a_call_before_an_overlapping_copy_is_still_compared() { + let text = [ + 0x53, 0x55, 0x48, 0x89, 0xfb, 0x89, 0xd5, 0xc7, 0x43, 0x40, 7, 0, 0, 0, 0xe8, 0, 0, 0, 0, 0x83, 0xe5, 0x07, 0x48, 0x89, 0xde, + 0x48, 0x8d, 0x7c, 0x2b, 0x01, 0xb9, 0x10, 0, 0, 0, 0xf3, 0xa4, 0x5d, 0x5b, 0xc3, + ]; + let path = object("overlap", &text, &[("g", 0, text.len() as u64)], &[(15, "sink")]); + let r = &check(&path, &["g"], &Options::default())[0]; + assert_eq!(r.verdict.label(), "DIVERGES(copy-overlap)", "{}", r.render()); + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["g".to_string()], &[]); + let mut killed = Vec::new(); + kuna_verify::session::run_steps(script, None, &[specs()], true, None, |step| { + let kuna_verify::session::Step::Decompiled { prog, fd, .. } = step else { return }; + let opts = Options::default(); + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + for m in kuna_verify::mutate::mutants(&program, &calls).into_iter().filter(|m| m.operator == kuna_verify::mutate::Operator::Constant) { + if let Some((r, what, _)) = kuna_verify::check::check_mutant(prog, fd, &opts, m) { + killed.push((what, r.verdict.label())); + } + } + }) + .unwrap(); + let stored: Vec<_> = killed.iter().filter(|(what, _)| what.ends_with("at 0x400007")).collect(); + assert!(!stored.is_empty(), "{killed:?}"); + assert!(stored.iter().all(|(_, label)| label == "DIFFERS"), "{killed:?}"); +} + +/// The first store is outside both copy ranges, with no call to snapshot it. +#[test] +fn memory_and_operands_of_an_overlapping_copy_are_compared_without_a_call() { + let text = [ + 0xc7, 0x47, 0x40, 7, 0, 0, 0, 0x83, 0xe2, 0x07, 0x48, 0x89, 0xfe, 0x48, 0x8d, 0x7c, 0x17, 0x01, 0xb9, 16, 0, 0, 0, 0xf3, 0xa4, 0xc3, + ]; + let path = object("overlap_prefix", &text, &[("g", 0, text.len() as u64)], &[]); + let opts = Options { runs: 16, ..Options::default() }; + let r = &check(&path, &["g"], &opts)[0]; + assert_eq!(r.verdict.label(), "DIVERGES(copy-overlap)", "{}", r.render()); + + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["g".to_string()], &[]); + let mut checked = false; + kuna_verify::session::drive(script, None, &[specs()], |prog, fd| { + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + let mutants = kuna_verify::mutate::mutants(&program, &calls); + let store = mutants.iter().copied() + .find(|m| m.operator == kuna_verify::mutate::Operator::DropStore) + .expect("a mutant that drops the first store"); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, store).unwrap(); + assert!(reached); + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.starts_with("memory before overlapping copy")), "{}", r.render()); + + let mask = mutants.into_iter().find(|m| { + m.operator == kuna_verify::mutate::Operator::Constant + && matches!(program.blocks[m.block].ops[m.op].kind, kuna_verify::program::Kind::Eval(kuna_num::opcodes::OpCode::CPUI_INT_AND)) + }).expect("a mutant that changes the destination mask"); + let (r, _, reached) = kuna_verify::check::check_mutant(prog, fd, &opts, mask).unwrap(); + assert!(reached); + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.starts_with("overlapping copy at")), "{}", r.render()); + checked = true; + }) + .unwrap(); + assert!(checked); +} + +#[test] +fn a_wide_copy_counts_bytes_instead_of_elements() { + let text = [ + 0x83, 0xe2, 0x07, 0x48, 0x89, 0xfe, 0x48, 0x8d, 0x7c, 0x17, 0x01, + 0xb9, 2, 0, 0, 0, 0xf3, 0x48, 0xa5, 0xc3, + ]; + let path = object("overlap_wide", &text, &[("g", 0, text.len() as u64)], &[]); + let r = &check(&path, &["g"], &Options { runs: 16, ..Options::default() })[0]; + assert_eq!(r.verdict.label(), "DIVERGES(copy-overlap)", "{}", r.render()); +} + +#[test] +fn a_copy_in_a_loop_is_compared_at_the_overlapping_visit() { + let text = [ + 0x49, 0x89, 0xf8, 0x48, 0x89, 0xfe, 0x48, 0x8d, 0xbf, 0x80, 0, 0, 0, 0xba, 2, 0, 0, 0, 0xb9, 16, 0, 0, 0, + 0xf3, 0xa4, 0x4c, 0x89, 0xc6, 0x49, 0x8d, 0x78, 0x01, 0xff, 0xca, 0x75, 0xee, 0xc3, + ]; + let path = object("copy_loop", &text, &[("g", 0, text.len() as u64)], &[]); + let r = &check(&path, &["g"], &Options { runs: 16, ..Options::default() })[0]; + assert_eq!(r.verdict.label(), "DIVERGES(copy-overlap)", "{}", r.render()); +} + +/// `g`: `mov ebx, 5; call h; mov eax, ebx; ret`, where `h` is `mov ebx, 7; +/// ret`. `h` changes RBX, which the convention says it preserves; kuna's C +/// follows the convention and returns 5, the program returns 7. The machine +/// puts RBX back as kuna assumes, so only the rerun that keeps the change +/// tells the run apart from an agreement. +#[test] +fn a_callee_that_breaks_the_convention_is_not_an_agreement() { + let text = [0xbb, 5, 0, 0, 0, 0xe8, 6, 0, 0, 0, 0x89, 0xd8, 0xc3, 0x90, 0x90, 0x90, 0xbb, 7, 0, 0, 0, 0xc3]; + let path = object("clobber", &text, &[("g", 0, 13), ("h", 16, 6)], &[]); + let r = &check(&path, &["g"], &Options::default())[0]; + let label = r.verdict.label(); + assert!(label.starts_with("UNKNOWN(abi-violation: the callee at 0x"), "{}", r.render()); + assert!(label.contains("changes RBX"), "{}", r.render()); +} + +/// `g`: `mov r11d, 5; call h; mov eax, r11d; ret`, where `h` is `mov r11d, 7; +/// ret`. The convention does not say a callee preserves R11 (the x86-64 cspec +/// lists only RAX, RDX and XMM0 as killed, and the argument and scratch +/// registers not at all), so the machine keeps the 7 `h` left. kuna's C keeps +/// the 5 across the call. Putting R11 back on the machine side made that an +/// agreement. +#[test] +fn a_register_the_convention_does_not_preserve_keeps_the_callee_s_value() { + let text = [0x41, 0xbb, 5, 0, 0, 0, 0xe8, 5, 0, 0, 0, 0x44, 0x89, 0xd8, 0xc3, 0x90, 0x41, 0xbb, 7, 0, 0, 0, 0xc3]; + let path = object("r11", &text, &[("g", 0, 15), ("h", 16, 7)], &[]); + let r = &check(&path, &["g"], &Options::default())[0]; + assert_eq!(r.verdict.label(), "DIFFERS", "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("machine RAX = 0x0000000000000007")), "{}", r.render()); +} + +/// `h` returns with `pop rcx; jmp rcx`, an indirect jump to its return +/// address, as ARM's `ldr pc, [sp], #8` does. The machine took that jump as a +/// branch inside the callee and ran the rest of `g` there, so `g`'s `pop rbx` +/// looked like `h` changing RBX. +#[test] +fn a_callee_that_jumps_to_its_return_address_returns() { + let text = [0x53, 0xbb, 5, 0, 0, 0, 0xe8, 4, 0, 0, 0, 0x89, 0xd8, 0x5b, 0xc3, 0x59, 0xff, 0xe1]; + let path = object("jmp_return", &text, &[("g", 0, 15), ("h", 15, 3)], &[]); + let r = &check(&path, &["g"], &Options::default())[0]; + assert!(r.verdict.label().starts_with("AGREES"), "{}", r.render()); + assert!(!r.render().contains("changes RBX"), "{}", r.render()); +} + +/// `skip`: `add rsp, 8; ret` returns past the harness's return address, to +/// whatever the stack holds above it. That is not the return kuna's C makes. +#[test] +fn a_return_to_another_address_is_not_a_return() { + let text = [0x48, 0x83, 0xc4, 0x08, 0xc3]; + let path = object("skip", &text, &[("skip", 0, text.len() as u64)], &[]); + let r = &check(&path, &["skip"], &Options::default())[0]; + let label = r.verdict.label(); + assert!(label.starts_with("UNKNOWN(unsupported-op: return at 0x"), "{}", r.render()); + assert!(label.contains("not to the return address"), "{}", r.render()); +} + +#[test] +fn a_concrete_callee_returning_to_unmapped_code_does_not_resume_its_caller() { + let text = [ + 0x48, 0x83, 0xec, 0x08, 0xe8, 0x0a, 0, 0, 0, 0x48, 0x83, 0xc4, 0x08, 0xb8, 7, 0, 0, 0, 0xc3, + 0x48, 0xc7, 0x04, 0x24, 0, 0, 0x50, 0, 0xc3, + ]; + let path = object("nested_return", &text, &[("caller", 0, 19), ("helper", 19, 9)], &[]); + let r = &check(&path, &["caller"], &Options { runs: 1, ..Options::default() })[0]; + assert!(r.verdict.label().starts_with("UNKNOWN(unsupported-op: a callee returned to unmapped address 0x500000"), "{}", r.render()); +} + +#[test] +fn a_wrong_return_after_a_concrete_call_does_not_count_as_agreement() { + let text = [ + 0x48, 0x83, 0xec, 0x08, 0xe8, 0x0c, 0, 0, 0, 0x48, 0x83, 0xc4, 0x08, + 0x83, 0xc0, 0x04, 0x48, 0x83, 0xc4, 0x08, 0xc3, 0xb8, 3, 0, 0, 0, 0xc3, + ]; + let path = object("caller_return", &text, &[("caller", 0, 21), ("helper", 21, 6)], &[]); + let r = &check(&path, &["caller"], &Options { runs: 1, ..Options::default() })[0]; + assert!(r.verdict.label().starts_with("UNKNOWN(unsupported-op: return at"), "{}", r.render()); + assert!(r.verdict.label().contains("not to the return address"), "{}", r.render()); +} + +#[test] +fn a_wrong_return_does_not_hide_an_earlier_call_difference() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../tests/datatests/injectoverride.xml"); + let opts = Options { runs: 16, ..Options::default() }; + let result = kuna_verify::check_datatest(&path.to_string_lossy(), &[specs()], &opts); + assert!(result.error.is_none(), "{:?}", result.error); + let report = result.reports.iter().find(|r| r.function == "callind_inject").unwrap(); + assert_eq!(report.verdict.label(), "DIFFERS", "{}", report.render()); + assert!(report.lines.iter().any(|l| l.starts_with("call 1 ")), "{}", report.render()); +} + +#[test] +fn tail_calls_can_return_through_an_unmodelled_link_register() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../tests/stages/kuna-calleereadarg-a64.xml"); + let opts = Options { runs: 4, ..Options::default() }; + let result = kuna_verify::check_datatest(&path.to_string_lossy(), &[specs()], &opts); + assert!(result.error.is_none(), "{:?}", result.error); + assert_eq!(result.reports.len(), 2); + for report in &result.reports { + assert_eq!(report.verdict, Verdict::Agrees(4), "{}", report.render()); + } +} + +/// `f(a)`: `sink(a)`, then `a - 3`, negated when negative. The checks of a +/// function's mutants share its setup and the machine's runs; each mutant +/// still gets what a check of it alone gets, whatever ran before it, a +/// `noreturn` mutant whose call every run reaches included. +#[test] +fn a_mutant_checked_on_shared_runs_ends_as_it_does_alone() { + let text = [ + 0x53, 0x89, 0xfb, 0xe8, 0, 0, 0, 0, 0x8d, 0x43, 0xfd, 0x85, 0xdb, 0x79, 0x02, 0xf7, 0xd8, 0x5b, 0xc3, + ]; + let path = object("shared_mutants", &text, &[("f", 0, text.len() as u64)], &[(4, "sink")]); + let opts = Options { runs: 32, ..Options::default() }; + let script = kuna_verify::session::binary_script(&path.to_string_lossy(), &["f".to_string()], &[]); + let mut operators = std::collections::BTreeSet::new(); + let mut killed = 0; + kuna_verify::session::drive(script, None, &[specs()], |prog, fd| { + let env = kuna_verify::state::Env::new(prog, opts.seed).unwrap(); + let calls = kuna_verify::calls::sites(fd, &env); + let program = kuna_verify::program::compile(prog, fd, &calls); + let mutants = kuna_verify::mutate::mutants(&program, &calls); + let alone: Vec<_> = mutants.iter().map(|&m| kuna_verify::check::check_mutant(prog, fd, &opts, m)).collect(); + let prepared = kuna_verify::check::prepare(prog, fd, &opts, false).unwrap_or_else(|r| panic!("{}", r.render())); + let shared = kuna_verify::check::Shared::new(&prepared); + let base = kuna_verify::check::check_shared(prog, fd, &opts, &shared); + let fresh = kuna_verify::check::check_function(prog, fd, None, &opts); + assert_eq!((base.verdict.label(), &base.lines), (fresh.verdict.label(), &fresh.lines)); + let key = |r: &Option<(kuna_verify::report::Report, String, bool)>| { + r.as_ref().map(|(r, what, reached)| (r.verdict.label(), r.lines.clone(), what.clone(), *reached)) + }; + for order in [false, true] { + let mut picked: Vec<_> = mutants.iter().copied().zip(&alone).collect(); + if order { + picked.reverse(); + } + for (m, alone) in picked { + let got = kuna_verify::check::check_mutant_shared(prog, fd, &opts, m, &shared); + assert_eq!(key(&got), key(alone), "{m:?}"); + operators.insert(format!("{:?}", m.operator)); + killed += usize::from(got.is_some_and(|(r, _, _)| r.verdict.label() == "DIFFERS")); + } + } + }) + .unwrap(); + assert!(operators.contains("NoReturn") && operators.contains("Branch") && operators.contains("Constant"), "{operators:?}"); + assert!(killed > 0); +} diff --git a/decompiler/crates/kuna-verify/tests/zext_pair.rs b/decompiler/crates/kuna-verify/tests/zext_pair.rs new file mode 100644 index 0000000000..f96cf11f6d --- /dev/null +++ b/decompiler/crates/kuna-verify/tests/zext_pair.rs @@ -0,0 +1,130 @@ +//! #794 end to end on 32-bit ARM: `ins16` returns a `u64` whose high word the +//! machine zeroes. Narrowed to `int` (`--option returnpair single`, the pre-fix +//! behavior) it agrees under the physical ABI and differs against the source's +//! contract; with the fix it agrees with both. + +use std::path::PathBuf; + +use kuna_verify::{check_binary, Options, Report, Verdict}; +use object::write::{Object, Symbol, SymbolSection}; +use object::{Architecture, BinaryFormat, Endianness, FileFlags, SectionKind, SymbolFlags, SymbolKind, SymbolScope}; + +const SOURCE: &str = "typedef unsigned long long u64; +u64 ins16(unsigned a, unsigned short b) { return ((a + 1) << 16) | b; } +u64 zadd(int a, int b) { return (unsigned)(a + b); } +u64 zsel(int a, unsigned b) { return a > 0 ? b : 7u; } +u64 twice(unsigned a, unsigned short b) { return ins16(a, b) * 2; } +"; + +/// `ins16` is `orr r0,r1,r0,lsl #16; mov r1,#0; add r0,r0,#65536; bx lr`; +/// `twice` calls it. +const FUNCS: &[(&str, &[u32])] = &[ + ("ins16", &[0xe1810800, 0xe3a01000, 0xe2800801, 0xe12fff1e]), + ("zadd", &[0xe0810000, 0xe3a01000, 0xe12fff1e]), + ("zsel", &[0xe3500000, 0xd3a01007, 0xe1a00001, 0xe3a01000, 0xe12fff1e]), + ("twice", &[0xe92d4800, 0xebfffff9, 0xe1a01081, 0xe1811fa0, 0xe1a00080, 0xe8bd4800, 0xe12fff1e]), +]; + +fn arm_object() -> PathBuf { + let mut text = Vec::new(); + let mut at = Vec::new(); + for (_, code) in FUNCS { + at.push(text.len() as u64); + text.extend(code.iter().flat_map(|w| w.to_le_bytes())); + } + let mut obj = Object::new(BinaryFormat::Elf, Architecture::Arm, Endianness::Little); + obj.flags = FileFlags::Elf { os_abi: 0, abi_version: 0, e_flags: 0x0500_0000 }; + let section = obj.add_section(Vec::new(), b".text".to_vec(), SectionKind::Text); + obj.append_section_data(section, &text, 16); + for ((name, code), &value) in FUNCS.iter().zip(&at) { + obj.add_symbol(Symbol { + name: name.as_bytes().to_vec(), + value, + size: (code.len() * 4) as u64, + kind: SymbolKind::Text, + scope: SymbolScope::Linkage, + weak: false, + section: SymbolSection::Section(section), + flags: SymbolFlags::None, + }); + } + let dir = std::env::temp_dir().join(format!("kuna-verify-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("zext_pair.o"); + write_whole(&path, &obj.write().unwrap()); + path +} + +/// Write `bytes` to `path` through a rename, so a test reading the fixture +/// never sees another test thread's half-written copy of it. +pub fn write_whole(path: &std::path::Path, bytes: &[u8]) { + static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let tmp = path.with_extension(format!("{n}.tmp")); + std::fs::write(&tmp, bytes).unwrap(); + std::fs::rename(&tmp, path).unwrap(); +} + +fn specs() -> Vec { + let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../specs"); + vec![p.canonicalize().unwrap().to_string_lossy().into_owned()] +} + +fn check(functions: &[&str], options: &[(&str, &str)], contract: bool) -> Vec { + let path = arm_object(); + let functions: Vec = functions.iter().map(|s| s.to_string()).collect(); + let options: Vec<(String, String)> = options.iter().map(|(n, v)| (n.to_string(), v.to_string())).collect(); + let opts = Options { runs: 64, ..Options::default() }; + let source = contract.then_some((SOURCE, "zext_pair.c")); + check_binary(&path.to_string_lossy(), &functions, &options, &specs(), source, &opts).unwrap() +} + +#[test] +fn narrowed_return_differs_only_against_the_contract() { + let physical = check(&["ins16"], &[("returnpair", "single")], false); + assert_eq!(physical[0].verdict, Verdict::Agrees(64), "{}", physical[0].render()); + assert!( + physical[0].suspects.iter().any(|s| s.contains("r1") && s.contains("every run")), + "{}", + physical[0].render() + ); + + let typed = check(&["ins16"], &[("returnpair", "single")], true); + let r = &typed[0]; + assert!(matches!(r.verdict, Verdict::Differs { .. }), "{}", r.render()); + let text = r.render(); + assert!(text.contains("contract u64 ins16(unsigned a, unsigned short b)"), "{text}"); + assert!(text.contains("r1:r0"), "{text}"); +} + +#[test] +fn the_fix_agrees_with_the_contract() { + let reports = check(&["ins16", "zadd", "zsel"], &[], true); + for r in &reports { + assert_eq!(r.verdict, Verdict::Agrees(64), "{}", r.render()); + } +} + +/// kuna prints `twice(void)` calling `sub_400020()`: it drops the two +/// arguments `twice` passes straight through to `ins16`. The machine runs the +/// callee for real, so the callee's reads show the drop. +#[test] +fn a_dropped_pass_through_argument_differs() { + let reports = check(&["twice"], &[], true); + let r = &reports[0]; + assert!(matches!(r.verdict, Verdict::Differs { .. }), "{}", r.render()); + assert!(r.render().contains("kuna's call passes nothing there"), "{}", r.render()); +} + +/// With no reruns allowed, the runs where `twice` drops a pass-through +/// argument the callee reads are not counted as agreeing, and say so; only the +/// runs where the dropped values happen to match count. +#[test] +fn calls_past_the_rerun_budget_are_not_agreement() { + let path = arm_object(); + let opts = Options { runs: 64, call_reruns: 0, ..Options::default() }; + let r = &check_binary(&path.to_string_lossy(), &["twice".to_string()], &[], &specs(), Some((SOURCE, "zext_pair.c")), &opts).unwrap()[0]; + let Verdict::Agrees(n) = r.verdict else { panic!("{}", r.render()) }; + assert!(n < 64, "{}", r.render()); + assert!(r.lines.iter().any(|l| l.contains("the machine was not rerun for the rest")), "{}", r.render()); +} diff --git a/docs/agents.md b/docs/agents.md index 46e4cc5b52..d40e6c00c4 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -18,7 +18,7 @@ is not needed for day-to-day work. | Path | What | |---|---| -| `decompiler/` | The engine — a cargo workspace. `kuna-decomp` is the decompiler (`src/` is phase-foldered: `p0_knowledge/`…`p9_emit/`, plus `substrate/`, `infra/` and the deobfuscation plane `deobf/`); `kuna-analysis` the loader/analyzer tier (ELF markup, strings, DWARF, function discovery); `kuna-sleigh`/`kuna-slacomp` the SLEIGH runtime/compiler (binary `slacomp`); `kuna-console` the `decomp_dbg`/`decomp_test_dbg` binaries; `kuna-cli` the user-facing `kuna` binary; `kuna-ghidra` and `kuna-wasm` the Ghidra and browser front-ends; `kuna-base`/`kuna-num`/`kuna-harness`/`kuna-lift-diff` support. | +| `decompiler/` | The engine — a cargo workspace. `kuna-decomp` is the decompiler (`src/` is phase-foldered: `p0_knowledge/`…`p9_emit/`, plus `substrate/`, `infra/` and the deobfuscation plane `deobf/`); `kuna-analysis` the loader/analyzer tier (ELF markup, strings, DWARF, function discovery); `kuna-sleigh`/`kuna-slacomp` the SLEIGH runtime/compiler (binary `slacomp`); `kuna-console` the `decomp_dbg`/`decomp_test_dbg` binaries; `kuna-cli` the user-facing `kuna` binary; `kuna-ghidra` and `kuna-wasm` the Ghidra and browser front-ends; `kuna-base`/`kuna-num`/`kuna-harness`/`kuna-lift-diff` support; `kuna-verify` the dev-only differential semantic check (`docs/features/diffverify/`). | | `decompiler/managed/` | Non-native engines, outside the p-code pipeline: `kuna-jvm`, a Rust port of Vineflower 1.12.0 and its bundled plugins (class files and jars to Java, Kotlin classes to Kotlin), same phase-folder taxonomy, its own schedule and IR; `kuna-cli` routes JVM inputs to it. | | `tests/datatests/` | Vendored XML regression corpus (83 files / 675 assertions) — what `make test` runs. | | `tests/stages/` | kuna-owned issue testcases — `make test-stages`. Conventions: `tests/stages/README.md`. | @@ -227,6 +227,7 @@ phases are **settable assertions/options** (`--option NAME VALUE`, discovered vi | `docs/re-pipeline.md` | The RE-friction loop: agents solve crackmes with kuna, record where it fails them, and close those gaps. The second, self-merging lane. | | `docs/decbench-loop.md` | The decbench benchmark / improvement campaign. | | `docs/modes.md` | `--mode auto\|reliable\|aggressive\|fast` option presets and size thresholds. | +| `docs/features/diffverify/README.md` | `kuna-verify`, the dev-only differential check: what it compares, its verdicts, how to read a `DIFFERS`, how to triage one. Agent rules and past regressions for the crate: `decompiler/crates/kuna-verify/AGENTS.md`. | | `docs/multilang.md` | The multi-language (Rust/Go/Swift) source-support architecture and roadmap: the `sourcelang` plane, idiom engine, type facets, per-language packs. | | `docs/observatory.md` | The local codebase observatory (`make observatory`): generated architecture/churn/coverage/walkthrough pages + their JSON contracts. | | `docs/missing-ghidra-analyses.md` | The `kuna-analysis` tier: the analyzer gap vs Ghidra, pass contract, commit gating. | diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md new file mode 100644 index 0000000000..e1ac4caa84 --- /dev/null +++ b/docs/features/diffverify/README.md @@ -0,0 +1,393 @@ +# diffverify — start here + +`kuna-verify` answers one question about a decompiled function: **does kuna's final IR +compute what the machine code computes?** It runs both from the same random machine +state and compares what each does: the calls it makes and their arguments, the memory it +writes outside its own frame, and the value it returns. No source code is needed. When +they differ, it prints the input that shows it and what each side did. + +It is a development tool. The crate is `decompiler/crates/kuna-verify`; the release `kuna` +binary does not link it, and nothing it does changes kuna's output. + +## 1. Quick start + +```sh +make binaries specs +(cd decompiler && cargo build --release -p kuna-verify) +K=decompiler/target/release/kuna-verify + +$K check ./prog main parse_args # some functions of a binary +$K check ./prog --all --jobs 10 # every function +$K corpus tests/datatests tests/stages # every function the test corpus decompiles +``` + +A difference looks like this (#794's fixture, with the option that brings the bug back): + +``` +ins16 DIFFERS (run 1 of 256) + contract u64 ins16(unsigned a, unsigned short b) (ins16.c) + input a0=0x00007fff (r0) a1=0x0000007f (r1) + machine r1:r0 = 0x000000008000007f + kuna int4 ins16(int4 a0, uint4 a1) = 0x8000007f; as u64 0xffffffff8000007f +``` + +## 2. What it checks, and what it does not + +- **Checked:** the final `Funcdata`, after every rule and action, against the function's + own SLEIGH p-code. Calls are compared one by one: where they are made from, their + target, their arguments, and the memory a callee could read at that moment. An + argument is compared at the width kuna passes it. When kuna passes only part of an + argument register to a stub callee with a recovered prototype, and the machine's + register holds more than that part zero- or sign-extended, the run names the dropped + bytes as a suspect (`kuna passes 4 bytes of x0, whose other bytes the machine sets`): + a stub never reads them, so no comparison would see a pointer kuna cut to `(int4)p`. + It is a lead only: an agreeing run still agrees, and unlike a prototype suspect it does + not turn a run that differs into `UNKNOWN`, since kuna's cut can be why it differs. At the end, + the memory written outside the frame and the return value are compared. The return + value is compared under the calling convention, and under the real return type when a + C prototype is given (`--contract FILE.c`). A `_Bool` contract compares zero or + one after testing the whole recovered return value for zero, including through + typedefs. Plain `char` there is unsigned on the + System V ABIs of ARM, AArch64, PowerPC, RISC-V and s390, and signed on x86, Apple + Silicon and Windows ARM; a source that mentions `-fsigned-char` or + `-funsigned-char` (in a comment) overrides it. The source is read without a + preprocessor, so a return type it cannot tell (a typedef defined two ways, one per + `#ifdef` branch, or two declarations with different return types) gives no contract: + `check` stops with an error naming it. +- **Not checked: the printed C.** A fault in the C printer (a cast, an operator's + precedence, a type's spelling) is not in the IR, so `AGREES` cannot rule it out. That + is Tier P, a separate axis (`proposal.md`). +- **Shared semantics.** Both sides use the same p-code op semantics (`value.rs`). A wrong + op semantic, or a wrong SLEIGH spec, is the same on both sides and invisible here. So are + the calling-convention models (`.cspec`): where arguments and return values live, what + a call preserves and what it pops. Checking those against an independent emulator and + against compiled code is a later tier's job (Tier L, `proposal.md`). +- **What the machine side takes from kuna.** It runs the machine code, but it still has to + know where each call's arguments live and whether a call returns. It does not take + kuna's word that a call does not return. It stops there only on evidence of its own: + - the callee's name is on Ghidra's no-return lists or on the checker's own list (for + `error` and `error_at_line`, only with a nonzero status); + - the compiler left only padding after the call; + - an in-image callee, run for real, reaches such a call. + + An in-image callee that, run for real, returns without going through a stub proves + kuna wrong. A run that ends on kuna's word alone is not counted (`noreturn-unverified`). +- **Where a function returns.** With a modelled outer return address, a run that + reaches a top-level `RETURN` to an unexpected address is `UNKNOWN(unsupported-op)` + when the calls ran without stubs. This catches functions that move their own + stack or return address (`add rsp, 8; ret`) even after a real callee returns. + Differences in earlier calls and system calls can still give `DIFFERS`. + With a modelled outer return address, a callee run without a stub that returns + to an unexpected unmapped address makes the run `UNKNOWN(unsupported-op)`. + This check applies to direct calls and indirect calls to known function entries. +- **The calling convention, for a callee run for real.** After a callee that returns, + the machine puts back only the registers the convention's model lists as + `unaffected` (on x86-64: RBX, RBP, R12-R15), not every register kuna's prototype does + not list as killed: the x86-64 cspec names only RAX, RDX and XMM0 killed, so the + argument and scratch registers keep what the callee left, as on the hardware. The + link register and the program counter are left out even where the cspec lists them + (ARM does): the call writes the one and the return the other. When a + callee at a function entry changes an `unaffected` register, the run is repeated with + the change kept; if that changes what the run does, it is `UNKNOWN(abi-violation)`, + otherwise the change is a suspect line. A callee returns when it jumps to its call's + continuation, by a `RETURN` or an indirect branch (ARM's `ldr pc, [sp], #8`, + x86's `pop rcx; jmp rcx`); the machine does not run the caller's code on as part + of the callee. +- **Stack arguments on x86-32 `cdecl`.** For a recovered prototype, the checker + tracks the mapped stack argument bytes a concrete callee reads before overwriting + them. If kuna passes different values there, the checker reruns the machine with + those values at the callee's entry stack pointer. Another callee return value or + other observable effects can give `DIFFERS`. A replay that falls back to a stub + or fails to return to the call's continuation with the expected stack pointer + leaves the check undecided. +- **How much it catches** is measured by planting faults in the IR (`mutation.md`): 76% + of reached mutants on the test corpus, 74–75% on `ls` and `find`. + +## 3. Verdicts + +| verdict | meaning | +|---|---| +| `AGREES(n)` | `n` runs agreed. Runs that trapped on both sides, or ran past `--budget` ops on both sides, are not counted, and the report says how many. A run past the budget on one side only makes the function `UNKNOWN(budget)`: one side may loop where the other does not. | +| `DIFFERS` | one run gave a difference. The report says which run and what differed. | +| `DIVERGES(id)` | the difference is one kuna makes on purpose, a declared divergence (`src/abi/divergence.rs`): `switchrunon-cut-row`, `synthesized-call`, `gowritebarrier`, `panic-check`, `ptrauth-trap`, `copy-overlap`, `divide-by-zero`, `nan-quieting`, `syscall-result`. Each one names the option that makes the trade, and the pattern the difference has to match. Any other difference under the same option is still `DIFFERS`. A declared call cuts the call trace at its site. An overlapping copy cuts the run at that instruction after comparing the earlier calls, system calls and memory, and the source, destination, byte count and direction of the copy. Unavailable machine operands, pending argument reruns or doubt about a callee's recovered prototype before the copy give `UNKNOWN`. | +| `UNKNOWN(reason)` | the check could not decide. `budget`: a side ran past `--budget` ops. `unsupported-op`: an op or user op the model does not run, or a system call whose registers kuna passes with a gap (§9). `trap`: only one side trapped, or both trapped in every run. `harness`: the model failed. `no switch row`: a switch value no row of kuna's table takes. `prototype-suspect`: the difference rests on a callee prototype kuna recovered and may have wrong. `uninitialized-local`: kuna's result depends on a local nothing assigned. `guessed-callee`: a callee whose effect the model had to guess. `noreturn-unverified`: every run ended at a call only kuna says does not return (§2). `call-reruns`: the replay limit left unchecked arguments before an overlapping copy or on every run. `callee-replay`: a callee could not be rerun concretely with kuna's arguments, or the resulting return value could not be compared. `assumed-domain`: it agrees only while a parameter kuna's recovered prototype types `bool` holds 0 or 1 (§5). `abi-violation`: a callee run for real changed a register the calling convention says it preserves, and the run depends on that change (§2). `timeout`: no verdict within `--fn-seconds`. | +| `SKIPPED(reason)` | reserved for Tier S. | + +Exit status: 1 when a function differs, 3 when a file could not be checked, 2 for a usage +error, and 0 otherwise. + +### Reading a report + +| line | says | +|---|---| +| `input` | the run's inputs, by the parameters kuna declares and where they live | +| `machine` / `kuna` | each side's return value. `kuna` repeats the prototype it states. | +| `contract` | the C prototype used for the return value, with `--contract` | +| `call N at A to T` | a call one side makes and the other does not, or makes from elsewhere or to another target | +| `call N to T, argument i (reg)` | an argument value that differs. With a recovered prototype it is a `PROTOTYPE_SUSPECT` note, not a difference. | +| `the callee reads R` / `the callee reads stack[...]` | a callee run for real reads an argument whose value kuna's C changes or omits | +| `kuna passes N arguments, and the prototype it gives the callee takes M` | a call short of its callee's declared prototype | +| `memory before call N` / `memory at exit` | the first byte that differs, and how many do | +| `kuna's result depends on ... which its C never assigns` | rerunning kuna's side with another value there changes its result: the C reads something it never set | +| `note` | not a difference: runs left out (trapped on both sides, or ended at a call only kuna says does not return), a call the machine ran itself | +| `trace` | with `--trace`: every call of the failing run on each side | +| `PROTOTYPE_SUSPECT(...)` | kuna's prototype for this function or a callee disagrees with what the run showed. This is not a verdict. | + +`--json` prints the same as one object per function (`function`, `verdict`, `label`, +`run`, `lines`, `suspects`, `ms`). A summary line follows. + +## 4. Commands + +```sh +kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... +kuna-verify corpus ... [--jobs N] [--file-seconds S] +kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] [--file-seconds S] +common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] +``` + +- **`check`** loads a binary with the options `kuna decompile` turns on (the Listing, and + the discovery passes off x86-64), so the function checked is the one the CLI prints. + `--option` passes kuna options through. With `--jobs`, the functions run in fixed chunks + of 32, one worker process per chunk. A function with no verdict after `--fn-seconds` is + `UNKNOWN(timeout)`. A time limit stops only a worker process, so giving `--fn-seconds` + (or `--file-seconds` to `corpus` and `mutate`) runs even one function or file in one. + A `--contract` file is read before any worker starts, and a worker that cannot read it + fails the run. +- **`corpus`** checks every decompile a datatest script makes, under the options that + script sets, one worker process per file. A worker still running after `--file-seconds` + is killed and its file reported as an error. With `--jobs 1` every file runs in one + process, so each datatest puts back the load-option environment its `option` commands + wrote; the next file loads as it would in a process of its own. +- **`mutate`** plants faults in kuna's side and reports how many the check catches + (`mutation.md`). A file or function that fails to load, or a worker that fails + to finish, gives exit status 3. + +## 5. How a check runs + +1. **Decompile.** `session.rs` drives the decompiler console in process and hands each + finished `Funcdata` to the check. +2. **Compile kuna's side.** `program.rs` turns the `Funcdata`'s blocks and ops into a + program with value slots. `calls.rs` records, for each call, what kuna says about it: + its target, prototype, killed registers, whether it returns, and where its arguments + live. Both sides use this record, so a call has one effect whichever side makes it. +3. **Make the state.** `state.rs` derives every register and memory byte from the run's + seed, lazily. It knows the image's read-only data, code sections and stack, and what a + call may write (memory an argument pointer reaches, globals). +4. **Run the machine side.** `machine.rs` lifts the function's own instructions one at a + time with kuna's SLEIGH translator and executes the p-code (`value.rs`, `x87.rs`). A + callee inside the image runs for real when the model can run it. kuna's side then + replays that callee's effect. A callee outside the image, or one the model cannot run, + gets a deterministic stub: it kills the registers the convention says it kills, with + values derived from the run, and may change the memory it can reach. A discarded + concrete attempt restores memory, registers and the execution metadata, including + nested stub observations and symbolic bytes. It still spends its execution budget. +5. **Run kuna's side.** `graph.rs` interprets the compiled program from the same state, + with the same stubs and replays. Where kuna's `varargsave` folded a variadic + function's register-save prologue, the printed `va_list` setup stands for + `va_start`, so kuna's side starts by filling the save area as `va_start` does (the + vector registers only when `al` is nonzero). At a call that receives the `va_list`, + the save area compared is the 176 bytes `va_start` defines, not the padding kuna's + local may take in. +6. **Compare.** `check.rs` compares the calls in order, the memory before each call, the + memory at exit and the return value. At a call, the frame objects compared are the + ones a callee can reach: an argument points to one, its address was stored outside + the frame (`global = &x`), or it was stored in an object already reachable + (`h.p = &x; f(&h)`). It declares divergences (`divergence.rs`), and + returns `UNKNOWN` where a difference rests on a guess. It also reruns kuna's side with + other values in anything kuna's C reads but never assigns. Both sides start a + parameter kuna's recovered prototype types `bool` at 0 or 1; a function that agrees is + then run again with any byte there. Differing there, or ending `UNKNOWN` there, is + `UNKNOWN(assumed-domain)`, since the domain is kuna's claim, not the program's; a + declared divergence there is the verdict. + Declared prototypes and the extensions the ABI documents keep their domain. Argument + replay requires a recorded concrete effect in both runs. If the first value chosen + for omitted register bytes prevents a concrete rerun, a second run can establish + a difference with zero in those bytes. Replay and the main check + use the ABI's return width, including x87 rounding, and apply the same NaN quiet-bit + equivalence. A supplied return contract also checks its own storage on machine reruns. +7. **Report.** `report.rs` prints the verdict as text or JSON. + +The crate is grouped by folder; the old module paths (`crate::check`, `crate::calls`, +...) are re-exported from `lib.rs`, so they still resolve. + +| folder | modules | role | +|---|---|---| +| `src/` | `lib.rs`, `bin/kuna-verify.rs`, `session.rs` | entry points, worker processes, the CLI; driving the console with the load options `kuna decompile` uses | +| `semantics/` | `value.rs`, `x87.rs`, `storage.rs` | p-code op semantics both sides share, x87's 80-bit format, storage names | +| `state/` | `mod.rs`, `mem.rs` | the machine state, image and stack layout; memory by copy-on-write pages, temporaries | +| `machine/` | `mod.rs`, `thunk.rs` | the machine side: lift, run, callees run for real, stubs; following thunks | +| `graph/` | `mod.rs`, `program.rs` | kuna's side: compiling a `Funcdata` for repeated runs, and running it | +| `abi/` | `mod.rs`, `calls.rs`, `contract.rs`, `divergence.rs` | calling conventions, per-call facts both sides share, C contracts, declared divergences | +| `compare/` | `check.rs`, `observe.rs`, `setup.rs` | the runs and the verdict; comparing calls, memory and system calls; each run's starting state | +| `tools/` | `mutate.rs` | mutation testing | +| `report/` | `mod.rs` | output | + +A later tier gets a folder of its own (`symbolic/` for Tier S, `printer/` for Tier P). + +## 6. In CI + +Not yet. A corpus baseline that CI compares each change against, and the CI step that +runs it, are a separate change. Until then `corpus` over `tests/datatests` and +`tests/stages` gives the same verdicts to compare by hand. + +## 7. As a check on pull requests + +The check is deterministic: its verdict comes from running the machine code, not from a +model's judgement, so it holds every pull request to the same bar whichever agent wrote +it. It has done two things review did not: + +- **Found bugs in merged code.** The decbench run found seven kuna bugs (#1916–#1922) + and three errors in the vendored SLEIGH specs (Tier L), all in code that + had passed its tests and review. +- **Confirmed fixes on its own.** The stage tests #1924 and #1927 added give `DIFFERS` + in their pass with the fix turned off and `AGREES` in the default pass, without anyone + reading the printed C. + +It is not a replacement for review. What it does not cover: + +- **Recall on real bugs is lower than on planted ones.** Of 22 past P3/P4 fixes put back + one at a time, it catches 7, and 11 with a C contract (`c4-results.md` §6). Planted + faults are caught at 74–76% (`mutation.md`). +- **The printed C.** Casts, precedence and readability are Tier P's (§2). +- **About 11% of functions get no verdict** (`UNKNOWN`): mostly the run budget, + unsupported ops (SIMD, user ops) and traps. +- **A `DIFFERS` still needs triage.** Most false ones so far were the harness's + (`triage.md` §2), so someone has to rule it out before blaming kuna. +- **What a reviewer looks at.** Option rules, the design of an edge case and code + quality are outside what running the IR can see. + +**Feedback an agent can act on.** A `DIFFERS` names an input, the call or byte that +differs and what each side did. That is a place to start debugging, not only a verdict, which is what an agent fixing its own change needs. + +**What is not claimed.** `AGREES` means the runs made agreed, not that the two are +equivalent on every input. The check covers semantic correctness of the decompile only: +not speed, memory safety or maintainability of the change. + +**The experiment that would settle it.** The hypothesis is that the check lowers the +semantic regressions decompiler pull requests bring in, without a stronger model. With +the same model and the same reasoning budget in every arm: + +| arm | how a change is written and checked | +|---|---| +| A | an agent writes the change and an agent reviews it | +| B | A, plus the existing tests (`make test`, `make test-stages`, `make rust-test`) | +| C | B, plus `kuna-verify`: a corpus baseline and the changed functions | + +Measured per arm: regressions that reach main, defects found before merge, fixes that +succeed, tokens spent, and fixes a maintainer has to add after merge. The tasks can be +replayed from merged pull requests that later needed a follow-up fix. It has not been +run yet. + +## 8. When a function differs + +1. **Read the report** (§3), and rerun with `--trace` to see every call. +2. **Rule out the harness** before naming a kuna bug (`triage.md`). The model has been + wrong before, about RTOS context switches, libgcc's multi-level returns, no-return + calls and joined return registers. `triage.md` lists them. +3. **Reduce it** to a few lines of C where you can (`clang --target=...`). Check that + `kuna decompile` prints the same wrong C, then file it or fix it. + +## 9. Not done yet + +- **Tier S and Tier P.** Proving agreement symbolically, and checking the printed C, are + designed (`proposal.md`) but not built. +- **PLT thunks as external calls everywhere.** Only the no-return check treats a thunk + that leads out of the image as an external call. Doing it everywhere exposes frame + pointers a function forms out of bounds (`ls` `O0` `group_number`, `&buf[-8]` aliasing + another slot), and how to judge those needs a design first. +- **The domain of an inferred narrow parameter.** An inferred `bool` is also checked with + any byte (§5); an `int` kuna infers in a register the ABI extends is still checked only + with extended values, which is right only when the inferred width is. Checking those + with any value too gave false `UNKNOWN`s (MIPS O32 `negative`), so it waits for a + rule that tells a width kuna inferred from one the ABI fixes. +- **A wrong return address after stubs.** If a run has used a stub, the checker + still accepts a top-level `RETURN` to an unexpected, unmapped address. The + stub's guessed stack cleanup can move the stack pointer, as in + `kuna-gobounds`. Checking this case requires tracking which stub effects + the return address depends on. +- **A function pointer the harness made up.** A pointer argument is an input like any + other, so an indirect call through one can land in the middle of some function in the + image, and the machine runs that code as the callee. The run then usually ends in a + return to another address, which is `UNKNOWN` (§2), so nothing false is claimed, but + the function is not checked (`ls` `cmp_extension`, `hash_do_for_each`). Running only a + known function entry fixes those, but it also stubs real pointers the image stores + (the x86-32 `kuna-stackcookie` functions) and calls through an unrelocated import slot + (`kuna-chkstkdarwin`); telling the two kinds of pointer apart comes first. +- **A callee that breaks the convention only because of made-up state.** On ARM + firmware most `UNKNOWN(abi-violation)`s left are not callees that fail to save a + register. Either a length or count the harness made up makes the callee overrun its + own frame and the saved copies with it (`crazyflie` `vl53l0xSetVcselPulsePeriod`, + a `memcpy` into a one-byte buffer; `u-boot` `flash_isset`), or an RTOS context switch + moves the stack pointer to another thread's stack and pops that thread's registers + (`chibios` `__port_switch`). `UNKNOWN` claims nothing false there, but those functions + go unchecked. To tell them apart from a real violation, the machine would have to + note that a callee's own saved copy was overwritten, or that the stack pointer moved + to another stack, before the callee's epilogue. +- **The caller's stack.** Memory compared at exit is everything outside the stack + region. Above the return address lie the incoming stack arguments, which the callee + owns and kuna may fold into variables, and then the caller's frame; a write there is + not compared yet. Telling the two apart needs the incoming argument area's size from + the machine side, not from kuna's prototype. +- **Replaying a counterexample.** A `DIFFERS` prints its inputs as text; there is no + `--replay` of a saved input. +- **Inputs random runs rarely hit.** A branch taken on one value in 2^32 is seldom + run. Concolic inputs from z3 (slice C5, `proposal.md`) are a separate change. +- **Unmapped stack arguments.** The x86-32 `cdecl` replay starts from stack slots + identified by call recovery and uses the callee's reads to check those slots. Finding + outgoing arguments that call recovery missed entirely requires independent evidence + to distinguish them from the rest of the caller's frame. Other conventions still + need their own stack mappings. +- **Object sizes for a callee outside the image.** What a callee can reach through a + frame pointer is kuna's local that holds it. A callee run for real is also compared on + the bytes it reads past that local, when they are another of kuna's locals; a stubbed + callee reads nothing the model sees, so there kuna's sizing still bounds the compare. +- **Code after a call kuna thinks returns.** If kuna misses that a call does not return, + it prints the bytes after it as code. No run reaches them on either side, so this is + invisible here; it is a readability fault for Tier P. A run in which a callee aborts + on its input stops on both sides, which is right. +- **Frame bytes kuna has no local for.** A callee run for real is compared on what it + reads inside and past the object it was given, but only where kuna has a local. A + byte kuna lost entirely (a store to a slot it never recovered) is not compared yet: + telling it from the outgoing argument area and saved registers, which kuna does not + keep in memory either, needs those found from the machine side first. +- **A return kuna claims narrower than the machine's register.** The return is compared + at the width kuna claims, and bytes of the return register outside it are not taken + as a wider return just because they vary: a 32-bit result computed in a 64-bit + register (`mov rax, rdi` for `int f(long x)`) leaves them varying too. A constant + value there is reported as a suspect. A caller that reads those bytes is where a + too-narrow return shows, when that caller is checked. +- **System-call arguments.** kuna passes a system call the registers its block sets + up, in order, and may leave some out. When they are the first argument registers, + each is compared with the machine's register at its place (one the machine never + touched holds its starting value). Which ones a given call needs is not modelled, so + one left out at the end is not a difference. One left out in the middle (the block + sets `r8` and `r9` but not `r10`) makes kuna's C pass the later values in the wrong + registers; its IR reads the right ones, so the check reports + `UNKNOWN(unsupported-op)` rather than agree or differ (`kuna-x64syscall` + `pointer_before`, pass `on`). +- **Arguments kuna recovered for a callee it has no prototype for.** At a call, the + arguments compared are the callee prototype's parameters. One kuna recovered from the + registers a call sets up (`sink(7)` where `sink` has no prototype) is checked only + where the machine runs the callee and the callee reads it; for a callee outside the + image it is not compared. +- **Which local function a PLT stub leads to.** A call kuna binds past a PLT stub is + checked to be a call to that stub. Where the stub leads comes from relocations the + machine side does not apply, so kuna's choice of target is not checked. +- **Speed.** Comparing memory by page rather than by byte, a lifting cache shared by a + worker's functions. None is at the top of the + current profile. +- **The pull-request experiment** of §7 has not been run. + +## 10. The other documents + +| file | what it holds | +|---|---| +| `proposal.md` | the design: tiers C, S, L and P, slices, principles, prior work | +| `analysis.md` | the analysis behind the proposal | +| `c1-results.md` | slice C1: register-only leaf functions | +| `c2-results.md` | slice C2: memory and calls | +| `c4-results.md` | slice C4 on the test corpus: precision and recall against restored bugs | +| `c4-decbench-results.md` | slice C4 on the decbench binaries: harness defects found, every `DIFFERS` sorted by cause, the issues filed | +| `triage.md` | how to decide whether a difference is the spec's, the emulator's, the checker's or the harness's | +| `mutation.md` | mutation testing: what share of planted faults the check catches | +| `record.json` | the slices' measured numbers, for scripts | diff --git a/docs/features/diffverify/analysis.md b/docs/features/diffverify/analysis.md index 63fb0c381d..c8221fcb30 100644 --- a/docs/features/diffverify/analysis.md +++ b/docs/features/diffverify/analysis.md @@ -90,7 +90,8 @@ concrete execution before symbolic proof, and a declared-divergence list from da ## 5. Pieces kuna already has - **Machine-side emulator.** `kuna-sleigh/src/emulate.rs` has `EmulatePcodeCache`, which - runs SLEIGH p-code over the load image. + runs SLEIGH p-code over the load image. C1 reuses its op table, not the engine: the + engine needs an `Rc`, and the `Architecture` owns its translator. - **Graph-side op semantics.** `p2_lift/kuna_emulatefunction.rs` has `EmulateFunction`/`EmulatePcodeOp`, which evaluates ops over a `Funcdata` syntax tree with a varnode-keyed state, for jump-table recovery. Only its per-op arithmetic carries diff --git a/docs/features/diffverify/c1-results.md b/docs/features/diffverify/c1-results.md new file mode 100644 index 0000000000..1e8b6b7ba1 --- /dev/null +++ b/docs/features/diffverify/c1-results.md @@ -0,0 +1,134 @@ +# diffverify — slice C1 results + +C1 is Tier C on register-only leaf functions (proposal, Slices), built as the dev-only +crate `decompiler/crates/kuna-verify`. This file records what it measured and what +building it changed in the design. + +```sh +make binaries specs +cd decompiler && cargo build --release -p kuna-verify && cd .. +decompiler/target/release/kuna-verify check ins16.o ins16 --contract ins16.c --option returnpair single +decompiler/target/release/kuna-verify corpus tests/datatests tests/stages +decompiler/target/release/kuna-verify check ins16.o --all --json +``` + +Run `corpus` from the repository root: stage tests load their fixtures by repo-relative +path. It runs one worker process per core (`--jobs N` to change it), and a file that +crashes the engine costs only its own verdicts. Every number below is from 256 runs per +function with the default seed. + +## 1. #794 against its source contract + +`--option returnpair single` is the pre-#794 behavior (the fix's commit message says the +option gives the word back). The fixture is the 32-bit ARM `ins16` from +`kuna-cli/tests/zext_pair_returns.rs`, rebuilt in `kuna-verify/tests/zext_pair.rs`. + +``` +$ kuna-verify check zext_pair.o ins16 --contract zext_pair.c --option returnpair single +ins16 DIFFERS (run 1 of 256) + contract u64 ins16(unsigned a, unsigned short b) (zext_pair.c) + input a0=0x00007fff (r0) a1=0x0000007f (r1) + machine r1:r0 = 0x000000008000007f + kuna int4 ins16(int4 a0, uint4 a1) = 0x8000007f; as u64 0xffffffff8000007f +``` + +The same run without `--contract` is `AGREES(256)` with +`PROTOTYPE_SUSPECT(the machine sets r1 to 0x00000000 on every run; the claimed return +leaves it out)`. The physical ABI cannot settle the prototype, and the check does not +claim it can. With the fix, `ins16`, `zadd` and `zsel` agree with their contracts. + +## 2. Verdicts over `tests/datatests` and `tests/stages` + +782 files, 3,979 decompiled functions (a script that decompiles a function twice counts +twice), no file errors. + +| verdict | functions | +|---|---:| +| `AGREES(256)` | 696 | +| `DIFFERS` | 4 | +| `DIVERGES` | 3 | +| `UNKNOWN` | 331 | +| `SKIPPED` | 2,945 | + +`SKIPPED` is outside C1: 2,003 functions call something, and 942 touch memory beyond their +own frame and read-only image data (C2). `UNKNOWN` is mostly honest: 155 CALLOTHERs +(syscalls, privileged and cache ops), about 150 floating-point ops, 15 step-budget +exhaustions, 7 lift failures, 4 decompiled flows that end in a halt, 1 return value kuna +stores in a temporary. + +The datatest corpus alone (83 files, 133 functions): 22 agree, 7 unknown, 104 skipped, no +difference, 7.3 s wall time. + +## 3. Every `DIFFERS` and `DIVERGES` + +| test | function | verdict | cause | +|---|---|---|---| +| `kuna-narrowext` | `pi`, `pu`, `psc` | `DIFFERS` | **The bug the test pins.** Its first pass sets `narrowext off`, the compiler spec's zero extension; on RV64 the machine relies on the sign-extended argument. The `abi` pass of the same functions agrees. Found without a contract. | +| `kuna-nullable-relocations` | `same` | `DIFFERS` | **Harness.** `cmpq $imm, %rdi` carries `R_X86_64_32S optional` against a weak symbol. kuna reads the weak address through a nullable slot; the machine side reads the loader's placeholder in the immediate. | +| `kuna-switchrunon`, `kuna-switchrunonguard` | `pick`, `pick`, `pick2` | `DIVERGES(switchrunon-cut-row)` | The run-on check cuts a bounds-free table, by design. On a selector past the kept rows the machine runs the next function's code. | + +Precision on this corpus: of 4 `DIFFERS`, 3 are a known bug and 1 is a harness limit. + +## 4. Harness defects found while building C1 + +Each of these first showed up as a `DIFFERS` or an inflated `AGREES`, and each would have +been reported as a kuna bug. They are why the corpus run is part of the slice. The first +run with current specs had 30 `DIFFERS`; 3 of them were the `narrowext` bug. + +| defect | effect before the fix | +|---|---| +| Compiled specs older than their sources in the main tree | 212 files failed to load, and every ARM, x86 and RISC-V verdict was about old semantics | +| Random upper bits in an argument register the ABI says the caller extends | 13 false `DIFFERS` on RV64, MIPS64 and PPC64 (`narrowext`'s fixed pass, `wide-shifts`, `constptrdeclared-riscv`, `mips-o32-register-slots`) | +| A written stack varnode not visible to a later LOAD of the same slot | 12 false `DIFFERS` (`arrayextent`, 4 functions decompiled 3 times) | +| A return value kuna keeps in a temporary, read from the machine's temporaries | 1 false `DIFFERS` (`gobool`) | +| Float ops whose names lack `FLOAT_` (`TRUNC`, `INT2FLOAT`) failing on both sides, which counted as agreement | functions reported `AGREES` though neither side ran the op | +| The jump-table placeholder label `NO_LABEL` masked to the selector's width matching a real selector | 1 false `DIFFERS` (`pick2` on `sel = 0xe1`) | + +## 5. Cost + +| | first build | now | +|---|---:|---:| +| check time, whole corpus | 49.8 s | 3.6 s | +| wall time, whole corpus | 111 s | 20.6 s (14 workers), 66 s (1) | +| wall time, `tests/datatests` | 7.3 s | 0.9 s | + +- The first build spent 47.2 s of its check time in the 15 functions that exhaust the + step budget on every random input (loops bounded by an argument). A function now stops + after 4 such runs (`Options::budget_runs`); its verdict is `UNKNOWN(budget)` either way. +- The decompiled function is compiled once into a flat program (`program.rs`) that every + run reuses, and registers live in a dense file that memoizes their initial bytes. +- Wall time is now mostly decompiling. Peak RSS is 454 MB for one process. +- Every verdict is identical before and after these changes, compared function by + function over the corpus, sequential and parallel alike. No solver and no compiler are + involved. + +## 6. What building C1 changed in the design + +1. **Machine side.** `EmulatePcodeCache` needs an `Rc`, and the + `Architecture` owns its translator. The machine side therefore lifts each instruction + with the program's own translator (`one_instruction`) and runs the ops itself, with the + same `OpBehavior` table `EmulatePcodeCache` uses. Both sides share that table; integer + ops on values of 9 to 16 bytes (a 64-bit multiply-high) are defined in `kuna-verify`, + and a unit test checks them against the table at 1, 2 and 4 bytes. +2. **Inputs keep the ABI's promises.** A 32-bit `int` reaches a 64-bit RISC-V or MIPS + register sign-extended, and a caller cannot pass anything else. Inputs follow the + documented rule (`narrowext abi`, through `kuna_narrowext::rules_for`) whatever the + run's own `narrowext`, so a run with the option off is checked against the real + convention. The rule applies to the **claimed** parameter widths. A prototype that claims + a parameter too narrow constrains the inputs to its claim; parameter types in contracts + remove that limit. +3. **Switches.** After jump-table normalization a BRANCHIND reads the switch variable, + not an address. The decompiled side takes the row whose label matches the selector, + else the table's default edge. A selector no row carries, on a table without a + default, is `UNKNOWN(no switch row)`. +4. **Declared divergences are predicates over observables, not engine flags.** The final + `Funcdata` does not keep whether `switchrunon` cut a table. `switchrunon-cut-row` matches + instead when a switch meets a selector no row carries and the machine's indirect branch + lands outside every block of the decompiled function. +5. **Exit-only user ops.** ARM's `bx lr` emits `setISAMode` before the RETURN. It is a + no-op before the function's exit and refused before a branch inside it. +6. **Halting flow.** A RETURN that kuna marks as a halt (a cut or undecodable flow) has no + defined value, so a run that reaches one is `UNKNOWN`. +7. **Relocated immediates** are a known limit (§3): the machine side reads the loader's + placeholder where kuna reads the relocation's target. C2 needs the relocation's runtime + value on the machine side. diff --git a/docs/features/diffverify/c2-results.md b/docs/features/diffverify/c2-results.md new file mode 100644 index 0000000000..0e58799ee0 --- /dev/null +++ b/docs/features/diffverify/c2-results.md @@ -0,0 +1,118 @@ +# diffverify — slice C2 results + +C2 adds memory and calls to Tier C (proposal, Slices). The machine side and the +decompiled side now load and store anywhere, and every call runs the same stub on both. +This file records how the model works, what it caught, and what is left for C4. + +```sh +decompiler/target/release/kuna-verify check callmem.o --all +decompiler/target/release/kuna-verify corpus tests/datatests tests/stages +``` + +## 1. The model + +**Memory.** The initial state defines every byte. A random pointer argument therefore +reads the same bytes on both sides, and the check never needs to know which arguments +are pointers. The observable is every byte either side leaves different outside the +stack, compared at each call and at the exit. + +**Calls.** Each call is compared in order on the call instruction's address. A computed +target is compared too, when both sides compute it (`CALLIND`). Its target is wrapped to +the code space and loses the ARM instruction-set bit. kuna's arguments are compared at +the storage its callee prototype gives them. A difference is `DIFFERS` only when that +prototype is declared (`is_input_locked`). A recovered one makes it a +`PROTOTYPE_SUSPECT`, as a return value is without a contract. Then the call has the same +effect on both sides (`calls.rs`, `State::call`): +- it kills the registers its model lists as killed-by-call and every output register, + with a value fixed by the run and the call's index; +- it pops `extrapop` bytes of stack; +- it may write the image's writable data and 4 KiB past every pointer passed to a + call so far. The memory is rewritten lazily: a byte this side did not write since + reads a value fixed by the call's index. + +That reachable set is never larger than what kuna itself treats as changed by a call. So +a value kuna keeps across a call stays equal unless kuna is wrong to keep it. A first +version that let a call write all memory outside the stack also rewrote the TLS stack +canary between the prologue and the epilogue. kuna knows the canary does not change, so +that version reported false `DIFFERS` (§4). + +**Calls kuna does not make.** Where kuna has no call at an instruction that calls code +in the image, kuna inlined, injected or dropped it. The machine runs that callee for +real, and its RETURN comes back to the caller. A deliberate removal then agrees, and a +wrong one shows up in what the callee does. A call kuna lacks to code outside the image +gets a stub and is reported as a call only the machine makes. + +**INDIRECT.** An INDIRECT stands before the op whose effect it describes, so the +compiled program moves each one after that op. Its output is then: +- the call's value for a register the call kills; +- what memory now holds for a stack or memory location; +- its input otherwise. + +**Limits.** A run makes at most 256 calls, so a loop of calls bounded by an argument +ends in `UNKNOWN(budget)` and does not grow without bound. No-return calls end both runs. +Memory builtins (`memcpy`, `strlen`, …) are `UNKNOWN(unsupported-op)`. + +## 2. The proposal's two checks + +Neither bug exists in kuna today, and their options were removed when the fixes became +unconditional (#1524). Each was put back for one run, in a local build only, behind an +environment variable that is not in this branch. + +| injected fault | function | default build | with the fault | +|---|---|---|---| +| #801: `Funcdata::stack_store_guard()` returns `false` | `inspect_bytes` (`kuna-stackstoreguard.xml`) | `AGREES(256)` | `DIFFERS`: `memory at exit: ram:0x50000000: machine 0x80, kuna 0x08`, with the note that the machine ran `helper` itself where kuna has no call | +| `guard_calls` adds no INDIRECT for `ram` | `twice` (`int a = counter; tick(); return a + counter;`) | `AGREES(256)` | `DIFFERS`: `machine EAX = 0xb1186181`, `kuna int4 twice() = 0x0000000a` (the value loaded before the call, used twice) | + +The second fixture is `kuna-verify/tests/call_effects.rs`, which pins the default +build's `AGREES`. + +## 3. The corpus + +`tests/datatests` and `tests/stages`, 3,979 decompiled functions, 256 runs each. + +| verdict | C1 | C2 | +|---|---:|---:| +| `AGREES(256)` | 696 | 2,482 | +| `DIFFERS` | 4 | 500 | +| `DIVERGES` | 3 | 3 | +| `UNKNOWN` | 331 | 994 | +| `SKIPPED` | 2,945 | 0 | + +Every function C1 found to agree still agrees, and its `DIFFERS` and `DIVERGES` are +unchanged, compared function by function. + +The 496 `DIFFERS` beyond C1's four are not triaged; that is C4's job. Their first differences, by +kind: + +| first difference | count | +|---|---:| +| return value | 147 | +| calls from different instructions (the two sides took different paths) | 83 | +| a call only the machine makes | 77 | +| memory before a call | 76 | +| memory at the exit | 41 | +| an argument to a declared callee | 42 | +| a call only kuna makes | 17 | +| a computed call target | 13 | + +A sample of the largest kind has most of them reading a stack local that a callee wrote +through a pointer: hidden return slots (`gh854-hiddenretarg-*`), and locals whose +address escaped (`varcross`, `partialmerge`). That is where the model's stack handling +gets checked next. + +## 4. Harness defects found while building C2 + +| defect | effect before the fix | +|---|---| +| A call's target read from the CALL op's first input, which by the final `Funcdata` names a call spec rather than an address | 1,560 false target differences | +| A call allowed to write all memory outside the stack, the TLS canary included | the canary check failed in every function with a stack protector, and the machine called `__stack_chk_fail` | +| A switch row whose address is not an out-edge's block start sent to the default edge | 1 false `DIFFERS` (`regionstructure-switch`); in C1 it hid behind a `void` return | +| A branch inside a delay-slot call instruction taken for a tail call | false extra calls on SPARC | +| Arguments read from the CALL op's input varnodes, which are temporaries | 746 false argument differences | +| Calls in a loop each keeping a memory snapshot | one function took 462 s; now 32 ms, capped at 256 calls | + +## 5. Cost + +Check time 50.3 s, wall time 11.0 s on 14 worker processes, peak RSS 332 MB for one +process. The check time grew because 2,945 skipped functions now run. Wall time fell +from 20.6 s: functions that loop over calls now stop at the call limit. diff --git a/docs/features/diffverify/c4-decbench-results.md b/docs/features/diffverify/c4-decbench-results.md new file mode 100644 index 0000000000..9bdb307406 --- /dev/null +++ b/docs/features/diffverify/c4-decbench-results.md @@ -0,0 +1,235 @@ +# diffverify — slice C4 on the decbench binaries + +`c4-results.md` ran the check on the corpus kuna already has. This file runs it on +real binaries: the decbench dataset (`noelo-lab/decbench-dataset`, 39 C projects, +x86-64 and i386 ELF/PE and Cortex-M firmware, at `O0`, `O2` and `O2-noinline`). + +```sh +kuna-verify check ... --json # the sample set +kuna-verify check --all --json # every function of a binary +``` + +kuna was built from `feat/diffverify-c2`, before any of the fixes in §4 merged. + +## 1. Harness defects real binaries showed + +The test corpus has small, hand-made binaries. Real ones found six defects in the +model, all fixed here: + +| defect | effect | fix | +|---|---|---| +| a call kuna knows does not return by its callee's name (`exit`, `__assert_fail`) was run on past | the machine ran into the next function | a call flow plants a no-return halt after is a no-return site (`calls.rs`) | +| a stubbed `bool` callee returned any byte | `x \|\| y` over its result differed from kuna's, which relies on 0 or 1 | the stub leaves 0 or 1 in a `bool` return register (`abi.rs`) | +| x86's `FS_OFFSET`/`GS_OFFSET` took random values, some inside the image | the stack-protector guard at `fs:0x28` changed across a call, and the machine took `__stack_chk_fail` | segment bases point at a fixed block outside the image and the stack (`check.rs`) | +| a Thumb `bx` refused (`setISAMode` before a branch) | every Cortex-M function with an interworking branch was `UNKNOWN` | a switch to the mode the target already decodes in runs (`machine.rs`) | +| memory barriers and x86's `lock` refused | `UNKNOWN(unsupported-op)` | no effect on one thread | +| ARM's exclusive monitor (`ldrex`/`strex`) refused | `UNKNOWN(unsupported-op)` | one thread always holds it: `strex` succeeds | + +On the test corpus these turned 82 `UNKNOWN` into `AGREES` and lost no `AGREES` +(`docs/baseline-verify.json` is re-recorded). They also exposed two `DIFFERS` there: +- `ghdec-isamode-inject` `dispatch`: kuna reads r3 after a call as if the call killed + it, but GCC's IPA-RA kept it there (the bug PR #1892 fixes); +- `kuna-armfloat-preset` `fixit`: the pass that turns `armfloatreturn` off, the bug + the test pins. + +## 2. The sample set + +decbench's published `sample-set`: 250 functions over 224 binaries. + +| verdict | before §1 | after §1 | +|---|---:|---:| +| `AGREES(256)` | 109 | 157 | +| `UNKNOWN` | 138 | 92 | +| `DIFFERS` | 3 | 1 | + +Two of the three `DIFFERS` before were the defects of §1 (`diff` `read_files`: a +`bool`; `touch` `main`: the stack guard). The one left is a harness limit (§4). + +## 3. Every function of a binary + +One binary per project, the one the sample set picks, every function: + +| | binaries done | functions | `AGREES` | `DIFFERS` | `UNKNOWN` | check time | +|---|---:|---:|---:|---:|---:|---:| +| `O2` | 32 of 37 | 12,641 | 9,941 (79%) | 126 | 2,574 | 0.9 CPU-h | +| `O0` | 34 of 37 | 15,592 | 12,742 (82%) | 117 | 2,732 | 1.6 CPU-h | + +Not done: `bash`, `cf2.elf`, `betaflight` and `cleanflight` (both levels) ran past a +40-minute limit, and `--all` printed only at the end, so they left nothing. `u-boot` +(`O2`) and `tar` (`O0`) were stopped by hand after two and a half hours. + +Since then `check` runs its functions over worker processes (`--jobs`, default the +core count). The functions go in fixed chunks of 32, one process per chunk, so which +functions share a process does not depend on `--jobs`. Each row prints as its function +finishes. A function with no verdict after `--fn-seconds` (600) is `UNKNOWN(timeout)`, +and the rest of its chunk goes to a new worker. `coreutils` `ls` (`O2`, 405 functions) +takes 31 s instead of 206 s with ten workers, with the same verdict for every function. `bash` +(`O2`), which left nothing before, finishes its 2,542 functions in 26 minutes on a +loaded machine, three of them `UNKNOWN(timeout)`. `u-boot` (`O2`) finishes its 2,013 +functions in 14 minutes with no timeout: it never hung, it needs 1.9 CPU-hours of checks, +which one process could not finish within the limit. Two lookups the model made for every +byte it read were linear scans: the loader's read-only ranges (925 in `bash`) and, for a +pointer outside the image, a load of that byte. They are now binary searches over merged +ranges. `bash` `set_pwd` checks in 5.2 s of CPU instead of 15.4 s, and +`make verify-corpus` takes 60 s instead of 110 s, with the same verdicts. + +`UNKNOWN` is half budget (2,785), half operations the model cannot run (2,274). Of +those: +- 1,263 are x87 80-bit floats (`fldz` and friends: `INT2FLOAT` into ten bytes); +- 444 are Cortex-M's `isCurrentModePrivileged`, which the model could answer with a + constant both sides read; +- 122 are ARM/Thumb switches to the mode the target is not already in; +- 106 are jumps to a random address, mostly through unrelocated GOT slots; +- 95 are `INT_AND` with an output narrower than its inputs (the IR defect a separate + fix handles); +- 93 are calls with unknown stack cleanup. + +## 4. The 243 `DIFFERS` + +| class | functions | what it is | +|---|---:|---| +| RTOS context switch | 74 | ChibiOS (57) and other RTOS calls into the scheduler. The machine runs the switch, which loads another thread's stack pointer from random memory: a harness limit. `chThdSetPriority` is the sample-set one | +| PLT stub of a function the object itself exports | 54 | `libedit`, `libselinux`, `libz`: kuna prints the `jmp [got]` stub as `(*dat_19018)()` and drops the arguments it forwards. A kuna defect, of little consequence | +| a call's output never connected | 37 | the result of a call kuna has no prototype for. `find` `pred_newer`: `difftime(a, b)` printed as `difftime()`, its `double` result in xmm0 read as an unassigned `v3` | +| argument dropped | 21 | tail-call and wrapper arguments. `rsyslogd` `multiSubmitFlush` (#1835 fixes it); `tar` `rpl_getopt_long`, whose callee takes a seventh argument on the stack, still prints `rpl_getopt_internal()` with #1835 | +| return value | 18 | `find` `optionl_stat`: an `int` returned as `unsigned long` over a tail call (#1896 fixes it) | +| call set, argument value, memory | 39 | among them `dexter.dll` `_GetOSVersion`, where i386 stack offsets after a cdecl `__memset` are off by the pushes (a return address is stored into `si.dwPageSize`; #1888 does not fix it), and `_AddCache`, whose `memcpy` source is an unassigned variable instead of `ptr`. The `O0` `hash_*` and `*_hasher` cases are not triaged yet | + +New kuna bugs that no open PR fixes, each with a repro: +- an unprototyped callee's arguments and `double` result: `find` `pred_newer`; +- a wrapper whose callee takes stack arguments: `tar` `rpl_getopt_long`; +- i386 stack depth after an in-image cdecl call: `dexter.dll` `_GetOSVersion`; +- a merged variable that is never assigned: `dexter.dll` `_AddCache`; +- a PLT stub's forwarded arguments: `libz.so` `crc32_z` at 0x3340. + +## 5. Closing the largest `UNKNOWN` causes + +The model now runs what made most of §3's `UNKNOWN(unsupported-op)`: +- **x87's 80-bit format** (`src/x87.rs`): conversions from integers and to and from + IEEE single and double (rounding to nearest, ties to even), sign operations, + comparisons, the NaN test and truncation are exact. Arithmetic on the format stays + unsupported. A `float` or `double` returned in `ST0` is rounded from the 80-bit value + before the compare. An integer wider than eight bytes converts to a float exactly + (kuna's IR widens an unsigned 64-bit integer to nine bytes first). +- **Cortex-M system registers**: the code runs privileged, `mrs` of the masks, base + priority and exception number reads 0 on both sides, and the writes change nothing + either side reads back. +- **kuna's memory builtins** (`memcpy`, `memset`, `memset16`/`32`/`64`, `memcmp`, which + `repstring` prints for x86's `rep` string instructions) run on the decompiled side, + spending the budget a byte at a time, as the loop they replace does. A `memcpy` + whose destination starts inside its source, ahead of it, is the overlap `rep movs` + defines and `memcpy` does not: declared as `DIVERGES(copy-overlap)`. + +Running more code showed two more defects in the model, now fixed: +- A store into read-only data or code (a random pointer into a firmware image at + address 0, or into a PIE's text) went through, and a later load of a literal pool + read the stored value. A store that changes such memory now traps; a run where it + traps is not compared, like a run that traps on both sides. +- `callee_writable` and the image lookups were linear scans (§3). + +| | before | after | +|---|---:|---:| +| sample set `AGREES` | 157 | 172 | +| sample set `DIFFERS` | 1 | 0 | +| `ssh-add` (`O0`) `AGREES` / `UNKNOWN` | 294 / 697 | 885 / 107 | +| `RTOSDemo` (`O2`) `AGREES` | 86 | 91 | +| test corpus `UNKNOWN` turned `AGREES` | | 32 | + +The sample set's one `DIFFERS`, `chThdSetPriority`, now agrees: its scheduler callees +read and write `basepri`, and with the system registers modelled they run. §4 put it +down to a context switch the model cannot run; that does not hold for this function, and +the other ChibiOS cases of §4 are not re-triaged yet. +`CMSIS_DAP.axf`'s CMSIS-RTOS calls now reach their `svc` and are +`DIVERGES(syscall-result)`. `RTOSDemo`'s new `DIFFERS`, `xQueueReceiveFromISR`, is a call +argument kuna does not pass, of §4's dropped-argument class. + +## 6. The rerun with the current harness + +Every function of the same 74 binaries again, after §5, with main merged up to #1932 (so +with the fixes of #1889–#1927), then every function that did not agree rechecked after the +last harness fix below. + +| | functions | `AGREES` | `DIFFERS` | `DIVERGES` | `UNKNOWN` | +|---|---:|---:|---:|---:|---:| +| first full run (§3–§4, partial) | 28,233 | 22,683 | 243 | — | 5,306 | +| before this section | 47,384 | 41,164 | 481 | 206 | 5,533 | +| after the first fixes below | 47,756 | 41,964 (88%) | 249 | 206 | 5,337 | +| now | 49,184 | 43,321 (88%) | 252 | 206 | 5,405 | + +`O2` has 160 `DIFFERS` and `O0` 92. The last line counts each function a binary defines; +the earlier lines counted a name that two functions of one binary share once (1,428 +functions). The recheck goes by name, so the 36 such functions in it keep the verdict of +the full run. + +**Harness defects this rerun showed, all fixed** (`triage.md` §2 lists them with the +rest): +- kuna-verify loaded a binary without the options `kuna decompile` turns on: the + Listing, which no-return propagation reads, and off x86-64 the discovery passes. So it + checked a different decompilation from the one the CLI prints, in which calls to + internal fatal wrappers (`ohshite`, `die`, `app_exit`) returned. +- A call followed only by padding and then another function, and a call kuna ends with a + `CALL_RETURN` override (`error (1, ...)`), ran on into the next function. +- An RTOS context switch returns into another thread on another stack; the callee is + now given the stub. A return to an enclosing call's return address on the same stack + (libgcc's soft-float routines) unwinds to that call instead. +- A call result kuna keeps in a joined register pair (`r1:r0`) was not read back. +- kuna's `varargsave` folds the stores of a variadic function's register-save prologue, + and the printed `va_list` setup stands for `va_start`. Once a `va_list` passed to a + callee was followed into the save area it points to, about 160 variadic functions + (`errc`, `ohshite`, `rl_message`, `parser_errmsg`) stopped agreeing: kuna's save area + was never filled. kuna's side now fills it as `va_start` does, from the stores the fold + records, and compares only the 176 bytes `va_start` defines. + +**What the 252 are:** the 249 of the line before, unchanged, and three new: `printServo` +(Cleanflight, both builds), whose `r1` differs at its 46th call in one run of 256, and +`USBD_Initialize` (Crazyflie `O0`), whose result depends on a call output kuna never +connects. None +of the 249 agrees after #1924 or #1927. + +| cause | functions | where | +|---|---:|---| +| kuna's C reads a variable nothing assigns (a call output or a register a call kills) | 55 | across projects; one mechanism each, not triaged one by one | +| a call drops arguments | 42 | #1916 (a stack argument), #1918 (an import without a prototype, and the PLT entries themselves); the rest not matched to an issue yet | +| the set or order of calls differs | 31 | not triaged | +| memory differs | 31 | includes 10 ChibiOS `rt_test_*` around scheduler calls, most likely the context-switch limit, not kuna | +| functions discovery found in data | 23 | Cortex-M firmware `sub_*` whose bytes are strings: `funcstart_patterns`/`aif` take them for code, and `decompile-all` prints them too | +| u-boot's aligned stack buffers | 16 | #1919, directly (`part_test_dos`, `fs_devread`, `print_partition_extended`) or through callees run for real; not each checked | +| a return value or an argument value | 25 | not triaged | +| `memcpy`'s arguments dropped | 10 | #1922: Betaflight's calls to its own `memcpy` keep one or two of three; `--option dwarf off` restores them in three of the five functions | +| `fdt_getprop()` with no arguments | 7 | #1917 | +| a call through a function pointer drops arguments | 6 | `tar` `tar_sparse_*` | +| i386 stack offsets after `memset`/`memcpy` | 4 | #1920 | +| a return widened in a tail-call cycle | 2 | #1921 | + +`transfer_entries` does not differ again: 64 concolic z3 queries (slice C5) over +eight seeds give `AGREES` or `UNKNOWN(budget)`. + +### The budget rule + +The numbers above were measured when one run past `--budget` made a function +`UNKNOWN(budget)`, which was 4,283 of the 5,405 `UNKNOWN`. Runs past the budget on both +sides are now counted apart, as trapped runs are; one past it on one side only still +makes the function `UNKNOWN(budget)`, since one side may loop where the other does not. +Measured on 286 of those functions (up to four per binary, names a binary defines once): + +| counting both-sided budget runs apart | functions | +|---|---:| +| `AGREES` | 135 (47%) | +| still `UNKNOWN(budget)` | 122 | +| another `UNKNOWN` it had hidden (trap, unsupported op, uninitialized local) | 24 | +| `DIVERGES` | 3 | +| `DIFFERS` | 2, not yet triaged (`dpkg-query` `pkg_array_init_from_names`, ChibiOS `rt_test_012_006_execute`) | + +On the test corpus 123 functions moved from `UNKNOWN(budget)` to `AGREES`, and three +to `DIFFERS`: `kuna-arrayextent`'s `ff_gcc` in its three passes, for an `n` past the +array, where the source writes out of bounds and the machine's frame layout and kuna's +differ. On `ls` (`O2`, `O0`) and `find`, 77 moved to `AGREES` and one to `DIFFERS` (`ls` +`O0` `mpsort_into_tmp`, not yet triaged). The full decbench run has not been repeated +under the new rule. + +Each such run costs two full budgets, so after four of them a function's later runs get +an eighth of the budget, and one that then runs past it on one side only is run again +with the whole budget before it counts as looping. On the test corpus that puts the +check at 194 CPU-seconds against 156 before the rule (`--jobs 4`, a loaded machine) and +4,102 functions agreeing against 3,931; without the shorter budget it took 323. + diff --git a/docs/features/diffverify/c4-results.md b/docs/features/diffverify/c4-results.md new file mode 100644 index 0000000000..e004c2b6f6 --- /dev/null +++ b/docs/features/diffverify/c4-results.md @@ -0,0 +1,404 @@ +# diffverify — slice C4 results (precision and recall) + +C4 is the corpus run and its precision and recall (proposal, Slices). This file records +both on the corpus kuna already has. Precision: every `DIFFERS` over `tests/datatests` +and `tests/stages` is triaged into a kuna bug, a bug its test pins on purpose, a harness +limit, or a declared divergence, and the harness defects that triage found were fixed on +the way. Recall: past P3/P4 fixes were put back one at a time in a local build, to see +which the check catches (§6). The decbench binaries are in `c4-decbench-results.md`. + +```sh +decompiler/target/release/kuna-verify corpus tests/datatests tests/stages --trace +``` + +`--trace` adds both sides' calls, in order, to every `DIFFERS`. An argument the callee's +prototype does not recover prints as `?`. + +## 1. The corpus + +4,030 decompiled functions, 256 runs each. C2 saw 3,979: it missed the 51 a script +decompiles with an abbreviated command (§5). + +| verdict | C2 | C4 | +|---|---:|---:| +| `AGREES(256)` | 2,482 | 3,246 | +| `DIFFERS` | 500 | 113 | +| `DIVERGES` | 3 | 24 | +| `UNKNOWN` | 994 | 647 | + +`UNKNOWN` by reason: 399 unsupported operations (SIMD and barrier user ops, memory +builtins, ISA-mode switches, float formats other than IEEE single and double), 226 +budget, 16 traps on both sides, and 6 undefined reads of the frame. + +Of the 113 `DIFFERS`: +- 28 are the ones §2 triages; +- 49 come from the two checks of §6a and are triaged in §6b; +- 15 come from float support and are triaged in §6c; +- 21 come from system calls and are triaged in §6d. + +None is an unexplained harness defect. + +Every function C1 found to agree still agrees. Of C2's 2,482, twelve no longer agree: +- `enum ptrenumlow` is `UNKNOWN(unsupported-op)`: its IR has an `INT_AND` whose output + is narrower than its inputs (§3). +- Four are `UNKNOWN(budget)`. In each, a loop waits for an in-image callee to change + memory. The callee is a `ret` placeholder that the machine now runs for real, where C2 + gave it the stub and let the stub write the memory. The machine side loops forever + because the program does. +- Two halt on an operation the machine cannot run: a Thumb `setISAMode` before a + branch, and a decompiled flow that ends in a halt. +- Two read an uninitialized local on both sides. In `kuna-msvcbyval` `sub_401000` the + argument is read from frame bytes outside the object the callee was given, which the + stub no longer writes (§5). +- Three, in `kuna-stacklifetimes-cfg`, give a frame object to a callee that uses a + float op the model cannot run, so the stub's effect is a guess: + `UNKNOWN(guessed-callee)`. + +The 24 `DIVERGES` match their predicates: `synthesized-call` (the MSVC string append, +outlined, AVR wrapper and `linuxsyscall` calls kuna makes up), `gowritebarrier`, +`switchrunon-cut-row`, `nan-quieting` (§6c), and `syscall-result`, `panic-check` and +`ptrauth-trap` (§6d). + +## 2. Every `DIFFERS` + +| class | test, function (pass) | count | what differs | +|---|---|---:|---| +| kuna bug | `gh8777-flagcompare-sborrow` `FUN_0` | 1 | `RuleSborrowGe` takes `0 <= V-K`, which is *not* N, for N. So it rewrites the loop's `V < K` continuation to `7 <= v1`, and the loop runs zero times where the binary runs seven. Assertion #2 pins the wrong output. | +| kuna bug | `kuna-repframecopy` `sub_4012c0` (`unsettled`) | 1 | The stack-pop solver guesses wrong for the call through a pointer to `guess`, which pops 4. kuna then reads a stack slot the binary never reads: machine `EAX = 0x8008`, kuna `0xffff`. The test header says the guess moves the block. | +| kuna bug | `kuna-stackviews` `obj_global_reuse` (pass 1, `stackviews off`, the default) | 1 | The IR drops the stores `mov [rsp],5`, `mov [rsp+4],7` and `mov [rsp],rdx` (`&datum`), although the function publishes RSP to the globals `object_pair` and `object_handle` and reads back through them. The C reads `object_pair->x` from a never-written local: machine `EAX = 0x43` (5 + 7 + 0x37), kuna `0x7ffffffe`. Pass 2 (`stackviews on`) keeps the stores and agrees. A frame address stored to a global has escaped, whatever the option. | +| kuna bug (prototype) | `kuna-libctypes` `next_byte` | 2 | The source returns `int` from `__uflow`. kuna claims `uint8` and zero-extends the 32-bit call result, but the x86-64 ABI leaves RAX's upper half undefined. | +| bug the test pins | `kuna-narrowext` `pi`, `pu`, `psc` (`narrowext off`) | 3 | The pass that reproduces #794. | +| bug the test pins | `kuna-indexedstoreguard` `cb_m8`, `-a64` `m8` | 2 | The known limitation the test documents. | +| bug the test pins | `overlapbranch` `overlap` (pass 2) | 1 | The overlapping-branch limitation the test documents. | +| bug the test pins | `ghangr-optimized-memcpy-6301a9` `memcpy_opt` (pass 1) | 1 | `jtsharepartial` and `unrolledguard` off: the indirect jump becomes a call. | +| bug the test pins | `ghdec-indexaliasguard` `transform` (pass 1, `indexaliasguard off`) | 1 | The pass deletes the stores the test pins (0x401344 to 0x40135d). kuna XORs into a local nothing wrote, where the binary XORs into the table. Pass 2, the fix, ends in `UNKNOWN(budget)`, so the fix itself is not checked. | +| source-level UB | `kuna-arrayextent` `d4_clang` | 3 | The source indexes past its array. The two sides read different neighbors. | +| harness limit | `kuna-nullable-relocations` `guard`, `same` | 8 | A relocation to an undefined weak symbol is not resolved to 0 in the image. | +| harness limit | `kuna-mipsgot-weak` `same` | 2 | The same: the direct reference to the undefined weak `optional` is not 0, while its GOT entry is. | +| harness limit | `injectoverride` `callind_inject` | 1 | kuna replaces the call with a call-fixup injection. The machine calls the real target. | +| harness limit | `kuna-calleeretpreserves` `f` | 1 | `int 0x29` (`__fastfail`) does not return. The machine treats it as returning. | +| harness limit | `kuna-calleescratchbody` `f` | 1 | The function reads the TEB through `gs`, which the initial state does not model. | + +Three `DIFFERS` that showed up mid-triage were not kuna's: `partialsplit` `loadalone`, +and `kuna-arrayextent` `q_clang` and `w_clang`. Each indexes past its array, into the +return address a call pushed (`loadalone`) or into the spill of `rbx` (`q_clang`, +`w_clang`). That is undefined in C, and the harness now reports it so (§4). + +## 3. kuna findings that are not `DIFFERS` + +- **IR size mismatch.** `enum ptrenumlow`, `enum ptrenumhigh` and `kuna-narrowload` + `t_bit` each have an `INT_AND` whose 1- or 4-byte output is narrower than its inputs + (`AL:1 = u:4 & #0x3000:4`). The interpreter refuses mixed sizes, so these are + `UNKNOWN(unsupported-op)`. The printed C is right in the three cases checked. The + IR still breaks the invariant that a p-code op's sizes match. +- **Address-tied locals.** In `kuna-msvcstrappend` `near_miss`, heritage puts no + INDIRECT guard on a STORE through `&local + i`. The local is address-tied, so the + printed C reads the variable and agrees. C2's interpreter read the stale SSA value + and called this `DIFFERS`. + +## 4. Harness defects found while triaging + +| defect | effect before the fix | +|---|---| +| Arguments read from the stack storage overlapping SP, not only the callee's prototype params | false argument differences | +| A machine `RETURN` always ended the function | `kuna-entryretdispatch` (a pushed-address `ret` that kuna reads as a call) differed | +| In-image tail calls (`BRANCH`, `CBRANCH`, `BRANCHIND` kuna made calls) got the stub | the kill value against the callee's real effect (`tailcallframe`, `memcpy_opt`) | +| A call value kept in a temporary read as 0 | 1-byte to 8-byte call results lost after a cast into a register: `gh510-phiopflags`, `kuna-arm-float-return`, `ghdec-realtypes-pointee`, `ghdec-undefname`, `kuna-libctypes` `fopen` | +| A return folded to a constant compared at `const:0` | `UNKNOWN` or a false `DIFFERS` (`kuna-bejoin-sparc`, `kuna-sparc-zeropair`, `kuna-gobool`); now compared at the register the model returns that type in | +| A `bool` parameter on the stack started as a random byte | 10 false `DIFFERS` in `kuna-stackobjects`: `!flag` is `flag ^ 1` | +| A callee run for real spent the caller's step budget | in-image callees ended their callers in `UNKNOWN(budget)`. Callees now share a pool of their own, and a callee that exhausts it gets the stub | +| Tracked registers (PowerPC TOC, MIPS `t9`) and the return address not seeded, and the MIPS ISA-mode bit of a computed target kept | false target and memory differences | +| Mixed-size ops evaluated by truncating | false `DIFFERS`; now `UNKNOWN(unsupported-op)` | +| A read of an uninitialized local on kuna's side alone counted as undefined behavior | a kuna read of the wrong slot hid as `UNKNOWN`. Only a run where both sides read the frame where C defines nothing is undefined now | +| A call's return address, and a callee's frame, stayed written below the stack pointer after the call returned | an out-of-bounds read there looked defined on the machine side only. Both sides now see uninitialized stack (`partialsplit` `loadalone`) | +| The prologue's spill of a callee-saved register counted as a defined local | reading past an array into it looked defined on the machine side only (`q_clang`, `w_clang`). A load of a spill is now a read of uninitialized stack unless it restores the same register, directly or through the temporary the instruction copies there | +| A stack-protector failure, and a machine write to the return address, compared as a result | `UNKNOWN(uninitialized-local)`: the stub let a call overwrite the frame | + +## 5. What a verdict claims + +A review of the C2 harness found four places where a verdict claimed more than the +runs showed. All four are fixed: +- **Traps.** A run that traps on both sides used to count as agreeing. Division by + zero is undefined in C, so the two sides' effects before the trap are not compared + either. Such a run now counts as not compared: `AGREES(n)` gives the runs that did + agree, with a note on how many trapped. A function whose every run traps is + `UNKNOWN(trap)`. +- **Declared divergences.** A return value that matched a declared divergence skipped + the memory comparison. The divergence now covers only the return value, so a store + that also differs is `DIFFERS`. +- **Call targets.** A target was compared only when both sides made an indirect call. + It is now also compared when one side resolved the call to a direct one, if both + targets are code in the image. An import slot or an unrelocated GOT entry is not + code, so these calls are not compared. +- **CLI.** `--runs 0` is a usage error. A corpus file that cannot be checked, a + worker crash included, makes the exit status 3. `DIFFERS` is 1. `UNKNOWN` is not a + failure. + +`tests/verdict_guards.rs` pins the first and last. The second and third change no +verdict in the corpus. + +A second review found seven more. All are fixed, and each fix keeps the corpus's +`DIFFERS` the same 29: +- **Frame objects a callee receives.** A store to a local whose address a call + receives was not compared, because stack bytes were never an observable. At each + call both sides now compare the object the pointer is into, with its extent taken + from kuna's local symbol for that address. kuna's side looks among the CALL op's + inputs, and the machine looks in the convention's argument registers. Only objects + both sides find are compared, so a stale pointer left in an unused register costs + nothing. + - A callee run for real counts only the bytes it reads. A callee kuna proved + read-only (#810's callee memory summaries) may then lose an unread initializer. + - Bytes a callee's own code left inside the object (a stack probe's pushes in a + buffer C never initialized) are not compared. + - The stub writes only that object, not a window past the pointer. A window + reached the stack canary and made `ptrtoarray` `passPtrToArray` call + `__stack_chk_fail`. + - An in-image callee the model cannot run (a float op) and that gets a frame + object makes later differences `UNKNOWN(guessed-callee)`: the stub's write is a + guess where kuna may know the callee only reads. + - Changing `int x = 1; sink(&x);` to store 2 on kuna's side, in a local build, now + gives `DIFFERS: memory before call 1 to sink: machine 0x01, kuna 0x02`. +- **Empty loops.** A block visit, and an instruction with no p-code, now spend the + step budget, so a loop of empty blocks ends in `UNKNOWN(budget)`. +- **Narrow returns.** The stub extends a callee's return value across its register + as `narrowext abi` documents. An RV64 `int` comes back sign-extended. +- **Preserved registers.** The stub kills what the call's own effect list says, + so what kuna proved a callee preserves (`calleepreserves`) stays. +- **Abbreviations.** `dec` and any other abbreviation of `decompile` is checked: + the console now reports the command a line resolved to. This adds 51 functions. +- **Pointer contracts.** A contract returning a pointer asks the model where a + pointer goes: A0 on ColdFire, not D0. +- **Failed loads.** A `decompile` after a `load` that failed is not checked: it + would check the function loaded before again. + +`tests/verdict_guards.rs` pins the trap, empty-loop, frame-object, failed-load, +abbreviation and CLI cases. + +A third review found seven more, all fixed: +- **Kept registers.** A stub that a callee falls back to now keeps the registers + `calleepreserves` proved it leaves alone, which the effect list does not carry. +- **Earlier escapes.** A frame object passed to any earlier call is compared at every + later call (`save(&x); x = 1; consume();`). +- **Direct targets.** These are compared too, after following thunks (a jump, an + `endbr64`, a PLT slot). Calls kuna bound past a PLT stub or replaced with an injection + are not compared, since the machine runs no dynamic linker and no call fixup. +- **Contracts.** `__int128` is 16 bytes, and an unknown word in a contract type is an + error rather than ignored. +- **Register return addresses.** A return address kept in a register (RISC-V `ra`, + ARM `lr`) is written by every call and is no longer read as a smashed frame. +- **Empty script lines** clear the console's resolved command. +- **Missing corpus paths** are a usage error. + +## 6. Recall + +Of the 56 P3/P4 fixes since June 2026, 39 have a stage fixture. The 27 whose fixture the +check could run were measured. Five were measured without a code change: a pass that sets +the fix's option off, or C1 and C2's fault injections. The other 22 were put back by hand +in a local build, never committed. A plain revert no longer applies, because the sources +moved into phase folders since, so each fault is a guard returning its pre-fix answer. +Each fixture's own assertions confirmed the old output was back. + +| outcome | fixes | +|---|---| +| caught, no contract | #801, #828 (`narrowext off`), #536 (`indexaliasguard off`), #893, #879 (1 of its 7 functions) | +| caught only with a C contract | #794, #855, #755, #797, #879 (all 7) | +| missed | #561, #554, #252, #564, #1500, #290, #1501, #542, #565, #559, #455, #875, #763 | +| nothing to catch: the IR computes the same value | #1537 (a temporary named), #251 (`SUBnn` printed), #249 (a masked target the CPU masks too) | +| a crash fix: shows as a file error | #227 | +| bug did not come back | #238 | + +Of the 22 that put a semantic bug back, 5 are caught without a contract (23%) and 9 with +one (41%). The misses fall into a few gaps, most of them in how the model treats calls: +- **A callee run for real shares its effect.** kuna's side replays what the machine's + run of the callee did, so a dropped or wrong argument changes nothing on kuna's side. + Only arguments kuna claims are compared, and a variadic one has no storage to compare + at. Missed: #564, #1500, #455, #875. +- **Storage kuna never initialized holds the machine's value.** A register kuna reads + without a parameter for it, or a call output it never connects, holds what the + machine has there, so C reading an unassigned `v1` or `_r3` computes the right value. + At most a `PROTOTYPE_SUSPECT` note appears. Missed: #290, #565, #1500, #1501. +- **A return claimed too narrow, or void, compares nothing without a contract.** With + one, #855, #755, #797 and #879 are caught. #763 (swapped halves) was not run with + one. #559 claims a return too wide, and its extra half really holds what the claim + says. +- **Frame objects at an in-image callee that reads nothing.** In #561 and #554 the wrong + bytes reach only a buffer passed to `sink`, which is a bare `ret` in these fixtures. + The program never reads them. A probe whose `sink` reads the buffer sees the + difference, as `UNKNOWN(uninitialized-local)` there, since the buffer's source is + never initialized either. +- **Writes into read-only memory.** #252 stores a literal's own bytes back into it, + which is not a value difference, and nothing checks for writes to read-only memory. +- **C that is false but runs the same.** #542 (`-sub_1100()` equals the RAX the real + `__chkstk` leaves) and #1501 (a jump made a call into in-image code) execute + identically. Only the printed-C tier can see them. + +### 6a. Two checks for the call gaps + +Two checks were added for the first two gaps, and the misses re-measured on them: +- **A callee's inputs.** + - Recording: a callee run for real has the argument-register bytes it reads before + writing them recorded. Bytes it only spills (a `push`, a home-slot store, a varargs + prologue) are not recorded. + - Placement: each of kuna's CALL inputs is placed at the callee's parameter storage, + else at its own register for an entry-register input, else at the next integer + argument register. Register pairs are split into their pieces. + - Confirmation: where kuna passes other bytes or none, the machine is rerun with + kuna's bytes in the callee's registers. Only a changed result is `DIFFERS`: the + function's own, or the callee's return value or memory writes. + - A callee with a declared prototype makes it a `PROTOTYPE_SUSPECT` instead, since kuna + follows the declaration. +- **What kuna's C never assigns.** kuna's side is rerun with other values in: + - argument or scratch registers it reads at entry with no parameter for them; + - output registers of a call it never connects; + - other registers a call kills, read after it. + + A changed kuna result is `DIFFERS`. For entry registers and non-output killed + registers, the machine is rerun with the same values first: when its own result + changes too, the binary reads that storage itself (a `push ecx` reserving a slot, a + hand-written routine reading `r10`), and the dependence is not kuna's. + +Re-measured with both checks: +- #565 and #1500 are now caught without a contract, through a call output kuna never + connects (`_r3` after the call). +- The other eleven misses stand: + - **Path:** the bug is on a path random inputs never take (#564: `end == cap`). That + needs C5's concolic inputs. + - **A smaller claim:** kuna claims less than the binary does. A void caller ignores the + callee result (#455). A return is narrowed or dropped (#559, #763). An argument + is dropped that the fixture's callee ignores (#875). + - **The binary reads the register too:** #290's `this` arrives in ECX, which the + binary reads at entry, so the missing parameter is a prototype claim. + - **No reader:** #561 and #554 reach only a callee that reads nothing. + - **No check:** #252 needs a read-only store check. A first try flagged AVR's + memory-mapped registers and XML fixtures' read-only chunks, and was dropped. + - **Printed C only:** #542 and #1501 are false only in the printed C. + +| | without a contract | with one | +|---|---:|---:| +| before the two checks | 5 of 22 | 9 of 22 | +| with them | 7 of 22 | 11 of 22 | + +### 6b. What the two checks found in the corpus + +The two checks add 49 `DIFFERS` over the corpus, and remove one (`kuna-calleescratchbody` +`f`, whose stub no longer overwrites what kuna proved the callee keeps). Triage found +no false positives in the 49. The false-positive classes the first version had were +removed before this count: pair arguments, Swift's `self`, declared prototypes, and +registers the binary itself reads. + +The largest group is one kuna defect: **a caller that passes its own entry argument +registers straight through to a callee loses the arguments.** kuna prints `v1 = add64();` +where the source is `add64(a, b)`. The same pattern shows up on six targets: +- x86-64: `narrowret-x86` `returns_word`, `libcnames` `ordered`; +- ARM; +- PPC: `bejoin-callers`, `bejoin-residue`, `relocobj-ppc-mips`; +- MIPS: `mipsunaligned`, `mipsgot-local`, `bejoin-mipspic`; +- eBPF: `ebpf-elf-map-reloc`; +- Rust and Swift: `rustabi`, `swiftcall`. + +Several of these tests pin the dropped spelling as expected output. + +Other real defects: +- **A register the callee leaves alone is treated as killed.** `loadguardreads` + `gather` passes `reg(&s0, 0)` with the 0 set once before an earlier call; `regpiece` + `sh_openpipe` does the same with EDX. +- **An assigned argument is dropped:** `pointerwalk-memo` `f` prints `ext()` for + `ext(buf[0])`. +- **A call output is never connected**, read as an unassigned `v1`: the off or bug passes + of `calleeretpreserves`, `callretpair`, `callretpairhalf` and + `declaring-double-score-return`. + +The rest are passes a test pins on purpose: +- the off passes of `calleearitycut`, `calleearityscratch`, `calleereadarg`, `bodyreads` + and `msvcstrappend`; +- `narrowext`'s RISC-V bug pass, which a guard had hidden as `UNKNOWN` (§5). + +`injectoverride` `inject_collapse` is a harness limit: the machine does not run kuna's +call-fixup injection. + +### 6c. Floats + +Float ops now run on IEEE single and double through the same `OpBehavior` table, +for both sides. Other float encodings (x87's 80 bits, half precision) stay +`UNKNOWN(unsupported-op)`. Two parts are exact rather than going through the host's +floats: +- a sign change (`FLOAT_NEG`, `FLOAT_ABS`); +- a NaN's format conversion. + +These keep a NaN's payload, as IEEE defines them and as a binary that clears a sign bit +with an integer AND does. A float argument a callee reads is placed at the float +register kuna's call input sits in. + +This judges 242 more functions (2,932 to 3,174 agree). Of the 15 new `DIFFERS`: +- **NaN compares on ARM and AArch64 (kuna defects):** `armfloat-preset` `scale_err`, + `floatret` `logish`, `prefersplit` `ccw_mixed`. + - The machine's `vcmp`/`fcmp` sets V on a NaN, so `ble` and `cset gt` take the + unordered arm. + - kuna prints `a != b && !(a < b)`, which is true for a NaN. `kuna_floatnegation` + folds only x86's unordered guard; with `nanignore none` all three agree. +- **Missing float arguments (kuna defects):** + - `arm-float-return`'s on pass prints `(float8)half()`, although `half` reads d0; + - `earlyrestart` `main` prints `set_gi_bits()` for `set_gi_bits(-7.5f)`. +- **Off passes and pinned outputs:** the off passes of `ghdec-calloverlap` and + `arm-float-return`, and `declaring-double-score-return`'s two clobber controls. +- **A harness limit:** `declaring-double-score-return` `score`, `wide_exact_caller` + and `refined_score`. + - kuna proves the MSVC cookie checker leaves XMM0's low lane alone, but the stub + still kills it. The proof is not in the call's effect list. + - Using kuna's per-call return-preserve proofs in the stub removed these five and + added about fifteen elsewhere, so it was dropped. + +`kuna-floatprecision` `widen_roundtrip` is a declared divergence, `nan-quieting`: +`nanignore compare` treats a float conversion round trip as the identity, so a +signalling NaN comes back unquieted. A float return that differs only in the quiet bit +of a NaN matches it. + +### 6d. System calls and traps + +A system call (`syscall`, `svc`, `ecall`, `sc`, `swi`) is now an event on both sides +instead of an unsupported op. Each side records the address, the user op and its +inputs, and the two lists are compared in order: +- **Inputs.** The SLEIGH op takes no registers. kuna's `syscallregs` and `x64syscall` + attach the number register and then some of the argument registers. Each one kuna + attaches is matched, in ABI order, with what the machine's register file holds there. +- **Result.** The machine writes the kernel's result register (and MIPS `a3`, PowerPC + `cr0`), as Linux and the BSDs do. The value is one both sides share, and kuna's call + output gets it too. +- **Traps.** A trap (`brk`, `udf`) in the function's own code ends the run as a + no-return. One reached inside a callee the machine runs for real is not an event. + +`syscallregs auto`, the default, writes nothing on an image that names no operating +system, and every XML fixture is one. There the machine writes nothing either. The run +is then repeated with the kernel's write, and if that changes the return, a store or a +call, the function is `DIVERGES(syscall-result)`. + +Two more options cut code the machine runs, knowingly: +- `gobounds` and `securitycheck` remove the branch to a Go or Rust check's panic + helper: `DIVERGES(panic-check)` when the machine calls one kuna does not. +- `ptrauthtrap` cuts an arm64e pointer-authentication check. The machine does not + authenticate (SLEIGH hides `autibsp`), so the return address it tests is whatever + was loaded: `DIVERGES(ptrauth-trap)` when it stops in the `brk #0xc47x`. + +This judges 72 more functions (3,174 to 3,246 agree; unsupported ops 509 to 399): +- **21 new `DIFFERS`, all off passes the tests pin.** These are `syscallregs off` in + the ARM, AArch64, RISC-V, MIPS, MIPS `a3` and PowerPC `cr0` tests, `x64syscall off` + in `kuna-x64syscall`, and both passes of `kuna-linuxsyscall-x64-compat`. In each, + the register read after the call still holds the number or an argument. +- **12 new `DIVERGES`:** + - 6 `syscall-result`: the `auto` passes and `kuna-ownreturn` `sys2nr`, which returns + `a0 + 1` where a kernel returns its result + 1; + - 2 `panic-check`: `kuna-gobounds` and `oxidizer-securitycheck` `pick` with the + option on; + - 2 `ptrauth-trap`: `x30check` and `_tail_auth` with `ptrauthtrap on`; + - 2 `synthesized-call`: `linuxsyscall`'s calls, which the machine used to stop short + of at the `int 0x80`. + +The `on` and `abi` passes of every system-call test agree. + +## 7. Cost + +Check time 152.9 s, wall time 22.9 s on 14 worker processes, over 4,030 functions. Peak RSS is 216 MB for the +heaviest single test. Check time grew from C2's 50.3 s because functions that used to +stop early now run: callees run for real, calls are kept in loops up to the 256-call +limit, and fewer runs halt on harness errors. One function, +`kuna-pointerwalk-budget-mips` `ldso_d2f0`, takes 9.2 s and ends as `UNKNOWN`. diff --git a/docs/features/diffverify/mutation.md b/docs/features/diffverify/mutation.md new file mode 100644 index 0000000000..f897c93bb0 --- /dev/null +++ b/docs/features/diffverify/mutation.md @@ -0,0 +1,108 @@ +# diffverify — mutation testing of the check + +Tests that pass say the check does what its tests ask. They do not say how much of what +can go wrong in a decompile it would see. `kuna-verify mutate` measures that: it plants +one semantic fault at a time in kuna's side of a function that agrees, and counts how +many the check reports as `DIFFERS`. + +```sh +kuna-verify mutate tests/datatests tests/stages --jobs 10 # the test corpus +kuna-verify mutate --all --jobs 10 # a binary +kuna-verify mutate ... --per-function 6 --json # some functions +``` + +## 1. What a mutant is + +A mutant changes one op of the compiled decompiled side (`src/graph/program.rs`) or the facts +kuna's side reads about one call. The machine side keeps its own copy of the call facts, +so a mutant never changes how the reference run is made. The one exception is `noreturn`, +below. The machine's runs are therefore made once per function, by the check of the +unmutated function, and reused by each of its mutants; a `noreturn` mutant reuses only a +run that never reached its call. Up to `--per-function` mutants (6) are taken per function, +one operator after another, so each kind is tried where the function has one. + +| operator | the fault | +|---|---| +| `opcode` | an arithmetic, logic, comparison or extension op becomes a near one: `+`/`-`, `&`/`|`, signed/unsigned compare, `<=`/`<`, `==`/`!=`, zero/sign extension, logical/arithmetic shift, signed/unsigned division | +| `constant` | a constant input's lowest bit flips | +| `swap` | the inputs of an op that does not commute trade places | +| `branch` | a conditional branch goes the other way | +| `drop-store` | a store does nothing | +| `call-target` | a direct call goes to another function: the call site's target, which is what the printed C names a direct callee by | +| `drop-arg` | a call loses its last argument. A recovered prototype loses the parameter too, as when kuna recovers one too few; a declared one (DWARF, libc types, a datatest's `parse line`) keeps it, as in #1922 | +| `noreturn` | a call that returns is said not to. This is kuna's claim about the call, which both sides read, so it is the one mutant the machine side sees too: it has to find the claim false itself (README §2) | + +A mutant whose op no run reaches cannot be seen by any check, so recall counts only the +mutants a run reached. A mutant that ends `UNKNOWN` (a budget overrun, a trap) is counted +apart, neither caught nor missed. Only functions that agree unmutated are mutated. + +## 2. What it found in the check + +The first runs showed three places where a real fault would have passed. All are fixed: + +- **A direct call's target was compared only when both addresses were code in the + image.** A datatest's callee usually lies outside the bytes it maps, and a PIE's PLT + stubs, followed through `BIND_NOW` GOT slots that the file leaves zero, all led to the + same address. A call to the wrong function, the wrong import included, passed. Targets + are now compared whenever each is code or outside the image, and two PLT stubs that only + meet at a non-code address are different calls. A target in mapped data is still left + alone: kuna binds 32-bit PowerPC PIC imports to their GOT slot. +- **A call that passed fewer arguments than the prototype kuna gives its callee was not + compared.** The argument comparison zipped the two sides' argument lists and stopped at + the shorter. It now reports `kuna passes N arguments, and the prototype it gives the + callee takes M`. +- **The first `drop-arg` was not a fair test.** It shortened the call and left the + prototype, so the check above caught every one by construction. A recovered prototype + now shrinks with the call. + +None of these changes the verdict of any function of the corpus, `ls` (`O2`, `O0`), `find` +or the decbench sample set. + +## 3. Recall + +With the machine side's call facts kept apart from kuna's: + +| | corpus | `ls` (`O2`) | `find` (`O2`) | +|---|---:|---:|---:| +| mutants reached | 15,822 | 1,155 | 1,914 | +| caught | 12,040 (76.1%) | 858 (74.3%) | 1,429 (74.7%) | +| `branch` | 87.2% | 86.7% | 82.0% | +| `call-target` | 83.7% | 84.2% | 84.5% | +| `constant` | 79.3% | 59.8% | 73.9% | +| `drop-arg` | 47.0% | 82.7% | 81.7% | +| `drop-store` | 89.4% | 66.2% | 80.6% | +| `noreturn` | 61.4% | 5.0% | 4.4% | +| `opcode` | 79.0% | 79.4% | 75.6% | +| `swap` | 78.2% | 89.3% | 79.6% | + +Concolic inputs (slice C5, a separate change) at 16 z3 queries per function raised +`constant` on `ls` (measured before `noreturn` was added) from 57.8% to 70.4%. + +`noreturn` on `ls` and `find` is mostly a claim about an imported function. It has no +name the lists know and no body in the image to run, so the run ends on kuna's word and +is not counted. That is 36 of 60 mutants on `ls` and 63 of 114 on `find`, reported as +`UNKNOWN(noreturn-unverified)` rather than passing as agreement. + +What is left, by kind: + +- **Values random runs rarely hit.** `x <= 9` against `x < 9`, a constant `0x3b9aca07` + against `0x3b9aca06`: the two differ on one input. Concolic inputs (slice C5) raise + `constant` on `ls` from 57.8% to 70.4%. +- **Arguments a stub never reads.** A callee outside the image gets the stub, which does + not depend on its integer arguments. An argument kuna drops along with a recovered + parameter is seen only where the callee runs for real and reads it (`the callee reads + RDI; kuna's call passes nothing there`). In the corpus most callees lie outside the + bytes a datatest maps, so `drop-arg` with a recovered prototype is caught in 23%; on `ls` + and `find`, whose callees are in the image or declared, in 86–91%. +- **Calls the check leaves alone by design.** A call bound past a PLT stub or replaced by + an injection (`resolved`), and a target in mapped data, are not compared. +- **Mutants that change nothing.** Flipping a constant that only feeds a mask's unused + bits, swapping the inputs of a comparison both sides of which are equal on every run, + or a store to a stack slot nothing reads again: no check can see these. + +## 4. What it does not measure + +Mutants change the final IR, and the check runs that IR. A fault in the C printer (a cast, +an operator's precedence, a type's spelling) is not in the IR, so `AGREES` cannot rule it +out and this recall does not cover it. That is Tier P's axis (`proposal.md`), and it is +measured separately when that tier exists. diff --git a/docs/features/diffverify/proposal.md b/docs/features/diffverify/proposal.md index 35bf71fa2d..1dcfe9a575 100644 --- a/docs/features/diffverify/proposal.md +++ b/docs/features/diffverify/proposal.md @@ -1,6 +1,8 @@ # [PROPOSAL] diffverify — differential semantic checking with z3, QEMU and kuna -Status: **proposal**. Design only; nothing is implemented before approval. +Status: **proposal**. Slices C1, C2, C3 and C4 (on the corpus kuna has) are implemented in +`decompiler/crates/kuna-verify`. Their measurements and the design changes they forced +are in `c1-results.md`, `c2-results.md` and `c4-results.md`. Evidence, coverage estimates and the hard part: `analysis.md` in this folder. ## What this makes possible @@ -29,8 +31,9 @@ candidate change that makes a function newly `DIFFERS` is rejected before review 1. **No home-grown solver or machine emulator.** z3 proves and finds inputs (C5), QEMU (through Unicorn where `qemu-user` is unavailable) checks the lift, and kuna's SLEIGH - emulator runs the machine code. kuna owns the encoding, the small symbolic executor - that builds it (C5), and an interpreter for its own `Funcdata` (Tier C). + translator and op semantics run the machine code. kuna owns the encoding, the small + symbolic executor that builds it (C5), and an interpreter for its own `Funcdata` + (Tier C). 2. **Dev-only.** A new workspace crate, `kuna-verify`, next to `kuna-harness`. The release binary does not link it and its output is byte-identical. Emitted C does not change, so there is no option row or DIV entry. @@ -55,17 +58,23 @@ candidate change that makes a function newly `DIFFERS` is rejected before review x86-64 `RDX:RAX` trim is one entry: option `returnpair`, x86-64, the `RDX` half of a 16-byte return, machine `RDX = 0`. A difference that matches an entry is `DIVERGES(entry)`; a different difference under the same option is still `DIFFERS`. + C1 found a second entry, `switchrunon-cut-row` (`c1-results.md` §3). Each entry counts its matches, so a sudden rise is visible. The list is part of the first slice, not an afterthought. ## Tier C — run both sides (first) **Machine side.** -- Run the function's own machine code from its entry with `EmulatePcodeCache` (SLEIGH - p-code over the load image) until it returns. +- Run the function's own machine code from its entry until it returns. Each instruction + is lifted by the program's SLEIGH translator, and its ops are evaluated with the + `OpBehavior` table `EmulatePcodeCache` uses (`c1-results.md` §6 says why not the engine + itself). - Inputs: a full random machine state, with seeded edge values (0, -1, sign boundaries, shift counts ≥ width). Both sides start from this same raw state: the same register, stack and memory values. +- Argument registers keep the extension the ABI documents for the claimed parameters + (`narrowext abi`): a caller cannot pass a 32-bit `int` in a 64-bit RISC-V register + without sign-extending it, so no input does. - Pointer arguments point into a mapped scratch region with the same contents **and the same addresses** on both sides. A pointer that differs between the sides makes every address-dependent value differ, which is a harness false positive, not a bug. All of @@ -106,22 +115,34 @@ function's type, because the binary alone cannot settle it: - Stores outside the function's own frame. - The ordered call sequence, each call with its callee and arguments. -**Calls.** -- The machine side runs a stub at each call. The stub records the call, returns a - recorded random value in the return registers, clobbers caller-saved registers, and - writes recorded random bytes to the memory the call can reach. That set is: - - what its pointer arguments point to; - - memory that escaped before the call; - - every writable global: the image's writable sections, since a callee with no - arguments can still change `counter`. - - Without the memory writes, a rule that reuses a value loaded before the call as if the +**Calls.** As built in C2 (`c2-results.md` §1): +- Both sides run the same stub at each call. It records the call with kuna's arguments + and the memory the callee could read, kills the registers the model lists as + killed-by-call and every output register with values fixed by the run and the call's + index, and pops `extrapop`. +- It may write the image's writable data and 4 KiB past every pointer passed to a call + so far, lazily, with bytes fixed by the call's index. That is no more than kuna itself + treats as changed by a call, so a value kuna keeps across one stays equal unless kuna + is wrong to keep it. Writing all memory outside the stack is too much: it rewrites the + stack canary, which kuna rightly keeps. + Since C4, a pointer into the frame reaches only the local object kuna's symbol gives + it. That object is compared at the call, as the bytes outside the stack are + (`c4-results.md` §5). +- Without the memory writes, a rule that reuses a value loaded before the call as if the call could not change it would agree with the machine and be missed. -- The decompiled side replays the same return values and memory writes call by call. - INDIRECT is a copy unless the recorded effect wrote that storage. -- A different call sequence is itself `DIFFERS`. -- A call whose reachable memory the harness cannot bound (an escaped pointer of unknown - extent, writable memory outside the image) is `UNKNOWN(call-effect)`. +- INDIRECT is moved after the op it guards. Its output is the call's value for a killed + register, what memory holds for a stack or memory location, and its input otherwise. +- Calls are compared in order on the call instruction's address, and a computed target + when both sides compute it. A different call sequence is itself `DIFFERS`. An argument + is `DIFFERS` against a declared callee prototype and `PROTOTYPE_SUSPECT` against a + recovered one. +- Where kuna has no call at an instruction that calls code in the image (inlined, + injected or dropped), the machine runs the callee for real, so a deliberate removal + agrees and a wrong one shows in what the callee does. +- Since C4 (`c4-results.md` §4), a call or tail call to code in the image runs for real + on the machine side, and kuna's side replays the effect it recorded. Such callees share + a step pool of their own, so they never spend the caller's budget. A callee the model + cannot run, or one that exhausts the pool, gets the stub. **Needs no phase hooks.** The machine side reads the binary and the decompiled side reads the finished `Funcdata`. Loops are fine: execution is bounded by a step budget, and a run @@ -254,7 +275,7 @@ localize than inside a whole-function proof. ## Tier L — the lift against the machine (QEMU/Unicorn) **Compares** one instruction's effect on random state: -- kuna side: SLEIGH p-code in `EmulatePcodeCache`; +- kuna side: the SLEIGH p-code and op semantics Tier C's machine side runs; - machine side: Unicorn, which is QEMU's TCG as a library and runs on macOS, unlike `qemu-user`. @@ -275,6 +296,11 @@ This tier makes Tier C's machine side trustworthy. ## Tier P — printed C against the binary (later, separate proposal) +Until this tier exists, `AGREES` says the final IR computes what the machine code +computes, not that the printed C does: a printer fault (a cast, an operator's precedence, +a type's spelling) is not in the IR. Mutation recall (`mutation.md`) measures IR faults +only, and the printed C is a separate axis. + 1. Compile one function's printed C with a generated header for kuna's `undefinedN`/`intN` types. 2. Link it into a harness next to the original. @@ -293,14 +319,15 @@ library rather than stubbed. | slice | scope | done when | |---|---|---| -| C1 | Tier C on register-only leaf functions: no calls and no memory access at all, except loads from read-only image data; same raw state on both sides; physical-ABI and typed-contract return checks; `PROTOTYPE_SUSPECT`; `UNKNOWN(unsupported-op)`; declared-divergence predicates | reverting #794 gives `DIFFERS` against its fixture's source contract; verdict table over `tests/datatests` + `tests/stages`, with per-function and total time | -| C2 | memory and call effects: stack, pointer-argument and global memory; call stubs that write reachable memory, globals included; `UNKNOWN(call-effect)` | reverting #801 gives `DIFFERS`; a rule that keeps a pre-call load across a call that writes it gives `DIFFERS` | -| C3 | rule localization over the C1/C2 verdicts | candidate culprits include `subvar_zext` on reverted #794; cost per finding | -| C4 | corpus run (decbench binaries); precision and recall | precision: triage of every `DIFFERS` into bug / declared divergence / harness bug. Recall: of the ~44 visible P3/P4 fixes that have a fixture, how many give `DIFFERS` when reverted. Published table with both | -| C5 | concolic inputs: expressions over the inputs on both sides, branch conditions negated through z3, capped paths and queries | a fixture whose difference appears only on one 32-bit value gives `DIFFERS`, where 256 random runs give `AGREES`; new paths reached per function on the corpus | +| C1 | Tier C on register-only leaf functions: no calls and no memory access at all, except loads from read-only image data; same raw state on both sides; physical-ABI and typed-contract return checks; `PROTOTYPE_SUSPECT`; `UNKNOWN(unsupported-op)`; declared-divergence predicates | reverting #794 gives `DIFFERS` against its fixture's source contract; verdict table over `tests/datatests` + `tests/stages`, with per-function and total time. **Done** (`c1-results.md`) | +| C2 | memory and call effects: stack, pointer-argument and global memory; call stubs that write reachable memory, globals included | reverting #801 gives `DIFFERS`; a rule that keeps a pre-call load across a call that writes it gives `DIFFERS`. **Done** (`c2-results.md`; both by a fault injected in a local build) | +| C3 | rule localization over the C1/C2 verdicts | candidate culprits include `subvar_zext` on reverted #794; cost per finding. **Done** (by holding back one rule at a time rather than reverting; 15 of 113 corpus `DIFFERS` named down to a rule application, the rest are action-level) | +| C4 | corpus run (decbench binaries); precision and recall | precision: triage of every `DIFFERS` into bug / declared divergence / harness bug. Recall: of the ~44 visible P3/P4 fixes that have a fixture, how many give `DIFFERS` when reverted. Published table with both. **Precision and recall done on `tests/datatests` + `tests/stages`** (`c4-results.md`: 7 of 22 restored bugs caught without a contract, 11 with one). **decbench done** (`c4-decbench-results.md`: 28,233 functions of 66 binaries, 80% `AGREES`; 243 `DIFFERS` triaged by class, five new kuna bugs) | +| C5 | concolic inputs: expressions over the inputs on both sides, branch conditions negated through z3, capped paths and queries | a fixture whose difference appears only on one 32-bit value gives `DIFFERS`, where 256 random runs give `AGREES`; new paths reached per function on the corpus **Done** (`c5-results.md`: `--concolic N`; a value-specific fault caught that 256 random runs miss; on decbench, concolic runs in 49 of 250 sample functions and 105 of 405 `ls` functions) | | S1 | Tier S for loop-free `AGREES` functions that pass the static entry condition, under the budget | `EQUIVALENT` and `UNKNOWN(budget)` counts on the same corpus; every `sat` replays or is classified | | S2 | bounded loops; budget baseline and budget-regression flag | `EQUIVALENT(≤k)` counts; a deliberately bloating rule change is flagged by budget alone | -| L1 | Tier L for x86-64, AArch64, ARM | per-arch mismatch report with skip list | +| L1 | Tier L for x86-64, AArch64, ARM | per-arch mismatch report with skip list. **Done** (8,805 instruction forms against Unicorn; x86-64 differs only in the `AF` the spec does not compute; three SLEIGH spec errors on AArch64 and Thumb) | +| M | mutation testing of the check: one semantic fault planted at a time in kuna's side of a function that agrees | recall per fault kind, the faults reached counted apart. **Done** (`mutation.md`: 76% of reached mutants caught on the corpus, 74–75% on `ls` and `find`; the gaps it showed in the check are fixed, and claims the check cannot verify are reported as such) | | P | separate proposal | — | C5 comes after C2 and before S1: most of what C1 skips needs C2's memory and call model @@ -310,9 +337,27 @@ first, and S1 reuses C5's expressions. gate only once the `DIFFERS` set is empty or every entry is a declared divergence, with a baseline file like `docs/baseline.json`. +That job, `make verify-corpus` and a `continue-on-error` step of the parity-gates job +in `.github/workflows/tests.yml`, comes in a change of its own. Each function's verdict +class over `tests/datatests` + `tests/stages` is pinned in `docs/baseline-verify.json`: +- `AGREES`, `DIFFERS`, `DIVERGES(id)` or `UNKNOWN(reason)`; +- no run count and no address, so the file changes only when a verdict does. + +A function that now differs, or a file that can no longer be checked, is an error +annotation, and `make verify-corpus` exits 1. Every other change is a notice. The step +uploads the verdict table and its own recording of the baseline. Re-record: +`make verify-corpus VERIFY_ARGS='--save-baseline docs/baseline-verify.json'`. + +Each file is checked in a worker process of its own. A process that checked +`kuna-ppc32picimports-abi` or `-reversed-save` before `kuna-ppc32picimports` decompiles +`check` differently there: as `__stack_chk_fail();` instead of `sub_1800(); return 7;`. +So verdicts that depended on how files were spread over workers now do not. + ## Cost -Nothing has been measured yet; C1 measures it. What the design expects, and why: +C1 measured Tier C (`c1-results.md` §5): 3.6 s of checking for 3,979 functions over both +corpora, and 20.6 s of wall time including every decompile, on 14 worker processes. +What the design expects for the rest, and why: - **Tier C** costs one decompile, which a check needs anyway, plus n concrete runs of one function (256 by default), each capped by a step budget. There is no solver and diff --git a/docs/features/diffverify/record.json b/docs/features/diffverify/record.json index 1df2f20b74..ff6ce9ad08 100644 --- a/docs/features/diffverify/record.json +++ b/docs/features/diffverify/record.json @@ -52,5 +52,159 @@ "S2", "L1", "P" + ], + "status": "C1, C2 and C3 implemented; C4 precision and recall on tests/datatests + tests/stages and on decbench", + "measurements": { + "C1": { + "corpus": "tests/datatests + tests/stages, 256 runs per function", + "files": 782, + "functions": 3979, + "verdicts": { + "AGREES": 696, + "DIFFERS": 4, + "DIVERGES": 3, + "UNKNOWN": 331, + "SKIPPED": 2945 + }, + "differs_triage": { + "known_bug": 3, + "harness": 1 + }, + "check_seconds": 3.6, + "wall_seconds": 20.6, + "peak_rss_mb": 454, + "results": "docs/features/diffverify/c1-results.md", + "check_seconds_first_build": 49.8, + "wall_seconds_one_worker": 66, + "workers": 14 + }, + "C2": { + "corpus": "tests/datatests + tests/stages, 256 runs per function", + "functions": 3979, + "verdicts": { + "AGREES": 2482, + "DIFFERS": 500, + "DIVERGES": 3, + "UNKNOWN": 994, + "SKIPPED": 0 + }, + "c1_agrees_regressed": 0, + "differs_triaged": false, + "check_seconds": 50.3, + "wall_seconds": 11.0, + "workers": 14, + "peak_rss_mb": 332, + "done_when": "both checks by a fault injected in a local build", + "results": "docs/features/diffverify/c2-results.md" + }, + "C4": { + "corpus": "tests/datatests + tests/stages, 256 runs per function", + "functions": 4030, + "verdicts": { + "AGREES": 3174, + "DIFFERS": 92, + "DIVERGES": 12, + "UNKNOWN": 752 + }, + "c1_agrees_regressed": 0, + "c2_agrees_regressed": 12, + "differs_triage": { + "section2": { + "kuna_bug": 5, + "pinned_by_test": 8, + "source_ub": 3, + "harness_limit": 12 + }, + "call_checks_added": 49, + "call_checks_false_positives": 0 + }, + "check_seconds": 152.9, + "wall_seconds": 22.9, + "workers": 14, + "peak_rss_mb": 216, + "recall": { + "fixes_since_2026_06": 56, + "with_stage_fixture": 39, + "measured": 27, + "semantic_bugs_reproduced": 22, + "caught_no_contract": 7, + "caught_with_contract": 11, + "missed": 11, + "ir_equivalent": 3, + "crash_file_error": 1, + "not_reproduced": 1, + "method": "fault restored by hand in a local build per fix (sources moved since, so reverts do not apply); fixture assertions confirm the pre-fix output", + "before_call_checks": { + "caught_no_contract": 5, + "caught_with_contract": 9 + } + }, + "results": "docs/features/diffverify/c4-results.md", + "kuna_bugs": [ + "gh8777-flagcompare-sborrow FUN_0 (RuleSborrowGe polarity)", + "kuna-repframecopy sub_4012c0 (stack-pop guess)", + "kuna-stackviews obj_global_reuse (default stackviews off drops stores to an escaped frame)", + "kuna-libctypes next_byte x2 (recovered return wider than int)" + ], + "float_support": { + "newly_judged": 242, + "new_differs": 15, + "kuna_defects": 5, + "harness_limit_functions": 3 + }, + "system_calls": { + "newly_judged": 72, + "new_differs": 21, + "new_differs_pinned_off_passes": 21, + "new_diverges": 12 + } + } + }, + "c3": { + "results": "docs/features/diffverify/c3-results.md", + "command": "kuna-verify localize [--pass N]", + "corpus_differs": 113, + "named_a_rule": 15, + "action_level": 98, + "wall_seconds_12_jobs": 199 + }, + "c4_decbench": { + "results": "docs/features/diffverify/c4-decbench-results.md", + "dataset": "noelo-lab/decbench-dataset", + "sample_set": {"functions": 250, "agrees": 157, "unknown": 92, "differs": 1}, + "all_functions": {"binaries": 66, "functions": 28233, "agrees": 22683, "differs": 243, "unknown": 5306}, + "harness_fixes": ["noreturn-halt", "bool-return", "segment-bases", "thumb-interworking", "barriers", "exclusive-monitor", "x87-extended", "cortex-m-system-registers", "memory-builtins", "readonly-store-trap"], + "sample_set_after_second_round": {"functions": 250, "agrees": 172, "unknown": 78, "differs": 0} + }, + "c5": { + "results": "docs/features/diffverify/c5-results.md", + "option": "kuna-verify check ... --concolic QUERIES", + "sample_set": {"functions_with_concolic_runs": 49, "concolic_runs": 80, "new_differs": 0, "new_divergences": 2}, + "ls_O2": {"functions_with_concolic_runs": 105, "concolic_runs": 237, "wall_seconds_before": 3.3, "wall_seconds_after": 13.4} + }, + "tier_l": { + "results": "docs/features/diffverify/tier-l-results.md", + "command": "python3 scripts/diffverify/tier_l.py x86-64|aarch64|thumb BINARY", + "forms": {"x86-64": 6686, "thumb": 1330, "aarch64": 789}, + "differ": {"x86-64": 0, "thumb": 16, "aarch64": 8}, + "spec_errors": ["aarch64 ldrsh/ldrsb W sign-extends into X", "thumb stmia skips writeback with base in list", "thumb-2 ands/bics/mvns leave C"] + }, + "ci": { + "baseline": "docs/baseline-verify.json", + "make": "make verify-corpus", + "workflow_step": "parity gates: diffverify corpus vs docs/baseline-verify.json (non-gating)", + "regression": "a function that newly differs, or a file that can no longer be checked" + }, + "declared_divergences": [ + "copy-overlap", + "divide-by-zero", + "returnpair-rdx-zero", + "switchrunon-cut-row", + "synthesized-call", + "gowritebarrier", + "nan-quieting", + "syscall-result", + "panic-check", + "ptrauth-trap" ] } diff --git a/docs/features/diffverify/triage.md b/docs/features/diffverify/triage.md new file mode 100644 index 0000000000..821fe164d2 --- /dev/null +++ b/docs/features/diffverify/triage.md @@ -0,0 +1,162 @@ +# diffverify — triaging a disagreement: spec, emulator, evaluator or harness + +A difference that diffverify reports is a fact about two executions. It is not yet a +fact about which of them is wrong. This page is the procedure for deciding, and the rule +that goes with it: + +> **Do not call a difference a SLEIGH spec error until the reference it was compared +> against, kuna-verify's own evaluator and the harness have each been ruled out.** + +Every Tier L or Tier C difference has at least five possible causes, and this work has +already met each of them. + +## 1. The five suspects + +| suspect | what it is | how it shows | +|---|---|---| +| **The SLEIGH spec** | the vendored `.sinc`/`.slaspec` turns the instruction into the wrong p-code | kuna's lift computes something the architecture manual defines otherwise | +| **The reference emulator** | Unicorn (QEMU's TCG as a library) in Tier L, or any other emulator used as the oracle | the oracle computes something the manual or the hardware does not | +| **kuna-verify's evaluator** | `value::eval`, `x87.rs` and the op semantics both sides of Tier C share | one p-code op evaluates differently from what the op means (NaN, division by zero, shifts past the width, `TRUNC` out of range) | +| **The harness** | the Tier L driver (`scripts/diffverify/tier_l.py`, `kuna-verify step`) or the Tier C model (state, stubs, calls run for real, returns) | inputs the two sides did not get alike, or a run the model follows differently from a CPU | +| **The architecture itself** | the manual leaves the result undefined, UNPREDICTABLE or implementation-defined | two correct implementations disagree, and neither is wrong | + +The spec is one row of five. A report that names it has to say why the other four are +not the cause. + +## 2. What this work has met + +Each suspect has produced a difference that, at first sight, looked like another one. + +**Spec errors (confirmed).** Three, all in Tier L: +- AArch64 `ldrsh`/`ldrsb` into a `W` register sign-extend into all 64 bits of `X`. The + Arm ARM's pseudocode sign-extends to the register size, 32 bits for a `W` register, + and a write to a `W` register zeroes the top half of `X`. Confirmed by running the + instruction on an AArch64 CPU. Already reported upstream as + NationalSecurityAgency/ghidra#6471. +- Thumb `stmia Rn!` with `Rn` in the register list skips its writeback: the spec reuses + LDM's `Rn_exclaim_WB` rule. Checked against the ARMv7-M pseudocode and Unicorn; no + Cortex-M hardware was run. NationalSecurityAgency/ghidra#10273. +- Thumb-2 `ands`, `bics`, `mvns` with a shifted or expanded operand leave `C` unchanged + where the pseudocode sets it to the shifter's carry-out. Checked against the ARMv7-M + pseudocode and Unicorn; no hardware. NationalSecurityAgency/ghidra#10274. + +**Under-specified p-code (not errors in the same sense).** VFP `vcvt` out of range, `vfma` +and `vfnma`, and the default NaN of `vsqrt` (Tier L): the spec's p-code +cannot say what the architecture defines (`TRUNC` leaves out-of-range undefined; p-code +has no fused multiply-add; NaN payloads are not modelled). These are reported as gaps, +not as errors. + +**A spec gap kept apart.** x86's `AF`: Ghidra's x86 spec does not compute the auxiliary +carry for most arithmetic. No decompiled C reads it, so Tier L counts it in its own +column instead of as a difference. + +**The evaluator.** A `DIVSS` with a NaN operand came back as the host's default NaN +instead of the operand, quieted, as SSE and ARM return it. The spec was right; the fix +was in `value.rs`. + +**The Tier L driver.** Before any of these were fixed, each looked like a difference: +- a random 8-byte register used as a pointer held a non-canonical address, which the + x86-64 machine faults on (`--canonical` keeps them below 2^47); +- Unicorn's instruction prefetch read code bytes kuna never read (fetch accesses are no + longer counted as reads); +- an access to unmapped memory for a write was counted as a read (only `READ_UNMAPPED` + counts); +- a Thumb instruction inside an IT block runs under ITSTATE, which a single instruction + run alone does not carry (left out and counted); +- flags the Intel SDM leaves undefined after an instruction differed (left out by + mnemonic). + +**The Tier C model.** On real binaries (`c4-decbench-results.md`), harness defects +produced `DIFFERS` that were not kuna's: +- an RTOS context switch: the callee loads another thread's stack pointer and returns + into that thread; +- libgcc's soft-float routines (`__aeabi_ddiv`), which reach a shared tail with `bl` + and return straight to their caller's caller: the return was taken for a context + switch and the call got the stub; +- a call `kuna decompile` knows does not return only through the Listing (`listing on`, + which the CLI turns on and kuna-verify did not), or through an `error (1, ...)` + `CALL_RETURN` override, or because the compiler left only padding after it; +- a call whose result kuna keeps in a joined register pair (`r1:r0`), which the replay + did not read back. + +And the architecture: ARM and AArch64 integer division by zero gives 0, where C leaves +`/` undefined; Tier C declares it (`DIVERGES(divide-by-zero)`) instead of reporting it. + +## 3. The checklist + +Work through it in order, and keep the answers: the report quotes them. + +1. **Reduce it.** One instruction and one state for Tier L (`kuna-verify step` prints + the state as JSON); for Tier C, the smallest function and input (`--seed`, `--trace`), + and a C source compiled with `clang --target=...` when one reproduces it. + +2. **Rule out the harness.** + - Did both sides get every input? Tier L leaves out instructions that read a register + outside the named set; check that the instruction does not read one anyway + (a flag, a system register, FPSCR/MXCSR, the x87 control word). + - Is execution state part of the input? IT blocks, Thumb or ARM mode, `FPSCR.DN`, + `FPSCR.FZ`, rounding mode, privilege. + - Is the memory the same? Mapped ranges, read-only ranges, what Unicorn prefetches. + - For Tier C: does the machine side follow the code as a CPU would? Look at the trace + for calls run for real, stubs, returns that do not land after their call, a stack + pointer that jumps, a call the machine makes that kuna's C does not (or the reverse) + next to a no-return callee. + - Is the kuna output checked the one `kuna decompile` prints? Run `kuna decompile` on + the same function and read the C. If they differ, the options differ. + +3. **Rule out the evaluator.** Print the p-code (`kuna raw-pcode BINARY ADDR`) and + evaluate the ops by hand from the state. Pay attention to ops whose meaning has edge + cases: `FLOAT_*` with NaN or infinity operands, `TRUNC`, `INT_DIV`/`INT_SDIV`/`INT_REM` + by zero, shifts by the width or more, `INT_SCARRY`/`INT_SBORROW`, `PIECE`/`SUBPIECE` + on non-byte boundaries. If the hand result differs from kuna-verify's, the evaluator is + wrong. + +4. **Rule out the reference emulator.** + - Record its version (Tier L uses Unicorn 2.1.2) and look for known issues with the + instruction in its tracker and in QEMU's. + - Run a second reference where one is available: QEMU user mode + (`qemu-aarch64`, `qemu-arm`) with a small static test program, or another emulator. + Two independent references agreeing is evidence; one is not. + - Remember that Unicorn is QEMU's TCG from an older QEMU, and that TCG implements what + the architecture defines, not always what a given CPU does with what it leaves + undefined. + +5. **Read the manual.** The pseudocode, not the prose: the Intel SDM's operation + section, the Arm ARM (DDI 0487) for A64 and A32/T32 on ARMv8, the ARMv7-M ARM + (DDI 0403) for Cortex-M, the ARMv7-A/R ARM (DDI 0406). If the result is UNDEFINED, + UNPREDICTABLE, CONSTRAINED UNPREDICTABLE or implementation-defined, stop: it is the + architecture's row of §1, and the report says so. + +6. **Run it on hardware** whenever two references disagree, the manual's reading is not + unambiguous, or the finding is going upstream. A few lines of assembly that set the + state, run the instruction and print the result are enough. Say which CPU. Where no + hardware was run (the Thumb findings above), the report says that too. + +7. **Check upstream.** Compare the vendored spec with Ghidra at `GHIDRA_REV` and at its + current head (`docs/history.md`), and search Ghidra's issues and pull requests. The + AArch64 finding was already NationalSecurityAgency/ghidra#6471. + +8. **Only then name the cause,** with one of these labels: + +| label | means | needs | +|---|---|---| +| `spec error` | the vendored spec computes what the manual defines otherwise | 5, and 6 or two references from 4 agreeing | +| `spec gap` | p-code cannot express what the architecture defines (fused ops, NaN payloads, out-of-range conversions) | 5 | +| `architecture-undefined` | the manual does not define the result | 5 | +| `emulator` | the reference disagrees with the manual or the hardware | 5, and 6 or a second reference | +| `evaluator` | kuna-verify evaluates a p-code op wrongly | 3 | +| `harness` | the driver or the model gave the sides different inputs or ran the code differently | 2 | +| `kuna bug` (Tier C) | the decompiled C computes something the machine code does not | 2 and 3, and the C read by hand | + +## 4. Reporting + +A report of a disagreement, in an issue, a PR or a results file, states: +- the instruction or function, the binary and its source (dataset path, sha256); +- the state or input that shows it, and both results; +- the label from §3, and which steps of the checklist were done: the manual section + read, the references run (with versions), the hardware run (with the CPU), or that + none was; +- for a `spec error`, the line of the `.sinc` that produces the wrong p-code. + +A finding without that chain is reported as a difference, not as an error of any one +party. From adc86b9e844f7c7155f42b81f30f92cfe403a6f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 07:45:06 +0900 Subject: [PATCH 3/7] [AUTOMATED] Add kuna-verify localize: name the rule application after which a function differs For a function kuna-verify finds DIFFERS, `localize` holds one rule back at a time through the rule cap and bisects how many of its applications are allowed, so that with k - 1 the function agrees over every run and with k it differs. It reports those applications by rule and address, under the same contract and options as `check`. Slice C3 of the diffverify proposal. Co-Authored-By: Claude Opus 5.5 --- .../crates/kuna-verify/src/bin/kuna-verify.rs | 35 ++- decompiler/crates/kuna-verify/src/lib.rs | 2 +- .../crates/kuna-verify/src/tools/localize.rs | 231 ++++++++++++++++++ .../crates/kuna-verify/src/tools/mod.rs | 3 +- .../kuna-verify/tests/stage_verdicts.rs | 14 ++ .../crates/kuna-verify/tests/zext_pair.rs | 16 ++ docs/features/diffverify/README.md | 22 +- docs/features/diffverify/c3-results.md | 100 ++++++++ docs/features/diffverify/proposal.md | 4 +- 9 files changed, 418 insertions(+), 9 deletions(-) create mode 100644 decompiler/crates/kuna-verify/src/tools/localize.rs create mode 100644 docs/features/diffverify/c3-results.md diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs index e8437c406f..105d0a1039 100644 --- a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -3,6 +3,7 @@ //! ```text //! kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify corpus ... [--jobs N] [--file-seconds S] +//! kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] //! common: [--runs N] [--seed S] [--budget OPS] [--json] [--sleighpath DIR] //! ``` @@ -27,13 +28,14 @@ use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, Stdio}; use std::time::Instant; -use kuna_verify::{check_binary_each, check_datatest, session, Options, Report, Row, Verdict}; +use kuna_verify::{check_binary_each, check_datatest, localize, session, Options, Report, Row, Verdict}; use serde_json::{json, Value}; const USAGE: &str = "usage: kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... kuna-verify corpus ... [--jobs N] [--file-seconds S] + kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] options: --runs N (256) --seed S --budget OPS (200000) --call-reruns N (4) --json --trace --sleighpath DIR"; @@ -52,6 +54,7 @@ struct Args { /// a worker process, which is what a time limit can stop. timed: bool, per_function: usize, + pass: Option, /// Flags a worker process gets again. forward: Vec, } @@ -70,6 +73,7 @@ fn parse(argv: &[String]) -> Result { file_seconds: 1200, timed: false, per_function: 6, + pass: None, forward: Vec::new(), }; let mut it = argv.iter(); @@ -121,6 +125,10 @@ fn parse(argv: &[String]) -> Result { a.timed = true; } "--per-function" => a.per_function = num(it.next(), "--per-function")?.max(1) as usize, + "--pass" => { + let p = num(it.next(), "--pass")?; + a.pass = Some(usize::try_from(p).ok().filter(|&p| p > 0).ok_or("--pass counts from 1")?); + } "--json" => a.json = true, "--all" => a.all = true, "--trace" => { @@ -639,6 +647,30 @@ fn run_corpus(a: &Args) -> Result { Ok(exit_code(&rows, errors.len())) } +/// Name the first rule application after which a decompile differs. +fn run_localize(a: &Args) -> Result { + let [target, function] = a.positional.as_slice() else { + return Err(USAGE.to_string()); + }; + let roots = spec_roots(a.sleighpath.as_deref()); + let source = match &a.contract { + Some(f) => Some((std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"))?, f.clone())), + None => None, + }; + let src = if target.ends_with(".xml") { + localize::Source::Datatest(target) + } else { + let contract = source.as_ref().map(|(s, n)| (s.as_str(), n.as_str())); + localize::Source::Binary { path: target, functions: vec![function.clone()], options: &a.options, contract } + }; + let found = localize::localize(&src, &roots, function, a.pass, &a.opts)?; + print!("{}", found.render()); + Ok(match found.finding { + localize::Finding::NotDiffering(_) => ExitCode::SUCCESS, + _ => ExitCode::from(1), + }) +} + /// `corpus`: the file count and the wall time of the whole run; a file count /// of 0 is a `check` run over workers, which has a wall time but no files. fn print_summary(a: &Args, slowest: &[(f64, String)], rows: &[Row], corpus: Option<(usize, f64)>) { @@ -691,6 +723,7 @@ fn main() -> ExitCode { "corpus" => run_corpus(&a), "shard" => run_shard(&a), "chunk" => run_chunk_worker(&a), + "localize" => run_localize(&a), "mutate" => run_mutate(&a), _ => Err(USAGE.to_string()), }); diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs index baa9c70c58..295a6f2d11 100644 --- a/decompiler/crates/kuna-verify/src/lib.rs +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -25,7 +25,7 @@ pub use abi::{calls, contract, divergence}; pub use compare::check; pub use graph::program; pub use semantics::{storage, value, x87}; -pub use tools::mutate; +pub use tools::{localize, mutate}; use std::time::{Duration, Instant}; diff --git a/decompiler/crates/kuna-verify/src/tools/localize.rs b/decompiler/crates/kuna-verify/src/tools/localize.rs new file mode 100644 index 0000000000..0ca0cca0d3 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/tools/localize.rs @@ -0,0 +1,231 @@ +//! diffverify C3: the first rule application after which a function differs. +//! +//! The decompile that differs is rerun once per rule that applied in it, with +//! that rule alone taken out (`kuna_rulecap`); every other rule and every +//! action runs, so each rerun is a complete decompile. A rule without which the +//! function agrees is a culprit, and a binary search over how many times it +//! may apply finds `k` where `k - 1` applications agree and `k` differ: the +//! `k`-th, named by the op address it rewrote. Both ends are measured, so a +//! verdict that flips more than once still yields a pair that brackets a flip. +//! When no single rule's removal helps, the cause is an action, or rules that +//! only go wrong together. + +use crate::check::check_function; +use crate::report::{Report, Verdict}; +use crate::session::{self, Cap}; +use kuna_decomp::kuna_rulecap::{Mode, Record}; +use crate::Options; + +/// Where a script comes from: a datatest, or an object file and options. +pub enum Source<'a> { + Datatest(&'a str), + /// `contract` is a C source and its name (`--contract`), as `check` takes it. + Binary { path: &'a str, functions: Vec, options: &'a [(String, String)], contract: Option<(&'a str, &'a str)> }, +} + +pub enum Finding { + /// The full decompile does not differ. + NotDiffering(Report), + /// It differs, and taking out any one rule that applied leaves it + /// differing (or not checkable): the cause is an action, or rules together. + NoRule { applied: Vec<(String, u64)>, inconclusive: Vec, report: Report }, + /// Each rule whose removal makes it agree, and where it goes wrong. + Rules { applied: usize, culprits: Vec, inconclusive: Vec, report: Report }, +} + +/// Application `k` of `total` of `rule`, at `addr`: with `k - 1` allowed the +/// function agrees over every run, with `k` it differs. Found by bisection, +/// which assumes a later application does not undo a difference, so `k` is a +/// candidate, not a proven first cause. +pub struct Culprit { + pub rule: String, + pub k: u64, + pub total: u64, + pub addr: Option, + /// Where that application falls among all the decompile's applications. + pub step: usize, +} + +pub struct Localized { + pub function: String, + /// Which decompile of the script, from 0. + pub decompile: usize, + pub finding: Finding, +} + +/// Runs past the full decompile's failing one that a probe checks; a culprit's +/// agreeing side is confirmed over every run. +const QUICK_RUNS: u32 = 32; + +/// Run the script up to its `decompile`-th decompile under `mode`, and check it. +/// `None` for the report when the capped decompile itself fails. +fn probe(src: &Source, roots: &[String], decompile: usize, mode: Mode, opts: &Options) -> Result<(Option, Record), String> { + let mut cap = Cap { decompile, mode, result: None }; + let mut seen = 0usize; + let mut report = None; + let (commands, conf, _env) = match src { + Source::Datatest(path) => { + let (prog, commands, env) = session::load_datatest(path, roots)?; + (commands, Some(prog), Some(env)) + } + Source::Binary { path, functions, options, .. } => (session::binary_script(path, functions, options), None, None), + }; + let source = match src { + Source::Binary { contract, .. } => *contract, + Source::Datatest(_) => None, + }; + let mut failure = None; + session::run(commands, conf, roots, true, Some(&mut cap), |prog, fd| { + if seen == decompile { + let contract = match source.map(|(src, name)| crate::contract::from_source(src, fd.get_name(), name, crate::abi::c_sizes(prog))) { + Some(Err(e)) => { + failure = Some(e); + None + } + Some(Ok(c)) => Some(c), + None => None, + }; + report = Some(check_function(prog, fd, contract.as_ref(), opts)); + } + seen += 1; + })?; + if let Some(e) = failure { + return Err(e); + } + Ok((report, cap.result.unwrap_or_default())) +} + +fn differs(r: &Report) -> bool { + matches!(r.verdict, Verdict::Differs { .. }) +} + +/// Localize the `pass`-th decompile (from 1) of `function`, or by default the +/// first of its decompiles that differs. +pub fn localize( + src: &Source, + roots: &[String], + function: &str, + pass: Option, + opts: &Options, +) -> Result { + let all = match src { + Source::Datatest(path) => { + let r = crate::check_datatest(path, roots, opts); + if let Some(e) = r.error.filter(|_| r.reports.is_empty()) { + return Err(e); + } + r.reports + } + Source::Binary { path, functions, options, contract } => crate::check_binary(path, functions, options, roots, *contract, opts)?, + }; + let mine: Vec = all.iter().enumerate().filter(|(_, r)| r.function == function).map(|(i, _)| i).collect(); + if mine.is_empty() { + return Err(format!("no decompile of {function}")); + } + let decompile = match pass { + Some(p) => *mine.get(p.wrapping_sub(1)).ok_or_else(|| format!("{function} is decompiled {} time(s)", mine.len()))?, + None => mine.iter().copied().find(|&i| differs(&all[i])).unwrap_or(mine[0]), + }; + let done = |finding| Ok(Localized { function: function.to_string(), decompile, finding }); + let (full, record) = probe(src, roots, decompile, Mode::Observe, opts)?; + let full = full.ok_or_else(|| format!("decompile {} of the script fails when counted", decompile + 1))?; + if !differs(&full) { + return done(Finding::NotDiffering(full)); + } + let full_run = match full.verdict { + Verdict::Differs { run, .. } => run, + _ => 0, + }; + let quick = Options { runs: opts.runs.min(full_run.saturating_add(QUICK_RUNS)), ..*opts }; + let mut culprits = Vec::new(); + let mut inconclusive = Vec::new(); + for (rule, &total) in &record.counts { + let limit = |allow| Mode::Limit { rule: rule.clone(), allow }; + let Some(without) = probe(src, roots, decompile, limit(0), &quick)?.0 else { + inconclusive.push(format!("{rule}: the decompile fails")); + continue; + }; + if differs(&without) { + if opts.trace { + let first = without.lines.iter().find(|l| !l.starts_with("input")).cloned().unwrap_or_default(); + inconclusive.push(format!("{rule}: DIFFERS {first}")); + } + continue; + } + if !matches!(without.verdict, Verdict::Agrees(_)) { + inconclusive.push(format!("{rule}: {}", without.verdict.label())); + continue; + } + let (mut lo, mut hi) = (0u64, total); + let mut addr = None; + while hi - lo > 1 { + let mid = lo + (hi - lo) / 2; + let (r, rec) = probe(src, roots, decompile, limit(mid), &quick)?; + if r.as_ref().is_some_and(differs) { + (hi, addr) = (mid, rec.last); + } else { + lo = mid; + } + } + if addr.is_none() { + addr = probe(src, roots, decompile, limit(hi), &quick)?.1.last; + } + let agrees = probe(src, roots, decompile, limit(lo), opts)?.0; + if !agrees.as_ref().is_some_and(|r| matches!(r.verdict, Verdict::Agrees(_))) { + let label = agrees.map_or_else(|| "the decompile fails".to_string(), |r| r.verdict.label()); + inconclusive.push(format!("{rule}: {label} with {lo} applied, over all runs")); + continue; + } + let step = record.sequence.iter().enumerate().filter(|(_, r)| *r == rule).nth(hi as usize - 1).map_or(0, |(i, _)| i + 1); + culprits.push(Culprit { rule: rule.clone(), k: hi, total, addr, step }); + } + culprits.sort_by_key(|c| c.step); + let applied = record.counts.len(); + if culprits.is_empty() { + let applied = record.counts.into_iter().collect(); + return done(Finding::NoRule { applied, inconclusive, report: full }); + } + done(Finding::Rules { applied, culprits, inconclusive, report: full }) +} + +impl Localized { + pub fn render(&self) -> String { + let head = format!("{} (decompile {})", self.function, self.decompile + 1); + let indent = |r: &Report| r.render().lines().skip(1).map(|l| format!(" {l}\n")).collect::(); + match &self.finding { + Finding::NotDiffering(r) => format!("{head} does not differ: {}\n", r.verdict.label()), + Finding::NoRule { applied, inconclusive, report } => { + let mut s = format!( + "{head} differs, and still differs without any one of the {} rules that applied: \ + the cause is an action, or rules together\n{}", + applied.len(), + indent(report) + ); + let list: Vec = applied.iter().map(|(r, n)| format!("{r}x{n}")).collect(); + s.push_str(&format!(" applied {}\n", list.join(" "))); + for i in inconclusive { + s.push_str(&format!(" without {i}\n")); + } + s + } + Finding::Rules { applied, culprits, inconclusive, report } => { + let mut s = format!( + "{head} differs; of the {applied} rules that applied, it agrees without these, in the order their last needed application ran (candidates found by bisection):\n" + ); + for (i, c) in culprits.iter().enumerate() { + let at = c.addr.map_or_else(|| "?".to_string(), |a| format!("{a:#x}")); + let latest = if i + 1 == culprits.len() { " <- latest" } else { "" }; + s.push_str(&format!( + " step {:>5} {} application {} of {} at {at} (agrees with {}, differs with {}){latest}\n", + c.step, c.rule, c.k, c.total, c.k - 1, c.k + )); + } + for i in inconclusive { + s.push_str(&format!(" without {i}\n")); + } + s.push_str(&indent(report)); + s + } + } + } +} diff --git a/decompiler/crates/kuna-verify/src/tools/mod.rs b/decompiler/crates/kuna-verify/src/tools/mod.rs index 3b60cb58cb..29c8f1427d 100644 --- a/decompiler/crates/kuna-verify/src/tools/mod.rs +++ b/decompiler/crates/kuna-verify/src/tools/mod.rs @@ -1,3 +1,4 @@ -//! Tools built on the check: mutation testing. +//! Tools built on the check: rule localization and mutation testing. +pub mod localize; pub mod mutate; diff --git a/decompiler/crates/kuna-verify/tests/stage_verdicts.rs b/decompiler/crates/kuna-verify/tests/stage_verdicts.rs index 919caa69b7..0eb19b60f0 100644 --- a/decompiler/crates/kuna-verify/tests/stage_verdicts.rs +++ b/decompiler/crates/kuna-verify/tests/stage_verdicts.rs @@ -212,3 +212,17 @@ fn an_indirect_jump_out_of_the_image_is_not_a_return() { let v = verdicts("kuna-gottailcall"); assert!(of(&v, &["notfn"]).iter().all(|l| l.contains("indirect jump") && l.contains("out of the image")), "{v:?}"); } + +/// C3 names the rule application after which `csc` differs with `narrowext` +/// off: the `propagatecopy` at 0x10036 that carries the unextended byte on. +#[test] +fn localize_names_the_copy_rule() { + use kuna_verify::localize::{localize, Finding, Source}; + let specs = repo().join("specs").to_string_lossy().into_owned(); + let path = repo().join("tests/stages/kuna-narrowext.xml").to_string_lossy().into_owned(); + let found = localize(&Source::Datatest(&path), &[specs], "csc", None, &Options::default()).unwrap(); + let text = found.render(); + let Finding::Rules { culprits, .. } = found.finding else { panic!("{text}") }; + let latest = culprits.last().unwrap(); + assert_eq!((latest.rule.as_str(), latest.addr), ("propagatecopy", Some(0x10036)), "{text}"); +} diff --git a/decompiler/crates/kuna-verify/tests/zext_pair.rs b/decompiler/crates/kuna-verify/tests/zext_pair.rs index f96cf11f6d..32423ca77c 100644 --- a/decompiler/crates/kuna-verify/tests/zext_pair.rs +++ b/decompiler/crates/kuna-verify/tests/zext_pair.rs @@ -128,3 +128,19 @@ fn calls_past_the_rerun_budget_are_not_agreement() { assert!(n < 64, "{}", r.render()); assert!(r.lines.iter().any(|l| l.contains("the machine was not rerun for the rest")), "{}", r.render()); } + +/// `localize` checks under the same contract as `check`: without it the +/// narrowed `ins16` does not differ, so there is nothing to localize. +#[test] +fn localize_uses_the_contract() { + use kuna_verify::localize::{localize, Finding, Source}; + let path = arm_object(); + let path = path.to_string_lossy(); + let options = vec![("returnpair".to_string(), "single".to_string())]; + let opts = Options { runs: 64, ..Options::default() }; + let src = |contract| Source::Binary { path: &path, functions: vec!["ins16".to_string()], options: &options, contract }; + let without = localize(&src(None), &specs(), "ins16", None, &opts).unwrap(); + assert!(matches!(without.finding, Finding::NotDiffering(_)), "{}", without.render()); + let with = localize(&src(Some((SOURCE, "zext_pair.c"))), &specs(), "ins16", None, &opts).unwrap(); + assert!(!matches!(with.finding, Finding::NotDiffering(_)), "{}", with.render()); +} diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md index e1ac4caa84..8a0b693136 100644 --- a/docs/features/diffverify/README.md +++ b/docs/features/diffverify/README.md @@ -141,6 +141,7 @@ error, and 0 otherwise. ```sh kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... kuna-verify corpus ... [--jobs N] [--file-seconds S] +kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] [--file-seconds S] common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] ``` @@ -158,6 +159,15 @@ common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4) is killed and its file reported as an error. With `--jobs 1` every file runs in one process, so each datatest puts back the load-option environment its `option` commands wrote; the next file loads as it would in a process of its own. +- **`localize`** names candidate rule applications after which a function starts to + differ, by holding rules back one at a time (`c3-results.md`), under the same + `--contract` as `check`. For each rule it bisects the number of applications allowed: + with `k - 1` the function agrees over every run, with `k` it differs. Bisection assumes + that once an application makes the function differ, later ones do not undo it; a rewrite + that a later one cancels can hide an earlier application, so `k` is a candidate to look + at, not a proof that it is the first or the only cause. Holding a rule back also + changes which rules apply after it, so a culprit may be one side of an interaction + rather than the direct cause. - **`mutate`** plants faults in kuna's side and reports how many the check catches (`mutation.md`). A file or function that fails to load, or a worker that fails to finish, gives exit status 3. @@ -219,7 +229,7 @@ The crate is grouped by folder; the old module paths (`crate::check`, `crate::ca | `graph/` | `mod.rs`, `program.rs` | kuna's side: compiling a `Funcdata` for repeated runs, and running it | | `abi/` | `mod.rs`, `calls.rs`, `contract.rs`, `divergence.rs` | calling conventions, per-call facts both sides share, C contracts, declared divergences | | `compare/` | `check.rs`, `observe.rs`, `setup.rs` | the runs and the verdict; comparing calls, memory and system calls; each run's starting state | -| `tools/` | `mutate.rs` | mutation testing | +| `tools/` | `localize.rs`, `mutate.rs` | rule localization, mutation testing | | `report/` | `mod.rs` | output | A later tier gets a folder of its own (`symbolic/` for Tier S, `printer/` for Tier P). @@ -257,7 +267,9 @@ It is not a replacement for review. What it does not cover: quality are outside what running the IR can see. **Feedback an agent can act on.** A `DIFFERS` names an input, the call or byte that -differs and what each side did. That is a place to start debugging, not only a verdict, which is what an agent fixing its own change needs. +differs and what each side did; `localize` then names candidate rule applications after +which the function starts to differ (`c3-results.md`). That is a place to start debugging, not +only a verdict, which is what an agent fixing its own change needs. **What is not claimed.** `AGREES` means the runs made agreed, not that the two are equivalent on every input. The check covers semantic correctness of the decompile only: @@ -271,7 +283,7 @@ the same model and the same reasoning budget in every arm: |---|---| | A | an agent writes the change and an agent reviews it | | B | A, plus the existing tests (`make test`, `make test-stages`, `make rust-test`) | -| C | B, plus `kuna-verify`: a corpus baseline and the changed functions | +| C | B, plus `kuna-verify`: a corpus baseline, the changed functions, `localize` on each `DIFFERS` | Measured per arm: regressions that reach main, defects found before merge, fixes that succeed, tokens spent, and fixes a maintainer has to add after merge. The tasks can be @@ -284,7 +296,8 @@ run yet. 2. **Rule out the harness** before naming a kuna bug (`triage.md`). The model has been wrong before, about RTOS context switches, libgcc's multi-level returns, no-return calls and joined return registers. `triage.md` lists them. -3. **Reduce it** to a few lines of C where you can (`clang --target=...`). Check that +3. **Name the rule** with `localize` when a rule rather than an action is responsible. +4. **Reduce it** to a few lines of C where you can (`clang --target=...`). Check that `kuna decompile` prints the same wrong C, then file it or fix it. ## 9. Not done yet @@ -386,6 +399,7 @@ run yet. | `analysis.md` | the analysis behind the proposal | | `c1-results.md` | slice C1: register-only leaf functions | | `c2-results.md` | slice C2: memory and calls | +| `c3-results.md` | slice C3: rule localization | | `c4-results.md` | slice C4 on the test corpus: precision and recall against restored bugs | | `c4-decbench-results.md` | slice C4 on the decbench binaries: harness defects found, every `DIFFERS` sorted by cause, the issues filed | | `triage.md` | how to decide whether a difference is the spec's, the emulator's, the checker's or the harness's | diff --git a/docs/features/diffverify/c3-results.md b/docs/features/diffverify/c3-results.md new file mode 100644 index 0000000000..8ea7560875 --- /dev/null +++ b/docs/features/diffverify/c3-results.md @@ -0,0 +1,100 @@ +# diffverify — slice C3 results (rule localization) + +C3 names the rule application after which a decompiled function stops computing what +the binary computes (proposal, Slices). + +```sh +decompiler/target/release/kuna-verify localize tests/stages/kuna-floatret.xml logish +``` +``` +logish (decompile 2) differs; of the 24 rules that applied, it agrees without these, in the order their last needed application ran: + step 134 selectcse application 1 of 1 at 0x40001c (agrees with 0, differs with 1) + step 155 subcommute application 2 of 2 at 0x40001c (agrees with 1, differs with 2) + step 180 subvar_shift application 3 of 4 at 0x40001c (agrees with 2, differs with 3) + step 200 ignorenan application 1 of 1 at 0x400018 (agrees with 0, differs with 1) <- latest +``` + +`--pass N` picks the `N`-th decompile of the function in the script. By default +`localize` picks the first one that differs. An object file works too, with +`--option NAME VALUE`. + +## 1. Method + +The proposal suggested reverting fixes. That needs a fix to revert, so it does not +work for a bug nobody has fixed. C3 instead reruns the decompile that differs with +rules held back. A per-thread cap in the rule pool does this +(`kuna-decomp/src/infra/kuna_rulecap.rs`, spec §0.6): +1. Count every rule application in the full decompile, by rule, in order. +2. Rerun once per rule that applied, with that rule alone held back. Every other rule + and every action runs, so each rerun is a complete decompile. +3. A rule without which the function agrees is a culprit. A binary search over how + many times it may apply finds `k`: with `k - 1` applications it agrees, with `k` it + differs. The `k`-th application is named by the op address it rewrote. +4. Both ends of the pair are measured. The agreeing end is confirmed over every run; + the search itself checks only up to 32 runs past the full decompile's failing run. +5. Culprits are listed in the order their `k`-th application ran in the full decompile. + +The binary search assumes that once an application makes the function differ, the +later ones do not undo it. A rewrite that a later application cancels breaks that, and +can hide an earlier application that already differed. So `k` is a candidate: the +agreeing end with `k - 1` is checked over every run and the differing end with `k` is a +concrete counterexample, but neither shows that `k` is the first or the only cause. +Holding a rule back also changes the IR every later rule sees and the order they apply +in, so a culprit can be one side of an interaction between rules rather than the +direct cause. + +Holding back every rule at once does not work as a baseline. Without the folding +rules, stack addresses are never resolved and actions see a different program. So +the first design, a cap on all applications, was dropped. + +Two kinds of culprit come out: +- **Enablers.** `propagatecopy`, `collapseconstants` and `sub2add` prepare the IR that + a later step gets wrong, so without them the wrong step never fires. +- **The rule that is wrong**, which is usually the one marked `latest`. + +A capped decompile gets a 5-second budget: with a rule held back, some actions +never settle. Running past that budget, or a verdict other than `AGREES` or +`DIFFERS`, is reported as inconclusive for that rule. + +## 2. The corpus + +`localize` was run on all 113 `DIFFERS` of the corpus: 199 s wall +time on 12 parallel jobs. + +| outcome | functions | +|---|---:| +| names one or more rules | 15 | +| differs without any one rule: an action, or rules together | 98 | + +The latest culprit in each of the 15: + +| latest culprit | functions | what §4 / §6 of `c4-results.md` says it is | +|---|---|---| +| `ignorenan` | `armfloat-preset` `scale_err` (2 passes), `floatret` `logish`, `prefersplit` `ccw_mixed` | the ARM/AArch64 NaN compares, the kuna defect of c4 §6c | +| `storevarnode` | `stackviews` `obj_global_reuse` (0x4011ec), `declaring-double-score-return` `refined_score` | the store kuna drops (c4 §2; #1834) and the callee-clobber control | +| `loadvarnode` | `mipsgot-weak` `same` (2 passes) | the load of an undefined weak symbol folded from the image: the harness limit of c4 §2 | +| `propagatecopy` | `narrowext` `ci`, `cu`, `csc`; `indexedstoreguard` `cb_m8`, `-a64` `m8`; `calleearitycut` `caller3`; `calleearityscratch` `boundary_const` | off passes and known limitations the tests pin | + +Each matches the triage in `c4-results.md` that was done by hand. + +The 98 that name no rule are mostly the call defects: +- arguments a caller passes straight through, dropped by prototype recovery; +- call outputs never connected; +- killed registers. + +Those are actions in P4, not rules. The rest are harness limits and off passes whose +cause is an action. + +`gh8777-flagcompare-sborrow` names no rule, although `RuleSborrowGe` is the bug +there. On PIC24 the W registers are memory-mapped, so the first difference the check +sees is the register file in RAM. That difference is there with or without the rule. + +## 3. Cost + +- **The hook, unarmed.** The pool reads one thread-local flag per rule attempt. A/B + of `decompile-all --jobs 1` over `dwarf_namespaces_rust_x86_64` (549 functions, + five runs each, alternating) showed no measurable cost: median user time 29.7 s + without the hook, 26.9 s with it, on a machine under load average 60. +- **Localizing.** About 1 + (rules applied) + Σ log2(applications of each culprit) + decompiles. A script is cut after the decompile being localized. Typical cases take + 1–10 s. diff --git a/docs/features/diffverify/proposal.md b/docs/features/diffverify/proposal.md index 1dcfe9a575..324d8bc0c2 100644 --- a/docs/features/diffverify/proposal.md +++ b/docs/features/diffverify/proposal.md @@ -2,7 +2,7 @@ Status: **proposal**. Slices C1, C2, C3 and C4 (on the corpus kuna has) are implemented in `decompiler/crates/kuna-verify`. Their measurements and the design changes they forced -are in `c1-results.md`, `c2-results.md` and `c4-results.md`. +are in `c1-results.md`, `c2-results.md`, `c3-results.md` and `c4-results.md`. Evidence, coverage estimates and the hard part: `analysis.md` in this folder. ## What this makes possible @@ -321,7 +321,7 @@ library rather than stubbed. |---|---|---| | C1 | Tier C on register-only leaf functions: no calls and no memory access at all, except loads from read-only image data; same raw state on both sides; physical-ABI and typed-contract return checks; `PROTOTYPE_SUSPECT`; `UNKNOWN(unsupported-op)`; declared-divergence predicates | reverting #794 gives `DIFFERS` against its fixture's source contract; verdict table over `tests/datatests` + `tests/stages`, with per-function and total time. **Done** (`c1-results.md`) | | C2 | memory and call effects: stack, pointer-argument and global memory; call stubs that write reachable memory, globals included | reverting #801 gives `DIFFERS`; a rule that keeps a pre-call load across a call that writes it gives `DIFFERS`. **Done** (`c2-results.md`; both by a fault injected in a local build) | -| C3 | rule localization over the C1/C2 verdicts | candidate culprits include `subvar_zext` on reverted #794; cost per finding. **Done** (by holding back one rule at a time rather than reverting; 15 of 113 corpus `DIFFERS` named down to a rule application, the rest are action-level) | +| C3 | rule localization over the C1/C2 verdicts | candidate culprits include `subvar_zext` on reverted #794; cost per finding. **Done** (`c3-results.md`: by holding back one rule at a time rather than reverting; 15 of 113 corpus `DIFFERS` named down to a rule application, the rest are action-level) | | C4 | corpus run (decbench binaries); precision and recall | precision: triage of every `DIFFERS` into bug / declared divergence / harness bug. Recall: of the ~44 visible P3/P4 fixes that have a fixture, how many give `DIFFERS` when reverted. Published table with both. **Precision and recall done on `tests/datatests` + `tests/stages`** (`c4-results.md`: 7 of 22 restored bugs caught without a contract, 11 with one). **decbench done** (`c4-decbench-results.md`: 28,233 functions of 66 binaries, 80% `AGREES`; 243 `DIFFERS` triaged by class, five new kuna bugs) | | C5 | concolic inputs: expressions over the inputs on both sides, branch conditions negated through z3, capped paths and queries | a fixture whose difference appears only on one 32-bit value gives `DIFFERS`, where 256 random runs give `AGREES`; new paths reached per function on the corpus **Done** (`c5-results.md`: `--concolic N`; a value-specific fault caught that 256 random runs miss; on decbench, concolic runs in 49 of 250 sample functions and 105 of 405 `ls` functions) | | S1 | Tier S for loop-free `AGREES` functions that pass the static entry condition, under the budget | `EQUIVALENT` and `UNKNOWN(budget)` counts on the same corpus; every `sat` replays or is classified | From fdca7b25d4d9ef4799bfb05f04d28a4505706fd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 07:54:38 +0900 Subject: [PATCH 4/7] [AUTOMATED] Run kuna-verify over both corpora in CI against a recorded baseline `make verify-corpus` checks every function tests/datatests and tests/stages decompile and compares each verdict with docs/baseline-verify.json; a non-gating step of the parity-gates job runs it and uploads the verdicts. A function that agreed (or a new one) and now differs, or a file that can no longer be checked, is a regression. A function that agreed and is now UNKNOWN, or agrees on at most half the runs it agreed on, is lost coverage. A DIFFERS is recorded with the place it first differs, without values, so a difference that moves is listed as a notice instead of passing unseen or failing the run. Baseline recorded on this base: 5,837 functions, 5,073 agree. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 38 + Makefile | 14 +- .../crates/kuna-verify/src/bin/kuna-verify.rs | 77 +- decompiler/crates/kuna-verify/src/lib.rs | 1 + .../crates/kuna-verify/src/report/baseline.rs | 367 ++++++ .../crates/kuna-verify/src/report/mod.rs | 2 + docs/baseline-verify.json | 1037 +++++++++++++++++ docs/features/diffverify/README.md | 36 +- docs/features/diffverify/proposal.md | 16 +- 9 files changed, 1570 insertions(+), 18 deletions(-) create mode 100644 decompiler/crates/kuna-verify/src/report/baseline.rs create mode 100644 docs/baseline-verify.json diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 3ceb99d994..22aa3cd0d7 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -163,6 +163,44 @@ jobs: cd decompiler cargo test -p kuna-ghidra --release -- --include-ignored --nocapture + # diffverify (docs/features/diffverify/): kuna-verify runs every function the + # two corpora decompile against the machine code and compares each verdict + # with docs/baseline-verify.json. Not a gate yet (the proposal's CI rule): + # a function that newly differs is an error annotation on the run, other + # changes are notices, and the job's result is untouched. The verdict + # table and this run's own baseline are uploaded to re-record from. + - name: diffverify corpus vs docs/baseline-verify.json (non-gating) + id: diffverify + continue-on-error: true + run: | + (cd decompiler && cargo build --release -p kuna-verify) + set +e + ./decompiler/target/release/kuna-verify corpus tests/datatests tests/stages --trace \ + --baseline docs/baseline-verify.json --save-baseline diffverify-baseline.json \ + > diffverify.md 2> diffverify-changes.txt + status=$? + set -e + grep -E '^::(error|warning|notice) ' diffverify.md || true + { + echo '### diffverify' + echo '```' + sed -n '/^files /,$p' diffverify.md + cat diffverify-changes.txt + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + exit $status + + - name: Upload the diffverify verdicts + if: always() && steps.diffverify.outcome != 'skipped' + uses: actions/upload-artifact@v4 + with: + name: diffverify + path: | + diffverify.md + diffverify-changes.txt + diffverify-baseline.json + if-no-files-found: ignore + # Node 22: the web suites below are written for (and only run on) a # current Node; the runner's default Node is not pinned. The suites that # drive headless Chrome (decompile-browser, -collab-browser, -collab-page, diff --git a/Makefile b/Makefile index 189a60be8c..e60bee390d 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ PYTHON ?= python3 # (inside target/, which is gitignored, so a failed run leaves no repo litter). GHIDRA_SIM_LOG := $(ENGINE)/target/ghidra-sim.log -.PHONY: all binaries specs test test-stages test-jvm test-cli test-tools test-ghidra rust rust-test lint clean check-spec version observatory coverage +.PHONY: all binaries specs test test-stages test-jvm verify-corpus test-cli test-tools test-ghidra rust rust-test lint clean check-spec version observatory coverage all: binaries specs @@ -59,6 +59,18 @@ test-stages: $(BINDIR)/kuna test-jvm: $(BINDIR)/kuna cd $(ROOT) && $(BINDIR)/kuna test --jvm +# diffverify (docs/features/diffverify/): kuna-verify over both corpora, every +# verdict compared with docs/baseline-verify.json, function by function even +# where a file's function list changed. Fails only on a function that now +# differs (a new one included) or a file that can no longer be checked; lost +# coverage and other changes are listed, with the count of AGREES before/after. +# Re-record: make verify-corpus VERIFY_ARGS='--save-baseline docs/baseline-verify.json' +verify-corpus: + cd $(ENGINE) && cargo build --$(PROFILE) -p kuna-verify + @test -n "$$(find $(SPECS) -name '*.sla' -print -quit)" || $(MAKE) specs + cd $(ROOT) && $(BINDIR)/kuna-verify corpus tests/datatests tests/stages --trace \ + --sleighpath $(SPECS) --baseline docs/baseline-verify.json $(VERIFY_ARGS) > /dev/null + $(BINDIR)/kuna: cd $(ENGINE) && cargo build --$(PROFILE) -p kuna-cli diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs index 105d0a1039..91a87d01ca 100644 --- a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -2,7 +2,7 @@ //! //! ```text //! kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... -//! kuna-verify corpus ... [--jobs N] [--file-seconds S] +//! kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] //! kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] //! common: [--runs N] [--seed S] [--budget OPS] [--json] [--sleighpath DIR] @@ -20,7 +20,9 @@ //! chunk goes to a fresh worker. //! //! Exit status: 1 when a function differs, 3 when a file could not be checked, -//! 2 for a usage error, else 0. +//! 2 for a usage error, else 0. With `--baseline`, 1 only for a regression +//! against it: a function that now differs, or a file that now fails. +//! Under GitHub Actions each change is also printed as an annotation. use std::collections::BTreeMap; use std::io::Write; @@ -28,13 +30,13 @@ use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode, Stdio}; use std::time::Instant; -use kuna_verify::{check_binary_each, check_datatest, localize, session, Options, Report, Row, Verdict}; +use kuna_verify::{baseline, check_binary_each, check_datatest, localize, session, Options, Report, Row, Verdict}; use serde_json::{json, Value}; const USAGE: &str = "usage: kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... - kuna-verify corpus ... [--jobs N] [--file-seconds S] + kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] options: --runs N (256) --seed S --budget OPS (200000) --call-reruns N (4) --json --trace --sleighpath DIR"; @@ -54,6 +56,8 @@ struct Args { /// a worker process, which is what a time limit can stop. timed: bool, per_function: usize, + baseline: Option, + save_baseline: Option, pass: Option, /// Flags a worker process gets again. forward: Vec, @@ -73,6 +77,8 @@ fn parse(argv: &[String]) -> Result { file_seconds: 1200, timed: false, per_function: 6, + baseline: None, + save_baseline: None, pass: None, forward: Vec::new(), }; @@ -129,6 +135,8 @@ fn parse(argv: &[String]) -> Result { let p = num(it.next(), "--pass")?; a.pass = Some(usize::try_from(p).ok().filter(|&p| p > 0).ok_or("--pass counts from 1")?); } + "--baseline" => a.baseline = Some(it.next().ok_or("--baseline needs a file")?.clone()), + "--save-baseline" => a.save_baseline = Some(it.next().ok_or("--save-baseline needs a file")?.clone()), "--json" => a.json = true, "--all" => a.all = true, "--trace" => { @@ -570,6 +578,10 @@ fn run_corpus(a: &Args) -> Result { if a.positional.is_empty() { return Err(USAGE.to_string()); } + let base = match &a.baseline { + Some(f) => Some(baseline::parse(&std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"))?).map_err(|e| format!("{f}: {e}"))?), + None => None, + }; let mut files = Vec::new(); for p in &a.positional { let path = Path::new(p); @@ -644,9 +656,66 @@ fn run_corpus(a: &Args) -> Result { if !errors.is_empty() && !a.json { println!("file errors {}", errors.len()); } + let now: baseline::Baseline = files + .iter() + .zip(&results) + .map(|(f, res)| { + let key = f.to_string_lossy().trim_start_matches("./").to_string(); + let mut rows: Vec<(String, String)> = res.rows.iter().map(|r| (r.function.clone(), baseline::class(r))).collect(); + if res.error.is_some() { + rows.push((String::new(), baseline::ERROR.to_string())); + } + (key, rows) + }) + .collect(); + if let Some(f) = &a.save_baseline { + std::fs::write(f, baseline::render(&now)).map_err(|e| format!("{f}: {e}"))?; + eprintln!("kuna-verify: baseline saved to {f}"); + if base.is_none() { + return Ok(ExitCode::SUCCESS); + } + } + if let (Some(base), Some(f)) = (base, &a.baseline) { + return Ok(report_baseline(&baseline::compare(&base, &now), f)); + } Ok(exit_code(&rows, errors.len())) } +/// Print how the run compares with the baseline; 1 on a regression. +fn report_baseline(c: &baseline::Changes, file: &str) -> ExitCode { + let actions = std::env::var_os("GITHUB_ACTIONS").is_some(); + let groups = [ + ("new DIFFERS or file errors", "error", &c.regressions), + ("no longer agree or no longer checked", "warning", &c.lost), + ("other changes", "notice", &c.other), + ]; + eprintln!(); + for (title, level, lines) in groups { + if lines.is_empty() { + continue; + } + eprintln!("{title} ({}):", lines.len()); + for l in lines.iter() { + eprintln!(" {l}"); + if actions { + println!("::{level} title=diffverify::{l}"); + } + } + } + eprintln!( + "AGREES {} -> {} of {} -> {} functions", + c.agreed.0, c.agreed.1, c.functions.0, c.functions.1 + ); + if c.regressions.is_empty() { + let note = if c.is_empty() { "" } else { "; re-record it if the changes are intended" }; + eprintln!("BASELINE OK against {file}{note}"); + ExitCode::SUCCESS + } else { + eprintln!("BASELINE REGRESSION against {file}: {} new", c.regressions.len()); + ExitCode::from(1) + } +} + /// Name the first rule application after which a decompile differs. fn run_localize(a: &Args) -> Result { let [target, function] = a.positional.as_slice() else { diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs index 295a6f2d11..b0bb86cae6 100644 --- a/decompiler/crates/kuna-verify/src/lib.rs +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -24,6 +24,7 @@ pub mod tools; pub use abi::{calls, contract, divergence}; pub use compare::check; pub use graph::program; +pub use report::baseline; pub use semantics::{storage, value, x87}; pub use tools::{localize, mutate}; diff --git a/decompiler/crates/kuna-verify/src/report/baseline.rs b/decompiler/crates/kuna-verify/src/report/baseline.rs new file mode 100644 index 0000000000..190cb7a918 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/report/baseline.rs @@ -0,0 +1,367 @@ +//! The corpus baseline (`docs/baseline-verify.json`): each datatest file's +//! verdict classes in script order, and how a run compares with it. +//! +//! A class leaves out what varies without the verdict changing: a `DIFFERS` +//! run and its values, an `UNKNOWN` address. A `DIFFERS` keeps where it first +//! differs (`DIFFERS(return)`, `DIFFERS(call at 0x10 to 0x20)`), so a function +//! that differs elsewhere than it did is listed. It keeps an `AGREES` run count, +//! so a function that agrees on at most half the runs it agreed on is lost +//! coverage; a smaller change in the count is not reported. Rows pair by function and +//! occurrence, so a file whose function list changed is still compared. A +//! function that now differs where it did not, a new function that differs, +//! or a file that can no longer be checked is a regression; lost coverage is a +//! warning; every other change is reported so the baseline can be re-recorded. + +use std::collections::BTreeMap; + +use serde_json::Value; + +use crate::report::Row; + +/// Per file, `(function, class)` in the order the script decompiles them; a +/// file that could not be checked has the class `ERROR` alone. +pub type Baseline = BTreeMap>; + +pub const ERROR: &str = "ERROR"; +const VERSION: u64 = 1; + +/// What the baseline records of a verdict. +pub fn class(r: &Row) -> String { + match r.class.as_str() { + "AGREES" => r.label.clone(), + "DIFFERS" => format!("DIFFERS({})", first_difference(r)), + "UNKNOWN" | "SKIPPED" => format!("{})", r.reason().unwrap_or_else(|| r.class.clone())), + _ => r.label.clone(), + } +} + +/// Where a run first differs, without values: `return`, `unassigned` (kuna's +/// result reads something its C never assigns), or its first differing line +/// up to the first `:`. +fn first_difference(r: &Row) -> String { + let skip = ["contract", "input", "note", "trace"]; + let line = r.lines.iter().map(|l| l.trim()).find(|l| !skip.iter().any(|p| l.starts_with(p))); + match line { + Some(l) if l.starts_with("machine ") || l.starts_with("kuna ") => "return".into(), + Some(l) if l.starts_with("kuna's result depends") => "unassigned".into(), + Some(l) => l.split(':').next().unwrap_or(l).trim().chars().take(80).collect(), + None => "?".into(), + } +} + +fn differs(k: &str) -> bool { + k == "DIFFERS" || k.starts_with("DIFFERS(") +} + +/// One line per file, sorted, so a re-recorded baseline diffs by file. +pub fn render(b: &Baseline) -> String { + let mut s = format!("{{\n \"version\": {VERSION},\n \"files\": {{\n"); + for (k, (file, rows)) in b.iter().enumerate() { + let items: Vec<_> = rows.iter().map(|(f, c)| serde_json::json!({"function": f, "verdict": c})).collect(); + let sep = if k + 1 == b.len() { "" } else { "," }; + s.push_str(&format!(" {}: {}{sep}\n", Value::from(file.as_str()), Value::from(items))); + } + s.push_str(" }\n}\n"); + s +} + +/// `name class`, where a name may hold spaces (`-[A b:]`) and so may the +/// reason of an `UNKNOWN`, `SKIPPED` or `DIVERGES` class (`UNKNOWN(no switch row)`). +fn split_row(r: &str) -> Option<(&str, &str)> { + let tagged = r.ends_with(')').then(|| [" UNKNOWN(", " SKIPPED(", " DIVERGES(", " AGREES("].iter().filter_map(|t| r.rfind(t)).max()).flatten(); + match tagged { + Some(i) => Some((&r[..i], &r[i + 1..])), + None => r.rsplit_once(' '), + } +} + +pub fn parse(text: &str) -> Result { + let v: Value = serde_json::from_str(text).map_err(|e| e.to_string())?; + let root = v.as_object().ok_or("the baseline is not a JSON object")?; + let versioned = root.contains_key("version"); + let files = if versioned { + if root["version"].as_u64() != Some(VERSION) { + return Err(format!("unsupported baseline version {}", root["version"])); + } + root.get("files").and_then(Value::as_object).ok_or("the baseline has no files object")? + } else { + root + }; + let mut b = Baseline::new(); + for (file, rows) in files { + let rows = rows.as_array().ok_or_else(|| format!("{file}: not an array"))?; + let mut out = Vec::with_capacity(rows.len()); + for r in rows { + let (f, c) = if versioned { + let f = r.get("function").and_then(Value::as_str).ok_or_else(|| format!("{file}: no function in {r}"))?; + let c = r.get("verdict").and_then(Value::as_str).ok_or_else(|| format!("{file}: no verdict in {r}"))?; + (f, c) + } else { + let r = r.as_str().ok_or_else(|| format!("{file}: not a string: {r}"))?; + split_row(r).ok_or_else(|| format!("{file}: no class in {r:?}"))? + }; + out.push((f.to_string(), c.to_string())); + } + b.insert(file.clone(), out); + } + Ok(b) +} + +#[derive(Default, Debug)] +pub struct Changes { + /// A function that now differs, a new function that differs, or a file + /// that can no longer be checked. + pub regressions: Vec, + /// Coverage lost without a new difference: a function that agreed and no + /// longer does, a function or file the baseline has that was not checked. + pub lost: Vec, + /// Every other change, a function that no longer differs among them. + pub other: Vec, + /// Functions that agree, and functions in all, in the baseline and now. + pub agreed: (usize, usize), + pub functions: (usize, usize), +} + +impl Changes { + pub fn is_empty(&self) -> bool { + self.regressions.is_empty() && self.lost.is_empty() && self.other.is_empty() + } +} + +/// Each row keyed by its function and how many times the file decompiled that +/// function before it, so a function decompiled again under other options +/// pairs with its own earlier verdict. +fn keyed(rows: &[(String, String)]) -> Vec<((String, usize), String)> { + let mut seen: BTreeMap<&str, usize> = BTreeMap::new(); + rows.iter() + .map(|(f, c)| { + let n = seen.entry(f.as_str()).or_default(); + *n += 1; + ((f.clone(), *n), c.clone()) + }) + .collect() +} + +fn name((f, n): &(String, usize)) -> String { + if *n == 1 { f.clone() } else { format!("{f} (decompile {n})") } +} + +/// `UNKNOWN` reasons that stand for a difference the check found but traced +/// to a guess: one appearing where a function agreed is a regression, since a +/// guess elsewhere in a run must not let a real difference pass the gate. +const DIFFERENCE_REASONS: [&str; 5] = ["prototype-suspect", "guessed-callee", "uninitialized-local", "assumed-domain", "abi-violation"]; + +fn found_difference(k: &str) -> bool { + k.strip_prefix("UNKNOWN(").is_some_and(|r| DIFFERENCE_REASONS.iter().any(|d| r.starts_with(d))) +} + +/// Whether a class is an agreement, and over how many runs when it says. +fn agrees(k: &str) -> Option> { + if k == "AGREES" { + return Some(None); + } + k.strip_prefix("AGREES(").and_then(|r| r.strip_suffix(')')).map(|n| n.parse().ok()) +} + +pub fn compare(base: &Baseline, now: &Baseline) -> Changes { + let mut c = Changes::default(); + let count = |b: &Baseline| { + let rows = b.values().flatten(); + (rows.clone().filter(|(_, k)| agrees(k).is_some()).count(), rows.count()) + }; + let (was_agreed, was_all) = count(base); + let (now_agreed, now_all) = count(now); + c.agreed = (was_agreed, now_agreed); + c.functions = (was_all, now_all); + for (file, rows) in now { + let Some(was) = base.get(file) else { + for (f, k) in rows.iter().filter(|(_, k)| differs(k) || k == ERROR) { + c.regressions.push(format!("{file} {f}: not in the baseline, {k}")); + } + c.other.push(format!("{file}: not in the baseline")); + continue; + }; + let was = keyed(was); + let rows = keyed(rows); + let old: BTreeMap<_, _> = was.iter().cloned().collect(); + let new: BTreeMap<_, _> = rows.iter().cloned().collect(); + for (key, k) in &rows { + let f = name(key); + let Some(o) = old.get(key) else { + let line = format!("{file} {f}: not in the baseline, {k}"); + if differs(k) || k == ERROR { + c.regressions.push(line); + } else { + c.other.push(line); + } + continue; + }; + if o == k { + continue; + } + let line = format!("{file} {f}: {o} -> {k}"); + if let (Some(was), Some(is)) = (agrees(o), agrees(k)) { + if let (Some(was), Some(is)) = (was, is) { + if is.saturating_mul(2) <= was { + c.lost.push(format!("{line}, at most half the runs")); + } + } + continue; + } + if differs(o) && differs(k) { + c.other.push(line); + } else if differs(k) || k == ERROR || (agrees(o).is_some() && found_difference(k)) { + c.regressions.push(line); + } else if agrees(o).is_some() { + c.lost.push(line); + } else { + c.other.push(line); + } + } + for (key, k) in was.iter().filter(|(key, _)| !new.contains_key(key)) { + let line = format!("{file} {}: {k}, no longer decompiled", name(key)); + if agrees(k).is_some() { + c.lost.push(line); + } else { + c.other.push(line); + } + } + } + for file in base.keys().filter(|f| !now.contains_key(*f)) { + c.lost.push(format!("{file}: in the baseline, not checked")); + } + c +} + +#[cfg(test)] +mod tests { + use super::*; + + fn b(entries: &[(&str, &[(&str, &str)])]) -> Baseline { + entries + .iter() + .map(|(f, rows)| (f.to_string(), rows.iter().map(|(a, c)| (a.to_string(), c.to_string())).collect())) + .collect() + } + + #[test] + fn render_round_trips() { + let x = b(&[ + ("t/a.xml", &[("f", "AGREES"), ("g g", "UNKNOWN(budget)"), ("h", "UNKNOWN(no switch row)"), ("-[A b:]", "UNKNOWN(no switch row)")]), + ("t/b.xml", &[("", ERROR)]), + ]); + assert_eq!(parse(&render(&x)).unwrap(), x); + } + + #[test] + fn structured_rows_preserve_verdict_tokens_in_names_and_reasons() { + let x = b(&[("f.xml", &[ + ("f UNKNOWN(budget)", "UNKNOWN(replay included AGREES(7))"), + ("f UNKNOWN(budget)", "DIVERGES(explanation contains SKIPPED(proof))"), + ])]); + assert_eq!(parse(&render(&x)).unwrap(), x); + assert_eq!(parse(r#"{"f.xml":["-[A b:] UNKNOWN(no switch row)"," ERROR"]}"#).unwrap(), + b(&[("f.xml", &[("-[A b:]", "UNKNOWN(no switch row)"), ("", ERROR)])])); + assert!(parse(r#"{"version":2,"files":{}}"#).is_err()); + } + + #[test] + fn only_a_new_difference_is_a_regression() { + let base = b(&[("a", &[("f", "AGREES"), ("g", "DIFFERS"), ("h", "AGREES"), ("i", "UNKNOWN(budget)")])]); + let now = b(&[("a", &[("f", "DIFFERS"), ("g", "AGREES"), ("h", "UNKNOWN(budget)"), ("i", "UNKNOWN(budget)")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a f: AGREES -> DIFFERS"]); + assert_eq!(c.lost, ["a h: AGREES -> UNKNOWN(budget)"]); + assert_eq!(c.other, ["a g: DIFFERS -> AGREES"]); + assert!(compare(&base, &base).is_empty()); + } + + #[test] + fn a_file_that_fails_or_changes_its_functions() { + let base = b(&[("a", &[("f", "AGREES")]), ("b", &[("f", "AGREES")])]); + let now = b(&[("a", &[("", ERROR)]), ("c", &[("f", "AGREES")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a : not in the baseline, ERROR"]); + assert_eq!(c.lost, ["a f: AGREES, no longer decompiled", "b: in the baseline, not checked"]); + assert_eq!(c.other, ["c: not in the baseline"]); + } + + /// A changed function list still compares the functions both have, and a + /// new function that differs is a regression even where an old one already + /// differed. + #[test] + fn a_changed_function_list_is_compared_by_name() { + let base = b(&[("a", &[("f", "DIFFERS"), ("g", "AGREES")])]); + let now = b(&[("a", &[("f", "DIFFERS"), ("h", "DIFFERS")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a h: not in the baseline, DIFFERS"]); + assert_eq!(c.lost, ["a g: AGREES, no longer decompiled"]); + assert_eq!((c.agreed, c.functions), ((1, 0), (2, 2))); + } + + /// An agreement over far fewer runs is lost coverage; a small change in the + /// count, or a count against an old class without one, is not reported. + #[test] + fn an_agreement_over_far_fewer_runs_is_lost_coverage() { + let base = b(&[("a", &[("f", "AGREES(256)"), ("g", "AGREES(256)"), ("h", "AGREES")])]); + let now = b(&[("a", &[("f", "AGREES(1)"), ("g", "AGREES(250)"), ("h", "AGREES(3)")])]); + let c = compare(&base, &now); + assert_eq!(c.lost, ["a f: AGREES(256) -> AGREES(1), at most half the runs"]); + assert!(c.regressions.is_empty() && c.other.is_empty()); + assert_eq!(c.agreed, (3, 3)); + assert_eq!(parse(&render(&now)).unwrap(), now); + } + + /// Half the runs is already lost coverage. + #[test] + fn an_agreement_over_half_the_runs_is_lost_coverage() { + let base = b(&[("a", &[("f", "AGREES(256)"), ("g", "AGREES(256)")])]); + let now = b(&[("a", &[("f", "AGREES(128)"), ("g", "AGREES(129)")])]); + assert_eq!(compare(&base, &now).lost, ["a f: AGREES(256) -> AGREES(128), at most half the runs"]); + } + + /// A function that still differs, but somewhere else, is listed and does + /// not fail; one that newly differs fails whatever the place. + #[test] + fn a_difference_that_moves_is_listed() { + let base = b(&[("a", &[("f", "DIFFERS(return)"), ("g", "DIFFERS"), ("h", "AGREES(256)"), ("i", "DIFFERS(return)")])]); + let now = b(&[("a", &[("f", "DIFFERS(call at 0x10 to 0x20)"), ("g", "DIFFERS(return)"), ("h", "DIFFERS(memory at exit)"), ("i", "DIFFERS(return)")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a h: AGREES(256) -> DIFFERS(memory at exit)"]); + assert_eq!(c.other, ["a f: DIFFERS(return) -> DIFFERS(call at 0x10 to 0x20)", "a g: DIFFERS -> DIFFERS(return)"]); + assert!(c.lost.is_empty()); + } + + #[test] + fn a_difference_is_recorded_by_where_it_first_differs() { + let row = |lines: &[&str]| Row { + function: "f".into(), class: "DIFFERS".into(), label: "DIFFERS".into(), run: Some((0, 256)), + lines: lines.iter().map(|l| l.to_string()).collect(), suspects: Vec::new(), ms: 0.0, + }; + assert_eq!(class(&row(&["input a0=0x1 (RDI)", "machine RAX = 0x2", "kuna int8 f(int8 a0) = 0x3"])), "DIFFERS(return)"); + assert_eq!(class(&row(&["contract int f(int)", "input a0=0x1", "call 1 at 0x18000c005: the machine calls 0x18000c020, kuna calls 0x10000"])), "DIFFERS(call 1 at 0x18000c005)"); + assert_eq!(class(&row(&["input a0=0x1", "memory at exit: ram:0x6: machine 0x07, kuna 0x0f (4 bytes differ)"])), "DIFFERS(memory at exit)"); + assert_eq!(class(&row(&["input a0=0x1", "kuna's result depends on a call's output register it never connects, which its C never assigns: 0x1"])), "DIFFERS(unassigned)"); + } + + /// A function that agreed and now has a difference the check traces to a + /// guess fails the gate; one that runs out of budget only loses coverage. + #[test] + fn a_difference_traced_to_a_guess_is_a_regression() { + let base = b(&[("a", &[("f", "AGREES(256)"), ("g", "AGREES(256)")])]); + let now = b(&[("a", &[("f", "UNKNOWN(prototype-suspect)"), ("g", "UNKNOWN(budget)")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a f: AGREES(256) -> UNKNOWN(prototype-suspect)"]); + assert_eq!(c.lost, ["a g: AGREES(256) -> UNKNOWN(budget)"]); + } + + /// A function decompiled twice pairs each decompile with its own. + #[test] + fn a_function_decompiled_twice_pairs_by_occurrence() { + let base = b(&[("a", &[("f", "DIFFERS"), ("f", "AGREES")])]); + let now = b(&[("a", &[("g", "AGREES"), ("f", "DIFFERS"), ("f", "DIFFERS")])]); + let c = compare(&base, &now); + assert_eq!(c.regressions, ["a f (decompile 2): AGREES -> DIFFERS"]); + assert_eq!(c.other, ["a g: not in the baseline, AGREES"]); + } +} diff --git a/decompiler/crates/kuna-verify/src/report/mod.rs b/decompiler/crates/kuna-verify/src/report/mod.rs index f4c2e64247..7564b122c6 100644 --- a/decompiler/crates/kuna-verify/src/report/mod.rs +++ b/decompiler/crates/kuna-verify/src/report/mod.rs @@ -2,6 +2,8 @@ //! script or an agent. +pub mod baseline; + use std::time::Duration; use serde_json::{json, Value}; diff --git a/docs/baseline-verify.json b/docs/baseline-verify.json new file mode 100644 index 0000000000..efeef5588d --- /dev/null +++ b/docs/baseline-verify.json @@ -0,0 +1,1037 @@ +{ + "version": 1, + "files": { + "tests/datatests/bitfields.xml": [{"function":"dosomething","verdict":"UNKNOWN(trap)"},{"function":"doload","verdict":"UNKNOWN(trap)"},{"function":"dostackinsert","verdict":"UNKNOWN(trap)"},{"function":"dostackextract","verdict":"UNKNOWN(trap)"},{"function":"docompare","verdict":"UNKNOWN(trap)"},{"function":"doublecompare","verdict":"UNKNOWN(trap)"},{"function":"addsigned","verdict":"UNKNOWN(trap)"},{"function":"increment","verdict":"UNKNOWN(trap)"}], + "tests/datatests/bitfields2.xml": [{"function":"dosomething","verdict":"UNKNOWN(trap)"},{"function":"doload","verdict":"UNKNOWN(trap)"},{"function":"dostackinsert","verdict":"UNKNOWN(trap)"},{"function":"dostackextract","verdict":"UNKNOWN(trap)"},{"function":"docompare","verdict":"UNKNOWN(trap)"},{"function":"doublecompare","verdict":"UNKNOWN(trap)"},{"function":"addsigned","verdict":"UNKNOWN(trap)"},{"function":"increment","verdict":"UNKNOWN(trap)"}], + "tests/datatests/boolless.xml": [{"function":"boolless","verdict":"AGREES(256)"}], + "tests/datatests/ccmp.xml": [{"function":"ccmp","verdict":"AGREES(256)"}], + "tests/datatests/concat.xml": [{"function":"concatregparam","verdict":"AGREES(256)"},{"function":"concatreturn","verdict":"AGREES(256)"},{"function":"concatreturnshort","verdict":"AGREES(256)"},{"function":"replaceshort","verdict":"AGREES(256)"},{"function":"zerofield","verdict":"AGREES(256)"},{"function":"zerofield2","verdict":"AGREES(256)"}], + "tests/datatests/concatsplit.xml": [{"function":"test_split","verdict":"AGREES(256)"}], + "tests/datatests/condconst.xml": [{"function":"condconst1","verdict":"AGREES(256)"},{"function":"condconst_copy","verdict":"AGREES(256)"},{"function":"condconst_conn","verdict":"AGREES(256)"}], + "tests/datatests/condconst2.xml": [{"function":"zeroprop","verdict":"AGREES(256)"},{"function":"throughadd","verdict":"AGREES(256)"},{"function":"condmove","verdict":"AGREES(256)"}], + "tests/datatests/condconstsub.xml": [{"function":"foo","verdict":"AGREES(256)"}], + "tests/datatests/condexesub.xml": [{"function":"func","verdict":"AGREES(256)"},{"function":"iblockadd","verdict":"AGREES(256)"}], + "tests/datatests/condmulti.xml": [{"function":"condconst_multi","verdict":"AGREES(256)"}], + "tests/datatests/convert.xml": [{"function":"convert_list","verdict":"AGREES(256)"}], + "tests/datatests/copytrim.xml": [{"function":"myloop","verdict":"AGREES(12)"},{"function":"myglob","verdict":"AGREES(256)"}], + "tests/datatests/deadvolatile.xml": [{"function":"deadvolatile","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/deindirect.xml": [{"function":"deindirect","verdict":"AGREES(256)"}], + "tests/datatests/deindirect2.xml": [{"function":"deind26","verdict":"AGREES(256)"}], + "tests/datatests/displayformat.xml": [{"function":"setglobals","verdict":"AGREES(256)"}], + "tests/datatests/divopt.xml": [{"function":"divoptu","verdict":"AGREES(256)"},{"function":"divopti","verdict":"AGREES(256)"},{"function":"modoptu","verdict":"AGREES(256)"},{"function":"modopti","verdict":"AGREES(256)"}], + "tests/datatests/doublemove.xml": [{"function":"loaddouble","verdict":"AGREES(256)"},{"function":"storedouble","verdict":"AGREES(256)"}], + "tests/datatests/dupptr.xml": [{"function":"argv_test","verdict":"AGREES(256)"},{"function":"loadstore_fieldarray","verdict":"AGREES(256)"},{"function":"loadstore_ptrfieldarray","verdict":"AGREES(256)"},{"function":"doublearray_stack","verdict":"AGREES(256)"},{"function":"sameindex","verdict":"AGREES(256)"},{"function":"sameindex_samefield","verdict":"AGREES(256)"},{"function":"twodim_array","verdict":"AGREES(256)"}], + "tests/datatests/elseif.xml": [{"function":"testElseIf","verdict":"AGREES(66)"}], + "tests/datatests/enum.xml": [{"function":"stackenumlow","verdict":"AGREES(256)"},{"function":"stackenumhigh","verdict":"AGREES(256)"},{"function":"ptrenumlow","verdict":"AGREES(256)"},{"function":"ptrenumhigh","verdict":"AGREES(256)"},{"function":"ptrenumequal","verdict":"AGREES(256)"}], + "tests/datatests/floatcast.xml": [{"function":"prec_conditions","verdict":"AGREES(256)"},{"function":"prec_comparison","verdict":"AGREES(256)"}], + "tests/datatests/floatconv.xml": [{"function":"rand_calc","verdict":"AGREES(256)"},{"function":"rand_ulong","verdict":"AGREES(256)"},{"function":"ulconv_win","verdict":"AGREES(256)"}], + "tests/datatests/floatprint.xml": [{"function":"establish","verdict":"AGREES(256)"}], + "tests/datatests/forloop1.xml": [{"function":"forloop1","verdict":"AGREES(103)"}], + "tests/datatests/forloop_loaditer.xml": [{"function":"forloop_loaditer","verdict":"AGREES(43)"}], + "tests/datatests/forloop_thruspecial.xml": [{"function":"forloop_thruspecial","verdict":"AGREES(103)"}], + "tests/datatests/forloop_varused.xml": [{"function":"forloop_loopvarused","verdict":"AGREES(103)"}], + "tests/datatests/forloop_withskip.xml": [{"function":"forloop_withskip","verdict":"AGREES(51)"}], + "tests/datatests/gp.xml": [{"function":"test_gp","verdict":"AGREES(256)"}], + "tests/datatests/heapstring.xml": [{"function":"fillin","verdict":"UNKNOWN(unsupported-op)"},{"function":"fillin_edit","verdict":"UNKNOWN(unsupported-op)"},{"function":"overlap","verdict":"UNKNOWN(unsupported-op)"},{"function":"fillin_wide","verdict":"UNKNOWN(unsupported-op)"},{"function":"negative_ptr","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/ifswitch.xml": [{"function":"testval","verdict":"AGREES(256)"}], + "tests/datatests/impliedfield.xml": [{"function":"getvalue","verdict":"AGREES(256)"}], + "tests/datatests/indproto.xml": [{"function":"indproto","verdict":"AGREES(256)"}], + "tests/datatests/injectoverride.xml": [{"function":"callind_inject","verdict":"DIFFERS(call 1 at 0x18000c005)"},{"function":"inject_collapse","verdict":"DIFFERS(call 1 at 0x18000c01a)"}], + "tests/datatests/inline.xml": [{"function":"add100","verdict":"AGREES(256)"},{"function":"twohard","verdict":"AGREES(256)"},{"function":"collatz","verdict":"AGREES(256)"}], + "tests/datatests/inlinetarget.xml": [{"function":"main","verdict":"AGREES(256)"}], + "tests/datatests/longdouble.xml": [{"function":"pass","verdict":"UNKNOWN(unsupported-op)"},{"function":"passmany","verdict":"AGREES(256)"},{"function":"printstruct","verdict":"AGREES(256)"},{"function":"printldfirst","verdict":"UNKNOWN(unsupported-op)"},{"function":"arrayindex","verdict":"UNKNOWN(unsupported-op)"},{"function":"writeLongDouble","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/loopcomment.xml": [{"function":"loopcomment","verdict":"AGREES(28)"}], + "tests/datatests/lzcount.xml": [{"function":"cntlzwtest","verdict":"AGREES(256)"}], + "tests/datatests/mixfloatint.xml": [{"function":"dldlll","verdict":"AGREES(256)"},{"function":"fi","verdict":"AGREES(256)"},{"function":"id","verdict":"AGREES(256)"},{"function":"ldld","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/datatests/modulo.xml": [{"function":"remtest","verdict":"AGREES(256)"}], + "tests/datatests/modulo2.xml": [{"function":"mod2","verdict":"AGREES(256)"},{"function":"mod3","verdict":"AGREES(256)"},{"function":"mod4","verdict":"AGREES(256)"},{"function":"mod6","verdict":"AGREES(256)"}], + "tests/datatests/multiret.xml": [{"function":"getval","verdict":"AGREES(256)"}], + "tests/datatests/namespace.xml": [{"function":"a::b::assign_vals","verdict":"AGREES(256)"}], + "tests/datatests/nan.xml": [{"function":"nanops","verdict":"AGREES(256)"}], + "tests/datatests/nestedoffset.xml": [{"function":"readstruct","verdict":"AGREES(256)"}], + "tests/datatests/noforloop_alias.xml": [{"function":"noforloop_alias","verdict":"AGREES(103)"}], + "tests/datatests/noforloop_globcall.xml": [{"function":"noforloop_globcall","verdict":"AGREES(256)"}], + "tests/datatests/noforloop_iterused.xml": [{"function":"noforloop_iterused","verdict":"AGREES(103)"}], + "tests/datatests/offsetarray.xml": [{"function":"access_array1","verdict":"AGREES(256)"}], + "tests/datatests/orcompare.xml": [{"function":"comp2","verdict":"AGREES(256)"},{"function":"comp3","verdict":"AGREES(256)"}], + "tests/datatests/packstructaccess.xml": [{"function":"access","verdict":"AGREES(256)"}], + "tests/datatests/partialmerge.xml": [{"function":"readpartial","verdict":"AGREES(256)"},{"function":"read_expr_interfere","verdict":"AGREES(256)"},{"function":"readpartial_callinterfere","verdict":"AGREES(256)"},{"function":"readpartialstack_inbetween","verdict":"AGREES(256)"},{"function":"partial_restore","verdict":"AGREES(256)"}], + "tests/datatests/partialsplit.xml": [{"function":"loadalone","verdict":"AGREES(256)"},{"function":"storeconst","verdict":"AGREES(256)"},{"function":"copyloadstore","verdict":"AGREES(256)"},{"function":"storealone","verdict":"AGREES(256)"},{"function":"copy","verdict":"AGREES(256)"},{"function":"copyconst","verdict":"AGREES(256)"}], + "tests/datatests/partialunion.xml": [{"function":"partialunion","verdict":"AGREES(256)"},{"function":"partial1","verdict":"AGREES(256)"}], + "tests/datatests/piecestruct.xml": [{"function":"assign","verdict":"AGREES(256)"}], + "tests/datatests/pointercmp.xml": [{"function":"myinit","verdict":"AGREES(256)"}], + "tests/datatests/pointerrel.xml": [{"function":"process_array","verdict":"AGREES(85)"},{"function":"process_array","verdict":"AGREES(85)"}], + "tests/datatests/pointersub.xml": [{"function":"getOuter","verdict":"AGREES(256)"}], + "tests/datatests/promotecompare.xml": [{"function":"promote_compare","verdict":"AGREES(256)"}], + "tests/datatests/ptrtoarray.xml": [{"function":"ptrToArray","verdict":"AGREES(256)"},{"function":"passPtrToArray","verdict":"AGREES(256)"}], + "tests/datatests/readvolatile.xml": [{"function":"iofunc","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/retspecial.xml": [{"function":"returnbig","verdict":"AGREES(256)"},{"function":"read_returnbig","verdict":"AGREES(256)"}], + "tests/datatests/retstruct.xml": [{"function":"retstruct","verdict":"AGREES(256)"}], + "tests/datatests/revisit.xml": [{"function":"revisit","verdict":"AGREES(256)"}], + "tests/datatests/sbyte.xml": [{"function":"printStruct","verdict":"AGREES(256)"}], + "tests/datatests/skipnext2.xml": [{"function":"skipinst","verdict":"AGREES(256)"}], + "tests/datatests/stackreturn.xml": [{"function":"stackreturn","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/stackspill.xml": [{"function":"spill","verdict":"AGREES(256)"},{"function":"callspill","verdict":"AGREES(256)"}], + "tests/datatests/stackstring.xml": [{"function":"nullbetween","verdict":"UNKNOWN(unsupported-op)"},{"function":"twomessages","verdict":"UNKNOWN(unsupported-op)"},{"function":"utf32message","verdict":"UNKNOWN(unsupported-op)"},{"function":"stringInStruct","verdict":"UNKNOWN(unsupported-op)"},{"function":"alterString","verdict":"UNKNOWN(unsupported-op)"},{"function":"conditionalString","verdict":"UNKNOWN(unsupported-op)"},{"function":"globalString","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/statuscmp.xml": [{"function":"statuscmp","verdict":"UNKNOWN(unsupported-op)"}], + "tests/datatests/switchhide.xml": [{"function":"switchhide","verdict":"AGREES(256)"}], + "tests/datatests/switchind.xml": [{"function":"switchind","verdict":"AGREES(256)"}], + "tests/datatests/switchloop.xml": [{"function":"switchloop","verdict":"AGREES(256)"}], + "tests/datatests/switchmulti.xml": [{"function":"switchmulti","verdict":"AGREES(256)"}], + "tests/datatests/switchreturn.xml": [{"function":"switchreturn","verdict":"AGREES(256)"}], + "tests/datatests/threedim.xml": [{"function":"array_access","verdict":"AGREES(256)"}], + "tests/datatests/twodim.xml": [{"function":"array_access","verdict":"AGREES(256)"}], + "tests/datatests/union_datatype.xml": [{"function":"fillin","verdict":"AGREES(85)"},{"function":"access","verdict":"AGREES(256)"},{"function":"printglob","verdict":"AGREES(256)"},{"function":"getvalue","verdict":"AGREES(256)"},{"function":"getvalue6","verdict":"AGREES(256)"},{"function":"getvalue2","verdict":"AGREES(256)"},{"function":"testvalue","verdict":"AGREES(256)"},{"function":"stackarray","verdict":"AGREES(256)"},{"function":"setvalue3","verdict":"AGREES(256)"},{"function":"getvalue3","verdict":"AGREES(256)"},{"function":"process","verdict":"AGREES(256)"},{"function":"getvalue4","verdict":"AGREES(256)"},{"function":"setval5","verdict":"AGREES(256)"}], + "tests/datatests/varcross.xml": [{"function":"store_cross","verdict":"AGREES(256)"},{"function":"global_cross","verdict":"AGREES(256)"},{"function":"local_cross","verdict":"AGREES(256)"}], + "tests/datatests/wayoffarray.xml": [{"function":"access_array1","verdict":"AGREES(256)"}], + "tests/stages/branchflip-negated-guard.xml": [{"function":"bf","verdict":"AGREES(256)"},{"function":"bf","verdict":"AGREES(256)"}], + "tests/stages/cortus-aps3-constructors.xml": [{"function":"FUN_0","verdict":"AGREES(256)"},{"function":"FUN_10","verdict":"AGREES(256)"},{"function":"FUN_30","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/funcboundflow.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/gh1243-8051-addc.xml": [{"function":"func0","verdict":"UNKNOWN(budget)"}], + "tests/stages/gh1276-flagcompare-boolsign.xml": [{"function":"FUN_0","verdict":"UNKNOWN(budget)"}], + "tests/stages/gh1282-boolsignshift.xml": [{"function":"Fn1","verdict":"AGREES(256)"}], + "tests/stages/gh1537-simd-memset.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/gh1627-x86-senduipi-gatherpf.xml": [{"function":"f","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/gh1628-x86-vmx-decode-flags.xml": [{"function":"rd","verdict":"UNKNOWN(unsupported-op)"},{"function":"launch","verdict":"UNKNOWN(unsupported-op)"},{"function":"wr","verdict":"UNKNOWN(unsupported-op)"},{"function":"st","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/gh1674-subpiece-shadow-wide-const.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/gh1793-outparam-argslot.xml": [{"function":"outslot","verdict":"AGREES(256)"},{"function":"outslot_init","verdict":"AGREES(256)"},{"function":"outslot_loop","verdict":"AGREES(12)"},{"function":"outparam","verdict":"AGREES(256)"},{"function":"outpair","verdict":"AGREES(256)"},{"function":"outindex","verdict":"AGREES(256)"}], + "tests/stages/gh180-implied-cover-scarry.xml": [{"function":"nlscan","verdict":"UNKNOWN(budget)"},{"function":"grow","verdict":"AGREES(256)"}], + "tests/stages/gh181-snipreads-indirect.xml": [{"function":"lsetfilecon_raw","verdict":"AGREES(256)"},{"function":"lsetfilecon_raw","verdict":"AGREES(256)"}], + "tests/stages/gh182-loadguardrange.xml": [{"function":"cliServo","verdict":"AGREES(256)"}], + "tests/stages/gh1883-quotientreturn-x64.xml": [{"function":"srem_float","verdict":"AGREES(252)"},{"function":"pick","verdict":"AGREES(252)"},{"function":"scale","verdict":"AGREES(252)"},{"function":"store_rem","verdict":"AGREES(252)"},{"function":"rem_double","verdict":"AGREES(253)"},{"function":"xmm1_only","verdict":"AGREES(253)"}], + "tests/stages/gh1916-stackpadarg-x86.xml": [{"function":"k7","verdict":"AGREES(256)"},{"function":"kc","verdict":"AGREES(256)"},{"function":"kp","verdict":"AGREES(256)"},{"function":"kl","verdict":"AGREES(256)"}], + "tests/stages/gh1922-declared-caller-readarg-thumb.xml": [{"function":"copy_profile","verdict":"AGREES(256)"},{"function":"burst","verdict":"AGREES(256)"},{"function":"one","verdict":"AGREES(256)"}], + "tests/stages/gh1922-pushpad-caller-readarg-thumb.xml": [{"function":"send_pkt","verdict":"AGREES(256)"},{"function":"send4","verdict":"AGREES(256)"},{"function":"vsend","verdict":"DIFFERS(call at 0x100be to 0x10000)"},{"function":"vsendz","verdict":"DIFFERS(call at 0x100f2 to 0x10000)"}], + "tests/stages/gh1951-avr-rcallwrap.xml": [{"function":"FUN_0","verdict":"DIVERGES(synthesized-call)"}], + "tests/stages/gh271-x86-maxlen-nop.xml": [{"function":"f","verdict":"AGREES(194)"}], + "tests/stages/gh275-spillargtrial.xml": [{"function":"packed_two_atan2","verdict":"UNKNOWN(unsupported-op)"},{"function":"packed_two_atan2","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/gh2786-unaryspacing.xml": [{"function":"FUN_00000000","verdict":"AGREES(256)"}], + "tests/stages/gh403-funcboundflow-cfg.xml": [{"function":"branchcut","verdict":"UNKNOWN(unsupported-op)"},{"function":"loopcut","verdict":"UNKNOWN(unsupported-op)"},{"function":"branchcut","verdict":"AGREES(256)"},{"function":"loopcut","verdict":"AGREES(256)"}], + "tests/stages/gh468-nulterminator.xml": [{"function":"canary_check","verdict":"AGREES(256)"},{"function":"canary_check","verdict":"AGREES(256)"},{"function":"pad_after","verdict":"AGREES(256)"},{"function":"pad_after","verdict":"AGREES(256)"},{"function":"gap_zero","verdict":"AGREES(256)"},{"function":"gap_zero","verdict":"AGREES(256)"},{"function":"pad_zero","verdict":"AGREES(256)"},{"function":"pad_zero","verdict":"AGREES(256)"},{"function":"read_later","verdict":"AGREES(256)"},{"function":"read_later","verdict":"AGREES(256)"},{"function":"read_direct","verdict":"UNKNOWN(budget)"},{"function":"read_direct","verdict":"UNKNOWN(budget)"},{"function":"nonzero","verdict":"AGREES(256)"},{"function":"nonzero","verdict":"AGREES(256)"},{"function":"wide_elem","verdict":"AGREES(256)"},{"function":"wide_elem","verdict":"AGREES(256)"},{"function":"wide_zero","verdict":"AGREES(256)"},{"function":"wide_zero","verdict":"AGREES(256)"},{"function":"addr_taken","verdict":"AGREES(256)"},{"function":"addr_taken","verdict":"AGREES(256)"},{"function":"wide_str","verdict":"AGREES(256)"},{"function":"wide_str","verdict":"AGREES(256)"},{"function":"two_literals","verdict":"AGREES(256)"},{"function":"two_literals","verdict":"AGREES(256)"},{"function":"struct_field","verdict":"AGREES(256)"},{"function":"struct_field","verdict":"AGREES(256)"}], + "tests/stages/gh4788-v850-bcond-disp17.xml": [], + "tests/stages/gh510-phiopflags.xml": [{"function":"scan_list","verdict":"AGREES(2)"}], + "tests/stages/gh558-arraynotation.xml": [{"function":"foo","verdict":"AGREES(12)"},{"function":"foo","verdict":"AGREES(12)"}], + "tests/stages/gh558-compareform.xml": [{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/gh5897-arm-cpy-mov.xml": [], + "tests/stages/gh6389-8085-undoc.xml": [], + "tests/stages/gh6882-sparcstructret.xml": [{"function":"p","verdict":"UNKNOWN(unsupported-op)"},{"function":"p","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/gh6904-ppc-e500-concat44.xml": [{"function":"some_funcptr_func","verdict":"AGREES(256)"}], + "tests/stages/gh6930-inferfuncentry.xml": [{"function":"evhttp_send_reply_chunk_with_cb","verdict":"AGREES(256)"}], + "tests/stages/gh6990-returnpair.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/gh7139-x86-16-disp16-signed.xml": [], + "tests/stages/gh7190-ovlesssimplify.xml": [{"function":"FUN_00000000","verdict":"AGREES(94)"}], + "tests/stages/gh7418-x86-call-rel16-mask.xml": [], + "tests/stages/gh7451-riscvzfaflis.xml": [], + "tests/stages/gh7890-arm-vcvt.xml": [{"function":"func","verdict":"AGREES(256)"}], + "tests/stages/gh8017-stackprobeloop.xml": [{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/gh829-varargforward-a64.xml": [{"function":"c2","verdict":"AGREES(256)"},{"function":"e3","verdict":"AGREES(256)"}], + "tests/stages/gh829-varargforward-x86.xml": [{"function":"d2","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"d5","verdict":"AGREES(256)"},{"function":"d3","verdict":"AGREES(256)"}], + "tests/stages/gh831-riscv-fpmove.xml": [{"function":"e13","verdict":"AGREES(256)"},{"function":"dbits","verdict":"AGREES(256)"},{"function":"fwplus","verdict":"AGREES(256)"},{"function":"cvtw","verdict":"AGREES(256)"},{"function":"cvtwu","verdict":"AGREES(256)"},{"function":"cvtws","verdict":"AGREES(256)"},{"function":"cvtwus","verdict":"AGREES(256)"}], + "tests/stages/gh831-riscv32-fpmove.xml": [{"function":"fbits","verdict":"AGREES(256)"},{"function":"fwplus","verdict":"AGREES(256)"},{"function":"cvtcall","verdict":"AGREES(256)"},{"function":"cvtwu","verdict":"AGREES(256)"},{"function":"cvtws","verdict":"AGREES(256)"},{"function":"cvtwus","verdict":"AGREES(256)"}], + "tests/stages/gh839-reloadarg-a64.xml": [{"function":"fa1","verdict":"AGREES(256)"},{"function":"fa2","verdict":"AGREES(256)"},{"function":"fa3","verdict":"AGREES(256)"},{"function":"fa4","verdict":"AGREES(256)"}], + "tests/stages/gh839-reloadarg.xml": [{"function":"a2","verdict":"AGREES(256)"},{"function":"a3","verdict":"AGREES(256)"},{"function":"a4","verdict":"AGREES(256)"},{"function":"sp6","verdict":"AGREES(256)"},{"function":"a5","verdict":"AGREES(256)"},{"function":"a6","verdict":"AGREES(256)"},{"function":"fa1","verdict":"AGREES(256)"},{"function":"fa2","verdict":"AGREES(256)"},{"function":"fa3","verdict":"AGREES(256)"},{"function":"fa4","verdict":"AGREES(256)"},{"function":"f1","verdict":"AGREES(256)"},{"function":"f4","verdict":"AGREES(256)"}], + "tests/stages/gh8391-arm-thumb-mrrc.xml": [], + "tests/stages/gh840-varargbits-a64.xml": [{"function":"b2","verdict":"AGREES(256)"},{"function":"b2z","verdict":"AGREES(256)"},{"function":"c1","verdict":"AGREES(256)"},{"function":"k1","verdict":"AGREES(256)"}], + "tests/stages/gh840-varargbits-x86.xml": [{"function":"b2","verdict":"AGREES(256)"},{"function":"b2g","verdict":"AGREES(256)"},{"function":"c1","verdict":"AGREES(256)"},{"function":"k1","verdict":"AGREES(256)"}], + "tests/stages/gh841-varargsharedfloat-ppc.xml": [{"function":"a9","verdict":"AGREES(256)"},{"function":"a7","verdict":"AGREES(256)"},{"function":"a5","verdict":"AGREES(256)"},{"function":"a9","verdict":"AGREES(256)"},{"function":"a7","verdict":"AGREES(256)"},{"function":"a5","verdict":"AGREES(256)"},{"function":"b1","verdict":"AGREES(256)"},{"function":"b2","verdict":"AGREES(256)"},{"function":"p1","verdict":"AGREES(256)"},{"function":"p4","verdict":"AGREES(256)"},{"function":"a9_o2","verdict":"AGREES(256)"},{"function":"a7_o2","verdict":"AGREES(256)"},{"function":"p1_o2","verdict":"AGREES(256)"},{"function":"p4_o2","verdict":"AGREES(256)"}], + "tests/stages/gh8456-arm-mrs-banked.xml": [], + "tests/stages/gh8467-dynamichashmax.xml": [{"function":"FUN_128d0","verdict":"AGREES(256)"}], + "tests/stages/gh847-zerocallregs.xml": [{"function":"put","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"setg","verdict":"AGREES(256)"},{"function":"zero","verdict":"AGREES(256)"},{"function":"addg","verdict":"AGREES(256)"},{"function":"scaleg","verdict":"AGREES(256)"},{"function":"zpair","verdict":"AGREES(256)"}], + "tests/stages/gh8471-thumbfuncptr.xml": [{"function":"call_fn_through_reference","verdict":"AGREES(256)"}], + "tests/stages/gh8500-stackalias.xml": [{"function":"identity","verdict":"AGREES(256)"},{"function":"identity","verdict":"AGREES(256)"}], + "tests/stages/gh854-hiddenretarg-a64.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f2","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"g2","verdict":"AGREES(256)"},{"function":"use","verdict":"AGREES(256)"},{"function":"use2","verdict":"AGREES(256)"},{"function":"cursor","verdict":"AGREES(256)"},{"function":"call_helper","verdict":"AGREES(256)"},{"function":"call_cnt","verdict":"AGREES(256)"},{"function":"phibuf","verdict":"AGREES(256)"}], + "tests/stages/gh854-hiddenretarg-a64apple.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"use","verdict":"AGREES(256)"}], + "tests/stages/gh854-hiddenretarg-a64win.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"use","verdict":"AGREES(256)"}], + "tests/stages/gh8724-arraystride.xml": [{"function":"test","verdict":"AGREES(16)"},{"function":"test","verdict":"AGREES(16)"}], + "tests/stages/gh873-zerofillreturn-a64.xml": [{"function":"scale","verdict":"AGREES(256)"},{"function":"zero","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"pair","verdict":"AGREES(256)"},{"function":"add2","verdict":"AGREES(256)"},{"function":"comb","verdict":"AGREES(256)"},{"function":"gscale","verdict":"AGREES(256)"},{"function":"gzero","verdict":"AGREES(256)"},{"function":"ins0","verdict":"AGREES(256)"}], + "tests/stages/gh876-varargupper-x86.xml": [{"function":"d4","verdict":"AGREES(256)"},{"function":"du","verdict":"AGREES(256)"},{"function":"d3","verdict":"AGREES(256)"},{"function":"c4","verdict":"AGREES(256)"},{"function":"w4","verdict":"AGREES(256)"},{"function":"u5","verdict":"AGREES(256)"},{"function":"u8","verdict":"AGREES(256)"},{"function":"c5","verdict":"AGREES(256)"},{"function":"dl","verdict":"AGREES(256)"}], + "tests/stages/gh8777-flagcompare-sborrow.xml": [{"function":"FUN_0","verdict":"DIFFERS(memory at exit)"}], + "tests/stages/gh8790-x86-prefetch-regform.xml": [], + "tests/stages/gh8817-v850indbranch.xml": [{"function":"tjmp","verdict":"AGREES(256)"},{"function":"tjmp","verdict":"AGREES(256)"}], + "tests/stages/gh8844-avr-rjmpwrap.xml": [{"function":"FUN_0","verdict":"AGREES(256)"}], + "tests/stages/gh8913-addcarrychain.xml": [{"function":"gh8913","verdict":"AGREES(256)"}], + "tests/stages/gh9001-hcs12brn.xml": [], + "tests/stages/gh9184-x86-fma-ymm256.xml": [{"function":"dot8_fma","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/gh9191-switchmodbound.xml": [{"function":"jmpmod","verdict":"AGREES(256)"},{"function":"jmpmod","verdict":"AGREES(256)"}], + "tests/stages/gh9203-condexe-loopcopy.xml": [{"function":"FUN_0","verdict":"AGREES(256)"}], + "tests/stages/gh9218-inputvarnodeadjust.xml": [{"function":"FUN_0","verdict":"AGREES(193)"}], + "tests/stages/gh9230-memsetseq.xml": [{"function":"foo1","verdict":"AGREES(256)"},{"function":"foo1","verdict":"AGREES(256)"}], + "tests/stages/ghangr-1after909-doit-73591e.xml": [{"function":"doit","verdict":"AGREES(255)"},{"function":"doit","verdict":"AGREES(255)"}], + "tests/stages/ghangr-call-argument-extensions.xml": [{"function":"pass_signed","verdict":"AGREES(256)"},{"function":"pass_signed","verdict":"AGREES(256)"},{"function":"pass_signed","verdict":"AGREES(256)"},{"function":"keep_signed","verdict":"AGREES(256)"}], + "tests/stages/ghangr-call-return-variable-folding-dcde82.xml": [{"function":"target","verdict":"AGREES(256)"},{"function":"target","verdict":"AGREES(256)"}], + "tests/stages/ghangr-condfold-newbury.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghangr-condfold-ruleb.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghangr-condfold.xml": [{"function":"cf","verdict":"AGREES(256)"},{"function":"cf","verdict":"AGREES(256)"}], + "tests/stages/ghangr-dd-argmatch-to-argument-noea-9e6e8b.xml": [{"function":"argmatch_to_argument","verdict":"AGREES(63)"},{"function":"argmatch_to_argument","verdict":"AGREES(63)"}], + "tests/stages/ghangr-dwarf-namespaces.xml": [{"function":"direct_left","verdict":"AGREES(256)"},{"function":"direct_nested","verdict":"AGREES(256)"},{"function":"direct_right","verdict":"AGREES(256)"},{"function":"direct_global","verdict":"AGREES(256)"},{"function":"direct_shadow","verdict":"AGREES(256)"},{"function":"direct_left","verdict":"AGREES(256)"},{"function":"direct_nested","verdict":"AGREES(256)"},{"function":"direct_right","verdict":"AGREES(256)"},{"function":"direct_global","verdict":"AGREES(256)"},{"function":"get_target","verdict":"AGREES(256)"},{"function":"direct_target","verdict":"AGREES(256)"}], + "tests/stages/ghangr-earlyreturn.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghangr-function-pointer-namespaces.xml": [{"function":"foreign_address","verdict":"AGREES(256)"},{"function":"nested_address","verdict":"AGREES(256)"},{"function":"right_address","verdict":"AGREES(256)"},{"function":"global_shadow","verdict":"AGREES(256)"},{"function":"scope_shadow","verdict":"AGREES(256)"},{"function":"left::same_address","verdict":"AGREES(256)"},{"function":"right::cross_address","verdict":"AGREES(256)"},{"function":"left::same_address","verdict":"AGREES(256)"},{"function":"global_shadow","verdict":"AGREES(256)"},{"function":"interior_address","verdict":"AGREES(256)"},{"function":"data_address","verdict":"AGREES(256)"},{"function":"interior_address","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-aarch64-divide.xml": [{"function":"guarded_quotient","verdict":"AGREES(256)"},{"function":"guarded_quotient","verdict":"AGREES(256)"},{"function":"raw_quotient","verdict":"AGREES(256)"},{"function":"bounds_control","verdict":"UNKNOWN(unsupported-op)"},{"function":"application_guard","verdict":"AGREES(250)"},{"function":"mixed_panics","verdict":"AGREES(256)"},{"function":"abi_quotient","verdict":"AGREES(250)"}], + "tests/stages/ghangr-go-aarch64-stack-stride.xml": [{"function":"TwoSpills","verdict":"AGREES(256)"},{"function":"LastRegister","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-aarch64-stackpop.xml": [{"function":"recursive","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-abi0-model.xml": [{"function":"main.store","verdict":"AGREES(256)"},{"function":"main.callStore","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.store","verdict":"AGREES(256)"},{"function":"main.callStore","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.abi0","verdict":"AGREES(256)"},{"function":"runtime.write.abi0","verdict":"AGREES(256)"},{"function":"runtime.sigtramp","verdict":"AGREES(256)"},{"function":"runtime.gogo.abi0","verdict":"AGREES(256)"},{"function":"runtime.exitThread.abi0","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-go-amd64-divide-control.xml": [{"function":"guarded_quotient","verdict":"UNKNOWN(unsupported-op)"},{"function":"guarded_quotient","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-arm64-dwarf-result-plain.xml": [{"function":"main.Rise","verdict":"AGREES(256)"},{"function":"main.Rise","verdict":"AGREES(256)"},{"function":"main.Fall","verdict":"AGREES(256)"},{"function":"main.RiseWide","verdict":"AGREES(256)"},{"function":"main.FallWide","verdict":"AGREES(256)"},{"function":"main.Rise","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-arm64-dwarf-result.xml": [{"function":"main.Rise","verdict":"AGREES(256)"},{"function":"main.Rise","verdict":"AGREES(256)"},{"function":"main.Fall","verdict":"AGREES(256)"},{"function":"main.RiseWide","verdict":"AGREES(256)"},{"function":"main.FallWide","verdict":"AGREES(256)"},{"function":"main.Rise","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-array-referent.xml": [{"function":"main.Read","verdict":"AGREES(256)"},{"function":"main.Write","verdict":"AGREES(256)"},{"function":"main.ReadWord","verdict":"AGREES(256)"},{"function":"main.Indirect","verdict":"AGREES(256)"},{"function":"main.PointerValue","verdict":"AGREES(256)"},{"function":"main.TruePointerLoad","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-byte-extract.xml": [{"function":"combine","verdict":"AGREES(256)"},{"function":"write_pair","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-byte-views.xml": [{"function":"main.multiResult","verdict":"AGREES(256)"},{"function":"main.multiResult","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-dwarf-string-inputs.xml": [{"function":"main.stringLen","verdict":"AGREES(256)"},{"function":"main.stringIndex","verdict":"AGREES(256)"},{"function":"main.twoStringBits","verdict":"AGREES(256)"},{"function":"main.stringLen","verdict":"AGREES(256)"},{"function":"main.stringBits","verdict":"AGREES(256)"},{"function":"main.stringCount","verdict":"AGREES(13)"},{"function":"main.shiftedString","verdict":"AGREES(256)"},{"function":"main.rawStringWords","verdict":"AGREES(256)"},{"function":"main.stringWrongOrder","verdict":"AGREES(256)"},{"function":"main.stringShortPiece","verdict":"AGREES(256)"},{"function":"main.stringLookalike","verdict":"AGREES(256)"},{"function":"main.stringNameCollision","verdict":"AGREES(256)"},{"function":"main.stringIndex","verdict":"AGREES(256)"},{"function":"main.forwardString","verdict":"AGREES(256)"},{"function":"main.forwardString","verdict":"AGREES(256)"},{"function":"main.twoStringBits","verdict":"AGREES(256)"},{"function":"main.shiftedTwoStrings","verdict":"AGREES(256)"},{"function":"main.twoStringWrongOrder","verdict":"AGREES(256)"},{"function":"main.twoStringShortSecond","verdict":"AGREES(256)"},{"function":"main.twoStringWrongKind","verdict":"AGREES(256)"},{"function":"main.twoStringCollision","verdict":"AGREES(256)"},{"function":"main.threeStringPairs","verdict":"AGREES(256)"},{"function":"main.twoStringForward","verdict":"AGREES(256)"},{"function":"main.twoStringForward","verdict":"AGREES(256)"},{"function":"main.twoStringBits","verdict":"AGREES(256)"},{"function":"main.stringLen","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-extensions.xml": [{"function":"index","verdict":"AGREES(256)"},{"function":"sign_scale","verdict":"AGREES(256)"},{"function":"zero_scale","verdict":"AGREES(256)"},{"function":"less_delta","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-mcall-resumption.xml": [{"function":"main.yield","verdict":"AGREES(256)"},{"function":"main.stop","verdict":"AGREES(256)"},{"function":"main.mcall","verdict":"AGREES(256)"},{"function":"main.yield","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"main.yield","verdict":"UNKNOWN(noreturn-unverified)"}], + "tests/stages/ghangr-go-pair-results.xml": [{"function":"main.pair","verdict":"AGREES(256)"},{"function":"main.pair","verdict":"AGREES(256)"},{"function":"main.unsignedPair","verdict":"AGREES(256)"},{"function":"main.consume","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.first","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.pair","verdict":"AGREES(256)"},{"function":"main.zeroPair","verdict":"AGREES(256)"},{"function":"main.highPair","verdict":"AGREES(256)"},{"function":"main.forward","verdict":"AGREES(256)"},{"function":"main.check","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.forward","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.modernForward","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.consume","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.Retype","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.MergeRetype","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.Retype","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-go-paniccheck-return.xml": [{"function":"runtime.panicshift","verdict":"AGREES(256)"},{"function":"runtime.panicCheck1","verdict":"AGREES(256)"},{"function":"runtime.panicshift","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-pointer-arithmetic-32.xml": [{"function":"load_offset","verdict":"AGREES(256)"},{"function":"store_offset","verdict":"AGREES(256)"},{"function":"return_offset","verdict":"AGREES(256)"},{"function":"load_dynamic","verdict":"AGREES(256)"},{"function":"store_dynamic","verdict":"AGREES(256)"},{"function":"return_dynamic","verdict":"AGREES(256)"},{"function":"return_negative","verdict":"AGREES(256)"},{"function":"integer_address","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-pointer-arithmetic-64.xml": [{"function":"load_offset","verdict":"AGREES(256)"},{"function":"store_offset","verdict":"AGREES(256)"},{"function":"return_offset","verdict":"AGREES(256)"},{"function":"load_dynamic","verdict":"AGREES(256)"},{"function":"store_dynamic","verdict":"AGREES(256)"},{"function":"return_dynamic","verdict":"AGREES(256)"},{"function":"return_negative","verdict":"AGREES(256)"},{"function":"integer_address","verdict":"AGREES(256)"},{"function":"before_a0","verdict":"AGREES(256)"},{"function":"before_a4","verdict":"AGREES(256)"},{"function":"at_a8","verdict":"AGREES(256)"},{"function":"at_b16","verdict":"AGREES(256)"},{"function":"before_a4","verdict":"AGREES(256)"},{"function":"before_a4","verdict":"AGREES(256)"},{"function":"before_a4","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-pointer-receiver.xml": [{"function":"main.(*Meter).Apply","verdict":"AGREES(256)"},{"function":"main.Forward","verdict":"AGREES(256)"},{"function":"main.ForwardShadow","verdict":"AGREES(256)"},{"function":"main.(*Meter).Pretend","verdict":"AGREES(256)"},{"function":"main.Apply","verdict":"AGREES(256)"},{"function":"main.Forward","verdict":"AGREES(256)"},{"function":"main.(*Meter).Apply","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-runtime-types-386.xml": [{"function":"main.createWord","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.createWord","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.create","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-go-store-value.xml": [{"function":"signed8","verdict":"AGREES(256)"},{"function":"unsigned16","verdict":"AGREES(256)"},{"function":"signed_xor32","verdict":"AGREES(256)"},{"function":"side_effect","verdict":"AGREES(256)"},{"function":"array_store","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-string-pointers.xml": [{"function":"plain","verdict":"UNKNOWN(unsupported-op)"},{"function":"escaped","verdict":"UNKNOWN(unsupported-op)"},{"function":"unicode","verdict":"UNKNOWN(unsupported-op)"},{"function":"plain","verdict":"UNKNOWN(unsupported-op)"},{"function":"escaped","verdict":"UNKNOWN(unsupported-op)"},{"function":"unicode","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-go-string-projection.xml": [{"function":"main.ByteOr","verdict":"AGREES(256)"},{"function":"main.ByteOr","verdict":"AGREES(256)"},{"function":"main.Forward","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.FromPrefix","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.FromOther","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.Length","verdict":"AGREES(256)"},{"function":"main.HeaderData","verdict":"AGREES(256)"},{"function":"main.UnsafeFirst","verdict":"AGREES(256)"},{"function":"main.ExplicitWords","verdict":"AGREES(256)"},{"function":"main.ByteOr","verdict":"AGREES(256)"},{"function":"main.ByteOr","verdict":"AGREES(256)"},{"function":"main.Forward","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.ByteOr","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go-zero-interface-return.xml": [{"function":"select_words","verdict":"AGREES(256)"},{"function":"keep_low","verdict":"AGREES(256)"},{"function":"one_low","verdict":"AGREES(256)"},{"function":"select_words","verdict":"AGREES(256)"}], + "tests/stages/ghangr-go126-runtime-types-386.xml": [{"function":"main.createWord","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.createWord","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.create","verdict":"UNKNOWN(uninitialized-local)"}], + "tests/stages/ghangr-godwarfsig.xml": [{"function":"main.fromWord","verdict":"AGREES(256)"},{"function":"main.narrow","verdict":"AGREES(256)"},{"function":"main.badReg","verdict":"AGREES(256)"},{"function":"main.fromWord","verdict":"AGREES(256)"},{"function":"main.narrow","verdict":"AGREES(256)"},{"function":"main.boolNot","verdict":"AGREES(256)"},{"function":"main.mix","verdict":"AGREES(256)"},{"function":"main.scale","verdict":"AGREES(256)"},{"function":"main.callIdentity","verdict":"AGREES(256)"},{"function":"main.abstractIdentity","verdict":"AGREES(256)"},{"function":"main.badReg","verdict":"AGREES(256)"},{"function":"main.identity","verdict":"AGREES(256)"},{"function":"main.identity","verdict":"AGREES(256)"},{"function":"main.wrongRegister","verdict":"AGREES(256)"},{"function":"main.identity","verdict":"AGREES(256)"},{"function":"main.identity","verdict":"AGREES(256)"},{"function":"main.wrongRegister","verdict":"AGREES(256)"},{"function":"main.resultRange","verdict":"AGREES(256)"},{"function":"main.recvStatus","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.recvStatus","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.discardStatus","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.otherSlot","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.widerElement","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.otherCallee","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.recvStatus","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-gooutput.xml": [{"function":"add","verdict":"AGREES(256)"},{"function":"read_at","verdict":"AGREES(256)"},{"function":"from_word","verdict":"AGREES(256)"},{"function":"bits","verdict":"AGREES(256)"},{"function":"bottom","verdict":"AGREES(90)"},{"function":"fallthroughs","verdict":"AGREES(256)"},{"function":"add","verdict":"AGREES(256)"}], + "tests/stages/ghangr-highslice-guard.xml": [{"function":"narrow_guard","verdict":"AGREES(256)"},{"function":"narrow_guard","verdict":"AGREES(256)"},{"function":"wide_guard","verdict":"AGREES(256)"},{"function":"explicit_zext","verdict":"AGREES(256)"},{"function":"byte_guard","verdict":"AGREES(256)"},{"function":"word_guard","verdict":"AGREES(256)"},{"function":"signed_guard","verdict":"AGREES(256)"}], + "tests/stages/ghangr-ifelseflatten.xml": [{"function":"el","verdict":"AGREES(198)"},{"function":"el","verdict":"AGREES(198)"}], + "tests/stages/ghangr-immutable-got-call-graph.xml": [{"function":"through_got","verdict":"AGREES(256)"},{"function":"through_mutable","verdict":"DIFFERS(call at 0x11f6 to ?)"}], + "tests/stages/ghangr-incorrect-duplication-chcon-a0e113.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/ghangr-integer-field-extract.xml": [{"function":"signed_int8","verdict":"AGREES(256)"},{"function":"signed_int16","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"},{"function":"shift32","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"},{"function":"signed_int8","verdict":"AGREES(256)"},{"function":"signed_int16","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"},{"function":"shift32","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"},{"function":"signed_int8","verdict":"AGREES(256)"},{"function":"signed_int16","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"},{"function":"shift32","verdict":"AGREES(256)"},{"function":"signed_int32_wide","verdict":"AGREES(256)"}], + "tests/stages/ghangr-ite-region-converter-missing-5db28e.xml": [{"function":"authenticate","verdict":"AGREES(256)"},{"function":"authenticate","verdict":"AGREES(256)"}], + "tests/stages/ghangr-iteexpr.xml": [{"function":"expr_arm","verdict":"AGREES(256)"},{"function":"expr_arm","verdict":"AGREES(256)"}], + "tests/stages/ghangr-iteregion.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/ghangr-joined-callback-return.xml": [{"function":"make_pair","verdict":"AGREES(256)"},{"function":"first","verdict":"AGREES(256)"},{"function":"second","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"forward","verdict":"AGREES(256)"},{"function":"narrow_second","verdict":"AGREES(256)"},{"function":"scalar","verdict":"AGREES(256)"},{"function":"invoke_void","verdict":"AGREES(256)"}], + "tests/stages/ghangr-loweredswitch-mv.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-loweredswitch.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-missing-function-call-1101b1.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-morton-my-message-callback-bfd2fa.xml": [{"function":"my_message_callback","verdict":"AGREES(256)"},{"function":"my_message_callback","verdict":"AGREES(256)"}], + "tests/stages/ghangr-noreturn-error.xml": [{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/ghangr-noreturn_extern.xml": [{"function":"victim","verdict":"AGREES(256)"},{"function":"victim","verdict":"AGREES(256)"}], + "tests/stages/ghangr-optimized-memcpy-6301a9.xml": [{"function":"memcpy_opt","verdict":"DIFFERS(call 1 at 0x42cd1c to 0x42ce38)"},{"function":"memcpy_opt","verdict":"UNKNOWN(budget)"},{"function":"memcpy_opt","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-returndup.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-array-address.xml": [{"function":"address_i64_s","verdict":"AGREES(256)"},{"function":"address_pointers_s","verdict":"AGREES(256)"},{"function":"nested_address_u","verdict":"AGREES(256)"},{"function":"callback_address","verdict":"AGREES(256)"},{"function":"wrap_unsigned","verdict":"AGREES(256)"},{"function":"signed_address","verdict":"AGREES(256)"},{"function":"left_address","verdict":"AGREES(256)"},{"function":"address_i64_s","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-array-decay.xml": [{"function":"field_i64","verdict":"AGREES(256)"},{"function":"whole_flags","verdict":"AGREES(256)"},{"function":"end_pointers","verdict":"AGREES(256)"},{"function":"erased_i32","verdict":"AGREES(256)"},{"function":"retyped_i64","verdict":"AGREES(256)"},{"function":"array_i32","verdict":"AGREES(256)"},{"function":"stored_i32","verdict":"AGREES(256)"},{"function":"passed_counted","verdict":"AGREES(256)"},{"function":"field_i64","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-array-index.xml": [{"function":"load_i64_s","verdict":"AGREES(256)"},{"function":"store_u8_u","verdict":"AGREES(256)"},{"function":"array_address_s","verdict":"AGREES(256)"},{"function":"nested_load_s","verdict":"AGREES(256)"},{"function":"callback_store","verdict":"AGREES(256)"},{"function":"right_context","verdict":"AGREES(256)"},{"function":"signed_context","verdict":"AGREES(256)"},{"function":"left_context","verdict":"AGREES(256)"},{"function":"constant_load","verdict":"AGREES(256)"},{"function":"load_i64_s","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-array-zero.xml": [{"function":"zero_unsigned","verdict":"AGREES(256)"},{"function":"zero_unsigned","verdict":"AGREES(256)"},{"function":"zero_signed","verdict":"AGREES(256)"},{"function":"zero_field","verdict":"AGREES(256)"},{"function":"zero_second","verdict":"AGREES(256)"},{"function":"zero_index","verdict":"AGREES(256)"},{"function":"zero_callback","verdict":"AGREES(256)"},{"function":"zero_bytes","verdict":"AGREES(256)"},{"function":"zero_unsigned","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-boolean-conversions.xml": [{"function":"as_unsigned8","verdict":"AGREES(256)"},{"function":"as_signed8","verdict":"AGREES(256)"},{"function":"masked8","verdict":"AGREES(256)"},{"function":"call_unsigned","verdict":"AGREES(256)"},{"function":"call_signed","verdict":"AGREES(256)"},{"function":"as_unsigned8","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-boolean-expressions.xml": [{"function":"loop_xor","verdict":"AGREES(92)"},{"function":"loop_and","verdict":"AGREES(92)"},{"function":"loop_or","verdict":"AGREES(92)"},{"function":"loop_eager","verdict":"AGREES(92)"},{"function":"loop_and_call","verdict":"AGREES(92)"},{"function":"loop_or_call","verdict":"AGREES(92)"},{"function":"loop_store","verdict":"AGREES(79)"},{"function":"loop_xor","verdict":"AGREES(92)"}], + "tests/stages/ghangr-rust-empty-match.xml": [{"function":"empty_case","verdict":"AGREES(256)"},{"function":"empty_default","verdict":"AGREES(256)"},{"function":"empty_shared","verdict":"AGREES(256)"},{"function":"empty_loop","verdict":"AGREES(85)"},{"function":"loop_break_control","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-rust-extensions.xml": [{"function":"sign_scale","verdict":"AGREES(256)"},{"function":"narrow_sum","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-function-address-namespaces.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"keyword_address","verdict":"AGREES(256)"},{"function":"const_address","verdict":"AGREES(256)"},{"function":"r17_probe::global_address","verdict":"AGREES(256)"},{"function":"global_shadow","verdict":"AGREES(256)"},{"function":"scope_shadow","verdict":"AGREES(256)"},{"function":"right::cross_address","verdict":"AGREES(256)"},{"function":"left::same_address","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-integer-conversions.xml": [{"function":"add8","verdict":"AGREES(256)"},{"function":"sub64","verdict":"AGREES(256)"},{"function":"mul32","verdict":"AGREES(256)"},{"function":"negate64","verdict":"AGREES(256)"},{"function":"mixed_add32","verdict":"AGREES(256)"},{"function":"as_unsigned8","verdict":"AGREES(256)"},{"function":"as_signed16","verdict":"AGREES(256)"},{"function":"inplace64","verdict":"AGREES(256)"},{"function":"call_unsigned","verdict":"AGREES(256)"},{"function":"negative_mask","verdict":"AGREES(256)"},{"function":"isolated_bit","verdict":"AGREES(256)"},{"function":"shift_again","verdict":"AGREES(256)"},{"function":"accumulate_calls","verdict":"AGREES(14)"},{"function":"mixed_sub_less","verdict":"AGREES(256)"},{"function":"mixed_sub_left","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-legacy-llvm.xml": [{"function":"std::rt::lang_start_internal::{{closure}}","verdict":"AGREES(256)"},{"function":"std::rt::lang_start_internal::{{closure}}","verdict":"AGREES(256)"},{"function":"demo::foo","verdict":"AGREES(256)"},{"function":"demo::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"demo::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"_ZN999bad17h0123456789abcdefE.llvm.9325873435131735662","verdict":"AGREES(256)"},{"function":"demo::keep","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-null-pointer.xml": [{"function":"null_pointer","verdict":"AGREES(256)"},{"function":"maybe_pointer","verdict":"AGREES(256)"},{"function":"pointer_is_null","verdict":"AGREES(256)"},{"function":"clear_pointer","verdict":"AGREES(251)"}], + "tests/stages/ghangr-rust-pointer-index.xml": [{"function":"load_i64_s","verdict":"AGREES(256)"},{"function":"store_i32_s","verdict":"AGREES(256)"},{"function":"address_u16_u","verdict":"AGREES(256)"},{"function":"field_load","verdict":"AGREES(256)"},{"function":"callback_store","verdict":"AGREES(256)"},{"function":"logical_address","verdict":"AGREES(256)"},{"function":"signed_address","verdict":"AGREES(256)"},{"function":"load_i64_s","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-probestack.xml": [{"function":"probe_page","verdict":"AGREES(256)"},{"function":"probe_observes_r11","verdict":"DIFFERS(return)"},{"function":"probe_saved_rbp","verdict":"AGREES(256)"},{"function":"probe_page","verdict":"AGREES(256)"},{"function":"probe_tail","verdict":"AGREES(256)"},{"function":"probe_pages","verdict":"AGREES(256)"},{"function":"probe_observes_r11","verdict":"AGREES(256)"},{"function":"probe_zero","verdict":"AGREES(256)"},{"function":"probe_one","verdict":"AGREES(256)"},{"function":"probe_page_r11","verdict":"AGREES(256)"},{"function":"probe_plus_one","verdict":"AGREES(256)"},{"function":"probe_pages_r11","verdict":"AGREES(256)"},{"function":"probe_saved_rbp","verdict":"AGREES(256)"},{"function":"probe_return_slot","verdict":"AGREES(256)"},{"function":"probe_side_effect","verdict":"AGREES(256)"},{"function":"probe_observes_flags","verdict":"DIFFERS(return)"},{"function":"probe_unknown","verdict":"DIFFERS(return)"},{"function":"probe_buffer","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-signed-bytes.xml": [{"function":"byte_less","verdict":"AGREES(256)"},{"function":"byte_lesseq","verdict":"AGREES(256)"},{"function":"byte_shift","verdict":"AGREES(256)"},{"function":"byte_store","verdict":"AGREES(256)"},{"function":"byte_unsigned","verdict":"AGREES(256)"},{"function":"byte_loop_direct","verdict":"AGREES(16)"},{"function":"unsigned_loop","verdict":"AGREES(16)"},{"function":"unsigned_less64","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-store-value.xml": [{"function":"signed8","verdict":"AGREES(256)"},{"function":"unsigned16","verdict":"AGREES(256)"},{"function":"signed_xor32","verdict":"AGREES(256)"},{"function":"side_effect","verdict":"AGREES(256)"},{"function":"signed_plain64","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-store-width.xml": [{"function":"wide","verdict":"AGREES(256)"},{"function":"bytefield","verdict":"AGREES(256)"},{"function":"matched","verdict":"AGREES(256)"},{"function":"core::escape::escape_unicode","verdict":"DIFFERS(memory at exit)"}], + "tests/stages/ghangr-rust-uppercase-legacy-hash.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"},{"function":"demo::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"mixed::hAbCdE0123456789f","verdict":"AGREES(256)"},{"function":"member::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"lower::actual","verdict":"AGREES(256)"},{"function":"cpp_demo::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"cpp_ok::go","verdict":"AGREES(256)"},{"function":"llvm::hABCDEF0123456789","verdict":"AGREES(256)"},{"function":"simple::main","verdict":"AGREES(256)"},{"function":"Bar::foo","verdict":"AGREES(256)"},{"function":"lowerllvm::actual","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rust-userop.xml": [{"function":"read_port","verdict":"UNKNOWN(unsupported-op)"},{"function":"read_variable","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_port","verdict":"UNKNOWN(unsupported-op)"},{"function":"packed_abs","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-rustfmtargs.xml": [{"function":"decimal_lf","verdict":"AGREES(256)"},{"function":"reorder","verdict":"AGREES(256)"},{"function":"signed_lf","verdict":"AGREES(256)"},{"function":"reject_trait","verdict":"AGREES(256)"},{"function":"reject_clobber","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtconstructor.xml": [{"function":"r13_constructor_stderr","verdict":"AGREES(256)"},{"function":"r13_constructor_stderr","verdict":"AGREES(256)"},{"function":"r13_constructor_stdout","verdict":"AGREES(256)"},{"function":"r13_display_stderr","verdict":"AGREES(256)"},{"function":"r13_display_stdout","verdict":"AGREES(256)"},{"function":"r13_constructor_stderr","verdict":"AGREES(256)"},{"function":"r13_constructor_stderr","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtflags.xml": [{"function":"traits","verdict":"AGREES(256)"},{"function":"signed","verdict":"AGREES(256)"},{"function":"align","verdict":"AGREES(256)"},{"function":"debug_hex","verdict":"AGREES(256)"},{"function":"reorder","verdict":"AGREES(256)"},{"function":"dynamic","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghangr-rustfmtio.xml": [{"function":"write_unsigned","verdict":"AGREES(256)"},{"function":"write_signed","verdict":"AGREES(256)"},{"function":"write_flags","verdict":"AGREES(256)"},{"function":"write_literal","verdict":"AGREES(256)"},{"function":"write_empty","verdict":"AGREES(256)"},{"function":"write_string","verdict":"AGREES(256)"},{"function":"write_pair","verdict":"AGREES(256)"},{"function":"write_dynamic","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtliteral.xml": [{"function":"literal_lf","verdict":"AGREES(256)"},{"function":"literal_stderr","verdict":"AGREES(256)"},{"function":"reject_mutable","verdict":"AGREES(256)"},{"function":"reject_template","verdict":"AGREES(256)"},{"function":"scoped_stdout","verdict":"AGREES(256)"},{"function":"scoped_stderr","verdict":"AGREES(256)"},{"function":"scoped_other","verdict":"AGREES(256)"},{"function":"scoped_incomplete","verdict":"AGREES(256)"},{"function":"scoped_nested","verdict":"AGREES(256)"},{"function":"scoped_global","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtpanic.xml": [{"function":"panic_literal","verdict":"AGREES(256)"},{"function":"panic_decimal","verdict":"AGREES(256)"},{"function":"panic_literal","verdict":"AGREES(256)"},{"function":"panic_hex","verdict":"AGREES(256)"},{"function":"panic_reorder","verdict":"AGREES(256)"},{"function":"panic_narrow","verdict":"AGREES(256)"},{"function":"panic_forwarded","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtpieces.xml": [{"function":"pieces_literal","verdict":"AGREES(256)"},{"function":"pieces_u32","verdict":"AGREES(256)"},{"function":"pieces_literal","verdict":"AGREES(256)"},{"function":"pieces_empty","verdict":"AGREES(256)"},{"function":"pieces_pair","verdict":"AGREES(256)"},{"function":"pieces_narrow","verdict":"AGREES(256)"},{"function":"pieces_adjacent","verdict":"AGREES(256)"},{"function":"pieces_repeat","verdict":"AGREES(256)"},{"function":"pieces_flags","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtresult.xml": [{"function":"hex_width","verdict":"AGREES(256)"},{"function":"decimal","verdict":"AGREES(256)"},{"function":"reordered","verdict":"AGREES(256)"},{"function":"local","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtstr.xml": [{"function":"str_plain","verdict":"AGREES(256)"},{"function":"str_flags","verdict":"AGREES(256)"},{"function":"str_pair","verdict":"AGREES(256)"},{"function":"str_integer","verdict":"AGREES(256)"},{"function":"str_result","verdict":"AGREES(256)"},{"function":"str_panic","verdict":"AGREES(256)"},{"function":"str_stderr","verdict":"AGREES(256)"},{"function":"str_debug","verdict":"AGREES(256)"}], + "tests/stages/ghangr-rustfmtwrite.xml": [{"function":"write_unsigned","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_signed","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_flags","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_literal","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_empty","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_string","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_pair","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_custom","verdict":"AGREES(256)"}], + "tests/stages/ghangr-scalar-call-results.xml": [{"function":"wide_value","verdict":"AGREES(256)"},{"function":"narrow_bool","verdict":"AGREES(256)"},{"function":"wide_value","verdict":"AGREES(256)"},{"function":"narrow_bool","verdict":"AGREES(256)"},{"function":"narrow_bool","verdict":"AGREES(256)"},{"function":"narrow_bool","verdict":"AGREES(256)"}], + "tests/stages/ghangr-setlocale-rettype.xml": [{"function":"setlocale_null","verdict":"AGREES(256)"}], + "tests/stages/ghangr-switchmultipred-memmove.xml": [{"function":"memmove","verdict":"AGREES(16)"},{"function":"memmove","verdict":"AGREES(16)"}], + "tests/stages/ghangr-switchreturn.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghangr-tee-o2-tail-jumps-4a1f49.xml": [{"function":"setlocale_null_androidfix","verdict":"AGREES(256)"},{"function":"setlocale_null_androidfix","verdict":"AGREES(256)"}], + "tests/stages/ghangr-true-1804-dedup-ite-tail-8a690c.xml": [{"function":"g","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/ghangr-who-condensing-opt-reversion-72e518.xml": [{"function":"cj","verdict":"UNKNOWN(budget)"},{"function":"cj","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghangr-x8664-cvs-863633.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghdec-branchflip-armswap.xml": [{"function":"armswap","verdict":"AGREES(256)"},{"function":"armswap","verdict":"AGREES(256)"}], + "tests/stages/ghdec-calloverlap.xml": [{"function":"f","verdict":"DIFFERS(unassigned)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghdec-callsitestackargs.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/ghdec-constspaceload.xml": [{"function":"neon_init","verdict":"AGREES(256)"}], + "tests/stages/ghdec-cspecprotos.xml": [{"function":"getfield","verdict":"AGREES(256)"},{"function":"addfield","verdict":"AGREES(256)"},{"function":"getfield","verdict":"AGREES(256)"},{"function":"addfield","verdict":"AGREES(256)"}], + "tests/stages/ghdec-fast-funcdisc.xml": [{"function":"sub_140001000","verdict":"AGREES(256)"}], + "tests/stages/ghdec-finalorder-entryfirst.xml": [{"function":"lines_differ","verdict":"AGREES(255)"}], + "tests/stages/ghdec-funcptralign.xml": [{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/ghdec-guardarm.xml": [{"function":"victim","verdict":"AGREES(256)"},{"function":"victim","verdict":"AGREES(256)"}], + "tests/stages/ghdec-indexaliasguard.xml": [{"function":"transform","verdict":"DIFFERS(memory at exit)"},{"function":"transform","verdict":"AGREES(29)"}], + "tests/stages/ghdec-inputtile-overlap.xml": [{"function":"rpl_fcntl","verdict":"AGREES(256)"}], + "tests/stages/ghdec-isamode-inject.xml": [{"function":"dispatch","verdict":"DIFFERS(unassigned)"}], + "tests/stages/ghdec-iteboolean.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghdec-itecondlist.xml": [{"function":"t","verdict":"AGREES(256)"}], + "tests/stages/ghdec-loopcondhoist.xml": [{"function":"victim","verdict":"AGREES(85)"},{"function":"victim","verdict":"AGREES(85)"}], + "tests/stages/ghdec-opcode-seam.xml": [{"function":"shift_undistribute","verdict":"AGREES(256)"}], + "tests/stages/ghdec-orchain.xml": [{"function":"t","verdict":"AGREES(256)"}], + "tests/stages/ghdec-paramcopyhoist.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/ghdec-peimportcall.xml": [{"function":"entry","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"bail","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"_call_slots","verdict":"AGREES(256)"}], + "tests/stages/ghdec-realtypes-pointee.xml": [{"function":"set_acl_fd","verdict":"AGREES(256)"},{"function":"acl_calc_mask","verdict":"AGREES(256)"},{"function":"set_acl_fd","verdict":"AGREES(256)"},{"function":"acl_calc_mask","verdict":"AGREES(256)"}], + "tests/stages/ghdec-returncopysplit.xml": [{"function":"get_hz","verdict":"AGREES(256)"},{"function":"get_hz","verdict":"AGREES(256)"}], + "tests/stages/ghdec-spacebase-unnamed.xml": [{"function":"scan_textfile","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/ghdec-stalejumptable.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/ghdec-subright.xml": [{"function":"put_u32_be","verdict":"AGREES(256)"},{"function":"mulhi_shift","verdict":"AGREES(256)"},{"function":"put_u32_be","verdict":"AGREES(256)"},{"function":"mulhi_shift","verdict":"AGREES(256)"}], + "tests/stages/ghdec-symbol-keyed-local-decls.xml": [{"function":"build_frame","verdict":"AGREES(256)"},{"function":"build_frame","verdict":"AGREES(256)"},{"function":"build_frame","verdict":"AGREES(256)"}], + "tests/stages/ghdec-undefname.xml": [{"function":"xstrcat","verdict":"AGREES(11)"},{"function":"set_qlen","verdict":"AGREES(256)"},{"function":"xstrcat","verdict":"AGREES(11)"},{"function":"set_qlen","verdict":"AGREES(256)"}], + "tests/stages/ghdec-unsigned-byte-vm-selector.xml": [{"function":"sub_12d0","verdict":"AGREES(256)"}], + "tests/stages/ghdec-whiledo-complex.xml": [{"function":"lookup_flag_data_by_name","verdict":"AGREES(256)"}], + "tests/stages/ghdec-zeroidiomuse.xml": [{"function":"feed","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-acleintrinsics.xml": [{"function":"barrier","verdict":"AGREES(256)"},{"function":"idle","verdict":"UNKNOWN(unsupported-op)"},{"function":"tag","verdict":"AGREES(256)"},{"function":"inc","verdict":"AGREES(256)"},{"function":"excl","verdict":"AGREES(256)"},{"function":"settag","verdict":"AGREES(256)"},{"function":"gettag","verdict":"AGREES(256)"},{"function":"alloc16","verdict":"AGREES(256)"},{"function":"store_other","verdict":"AGREES(256)"},{"function":"store_pair","verdict":"AGREES(256)"},{"function":"load_other","verdict":"AGREES(256)"},{"function":"add_off","verdict":"AGREES(256)"},{"function":"sub_off","verdict":"AGREES(256)"},{"function":"isb_one","verdict":"AGREES(256)"},{"function":"clear2","verdict":"AGREES(256)"},{"function":"barrier","verdict":"AGREES(256)"},{"function":"idle","verdict":"UNKNOWN(unsupported-op)"},{"function":"tag","verdict":"UNKNOWN(unsupported-op)"},{"function":"inc","verdict":"UNKNOWN(unsupported-op)"},{"function":"excl","verdict":"UNKNOWN(unsupported-op)"},{"function":"settag","verdict":"UNKNOWN(unsupported-op)"},{"function":"gettag","verdict":"UNKNOWN(unsupported-op)"},{"function":"alloc16","verdict":"UNKNOWN(unsupported-op)"},{"function":"store_other","verdict":"UNKNOWN(unsupported-op)"},{"function":"store_pair","verdict":"UNKNOWN(unsupported-op)"},{"function":"load_other","verdict":"UNKNOWN(unsupported-op)"},{"function":"add_off","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_off","verdict":"UNKNOWN(unsupported-op)"},{"function":"isb_one","verdict":"AGREES(256)"},{"function":"clear2","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-address-only-local.xml": [{"function":"read_escaped","verdict":"AGREES(256)"},{"function":"read_escaped","verdict":"AGREES(256)"}], + "tests/stages/kuna-address-split-local.xml": [{"function":"read_split","verdict":"AGREES(256)"}], + "tests/stages/kuna-addrtakenentry.xml": [{"function":"sub_140001040","verdict":"AGREES(256)"}], + "tests/stages/kuna-aggregatefields.xml": [{"function":"nested_first","verdict":"AGREES(256)"},{"function":"double_float","verdict":"AGREES(256)"},{"function":"quad_struct","verdict":"AGREES(256)"}], + "tests/stages/kuna-aif-slot-edges.xml": [{"function":"","verdict":"ERROR"}], + "tests/stages/kuna-aifbracket.xml": [], + "tests/stages/kuna-aifnoppad.xml": [], + "tests/stages/kuna-aifpoolslide.xml": [], + "tests/stages/kuna-aliasoverlap.xml": [{"function":"inside","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"indexed","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"before","verdict":"AGREES(256)"},{"function":"next","verdict":"AGREES(256)"},{"function":"splitstore","verdict":"AGREES(256)"},{"function":"splitother","verdict":"AGREES(256)"},{"function":"splitcall","verdict":"AGREES(256)"},{"function":"splitplain","verdict":"AGREES(256)"}], + "tests/stages/kuna-android-binder.xml": [{"function":"sub_4ac4","verdict":"AGREES(256)"},{"function":"org_example_ILevel_onTransact","verdict":"AGREES(256)"}], + "tests/stages/kuna-android-java-calls.xml": [{"function":"Java_demo_Bridge_cached__Ldemo_Player_2I","verdict":"AGREES(256)"},{"function":"Java_demo_Bridge_cached__Ldemo_Player_2I","verdict":"AGREES(256)"}], + "tests/stages/kuna-android-jni.xml": [{"function":"sub_48c0","verdict":"AGREES(256)"},{"function":"JNI_OnLoad","verdict":"AGREES(256)"},{"function":"Java_org_example_Bridge_countBytes","verdict":"AGREES(256)"}], + "tests/stages/kuna-argclobber-armreturn.xml": [{"function":"caller2","verdict":"AGREES(256)"},{"function":"caller2","verdict":"AGREES(256)"}], + "tests/stages/kuna-argclobber-forward.xml": [{"function":"caller4","verdict":"AGREES(256)"},{"function":"caller4","verdict":"AGREES(256)"}], + "tests/stages/kuna-argclobber-guards.xml": [{"function":"caller3","verdict":"AGREES(256)"},{"function":"caller3","verdict":"AGREES(256)"}], + "tests/stages/kuna-argclobber.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-argkeep.xml": [{"function":"k_one","verdict":"AGREES(256)"},{"function":"k_two","verdict":"AGREES(256)"},{"function":"k_three","verdict":"AGREES(256)"},{"function":"k_store","verdict":"AGREES(256)"},{"function":"k_some","verdict":"AGREES(256)"},{"function":"k_drop","verdict":"AGREES(256)"},{"function":"k_own","verdict":"AGREES(256)"},{"function":"k_spoil","verdict":"AGREES(256)"},{"function":"k_var","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-backward-interworking.xml": [{"function":"arm_caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-conditional-switch.xml": [{"function":"arm_switch_conditional","verdict":"AGREES(256)"},{"function":"arm_switch_unconditional","verdict":"AGREES(256)"},{"function":"arm_switch_addls","verdict":"AGREES(256)"},{"function":"arm_switch_frame","verdict":"AGREES(256)"},{"function":"arm_indirect_call","verdict":"AGREES(256)"},{"function":"arm_switch_conditional","verdict":"AGREES(256)"},{"function":"arm_switch_unconditional","verdict":"AGREES(256)"},{"function":"arm_switch_addls","verdict":"AGREES(256)"},{"function":"arm_switch_frame","verdict":"AGREES(256)"},{"function":"arm_indirect_call","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-constant-shift.xml": [{"function":"ShiftLeftTwo","verdict":"AGREES(256)"},{"function":"ShiftSigned","verdict":"AGREES(256)"},{"function":"ShiftArithmetic","verdict":"AGREES(256)"},{"function":"ShiftAndStore","verdict":"AGREES(256)"},{"function":"ShiftUnsigned","verdict":"AGREES(256)"},{"function":"ShiftLeftTwo","verdict":"AGREES(256)"},{"function":"ShiftSigned","verdict":"AGREES(256)"},{"function":"ShiftArithmetic","verdict":"AGREES(256)"},{"function":"ShiftAndStore","verdict":"AGREES(256)"},{"function":"ShiftUnsigned","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-coprocessor-selectors-be.xml": [{"function":"WriteRegion","verdict":"UNKNOWN(unsupported-op)"},{"function":"WriteSelectors","verdict":"UNKNOWN(unsupported-op)"},{"function":"ReadSelectors","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arm-coprocessor-selectors.xml": [{"function":"WriteRegion","verdict":"UNKNOWN(unsupported-op)"},{"function":"WriteSelectors","verdict":"UNKNOWN(unsupported-op)"},{"function":"ReadSelectors","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arm-cpsr-control.xml": [{"function":"mask_irq","verdict":"UNKNOWN(unsupported-op)"},{"function":"restore_irq","verdict":"UNKNOWN(unsupported-op)"},{"function":"immediate_irq","verdict":"UNKNOWN(unsupported-op)"},{"function":"control_flags","verdict":"UNKNOWN(unsupported-op)"},{"function":"immediate_flags","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arm-cpsr-ge.xml": [{"function":"ReadGEAfterSadd8","verdict":"UNKNOWN(unsupported-op)"},{"function":"RestoreGEThenSel","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arm-float-arguments.xml": [{"function":"show2","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-float-return.xml": [{"function":"raw_fixed","verdict":"AGREES(256)"},{"function":"raw_fixed","verdict":"AGREES(256)"},{"function":"raw_fixed","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"fixed","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"bump","verdict":"AGREES(256)"},{"function":"second","verdict":"AGREES(256)"},{"function":"w2","verdict":"AGREES(256)"},{"function":"a3","verdict":"DIFFERS(call at 0x400128 to 0x4000bc)"},{"function":"a7","verdict":"DIFFERS(call at 0x400150 to 0x4000bc)"},{"function":"a6","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"fixed","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"bump","verdict":"AGREES(256)"},{"function":"second","verdict":"AGREES(256)"},{"function":"w2","verdict":"AGREES(256)"},{"function":"a3","verdict":"AGREES(256)"},{"function":"a7","verdict":"AGREES(256)"},{"function":"a6","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-frame-inventory.xml": [{"function":"sub_8000400","verdict":"AGREES(256)"},{"function":"sub_80003fc","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-frame-spill.xml": [{"function":"spill_argument","verdict":"AGREES(256)"},{"function":"spill_argument","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-opaque-double.xml": [{"function":"scale_d","verdict":"AGREES(256)"},{"function":"load_d","verdict":"AGREES(256)"},{"function":"conv_d","verdict":"AGREES(256)"},{"function":"two_d","verdict":"AGREES(256)"},{"function":"mixed_id","verdict":"AGREES(256)"},{"function":"indirect_d","verdict":"AGREES(256)"},{"function":"moved_d","verdict":"AGREES(256)"},{"function":"chain_d","verdict":"AGREES(256)"},{"function":"forward_d","verdict":"AGREES(256)"},{"function":"after_store","verdict":"AGREES(256)"},{"function":"call_ign","verdict":"AGREES(256)"},{"function":"mixed_fd","verdict":"AGREES(256)"},{"function":"scale_d","verdict":"AGREES(256)"},{"function":"load_d","verdict":"AGREES(256)"},{"function":"conv_d","verdict":"AGREES(256)"},{"function":"two_d","verdict":"AGREES(256)"},{"function":"mixed_id","verdict":"AGREES(256)"},{"function":"indirect_d","verdict":"AGREES(256)"},{"function":"moved_d","verdict":"AGREES(256)"},{"function":"chain_d","verdict":"AGREES(256)"},{"function":"forward_d","verdict":"AGREES(256)"},{"function":"after_store","verdict":"AGREES(256)"},{"function":"call_ign","verdict":"AGREES(256)"},{"function":"mixed_fd","verdict":"AGREES(256)"},{"function":"scale_d","verdict":"AGREES(256)"},{"function":"load_d","verdict":"AGREES(256)"},{"function":"conv_d","verdict":"AGREES(256)"},{"function":"two_d","verdict":"AGREES(256)"},{"function":"mixed_id","verdict":"AGREES(256)"},{"function":"indirect_d","verdict":"AGREES(256)"},{"function":"moved_d","verdict":"AGREES(256)"},{"function":"chain_d","verdict":"AGREES(256)"},{"function":"forward_d","verdict":"AGREES(256)"},{"function":"after_store","verdict":"AGREES(256)"},{"function":"call_ign","verdict":"AGREES(256)"},{"function":"mixed_fd","verdict":"AGREES(256)"},{"function":"scale_d","verdict":"AGREES(256)"},{"function":"load_d","verdict":"AGREES(256)"},{"function":"conv_d","verdict":"AGREES(256)"},{"function":"two_d","verdict":"AGREES(256)"},{"function":"mixed_id","verdict":"AGREES(256)"},{"function":"indirect_d","verdict":"AGREES(256)"},{"function":"moved_d","verdict":"AGREES(256)"},{"function":"chain_d","verdict":"AGREES(256)"},{"function":"forward_d","verdict":"AGREES(256)"},{"function":"after_store","verdict":"AGREES(256)"},{"function":"call_ign","verdict":"AGREES(256)"},{"function":"mixed_fd","verdict":"AGREES(256)"},{"function":"pieced_f","verdict":"AGREES(256)"},{"function":"guard_d","verdict":"AGREES(256)"},{"function":"guard_spin","verdict":"AGREES(256)"},{"function":"o0_fd","verdict":"AGREES(256)"},{"function":"o0_fp","verdict":"AGREES(256)"},{"function":"o0_fdd","verdict":"AGREES(256)"},{"function":"o0_fd","verdict":"AGREES(256)"},{"function":"o0_fp","verdict":"AGREES(256)"},{"function":"o0_fdd","verdict":"AGREES(256)"},{"function":"guard_shared","verdict":"AGREES(256)"},{"function":"tail_shared","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-pop-return.xml": [{"function":"stack_pop_return","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-register-shift-signed.xml": [{"function":"ShiftNegative","verdict":"AGREES(256)"},{"function":"ShiftArithmetic","verdict":"AGREES(256)"},{"function":"ShiftNegative","verdict":"AGREES(256)"},{"function":"ShiftArithmetic","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-register-shift.xml": [{"function":"ShiftOne","verdict":"AGREES(256)"},{"function":"ShiftAndStore","verdict":"AGREES(256)"},{"function":"ShiftOne","verdict":"AGREES(256)"},{"function":"ShiftValue","verdict":"AGREES(256)"},{"function":"ShiftAndStore","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-stack-vararg-double.xml": [{"function":"show_s","verdict":"AGREES(256)"},{"function":"show_ll","verdict":"AGREES(256)"},{"function":"show_bits","verdict":"AGREES(256)"},{"function":"show_two","verdict":"AGREES(256)"},{"function":"show_mut","verdict":"AGREES(256)"},{"function":"show_s","verdict":"AGREES(256)"},{"function":"show_ll","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"show_s","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-stored-double.xml": [{"function":"sel","verdict":"AGREES(256)"},{"function":"zero_if","verdict":"AGREES(256)"},{"function":"put_ref","verdict":"AGREES(256)"},{"function":"put_g","verdict":"AGREES(256)"},{"function":"put_gv","verdict":"AGREES(256)"},{"function":"put_two","verdict":"AGREES(256)"},{"function":"put_gf","verdict":"AGREES(256)"},{"function":"sel","verdict":"AGREES(256)"},{"function":"zero_if","verdict":"AGREES(256)"},{"function":"put_ref","verdict":"AGREES(256)"},{"function":"put_g","verdict":"AGREES(256)"},{"function":"put_gv","verdict":"AGREES(256)"},{"function":"put_two","verdict":"AGREES(256)"},{"function":"put_gf","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"put_mmio","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arm-variadic-double.xml": [{"function":"show2","verdict":"AGREES(256)"},{"function":"show_d1","verdict":"AGREES(256)"},{"function":"pun","verdict":"AGREES(256)"},{"function":"two_f","verdict":"AGREES(256)"},{"function":"show_f","verdict":"AGREES(256)"},{"function":"show3","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"show_d1","verdict":"AGREES(256)"},{"function":"pun","verdict":"AGREES(256)"},{"function":"two_f","verdict":"AGREES(256)"},{"function":"show_f","verdict":"AGREES(256)"},{"function":"show3","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"}], + "tests/stages/kuna-arm-volatile-loads.xml": [{"function":"read_four","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-armcondskip.xml": [{"function":"clamp","verdict":"AGREES(256)"}], + "tests/stages/kuna-armderef.xml": [{"function":"abs_write","verdict":"AGREES(256)"}], + "tests/stages/kuna-armfloat-preset.xml": [{"function":"scale","verdict":"AGREES(256)"},{"function":"mix","verdict":"AGREES(256)"},{"function":"backfill","verdict":"AGREES(256)"},{"function":"copysign_bits","verdict":"AGREES(256)"},{"function":"payload","verdict":"AGREES(256)"},{"function":"scale_err","verdict":"AGREES(256)"},{"function":"from_bits","verdict":"AGREES(256)"},{"function":"save_vfp","verdict":"AGREES(256)"},{"function":"from_bits_o0","verdict":"AGREES(256)"},{"function":"set8f","verdict":"AGREES(256)"},{"function":"getpar","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"mix","verdict":"AGREES(256)"},{"function":"backfill","verdict":"AGREES(256)"},{"function":"copysign_bits","verdict":"AGREES(256)"},{"function":"payload","verdict":"AGREES(256)"},{"function":"scale_err","verdict":"AGREES(256)"},{"function":"from_bits","verdict":"AGREES(256)"},{"function":"save_vfp","verdict":"AGREES(256)"},{"function":"from_bits_o0","verdict":"AGREES(256)"},{"function":"set8f","verdict":"AGREES(256)"},{"function":"getpar","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"mix","verdict":"AGREES(256)"},{"function":"backfill","verdict":"AGREES(256)"},{"function":"payload","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"},{"function":"mix","verdict":"AGREES(256)"},{"function":"backfill","verdict":"AGREES(256)"},{"function":"payload","verdict":"AGREES(256)"},{"function":"fixit","verdict":"DIFFERS(unassigned)"},{"function":"fixit","verdict":"AGREES(256)"},{"function":"neg_trunc","verdict":"AGREES(256)"},{"function":"to_ticks","verdict":"AGREES(256)"},{"function":"neg_trunc","verdict":"AGREES(256)"},{"function":"to_ticks","verdict":"AGREES(256)"}], + "tests/stages/kuna-armfuncmode.xml": [{"function":"arm_helper","verdict":"AGREES(256)"},{"function":"arm_helper","verdict":"AGREES(256)"},{"function":"arm_helper","verdict":"AGREES(256)"},{"function":"arm_helper","verdict":"UNKNOWN(unsupported-op)"},{"function":"arm_export","verdict":"UNKNOWN(budget)"},{"function":"sub_1020c","verdict":"AGREES(256)"},{"function":"sub_10290","verdict":"AGREES(256)"},{"function":"sub_103e0","verdict":"AGREES(256)"},{"function":"sub_2000094","verdict":"AGREES(256)"}], + "tests/stages/kuna-armpltslot.xml": [{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/kuna-armshiftguard.xml": [{"function":"MaskedBit","verdict":"AGREES(256)"},{"function":"FieldShift","verdict":"AGREES(256)"},{"function":"AnyShift","verdict":"AGREES(256)"},{"function":"ShiftLeft64","verdict":"AGREES(256)"},{"function":"ShiftRight64","verdict":"AGREES(256)"},{"function":"AnyShift","verdict":"AGREES(256)"},{"function":"ShiftLeft64","verdict":"AGREES(256)"},{"function":"ShiftRight64","verdict":"AGREES(256)"},{"function":"MaskedBit","verdict":"AGREES(256)"},{"function":"FieldShift","verdict":"AGREES(256)"},{"function":"AnyShift","verdict":"AGREES(256)"},{"function":"MaskedBit","verdict":"AGREES(256)"}], + "tests/stages/kuna-armwalkmode.xml": [{"function":"sub_2000080","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_2000080","verdict":"AGREES(256)"},{"function":"sub_2000040","verdict":"AGREES(256)"},{"function":"sub_2000000","verdict":"AGREES(256)"},{"function":"sub_2000080","verdict":"AGREES(256)"},{"function":"sub_10172","verdict":"AGREES(120)"}], + "tests/stages/kuna-arraycoverwidth.xml": [{"function":"vm","verdict":"AGREES(256)"}], + "tests/stages/kuna-arrayextent.xml": [{"function":"h_clang","verdict":"AGREES(256)"},{"function":"h_gcc","verdict":"AGREES(256)"},{"function":"m_clang","verdict":"AGREES(256)"},{"function":"m_gcc","verdict":"AGREES(256)"},{"function":"q_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"q_gcc","verdict":"UNKNOWN(budget)"},{"function":"w_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ff_gcc","verdict":"DIFFERS(return)"},{"function":"d4_clang","verdict":"DIFFERS(return)"},{"function":"s6_gcc","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ws_clang","verdict":"AGREES(103)"},{"function":"h3_clang","verdict":"UNKNOWN(unsupported-op)"},{"function":"h_clang","verdict":"AGREES(256)"},{"function":"h_gcc","verdict":"AGREES(256)"},{"function":"m_clang","verdict":"AGREES(256)"},{"function":"m_gcc","verdict":"AGREES(256)"},{"function":"q_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"q_gcc","verdict":"UNKNOWN(budget)"},{"function":"w_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ff_gcc","verdict":"DIFFERS(return)"},{"function":"d4_clang","verdict":"DIFFERS(return)"},{"function":"s6_gcc","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ws_clang","verdict":"AGREES(103)"},{"function":"h3_clang","verdict":"UNKNOWN(unsupported-op)"},{"function":"h_clang","verdict":"AGREES(256)"},{"function":"h_gcc","verdict":"AGREES(256)"},{"function":"m_clang","verdict":"AGREES(256)"},{"function":"m_gcc","verdict":"AGREES(256)"},{"function":"q_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"q_gcc","verdict":"UNKNOWN(budget)"},{"function":"w_clang","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ff_gcc","verdict":"DIFFERS(return)"},{"function":"d4_clang","verdict":"DIFFERS(return)"},{"function":"s6_gcc","verdict":"UNKNOWN(uninitialized-local)"},{"function":"ws_clang","verdict":"AGREES(103)"},{"function":"h3_clang","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-arraysize.xml": [{"function":"line_len","verdict":"AGREES(256)"},{"function":"line_len","verdict":"AGREES(256)"},{"function":"link_len","verdict":"AGREES(256)"},{"function":"link_len","verdict":"AGREES(256)"},{"function":"link_plus1","verdict":"AGREES(256)"},{"function":"link_plus1","verdict":"AGREES(256)"},{"function":"fortified","verdict":"AGREES(256)"},{"function":"fortified","verdict":"AGREES(256)"},{"function":"float_text","verdict":"AGREES(256)"},{"function":"float_text","verdict":"AGREES(256)"},{"function":"float_text","verdict":"AGREES(256)"},{"function":"short_read","verdict":"AGREES(256)"},{"function":"short_read","verdict":"AGREES(256)"},{"function":"term_room","verdict":"AGREES(256)"},{"function":"term_room","verdict":"AGREES(256)"},{"function":"veto","verdict":"AGREES(256)"},{"function":"veto","verdict":"AGREES(256)"},{"function":"scan_back","verdict":"AGREES(256)"},{"function":"scan_back","verdict":"AGREES(256)"},{"function":"sum_n","verdict":"AGREES(256)"},{"function":"sum_n","verdict":"AGREES(256)"}], + "tests/stages/kuna-arraysubfield.xml": [{"function":"lo8","verdict":"AGREES(256)"},{"function":"hi8","verdict":"AGREES(256)"},{"function":"elem","verdict":"AGREES(256)"},{"function":"shift64","verdict":"AGREES(256)"},{"function":"lo8","verdict":"AGREES(256)"},{"function":"hi8","verdict":"AGREES(256)"},{"function":"elem","verdict":"AGREES(256)"}], + "tests/stages/kuna-assert-callee.xml": [{"function":"twice","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-assert-format-isolate.xml": [{"function":"is_rwx","verdict":"AGREES(256)"},{"function":"is_rwx","verdict":"AGREES(256)"},{"function":"reuse","verdict":"AGREES(256)"},{"function":"reuse","verdict":"AGREES(256)"},{"function":"triple","verdict":"AGREES(256)"},{"function":"triple","verdict":"AGREES(256)"},{"function":"triple","verdict":"AGREES(256)"}], + "tests/stages/kuna-assert.xml": [{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"},{"function":"fetch_second","verdict":"AGREES(256)"},{"function":"fetch_second","verdict":"AGREES(256)"}], + "tests/stages/kuna-authptrcall.xml": [{"function":"_call_auth_ptr","verdict":"AGREES(256)"},{"function":"_call_table","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-avr.xml": [{"function":"negate","verdict":"AGREES(256)"},{"function":"addk","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-callers.xml": [{"function":"add64","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"c_add","verdict":"AGREES(256)"},{"function":"c_hi","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"c_pass","verdict":"AGREES(256)"},{"function":"add64","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"c_add","verdict":"AGREES(256)"},{"function":"c_hi","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"c_pass","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-evidence-armeb.xml": [{"function":"uwide_mul","verdict":"AGREES(256)"},{"function":"mulhi","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"uwide_mul","verdict":"AGREES(256)"},{"function":"mulhi","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-evidence-pairs.xml": [{"function":"ld_ll","verdict":"AGREES(256)"},{"function":"ldfield_ll","verdict":"AGREES(256)"},{"function":"carry_ll","verdict":"AGREES(256)"},{"function":"carry_hi","verdict":"AGREES(256)"},{"function":"ld_sum","verdict":"AGREES(256)"},{"function":"ld_ll","verdict":"AGREES(256)"},{"function":"ldfield_ll","verdict":"AGREES(256)"},{"function":"carry_ll","verdict":"AGREES(256)"},{"function":"carry_hi","verdict":"AGREES(256)"},{"function":"ld_sum","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-evidence-sparc.xml": [{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"shi","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"shi","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-evidence.xml": [{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"zsum","verdict":"AGREES(256)"},{"function":"sum64","verdict":"AGREES(256)"},{"function":"sum_hi","verdict":"AGREES(256)"},{"function":"clr","verdict":"AGREES(256)"},{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"zsum","verdict":"AGREES(256)"},{"function":"sum64","verdict":"AGREES(256)"},{"function":"sum_hi","verdict":"AGREES(256)"},{"function":"clr","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-mips.xml": [{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"realeof","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-mipsclang.xml": [{"function":"add64","verdict":"AGREES(256)"},{"function":"widen1","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"add64","verdict":"AGREES(256)"},{"function":"widen1","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"sum_both","verdict":"AGREES(256)"},{"function":"sum_or_entry","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-mipspic.xml": [{"function":"add64","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"add64","verdict":"AGREES(256)"},{"function":"add_hi","verdict":"AGREES(256)"},{"function":"c_unal","verdict":"DIFFERS(call at 0x400110 to 0x4000f0)"},{"function":"c_unal","verdict":"DIFFERS(call at 0x400110 to 0x4000f0)"}], + "tests/stages/kuna-bejoin-residue.xml": [{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"local","verdict":"AGREES(256)"},{"function":"local_hi","verdict":"AGREES(256)"},{"function":"sign","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"local","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"uwiden","verdict":"AGREES(256)"},{"function":"add64","verdict":"AGREES(256)"},{"function":"sign_of","verdict":"AGREES(256)"},{"function":"add64","verdict":"AGREES(256)"},{"function":"sign_of","verdict":"AGREES(256)"},{"function":"sign_of","verdict":"DIFFERS(call at 0x40009c to 0x400078)"},{"function":"sign_of","verdict":"DIFFERS(call at 0x40009c to 0x400078)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"drop","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-sparc.xml": [{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"keep_zero","verdict":"AGREES(252)"},{"function":"back4","verdict":"AGREES(256)"},{"function":"zero_after","verdict":"AGREES(256)"},{"function":"one_after","verdict":"AGREES(256)"},{"function":"mark","verdict":"AGREES(251)"},{"function":"bound","verdict":"AGREES(256)"},{"function":"ibyte","verdict":"AGREES(256)"},{"function":"ubyte","verdict":"AGREES(256)"},{"function":"ihalf","verdict":"AGREES(256)"},{"function":"ibyte_leaf","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin-sparc64.xml": [{"function":"neg_one","verdict":"AGREES(256)"},{"function":"k_one","verdict":"AGREES(256)"},{"function":"status64","verdict":"AGREES(256)"},{"function":"bool64","verdict":"AGREES(256)"},{"function":"sel_const","verdict":"AGREES(256)"},{"function":"mix2","verdict":"AGREES(256)"},{"function":"mix3","verdict":"AGREES(256)"},{"function":"neg_one_O0","verdict":"AGREES(256)"},{"function":"k_one_O0","verdict":"AGREES(256)"},{"function":"status64_O0","verdict":"AGREES(256)"},{"function":"bool64_O0","verdict":"AGREES(256)"},{"function":"sel_const_O0","verdict":"AGREES(256)"},{"function":"mix2_O0","verdict":"AGREES(256)"},{"function":"mix3_O0","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoin.xml": [{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"add_one","verdict":"AGREES(256)"},{"function":"triple_plus","verdict":"AGREES(256)"},{"function":"sum64","verdict":"AGREES(256)"},{"function":"sum_hi","verdict":"AGREES(256)"},{"function":"carry","verdict":"AGREES(256)"},{"function":"wide_mul","verdict":"AGREES(256)"},{"function":"add_one","verdict":"AGREES(256)"},{"function":"triple_plus","verdict":"AGREES(256)"},{"function":"sum64","verdict":"AGREES(256)"},{"function":"sum_hi","verdict":"AGREES(256)"},{"function":"carry","verdict":"AGREES(256)"}], + "tests/stages/kuna-bejoinpass.xml": [{"function":"viahook","verdict":"AGREES(256)"},{"function":"viahook","verdict":"AGREES(256)"},{"function":"viahook","verdict":"AGREES(256)"},{"function":"viahook","verdict":"AGREES(256)"}], + "tests/stages/kuna-bigendian-lane-consume.xml": [{"function":"saved_output","verdict":"AGREES(253)"},{"function":"short_induction","verdict":"AGREES(76)"},{"function":"float_recurrence","verdict":"AGREES(253)"},{"function":"retained_scale","verdict":"AGREES(252)"}], + "tests/stages/kuna-bit-reinterpret-arm.xml": [{"function":"bits32","verdict":"AGREES(256)"},{"function":"unbits32","verdict":"AGREES(256)"},{"function":"bits64","verdict":"AGREES(256)"},{"function":"unbits64","verdict":"AGREES(256)"},{"function":"numeric32","verdict":"AGREES(256)"},{"function":"trunc32","verdict":"AGREES(256)"}], + "tests/stages/kuna-bit-reinterpret-declared.xml": [{"function":"clampg","verdict":"AGREES(256)"},{"function":"s_select","verdict":"AGREES(256)"},{"function":"s_ternary","verdict":"AGREES(256)"}], + "tests/stages/kuna-bit-reinterpret-thumb.xml": [{"function":"bits32","verdict":"AGREES(256)"},{"function":"unbits32","verdict":"AGREES(256)"},{"function":"bits64","verdict":"AGREES(256)"},{"function":"unbits64","verdict":"AGREES(256)"},{"function":"numeric32","verdict":"AGREES(256)"},{"function":"trunc32","verdict":"AGREES(256)"}], + "tests/stages/kuna-bit-reinterpret-x64.xml": [{"function":"bits32","verdict":"AGREES(256)"},{"function":"unbits32","verdict":"AGREES(256)"},{"function":"bits64","verdict":"AGREES(256)"},{"function":"unbits64","verdict":"AGREES(256)"},{"function":"numeric32","verdict":"AGREES(256)"},{"function":"trunc32","verdict":"AGREES(256)"}], + "tests/stages/kuna-blobs.xml": [{"function":"get_logo","verdict":"AGREES(256)"},{"function":"get_archive","verdict":"AGREES(256)"},{"function":"get_broken","verdict":"AGREES(256)"},{"function":"get_logo","verdict":"AGREES(256)"},{"function":"get_icon","verdict":"AGREES(256)"},{"function":"get_photo","verdict":"AGREES(256)"},{"function":"get_archive","verdict":"AGREES(256)"},{"function":"get_packed","verdict":"AGREES(256)"},{"function":"get_broken","verdict":"AGREES(256)"}], + "tests/stages/kuna-bodyreads.xml": [{"function":"mix","verdict":"DIFFERS(call at 0x4011da to 0x4011b0)"},{"function":"mix","verdict":"AGREES(256)"}], + "tests/stages/kuna-boolbranch-thumb.xml": [{"function":"brgreater","verdict":"AGREES(256)"},{"function":"itgreater","verdict":"AGREES(256)"},{"function":"brgreater","verdict":"AGREES(256)"}], + "tests/stages/kuna-boolbranch.xml": [{"function":"positive","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"flagged","verdict":"AGREES(256)"},{"function":"positive","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"flagged","verdict":"AGREES(256)"},{"function":"addsat","verdict":"AGREES(256)"},{"function":"greater","verdict":"AGREES(256)"}], + "tests/stages/kuna-boolbyte.xml": [{"function":"flagparam","verdict":"AGREES(256)"},{"function":"bytearith","verdict":"AGREES(256)"},{"function":"lowbit","verdict":"AGREES(256)"},{"function":"flagstore","verdict":"AGREES(256)"},{"function":"callfill","verdict":"AGREES(256)"},{"function":"callslot","verdict":"AGREES(256)"},{"function":"truncjoin","verdict":"AGREES(256)"},{"function":"truncflag","verdict":"AGREES(256)"},{"function":"flagparam","verdict":"AGREES(256)"},{"function":"bytearith","verdict":"AGREES(256)"},{"function":"lowbit","verdict":"AGREES(256)"},{"function":"flagstore","verdict":"AGREES(256)"},{"function":"callfill","verdict":"AGREES(256)"},{"function":"callslot","verdict":"AGREES(256)"},{"function":"truncjoin","verdict":"AGREES(256)"},{"function":"truncflag","verdict":"AGREES(256)"}], + "tests/stages/kuna-boolret-thumb.xml": [{"function":"is_empty","verdict":"AGREES(256)"},{"function":"both_set","verdict":"AGREES(256)"},{"function":"is_empty","verdict":"AGREES(256)"},{"function":"both_set","verdict":"AGREES(256)"}], + "tests/stages/kuna-boolret.xml": [{"function":"is_abs","verdict":"AGREES(256)"},{"function":"is_full","verdict":"AGREES(256)"},{"function":"is_abs","verdict":"AGREES(256)"},{"function":"is_full","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"either","verdict":"AGREES(256)"},{"function":"bump_and_test","verdict":"AGREES(256)"}], + "tests/stages/kuna-boundschecked.xml": [{"function":"clear_obj","verdict":"AGREES(256)"},{"function":"dup_obj","verdict":"AGREES(256)"},{"function":"shift_obj","verdict":"AGREES(256)"},{"function":"dup_name","verdict":"AGREES(256)"},{"function":"add_name","verdict":"AGREES(256)"},{"function":"format_pair","verdict":"AGREES(256)"},{"function":"clear_obj","verdict":"AGREES(256)"},{"function":"dup_obj","verdict":"AGREES(256)"},{"function":"shift_obj","verdict":"AGREES(256)"},{"function":"dup_name","verdict":"AGREES(256)"},{"function":"add_name","verdict":"AGREES(256)"},{"function":"format_pair","verdict":"AGREES(256)"},{"function":"clear_obj","verdict":"AGREES(256)"},{"function":"dup_obj","verdict":"AGREES(256)"}], + "tests/stages/kuna-brktrap.xml": [{"function":"add_trap","verdict":"AGREES(256)"},{"function":"mul_add_trap","verdict":"AGREES(256)"},{"function":"index_gcc","verdict":"AGREES(256)"},{"function":"add_ubsan","verdict":"AGREES(256)"},{"function":"debug_trap","verdict":"AGREES(256)"},{"function":"debugger_bp","verdict":"AGREES(256)"},{"function":"deref_fastfail","verdict":"AGREES(256)"},{"function":"kernel_warn","verdict":"AGREES(256)"},{"function":"fastfail_code","verdict":"AGREES(256)"},{"function":"pac_guard","verdict":"AGREES(256)"}], + "tests/stages/kuna-bytemap-noguard.xml": [{"function":"cmp_nodes","verdict":"AGREES(256)"},{"function":"cmp_folded","verdict":"AGREES(256)"},{"function":"cmp_bytetag","verdict":"AGREES(256)"},{"function":"cmp_coldrow","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-bytestoreruns.xml": [{"function":"put3","verdict":"AGREES(256)"},{"function":"put100","verdict":"AGREES(256)"},{"function":"put8000","verdict":"AGREES(256)"},{"function":"put_fill","verdict":"AGREES(256)"},{"function":"put_pair","verdict":"AGREES(256)"},{"function":"put_text","verdict":"AGREES(256)"},{"function":"put_mixed","verdict":"AGREES(256)"},{"function":"put_wide","verdict":"AGREES(256)"},{"function":"put3","verdict":"AGREES(256)"},{"function":"put100","verdict":"AGREES(256)"},{"function":"put8000","verdict":"AGREES(256)"},{"function":"put_fill","verdict":"AGREES(256)"},{"function":"put_pair","verdict":"AGREES(256)"},{"function":"put_text","verdict":"AGREES(256)"},{"function":"put_mixed","verdict":"AGREES(256)"},{"function":"put_wide","verdict":"AGREES(256)"},{"function":"put100","verdict":"AGREES(256)"},{"function":"std::io::error::Error::fmt","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-bytestorewidth.xml": [{"function":"fill","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill_text","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill_text","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"},{"function":"fill_text","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(256)"}], + "tests/stages/kuna-cachereturn.xml": [{"function":"get_cached","verdict":"AGREES(256)"},{"function":"ensure","verdict":"AGREES(256)"},{"function":"get_slot","verdict":"AGREES(256)"},{"function":"get_split","verdict":"AGREES(256)"},{"function":"get_cached","verdict":"AGREES(256)"},{"function":"ensure","verdict":"AGREES(256)"},{"function":"get_slot","verdict":"AGREES(256)"},{"function":"get_split","verdict":"AGREES(256)"},{"function":"get_cached","verdict":"AGREES(256)"},{"function":"ensure","verdict":"AGREES(256)"},{"function":"get_slot","verdict":"AGREES(256)"},{"function":"get_split","verdict":"AGREES(256)"}], + "tests/stages/kuna-call-array-extent.xml": [{"function":"escaped_output","verdict":"AGREES(256)"},{"function":"escaped_output","verdict":"AGREES(256)"},{"function":"bounded_output","verdict":"AGREES(256)"},{"function":"separate_word","verdict":"AGREES(256)"},{"function":"overlapping_output","verdict":"AGREES(256)"},{"function":"overlapping_output","verdict":"AGREES(256)"},{"function":"looping_output","verdict":"AGREES(256)"},{"function":"looping_output","verdict":"AGREES(256)"},{"function":"lower_scalar_output","verdict":"AGREES(256)"},{"function":"lower_scalar_output","verdict":"AGREES(256)"},{"function":"parent_tail_scalar","verdict":"AGREES(256)"},{"function":"parent_tail_scalar","verdict":"AGREES(256)"},{"function":"duplicate_arg_output","verdict":"AGREES(256)"},{"function":"duplicate_arg_output","verdict":"AGREES(256)"}], + "tests/stages/kuna-callbacktype.xml": [{"function":"by_key","verdict":"AGREES(256)"},{"function":"on_int","verdict":"AGREES(256)"},{"function":"by_key","verdict":"AGREES(256)"},{"function":"on_int","verdict":"AGREES(256)"}], + "tests/stages/kuna-callee-homes-win64.xml": [{"function":"fixture_home_clean","verdict":"AGREES(256)"},{"function":"fixture_home_read","verdict":"AGREES(256)"},{"function":"fixture_home_escape","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleeargs.xml": [{"function":"steer","verdict":"UNKNOWN(unsupported-op)"},{"function":"steer","verdict":"UNKNOWN(unsupported-op)"},{"function":"draw","verdict":"AGREES(256)"},{"function":"draw","verdict":"AGREES(256)"},{"function":"big_draw","verdict":"AGREES(256)"},{"function":"big_draw","verdict":"AGREES(256)"},{"function":"nmsg","verdict":"UNKNOWN(unsupported-op)"},{"function":"nmsg","verdict":"UNKNOWN(unsupported-op)"},{"function":"count","verdict":"AGREES(256)"},{"function":"count","verdict":"AGREES(256)"},{"function":"isctype","verdict":"AGREES(256)"},{"function":"start","verdict":"AGREES(256)"},{"function":"start","verdict":"AGREES(256)"},{"function":"call_ret","verdict":"AGREES(256)"},{"function":"call_xmm","verdict":"AGREES(256)"},{"function":"call_pushesp","verdict":"AGREES(256)"},{"function":"cookie_caller","verdict":"UNKNOWN(unsupported-op)"},{"function":"call_argslot","verdict":"AGREES(256)"},{"function":"call_movq","verdict":"AGREES(256)"},{"function":"call_ecx","verdict":"AGREES(256)"},{"function":"call_heap","verdict":"AGREES(256)"},{"function":"call_ret2","verdict":"AGREES(256)"},{"function":"call_ret2","verdict":"AGREES(256)"},{"function":"call_ret","verdict":"AGREES(256)"},{"function":"call_xmm","verdict":"AGREES(256)"},{"function":"call_pushesp","verdict":"AGREES(256)"},{"function":"cookie_caller","verdict":"UNKNOWN(unsupported-op)"},{"function":"call_argslot","verdict":"AGREES(256)"},{"function":"call_movq","verdict":"AGREES(256)"},{"function":"call_ecx","verdict":"AGREES(256)"},{"function":"call_heap","verdict":"AGREES(256)"},{"function":"steer2","verdict":"AGREES(256)"},{"function":"consts","verdict":"AGREES(256)"},{"function":"steer2","verdict":"AGREES(256)"},{"function":"consts","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearity-formatwitness.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"no_conversion_control","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearity.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearitycut.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller2","verdict":"DIFFERS(call at 0x10008e to 0x100030)"},{"function":"caller3","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearityfwd.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearitylive.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller2","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleearityscratch.xml": [{"function":"scratch_wide","verdict":"AGREES(256)"},{"function":"scratch_byte","verdict":"AGREES(256)"},{"function":"boundary_live","verdict":"AGREES(256)"},{"function":"boundary_const","verdict":"DIFFERS(call at 0x1000ec to 0x100040)"}], + "tests/stages/kuna-calleedeadarg.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleefilledarg-ctramp.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller2","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleefilledarg.xml": [{"function":"walk","verdict":"AGREES(256)"},{"function":"walk_plain","verdict":"AGREES(256)"},{"function":"walk","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleefloatreads.xml": [{"function":"caller","verdict":"DIFFERS(return)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"leftover","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"leftover","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"twocalls","verdict":"AGREES(256)"},{"function":"a3","verdict":"AGREES(256)"},{"function":"a7","verdict":"AGREES(256)"},{"function":"outer2","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleenamedlocals.xml": [{"function":"visit","verdict":"AGREES(9)"},{"function":"k1","verdict":"AGREES(256)"},{"function":"m1","verdict":"AGREES(256)"},{"function":"m2","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"gc","verdict":"AGREES(16)"},{"function":"stackreturn","verdict":"UNKNOWN(unsupported-op)"},{"function":"visit","verdict":"AGREES(9)"},{"function":"k1","verdict":"AGREES(256)"},{"function":"m1","verdict":"AGREES(256)"},{"function":"m2","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"gc","verdict":"AGREES(16)"},{"function":"stackreturn","verdict":"UNKNOWN(unsupported-op)"},{"function":"visit","verdict":"AGREES(9)"},{"function":"k1","verdict":"AGREES(256)"},{"function":"m1","verdict":"AGREES(256)"},{"function":"m2","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"s4","verdict":"AGREES(256)"},{"function":"gc","verdict":"AGREES(16)"},{"function":"stackreturn","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-calleepop-x86-16.xml": [{"function":"caller","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-calleepopframe.xml": [{"function":"sub_401000","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleepopslot.xml": [{"function":"sub_401000","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleepreserves.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleepreservesargs.xml": [{"function":"twice","verdict":"AGREES(256)"},{"function":"stale","verdict":"AGREES(256)"},{"function":"pipe","verdict":"AGREES(256)"},{"function":"snipsys","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleeprotostack-homeslot.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleepurge.xml": [{"function":"split","verdict":"UNKNOWN(unsupported-op)"},{"function":"use_add2","verdict":"AGREES(256)"},{"function":"map_string","verdict":"UNKNOWN(unsupported-op)"},{"function":"seh_open","verdict":"UNKNOWN(unsupported-op)"},{"function":"start","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleereadarg-a64.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller2","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleereadarg-arm.xml": [{"function":"fwd","verdict":"AGREES(256)"},{"function":"neg","verdict":"AGREES(256)"},{"function":"negpush","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleereadarg-sixth.xml": [{"function":"six","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleereadarg.xml": [{"function":"t9","verdict":"AGREES(256)"},{"function":"fwd","verdict":"AGREES(256)"},{"function":"neg","verdict":"AGREES(256)"},{"function":"negv","verdict":"AGREES(256)"},{"function":"sbbpick","verdict":"AGREES(256)"},{"function":"k1d","verdict":"DIFFERS(call at 0x401150 to 0x401130)"}], + "tests/stages/kuna-calleereginputs.xml": [{"function":"use","verdict":"UNKNOWN(unsupported-op)"},{"function":"use","verdict":"UNKNOWN(unsupported-op)"},{"function":"forward","verdict":"AGREES(256)"},{"function":"inherited","verdict":"AGREES(256)"},{"function":"reload","verdict":"AGREES(256)"},{"function":"drift","verdict":"AGREES(256)"},{"function":"fastcaller","verdict":"AGREES(256)"},{"function":"partial","verdict":"AGREES(256)"},{"function":"forward","verdict":"AGREES(256)"},{"function":"inherited","verdict":"AGREES(256)"},{"function":"reload","verdict":"AGREES(256)"},{"function":"drift","verdict":"AGREES(256)"},{"function":"fastcaller","verdict":"AGREES(256)"},{"function":"partial","verdict":"AGREES(256)"},{"function":"vcall","verdict":"UNKNOWN(unsupported-op)"},{"function":"comcall","verdict":"UNKNOWN(unsupported-op)"},{"function":"reserve","verdict":"UNKNOWN(unsupported-op)"},{"function":"ctable","verdict":"UNKNOWN(unsupported-op)"},{"function":"comcopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"comesi","verdict":"UNKNOWN(unsupported-op)"},{"function":"crosscall","verdict":"UNKNOWN(unsupported-op)"},{"function":"ecxcopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"gccsret","verdict":"UNKNOWN(unsupported-op)"},{"function":"latecopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"lateother","verdict":"UNKNOWN(unsupported-op)"},{"function":"vepilog","verdict":"AGREES(256)"},{"function":"vouter","verdict":"AGREES(256)"},{"function":"vseh","verdict":"AGREES(256)"},{"function":"vdefer","verdict":"AGREES(256)"},{"function":"vcall","verdict":"UNKNOWN(unsupported-op)"},{"function":"comcall","verdict":"UNKNOWN(unsupported-op)"},{"function":"reserve","verdict":"UNKNOWN(unsupported-op)"},{"function":"ctable","verdict":"UNKNOWN(unsupported-op)"},{"function":"comcopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"comesi","verdict":"UNKNOWN(unsupported-op)"},{"function":"crosscall","verdict":"UNKNOWN(unsupported-op)"},{"function":"ecxcopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"gccsret","verdict":"UNKNOWN(unsupported-op)"},{"function":"latecopy","verdict":"UNKNOWN(unsupported-op)"},{"function":"lateother","verdict":"UNKNOWN(unsupported-op)"},{"function":"vepilog","verdict":"AGREES(256)"},{"function":"vouter","verdict":"AGREES(256)"},{"function":"vseh","verdict":"AGREES(256)"},{"function":"vdefer","verdict":"AGREES(256)"},{"function":"vcall_c","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-calleeretpreserves-mips.xml": [{"function":"afterstore2","verdict":"AGREES(256)"},{"function":"afterbranch","verdict":"AGREES(256)"},{"function":"aftervoid","verdict":"AGREES(256)"},{"function":"hiword","verdict":"AGREES(256)"},{"function":"afterstore2","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleeretpreserves-mipsbe.xml": [{"function":"afterstore2","verdict":"AGREES(256)"},{"function":"afterbranch","verdict":"AGREES(256)"},{"function":"aftervoid","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleeretpreserves.xml": [{"function":"f","verdict":"DIFFERS(return)"},{"function":"g","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"i","verdict":"AGREES(256)"},{"function":"j","verdict":"DIFFERS(unassigned)"},{"function":"j","verdict":"AGREES(256)"},{"function":"j","verdict":"DIFFERS(unassigned)"},{"function":"j","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleescratchbody.xml": [{"function":"f","verdict":"UNKNOWN(guessed-callee)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-calleevote.xml": [{"function":"get_cap","verdict":"AGREES(256)"},{"function":"get_cap","verdict":"AGREES(256)"}], + "tests/stages/kuna-callerreads.xml": [{"function":"triple","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"scale","verdict":"AGREES(256)"}], + "tests/stages/kuna-callkeep.xml": [{"function":"k_mem","verdict":"AGREES(85)"},{"function":"k_outer","verdict":"DIFFERS(call at 0x14f5 to 0x12d0)"},{"function":"k_rec","verdict":"AGREES(85)"},{"function":"k_quot","verdict":"AGREES(85)"},{"function":"k_keep","verdict":"AGREES(256)"},{"function":"k_wrap","verdict":"AGREES(256)"},{"function":"k_maybe","verdict":"AGREES(256)"}], + "tests/stages/kuna-calloverlap-floatret.xml": [{"function":"f","verdict":"DIFFERS(unassigned)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-callplaceholder.xml": [{"function":"probe","verdict":"UNKNOWN(uninitialized-local)"}], + "tests/stages/kuna-callpopret.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-callproto.xml": [{"function":"report","verdict":"AGREES(256)"},{"function":"report","verdict":"AGREES(256)"},{"function":"report","verdict":"AGREES(256)"}], + "tests/stages/kuna-callpush.xml": [{"function":"stacked","verdict":"AGREES(16)"},{"function":"pc_here","verdict":"AGREES(20)"}], + "tests/stages/kuna-callretmulti.xml": [{"function":"sub_140002930","verdict":"UNKNOWN(budget)"},{"function":"same_block_two_sink","verdict":"AGREES(256)"},{"function":"sub_140002930","verdict":"UNKNOWN(budget)"},{"function":"same_block_two_sink","verdict":"AGREES(256)"}], + "tests/stages/kuna-callretpair.xml": [{"function":"read_tag","verdict":"AGREES(256)"},{"function":"read_tag_clobber","verdict":"AGREES(256)"}], + "tests/stages/kuna-callretpairhalf.xml": [{"function":"hib","verdict":"AGREES(256)"},{"function":"hiplus","verdict":"AGREES(256)"},{"function":"hiw","verdict":"AGREES(256)"},{"function":"lob","verdict":"AGREES(256)"},{"function":"hig32","verdict":"DIFFERS(unassigned)"},{"function":"hip","verdict":"DIFFERS(unassigned)"},{"function":"lo40t","verdict":"AGREES(256)"},{"function":"hibt","verdict":"AGREES(256)"}], + "tests/stages/kuna-callrettype.xml": [{"function":"skip_blanks","verdict":"AGREES(256)"},{"function":"upper_of_rest","verdict":"AGREES(256)"},{"function":"skip_blanks","verdict":"AGREES(256)"},{"function":"upper_of_rest","verdict":"AGREES(256)"}], + "tests/stages/kuna-calltargetstorage.xml": [{"function":"viaparam","verdict":"AGREES(256)"},{"function":"viaglobal","verdict":"AGREES(256)"},{"function":"viafield","verdict":"AGREES(256)"},{"function":"viaparam","verdict":"AGREES(256)"},{"function":"viaglobal","verdict":"AGREES(256)"},{"function":"viafield","verdict":"AGREES(256)"},{"function":"viafield","verdict":"AGREES(256)"},{"function":"viaparam","verdict":"AGREES(256)"},{"function":"viaparam","verdict":"AGREES(256)"}], + "tests/stages/kuna-calltargettype-a64.xml": [{"function":"fstore","verdict":"AGREES(255)"},{"function":"fmul","verdict":"AGREES(256)"},{"function":"icall","verdict":"AGREES(256)"},{"function":"fstore","verdict":"AGREES(255)"},{"function":"fmul","verdict":"AGREES(256)"},{"function":"icall","verdict":"AGREES(256)"}], + "tests/stages/kuna-calltargettype-armhf.xml": [{"function":"fstore","verdict":"AGREES(254)"},{"function":"fmul","verdict":"AGREES(256)"},{"function":"icall","verdict":"AGREES(256)"},{"function":"fstore","verdict":"AGREES(254)"},{"function":"fmul","verdict":"AGREES(256)"},{"function":"icall","verdict":"AGREES(256)"}], + "tests/stages/kuna-calltargettype.xml": [{"function":"call","verdict":"AGREES(256)"},{"function":"call2","verdict":"AGREES(256)"},{"function":"calls","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"chosen","verdict":"AGREES(256)"},{"function":"sorter","verdict":"AGREES(256)"},{"function":"fstore","verdict":"AGREES(256)"},{"function":"c_call","verdict":"AGREES(256)"},{"function":"c_call2","verdict":"AGREES(256)"},{"function":"c_calls","verdict":"AGREES(256)"},{"function":"c_twice","verdict":"AGREES(256)"},{"function":"c_chosen","verdict":"AGREES(256)"},{"function":"c_sorter","verdict":"AGREES(256)"},{"function":"c_fstore","verdict":"AGREES(256)"},{"function":"call","verdict":"AGREES(256)"},{"function":"call2","verdict":"AGREES(256)"},{"function":"calls","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"chosen","verdict":"AGREES(256)"},{"function":"sorter","verdict":"AGREES(256)"},{"function":"fstore","verdict":"AGREES(256)"},{"function":"c_call","verdict":"AGREES(256)"},{"function":"c_call2","verdict":"AGREES(256)"},{"function":"c_calls","verdict":"AGREES(256)"},{"function":"c_twice","verdict":"AGREES(256)"},{"function":"c_chosen","verdict":"AGREES(256)"},{"function":"c_sorter","verdict":"AGREES(256)"},{"function":"c_fstore","verdict":"AGREES(256)"},{"function":"call","verdict":"AGREES(256)"},{"function":"call2","verdict":"AGREES(256)"},{"function":"calls","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"chosen","verdict":"AGREES(256)"},{"function":"sorter","verdict":"AGREES(256)"},{"function":"fstore","verdict":"AGREES(256)"},{"function":"c_call","verdict":"AGREES(256)"},{"function":"c_call2","verdict":"AGREES(256)"},{"function":"c_calls","verdict":"AGREES(256)"},{"function":"c_twice","verdict":"AGREES(256)"},{"function":"c_chosen","verdict":"AGREES(256)"},{"function":"c_sorter","verdict":"AGREES(256)"},{"function":"c_fstore","verdict":"AGREES(256)"}], + "tests/stages/kuna-calltrampoline.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-callwide.xml": [{"function":"produce_sum","verdict":"AGREES(256)"},{"function":"produce_sum","verdict":"AGREES(256)"},{"function":"caller64","verdict":"AGREES(256)"},{"function":"caller_high8","verdict":"AGREES(256)"}], + "tests/stages/kuna-casp-pairs-be.xml": [{"function":"store_zero","verdict":"AGREES(256)"}], + "tests/stages/kuna-casp-pairs.xml": [{"function":"exchange","verdict":"AGREES(256)"},{"function":"compare_zero","verdict":"AGREES(256)"},{"function":"store_zero","verdict":"AGREES(256)"}], + "tests/stages/kuna-castarith.xml": [{"function":"rd32","verdict":"AGREES(256)"},{"function":"rdneg","verdict":"AGREES(256)"},{"function":"rdodd","verdict":"AGREES(256)"},{"function":"wr16","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"rdbyte","verdict":"AGREES(256)"},{"function":"rdidx","verdict":"AGREES(256)"},{"function":"rd32","verdict":"AGREES(256)"},{"function":"rdneg","verdict":"AGREES(256)"},{"function":"rdodd","verdict":"AGREES(256)"},{"function":"wr16","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"rdbyte","verdict":"AGREES(256)"},{"function":"rdidx","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"}], + "tests/stages/kuna-castimplied.xml": [{"function":"argi","verdict":"AGREES(256)"},{"function":"argl","verdict":"AGREES(256)"},{"function":"vararg","verdict":"AGREES(256)"},{"function":"asg","verdict":"AGREES(85)"},{"function":"ret","verdict":"AGREES(256)"},{"function":"stacked","verdict":"AGREES(256)"},{"function":"keepinner","verdict":"AGREES(256)"},{"function":"argi","verdict":"AGREES(256)"},{"function":"argl","verdict":"AGREES(256)"},{"function":"vararg","verdict":"AGREES(256)"},{"function":"asg","verdict":"AGREES(85)"},{"function":"ret","verdict":"AGREES(256)"},{"function":"stacked","verdict":"AGREES(256)"},{"function":"keepinner","verdict":"AGREES(256)"}], + "tests/stages/kuna-castindex.xml": [{"function":"ldidx","verdict":"AGREES(256)"},{"function":"ld64","verdict":"AGREES(256)"},{"function":"ldbyte","verdict":"AGREES(256)"},{"function":"rec16","verdict":"AGREES(256)"},{"function":"diff","verdict":"AGREES(256)"},{"function":"ldidx","verdict":"AGREES(256)"},{"function":"ld64","verdict":"AGREES(256)"},{"function":"ldbyte","verdict":"AGREES(256)"},{"function":"rec16","verdict":"AGREES(256)"},{"function":"diff","verdict":"AGREES(256)"}], + "tests/stages/kuna-castobject.xml": [{"function":"exit_code","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"two_widths","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"exit_code","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"two_widths","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"}], + "tests/stages/kuna-castsign.xml": [{"function":"sign_of","verdict":"AGREES(256)"},{"function":"trim_right","verdict":"AGREES(256)"},{"function":"halved","verdict":"AGREES(256)"},{"function":"through_ptr","verdict":"AGREES(256)"},{"function":"sign_of","verdict":"AGREES(256)"},{"function":"trim_right","verdict":"AGREES(256)"},{"function":"halved","verdict":"AGREES(256)"},{"function":"through_ptr","verdict":"AGREES(256)"},{"function":"sign_of","verdict":"AGREES(256)"}], + "tests/stages/kuna-castternary.xml": [{"function":"quantum","verdict":"AGREES(256)"},{"function":"ones","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"less","verdict":"AGREES(256)"},{"function":"quantum","verdict":"AGREES(256)"},{"function":"ones","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"less","verdict":"AGREES(256)"}], + "tests/stages/kuna-castwiden.xml": [{"function":"add_load","verdict":"AGREES(256)"},{"function":"mul_two","verdict":"AGREES(256)"},{"function":"lit_mul","verdict":"AGREES(256)"},{"function":"store_long","verdict":"AGREES(256)"},{"function":"assign_size","verdict":"AGREES(256)"},{"function":"keep_less","verdict":"AGREES(256)"},{"function":"keep_mixed","verdict":"AGREES(256)"},{"function":"add_load","verdict":"AGREES(256)"},{"function":"mul_two","verdict":"AGREES(256)"},{"function":"lit_mul","verdict":"AGREES(256)"},{"function":"store_long","verdict":"AGREES(256)"},{"function":"assign_size","verdict":"AGREES(256)"},{"function":"keep_less","verdict":"AGREES(256)"},{"function":"keep_mixed","verdict":"AGREES(256)"},{"function":"add_load","verdict":"AGREES(256)"},{"function":"mul_two","verdict":"AGREES(256)"},{"function":"lit_mul","verdict":"AGREES(256)"},{"function":"store_long","verdict":"AGREES(256)"},{"function":"assign_size","verdict":"AGREES(256)"},{"function":"keep_less","verdict":"AGREES(256)"},{"function":"keep_mixed","verdict":"AGREES(256)"}], + "tests/stages/kuna-catalog.xml": [], + "tests/stages/kuna-cfstrings.xml": [{"function":"_get_greeting","verdict":"AGREES(256)"},{"function":"_get_after","verdict":"AGREES(256)"},{"function":"_get_greeting","verdict":"AGREES(256)"},{"function":"_get_after","verdict":"AGREES(256)"},{"function":"_get_greeting","verdict":"AGREES(256)"},{"function":"_get_after","verdict":"AGREES(256)"}], + "tests/stages/kuna-chainassoc.xml": [{"function":"kex","verdict":"AGREES(256)"},{"function":"odd","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"comma","verdict":"AGREES(256)"},{"function":"scan","verdict":"AGREES(256)"},{"function":"range","verdict":"AGREES(256)"},{"function":"sep","verdict":"AGREES(256)"},{"function":"kex","verdict":"AGREES(256)"},{"function":"odd","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"comma","verdict":"AGREES(256)"},{"function":"scan","verdict":"AGREES(256)"},{"function":"range","verdict":"AGREES(256)"},{"function":"sep","verdict":"AGREES(256)"}], + "tests/stages/kuna-chainfold.xml": [{"function":"store","verdict":"AGREES(256)"},{"function":"store","verdict":"AGREES(256)"},{"function":"commit","verdict":"AGREES(256)"},{"function":"commit","verdict":"AGREES(256)"},{"function":"send","verdict":"AGREES(256)"},{"function":"send","verdict":"AGREES(256)"}], + "tests/stages/kuna-charbyte.xml": [{"function":"isdash","verdict":"AGREES(256)"},{"function":"isdashu","verdict":"AGREES(256)"},{"function":"highbit","verdict":"AGREES(256)"},{"function":"ishigh","verdict":"AGREES(256)"},{"function":"dashlen","verdict":"AGREES(256)"},{"function":"argbyte","verdict":"AGREES(256)"},{"function":"sibling","verdict":"AGREES(256)"},{"function":"counter","verdict":"AGREES(256)"},{"function":"highcase","verdict":"AGREES(256)"},{"function":"isdash","verdict":"AGREES(256)"},{"function":"isdashu","verdict":"AGREES(256)"},{"function":"highbit","verdict":"AGREES(256)"},{"function":"ishigh","verdict":"AGREES(256)"},{"function":"dashlen","verdict":"AGREES(256)"},{"function":"argbyte","verdict":"AGREES(256)"},{"function":"sibling","verdict":"AGREES(256)"},{"function":"counter","verdict":"AGREES(256)"},{"function":"highcase","verdict":"AGREES(256)"}], + "tests/stages/kuna-charptr.xml": [{"function":"dropsuffix","verdict":"AGREES(256)"},{"function":"pathprefix","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"prefixcmp","verdict":"AGREES(256)"},{"function":"fieldbyte","verdict":"AGREES(256)"},{"function":"mixedwidth","verdict":"AGREES(256)"},{"function":"otherproto","verdict":"AGREES(256)"},{"function":"offsetcall","verdict":"AGREES(256)"},{"function":"fieldwalk","verdict":"AGREES(256)"},{"function":"fieldwalk2","verdict":"AGREES(256)"},{"function":"dropsuffix","verdict":"AGREES(256)"},{"function":"pathprefix","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"prefixcmp","verdict":"AGREES(256)"},{"function":"fieldbyte","verdict":"AGREES(256)"},{"function":"mixedwidth","verdict":"AGREES(256)"},{"function":"otherproto","verdict":"AGREES(256)"},{"function":"offsetcall","verdict":"AGREES(256)"},{"function":"fieldwalk","verdict":"AGREES(256)"},{"function":"fieldwalk2","verdict":"AGREES(256)"}], + "tests/stages/kuna-chkstkdarwin.xml": [{"function":"_big_frame","verdict":"AGREES(256)"},{"function":"_vla_last","verdict":"AGREES(256)"},{"function":"_probe_stub","verdict":"AGREES(256)"},{"function":"__chkstk_darwin","verdict":"AGREES(256)"},{"function":"_big_frame","verdict":"UNKNOWN(unsupported-op)"},{"function":"_vla_last","verdict":"UNKNOWN(unsupported-op)"},{"function":"_probe_stub","verdict":"UNKNOWN(unsupported-op)"},{"function":"__chkstk_darwin","verdict":"AGREES(256)"},{"function":"_big_e","verdict":"UNKNOWN(unsupported-op)"},{"function":"_vla_e","verdict":"UNKNOWN(unsupported-op)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-cnorm-braceelide.xml": [{"function":"be_fn","verdict":"AGREES(256)"},{"function":"be_fn","verdict":"AGREES(256)"}], + "tests/stages/kuna-cnorm-compoundassign.xml": [{"function":"ca_add","verdict":"AGREES(233)"},{"function":"ca_and","verdict":"AGREES(101)"},{"function":"ca_negadd","verdict":"UNKNOWN(budget)"},{"function":"ca_add","verdict":"AGREES(233)"},{"function":"ca_and","verdict":"AGREES(101)"},{"function":"ca_negadd","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-cnorm-nullprint.xml": [{"function":"nullprint_fn","verdict":"AGREES(256)"},{"function":"nullprint_fn","verdict":"AGREES(256)"}], + "tests/stages/kuna-cnorm-protogap.xml": [{"function":"protogap_fn","verdict":"AGREES(256)"},{"function":"protogap_fn","verdict":"AGREES(256)"}], + "tests/stages/kuna-cnorm-truthycond.xml": [{"function":"tfn","verdict":"AGREES(256)"},{"function":"pfn","verdict":"AGREES(256)"},{"function":"vfn","verdict":"AGREES(256)"},{"function":"tfn","verdict":"AGREES(256)"},{"function":"pfn","verdict":"AGREES(256)"},{"function":"vfn","verdict":"AGREES(256)"}], + "tests/stages/kuna-cnorm-warnstyle.xml": [{"function":"ws_fn","verdict":"AGREES(256)"},{"function":"wa_fn","verdict":"AGREES(3)"},{"function":"ws_fn","verdict":"AGREES(256)"},{"function":"wa_fn","verdict":"AGREES(3)"}], + "tests/stages/kuna-codescalar.xml": [{"function":"codebyte","verdict":"AGREES(256)"},{"function":"databyte","verdict":"AGREES(256)"}], + "tests/stages/kuna-condcall.xml": [{"function":"sub_8152","verdict":"AGREES(256)"}], + "tests/stages/kuna-condexe-heritage.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-condexeret.xml": [{"function":"twice","verdict":"AGREES(256)"},{"function":"once","verdict":"AGREES(256)"},{"function":"differ","verdict":"AGREES(256)"},{"function":"compl","verdict":"AGREES(256)"},{"function":"sfp","verdict":"AGREES(256)"},{"function":"nested","verdict":"AGREES(256)"},{"function":"comp","verdict":"AGREES(256)"},{"function":"comp2","verdict":"AGREES(256)"},{"function":"tworet","verdict":"AGREES(256)"},{"function":"tworet1","verdict":"AGREES(256)"},{"function":"tworet7","verdict":"AGREES(256)"}], + "tests/stages/kuna-condexeretuse.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pair","verdict":"AGREES(256)"},{"function":"popr","verdict":"AGREES(256)"},{"function":"differ","verdict":"AGREES(256)"},{"function":"stores","verdict":"AGREES(256)"},{"function":"compl","verdict":"AGREES(256)"},{"function":"tpick","verdict":"AGREES(256)"},{"function":"spin","verdict":"AGREES(253)"},{"function":"nrexit","verdict":"AGREES(256)"},{"function":"tnrexit","verdict":"AGREES(256)"}], + "tests/stages/kuna-conditional-register.xml": [{"function":"candidate","verdict":"AGREES(256)"}], + "tests/stages/kuna-conditional-tail-stub.xml": [{"function":"drop_if","verdict":"AGREES(256)"},{"function":"drop_endbr","verdict":"AGREES(256)"},{"function":"keep_local","verdict":"AGREES(256)"},{"function":"keep_rax","verdict":"DIFFERS(unassigned)"},{"function":"drop_if","verdict":"AGREES(256)"}], + "tests/stages/kuna-conditional-tail.xml": [{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"UNKNOWN(unsupported-op)"},{"function":"unknown","verdict":"UNKNOWN(unsupported-op)"},{"function":"middle","verdict":"UNKNOWN(unsupported-op)"},{"function":"local","verdict":"AGREES(256)"},{"function":"value_tail","verdict":"AGREES(256)"},{"function":"fatal_tail","verdict":"AGREES(2)"},{"function":"unbounded","verdict":"AGREES(256)"},{"function":"clipped_tail","verdict":"UNKNOWN(unsupported-op)"},{"function":"value_tail","verdict":"AGREES(256)"}], + "tests/stages/kuna-condstmts.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-console.xml": [], + "tests/stages/kuna-constptrdeclared-msp430.xml": [{"function":"f1","verdict":"AGREES(256)"}], + "tests/stages/kuna-constptrdeclared-riscv.xml": [{"function":"rq","verdict":"AGREES(256)"},{"function":"ru","verdict":"AGREES(256)"},{"function":"rl","verdict":"AGREES(256)"}], + "tests/stages/kuna-constptrdeclared-x86.xml": [{"function":"cd","verdict":"AGREES(256)"},{"function":"dret","verdict":"AGREES(256)"},{"function":"cl","verdict":"AGREES(256)"},{"function":"laddr","verdict":"AGREES(256)"},{"function":"pret","verdict":"AGREES(256)"},{"function":"cs","verdict":"AGREES(256)"},{"function":"ebig","verdict":"AGREES(256)"},{"function":"laddr","verdict":"AGREES(256)"},{"function":"pret","verdict":"AGREES(256)"}], + "tests/stages/kuna-cookiescramble.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-copiedconst.xml": [{"function":"twice","verdict":"AGREES(256)"},{"function":"twice_word","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"swap","verdict":"AGREES(256)"},{"function":"staged","verdict":"AGREES(256)"},{"function":"hole","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"built","verdict":"AGREES(256)"},{"function":"ordered","verdict":"AGREES(256)"},{"function":"lowered","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"widths","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"twice_word","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"swap","verdict":"AGREES(256)"},{"function":"staged","verdict":"AGREES(256)"},{"function":"hole","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"built","verdict":"AGREES(256)"},{"function":"ordered","verdict":"AGREES(256)"},{"function":"lowered","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"widths","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"pooled","verdict":"AGREES(256)"},{"function":"optnull","verdict":"AGREES(256)"},{"function":"sctty","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"opened","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"twice_word","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"swap","verdict":"AGREES(256)"},{"function":"staged","verdict":"AGREES(256)"},{"function":"hole","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"built","verdict":"AGREES(256)"},{"function":"ordered","verdict":"AGREES(256)"},{"function":"lowered","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"widths","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"twice_word","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"swap","verdict":"AGREES(256)"},{"function":"staged","verdict":"AGREES(256)"},{"function":"hole","verdict":"AGREES(256)"},{"function":"stored","verdict":"AGREES(256)"},{"function":"built","verdict":"AGREES(256)"},{"function":"ordered","verdict":"AGREES(256)"},{"function":"lowered","verdict":"AGREES(256)"},{"function":"narrow","verdict":"AGREES(256)"},{"function":"widths","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"merged","verdict":"AGREES(256)"},{"function":"pooled","verdict":"AGREES(256)"},{"function":"optnull","verdict":"AGREES(256)"},{"function":"sctty","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"opened","verdict":"AGREES(256)"}], + "tests/stages/kuna-copywaves.xml": [{"function":"churn","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-cortexmpriv.xml": [{"function":"read_basepri","verdict":"AGREES(256)"},{"function":"read_basepri","verdict":"AGREES(256)"}], + "tests/stages/kuna-ctype-header-names.xml": [], + "tests/stages/kuna-ctypes.xml": [{"function":"printf","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"printf","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/kuna-custom-call-storage.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"mapper","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only_caller","verdict":"AGREES(256)"},{"function":"return_only_caller","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only_caller","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only","verdict":"AGREES(256)"},{"function":"return_only_caller","verdict":"AGREES(256)"},{"function":"no_inputs","verdict":"AGREES(256)"}], + "tests/stages/kuna-cxxalloc.xml": [{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401050","verdict":"AGREES(256)"},{"function":"drop_array","verdict":"AGREES(256)"}], + "tests/stages/kuna-deadcascade.xml": [{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"churn","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-deadwaves.xml": [{"function":"churn","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-declared-callback-c.xml": [{"function":"invoke","verdict":"AGREES(256)"},{"function":"publish","verdict":"AGREES(256)"},{"function":"invoke_slot","verdict":"AGREES(256)"},{"function":"invoke_twice","verdict":"AGREES(256)"},{"function":"get_slot","verdict":"AGREES(256)"},{"function":"invoke_record","verdict":"AGREES(256)"},{"function":"invoke","verdict":"AGREES(256)"},{"function":"publish","verdict":"AGREES(256)"},{"function":"invoke_twice","verdict":"AGREES(256)"}], + "tests/stages/kuna-declaredlibcproto.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-declaredpop.xml": [{"function":"sub_401000","verdict":"AGREES(256)"}], + "tests/stages/kuna-declaring-double-score-return.xml": [{"function":"score","verdict":"DIFFERS(return)"},{"function":"clobber_caller","verdict":"DIFFERS(unassigned)"},{"function":"exact_clobber_caller","verdict":"DIFFERS(unassigned)"},{"function":"wide_exact_caller","verdict":"DIFFERS(return)"},{"function":"refined_score","verdict":"DIFFERS(return)"},{"function":"refined_score","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-declorder.xml": [{"function":"tally12","verdict":"AGREES(256)"},{"function":"tally12","verdict":"AGREES(256)"}], + "tests/stages/kuna-decodehalt.xml": [{"function":"dh_fn","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-dedup-goto-arm.xml": [{"function":"g","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-dedupitetail-gototarget.xml": [{"function":"g","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-dedupitetail-switchgoto.xml": [{"function":"g","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-devectorize-effects.xml": [{"function":"sum_flag","verdict":"AGREES(16)"},{"function":"sum_count","verdict":"AGREES(16)"},{"function":"sum_flag","verdict":"AGREES(16)"},{"function":"sum_count","verdict":"AGREES(16)"}], + "tests/stages/kuna-devectorize.xml": [{"function":"byte_sum","verdict":"AGREES(16)"},{"function":"byte_sum","verdict":"AGREES(16)"}], + "tests/stages/kuna-devirtualize-frame.xml": [{"function":"tg_between","verdict":"AGREES(256)"}], + "tests/stages/kuna-devirtualize-interp.xml": [{"function":"sw_writable","verdict":"AGREES(256)"},{"function":"sw_writable","verdict":"AGREES(256)"},{"function":"sw_readonly","verdict":"AGREES(256)"},{"function":"th_copied","verdict":"AGREES(256)"},{"function":"th_inline","verdict":"AGREES(256)"},{"function":"wv_woven","verdict":"AGREES(256)"},{"function":"sw_patched","verdict":"AGREES(256)"},{"function":"tg_indexed","verdict":"AGREES(256)"},{"function":"tg_istore","verdict":"AGREES(256)"},{"function":"tg_carried","verdict":"AGREES(256)"}], + "tests/stages/kuna-devirtualize-slot.xml": [{"function":"tg_reuse","verdict":"AGREES(256)"}], + "tests/stages/kuna-devirtualize-sound.xml": [{"function":"f_sum","verdict":"AGREES(256)"},{"function":"f_eq","verdict":"AGREES(256)"},{"function":"f_big","verdict":"UNKNOWN(budget)"},{"function":"f_mem","verdict":"AGREES(256)"},{"function":"f_corr","verdict":"AGREES(256)"},{"function":"f_call","verdict":"AGREES(256)"},{"function":"f_tbl","verdict":"AGREES(256)"},{"function":"f_glob","verdict":"AGREES(256)"},{"function":"f_gcall","verdict":"AGREES(256)"},{"function":"f_ptr","verdict":"AGREES(256)"},{"function":"f_ploop","verdict":"AGREES(256)"},{"function":"f_join","verdict":"AGREES(256)"},{"function":"f_callp","verdict":"AGREES(256)"},{"function":"f_deep","verdict":"UNKNOWN(budget)"},{"function":"f_ijmp","verdict":"AGREES(256)"},{"function":"f_epi","verdict":"AGREES(256)"},{"function":"f_sel","verdict":"AGREES(256)"},{"function":"f_mba","verdict":"AGREES(256)"},{"function":"f_spbit","verdict":"UNKNOWN(unsupported-op)"},{"function":"f_out","verdict":"AGREES(256)"},{"function":"f_arg","verdict":"AGREES(256)"},{"function":"f_below","verdict":"AGREES(256)"},{"function":"f_ctx","verdict":"AGREES(256)"},{"function":"f_ctxi","verdict":"UNKNOWN(trap)"},{"function":"f_cell","verdict":"AGREES(256)"},{"function":"f_lost","verdict":"AGREES(256)"}], + "tests/stages/kuna-devirtualize.xml": [{"function":"func","verdict":"UNKNOWN(unsupported-op)"},{"function":"func","verdict":"AGREES(256)"},{"function":"func","verdict":"AGREES(256)"}], + "tests/stages/kuna-dispatch-values.xml": [{"function":"foreign_copy_n32","verdict":"UNKNOWN(unsupported-op)"},{"function":"narrow_n32","verdict":"UNKNOWN(unsupported-op)"},{"function":"foreign_copy_64","verdict":"UNKNOWN(unsupported-op)"},{"function":"narrow_64","verdict":"UNKNOWN(unsupported-op)"},{"function":"edge_n32","verdict":"UNKNOWN(unsupported-op)"},{"function":"edge_64","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-dropjump.xml": [{"function":"fd","verdict":"AGREES(256)"},{"function":"fg","verdict":"DIVERGES(switchrunon-cut-row)"}], + "tests/stages/kuna-duplabels.xml": [{"function":"arith","verdict":"AGREES(256)"}], + "tests/stages/kuna-dwarf-addrx.xml": [{"function":"bump","verdict":"AGREES(256)"},{"function":"bump","verdict":"AGREES(256)"}], + "tests/stages/kuna-dwarfvariants.xml": [{"function":"ret_result","verdict":"AGREES(256)"},{"function":"ret_three","verdict":"AGREES(256)"},{"function":"ret_pair","verdict":"AGREES(256)"},{"function":"ret_plain","verdict":"AGREES(256)"},{"function":"put_res","verdict":"AGREES(256)"},{"function":"put_opt","verdict":"AGREES(256)"},{"function":"r16","verdict":"AGREES(256)"}], + "tests/stages/kuna-dyldcacheobjc.xml": [{"function":"sub_180001800","verdict":"AGREES(256)"},{"function":"-[Greeter greet:]","verdict":"AGREES(256)"},{"function":"-[Greeter count]","verdict":"AGREES(256)"},{"function":"sub_180001820","verdict":"AGREES(256)"},{"function":"sub_180001830","verdict":"AGREES(256)"},{"function":"-[Greeter greet:]","verdict":"AGREES(256)"}], + "tests/stages/kuna-dyldcrossrefs.xml": [{"function":"caller_entry","verdict":"AGREES(256)"},{"function":"caller_indirect","verdict":"AGREES(256)"},{"function":"caller_entry","verdict":"AGREES(256)"},{"function":"caller_indirect","verdict":"AGREES(256)"}], + "tests/stages/kuna-dyldimage-merge.xml": [{"function":"caller_entry","verdict":"AGREES(256)"},{"function":"_callee_add","verdict":"AGREES(256)"},{"function":"caller_entry","verdict":"AGREES(256)"}], + "tests/stages/kuna-e500-call-slots.xml": [{"function":"constant_call","verdict":"AGREES(256)"},{"function":"constant_call","verdict":"AGREES(256)"},{"function":"arithmetic_call","verdict":"AGREES(256)"},{"function":"call_result","verdict":"AGREES(256)"},{"function":"conditional_call","verdict":"AGREES(256)"}], + "tests/stages/kuna-earlyrestart.xml": [{"function":"main","verdict":"DIFFERS(call at 0x113f to 0x1350)"}], + "tests/stages/kuna-ebpf-elf-map-reloc.xml": [{"function":"prog","verdict":"AGREES(256)"},{"function":"prog","verdict":"AGREES(256)"},{"function":"prog","verdict":"AGREES(256)"},{"function":"prog","verdict":"AGREES(256)"},{"function":"prog","verdict":"AGREES(256)"}], + "tests/stages/kuna-elemptr.xml": [{"function":"w_decode","verdict":"AGREES(203)"},{"function":"w_build","verdict":"AGREES(256)"},{"function":"w_sidx","verdict":"AGREES(85)"},{"function":"w_table","verdict":"AGREES(103)"},{"function":"w_record","verdict":"AGREES(85)"},{"function":"w_mixed","verdict":"AGREES(256)"},{"function":"w_wu","verdict":"AGREES(256)"},{"function":"w_put","verdict":"AGREES(256)"},{"function":"w_ctr","verdict":"AGREES(92)"},{"function":"w_hdr","verdict":"AGREES(256)"},{"function":"w_gpbump","verdict":"AGREES(256)"},{"function":"w_tfirst","verdict":"AGREES(256)"},{"function":"w_nexttab","verdict":"AGREES(256)"},{"function":"w_pick","verdict":"AGREES(90)"},{"function":"w_decode","verdict":"AGREES(203)"},{"function":"w_build","verdict":"AGREES(256)"},{"function":"w_sidx","verdict":"AGREES(85)"},{"function":"w_table","verdict":"AGREES(103)"},{"function":"w_record","verdict":"AGREES(85)"},{"function":"w_mixed","verdict":"AGREES(256)"},{"function":"w_wu","verdict":"AGREES(256)"},{"function":"w_put","verdict":"AGREES(256)"},{"function":"w_ctr","verdict":"AGREES(92)"},{"function":"w_hdr","verdict":"AGREES(256)"},{"function":"w_gpbump","verdict":"AGREES(256)"},{"function":"w_tfirst","verdict":"AGREES(256)"},{"function":"w_nexttab","verdict":"AGREES(256)"},{"function":"w_pick","verdict":"AGREES(90)"}], + "tests/stages/kuna-elf-unwind-pcread.xml": [{"function":"bump","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-elfaliasnames.xml": [{"function":"answer","verdict":"AGREES(256)"},{"function":"__answer_from_arm","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"},{"function":"shared","verdict":"AGREES(256)"},{"function":"twin","verdict":"AGREES(256)"}], + "tests/stages/kuna-elfgotimports.xml": [{"function":"get_counter","verdict":"AGREES(256)"},{"function":"get_exported","verdict":"AGREES(256)"},{"function":"get_counter","verdict":"AGREES(256)"},{"function":"get_exported","verdict":"AGREES(256)"},{"function":"get_counter","verdict":"AGREES(256)"},{"function":"get_exported","verdict":"AGREES(256)"},{"function":"get_counter","verdict":"AGREES(256)"},{"function":"get_exported","verdict":"AGREES(256)"}], + "tests/stages/kuna-elfmain-named.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/kuna-elfmain.xml": [{"function":"sub_1405","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"sub_1026","verdict":"AGREES(256)"},{"function":"main","verdict":"DIFFERS(call at 0x1044 to 0x1050)"}], + "tests/stages/kuna-elfv1-exportroots.xml": [], + "tests/stages/kuna-elfv1-symbolextent.xml": [{"function":"sample","verdict":"AGREES(256)"},{"function":"exact24","verdict":"AGREES(256)"},{"function":"sample","verdict":"AGREES(256)"},{"function":"exact24","verdict":"AGREES(256)"}], + "tests/stages/kuna-emptystrconst.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-endptrbound.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"m","verdict":"AGREES(256)"},{"function":"r","verdict":"AGREES(256)"},{"function":"c","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"m","verdict":"AGREES(256)"},{"function":"r","verdict":"AGREES(256)"},{"function":"c","verdict":"AGREES(256)"}], + "tests/stages/kuna-entrymainproto.xml": [{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/kuna-entryretdispatch.xml": [{"function":"entry_dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-entrythumbflow.xml": [{"function":"sub_401000","verdict":"AGREES(256)"}], + "tests/stages/kuna-epiloguepop-sysv.xml": [{"function":"twice","verdict":"AGREES(256)"},{"function":"halfsel","verdict":"AGREES(256)"},{"function":"halfsel_redzone","verdict":"AGREES(256)"},{"function":"konst","verdict":"AGREES(256)"}], + "tests/stages/kuna-epiloguepop-x87.xml": [{"function":"twice","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-epiloguepop.xml": [{"function":"halfsel","verdict":"UNKNOWN(unsupported-op)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"eflags","verdict":"AGREES(256)"},{"function":"spill","verdict":"AGREES(256)"},{"function":"pair","verdict":"AGREES(256)"}], + "tests/stages/kuna-evalcurrentproto.xml": [{"function":"fc","verdict":"AGREES(256)"}], + "tests/stages/kuna-exclusivearguse.xml": [{"function":"append","verdict":"AGREES(256)"},{"function":"append_loop","verdict":"AGREES(5)"}], + "tests/stages/kuna-expandload-opsize.xml": [{"function":"t_bit","verdict":"AGREES(256)"},{"function":"t_test","verdict":"AGREES(256)"}], + "tests/stages/kuna-extent-direct-branch.xml": [{"function":"outer","verdict":"AGREES(256)"},{"function":"outer","verdict":"AGREES(256)"},{"function":"veneer","verdict":"AGREES(256)"},{"function":"outer_indirect","verdict":"AGREES(256)"}], + "tests/stages/kuna-extent-fallthrough.xml": [{"function":"outer","verdict":"AGREES(256)"},{"function":"outer","verdict":"AGREES(256)"}], + "tests/stages/kuna-extrapop-function.xml": [{"function":"f","verdict":"DIFFERS(return)"},{"function":"f","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"}], + "tests/stages/kuna-fastfailnoreturn.xml": [{"function":"fastfail_guard","verdict":"AGREES(254)"}], + "tests/stages/kuna-fatalchain.xml": [{"function":"reply","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"reply","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"compose","verdict":"AGREES(256)"},{"function":"compose","verdict":"AGREES(256)"}], + "tests/stages/kuna-fatstr.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-fcmp-unordered.xml": [{"function":"a64_eq","verdict":"AGREES(256)"},{"function":"a64_ne","verdict":"AGREES(256)"},{"function":"a64_mi","verdict":"AGREES(256)"},{"function":"a64_pl","verdict":"AGREES(256)"},{"function":"a64_ge","verdict":"AGREES(256)"},{"function":"a64_lt","verdict":"AGREES(256)"},{"function":"a64_gt","verdict":"AGREES(256)"},{"function":"a64_le","verdict":"AGREES(256)"},{"function":"a64_hi","verdict":"AGREES(256)"},{"function":"a64_ls","verdict":"AGREES(256)"},{"function":"a64_hs","verdict":"AGREES(256)"},{"function":"a64_lo","verdict":"AGREES(256)"},{"function":"a64_gt_zero","verdict":"AGREES(256)"},{"function":"a64_le_branch","verdict":"AGREES(256)"},{"function":"a32_gt","verdict":"AGREES(256)"},{"function":"a32_le","verdict":"AGREES(256)"},{"function":"a32_ge","verdict":"AGREES(256)"},{"function":"a32_lt","verdict":"AGREES(256)"},{"function":"a32_pl","verdict":"AGREES(256)"},{"function":"a32_mi","verdict":"AGREES(256)"},{"function":"scale_err","verdict":"AGREES(256)"},{"function":"logish","verdict":"AGREES(256)"},{"function":"ccw_mixed","verdict":"AGREES(256)"}], + "tests/stages/kuna-fcvtround-a64.xml": [{"function":"floor_i","verdict":"AGREES(256)"},{"function":"ceil_i","verdict":"AGREES(256)"},{"function":"table_lerp","verdict":"AGREES(256)"},{"function":"round_i","verdict":"AGREES(256)"},{"function":"rne_i","verdict":"UNKNOWN(unsupported-op)"},{"function":"floor_l","verdict":"AGREES(256)"},{"function":"ceil_simd","verdict":"AGREES(256)"},{"function":"floor_f","verdict":"AGREES(256)"},{"function":"ceil_d","verdict":"AGREES(256)"},{"function":"round_d","verdict":"AGREES(256)"},{"function":"rne_f","verdict":"UNKNOWN(unsupported-op)"},{"function":"rint_d","verdict":"UNKNOWN(unsupported-op)"},{"function":"nearby_d","verdict":"UNKNOWN(unsupported-op)"},{"function":"trunc_d","verdict":"UNKNOWN(unsupported-op)"},{"function":"has_frac","verdict":"AGREES(256)"},{"function":"ufloor","verdict":"AGREES(256)"},{"function":"vfloor","verdict":"AGREES(256)"},{"function":"uceil_l","verdict":"AGREES(256)"},{"function":"floor_h","verdict":"UNKNOWN(unsupported-op)"},{"function":"f32z_hi","verdict":"AGREES(256)"},{"function":"f64x_s","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-fieldtype.xml": [{"function":"buf_shift","verdict":"AGREES(60)"},{"function":"ent_release","verdict":"AGREES(256)"},{"function":"ops_run","verdict":"AGREES(256)"},{"function":"range_walk","verdict":"AGREES(4)"},{"function":"cell_val","verdict":"AGREES(256)"},{"function":"slot_post","verdict":"AGREES(256)"},{"function":"buf_shift","verdict":"AGREES(60)"},{"function":"ent_release","verdict":"AGREES(256)"},{"function":"ops_run","verdict":"AGREES(256)"},{"function":"range_walk","verdict":"AGREES(4)"},{"function":"cell_val","verdict":"AGREES(256)"},{"function":"slot_post","verdict":"AGREES(256)"},{"function":"pctx_print","verdict":"AGREES(256)"},{"function":"pctx_print","verdict":"AGREES(256)"}], + "tests/stages/kuna-flagwidth.xml": [{"function":"count_runs","verdict":"AGREES(85)"},{"function":"join_words","verdict":"AGREES(71)"},{"function":"join_words_b","verdict":"AGREES(71)"},{"function":"spill_flag","verdict":"AGREES(64)"},{"function":"b_field","verdict":"AGREES(85)"},{"function":"bool_or_seen","verdict":"AGREES(85)"},{"function":"count_runs","verdict":"AGREES(85)"},{"function":"join_words","verdict":"AGREES(71)"},{"function":"join_words_b","verdict":"AGREES(71)"},{"function":"spill_flag","verdict":"AGREES(64)"},{"function":"b_field","verdict":"AGREES(85)"},{"function":"bool_or_seen","verdict":"AGREES(85)"}], + "tests/stages/kuna-flexarray.xml": [{"function":"first_byte","verdict":"AGREES(256)"},{"function":"get_item","verdict":"AGREES(256)"}], + "tests/stages/kuna-float-storage-truncation.xml": [{"function":"low_bits","verdict":"AGREES(256)"},{"function":"numeric","verdict":"AGREES(256)"},{"function":"integer","verdict":"AGREES(256)"},{"function":"low_bits","verdict":"AGREES(256)"},{"function":"numeric","verdict":"AGREES(256)"},{"function":"integer","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatbits.xml": [{"function":"fb_fabsf","verdict":"AGREES(256)"},{"function":"fb_negf","verdict":"AGREES(256)"},{"function":"fb_copysignf","verdict":"AGREES(256)"},{"function":"fb_isnanf","verdict":"AGREES(256)"},{"function":"fb_bump","verdict":"AGREES(256)"},{"function":"fb_store","verdict":"AGREES(256)"},{"function":"fb_mix","verdict":"AGREES(256)"},{"function":"fb_fabsf","verdict":"AGREES(256)"},{"function":"fb_negf","verdict":"AGREES(256)"},{"function":"fb_copysignf","verdict":"AGREES(256)"},{"function":"fb_isnanf","verdict":"AGREES(256)"},{"function":"fb_fabs","verdict":"AGREES(256)"},{"function":"fb_bump","verdict":"AGREES(256)"},{"function":"fb_store","verdict":"AGREES(256)"},{"function":"fb_mix","verdict":"AGREES(256)"},{"function":"fb_fabsf","verdict":"AGREES(256)"},{"function":"fb_negf","verdict":"AGREES(256)"},{"function":"fb_copysignf","verdict":"AGREES(256)"},{"function":"fb_isnanf","verdict":"AGREES(256)"},{"function":"fb_bump","verdict":"AGREES(256)"},{"function":"fb_store","verdict":"AGREES(256)"},{"function":"fb_mix","verdict":"AGREES(256)"},{"function":"fb_fabs","verdict":"AGREES(256)"},{"function":"fr_isqnan0","verdict":"AGREES(256)"},{"function":"fr_iszero","verdict":"AGREES(256)"},{"function":"fr_eqbits","verdict":"AGREES(256)"},{"function":"fr_ne0","verdict":"AGREES(256)"},{"function":"fr_isinf","verdict":"AGREES(256)"},{"function":"fr_isone","verdict":"AGREES(256)"},{"function":"fr_tenth","verdict":"AGREES(256)"},{"function":"fr_fmax","verdict":"AGREES(256)"},{"function":"fr_fmin","verdict":"AGREES(256)"},{"function":"fr_onep","verdict":"AGREES(256)"},{"function":"fr_third","verdict":"AGREES(256)"},{"function":"fr_big","verdict":"AGREES(256)"},{"function":"fr_sel","verdict":"AGREES(256)"},{"function":"fr_unset","verdict":"AGREES(256)"},{"function":"fr_canon","verdict":"AGREES(256)"},{"function":"fr_isqnan0","verdict":"AGREES(256)"},{"function":"fr_iszero","verdict":"AGREES(256)"},{"function":"fr_eqbits","verdict":"AGREES(256)"},{"function":"fr_ne0","verdict":"AGREES(256)"},{"function":"fr_isinf","verdict":"AGREES(256)"},{"function":"fr_isone","verdict":"AGREES(256)"},{"function":"fr_tenth","verdict":"AGREES(256)"},{"function":"fr_fmax","verdict":"AGREES(256)"},{"function":"fr_fmin","verdict":"AGREES(256)"},{"function":"fr_onep","verdict":"AGREES(256)"},{"function":"fr_third","verdict":"AGREES(256)"},{"function":"fr_big","verdict":"AGREES(256)"},{"function":"fr_sel","verdict":"AGREES(256)"},{"function":"fr_unset","verdict":"AGREES(256)"},{"function":"fr_lowzero","verdict":"AGREES(256)"},{"function":"fr_andv","verdict":"AGREES(256)"},{"function":"fr_negy","verdict":"AGREES(256)"},{"function":"fr_lowflip","verdict":"AGREES(256)"},{"function":"fr_isqnan0","verdict":"AGREES(256)"},{"function":"fr_iszero","verdict":"AGREES(256)"},{"function":"fr_eqbits","verdict":"AGREES(256)"},{"function":"fr_ne0","verdict":"AGREES(256)"},{"function":"fr_isinf","verdict":"AGREES(256)"},{"function":"fr_isone","verdict":"AGREES(256)"},{"function":"fr_tenth","verdict":"AGREES(256)"},{"function":"fr_fmax","verdict":"AGREES(256)"},{"function":"fr_fmin","verdict":"AGREES(256)"},{"function":"fr_onep","verdict":"AGREES(256)"},{"function":"fr_third","verdict":"AGREES(256)"},{"function":"fr_big","verdict":"AGREES(256)"},{"function":"fr_canon","verdict":"AGREES(256)"}], + "tests/stages/kuna-floateq.xml": [{"function":"fq_negzero","verdict":"AGREES(256)"},{"function":"fq_qnan","verdict":"AGREES(256)"},{"function":"fq_two","verdict":"AGREES(256)"},{"function":"fq_dnegzero","verdict":"AGREES(256)"},{"function":"fq_dqnan","verdict":"AGREES(256)"},{"function":"fq_abszero","verdict":"AGREES(256)"},{"function":"fq_one","verdict":"AGREES(256)"},{"function":"fq_feq","verdict":"AGREES(256)"},{"function":"fq_dfne","verdict":"AGREES(256)"},{"function":"fq_negzero","verdict":"AGREES(256)"},{"function":"fq_qnan","verdict":"AGREES(256)"},{"function":"fq_two","verdict":"AGREES(256)"},{"function":"fq_dnegzero","verdict":"AGREES(256)"},{"function":"fq_dqnan","verdict":"AGREES(256)"},{"function":"fq_abszero","verdict":"AGREES(256)"},{"function":"fq_one","verdict":"AGREES(256)"},{"function":"fq_feq","verdict":"AGREES(256)"},{"function":"fq_dfne","verdict":"AGREES(256)"},{"function":"fq_negzero","verdict":"AGREES(256)"},{"function":"fq_qnan","verdict":"AGREES(256)"},{"function":"fq_two","verdict":"AGREES(256)"},{"function":"fq_dnegzero","verdict":"AGREES(256)"},{"function":"fq_dqnan","verdict":"AGREES(256)"},{"function":"fq_abszero","verdict":"AGREES(256)"},{"function":"fq_one","verdict":"AGREES(256)"},{"function":"fq_feq","verdict":"AGREES(256)"},{"function":"fq_dfne","verdict":"AGREES(256)"},{"function":"fq_negzero","verdict":"AGREES(256)"},{"function":"fq_qnan","verdict":"AGREES(256)"},{"function":"fq_two","verdict":"AGREES(256)"},{"function":"fq_abszero","verdict":"AGREES(256)"},{"function":"fq_one","verdict":"AGREES(256)"},{"function":"fq_feq","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatglobals.xml": [{"function":"fy","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"set_gpun","verdict":"AGREES(256)"},{"function":"setz","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"set_gpun","verdict":"AGREES(256)"},{"function":"setz","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"set_gpun","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"ixa","verdict":"AGREES(256)"},{"function":"lv0","verdict":"AGREES(256)"},{"function":"fld","verdict":"AGREES(256)"},{"function":"neg","verdict":"AGREES(256)"},{"function":"put","verdict":"AGREES(256)"},{"function":"ixa","verdict":"AGREES(256)"},{"function":"lv0","verdict":"AGREES(256)"},{"function":"ixs","verdict":"AGREES(256)"},{"function":"fld","verdict":"AGREES(256)"},{"function":"neg","verdict":"AGREES(256)"},{"function":"put","verdict":"AGREES(256)"},{"function":"ixa","verdict":"AGREES(256)"},{"function":"lv0","verdict":"AGREES(256)"},{"function":"put","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatgrouping.xml": [{"function":"right_grouped","verdict":"AGREES(256)"},{"function":"left_grouped","verdict":"AGREES(256)"},{"function":"right_sum","verdict":"AGREES(256)"},{"function":"left_sum","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatlane.xml": [{"function":"narrow","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"narrowg","verdict":"AGREES(256)"},{"function":"fromint","verdict":"AGREES(256)"},{"function":"dbl","verdict":"AGREES(256)"},{"function":"mk","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatparam.xml": [{"function":"fs","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"fr","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"bits","verdict":"AGREES(256)"},{"function":"sink","verdict":"AGREES(256)"},{"function":"fs","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"fr","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"sink","verdict":"AGREES(256)"},{"function":"fs","verdict":"AGREES(256)"},{"function":"ff","verdict":"AGREES(256)"},{"function":"fr","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"fy","verdict":"AGREES(256)"},{"function":"bits","verdict":"AGREES(256)"},{"function":"sink","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatprecision.xml": [{"function":"widened_update","verdict":"AGREES(256)"},{"function":"packed_update","verdict":"AGREES(256)"},{"function":"float_update","verdict":"AGREES(256)"},{"function":"widen_roundtrip","verdict":"DIVERGES(nan-quieting)"},{"function":"widened_product","verdict":"AGREES(256)"},{"function":"widened_quotient","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatret.xml": [{"function":"qnanf_","verdict":"AGREES(256)"},{"function":"logish","verdict":"AGREES(256)"},{"function":"qp","verdict":"AGREES(256)"},{"function":"sn","verdict":"AGREES(256)"},{"function":"nn","verdict":"AGREES(256)"},{"function":"third","verdict":"AGREES(256)"},{"function":"sub_11c0","verdict":"AGREES(256)"},{"function":"sub_11d0","verdict":"AGREES(256)"},{"function":"sub_11f0","verdict":"AGREES(256)"},{"function":"putf2","verdict":"AGREES(256)"}], + "tests/stages/kuna-floatstore.xml": [{"function":"mat_init","verdict":"AGREES(256)"},{"function":"mat_init","verdict":"AGREES(256)"},{"function":"mat_param","verdict":"AGREES(256)"},{"function":"mat_param","verdict":"AGREES(256)"}], + "tests/stages/kuna-flowmode.xml": [{"function":"sub_2000080","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_2000080","verdict":"AGREES(256)"},{"function":"sub_2000080","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_2000080","verdict":"AGREES(256)"},{"function":"sub_2000040","verdict":"AGREES(256)"},{"function":"sub_2000000","verdict":"AGREES(256)"}], + "tests/stages/kuna-foldcallret-barrier.xml": [{"function":"target","verdict":"AGREES(256)"},{"function":"target2","verdict":"AGREES(256)"}], + "tests/stages/kuna-foldcallret-shortcircuit.xml": [{"function":"w1f","verdict":"AGREES(256)"},{"function":"w4f","verdict":"AGREES(256)"},{"function":"w1f","verdict":"AGREES(256)"},{"function":"w4f","verdict":"AGREES(256)"},{"function":"w4f","verdict":"AGREES(256)"}], + "tests/stages/kuna-foldcallretphi-join.xml": [{"function":"target","verdict":"AGREES(256)"},{"function":"target","verdict":"AGREES(256)"}], + "tests/stages/kuna-foldcallretphi.xml": [{"function":"target","verdict":"AGREES(256)"},{"function":"target","verdict":"AGREES(256)"},{"function":"target2","verdict":"AGREES(256)"},{"function":"target3","verdict":"AGREES(256)"}], + "tests/stages/kuna-formatstring-static.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"report","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(23)"},{"function":"report","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(23)"},{"function":"report","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(23)"},{"function":"_main","verdict":"AGREES(256)"},{"function":"_main","verdict":"AGREES(256)"},{"function":"_main","verdict":"AGREES(256)"},{"function":"f_conv","verdict":"AGREES(256)"},{"function":"f_sum","verdict":"AGREES(256)"},{"function":"f_is","verdict":"AGREES(256)"},{"function":"f_conv","verdict":"AGREES(256)"},{"function":"f_sum","verdict":"AGREES(256)"},{"function":"f_is","verdict":"AGREES(256)"},{"function":"f_conv","verdict":"AGREES(256)"},{"function":"f_sum","verdict":"AGREES(256)"},{"function":"f_is","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"show2","verdict":"AGREES(256)"},{"function":"rd","verdict":"AGREES(256)"},{"function":"show_zu","verdict":"AGREES(256)"},{"function":"show_td","verdict":"AGREES(256)"},{"function":"show_zu","verdict":"AGREES(256)"},{"function":"show_td","verdict":"AGREES(256)"},{"function":"show_zu","verdict":"AGREES(256)"},{"function":"show_td","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"AGREES(256)"},{"function":"credits","verdict":"AGREES(256)"},{"function":"credits","verdict":"AGREES(256)"},{"function":"credits","verdict":"AGREES(256)"},{"function":"show9","verdict":"AGREES(256)"},{"function":"read_int","verdict":"AGREES(256)"},{"function":"read_chars","verdict":"AGREES(256)"},{"function":"show9","verdict":"AGREES(256)"},{"function":"read_int","verdict":"AGREES(256)"},{"function":"read_chars","verdict":"AGREES(256)"},{"function":"show9","verdict":"AGREES(256)"},{"function":"read_int","verdict":"AGREES(256)"},{"function":"read_chars","verdict":"AGREES(256)"}], + "tests/stages/kuna-fpu-trunc-views.xml": [{"function":"phi_0","verdict":"AGREES(256)"},{"function":"phi_1","verdict":"AGREES(256)"},{"function":"transport","verdict":"AGREES(256)"},{"function":"effect","verdict":"AGREES(256)"},{"function":"clobber","verdict":"AGREES(256)"}], + "tests/stages/kuna-framepublish-seh.xml": [{"function":"seh_push_ecx","verdict":"AGREES(256)"},{"function":"mid_published","verdict":"AGREES(256)"}], + "tests/stages/kuna-framerecord.xml": [{"function":"sample","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"escaped","verdict":"AGREES(256)"},{"function":"logwrap","verdict":"AGREES(256)"},{"function":"logcopy","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"early","verdict":"AGREES(256)"},{"function":"local","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"plain","verdict":"AGREES(256)"}], + "tests/stages/kuna-framereload-a64.xml": [{"function":"get3","verdict":"AGREES(256)"},{"function":"uw4","verdict":"AGREES(256)"}], + "tests/stages/kuna-framereload.xml": [{"function":"f3","verdict":"AGREES(256)"},{"function":"dm","verdict":"AGREES(256)"},{"function":"pun","verdict":"AGREES(256)"},{"function":"half","verdict":"AGREES(256)"},{"function":"twoi","verdict":"AGREES(256)"},{"function":"pieces","verdict":"AGREES(256)"},{"function":"lfillf","verdict":"AGREES(256)"}], + "tests/stages/kuna-funcstart-symbolextent.xml": [], + "tests/stages/kuna-glibcvoidimport.xml": [{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"turn","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"}], + "tests/stages/kuna-global-aggregate-store.xml": [{"function":"update","verdict":"AGREES(256)"}], + "tests/stages/kuna-global-array-member-store.xml": [{"function":"update","verdict":"AGREES(256)"}], + "tests/stages/kuna-global-load-call-order.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"no_finish","verdict":"AGREES(256)"},{"function":"loop_clear","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalarrayanchor-a64.xml": [{"function":"negative","verdict":"AGREES(256)"},{"function":"negative","verdict":"AGREES(256)"},{"function":"negative_load","verdict":"AGREES(256)"},{"function":"two_indices","verdict":"AGREES(256)"},{"function":"byte_index","verdict":"AGREES(256)"},{"function":"word_index","verdict":"AGREES(256)"},{"function":"wide_byte","verdict":"AGREES(256)"},{"function":"wide_short","verdict":"AGREES(256)"},{"function":"float_bits","verdict":"AGREES(256)"},{"function":"wide_index_u32","verdict":"AGREES(256)"},{"function":"wrapped_index_u32","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalarrayanchor.xml": [{"function":"clear_slot","verdict":"AGREES(256)"},{"function":"clear_slot","verdict":"AGREES(256)"},{"function":"clear_neighbor","verdict":"AGREES(256)"},{"function":"clear_unbiased","verdict":"AGREES(256)"},{"function":"clear_unmapped","verdict":"AGREES(256)"},{"function":"clear_byte","verdict":"AGREES(256)"},{"function":"calculate","verdict":"AGREES(256)"},{"function":"read_slot","verdict":"AGREES(256)"},{"function":"clear_positive","verdict":"AGREES(256)"},{"function":"clear_far","verdict":"AGREES(256)"},{"function":"clear_unscaled","verdict":"AGREES(256)"},{"function":"clear_two_indices","verdict":"AGREES(256)"},{"function":"clear_low","verdict":"AGREES(252)"},{"function":"clear_byte_array","verdict":"AGREES(256)"},{"function":"clear_split","verdict":"AGREES(256)"},{"function":"clear_split_alone","verdict":"AGREES(256)"},{"function":"clear_slot","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalcallranges.xml": [{"function":"initialize","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalloadguard.xml": [{"function":"d_loop","verdict":"AGREES(85)"},{"function":"d_branch","verdict":"AGREES(256)"},{"function":"d_pre","verdict":"UNKNOWN(budget)"},{"function":"d_phi","verdict":"AGREES(256)"},{"function":"d_load","verdict":"AGREES(256)"},{"function":"d_mv","verdict":"AGREES(256)"},{"function":"d_loop","verdict":"AGREES(85)"},{"function":"d_branch","verdict":"AGREES(256)"},{"function":"d_pre","verdict":"UNKNOWN(budget)"},{"function":"d_phi","verdict":"AGREES(256)"},{"function":"d_load","verdict":"AGREES(256)"},{"function":"d_mv","verdict":"AGREES(256)"},{"function":"d_cond","verdict":"AGREES(256)"},{"function":"d_cond","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalorder.xml": [{"function":"ew","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalpointee.xml": [{"function":"p_int","verdict":"AGREES(256)"},{"function":"r_char","verdict":"AGREES(256)"},{"function":"r_long","verdict":"AGREES(256)"},{"function":"r_void","verdict":"AGREES(256)"},{"function":"w_short","verdict":"AGREES(256)"},{"function":"m_call","verdict":"AGREES(256)"},{"function":"m_join","verdict":"AGREES(256)"},{"function":"g_alias","verdict":"AGREES(256)"},{"function":"g_reload","verdict":"AGREES(256)"},{"function":"g_before","verdict":"AGREES(256)"},{"function":"g_write","verdict":"AGREES(256)"},{"function":"g_diff","verdict":"AGREES(256)"},{"function":"g_twice","verdict":"AGREES(256)"},{"function":"g_old","verdict":"AGREES(256)"},{"function":"g_branch","verdict":"AGREES(256)"},{"function":"p_int","verdict":"AGREES(256)"},{"function":"r_long","verdict":"AGREES(256)"},{"function":"w_short","verdict":"AGREES(256)"},{"function":"m_call","verdict":"AGREES(256)"},{"function":"g_alias","verdict":"AGREES(256)"},{"function":"g_reload","verdict":"AGREES(256)"},{"function":"g_before","verdict":"AGREES(256)"},{"function":"g_write","verdict":"AGREES(256)"},{"function":"g_diff","verdict":"AGREES(256)"},{"function":"g_twice","verdict":"AGREES(256)"},{"function":"g_old","verdict":"AGREES(256)"},{"function":"g_branch","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalref-views.xml": [{"function":"v_two","verdict":"AGREES(256)"},{"function":"v_shift","verdict":"AGREES(256)"},{"function":"v_flags","verdict":"AGREES(256)"},{"function":"v_bound","verdict":"AGREES(256)"},{"function":"v_after","verdict":"AGREES(256)"},{"function":"v_narrow","verdict":"AGREES(256)"},{"function":"v_carg","verdict":"AGREES(256)"},{"function":"v_tick","verdict":"AGREES(256)"},{"function":"v_two","verdict":"AGREES(256)"},{"function":"v_shift","verdict":"AGREES(256)"},{"function":"v_flags","verdict":"AGREES(256)"},{"function":"v_bound","verdict":"AGREES(256)"},{"function":"v_after","verdict":"AGREES(256)"},{"function":"v_narrow","verdict":"AGREES(256)"},{"function":"v_carg","verdict":"AGREES(256)"},{"function":"v_tick","verdict":"AGREES(256)"},{"function":"f_key","verdict":"AGREES(256)"},{"function":"f_load","verdict":"AGREES(256)"},{"function":"f_reg","verdict":"AGREES(256)"},{"function":"f_key","verdict":"AGREES(256)"},{"function":"f_load","verdict":"AGREES(256)"},{"function":"f_reg","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalref.xml": [{"function":"w_buffer","verdict":"AGREES(256)"},{"function":"w_glyph","verdict":"AGREES(256)"},{"function":"w_width","verdict":"AGREES(256)"},{"function":"w_count","verdict":"AGREES(256)"},{"function":"w_buffer","verdict":"AGREES(256)"},{"function":"w_glyph","verdict":"AGREES(256)"},{"function":"w_width","verdict":"AGREES(256)"},{"function":"w_count","verdict":"AGREES(256)"}], + "tests/stages/kuna-globalvalue.xml": [{"function":"w_branch","verdict":"AGREES(256)"},{"function":"w_signed","verdict":"AGREES(256)"},{"function":"w_first","verdict":"AGREES(255)"},{"function":"w_i2f","verdict":"AGREES(256)"},{"function":"w_alias","verdict":"AGREES(256)"},{"function":"w_eqc","verdict":"AGREES(256)"},{"function":"w_sadd","verdict":"AGREES(256)"},{"function":"w_xordiv","verdict":"AGREES(256)"},{"function":"w_f","verdict":"AGREES(256)"},{"function":"w_cond","verdict":"AGREES(256)"},{"function":"w_fold16","verdict":"AGREES(256)"},{"function":"w_fold8","verdict":"AGREES(256)"},{"function":"w_neg16","verdict":"AGREES(256)"},{"function":"w_sub16","verdict":"AGREES(256)"},{"function":"w_not16","verdict":"AGREES(256)"},{"function":"w_realias","verdict":"AGREES(256)"},{"function":"w_reboth","verdict":"AGREES(256)"},{"function":"w_recopy","verdict":"AGREES(256)"},{"function":"w_oif","verdict":"AGREES(256)"},{"function":"w_oloop","verdict":"AGREES(256)"}], + "tests/stages/kuna-go-atomic-return.xml": [{"function":"add32_new","verdict":"AGREES(256)"},{"function":"add64_new","verdict":"AGREES(256)"},{"function":"dec32_branch","verdict":"AGREES(256)"},{"function":"old32_live","verdict":"AGREES(256)"},{"function":"carry_live","verdict":"AGREES(256)"},{"function":"unlocked_add","verdict":"AGREES(256)"},{"function":"locked_add","verdict":"AGREES(256)"},{"function":"intervening_store","verdict":"AGREES(256)"},{"function":"hle_add","verdict":"UNKNOWN(unsupported-op)"},{"function":"narrow_add","verdict":"AGREES(256)"},{"function":"exchange","verdict":"AGREES(256)"},{"function":"unsigned_add","verdict":"AGREES(256)"},{"function":"untrusted_add","verdict":"AGREES(256)"},{"function":"shadowed_add","verdict":"AGREES(256)"},{"function":"wrong_delta","verdict":"AGREES(256)"},{"function":"extra_old","verdict":"AGREES(256)"},{"function":"twice_add","verdict":"AGREES(256)"},{"function":"volatile_add","verdict":"AGREES(256)"},{"function":"retry_add","verdict":"AGREES(256)"},{"function":"add_then_call","verdict":"AGREES(256)"},{"function":"add32_new","verdict":"AGREES(256)"},{"function":"add32_new","verdict":"AGREES(256)"},{"function":"add32_new","verdict":"AGREES(256)"}], + "tests/stages/kuna-go-ordered-compare.xml": [{"function":"ordered_eq_args","verdict":"AGREES(256)"},{"function":"ordered_eq_constant","verdict":"AGREES(256)"},{"function":"ordered_ne_args","verdict":"AGREES(256)"},{"function":"unordered_other","verdict":"DIFFERS(return)"},{"function":"ordered_eq_load","verdict":"AGREES(256)"},{"function":"ordered_eq_with_store","verdict":"DIFFERS(memory at exit)"},{"function":"ordered_eq_args","verdict":"AGREES(256)"}], + "tests/stages/kuna-gobool.xml": [{"function":"is_one","verdict":"AGREES(256)"},{"function":"is_one","verdict":"AGREES(256)"}], + "tests/stages/kuna-gobounds.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick","verdict":"DIVERGES(panic-check)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"store_then_panic","verdict":"AGREES(256)"},{"function":"panic_wrapper","verdict":"AGREES(256)"},{"function":"global_then_panic","verdict":"AGREES(256)"}], + "tests/stages/kuna-gojumpchain.xml": [{"function":"forwarded","verdict":"DIVERGES(gowritebarrier)"},{"function":"forwarded","verdict":"AGREES(256)"},{"function":"write_forwarder","verdict":"AGREES(256)"},{"function":"cycle","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-gomorestack.xml": [{"function":"add","verdict":"AGREES(84)"},{"function":"add","verdict":"UNKNOWN(budget)"},{"function":"add","verdict":"AGREES(137)"},{"function":"add","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-gotimportproto.xml": [{"function":"duplicate","verdict":"AGREES(256)"}], + "tests/stages/kuna-gotonext.xml": [{"function":"fall","verdict":"AGREES(256)"},{"function":"arith","verdict":"AGREES(256)"},{"function":"strcase","verdict":"AGREES(256)"},{"function":"fall_clang","verdict":"AGREES(256)"},{"function":"fall","verdict":"AGREES(256)"},{"function":"arith","verdict":"AGREES(256)"},{"function":"strcase","verdict":"AGREES(256)"},{"function":"fall_clang","verdict":"AGREES(256)"}], + "tests/stages/kuna-gotoreduce-auto.xml": [{"function":"find","verdict":"AGREES(256)"},{"function":"drain","verdict":"UNKNOWN(budget)"},{"function":"early","verdict":"AGREES(256)"},{"function":"find","verdict":"AGREES(256)"},{"function":"drain","verdict":"UNKNOWN(budget)"},{"function":"early","verdict":"AGREES(256)"}], + "tests/stages/kuna-gotslotimports.xml": [{"function":"first","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"length","verdict":"AGREES(256)"},{"function":"same","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"drop","verdict":"AGREES(256)"},{"function":"len2","verdict":"AGREES(256)"},{"function":"bail","verdict":"AGREES(256)"},{"function":"first","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"first","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"bail","verdict":"AGREES(256)"},{"function":"relative","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"absolute","verdict":"AGREES(256)"},{"function":"forward","verdict":"AGREES(256)"},{"function":"interposed","verdict":"AGREES(256)"},{"function":"replaced","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"first_env","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"first_env","verdict":"AGREES(256)"}], + "tests/stages/kuna-gottailcall.xml": [{"function":"h","verdict":"AGREES(256)"},{"function":"notfn","verdict":"UNKNOWN(unsupported-op)"},{"function":"onecase","verdict":"AGREES(256)"}], + "tests/stages/kuna-gotypenames.xml": [{"function":"main.main","verdict":"UNKNOWN(uninitialized-local)"},{"function":"runtime.printany","verdict":"UNKNOWN(unsupported-op)"},{"function":"main.mk","verdict":"UNKNOWN(unsupported-op)"},{"function":"internal/bisect.New","verdict":"UNKNOWN(unsupported-op)"},{"function":"internal/poll.(*FD).Close","verdict":"UNKNOWN(budget)"},{"function":"internal/bisect.New","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-gowbphi.xml": [{"function":"wbstore","verdict":"AGREES(256)"},{"function":"wbstore","verdict":"AGREES(256)"}], + "tests/stages/kuna-gowritebarrier.xml": [{"function":"store","verdict":"AGREES(256)"},{"function":"store","verdict":"DIVERGES(gowritebarrier)"}], + "tests/stages/kuna-guardauto.xml": [{"function":"unget","verdict":"AGREES(256)"},{"function":"backup","verdict":"AGREES(256)"},{"function":"unget","verdict":"AGREES(256)"},{"function":"backup","verdict":"AGREES(256)"}], + "tests/stages/kuna-guarded-local-read-sparc.xml": [{"function":"guarded","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"}], + "tests/stages/kuna-guarded-local-read.xml": [{"function":"guarded","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"}], + "tests/stages/kuna-guardrunjoin.xml": [{"function":"ach","verdict":"AGREES(256)"}], + "tests/stages/kuna-haltloopguard.xml": [{"function":"sysreset","verdict":"UNKNOWN(budget)"},{"function":"park","verdict":"UNKNOWN(unsupported-op)"},{"function":"toggle","verdict":"UNKNOWN(budget)"},{"function":"irred","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-hideshadow.xml": [{"function":"target","verdict":"AGREES(256)"},{"function":"guard","verdict":"AGREES(256)"}], + "tests/stages/kuna-homespill-win64.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"},{"function":"unused2","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"negatives","verdict":"AGREES(256)"},{"function":"reused","verdict":"AGREES(256)"},{"function":"vararg","verdict":"AGREES(256)"},{"function":"spillhigh","verdict":"AGREES(256)"}], + "tests/stages/kuna-ilp32long-mips.xml": [{"function":"cll","verdict":"AGREES(256)"},{"function":"ln","verdict":"AGREES(256)"},{"function":"ll","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"cl","verdict":"AGREES(256)"},{"function":"cp","verdict":"AGREES(256)"},{"function":"ln","verdict":"AGREES(256)"},{"function":"ll","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-ilp32long-ppc.xml": [{"function":"cll","verdict":"AGREES(256)"},{"function":"ln","verdict":"AGREES(256)"},{"function":"ll","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"cl","verdict":"AGREES(256)"},{"function":"cp","verdict":"AGREES(256)"},{"function":"ln","verdict":"AGREES(256)"},{"function":"ll","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-iltentry.xml": [{"function":"sub_401130","verdict":"AGREES(256)"}], + "tests/stages/kuna-impliedrefs.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"}], + "tests/stages/kuna-import-result.xml": [{"function":"length","verdict":"AGREES(256)"},{"function":"compare","verdict":"AGREES(256)"},{"function":"local_discard","verdict":"AGREES(256)"},{"function":"literal","verdict":"AGREES(256)"},{"function":"discard","verdict":"AGREES(256)"},{"function":"discard_callback","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"unstated","verdict":"AGREES(256)"},{"function":"reset","verdict":"AGREES(256)"},{"function":"store_after","verdict":"AGREES(256)"},{"function":"regular","verdict":"AGREES(256)"},{"function":"locate_char","verdict":"AGREES(256)"},{"function":"separate","verdict":"AGREES(256)"},{"function":"conditional","verdict":"AGREES(256)"},{"function":"length","verdict":"AGREES(256)"},{"function":"compare","verdict":"AGREES(256)"},{"function":"length","verdict":"AGREES(256)"},{"function":"compare","verdict":"AGREES(256)"},{"function":"length","verdict":"AGREES(256)"},{"function":"compare","verdict":"AGREES(256)"},{"function":"literal","verdict":"AGREES(256)"},{"function":"replaced","verdict":"AGREES(256)"},{"function":"consume_line","verdict":"UNKNOWN(budget)"},{"function":"constant_unknown","verdict":"AGREES(256)"},{"function":"through_local","verdict":"AGREES(256)"},{"function":"seventh","verdict":"AGREES(256)"},{"function":"unstated","verdict":"AGREES(256)"},{"function":"untouched","verdict":"AGREES(256)"},{"function":"saved","verdict":"AGREES(256)"},{"function":"checked","verdict":"AGREES(256)"},{"function":"untouched","verdict":"AGREES(256)"},{"function":"index_read","verdict":"AGREES(256)"}], + "tests/stages/kuna-importdata.xml": [{"function":"_main","verdict":"AGREES(256)"},{"function":"_main","verdict":"AGREES(256)"}], + "tests/stages/kuna-importslotvalues.xml": [{"function":"setup","verdict":"AGREES(256)"},{"function":"setup","verdict":"AGREES(256)"},{"function":"setup","verdict":"AGREES(256)"},{"function":"setup","verdict":"AGREES(256)"}], + "tests/stages/kuna-indexedfloat-a64.xml": [{"function":"at","verdict":"AGREES(256)"},{"function":"mem","verdict":"AGREES(256)"},{"function":"iat","verdict":"AGREES(256)"}], + "tests/stages/kuna-indexedfloat.xml": [{"function":"at","verdict":"AGREES(256)"},{"function":"atd","verdict":"AGREES(256)"},{"function":"mem","verdict":"AGREES(256)"},{"function":"twice","verdict":"AGREES(256)"},{"function":"iat","verdict":"AGREES(256)"},{"function":"upun2","verdict":"AGREES(256)"},{"function":"xmmdead","verdict":"AGREES(256)"}], + "tests/stages/kuna-indexedstoreguard-a64.xml": [{"function":"l6b","verdict":"AGREES(256)"},{"function":"i6b","verdict":"AGREES(256)"},{"function":"u2","verdict":"AGREES(256)"},{"function":"u5","verdict":"AGREES(256)"},{"function":"w5","verdict":"AGREES(14)"},{"function":"gap2","verdict":"AGREES(81)"},{"function":"m8","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-indexedstoreguard.xml": [{"function":"g_byte","verdict":"AGREES(256)"},{"function":"g_int","verdict":"AGREES(256)"},{"function":"g_long","verdict":"AGREES(256)"},{"function":"g_struct","verdict":"AGREES(256)"},{"function":"g_second","verdict":"AGREES(256)"},{"function":"g_two","verdict":"AGREES(256)"},{"function":"c_byte","verdict":"AGREES(256)"},{"function":"c_int","verdict":"AGREES(256)"},{"function":"c_long","verdict":"AGREES(256)"},{"function":"c_struct","verdict":"AGREES(256)"},{"function":"c_second","verdict":"AGREES(256)"},{"function":"c_two","verdict":"AGREES(256)"},{"function":"o_int","verdict":"AGREES(256)"},{"function":"o_second","verdict":"AGREES(256)"},{"function":"gb_ib","verdict":"AGREES(256)"},{"function":"gb_im","verdict":"AGREES(256)"},{"function":"gb_sb","verdict":"AGREES(256)"},{"function":"gb_cb","verdict":"AGREES(256)"},{"function":"gb_l6b","verdict":"AGREES(256)"},{"function":"gb_u2","verdict":"AGREES(256)"},{"function":"gb_u5","verdict":"AGREES(256)"},{"function":"gb_w5","verdict":"AGREES(16)"},{"function":"gb_ws","verdict":"AGREES(256)"},{"function":"cb_ib","verdict":"AGREES(256)"},{"function":"cb_im","verdict":"AGREES(256)"},{"function":"cb_sb","verdict":"AGREES(256)"},{"function":"cb_cb","verdict":"AGREES(256)"},{"function":"cb_l6b","verdict":"AGREES(256)"},{"function":"cb_u2","verdict":"AGREES(256)"},{"function":"cb_u5","verdict":"AGREES(256)"},{"function":"cb_w5","verdict":"UNKNOWN(budget)"},{"function":"cb_ws","verdict":"UNKNOWN(unsupported-op)"},{"function":"gb_wp","verdict":"AGREES(256)"},{"function":"cb_wq","verdict":"UNKNOWN(unsupported-op)"},{"function":"cb_m8","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-indirect-value-arguments.xml": [{"function":"stack_value","verdict":"AGREES(256)"},{"function":"stack_pointer","verdict":"AGREES(256)"},{"function":"pointer_value","verdict":"AGREES(256)"},{"function":"indirect_value","verdict":"AGREES(256)"},{"function":"value_reader","verdict":"AGREES(256)"},{"function":"advanced","verdict":"AGREES(256)"},{"function":"spilled","verdict":"AGREES(256)"},{"function":"updated","verdict":"AGREES(256)"},{"function":"cursor","verdict":"AGREES(256)"},{"function":"indirect_pointer","verdict":"AGREES(256)"},{"function":"stack_value_reverse","verdict":"AGREES(256)"},{"function":"stack_pointer_reverse","verdict":"AGREES(256)"},{"function":"stack_cursor","verdict":"AGREES(256)"},{"function":"collision_cursor","verdict":"AGREES(256)"}], + "tests/stages/kuna-indirectonly-escape.xml": [{"function":"walk","verdict":"AGREES(256)"},{"function":"walk","verdict":"AGREES(256)"}], + "tests/stages/kuna-indirectonly.xml": [{"function":"take","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"take","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"}], + "tests/stages/kuna-inferfuncentry-intbound.xml": [{"function":"bound","verdict":"AGREES(256)"},{"function":"reg","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-inflatecover.xml": [{"function":"swaphalves","verdict":"AGREES(256)"}], + "tests/stages/kuna-infloopstyle.xml": [{"function":"forever","verdict":"UNKNOWN(budget)"},{"function":"countdown","verdict":"AGREES(94)"},{"function":"forever","verdict":"UNKNOWN(budget)"},{"function":"countdown","verdict":"AGREES(94)"}], + "tests/stages/kuna-inputparamgap.xml": [{"function":"on_key","verdict":"AGREES(256)"},{"function":"on_two","verdict":"AGREES(256)"}], + "tests/stages/kuna-int3pad.xml": [{"function":"antidbg","verdict":"AGREES(256)"},{"function":"antidbg","verdict":"AGREES(256)"},{"function":"antidbg","verdict":"AGREES(253)"}], + "tests/stages/kuna-integer-float-rounding-x87.xml": [{"function":"cmpf","verdict":"AGREES(256)"},{"function":"lt1","verdict":"AGREES(256)"},{"function":"l2d2f","verdict":"AGREES(256)"}], + "tests/stages/kuna-integer-float-rounding.xml": [{"function":"rounded","verdict":"AGREES(256)"},{"function":"exact_intermediate","verdict":"AGREES(256)"}], + "tests/stages/kuna-integer-float-rounding64.xml": [{"function":"double_rounded","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumclasses.xml": [{"function":"sub_14b8","verdict":"AGREES(256)"},{"function":"shapes::Shape::vfunc_2","verdict":"AGREES(256)"},{"function":"shapes::Circle::Circle","verdict":"AGREES(256)"},{"function":"shapes::Shape::vfunc_2","verdict":"AGREES(256)"},{"function":"shapes::Circle::vfunc_2","verdict":"AGREES(256)"},{"function":"shapes::Circle::Circle","verdict":"AGREES(256)"},{"function":"shapes::Vec_double::vfunc_2","verdict":"AGREES(256)"},{"function":"shapes::Widget::vfunc_2","verdict":"AGREES(256)"},{"function":"zoo::Counter::vfunc_0","verdict":"AGREES(256)"},{"function":"bv::Zero::vfunc_2","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumctors.xml": [{"function":"on_stack","verdict":"AGREES(256)"},{"function":"sub_151c","verdict":"AGREES(256)"},{"function":"on_stack","verdict":"AGREES(256)"},{"function":"zoo::Dog::Dog","verdict":"AGREES(256)"},{"function":"make_dog","verdict":"AGREES(256)"},{"function":"use_gadgets","verdict":"AGREES(256)"},{"function":"kit::Gadget::~Gadget","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumrtti-gotslot.xml": [{"function":"fn_addr","verdict":"AGREES(256)"},{"function":"sub_10494","verdict":"AGREES(256)"},{"function":"sub_104cc","verdict":"AGREES(256)"},{"function":"Real::vfunc_2","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumrtti-macho-classic.xml": [{"function":"_make","verdict":"AGREES(256)"},{"function":"_make","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumrtti-macho.xml": [{"function":"_make","verdict":"AGREES(256)"},{"function":"_make","verdict":"AGREES(256)"}], + "tests/stages/kuna-itaniumvfunc.xml": [{"function":"sub_182b","verdict":"AGREES(256)"},{"function":"probe_shapes","verdict":"AGREES(256)"},{"function":"shapes::Widget::vfunc_for_Drawable_2","verdict":"AGREES(256)"},{"function":"probe_shapes","verdict":"AGREES(256)"}], + "tests/stages/kuna-iteregion-auto.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"flag","verdict":"AGREES(256)"},{"function":"arg","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"flag","verdict":"AGREES(256)"},{"function":"arg","verdict":"AGREES(256)"}], + "tests/stages/kuna-iteregion-chain.xml": [{"function":"chain","verdict":"AGREES(256)"},{"function":"chain_if","verdict":"AGREES(256)"},{"function":"either","verdict":"AGREES(256)"},{"function":"pair","verdict":"AGREES(256)"},{"function":"pair_if","verdict":"AGREES(256)"},{"function":"chain","verdict":"AGREES(256)"},{"function":"either","verdict":"AGREES(256)"},{"function":"pair","verdict":"AGREES(256)"}], + "tests/stages/kuna-iteregion-truthselect.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"size","verdict":"AGREES(256)"},{"function":"lim","verdict":"AGREES(256)"},{"function":"clamp","verdict":"AGREES(256)"},{"function":"update","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"size","verdict":"AGREES(256)"}], + "tests/stages/kuna-jump-as-call-liveness.xml": [{"function":"dead_jump","verdict":"AGREES(256)"},{"function":"live_jump","verdict":"AGREES(256)"},{"function":"unwind_phase2","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-jumptable-bytemap-rows.xml": [{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-jumptablemax.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-jumptableslots.xml": [{"function":"wide","verdict":"AGREES(256)"}], + "tests/stages/kuna-kernelbug.xml": [{"function":"kwarn_check","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-kernelcache.xml": [{"function":"sub_fffffff007007800","verdict":"AGREES(256)"},{"function":"widget_start","verdict":"AGREES(256)"},{"function":"widget_via_stub","verdict":"AGREES(256)"},{"function":"kernel_add","verdict":"AGREES(256)"}], + "tests/stages/kuna-kernelcacheboot.xml": [{"function":"gadget_start","verdict":"AGREES(256)"},{"function":"gadget_start","verdict":"AGREES(256)"},{"function":"gadget_log","verdict":"AGREES(256)"}], + "tests/stages/kuna-labelstmt-arm.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe_control","verdict":"AGREES(256)"}], + "tests/stages/kuna-labelstmt-x64.xml": [{"function":"last_case","verdict":"AGREES(256)"},{"function":"skip_blanks","verdict":"AGREES(256)"}], + "tests/stages/kuna-lanedivide-freefanout.xml": [{"function":"sub_e87b0","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-lanedivide-terminator.xml": [{"function":"f_hi","verdict":"AGREES(85)"},{"function":"f_mid","verdict":"AGREES(85)"}], + "tests/stages/kuna-latchjoin.xml": [{"function":"visit","verdict":"AGREES(50)"},{"function":"count","verdict":"AGREES(50)"},{"function":"sendall","verdict":"AGREES(81)"},{"function":"visit","verdict":"AGREES(50)"},{"function":"count","verdict":"AGREES(50)"},{"function":"sendall","verdict":"AGREES(81)"}], + "tests/stages/kuna-libcnames-addr.xml": [{"function":"echo","verdict":"AGREES(256)"},{"function":"echo","verdict":"AGREES(256)"},{"function":"file_size","verdict":"AGREES(256)"},{"function":"child","verdict":"AGREES(256)"},{"function":"parse","verdict":"AGREES(256)"},{"function":"read_hdr","verdict":"AGREES(256)"},{"function":"when","verdict":"AGREES(256)"},{"function":"stash","verdict":"AGREES(256)"},{"function":"reuse","verdict":"AGREES(256)"},{"function":"echo","verdict":"AGREES(256)"},{"function":"echo","verdict":"AGREES(256)"},{"function":"echo","verdict":"AGREES(256)"},{"function":"echo","verdict":"AGREES(256)"},{"function":"sub_401000","verdict":"UNKNOWN(budget)"},{"function":"sub_401000","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-libcnames-win32.xml": [{"function":"sub_4010e0","verdict":"AGREES(256)"},{"function":"sub_4010e0","verdict":"AGREES(256)"},{"function":"sub_401000","verdict":"UNKNOWN(budget)"},{"function":"sub_4010e0","verdict":"AGREES(256)"},{"function":"sub_4010e0","verdict":"AGREES(256)"},{"function":"sub_140001150","verdict":"AGREES(256)"},{"function":"sub_140001000","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-libcnames.xml": [{"function":"copy_file","verdict":"AGREES(256)"},{"function":"copy_file","verdict":"AGREES(256)"},{"function":"joined","verdict":"AGREES(256)"},{"function":"first_line","verdict":"AGREES(256)"},{"function":"emit","verdict":"AGREES(256)"},{"function":"ordered","verdict":"AGREES(256)"},{"function":"copy_file","verdict":"AGREES(256)"},{"function":"copy_file","verdict":"AGREES(256)"},{"function":"copy_file","verdict":"AGREES(256)"},{"function":"copy_file","verdict":"AGREES(256)"}], + "tests/stages/kuna-libctypes.xml": [{"function":"fclose","verdict":"AGREES(256)"},{"function":"fopen","verdict":"AGREES(256)"},{"function":"mode_of","verdict":"AGREES(256)"},{"function":"fclose","verdict":"AGREES(256)"},{"function":"fopen","verdict":"AGREES(256)"},{"function":"mode_of","verdict":"AGREES(256)"},{"function":"fclose","verdict":"AGREES(256)"},{"function":"get_prefix","verdict":"AGREES(256)"},{"function":"next_byte","verdict":"AGREES(256)"},{"function":"size_of","verdict":"AGREES(256)"},{"function":"next_byte","verdict":"AGREES(256)"},{"function":"size_of","verdict":"AGREES(256)"},{"function":"pending","verdict":"AGREES(256)"},{"function":"flush_mark","verdict":"AGREES(256)"},{"function":"hand_off","verdict":"AGREES(256)"},{"function":"say","verdict":"AGREES(256)"},{"function":"pending","verdict":"AGREES(256)"},{"function":"flush_mark","verdict":"AGREES(256)"},{"function":"hand_off","verdict":"AGREES(256)"},{"function":"say","verdict":"AGREES(256)"},{"function":"pending","verdict":"AGREES(256)"},{"function":"flush_mark","verdict":"AGREES(256)"},{"function":"hand_off","verdict":"AGREES(256)"},{"function":"say","verdict":"AGREES(256)"},{"function":"pending","verdict":"AGREES(256)"},{"function":"flush_mark","verdict":"AGREES(256)"},{"function":"hand_off","verdict":"AGREES(256)"},{"function":"say","verdict":"AGREES(256)"},{"function":"grow","verdict":"AGREES(256)"},{"function":"emit","verdict":"AGREES(256)"},{"function":"grow_import","verdict":"AGREES(256)"},{"function":"grow","verdict":"AGREES(256)"},{"function":"emit","verdict":"AGREES(256)"},{"function":"grow_import","verdict":"AGREES(256)"},{"function":"kws_grow","verdict":"AGREES(256)"},{"function":"inst_refs","verdict":"AGREES(256)"},{"function":"grow_in","verdict":"AGREES(256)"},{"function":"sub_8049040","verdict":"AGREES(256)"},{"function":"sub_804911e","verdict":"AGREES(256)"}], + "tests/stages/kuna-libcwiden.xml": [{"function":"can_write","verdict":"AGREES(256)"},{"function":"move_entry","verdict":"AGREES(256)"},{"function":"make_dir","verdict":"AGREES(256)"},{"function":"jail","verdict":"AGREES(256)"}], + "tests/stages/kuna-linuxsyscall-x64-compat.xml": [{"function":"compat_exit","verdict":"AGREES(256)"},{"function":"native_call","verdict":"DIFFERS(return)"},{"function":"compat_exit","verdict":"DIVERGES(synthesized-call)"},{"function":"native_call","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-linuxsyscall.xml": [{"function":"start","verdict":"AGREES(256)"},{"function":"start","verdict":"DIVERGES(synthesized-call)"}], + "tests/stages/kuna-listing-flag.xml": [{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/kuna-loadguardreads.xml": [{"function":"gather","verdict":"AGREES(256)"}], + "tests/stages/kuna-local-edits-reselection.xml": [{"function":"typed_a","verdict":"AGREES(256)"},{"function":"typed_a","verdict":"AGREES(256)"},{"function":"typed_b","verdict":"AGREES(256)"},{"function":"typed_b","verdict":"AGREES(256)"},{"function":"untouched","verdict":"AGREES(256)"},{"function":"reopened_a","verdict":"AGREES(256)"},{"function":"reopened_a","verdict":"AGREES(256)"},{"function":"typed_b","verdict":"AGREES(256)"}], + "tests/stages/kuna-localstackviews.xml": [{"function":"stack_reuse","verdict":"AGREES(256)"},{"function":"escaped_indirect_write","verdict":"AGREES(256)"}], + "tests/stages/kuna-loopcondhoist.xml": [{"function":"lookup","verdict":"AGREES(256)"},{"function":"find","verdict":"AGREES(256)"},{"function":"readc","verdict":"AGREES(256)"},{"function":"readc_o2","verdict":"AGREES(256)"},{"function":"lookup","verdict":"AGREES(256)"},{"function":"find","verdict":"AGREES(256)"},{"function":"readc","verdict":"AGREES(256)"},{"function":"readc_o2","verdict":"AGREES(256)"},{"function":"lookup","verdict":"AGREES(256)"},{"function":"readc_o2","verdict":"AGREES(256)"}], + "tests/stages/kuna-loopcontinue-auto-thumb.xml": [{"function":"scan","verdict":"AGREES(120)"},{"function":"first","verdict":"AGREES(256)"},{"function":"skip","verdict":"AGREES(120)"},{"function":"scan","verdict":"AGREES(120)"},{"function":"first","verdict":"AGREES(256)"},{"function":"skip","verdict":"AGREES(120)"}], + "tests/stages/kuna-loopcontinue-auto.xml": [{"function":"scan","verdict":"AGREES(103)"},{"function":"first","verdict":"AGREES(256)"},{"function":"skip","verdict":"AGREES(103)"},{"function":"scan","verdict":"AGREES(103)"},{"function":"first","verdict":"AGREES(256)"},{"function":"skip","verdict":"AGREES(103)"}], + "tests/stages/kuna-loopcontinue-while.xml": [{"function":"little2_attributeValueTok","verdict":"AGREES(199)"},{"function":"little2_attributeValueTok","verdict":"AGREES(199)"},{"function":"little2_attributeValueTok","verdict":"AGREES(198)"}], + "tests/stages/kuna-loopcontinue.xml": [{"function":"retry_server","verdict":"UNKNOWN(budget)"},{"function":"retry_server","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-looptest-entry.xml": [{"function":"spin","verdict":"AGREES(256)"},{"function":"skip_spaces","verdict":"AGREES(256)"},{"function":"each_index","verdict":"UNKNOWN(budget)"},{"function":"ten_o0","verdict":"AGREES(256)"},{"function":"free_args","verdict":"AGREES(106)"},{"function":"reset_free","verdict":"AGREES(14)"},{"function":"flip_body","verdict":"AGREES(256)"},{"function":"bump_range","verdict":"UNKNOWN(budget)"},{"function":"clear_grid","verdict":"AGREES(256)"},{"function":"spin","verdict":"AGREES(256)"},{"function":"skip_spaces","verdict":"AGREES(256)"},{"function":"each_index","verdict":"UNKNOWN(budget)"},{"function":"ten_o0","verdict":"AGREES(256)"},{"function":"free_args","verdict":"AGREES(106)"},{"function":"reset_free","verdict":"AGREES(14)"},{"function":"flip_body","verdict":"AGREES(256)"},{"function":"bump_range","verdict":"UNKNOWN(budget)"},{"function":"clear_grid","verdict":"AGREES(256)"}], + "tests/stages/kuna-looptest-order.xml": [{"function":"down","verdict":"AGREES(90)"},{"function":"bytes","verdict":"AGREES(85)"},{"function":"step2","verdict":"AGREES(69)"},{"function":"wrapend","verdict":"AGREES(16)"},{"function":"down","verdict":"AGREES(90)"},{"function":"bytes","verdict":"AGREES(85)"}], + "tests/stages/kuna-looptest-zerotrip.xml": [{"function":"dsum","verdict":"AGREES(90)"},{"function":"lsum_or_minus","verdict":"AGREES(49)"},{"function":"bytes_differ","verdict":"AGREES(13)"},{"function":"count_report","verdict":"AGREES(49)"},{"function":"count_or_one","verdict":"AGREES(49)"},{"function":"visit","verdict":"AGREES(141)"},{"function":"popcount_or","verdict":"AGREES(256)"},{"function":"free_opts","verdict":"AGREES(1)"},{"function":"walk_keep","verdict":"AGREES(49)"},{"function":"dsum","verdict":"AGREES(90)"},{"function":"lsum_or_minus","verdict":"AGREES(49)"},{"function":"bytes_differ","verdict":"AGREES(13)"},{"function":"count_report","verdict":"AGREES(49)"},{"function":"count_or_one","verdict":"AGREES(49)"},{"function":"visit","verdict":"AGREES(141)"},{"function":"popcount_or","verdict":"AGREES(256)"},{"function":"free_opts","verdict":"AGREES(1)"},{"function":"walk_keep","verdict":"AGREES(49)"}], + "tests/stages/kuna-looptest.xml": [{"function":"fill","verdict":"AGREES(16)"},{"function":"drain","verdict":"AGREES(91)"},{"function":"zero16","verdict":"AGREES(256)"},{"function":"count","verdict":"AGREES(90)"},{"function":"walk","verdict":"AGREES(65)"},{"function":"skip","verdict":"AGREES(256)"},{"function":"fill","verdict":"AGREES(16)"},{"function":"drain","verdict":"AGREES(91)"},{"function":"zero16","verdict":"AGREES(256)"},{"function":"walk","verdict":"AGREES(65)"}], + "tests/stages/kuna-loweredswitch-auto.xml": [{"function":"sw2","verdict":"AGREES(256)"},{"function":"if3","verdict":"AGREES(256)"},{"function":"swf","verdict":"AGREES(256)"},{"function":"sw2_on","verdict":"AGREES(256)"},{"function":"if3_on","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitch-bits.xml": [{"function":"ecdsa","verdict":"AGREES(256)"},{"function":"vowel","verdict":"AGREES(256)"},{"function":"skipws","verdict":"AGREES(256)"},{"function":"still_open","verdict":"AGREES(256)"},{"function":"ecdsa_on","verdict":"AGREES(256)"},{"function":"vowel_on","verdict":"AGREES(256)"},{"function":"still_open_on","verdict":"AGREES(4)"}], + "tests/stages/kuna-loweredswitch-linear.xml": [{"function":"sw3","verdict":"AGREES(256)"},{"function":"chain","verdict":"AGREES(256)"},{"function":"sw3","verdict":"AGREES(256)"},{"function":"chain","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitch-scrutinee.xml": [{"function":"swfn","verdict":"AGREES(256)"},{"function":"swfn","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitch-small.xml": [{"function":"nid_name","verdict":"AGREES(256)"},{"function":"enable","verdict":"AGREES(256)"},{"function":"nid_name","verdict":"AGREES(256)"},{"function":"enable","verdict":"AGREES(256)"},{"function":"two","verdict":"AGREES(256)"},{"function":"colon","verdict":"AGREES(256)"},{"function":"kind","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"two","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitch-tree.xml": [{"function":"wide","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitchexact.xml": [{"function":"classify","verdict":"AGREES(256)"},{"function":"pick_table","verdict":"AGREES(256)"},{"function":"g3","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"},{"function":"rlater","verdict":"AGREES(256)"},{"function":"g3","verdict":"AGREES(256)"}], + "tests/stages/kuna-loweredswitchheads.xml": [{"function":"main","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-loweredswitchvalue.xml": [{"function":"dispatch","verdict":"AGREES(256)"},{"function":"big_consts","verdict":"AGREES(256)"}], + "tests/stages/kuna-mapped-volatile.xml": [{"function":"mmio_select","verdict":"UNKNOWN(unsupported-op)"},{"function":"cursor_order","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-mappedflowboundary.xml": [{"function":"sub_10000","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_10000","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-maxlinewidth.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-minss-nan.xml": [{"function":"scalar_min","verdict":"AGREES(256)"},{"function":"scalar_min","verdict":"AGREES(256)"},{"function":"ratio_clamp","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-float-arguments.xml": [{"function":"float_first","verdict":"AGREES(256)"},{"function":"int_first","verdict":"AGREES(256)"},{"function":"stack_arg","verdict":"AGREES(256)"},{"function":"stack_float","verdict":"AGREES(256)"},{"function":"stack_int","verdict":"AGREES(256)"},{"function":"var_call","verdict":"AGREES(256)"},{"function":"use_intdbl","verdict":"AGREES(256)"},{"function":"use_many","verdict":"AGREES(256)"},{"function":"float_first","verdict":"AGREES(256)"},{"function":"int_first","verdict":"AGREES(256)"},{"function":"stack_arg","verdict":"AGREES(256)"},{"function":"stack_float","verdict":"AGREES(256)"},{"function":"stack_int","verdict":"AGREES(256)"},{"function":"var_call","verdict":"AGREES(256)"},{"function":"use_intdbl","verdict":"AGREES(256)"},{"function":"use_many","verdict":"AGREES(256)"},{"function":"float_first","verdict":"AGREES(256)"},{"function":"int_first","verdict":"AGREES(256)"},{"function":"stack_arg","verdict":"AGREES(256)"},{"function":"stack_float","verdict":"AGREES(256)"},{"function":"stack_int","verdict":"AGREES(256)"},{"function":"float_double","verdict":"AGREES(256)"},{"function":"last_register","verdict":"AGREES(256)"},{"function":"pair_first","verdict":"AGREES(256)"},{"function":"pair_later","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"leading","verdict":"AGREES(256)"},{"function":"use_aligned","verdict":"AGREES(256)"},{"function":"use_later","verdict":"AGREES(256)"},{"function":"use_wide_later","verdict":"AGREES(256)"},{"function":"float_first","verdict":"AGREES(256)"},{"function":"int_first","verdict":"AGREES(256)"},{"function":"two_floats","verdict":"AGREES(256)"},{"function":"var_call","verdict":"AGREES(256)"},{"function":"use_later","verdict":"AGREES(256)"},{"function":"use_consecutive","verdict":"AGREES(256)"},{"function":"call_small","verdict":"AGREES(256)"},{"function":"call_large","verdict":"AGREES(256)"},{"function":"call_small","verdict":"AGREES(256)"},{"function":"call_large","verdict":"AGREES(256)"},{"function":"forward","verdict":"AGREES(256)"},{"function":"forward_pair","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-kscratch.xml": [{"function":"scratch","verdict":"UNKNOWN(unsupported-op)"},{"function":"previous","verdict":"UNKNOWN(unsupported-op)"},{"function":"read_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"clear_first","verdict":"UNKNOWN(unsupported-op)"},{"function":"around","verdict":"UNKNOWN(unsupported-op)"},{"function":"observe","verdict":"UNKNOWN(unsupported-op)"},{"function":"write_twice","verdict":"UNKNOWN(unsupported-op)"},{"function":"transfer","verdict":"UNKNOWN(unsupported-op)"},{"function":"replace","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-kscratch3.xml": [{"function":"transfer","verdict":"UNKNOWN(unsupported-op)"},{"function":"replace","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-mips-o32-aggregate-placement.xml": [{"function":"first","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-o32-call-arguments.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-o32-register-slots.xml": [{"function":"negative","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-o64-calls.xml": [{"function":"forward","verdict":"AGREES(256)"},{"function":"combine","verdict":"AGREES(256)"},{"function":"next_slot","verdict":"AGREES(256)"},{"function":"high_word","verdict":"AGREES(256)"},{"function":"dbits","verdict":"AGREES(256)"},{"function":"frombits","verdict":"AGREES(256)"},{"function":"fbits","verdict":"AGREES(256)"},{"function":"fromword","verdict":"AGREES(256)"},{"function":"fifthfloat","verdict":"AGREES(256)"},{"function":"field","verdict":"AGREES(256)"},{"function":"fifthfield","verdict":"AGREES(256)"},{"function":"build","verdict":"AGREES(256)"},{"function":"makeunion","verdict":"AGREES(256)"},{"function":"tail","verdict":"AGREES(256)"}], + "tests/stages/kuna-mips-octeon-elf32-o64.xml": [{"function":"crc16","verdict":"AGREES(185)"},{"function":"describe","verdict":"AGREES(256)"},{"function":"crc16","verdict":"AGREES(185)"},{"function":"describe","verdict":"AGREES(256)"},{"function":"describe","verdict":"AGREES(256)"},{"function":"load","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-mips-weak-data.xml": [{"function":"take_address","verdict":"AGREES(256)"},{"function":"read_optional","verdict":"AGREES(256)"},{"function":"write_optional","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"},{"function":"take_offset","verdict":"DIFFERS(return)"},{"function":"call_optional","verdict":"AGREES(256)"},{"function":"address_with_collision","verdict":"AGREES(256)"},{"function":"take_address","verdict":"AGREES(256)"},{"function":"read_optional","verdict":"AGREES(256)"},{"function":"write_optional","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"},{"function":"take_offset","verdict":"DIFFERS(return)"},{"function":"call_optional","verdict":"AGREES(256)"},{"function":"address_with_collision","verdict":"AGREES(256)"},{"function":"take_address","verdict":"AGREES(256)"},{"function":"read_optional","verdict":"AGREES(256)"},{"function":"write_optional","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"},{"function":"take_offset","verdict":"DIFFERS(return)"},{"function":"call_optional","verdict":"AGREES(256)"},{"function":"address_with_collision","verdict":"AGREES(256)"}], + "tests/stages/kuna-mipsgot-local.xml": [{"function":"c_add","verdict":"DIFFERS(call at 0x334 to 0x2f8)"},{"function":"c_calls","verdict":"DIFFERS(call at 0x388 to 0x310)"}], + "tests/stages/kuna-mipsgot-weak.xml": [{"function":"call_optional","verdict":"AGREES(256)"},{"function":"call_optional","verdict":"AGREES(256)"},{"function":"same","verdict":"DIFFERS(return)"},{"function":"same","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-mipsreloc-chains.xml": [{"function":"read_global","verdict":"AGREES(256)"},{"function":"call_external","verdict":"AGREES(256)"},{"function":"composed_call","verdict":"AGREES(256)"},{"function":"scalar_chain_call","verdict":"AGREES(256)"},{"function":"cross_record_call","verdict":"AGREES(256)"},{"function":"relative_call","verdict":"AGREES(256)"},{"function":"composed_call","verdict":"AGREES(256)"},{"function":"scalar_chain_call","verdict":"AGREES(256)"},{"function":"cross_record_call","verdict":"AGREES(256)"},{"function":"relative_call","verdict":"AGREES(256)"},{"function":"read_combined","verdict":"AGREES(256)"},{"function":"read_wrapped","verdict":"AGREES(256)"},{"function":"read_mixed","verdict":"AGREES(256)"},{"function":"read_mixed_lo","verdict":"AGREES(256)"},{"function":"read_chain","verdict":"AGREES(256)"},{"function":"read_combined","verdict":"AGREES(256)"},{"function":"read_wrapped","verdict":"AGREES(256)"},{"function":"read_mixed","verdict":"AGREES(256)"},{"function":"read_mixed_lo","verdict":"AGREES(256)"},{"function":"read_chain","verdict":"AGREES(256)"},{"function":"read_composed_pc32","verdict":"AGREES(256)"},{"function":"read_standalone_pc32","verdict":"AGREES(256)"},{"function":"read_composed_pc32","verdict":"AGREES(256)"},{"function":"read_standalone_pc32","verdict":"AGREES(256)"},{"function":"read_composed_pc32","verdict":"AGREES(256)"},{"function":"read_standalone_pc32","verdict":"AGREES(256)"},{"function":"read_composed_pc32","verdict":"AGREES(256)"},{"function":"read_standalone_pc32","verdict":"AGREES(256)"}], + "tests/stages/kuna-mipsunaligned.xml": [{"function":"c_unal","verdict":"DIFFERS(call at 0x400110 to 0x4000f0)"},{"function":"get_word","verdict":"AGREES(256)"},{"function":"copy_word","verdict":"AGREES(256)"},{"function":"get_word","verdict":"AGREES(256)"},{"function":"copy_word","verdict":"AGREES(256)"}], + "tests/stages/kuna-msvcbyval.xml": [{"function":"sub_401020","verdict":"UNKNOWN(uninitialized-local)"},{"function":"sub_401000","verdict":"UNKNOWN(uninitialized-local)"},{"function":"sub_401020","verdict":"AGREES(256)"},{"function":"sub_401050","verdict":"AGREES(256)"},{"function":"sub_401080","verdict":"UNKNOWN(uninitialized-local)"},{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401130","verdict":"AGREES(256)"},{"function":"sub_401190","verdict":"AGREES(256)"},{"function":"sub_4011e0","verdict":"AGREES(256)"},{"function":"sub_4010f0","verdict":"AGREES(256)"},{"function":"sub_401210","verdict":"AGREES(256)"},{"function":"sub_401240","verdict":"AGREES(256)"},{"function":"sub_401260","verdict":"AGREES(256)"}], + "tests/stages/kuna-msvcfpconst.xml": [{"function":"_scale","verdict":"UNKNOWN(unsupported-op)"},{"function":"_fscale","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-msvcftol.xml": [{"function":"ftol_conv","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-msvcftolsig.xml": [{"function":"sub_401150","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_401033","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_401042","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_401042","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-msvcsig.xml": [{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401020","verdict":"UNKNOWN(uninitialized-local)"}], + "tests/stages/kuna-msvcstackguard-return.xml": [{"function":"guarded_returns","verdict":"AGREES(256)"},{"function":"guarded_returns","verdict":"AGREES(256)"}], + "tests/stages/kuna-msvcstackguard.xml": [{"function":"guarded","verdict":"AGREES(256)"},{"function":"guarded","verdict":"AGREES(256)"},{"function":"pointer_after_checks","verdict":"UNKNOWN(budget)"},{"function":"pointer_after_checks","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-msvcstrappend.xml": [{"function":"build_password","verdict":"DIVERGES(synthesized-call)"},{"function":"append_chars","verdict":"DIVERGES(synthesized-call)"},{"function":"quote","verdict":"DIVERGES(synthesized-call)"},{"function":"near_miss","verdict":"AGREES(256)"},{"function":"nm_other_ptr_object","verdict":"AGREES(256)"},{"function":"nm_extra_store","verdict":"AGREES(256)"},{"function":"nm_other_capacity_field","verdict":"AGREES(256)"},{"function":"nm_heap_wrong_field","verdict":"AGREES(256)"},{"function":"nm_nul_to_local","verdict":"AGREES(256)"},{"function":"nm_missing_nul","verdict":"AGREES(256)"},{"function":"nm_append_stores_one","verdict":"AGREES(256)"},{"function":"nm_signed_compare","verdict":"AGREES(256)"},{"function":"nm_inverted_head","verdict":"AGREES(256)"},{"function":"nm_reads_rcx_after","verdict":"AGREES(256)"},{"function":"nm_reads_flag_after","verdict":"AGREES(256)"},{"function":"nm_callee_saved","verdict":"AGREES(256)"},{"function":"nm_grow_other_object","verdict":"AGREES(256)"},{"function":"nm_grow_by_two","verdict":"AGREES(256)"},{"function":"nm_nul_wrong_index","verdict":"AGREES(256)"},{"function":"nm_char_before_select","verdict":"AGREES(256)"},{"function":"nm_char_differs_by_path","verdict":"AGREES(256)"},{"function":"nm_size_store_narrow","verdict":"AGREES(256)"},{"function":"nm_append_writable_literal","verdict":"AGREES(256)"},{"function":"nm_append_literal_mismatch","verdict":"AGREES(256)"},{"function":"nm_append_rax_not_this","verdict":"AGREES(256)"},{"function":"nm_size_only_small","verdict":"AGREES(256)"},{"function":"nm_fast_arm_entered","verdict":"UNKNOWN(unsupported-op)"},{"function":"nm_grow_entered","verdict":"AGREES(256)"},{"function":"nm_grow_keeps_result","verdict":"AGREES(256)"},{"function":"nm_append_count_mismatch","verdict":"AGREES(256)"},{"function":"nm_reads_cl_on_one_path","verdict":"AGREES(256)"},{"function":"pos_zeroes_after","verdict":"DIVERGES(synthesized-call)"},{"function":"build_password","verdict":"AGREES(256)"},{"function":"append_chars","verdict":"DIFFERS(call at 0x1400011c7 to 0x140001280)"},{"function":"quote","verdict":"AGREES(256)"},{"function":"near_miss","verdict":"AGREES(256)"},{"function":"nm_other_ptr_object","verdict":"AGREES(256)"},{"function":"nm_extra_store","verdict":"AGREES(256)"},{"function":"nm_other_capacity_field","verdict":"AGREES(256)"},{"function":"nm_heap_wrong_field","verdict":"AGREES(256)"},{"function":"nm_nul_to_local","verdict":"AGREES(256)"},{"function":"nm_missing_nul","verdict":"AGREES(256)"},{"function":"nm_append_stores_one","verdict":"AGREES(256)"},{"function":"nm_signed_compare","verdict":"AGREES(256)"},{"function":"nm_inverted_head","verdict":"AGREES(256)"},{"function":"nm_reads_rcx_after","verdict":"AGREES(256)"},{"function":"nm_reads_flag_after","verdict":"AGREES(256)"},{"function":"nm_callee_saved","verdict":"AGREES(256)"},{"function":"nm_grow_other_object","verdict":"AGREES(256)"},{"function":"nm_grow_by_two","verdict":"AGREES(256)"},{"function":"nm_nul_wrong_index","verdict":"AGREES(256)"},{"function":"nm_char_before_select","verdict":"AGREES(256)"},{"function":"nm_char_differs_by_path","verdict":"AGREES(256)"},{"function":"nm_size_store_narrow","verdict":"AGREES(256)"},{"function":"nm_append_writable_literal","verdict":"AGREES(256)"},{"function":"nm_append_literal_mismatch","verdict":"AGREES(256)"},{"function":"nm_append_rax_not_this","verdict":"AGREES(256)"},{"function":"nm_size_only_small","verdict":"AGREES(256)"},{"function":"nm_fast_arm_entered","verdict":"UNKNOWN(unsupported-op)"},{"function":"nm_grow_entered","verdict":"AGREES(256)"},{"function":"nm_grow_keeps_result","verdict":"AGREES(256)"},{"function":"nm_append_count_mismatch","verdict":"AGREES(256)"},{"function":"nm_reads_cl_on_one_path","verdict":"AGREES(256)"},{"function":"pos_zeroes_after","verdict":"AGREES(256)"}], + "tests/stages/kuna-n32-stack.xml": [{"function":"sum_ten","verdict":"AGREES(256)"},{"function":"pointer_ninth","verdict":"AGREES(256)"},{"function":"signed_ninth","verdict":"AGREES(256)"},{"function":"float_ninth","verdict":"AGREES(256)"},{"function":"indirect_frame","verdict":"AGREES(256)"},{"function":"indirect_frame","verdict":"AGREES(256)"},{"function":"pair_indirect","verdict":"AGREES(256)"},{"function":"pair_indirect","verdict":"AGREES(256)"}], + "tests/stages/kuna-n32-width.xml": [{"function":"compare_bits","verdict":"AGREES(256)"},{"function":"return_bits","verdict":"AGREES(256)"},{"function":"add_bits","verdict":"AGREES(256)"},{"function":"sp_high","verdict":"AGREES(256)"},{"function":"sp_full","verdict":"AGREES(256)"},{"function":"sp_and_stack","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrow-register-inputs.xml": [{"function":"store_parts","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrow-word-compare.xml": [{"function":"sum_is_zero","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-narrowargs-x86.xml": [{"function":"store3","verdict":"AGREES(256)"},{"function":"store3","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrowargs.xml": [{"function":"put16","verdict":"AGREES(249)"},{"function":"put_hi","verdict":"AGREES(252)"},{"function":"put_flag","verdict":"AGREES(252)"},{"function":"put16","verdict":"AGREES(249)"},{"function":"put_hi","verdict":"AGREES(252)"},{"function":"put_flag","verdict":"AGREES(252)"}], + "tests/stages/kuna-narrowed-call-input.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrowequal.xml": [{"function":"sum_is_80","verdict":"AGREES(256)"},{"function":"byte_is_flag","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrowext.xml": [{"function":"csc","verdict":"DIFFERS(return)"},{"function":"cus","verdict":"AGREES(256)"},{"function":"ci","verdict":"DIFFERS(return)"},{"function":"cu","verdict":"DIFFERS(return)"},{"function":"pi","verdict":"DIFFERS(return)"},{"function":"pus","verdict":"AGREES(256)"},{"function":"pu","verdict":"DIFFERS(return)"},{"function":"psc","verdict":"DIFFERS(return)"},{"function":"csc","verdict":"AGREES(256)"},{"function":"cus","verdict":"AGREES(256)"},{"function":"ci","verdict":"AGREES(256)"},{"function":"cu","verdict":"AGREES(256)"},{"function":"pi","verdict":"AGREES(256)"},{"function":"pus","verdict":"AGREES(256)"},{"function":"pu","verdict":"AGREES(256)"},{"function":"psc","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrowload.xml": [{"function":"t_low","verdict":"AGREES(256)"},{"function":"t_bit","verdict":"AGREES(256)"},{"function":"p_low","verdict":"AGREES(256)"},{"function":"p_bit","verdict":"AGREES(256)"},{"function":"q_bit","verdict":"AGREES(256)"},{"function":"s_set","verdict":"AGREES(256)"},{"function":"c_bit","verdict":"AGREES(256)"},{"function":"l_bit","verdict":"AGREES(254)"}], + "tests/stages/kuna-narrowret-x86.xml": [{"function":"next_byte","verdict":"AGREES(256)"},{"function":"whole","verdict":"AGREES(256)"},{"function":"larger_byte","verdict":"AGREES(256)"},{"function":"returns_word","verdict":"AGREES(256)"},{"function":"next_byte","verdict":"AGREES(256)"},{"function":"whole","verdict":"AGREES(256)"},{"function":"larger_byte","verdict":"AGREES(256)"},{"function":"returns_word","verdict":"AGREES(256)"}], + "tests/stages/kuna-narrowret.xml": [{"function":"next_byte","verdict":"AGREES(256)"},{"function":"above","verdict":"AGREES(256)"},{"function":"larger_byte","verdict":"AGREES(256)"},{"function":"count_above","verdict":"AGREES(256)"},{"function":"keeps_sign","verdict":"AGREES(256)"},{"function":"next_byte","verdict":"AGREES(256)"},{"function":"above","verdict":"AGREES(256)"},{"function":"larger_byte","verdict":"AGREES(256)"},{"function":"count_above","verdict":"AGREES(256)"},{"function":"keeps_sign","verdict":"AGREES(256)"}], + "tests/stages/kuna-native-switch-labels.xml": [{"function":"signed8","verdict":"AGREES(256)"},{"function":"signed16","verdict":"AGREES(256)"},{"function":"signed32","verdict":"AGREES(256)"},{"function":"signed64","verdict":"AGREES(256)"},{"function":"unsigned8","verdict":"AGREES(256)"},{"function":"unsigned16","verdict":"AGREES(256)"},{"function":"unsigned32","verdict":"AGREES(256)"},{"function":"unsigned64","verdict":"AGREES(256)"},{"function":"signed16_load","verdict":"AGREES(256)"},{"function":"signed16_widen","verdict":"AGREES(256)"}], + "tests/stages/kuna-nestand.xml": [{"function":"nobody","verdict":"AGREES(256)"},{"function":"path","verdict":"AGREES(256)"},{"function":"chained","verdict":"AGREES(256)"},{"function":"nobody","verdict":"AGREES(256)"},{"function":"path","verdict":"AGREES(256)"},{"function":"chained","verdict":"AGREES(256)"},{"function":"outer_else","verdict":"AGREES(256)"},{"function":"inner_else","verdict":"AGREES(256)"},{"function":"second","verdict":"AGREES(256)"},{"function":"kept","verdict":"AGREES(256)"},{"function":"nobody","verdict":"AGREES(256)"},{"function":"nobody","verdict":"AGREES(256)"},{"function":"chained","verdict":"AGREES(256)"},{"function":"second","verdict":"AGREES(256)"}], + "tests/stages/kuna-nodejoin-late-phi.xml": [{"function":"late_phi","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-noreturn-discstrict.xml": [{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"},{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/kuna-normalize-branches.xml": [{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-nullable-relocations.xml": [{"function":"guard","verdict":"DIFFERS(call 1 at 0x400018 to 0x402000)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x400028 to 0x402000)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x40000e to 0x402000)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x400013 to 0x402000)"},{"function":"unrelated_literal","verdict":"AGREES(256)"},{"function":"unrelated_literal","verdict":"AGREES(256)"},{"function":"unrelated_literal","verdict":"AGREES(256)"},{"function":"unrelated_literal","verdict":"AGREES(256)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x400030 to 0x402000)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x400060 to 0x402000)"},{"function":"guard","verdict":"DIFFERS(call 1 at 0x400014 to 0x402000)"},{"function":"same","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-nzmask-wide-stride.xml": [{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-o0detect.xml": [{"function":"unget","verdict":"AGREES(256)"},{"function":"onsig","verdict":"AGREES(256)"},{"function":"mode","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"unget","verdict":"AGREES(256)"},{"function":"onsig","verdict":"AGREES(256)"},{"function":"mode","verdict":"AGREES(256)"}], + "tests/stages/kuna-o0fold.xml": [{"function":"show","verdict":"AGREES(256)"},{"function":"show","verdict":"AGREES(256)"},{"function":"add","verdict":"AGREES(256)"},{"function":"add","verdict":"AGREES(256)"}], + "tests/stages/kuna-objcdirect.xml": [{"function":"-[Label bump:]","verdict":"AGREES(256)"},{"function":"+[Label scale:]","verdict":"AGREES(256)"},{"function":"-[Label flags]","verdict":"AGREES(256)"}], + "tests/stages/kuna-objcforin.xml": [{"function":"_visit_all","verdict":"UNKNOWN(budget)"},{"function":"_visit_all","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-objcmeta.xml": [{"function":"sub_10000083c","verdict":"AGREES(256)"},{"function":"sub_100000860","verdict":"AGREES(256)"},{"function":"_use","verdict":"AGREES(256)"},{"function":"-[Base ratio]","verdict":"AGREES(256)"},{"function":"-[Base(Extra) greet:]","verdict":"AGREES(256)"},{"function":"-[Sub x]","verdict":"AGREES(256)"},{"function":"_use","verdict":"AGREES(256)"},{"function":"-[Base ratio]","verdict":"AGREES(256)"},{"function":"-[Base(Extra) greet:]","verdict":"AGREES(256)"},{"function":"-[Sub x]","verdict":"AGREES(256)"}], + "tests/stages/kuna-objcrefs.xml": [{"function":"sub_1000007ec","verdict":"AGREES(256)"},{"function":"_use","verdict":"AGREES(256)"},{"function":"_remote","verdict":"AGREES(256)"},{"function":"-[Derived greet:]","verdict":"AGREES(256)"},{"function":"_use","verdict":"AGREES(256)"},{"function":"_use2","verdict":"AGREES(256)"},{"function":"_tag","verdict":"AGREES(256)"},{"function":"_remote","verdict":"AGREES(256)"}], + "tests/stages/kuna-objcsdk.xml": [{"function":"_style","verdict":"AGREES(256)"},{"function":"_style","verdict":"UNKNOWN(unsupported-op)"},{"function":"objc_msgSend$frame","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-objctypes.xml": [{"function":"sub_100000740","verdict":"AGREES(256)"},{"function":"-[Holder innerCount]","verdict":"AGREES(256)"},{"function":"-[Holder inner]","verdict":"AGREES(256)"},{"function":"-[Holder innerCount]","verdict":"AGREES(256)"},{"function":"-[Holder inner]","verdict":"AGREES(256)"},{"function":"-[Holder setInner:]","verdict":"AGREES(256)"}], + "tests/stages/kuna-octeon-64-abi.xml": [{"function":"quad_after","verdict":"AGREES(256)"},{"function":"quad_identity","verdict":"AGREES(256)"},{"function":"quad_last_after","verdict":"AGREES(256)"}], + "tests/stages/kuna-octeon-atomic-refusal.xml": [{"function":"unsupported_atomic","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-octeon-atomics-n32.xml": [{"function":"atomic_global","verdict":"UNKNOWN(unsupported-op)"},{"function":"atomic_local","verdict":"UNKNOWN(unsupported-op)"},{"function":"conditional","verdict":"UNKNOWN(unsupported-op)"},{"function":"barriers","verdict":"UNKNOWN(unsupported-op)"},{"function":"wide_integer","verdict":"UNKNOWN(unsupported-op)"},{"function":"partial_global","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-octeon-atomics-n64.xml": [{"function":"atomic_global","verdict":"UNKNOWN(unsupported-op)"},{"function":"atomic_local","verdict":"UNKNOWN(unsupported-op)"},{"function":"conditional","verdict":"UNKNOWN(unsupported-op)"},{"function":"barriers","verdict":"UNKNOWN(unsupported-op)"},{"function":"wide_integer","verdict":"UNKNOWN(unsupported-op)"},{"function":"partial_global","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-octeon-core.xml": [{"function":"low_sum","verdict":"AGREES(256)"},{"function":"bit_three","verdict":"AGREES(256)"},{"function":"byte_at_eight","verdict":"AGREES(256)"}], + "tests/stages/kuna-octeon-n32-abi.xml": [{"function":"pair_first","verdict":"AGREES(256)"},{"function":"small_result","verdict":"AGREES(256)"},{"function":"quad_identity","verdict":"AGREES(256)"}], + "tests/stages/kuna-octeon-n64-arguments.xml": [{"function":"get_four","verdict":"AGREES(256)"},{"function":"float_identity","verdict":"AGREES(256)"},{"function":"float_last","verdict":"AGREES(256)"},{"function":"float_stack","verdict":"AGREES(256)"}], + "tests/stages/kuna-octeoneffects.xml": [{"function":"update","verdict":"UNKNOWN(unsupported-op)"},{"function":"barrier","verdict":"UNKNOWN(unsupported-op)"},{"function":"reserve","verdict":"UNKNOWN(unsupported-op)"},{"function":"snapshot","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"update","verdict":"UNKNOWN(unsupported-op)"},{"function":"barrier","verdict":"UNKNOWN(unsupported-op)"},{"function":"spill","verdict":"UNKNOWN(unsupported-op)"},{"function":"linked","verdict":"UNKNOWN(unsupported-op)"},{"function":"snapshot","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"ordered_snapshot","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_elsewhere","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_deep","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"barrier","verdict":"UNKNOWN(unsupported-op)"},{"function":"snapshot","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_neighbor_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"ordered_snapshot","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_elsewhere","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_deep","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative","verdict":"UNKNOWN(unsupported-op)"},{"function":"zero_incoming_negative_transient","verdict":"UNKNOWN(unsupported-op)"},{"function":"persist_atomic","verdict":"AGREES(256)"},{"function":"persist_atomic","verdict":"AGREES(256)"}], + "tests/stages/kuna-opaquepointerretype.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"}], + "tests/stages/kuna-opaquepredicate.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"square","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"parity","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"square","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"mixedkeep","verdict":"AGREES(256)"},{"function":"parity","verdict":"AGREES(256)"},{"function":"steps","verdict":"AGREES(256)"}], + "tests/stages/kuna-outlang-rust.xml": [{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-outline-proto.xml": [{"function":"reg","verdict":"AGREES(256)"},{"function":"reg","verdict":"DIVERGES(synthesized-call)"}], + "tests/stages/kuna-outline.xml": [{"function":"ol","verdict":"AGREES(256)"},{"function":"ol","verdict":"DIVERGES(synthesized-call)"}], + "tests/stages/kuna-ownreturn.xml": [{"function":"own","verdict":"AGREES(256)"},{"function":"own_cond","verdict":"AGREES(256)"},{"function":"keep_int","verdict":"AGREES(256)"},{"function":"two_ret","verdict":"AGREES(256)"},{"function":"sys2nr","verdict":"DIVERGES(syscall-result)"},{"function":"ashr_hi","verdict":"AGREES(256)"}], + "tests/stages/kuna-pacflow-a64.xml": [{"function":"call_it","verdict":"AGREES(256)"},{"function":"sign_it","verdict":"AGREES(256)"},{"function":"auth_it","verdict":"AGREES(256)"},{"function":"strip_it","verdict":"AGREES(256)"},{"function":"sign_fn","verdict":"AGREES(256)"},{"function":"store_signed","verdict":"AGREES(256)"},{"function":"sign_ia_plain","verdict":"AGREES(256)"},{"function":"auth_ib_plain","verdict":"AGREES(256)"},{"function":"auth_iza","verdict":"AGREES(256)"},{"function":"strip_data","verdict":"AGREES(256)"},{"function":"sign_db_store","verdict":"AGREES(256)"}], + "tests/stages/kuna-pacmodifier-arg-a64e.xml": [{"function":"swap_signed","verdict":"AGREES(256)"},{"function":"swap_global","verdict":"AGREES(256)"},{"function":"tagged","verdict":"AGREES(256)"},{"function":"buffer","verdict":"AGREES(256)"}], + "tests/stages/kuna-panicloc.xml": [{"function":"pick","verdict":"DIVERGES(panic-check)"},{"function":"pick","verdict":"DIVERGES(panic-check)"}], + "tests/stages/kuna-parameter-alias.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"}], + "tests/stages/kuna-paramrefdecl.xml": [{"function":"derive_key","verdict":"AGREES(256)"}], + "tests/stages/kuna-parisc-nested-operands.xml": [{"function":"two_calls","verdict":"AGREES(256)"}], + "tests/stages/kuna-partialconcat.xml": [{"function":"swap_port","verdict":"AGREES(256)"},{"function":"swap_low_word","verdict":"AGREES(256)"},{"function":"join_words","verdict":"AGREES(256)"}], + "tests/stages/kuna-passthrough-filegap-arm.xml": [{"function":"bits_tail","verdict":"AGREES(256)"},{"function":"sst_tail","verdict":"DIFFERS(call at 0x10028 to 0x1001c)"}], + "tests/stages/kuna-passthrough-filegap.xml": [{"function":"bits_tail","verdict":"AGREES(256)"},{"function":"sst_tail","verdict":"DIFFERS(call at 0x40101f to 0x401013)"}], + "tests/stages/kuna-passthrough.xml": [{"function":"fwd","verdict":"AGREES(256)"},{"function":"fwdtest","verdict":"AGREES(256)"},{"function":"fwd","verdict":"AGREES(256)"},{"function":"fwdtest","verdict":"AGREES(256)"},{"function":"forward_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"forward_text","verdict":"UNKNOWN(unsupported-op)"},{"function":"forward_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"forward_text","verdict":"UNKNOWN(unsupported-op)"},{"function":"wrap","verdict":"AGREES(256)"}], + "tests/stages/kuna-passthroughfwdstack.xml": [{"function":"getopt_long","verdict":"AGREES(256)"},{"function":"getopt_long_only","verdict":"AGREES(256)"},{"function":"twice_pid","verdict":"AGREES(256)"},{"function":"twice_cnt","verdict":"AGREES(256)"},{"function":"getopt_long","verdict":"DIFFERS(call at 0x403009 to 0x403080)"}], + "tests/stages/kuna-passthroughslot-arm.xml": [{"function":"sbuffill","verdict":"AGREES(252)"},{"function":"lock","verdict":"AGREES(256)"},{"function":"lock3","verdict":"AGREES(256)"},{"function":"sbuffill","verdict":"DIFFERS(call at 0x10010 to 0x10000)"},{"function":"lock","verdict":"AGREES(256)"}], + "tests/stages/kuna-passthroughslot.xml": [{"function":"getopt_long","verdict":"AGREES(256)"},{"function":"w5","verdict":"AGREES(256)"},{"function":"get_int","verdict":"AGREES(256)"},{"function":"g3","verdict":"AGREES(256)"},{"function":"pid_plus","verdict":"AGREES(256)"},{"function":"p_rbx_first","verdict":"AGREES(256)"},{"function":"pid_minus","verdict":"AGREES(256)"},{"function":"getopt_long","verdict":"DIFFERS(call at 0x40103b to 0x401000)"},{"function":"w5","verdict":"DIFFERS(call at 0x401084 to 0x401050)"},{"function":"get_int","verdict":"DIFFERS(call at 0x40110c to 0x4010d0)"}], + "tests/stages/kuna-pdb-sidecar.xml": [], + "tests/stages/kuna-pebnames-x86.xml": [{"function":"anti_debug32","verdict":"AGREES(256)"},{"function":"anti_debug32","verdict":"AGREES(256)"},{"function":"seh_frame32","verdict":"AGREES(256)"},{"function":"seh_frame32","verdict":"AGREES(256)"},{"function":"eh_frame32","verdict":"AGREES(256)"},{"function":"eh_frame32","verdict":"AGREES(256)"},{"function":"hole_1010","verdict":"AGREES(256)"},{"function":"past_end32","verdict":"AGREES(256)"},{"function":"version_holes32","verdict":"AGREES(256)"},{"function":"peb_past_end32","verdict":"AGREES(256)"},{"function":"gs_32","verdict":"AGREES(256)"}], + "tests/stages/kuna-pebnames.xml": [{"function":"anti_debug","verdict":"AGREES(256)"},{"function":"anti_debug","verdict":"AGREES(256)"},{"function":"anti_debug","verdict":"AGREES(256)"},{"function":"past_end","verdict":"AGREES(256)"},{"function":"version_hole","verdict":"AGREES(256)"},{"function":"var_disp","verdict":"AGREES(256)"},{"function":"fs_long_mode","verdict":"AGREES(256)"},{"function":"store_then_probe","verdict":"AGREES(256)"},{"function":"switch_probe","verdict":"AGREES(256)"},{"function":"switch_probe","verdict":"AGREES(256)"}], + "tests/stages/kuna-pemain.xml": [{"function":"sub_1400011a0","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"AGREES(256)"}], + "tests/stages/kuna-persistcalls.xml": [{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"small","verdict":"AGREES(256)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"small","verdict":"AGREES(256)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"small","verdict":"AGREES(256)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"revisit","verdict":"AGREES(256)"},{"function":"loopstore","verdict":"AGREES(103)"},{"function":"snip","verdict":"AGREES(256)"},{"function":"snipsys","verdict":"AGREES(256)"},{"function":"revisit","verdict":"AGREES(256)"},{"function":"loopstore","verdict":"AGREES(103)"},{"function":"snip","verdict":"AGREES(256)"},{"function":"snipsys","verdict":"AGREES(256)"}], + "tests/stages/kuna-picbase.xml": [{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/kuna-piececover.xml": [{"function":"swapbytes","verdict":"AGREES(256)"}], + "tests/stages/kuna-piecepathology.xml": [{"function":"next_byte","verdict":"AGREES(256)"},{"function":"next_byte","verdict":"AGREES(256)"}], + "tests/stages/kuna-pipeline-quality.xml": [{"function":"testElseIf","verdict":"AGREES(66)"},{"function":"testElseIf","verdict":"AGREES(66)"}], + "tests/stages/kuna-pltlocal.xml": [{"function":"timer_wrapper","verdict":"AGREES(256)"}], + "tests/stages/kuna-pointer-arguments.xml": [{"function":"sink","verdict":"AGREES(256)"},{"function":"change","verdict":"AGREES(256)"}], + "tests/stages/kuna-pointer-storage-literal.xml": [{"function":"emit","verdict":"AGREES(256)"}], + "tests/stages/kuna-pointerwalk-budget-mips.xml": [{"function":"ldso_d2f0","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-pointerwalk-memo.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-poolfallthru.xml": [{"function":"probe","verdict":"UNKNOWN(unsupported-op)"},{"function":"probe","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"probe","verdict":"UNKNOWN(unsupported-op)"},{"function":"probe","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"cond_call","verdict":"UNKNOWN(unsupported-op)"},{"function":"labelled_word","verdict":"AGREES(256)"},{"function":"halfword_read","verdict":"AGREES(256)"},{"function":"live_gap","verdict":"UNKNOWN(unsupported-op)"},{"function":"wide_gap","verdict":"UNKNOWN(unsupported-op)"},{"function":"data_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"returning_callee","verdict":"UNKNOWN(unsupported-op)"},{"function":"unproven_reader","verdict":"UNKNOWN(unsupported-op)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"},{"function":"bounded_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"pad_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"indirect_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"two_pools","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"wide_literal","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"ordered_loads","verdict":"AGREES(253)"},{"function":"junk_pointer","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"},{"function":"cond_call","verdict":"UNKNOWN(unsupported-op)"},{"function":"labelled_word","verdict":"AGREES(256)"},{"function":"halfword_read","verdict":"AGREES(256)"},{"function":"live_gap","verdict":"UNKNOWN(unsupported-op)"},{"function":"wide_gap","verdict":"UNKNOWN(unsupported-op)"},{"function":"data_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"returning_callee","verdict":"UNKNOWN(unsupported-op)"},{"function":"unproven_reader","verdict":"UNKNOWN(unsupported-op)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"},{"function":"bounded_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"pad_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"indirect_call","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"two_pools","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"wide_literal","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"ordered_loads","verdict":"AGREES(253)"},{"function":"junk_pointer","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"},{"function":"svc_junk","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-postinc.xml": [{"function":"sumb","verdict":"AGREES(16)"},{"function":"fill","verdict":"AGREES(2)"},{"function":"sumi","verdict":"AGREES(1)"},{"function":"sumb","verdict":"AGREES(16)"},{"function":"fill","verdict":"AGREES(2)"}], + "tests/stages/kuna-powerpc-e500mc-hard-float.xml": [{"function":"add","verdict":"AGREES(256)"}], + "tests/stages/kuna-powerpc-isel.xml": [{"function":"choose","verdict":"AGREES(256)"},{"function":"sum5","verdict":"AGREES(256)"},{"function":"choose_zero","verdict":"AGREES(256)"}], + "tests/stages/kuna-powerpc-spe-integer-pair.xml": [{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc-lwarx-reservation.xml": [{"function":"atomic_increment","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-ppc-nested-operands.xml": [{"function":"rotate_mask","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32-computed-lr.xml": [{"function":"dispatch","verdict":"DIFFERS(return)"},{"function":"shared_lr","verdict":"AGREES(256)"},{"function":"guarded_lr","verdict":"AGREES(256)"},{"function":"saved_lr","verdict":"AGREES(256)"},{"function":"two_destinations","verdict":"AGREES(256)"},{"function":"correlated_operands","verdict":"AGREES(256)"},{"function":"saved_lr_through_alias","verdict":"AGREES(256)"},{"function":"reused_lr_slot","verdict":"DIFFERS(return)"},{"function":"unused_lr_arithmetic","verdict":"DIFFERS(return)"},{"function":"store_through_lr","verdict":"AGREES(256)"},{"function":"store_incoming_lr_then_jump","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-abi-indirect.xml": [{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-abi-isolation.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-abi.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-address-escapes.xml": [{"function":"check2","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-aggressive.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-callback-provenance.xml": [{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1014","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"},{"function":"sub_1008","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-caller-context.xml": [{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-control-edges.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-control-flow.xml": [{"function":"check2","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-driver.xml": [{"function":"refs","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"refs","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-indirect.xml": [{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-loads-and-entries.xml": [{"function":"check2","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-memory-and-mappings.xml": [{"function":"check2","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-reversed-save.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-runtime.xml": [{"function":"check","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-slot-clobber.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-stack-ctr.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check2","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports-stub-entry-alias.xml": [{"function":"check2","verdict":"AGREES(256)"},{"function":"_DT_INIT","verdict":"AGREES(256)"},{"function":"sub_1004","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc32picimports.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"UNKNOWN(noreturn-unverified)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc64-ldarx-encoding.xml": [{"function":"ldx_then_ldarx","verdict":"AGREES(256)"},{"function":"atomic_increment","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-ppc64-plt-stubs.xml": [{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release_pcrel","verdict":"AGREES(256)"},{"function":"measure_pcrel","verdict":"AGREES(256)"},{"function":"release","verdict":"AGREES(256)"},{"function":"measure","verdict":"AGREES(256)"},{"function":"release_pcrel","verdict":"AGREES(256)"},{"function":"measure_pcrel","verdict":"AGREES(256)"},{"function":"outer","verdict":"AGREES(256)"},{"function":"sample","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc64-toc-reload-switch.xml": [{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch_copy","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc64be-elfv2-stack-args.xml": [{"function":"f9","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-ppc64le-elfv2-stack-args.xml": [{"function":"f9","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-prefersplit.xml": [{"function":"ccw_entry","verdict":"AGREES(256)"},{"function":"ccw_entry","verdict":"AGREES(256)"},{"function":"ccw_helper","verdict":"AGREES(256)"},{"function":"ccw_formatter","verdict":"AGREES(256)"},{"function":"ccw_vector","verdict":"AGREES(256)"},{"function":"ccw_tagged","verdict":"AGREES(256)"},{"function":"ccw_mixed","verdict":"AGREES(256)"},{"function":"ccw_array","verdict":"AGREES(256)"},{"function":"ccw_phi","verdict":"AGREES(256)"},{"function":"ccw_ints","verdict":"AGREES(256)"}], + "tests/stages/kuna-prefixed-noreturn.xml": [{"function":"keeps_session","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"plain","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_exit","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"plain","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_exit","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"AGREES(256)"},{"function":"keeps_count","verdict":"UNKNOWN(unsupported-op)"},{"function":"keeps_exit","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-prefixed-unsized.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"hops","verdict":"AGREES(256)"},{"function":"counts","verdict":"AGREES(256)"},{"function":"leaves","verdict":"AGREES(256)"},{"function":"keeps_mid","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"hops","verdict":"AGREES(256)"},{"function":"counts","verdict":"AGREES(256)"},{"function":"leaves","verdict":"AGREES(256)"},{"function":"keeps_mid","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"}], + "tests/stages/kuna-preloaded-local-read-sparc.xml": [{"function":"preload","verdict":"AGREES(256)"}], + "tests/stages/kuna-preloaded-local-read.xml": [{"function":"preload","verdict":"AGREES(256)"}], + "tests/stages/kuna-protoorder-tailcallees.xml": [{"function":"thunk","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"thunk","verdict":"AGREES(256)"},{"function":"pass","verdict":"AGREES(256)"},{"function":"_tail_auth","verdict":"DIVERGES(ptrauth-trap)"},{"function":"_tail_auth","verdict":"DIVERGES(ptrauth-trap)"}], + "tests/stages/kuna-protoranges-homeslot.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-prunedssa.xml": [{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"escaped","verdict":"AGREES(256)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"escaped","verdict":"AGREES(256)"},{"function":"churn","verdict":"UNKNOWN(budget)"},{"function":"churn","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-ptradd-absolute-index.xml": [{"function":"bytemem_index","verdict":"AGREES(256)"}], + "tests/stages/kuna-ptrauthtrap.xml": [{"function":"both","verdict":"AGREES(256)"},{"function":"plain","verdict":"AGREES(256)"},{"function":"x30check","verdict":"DIVERGES(ptrauth-trap)"},{"function":"x30forged","verdict":"AGREES(256)"},{"function":"x30inverted","verdict":"AGREES(256)"},{"function":"x30forgedearlier","verdict":"AGREES(256)"},{"function":"x30loaded","verdict":"AGREES(256)"},{"function":"_tail_auth","verdict":"AGREES(256)"},{"function":"_strip_check","verdict":"AGREES(256)"},{"function":"_tail_auth","verdict":"DIVERGES(ptrauth-trap)"},{"function":"_strip_check","verdict":"AGREES(256)"},{"function":"_check","verdict":"AGREES(256)"},{"function":"_check_x0","verdict":"AGREES(256)"}], + "tests/stages/kuna-ptrchain.xml": [{"function":"mixed","verdict":"AGREES(256)"},{"function":"alone","verdict":"AGREES(256)"},{"function":"negated","verdict":"AGREES(256)"},{"function":"field","verdict":"AGREES(256)"},{"function":"is_abs","verdict":"AGREES(256)"},{"function":"count","verdict":"AGREES(191)"},{"function":"mixed","verdict":"AGREES(256)"},{"function":"alone","verdict":"AGREES(256)"},{"function":"negated","verdict":"AGREES(256)"},{"function":"field","verdict":"AGREES(256)"},{"function":"is_abs","verdict":"AGREES(256)"},{"function":"count","verdict":"AGREES(191)"}], + "tests/stages/kuna-ptrdepthcap.xml": [{"function":"check","verdict":"AGREES(256)"},{"function":"check","verdict":"AGREES(256)"}], + "tests/stages/kuna-ptrfromuse-faroffset.xml": [{"function":"near_leaf","verdict":"AGREES(240)"},{"function":"page_leaf","verdict":"AGREES(237)"},{"function":"conn_leaf","verdict":"AGREES(256)"},{"function":"get_data","verdict":"AGREES(256)"},{"function":"put_bss","verdict":"AGREES(256)"},{"function":"get_code","verdict":"AGREES(256)"},{"function":"get_local","verdict":"AGREES(256)"},{"function":"near_leaf","verdict":"AGREES(240)"},{"function":"page_leaf","verdict":"AGREES(237)"},{"function":"conn_leaf","verdict":"AGREES(256)"},{"function":"get_data","verdict":"AGREES(256)"},{"function":"put_bss","verdict":"AGREES(256)"},{"function":"get_code","verdict":"AGREES(256)"},{"function":"get_local","verdict":"AGREES(256)"},{"function":"near_leaf","verdict":"AGREES(256)"},{"function":"page_leaf","verdict":"AGREES(256)"},{"function":"conn_leaf","verdict":"AGREES(256)"},{"function":"get_data","verdict":"AGREES(256)"},{"function":"put_bss","verdict":"AGREES(256)"},{"function":"get_code","verdict":"AGREES(256)"},{"function":"get_local","verdict":"AGREES(256)"},{"function":"near_leaf","verdict":"AGREES(256)"},{"function":"page_leaf","verdict":"AGREES(256)"},{"function":"conn_leaf","verdict":"AGREES(256)"},{"function":"get_data","verdict":"AGREES(256)"},{"function":"put_bss","verdict":"AGREES(256)"},{"function":"get_code","verdict":"AGREES(256)"},{"function":"get_local","verdict":"AGREES(256)"},{"function":"update","verdict":"AGREES(247)"},{"function":"read_reg","verdict":"AGREES(256)"},{"function":"letter_rank","verdict":"AGREES(256)"},{"function":"get_ext","verdict":"AGREES(256)"}], + "tests/stages/kuna-ptrfromuse.xml": [{"function":"sumfields","verdict":"AGREES(256)"},{"function":"scaledbase","verdict":"AGREES(256)"},{"function":"derefzero","verdict":"AGREES(256)"},{"function":"globalindex","verdict":"AGREES(256)"},{"function":"blindindex","verdict":"AGREES(256)"},{"function":"sumfields","verdict":"AGREES(256)"},{"function":"scaledbase","verdict":"AGREES(256)"},{"function":"derefzero","verdict":"AGREES(256)"},{"function":"globalindex","verdict":"AGREES(256)"},{"function":"blindindex","verdict":"AGREES(256)"},{"function":"sumfields","verdict":"AGREES(256)"},{"function":"scaledbase","verdict":"AGREES(256)"},{"function":"derefzero","verdict":"AGREES(256)"},{"function":"globalindex","verdict":"AGREES(256)"},{"function":"blindindex","verdict":"AGREES(256)"}], + "tests/stages/kuna-ptrptr.xml": [{"function":"w_cmp","verdict":"AGREES(256)"},{"function":"w_walk","verdict":"AGREES(41)"},{"function":"w_out","verdict":"AGREES(256)"},{"function":"w_grow","verdict":"AGREES(256)"},{"function":"c_words","verdict":"AGREES(85)"},{"function":"c_list","verdict":"AGREES(50)"},{"function":"c_db","verdict":"AGREES(256)"},{"function":"c_span","verdict":"AGREES(256)"},{"function":"w_cmp","verdict":"AGREES(256)"},{"function":"w_walk","verdict":"AGREES(41)"},{"function":"w_out","verdict":"AGREES(256)"},{"function":"w_grow","verdict":"AGREES(256)"},{"function":"c_words","verdict":"AGREES(85)"},{"function":"c_list","verdict":"AGREES(50)"},{"function":"c_db","verdict":"AGREES(256)"},{"function":"c_span","verdict":"AGREES(256)"},{"function":"w_files","verdict":"AGREES(47)"}], + "tests/stages/kuna-pushimmediateret.xml": [{"function":"push_immediate_ret","verdict":"AGREES(256)"}], + "tests/stages/kuna-pushpadread.xml": [{"function":"run","verdict":"AGREES(256)"},{"function":"report","verdict":"AGREES(256)"},{"function":"forward","verdict":"AGREES(256)"}], + "tests/stages/kuna-rangetest-thumb.xml": [{"function":"handle","verdict":"AGREES(252)"},{"function":"handle","verdict":"AGREES(252)"},{"function":"handle","verdict":"AGREES(252)"}], + "tests/stages/kuna-rangetest.xml": [{"function":"printable","verdict":"AGREES(256)"},{"function":"reject","verdict":"AGREES(256)"},{"function":"digit","verdict":"AGREES(256)"},{"function":"lower_after","verdict":"AGREES(256)"},{"function":"isdig","verdict":"AGREES(256)"},{"function":"small","verdict":"AGREES(256)"},{"function":"number","verdict":"AGREES(256)"},{"function":"ctl","verdict":"AGREES(103)"},{"function":"printable","verdict":"AGREES(256)"},{"function":"reject","verdict":"AGREES(256)"},{"function":"digit","verdict":"AGREES(256)"},{"function":"lower_after","verdict":"AGREES(256)"},{"function":"isdig","verdict":"AGREES(256)"},{"function":"small","verdict":"AGREES(256)"},{"function":"number","verdict":"AGREES(256)"},{"function":"ctl","verdict":"AGREES(103)"},{"function":"printable","verdict":"AGREES(256)"},{"function":"reject","verdict":"AGREES(256)"},{"function":"digit","verdict":"AGREES(256)"},{"function":"lower_after","verdict":"AGREES(256)"},{"function":"isdig","verdict":"AGREES(256)"},{"function":"small","verdict":"AGREES(256)"},{"function":"number","verdict":"AGREES(256)"},{"function":"ctl","verdict":"AGREES(103)"}], + "tests/stages/kuna-recordlayout.xml": [{"function":"item_value","verdict":"AGREES(256)"},{"function":"wire_len","verdict":"AGREES(256)"}], + "tests/stages/kuna-reentereddispatch.xml": [{"function":"callback_dispatch","verdict":"AGREES(256)"},{"function":"reentry_n32_r31_2","verdict":"DIFFERS(call 1 at 0x40000c to 0x40002c)"},{"function":"reentry_n32_r31_4","verdict":"DIFFERS(call 1 at 0x40000c to 0x40002c)"},{"function":"reentry_64_r31_2","verdict":"DIFFERS(call 1 at 0x40000c to 0x40002c)"},{"function":"reentry_64_r31_4","verdict":"DIFFERS(call 1 at 0x40000c to 0x40002c)"},{"function":"reentry_64_r9_2","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_2_early","verdict":"DIFFERS(call 1 at 0x40000c to 0x400044)"},{"function":"reentry_64_r31_2_condreturn","verdict":"DIFFERS(call 1 at 0x40000c to 0x40002c)"},{"function":"reentry_64_r31_2_indirect_reentry","verdict":"DIFFERS(call 1 at 0x40000c to 0x400034)"},{"function":"reentry_n32_r31_2","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_n32_r31_4","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_2","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_4","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r9_2","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_2_early","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_2_condreturn","verdict":"UNKNOWN(unsupported-op)"},{"function":"reentry_64_r31_2_indirect_reentry","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-regionedgeorder-preset.xml": [{"function":"set_exit_status","verdict":"AGREES(256)"},{"function":"set_exit_status","verdict":"AGREES(256)"},{"function":"set_exit_status","verdict":"AGREES(256)"}], + "tests/stages/kuna-regions.xml": [{"function":"test","verdict":"AGREES(16)"}], + "tests/stages/kuna-register-pair-call-args.xml": [{"function":"both","verdict":"AGREES(256)"},{"function":"nonzero","verdict":"AGREES(256)"},{"function":"reversed","verdict":"AGREES(256)"},{"function":"delay","verdict":"AGREES(256)"},{"function":"high_only","verdict":"AGREES(256)"},{"function":"low_only","verdict":"AGREES(256)"},{"function":"unchanged_pair","verdict":"AGREES(256)"},{"function":"single_without_wide","verdict":"AGREES(256)"},{"function":"one_argument","verdict":"AGREES(256)"},{"function":"one_variadic","verdict":"AGREES(256)"},{"function":"declared_wide","verdict":"AGREES(256)"},{"function":"unknown_wide_output","verdict":"AGREES(256)"},{"function":"convert_argument","verdict":"AGREES(256)"},{"function":"interval_argument","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"math_wrapper","verdict":"AGREES(256)"},{"function":"math_wrapper","verdict":"AGREES(256)"},{"function":"math_wrapper","verdict":"AGREES(256)"},{"function":"pair_then_single","verdict":"AGREES(256)"},{"function":"pair_then_single","verdict":"AGREES(256)"}], + "tests/stages/kuna-registerlifetimes-join.xml": [{"function":"wide_names","verdict":"AGREES(256)"},{"function":"wide_names","verdict":"AGREES(256)"},{"function":"wide_names","verdict":"AGREES(256)"},{"function":"multiply_names","verdict":"AGREES(256)"},{"function":"multiply_names","verdict":"AGREES(256)"},{"function":"multiply_names","verdict":"AGREES(256)"},{"function":"register_parameter_reuse","verdict":"AGREES(256)"},{"function":"register_parameter_reuse","verdict":"AGREES(256)"},{"function":"value_domains","verdict":"AGREES(256)"},{"function":"value_domains","verdict":"AGREES(256)"}], + "tests/stages/kuna-regnarrow-args.xml": [{"function":"f0000","verdict":"AGREES(256)"},{"function":"f0017","verdict":"AGREES(256)"},{"function":"f0000","verdict":"AGREES(256)"}], + "tests/stages/kuna-regnarrow-x86.xml": [{"function":"sum_bytes","verdict":"AGREES(16)"},{"function":"sum_bytes","verdict":"AGREES(16)"}], + "tests/stages/kuna-regnarrow.xml": [{"function":"count_bytes","verdict":"AGREES(256)"},{"function":"count_words","verdict":"AGREES(256)"},{"function":"halve","verdict":"AGREES(256)"},{"function":"count_bytes","verdict":"AGREES(256)"},{"function":"count_words","verdict":"AGREES(256)"},{"function":"halve","verdict":"AGREES(256)"}], + "tests/stages/kuna-regpiece.xml": [{"function":"sh_openpipe","verdict":"AGREES(256)"},{"function":"sh_openpipe","verdict":"AGREES(256)"}], + "tests/stages/kuna-regsigned.xml": [{"function":"total","verdict":"AGREES(63)"},{"function":"keep","verdict":"AGREES(252)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"total","verdict":"AGREES(63)"},{"function":"keep","verdict":"AGREES(252)"},{"function":"widen","verdict":"AGREES(256)"}], + "tests/stages/kuna-relocobj-arm-thumb.xml": [], + "tests/stages/kuna-relocobj-ppc-mips.xml": [{"function":"add64","verdict":"AGREES(256)"},{"function":"store","verdict":"AGREES(256)"},{"function":"callint","verdict":"AGREES(256)"},{"function":"store","verdict":"DIFFERS(call at 0x400020 to 0x400000)"},{"function":"callint","verdict":"AGREES(256)"},{"function":"wrap","verdict":"AGREES(256)"},{"function":"store","verdict":"AGREES(256)"}], + "tests/stages/kuna-relocrebase-be.xml": [{"function":"greet","verdict":"AGREES(256)"}], + "tests/stages/kuna-repframecopy.xml": [{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401070","verdict":"AGREES(256)"},{"function":"sub_401130","verdict":"AGREES(256)"},{"function":"sub_401180","verdict":"AGREES(256)"},{"function":"sub_4010b0","verdict":"AGREES(256)"},{"function":"sub_4010d0","verdict":"AGREES(256)"},{"function":"sub_4010f0","verdict":"AGREES(256)"},{"function":"sub_401150","verdict":"AGREES(256)"},{"function":"sub_401270","verdict":"AGREES(256)"},{"function":"sub_401300","verdict":"AGREES(256)"},{"function":"sub_401340","verdict":"AGREES(256)"},{"function":"sub_401370","verdict":"AGREES(256)"},{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_4010d0","verdict":"AGREES(256)"},{"function":"sub_401100","verdict":"AGREES(256)"},{"function":"sub_401130","verdict":"AGREES(256)"},{"function":"sub_4011d0","verdict":"AGREES(256)"},{"function":"sub_401280","verdict":"AGREES(256)"},{"function":"sub_4012c0","verdict":"DIFFERS(return)"},{"function":"sub_401240","verdict":"AGREES(256)"},{"function":"sub_401240","verdict":"AGREES(256)"}], + "tests/stages/kuna-repstring-i386.xml": [{"function":"fill32","verdict":"UNKNOWN(budget)"},{"function":"zero32","verdict":"UNKNOWN(budget)"},{"function":"fill8","verdict":"UNKNOWN(budget)"},{"function":"copy32","verdict":"UNKNOWN(budget)"},{"function":"copy_end","verdict":"UNKNOWN(budget)"},{"function":"isdash","verdict":"AGREES(256)"},{"function":"order","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"same_n","verdict":"UNKNOWN(budget)"},{"function":"same5","verdict":"AGREES(256)"},{"function":"mismatch","verdict":"AGREES(256)"},{"function":"fill32","verdict":"AGREES(17)"},{"function":"zero32","verdict":"AGREES(17)"},{"function":"fill8","verdict":"AGREES(13)"},{"function":"copy32","verdict":"AGREES(13)"},{"function":"copy_end","verdict":"AGREES(13)"},{"function":"isdash","verdict":"AGREES(256)"},{"function":"order","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"same_n","verdict":"AGREES(256)"},{"function":"same5","verdict":"AGREES(256)"},{"function":"mismatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-repstring.xml": [{"function":"fill32","verdict":"AGREES(16)"},{"function":"zero32","verdict":"AGREES(16)"},{"function":"fill8","verdict":"UNKNOWN(budget)"},{"function":"copy32","verdict":"UNKNOWN(budget)"},{"function":"copy_end","verdict":"UNKNOWN(budget)"},{"function":"isdash","verdict":"AGREES(256)"},{"function":"order","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"same_n","verdict":"UNKNOWN(budget)"},{"function":"same5","verdict":"AGREES(256)"},{"function":"mismatch","verdict":"AGREES(256)"},{"function":"zero_g","verdict":"AGREES(256)"},{"function":"fill32","verdict":"AGREES(16)"},{"function":"zero32","verdict":"AGREES(16)"},{"function":"fill8","verdict":"AGREES(14)"},{"function":"copy32","verdict":"AGREES(14)"},{"function":"copy_end","verdict":"AGREES(14)"},{"function":"isdash","verdict":"AGREES(256)"},{"function":"order","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"same_n","verdict":"AGREES(255)"},{"function":"same5","verdict":"AGREES(256)"},{"function":"mismatch","verdict":"AGREES(256)"},{"function":"zero_g","verdict":"AGREES(256)"}], + "tests/stages/kuna-restart-warnings.xml": [{"function":"sub_4009bc","verdict":"DIFFERS(unassigned)"}], + "tests/stages/kuna-restartproto.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick_off","verdict":"AGREES(256)"}], + "tests/stages/kuna-restarts.xml": [{"function":"switchmulti","verdict":"AGREES(256)"},{"function":"norestart","verdict":"AGREES(256)"}], + "tests/stages/kuna-retcallhalf.xml": [{"function":"full_or","verdict":"AGREES(256)"},{"function":"full_add","verdict":"AGREES(256)"},{"function":"hi_const","verdict":"AGREES(256)"},{"function":"sext","verdict":"AGREES(256)"},{"function":"lo_or","verdict":"AGREES(256)"},{"function":"vdiv","verdict":"AGREES(256)"},{"function":"keepz","verdict":"AGREES(256)"},{"function":"popd","verdict":"AGREES(256)"},{"function":"sysafter","verdict":"AGREES(256)"}], + "tests/stages/kuna-retcopyclone.xml": [{"function":"audit_pair","verdict":"AGREES(256)"},{"function":"audit_select","verdict":"AGREES(256)"},{"function":"audit_retry","verdict":"AGREES(256)"},{"function":"audit_select","verdict":"AGREES(256)"},{"function":"audit_retry","verdict":"AGREES(256)"}], + "tests/stages/kuna-retinputhalf.xml": [{"function":"wide","verdict":"AGREES(256)"},{"function":"w2","verdict":"AGREES(256)"}], + "tests/stages/kuna-retpairhalf.xml": [{"function":"sx","verdict":"AGREES(256)"},{"function":"zx","verdict":"AGREES(256)"},{"function":"sxa","verdict":"AGREES(256)"},{"function":"kc","verdict":"AGREES(256)"},{"function":"dupc","verdict":"AGREES(256)"},{"function":"sxsel","verdict":"AGREES(256)"},{"function":"kc0","verdict":"AGREES(256)"},{"function":"div7","verdict":"AGREES(256)"},{"function":"sgnst","verdict":"AGREES(256)"},{"function":"scrub","verdict":"AGREES(256)"},{"function":"sysarg","verdict":"AGREES(256)"},{"function":"vmsrc","verdict":"AGREES(256)"},{"function":"msrc","verdict":"UNKNOWN(unsupported-op)"},{"function":"feedc","verdict":"AGREES(256)"}], + "tests/stages/kuna-retpushedhalf.xml": [{"function":"same_reg_restore","verdict":"AGREES(256)"},{"function":"cross_reg_restore","verdict":"AGREES(256)"},{"function":"dead_rdx_write","verdict":"AGREES(256)"}], + "tests/stages/kuna-retshape-arms.xml": [{"function":"describe","verdict":"AGREES(256)"},{"function":"wrap_add","verdict":"AGREES(256)"},{"function":"describe","verdict":"AGREES(256)"}], + "tests/stages/kuna-retshape-guards.xml": [{"function":"mutable_ptr","verdict":"AGREES(256)"},{"function":"settle","verdict":"AGREES(256)"},{"function":"mutable_ptr","verdict":"AGREES(256)"}], + "tests/stages/kuna-retsplitglobal.xml": [{"function":"alphabet_init","verdict":"UNKNOWN(unsupported-op)"},{"function":"alphabet_init","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-retsplitlimit.xml": [{"function":"cached","verdict":"AGREES(256)"},{"function":"cached","verdict":"AGREES(256)"},{"function":"cached","verdict":"AGREES(256)"}], + "tests/stages/kuna-retsysreg-a64.xml": [{"function":"pmr","verdict":"UNKNOWN(unsupported-op)"},{"function":"fpcr","verdict":"UNKNOWN(unsupported-op)"},{"function":"daif","verdict":"UNKNOWN(unsupported-op)"},{"function":"two","verdict":"UNKNOWN(unsupported-op)"},{"function":"i128","verdict":"UNKNOWN(unsupported-op)"},{"function":"cvau","verdict":"UNKNOWN(unsupported-op)"},{"function":"civac","verdict":"UNKNOWN(unsupported-op)"},{"function":"tlbi","verdict":"UNKNOWN(unsupported-op)"},{"function":"ic","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-retsysreg-mips.xml": [{"function":"pk","verdict":"UNKNOWN(unsupported-op)"},{"function":"pkw","verdict":"UNKNOWN(unsupported-op)"},{"function":"cch","verdict":"UNKNOWN(unsupported-op)"},{"function":"syn","verdict":"AGREES(256)"},{"function":"cop2","verdict":"UNKNOWN(unsupported-op)"},{"function":"st","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-retsysreg.xml": [{"function":"keepc","verdict":"AGREES(256)"},{"function":"comp","verdict":"AGREES(256)"},{"function":"compm","verdict":"UNKNOWN(unsupported-op)"},{"function":"callhi","verdict":"AGREES(256)"},{"function":"mcrr_ret","verdict":"UNKNOWN(unsupported-op)"},{"function":"keepc_t","verdict":"AGREES(256)"},{"function":"raise_bp","verdict":"AGREES(256)"},{"function":"lock_prim","verdict":"AGREES(256)"},{"function":"pk","verdict":"UNKNOWN(unsupported-op)"},{"function":"pk_t","verdict":"UNKNOWN(unsupported-op)"},{"function":"cln","verdict":"UNKNOWN(unsupported-op)"},{"function":"inv","verdict":"UNKNOWN(unsupported-op)"},{"function":"pli","verdict":"UNKNOWN(unsupported-op)"},{"function":"ctlk","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-rettriangle.xml": [{"function":"finish","verdict":"AGREES(256)"},{"function":"check_name","verdict":"AGREES(256)"},{"function":"guard_first","verdict":"AGREES(256)"},{"function":"two_way","verdict":"AGREES(256)"},{"function":"finish","verdict":"AGREES(256)"},{"function":"check_name","verdict":"AGREES(256)"},{"function":"guard_first","verdict":"AGREES(256)"},{"function":"two_way","verdict":"AGREES(256)"}], + "tests/stages/kuna-returnbranch.xml": [{"function":"bounce","verdict":"UNKNOWN(unsupported-op)"},{"function":"bounce_leading_nop","verdict":"UNKNOWN(unsupported-op)"},{"function":"bounce","verdict":"AGREES(256)"},{"function":"bounce_leading_nop","verdict":"AGREES(256)"}], + "tests/stages/kuna-returndup-auto.xml": [{"function":"guard","verdict":"AGREES(256)"},{"function":"wrapped","verdict":"AGREES(256)"},{"function":"vguard","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"guard","verdict":"AGREES(256)"},{"function":"vguard","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-returndup-switch-default.xml": [{"function":"swret","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-returndupcalls.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick3","verdict":"AGREES(256)"},{"function":"pick","verdict":"DIFFERS(call at 0x401022 to 0x401000)"},{"function":"pick3","verdict":"DIFFERS(call at 0x401052 to 0x401000)"}], + "tests/stages/kuna-returnglobal-sparc.xml": [{"function":"leftover","verdict":"AGREES(256)"},{"function":"dirty","verdict":"AGREES(256)"}], + "tests/stages/kuna-returnhintcaller.xml": [{"function":"add_default","verdict":"AGREES(256)"},{"function":"add_node","verdict":"AGREES(256)"},{"function":"add_sub","verdict":"AGREES(256)"},{"function":"add_default","verdict":"AGREES(256)"},{"function":"add_node","verdict":"AGREES(256)"},{"function":"add_sub","verdict":"AGREES(256)"},{"function":"add_default","verdict":"AGREES(256)"},{"function":"add_node","verdict":"AGREES(256)"},{"function":"add_default","verdict":"AGREES(256)"},{"function":"add_node","verdict":"AGREES(256)"},{"function":"add_sub","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"}], + "tests/stages/kuna-returnpiece.xml": [{"function":"join_lo_hi","verdict":"AGREES(256)"},{"function":"join_third","verdict":"AGREES(256)"},{"function":"join_sixth","verdict":"AGREES(256)"},{"function":"join_signed","verdict":"AGREES(256)"},{"function":"join_hi_sum","verdict":"AGREES(256)"},{"function":"join_lo_sum","verdict":"AGREES(256)"},{"function":"join_hi_lo","verdict":"AGREES(256)"},{"function":"join_hi_sum_o2","verdict":"AGREES(256)"}], + "tests/stages/kuna-retvalue.xml": [{"function":"make_cell","verdict":"AGREES(256)"},{"function":"skip_blanks","verdict":"AGREES(256)"},{"function":"lookup","verdict":"AGREES(256)"},{"function":"reset","verdict":"AGREES(256)"},{"function":"push_cell","verdict":"AGREES(256)"}], + "tests/stages/kuna-revisitrefine.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-rex-before-prefix.xml": [{"function":"rex_stos","verdict":"AGREES(13)"},{"function":"rex_stos16","verdict":"UNKNOWN(budget)"},{"function":"rex_movs","verdict":"AGREES(13)"},{"function":"rex_load","verdict":"AGREES(256)"},{"function":"rex_cmps","verdict":"AGREES(256)"}], + "tests/stages/kuna-riscv-narrow-float-struct.xml": [{"function":"put_ld","verdict":"AGREES(256)"},{"function":"put_fi","verdict":"AGREES(256)"},{"function":"put_ld","verdict":"AGREES(256)"},{"function":"put_ld","verdict":"AGREES(256)"},{"function":"put_fi","verdict":"AGREES(256)"}], + "tests/stages/kuna-riscv-zcmp.xml": [{"function":"keep","verdict":"AGREES(256)"},{"function":"swapcall","verdict":"AGREES(256)"},{"function":"zret","verdict":"AGREES(256)"},{"function":"popsep","verdict":"AGREES(256)"}], + "tests/stages/kuna-riscv32-int-float-struct.xml": [{"function":"take_id","verdict":"AGREES(256)"},{"function":"ret_id","verdict":"AGREES(256)"},{"function":"call_id","verdict":"AGREES(256)"}], + "tests/stages/kuna-riscv64-int-float-struct.xml": [{"function":"take_ld","verdict":"AGREES(256)"},{"function":"take_fi","verdict":"AGREES(256)"},{"function":"take_fd","verdict":"AGREES(256)"},{"function":"take_ld_late","verdict":"AGREES(256)"},{"function":"ret_ld","verdict":"AGREES(256)"},{"function":"call_ld","verdict":"AGREES(256)"}], + "tests/stages/kuna-rodatastring.xml": [{"function":"f","verdict":"UNKNOWN(unsupported-op)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-rust-option-niche.xml": [{"function":"named_some","verdict":"AGREES(256)"},{"function":"named_none","verdict":"AGREES(256)"},{"function":"named_payload","verdict":"AGREES(256)"},{"function":"returned_some","verdict":"AGREES(256)"},{"function":"raw_null","verdict":"AGREES(256)"},{"function":"named_some","verdict":"AGREES(256)"}], + "tests/stages/kuna-rust-option-returned.xml": [{"function":"inspect_returned","verdict":"AGREES(256)"}], + "tests/stages/kuna-rust-process-exit.xml": [{"function":"exit_choice","verdict":"AGREES(249)"},{"function":"returning_names","verdict":"AGREES(251)"},{"function":"exit_choice","verdict":"AGREES(249)"},{"function":"returning_names","verdict":"AGREES(251)"}], + "tests/stages/kuna-rust-switch-labels.xml": [{"function":"signed8","verdict":"AGREES(256)"},{"function":"signed16","verdict":"AGREES(256)"},{"function":"signed32","verdict":"AGREES(256)"},{"function":"signed64","verdict":"AGREES(256)"},{"function":"unsigned8","verdict":"AGREES(256)"},{"function":"unsigned16","verdict":"AGREES(256)"},{"function":"unsigned32","verdict":"AGREES(256)"},{"function":"unsigned64","verdict":"AGREES(256)"},{"function":"signed16_load","verdict":"AGREES(256)"},{"function":"signed16_widen","verdict":"AGREES(256)"},{"function":"text8","verdict":"AGREES(256)"},{"function":"text8","verdict":"AGREES(256)"}], + "tests/stages/kuna-rustabi.xml": [{"function":"prod","verdict":"AGREES(256)"},{"function":"cons","verdict":"AGREES(256)"},{"function":"pair_shaped_reader","verdict":"DIFFERS(unassigned)"},{"function":"prod","verdict":"AGREES(256)"},{"function":"cons","verdict":"AGREES(256)"},{"function":"pair_shaped_reader","verdict":"DIFFERS(unassigned)"}], + "tests/stages/kuna-rustversion-commit.xml": [{"function":"decimal_lf","verdict":"AGREES(256)"},{"function":"reorder","verdict":"AGREES(256)"}], + "tests/stages/kuna-saved-register-lanes-sysv.xml": [{"function":"fixture_sysv_observed_lane","verdict":"AGREES(256)"}], + "tests/stages/kuna-saved-register-lanes-win64.xml": [{"function":"fixture_spills_rect","verdict":"AGREES(256)"},{"function":"fixture_observed_lane","verdict":"AGREES(256)"}], + "tests/stages/kuna-scalar-stack-pointer.xml": [{"function":"project_unsigned","verdict":"AGREES(256)"},{"function":"project_signed","verdict":"AGREES(256)"},{"function":"ordinary","verdict":"AGREES(256)"},{"function":"ordinary","verdict":"AGREES(256)"}], + "tests/stages/kuna-sdivpow2-thumb.xml": [{"function":"itdiv8","verdict":"AGREES(256)"},{"function":"brdiv4096","verdict":"AGREES(256)"}], + "tests/stages/kuna-sdivpow2.xml": [{"function":"div8","verdict":"AGREES(256)"},{"function":"div1024","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"round8","verdict":"AGREES(256)"},{"function":"hibyte","verdict":"AGREES(256)"},{"function":"notdiv","verdict":"AGREES(256)"}], + "tests/stages/kuna-segmentize-z80.xml": [{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-segmentize.xml": [{"function":"addtwo","verdict":"UNKNOWN(unsupported-op)"},{"function":"video","verdict":"UNKNOWN(unsupported-op)"},{"function":"farsum","verdict":"UNKNOWN(unsupported-op)"},{"function":"pick","verdict":"UNKNOWN(unsupported-op)"},{"function":"farlong","verdict":"UNKNOWN(unsupported-op)"},{"function":"pickfar","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-selectarith.xml": [{"function":"set_name","verdict":"AGREES(256)"},{"function":"set_mode","verdict":"AGREES(256)"},{"function":"width","verdict":"AGREES(256)"},{"function":"below","verdict":"AGREES(256)"},{"function":"two_flags","verdict":"AGREES(256)"},{"function":"set_name","verdict":"AGREES(256)"},{"function":"set_mode","verdict":"AGREES(256)"},{"function":"width","verdict":"AGREES(256)"},{"function":"w_eqc","verdict":"AGREES(256)"}], + "tests/stages/kuna-sharedpush-regparm.xml": [{"function":"sub_401060","verdict":"AGREES(256)"},{"function":"sub_401040","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_4010f0","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sharedpush.xml": [{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401040","verdict":"AGREES(256)"},{"function":"sub_401080","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_4010a0","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_401100","verdict":"AGREES(256)"},{"function":"sub_401120","verdict":"AGREES(256)"}], + "tests/stages/kuna-short-ascii-string.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"main","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-short-utf16-window.xml": [{"function":"entry","verdict":"AGREES(256)"}], + "tests/stages/kuna-signed-float-trunc.xml": [{"function":"unsigned_join","verdict":"AGREES(256)"},{"function":"signed_join","verdict":"AGREES(256)"}], + "tests/stages/kuna-signed-float-trunc64.xml": [{"function":"merged64","verdict":"AGREES(256)"},{"function":"widened","verdict":"AGREES(256)"}], + "tests/stages/kuna-signed-stack-index.xml": [{"function":"signed_stack_index","verdict":"AGREES(256)"}], + "tests/stages/kuna-signedness-int16.xml": [{"function":"f","verdict":"UNKNOWN(unsupported-op)"},{"function":"f","verdict":"UNKNOWN(unsupported-op)"},{"function":"g","verdict":"UNKNOWN(unsupported-op)"},{"function":"g","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-signedness.xml": [{"function":"f","verdict":"UNKNOWN(budget)"},{"function":"f","verdict":"UNKNOWN(budget)"},{"function":"g","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-signedread-a64.xml": [{"function":"__sigismember","verdict":"AGREES(256)"}], + "tests/stages/kuna-signedread.xml": [{"function":"bitmask","verdict":"AGREES(256)"},{"function":"sigmember","verdict":"AGREES(256)"},{"function":"sshift","verdict":"AGREES(256)"},{"function":"sless","verdict":"AGREES(256)"},{"function":"sdiv","verdict":"AGREES(256)"},{"function":"ucmp","verdict":"AGREES(256)"}], + "tests/stages/kuna-simdlane.xml": [{"function":"alphabet_init","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-slotdeindirect.xml": [{"function":"sub_140001000","verdict":"AGREES(256)"},{"function":"sub_140001050","verdict":"AGREES(256)"},{"function":"sub_1400010b0","verdict":"AGREES(256)"},{"function":"sub_401000","verdict":"AGREES(256)"},{"function":"sub_401040","verdict":"AGREES(81)"},{"function":"sub_401070","verdict":"AGREES(256)"},{"function":"sub_4010b0","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sparc-call-continuation.xml": [], + "tests/stages/kuna-sparc-callreturn.xml": [{"function":"f1","verdict":"AGREES(256)"},{"function":"f4","verdict":"AGREES(256)"},{"function":"f5","verdict":"AGREES(256)"},{"function":"f6","verdict":"AGREES(256)"},{"function":"fl","verdict":"AGREES(254)"},{"function":"widen","verdict":"AGREES(256)"},{"function":"g0","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-delay-condition.xml": [{"function":"clear_if_both","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-delay-tail-call.xml": [{"function":"forward","verdict":"AGREES(256)"},{"function":"ordinary","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-double-abs.xml": [{"function":"absolute_double32","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-double-alignment.xml": [{"function":"double_field","verdict":"AGREES(256)"},{"function":"eighth_double","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-double-sign.xml": [{"function":"negate_double","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-external-tail.xml": [{"function":"external_tail","verdict":"UNKNOWN(unsupported-op)"},{"function":"external_tail","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc-fdtoi.xml": [{"function":"fdtoi_word","verdict":"AGREES(256)"},{"function":"carrier_conversion","verdict":"AGREES(252)"}], + "tests/stages/kuna-sparc-register-pair.xml": [{"function":"pair_loop","verdict":"AGREES(75)"}], + "tests/stages/kuna-sparc-structret-marker.xml": [{"function":"aggregate_marker","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sparc-trap-resume.xml": [{"function":"trap_in_delay","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sparc-zeropair.xml": [{"function":"keep_zero","verdict":"AGREES(252)"},{"function":"same","verdict":"AGREES(256)"},{"function":"flag_zero","verdict":"AGREES(252)"},{"function":"keep_five","verdict":"AGREES(252)"},{"function":"ll_const","verdict":"AGREES(256)"},{"function":"ull_arg","verdict":"AGREES(256)"},{"function":"ll_mul","verdict":"AGREES(256)"},{"function":"keep_zero_O0","verdict":"AGREES(252)"},{"function":"flag_zero_O0","verdict":"AGREES(252)"},{"function":"ull_arg_O0","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc32-call-gap.xml": [], + "tests/stages/kuna-sparc64-callreturn.xml": [{"function":"f1","verdict":"AGREES(256)"},{"function":"f2","verdict":"AGREES(256)"},{"function":"f3","verdict":"AGREES(256)"},{"function":"fd","verdict":"AGREES(251)"},{"function":"f1_O0","verdict":"AGREES(256)"},{"function":"f2_O0","verdict":"AGREES(256)"},{"function":"f3_O0","verdict":"AGREES(256)"},{"function":"fd_O0","verdict":"AGREES(251)"}], + "tests/stages/kuna-sparc64-double-abs.xml": [{"function":"absolute_double64","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc64-double-sign.xml": [{"function":"negate_double64","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc64-fdtoi.xml": [{"function":"fdtoi64","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc64-hiddenret-slot-locals.xml": [{"function":"delim","verdict":"AGREES(256)"},{"function":"fill_raw","verdict":"AGREES(256)"}], + "tests/stages/kuna-sparc64-large-frame.xml": [], + "tests/stages/kuna-sparc64-or-masked-spill.xml": [{"function":"flag","verdict":"AGREES(256)"}], + "tests/stages/kuna-spillptr-loadguard.xml": [{"function":"f_spill","verdict":"AGREES(256)"},{"function":"f_direct","verdict":"AGREES(256)"},{"function":"f_param","verdict":"UNKNOWN(uninitialized-local)"},{"function":"vsum","verdict":"AGREES(103)"}], + "tests/stages/kuna-splitstorekeep.xml": [{"function":"copy31","verdict":"AGREES(256)"},{"function":"copy32","verdict":"AGREES(256)"}], + "tests/stages/kuna-stack-address-argument.xml": [{"function":"widen_value","verdict":"AGREES(256)"},{"function":"widen_value","verdict":"AGREES(256)"}], + "tests/stages/kuna-stack-address-word.xml": [{"function":"conditional_word","verdict":"AGREES(256)"},{"function":"conditional_word","verdict":"AGREES(256)"}], + "tests/stages/kuna-stack-byte-copy.xml": [{"function":"PushedByteBranchesSeed","verdict":"AGREES(256)"},{"function":"PushedByteSnapshot","verdict":"AGREES(256)"},{"function":"PushedByteBranchesSeed","verdict":"AGREES(256)"}], + "tests/stages/kuna-stack-float-snapshot.xml": [{"function":"flip_first_and_add","verdict":"AGREES(256)"},{"function":"flip_second_and_add","verdict":"AGREES(256)"},{"function":"flip_first_and_add","verdict":"AGREES(256)"},{"function":"flip_second_and_add","verdict":"AGREES(256)"},{"function":"integer_to_float","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackarggap.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackchklocal.xml": [{"function":"r6","verdict":"AGREES(256)"},{"function":"r6","verdict":"AGREES(4)"},{"function":"r6","verdict":"AGREES(256)"},{"function":"r6","verdict":"AGREES(4)"},{"function":"r6","verdict":"AGREES(256)"},{"function":"r6","verdict":"AGREES(256)"},{"function":"r6","verdict":"AGREES(256)"},{"function":"r6","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackcookie.xml": [{"function":"gsseh","verdict":"AGREES(256)"},{"function":"gsthis","verdict":"AGREES(256)"},{"function":"gsebp","verdict":"AGREES(256)"},{"function":"keyarg","verdict":"AGREES(256)"},{"function":"keyread","verdict":"AGREES(256)"},{"function":"copyarg","verdict":"AGREES(256)"},{"function":"sehkey","verdict":"AGREES(256)"},{"function":"sehebp","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackguard-tailcall.xml": [{"function":"t2","verdict":"AGREES(256)"},{"function":"t3","verdict":"AGREES(256)"},{"function":"k2","verdict":"AGREES(256)"},{"function":"w3","verdict":"AGREES(256)"},{"function":"t2s","verdict":"AGREES(256)"},{"function":"h6","verdict":"AGREES(256)"},{"function":"h7","verdict":"AGREES(256)"},{"function":"t2","verdict":"AGREES(256)"},{"function":"t3","verdict":"AGREES(256)"},{"function":"k2","verdict":"AGREES(256)"},{"function":"w3","verdict":"AGREES(256)"},{"function":"t2s","verdict":"AGREES(256)"},{"function":"h6","verdict":"AGREES(256)"},{"function":"h7","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-callee-x86.xml": [{"function":"overwrite_after_stack_read","verdict":"AGREES(256)"},{"function":"overwrite_after_stack_read","verdict":"AGREES(256)"},{"function":"overwrite_after_stack_hidden","verdict":"AGREES(256)"},{"function":"read_after_stack_write","verdict":"AGREES(256)"},{"function":"returned_pointer_read_before_overwrite","verdict":"AGREES(256)"},{"function":"returned_pointer_read_after_overwrite","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-callee-x86_64.xml": [{"function":"overwrite_after_stack_read","verdict":"AGREES(256)"},{"function":"overwrite_after_stack_read","verdict":"AGREES(256)"},{"function":"overwrite_after_stack_hidden","verdict":"AGREES(256)"},{"function":"read_after_stack_write","verdict":"AGREES(256)"},{"function":"returned_pointer_read_before_overwrite","verdict":"AGREES(256)"},{"function":"returned_pointer_read_after_overwrite","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-callee.xml": [{"function":"overwrite_after_read_second","verdict":"AGREES(256)"},{"function":"overwrite_after_read_second","verdict":"AGREES(256)"},{"function":"overwrite_after_no_memory","verdict":"AGREES(256)"},{"function":"overwrite_after_hidden_read","verdict":"AGREES(256)"},{"function":"overwrite_after_branch_read","verdict":"AGREES(256)"},{"function":"overwrite_after_const_write","verdict":"AGREES(256)"},{"function":"read_after_const_write","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-cfg.xml": [{"function":"one_path_overwrites","verdict":"AGREES(256)"},{"function":"all_paths_overwrite","verdict":"AGREES(256)"},{"function":"one_path_overwrites","verdict":"AGREES(256)"},{"function":"loop_overwrites","verdict":"AGREES(103)"},{"function":"loop_may_skip","verdict":"AGREES(103)"},{"function":"xor_view","verdict":"AGREES(256)"},{"function":"xor_view","verdict":"AGREES(256)"},{"function":"double_bits","verdict":"AGREES(256)"},{"function":"constant_bits","verdict":"AGREES(256)"},{"function":"effect_bits","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-index.xml": [{"function":"bounded_index_store","verdict":"AGREES(256)"},{"function":"bounded_index_store","verdict":"AGREES(256)"},{"function":"bounded_index_load","verdict":"AGREES(256)"},{"function":"bounded_byte_store","verdict":"AGREES(256)"},{"function":"bounded_reverse_store","verdict":"AGREES(256)"},{"function":"unbounded_index_store","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacklifetimes-partial.xml": [{"function":"rgb_reuse","verdict":"AGREES(256)"},{"function":"rgb_reuse","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackobjects.xml": [{"function":"obj_repeat","verdict":"AGREES(256)"},{"function":"obj_repeat","verdict":"AGREES(256)"},{"function":"obj_reuse","verdict":"AGREES(256)"},{"function":"obj_branch","verdict":"AGREES(256)"},{"function":"obj_loop","verdict":"AGREES(256)"},{"function":"obj_partial","verdict":"AGREES(256)"},{"function":"obj_reuse","verdict":"AGREES(256)"},{"function":"obj_reuse","verdict":"AGREES(256)"},{"function":"obj_reuse","verdict":"AGREES(256)"},{"function":"obj_reuse","verdict":"AGREES(256)"},{"function":"obj_repeat","verdict":"AGREES(256)"},{"function":"obj_repeat","verdict":"AGREES(256)"},{"function":"param_reuse","verdict":"AGREES(256)"},{"function":"param_reuse","verdict":"AGREES(256)"},{"function":"param_reuse","verdict":"AGREES(256)"},{"function":"param_reuse","verdict":"AGREES(256)"},{"function":"param_incoming","verdict":"AGREES(256)"},{"function":"param_pair","verdict":"AGREES(256)"},{"function":"param_incoming","verdict":"AGREES(256)"},{"function":"param_incoming","verdict":"AGREES(256)"},{"function":"param_incoming","verdict":"AGREES(256)"},{"function":"param_mutation","verdict":"AGREES(256)"},{"function":"param_escaped","verdict":"AGREES(256)"},{"function":"param_escaped","verdict":"AGREES(256)"},{"function":"param_scalar_escaped","verdict":"AGREES(256)"},{"function":"param_equal_float","verdict":"AGREES(256)"},{"function":"param_scalar_escaped","verdict":"AGREES(256)"},{"function":"param_equal_float","verdict":"AGREES(256)"},{"function":"param_multiple","verdict":"AGREES(256)"},{"function":"param_multiple_interior","verdict":"AGREES(256)"},{"function":"param_word_partial","verdict":"AGREES(256)"},{"function":"param_multiple_interior","verdict":"AGREES(256)"},{"function":"param_multiple_interior","verdict":"AGREES(256)"},{"function":"param_scalar_escaped","verdict":"AGREES(256)"},{"function":"param_scalar_escaped","verdict":"AGREES(256)"},{"function":"param_scalar_escaped","verdict":"AGREES(256)"},{"function":"parameter_dynamic_reuse","verdict":"AGREES(256)"},{"function":"parameter_dynamic_reuse","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackpointerfields.xml": [{"function":"group_fields","verdict":"AGREES(256)"},{"function":"group_fields","verdict":"AGREES(256)"},{"function":"group_fields","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackpointerretype.xml": [{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"},{"function":"probe","verdict":"AGREES(256)"}], + "tests/stages/kuna-stacksolver-unsolved.xml": [{"function":"f","verdict":"UNKNOWN(unsupported-op)"},{"function":"h","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-stackstoreguard.xml": [{"function":"inspect_bytes","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackstruct.xml": [{"function":"header_gcc_o0","verdict":"AGREES(256)"},{"function":"word_sum_gcc_o0","verdict":"AGREES(256)"},{"function":"text_len_gcc_o0","verdict":"AGREES(256)"},{"function":"header_gcc_o2","verdict":"AGREES(256)"},{"function":"word_sum_gcc_o2","verdict":"AGREES(256)"},{"function":"text_len_gcc_o2","verdict":"AGREES(256)"},{"function":"header_clang_o0","verdict":"AGREES(256)"},{"function":"word_sum_clang_o0","verdict":"AGREES(256)"},{"function":"text_len_clang_o0","verdict":"AGREES(256)"},{"function":"header_clang_o2","verdict":"AGREES(256)"},{"function":"word_sum_clang_o2","verdict":"AGREES(256)"},{"function":"text_len_clang_o2","verdict":"AGREES(256)"},{"function":"header_gcc_o0","verdict":"AGREES(256)"},{"function":"header_gcc_o2","verdict":"AGREES(256)"},{"function":"header_gcc_o0","verdict":"AGREES(256)"},{"function":"word_sum_gcc_o0","verdict":"AGREES(256)"},{"function":"text_len_gcc_o0","verdict":"AGREES(256)"},{"function":"header_gcc_o2","verdict":"AGREES(256)"},{"function":"word_sum_gcc_o2","verdict":"AGREES(256)"},{"function":"text_len_gcc_o2","verdict":"AGREES(256)"},{"function":"header_clang_o0","verdict":"AGREES(256)"},{"function":"word_sum_clang_o0","verdict":"AGREES(256)"},{"function":"text_len_clang_o0","verdict":"AGREES(256)"},{"function":"header_clang_o2","verdict":"AGREES(256)"},{"function":"word_sum_clang_o2","verdict":"AGREES(256)"},{"function":"text_len_clang_o2","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackversions.xml": [{"function":"frame_alias","verdict":"UNKNOWN(budget)"},{"function":"frame_alias","verdict":"UNKNOWN(budget)"},{"function":"frame_seed","verdict":"UNKNOWN(budget)"},{"function":"frame_cached","verdict":"AGREES(256)"}], + "tests/stages/kuna-stackviews.xml": [{"function":"stack_reuse","verdict":"AGREES(256)"},{"function":"stack_reuse","verdict":"AGREES(256)"},{"function":"override_reuse","verdict":"AGREES(256)"},{"function":"override_reuse","verdict":"AGREES(256)"},{"function":"stack_reuse","verdict":"AGREES(256)"},{"function":"stack_reuse","verdict":"AGREES(256)"},{"function":"obj_global_reuse","verdict":"AGREES(256)"},{"function":"obj_volatile_reuse","verdict":"UNKNOWN(unsupported-op)"},{"function":"obj_global_reuse","verdict":"AGREES(256)"},{"function":"obj_volatile_reuse","verdict":"UNKNOWN(unsupported-op)"},{"function":"cached_stack_word","verdict":"AGREES(256)"},{"function":"publish_frame_word","verdict":"AGREES(256)"}], + "tests/stages/kuna-stated-jump-owners.xml": [{"function":"split","verdict":"UNKNOWN(unsupported-op)"},{"function":"owners::split","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_401040","verdict":"AGREES(256)"},{"function":"declared","verdict":"UNKNOWN(unsupported-op)"},{"function":"dispatch","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-stated-jump-placement.xml": [{"function":"near_jump","verdict":"UNKNOWN(unsupported-op)"},{"function":"far_jump","verdict":"UNKNOWN(unsupported-op)"},{"function":"far_low","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_10000","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-stated-jump.xml": [{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"UNKNOWN(unsupported-op)"},{"function":"dispatch","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-storealias.xml": [{"function":"s_param","verdict":"AGREES(256)"},{"function":"s_const","verdict":"AGREES(256)"},{"function":"s_once","verdict":"AGREES(256)"},{"function":"l_keep","verdict":"AGREES(256)"},{"function":"l_twice","verdict":"AGREES(256)"},{"function":"w_order","verdict":"AGREES(256)"},{"function":"r_order","verdict":"AGREES(256)"},{"function":"w_inc","verdict":"AGREES(256)"},{"function":"r_cond","verdict":"AGREES(256)"},{"function":"r_two","verdict":"AGREES(256)"},{"function":"e_call","verdict":"AGREES(256)"},{"function":"e_reg","verdict":"AGREES(256)"},{"function":"w_dead","verdict":"AGREES(256)"},{"function":"w_dead2","verdict":"AGREES(256)"},{"function":"s_param","verdict":"AGREES(256)"},{"function":"s_const","verdict":"AGREES(256)"},{"function":"s_once","verdict":"AGREES(256)"},{"function":"l_keep","verdict":"AGREES(256)"},{"function":"l_twice","verdict":"AGREES(256)"},{"function":"w_order","verdict":"AGREES(256)"},{"function":"r_order","verdict":"AGREES(256)"},{"function":"w_inc","verdict":"AGREES(256)"},{"function":"r_cond","verdict":"AGREES(256)"},{"function":"r_two","verdict":"AGREES(256)"},{"function":"e_call","verdict":"AGREES(256)"},{"function":"e_reg","verdict":"AGREES(256)"},{"function":"w_dead","verdict":"AGREES(256)"},{"function":"w_dead2","verdict":"AGREES(256)"},{"function":"r_loop","verdict":"AGREES(85)"},{"function":"w_epi","verdict":"AGREES(256)"},{"function":"w_big","verdict":"AGREES(256)"},{"function":"w_big2","verdict":"AGREES(256)"},{"function":"r_loop","verdict":"AGREES(85)"},{"function":"w_epi","verdict":"AGREES(256)"},{"function":"w_big","verdict":"AGREES(256)"},{"function":"w_big2","verdict":"AGREES(256)"}], + "tests/stages/kuna-storecopyeffects.xml": [{"function":"s7","verdict":"AGREES(256)"},{"function":"s_repeat","verdict":"AGREES(256)"},{"function":"s_read","verdict":"AGREES(256)"},{"function":"s_dead","verdict":"AGREES(256)"}], + "tests/stages/kuna-strlenscan.xml": [{"function":"name_len","verdict":"UNKNOWN(unsupported-op)"},{"function":"last_char","verdict":"UNKNOWN(unsupported-op)"},{"function":"weighted_len","verdict":"UNKNOWN(unsupported-op)"},{"function":"len_then_clear","verdict":"UNKNOWN(unsupported-op)"},{"function":"len_then_wipe","verdict":"UNKNOWN(unsupported-op)"},{"function":"add_slash","verdict":"UNKNOWN(unsupported-op)"},{"function":"len_join","verdict":"UNKNOWN(unsupported-op)"},{"function":"scan_slash","verdict":"UNKNOWN(budget)"},{"function":"raw_count","verdict":"AGREES(256)"},{"function":"name_len","verdict":"AGREES(256)"},{"function":"last_char","verdict":"AGREES(256)"},{"function":"weighted_len","verdict":"AGREES(256)"},{"function":"len_then_clear","verdict":"AGREES(256)"},{"function":"len_then_wipe","verdict":"AGREES(256)"},{"function":"add_slash","verdict":"AGREES(256)"},{"function":"len_join","verdict":"AGREES(256)"},{"function":"scan_slash","verdict":"UNKNOWN(budget)"},{"function":"raw_count","verdict":"AGREES(256)"}], + "tests/stages/kuna-structdefs.xml": [{"function":"readfields","verdict":"AGREES(256)"}], + "tests/stages/kuna-stubbinds.xml": [{"function":"_probe_stub","verdict":"AGREES(256)"},{"function":"sub_100000520","verdict":"AGREES(256)"},{"function":"_probe_stub","verdict":"UNKNOWN(unsupported-op)"},{"function":"__chkstk_darwin","verdict":"AGREES(256)"}], + "tests/stages/kuna-stubtailcall.xml": [{"function":"strcpy","verdict":"AGREES(256)"}], + "tests/stages/kuna-subcommuteshift.xml": [{"function":"cancel_byte_arithmetic","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sve-ld1w.xml": [{"function":"load_words","verdict":"UNKNOWN(unsupported-op)"},{"function":"load_before","verdict":"UNKNOWN(unsupported-op)"},{"function":"load_index","verdict":"UNKNOWN(unsupported-op)"},{"function":"store_broadcast","verdict":"UNKNOWN(unsupported-op)"},{"function":"merge_words","verdict":"UNKNOWN(unsupported-op)"},{"function":"gather_words","verdict":"UNKNOWN(unsupported-op)"},{"function":"broadcast_direct","verdict":"UNKNOWN(unsupported-op)"},{"function":"stack_words","verdict":"UNKNOWN(unsupported-op)"},{"function":"discard_load","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sve-scalar-counts.xml": [{"function":"byte_count","verdict":"UNKNOWN(unsupported-op)"},{"function":"half_count","verdict":"UNKNOWN(unsupported-op)"},{"function":"word_count","verdict":"UNKNOWN(unsupported-op)"},{"function":"double_count","verdict":"UNKNOWN(unsupported-op)"},{"function":"increment","verdict":"UNKNOWN(unsupported-op)"},{"function":"decrement","verdict":"UNKNOWN(unsupported-op)"},{"function":"offset_count","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-sve-whilelo.xml": [{"function":"any_word","verdict":"UNKNOWN(unsupported-op)"},{"function":"first_byte","verdict":"UNKNOWN(unsupported-op)"},{"function":"last_half","verdict":"UNKNOWN(unsupported-op)"},{"function":"carry_double","verdict":"UNKNOWN(unsupported-op)"},{"function":"overflow_clear","verdict":"UNKNOWN(unsupported-op)"},{"function":"store_choice","verdict":"UNKNOWN(unsupported-op)"},{"function":"store_pred","verdict":"UNKNOWN(unsupported-op)"},{"function":"empty_alias","verdict":"UNKNOWN(unsupported-op)"},{"function":"scalar_only","verdict":"AGREES(256)"}], + "tests/stages/kuna-sve-xor-three.xml": [{"function":"mix","verdict":"UNKNOWN(unsupported-op)"},{"function":"cancel","verdict":"UNKNOWN(unsupported-op)"},{"function":"reserved","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-swiftcall.xml": [{"function":"callfix.Account.vtable#7.method","verdict":"UNKNOWN(unsupported-op)"},{"function":".requirement#1","verdict":"AGREES(256)"},{"function":"sub_3490","verdict":"UNKNOWN(unsupported-op)"},{"function":"callfix.Account.vtable#7.method","verdict":"UNKNOWN(unsupported-op)"},{"function":".requirement#1","verdict":"AGREES(256)"},{"function":".requirement#1","verdict":"AGREES(256)"},{"function":"sub_3490","verdict":"UNKNOWN(unsupported-op)"},{"function":"callfix.Counter.advance(by:times:)","verdict":"UNKNOWN(unsupported-op)"},{"function":"callfix.run(_:_:_:)","verdict":"UNKNOWN(unsupported-op)"},{"function":"callfix.Account.settle(_:)","verdict":"AGREES(256)"},{"function":"callfix.Account.settle(_:)","verdict":"AGREES(256)"},{"function":"helperfix.once(_:_:)","verdict":"AGREES(256)"},{"function":"helperfix.loop(_:_:_:)","verdict":"UNKNOWN(unsupported-op)"},{"function":"helperfix.once(_:_:)","verdict":"AGREES(256)"},{"function":"helperfix.loop(_:_:_:)","verdict":"UNKNOWN(unsupported-op)"},{"function":"sub_10dc","verdict":"AGREES(256)"},{"function":"sub_10fe","verdict":"AGREES(256)"},{"function":".requirement#0","verdict":"AGREES(256)"},{"function":"leaffix.once(_:_:)","verdict":"AGREES(256)"},{"function":"freefix.once(_:_:)","verdict":"AGREES(256)"},{"function":"sub_2836","verdict":"DIFFERS(unassigned)"},{"function":"sub_2874","verdict":"AGREES(256)"}], + "tests/stages/kuna-swiftdemangle.xml": [{"function":"main.countWords(of:)","verdict":"AGREES(256)"},{"function":"-[main.Greeter greet:]","verdict":"AGREES(256)"}], + "tests/stages/kuna-swifthelpers.xml": [{"function":"hf.useBox(_:)","verdict":"AGREES(256)"},{"function":"hf.pair(_:)","verdict":"AGREES(256)"},{"function":"hf.useBox(_:)","verdict":"AGREES(256)"},{"function":":hf.Shape>.lazy_protocol_witness_table_accessor","verdict":"AGREES(256)"},{"function":"hf.pair(_:)","verdict":"AGREES(256)"},{"function":"hf.wrap(_:)","verdict":"DIFFERS(memory before call 6 to 0x40)"}], + "tests/stages/kuna-swifticf.xml": [{"function":"sub_27f0","verdict":"AGREES(256)"},{"function":"sub_2ab0","verdict":"AGREES(256)"},{"function":"<*:icffix.Tagged>.requirement#0","verdict":"AGREES(256)"},{"function":".requirement#0.merged#2","verdict":"UNKNOWN(callee-replay)"},{"function":".requirement#0","verdict":"AGREES(256)"}], + "tests/stages/kuna-swiftmetadata.xml": [{"function":"sub_30b0","verdict":"AGREES(256)"},{"function":"sub_2fe0","verdict":"AGREES(256)"},{"function":"sub_2ab0","verdict":"AGREES(256)"},{"function":"metafix.Point.type_metadata_accessor","verdict":"AGREES(256)"},{"function":"metafix.Animal.vtable#4.method","verdict":"AGREES(256)"},{"function":".hash(into:)","verdict":"AGREES(256)"}], + "tests/stages/kuna-swiftstrobj.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"level","verdict":"AGREES(256)"},{"function":"ctl_join","verdict":"AGREES(256)"}], + "tests/stages/kuna-swifttypes.xml": [{"function":"typefix.Sprite.vtable#6.getter","verdict":"AGREES(256)"},{"function":"typefix.Point.type_metadata_accessor","verdict":"AGREES(256)"},{"function":"typefix.Sprite.vtable#6.getter","verdict":"AGREES(256)"},{"function":"typefix.Sprite.vtable#0.getter","verdict":"AGREES(256)"},{"function":"typefix.Point.type_metadata_accessor","verdict":"AGREES(256)"},{"function":".requirement#1","verdict":"AGREES(256)"}], + "tests/stages/kuna-switch-return-paths.xml": [{"function":"toggle_dispatch","verdict":"AGREES(256)"},{"function":"toggle_dispatch","verdict":"AGREES(256)"},{"function":"toggle_dispatch","verdict":"AGREES(256)"},{"function":"toggle_dispatch","verdict":"AGREES(256)"}], + "tests/stages/kuna-switcharmorder.xml": [{"function":"force_str","verdict":"AGREES(5)"},{"function":"enable","verdict":"AGREES(256)"},{"function":"enable","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchcond.xml": [{"function":"scan","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchextent-a64.xml": [{"function":"unchecked","verdict":"UNKNOWN(no switch row)"},{"function":"last","verdict":"AGREES(256)"},{"function":"entering","verdict":"AGREES(256)"},{"function":"unchecked","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchguardreload.xml": [{"function":"reloaded","verdict":"AGREES(256)"},{"function":"neighbour","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchmerge-split.xml": [{"function":"k","verdict":"AGREES(256)"},{"function":"m","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"},{"function":"m","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchmerge-values.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"p","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchmerge.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchnext-a64.xml": [{"function":"name_of","verdict":"UNKNOWN(no switch row)"},{"function":"name_of","verdict":"AGREES(256)"},{"function":"last_two","verdict":"UNKNOWN(no switch row)"},{"function":"disp","verdict":"UNKNOWN(no switch row)"}], + "tests/stages/kuna-switchnextcsel-a64.xml": [{"function":"name_of","verdict":"UNKNOWN(no switch row)"}], + "tests/stages/kuna-switchrunon.xml": [{"function":"pick","verdict":"DIVERGES(switchrunon-cut-row)"},{"function":"pick2","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchrunonguard.xml": [{"function":"pick","verdict":"DIVERGES(switchrunon-cut-row)"},{"function":"pick2","verdict":"DIVERGES(switchrunon-cut-row)"}], + "tests/stages/kuna-switchselector.xml": [{"function":"dlgproc","verdict":"AGREES(256)"},{"function":"dlgproc","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchselfloop.xml": [{"function":"self_loop","verdict":"AGREES(256)"},{"function":"self_loop_exit","verdict":"AGREES(256)"},{"function":"mixed_loop","verdict":"AGREES(256)"},{"function":"self_loop","verdict":"AGREES(256)"},{"function":"self_loop_exit","verdict":"AGREES(256)"},{"function":"mixed_loop","verdict":"AGREES(256)"},{"function":"direct_mixed","verdict":"AGREES(256)"},{"function":"hoist_dispatch","verdict":"UNKNOWN(budget)"}], + "tests/stages/kuna-switchsingle.xml": [{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/kuna-switchunrolledsense.xml": [{"function":"unrolled","verdict":"AGREES(256)"},{"function":"unrolled","verdict":"AGREES(256)"}], + "tests/stages/kuna-symbolnamebound.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"n0000::n0001::n0002::n0003::n0004::n0005::n0006::n0007::n0008::n0009::n0010::n0011::n0012::n0013::n0014::n0015::n0016::n0017::n0018::n0019::n0020::n0021::n0022::n0023::n0024::n0025::n0026::n0027::n0028::n0029::n0030::n0031::n0032::n0033::n0034::n0035::n0036::n0037::n0038::n0039::n0040::n0041::n0042::n0043::n0044::n0045::n0046::n0047::n0048::n0049::n0050::n0051::n0052::n0053::n0054::n0055::n0056::n0057::n0058::n0059::n0060::n0061::n0062::n0063::n0064::n0065::n0066::n0067::n0068::n0069::n0070::n0071::n0072::n0073::n0074::n0075::n0076::n0077::n0078::n0079::n0080::n0081::n0082::n0083::n0084::n0085::n0086::n0087::n0088::n0089::n0090::n0091::n0092::n0093::n0094::n0095::n0096::n0097::n0098::n0099::n0100::n0101::n0102::n0103::n0104::n0105::n0106::n0107::n0108::n0109::n0110::n0111::n0112::n0113::n0114::n0115::n0116::n0117::n0118::n0119::n0120::n0121::n0122::n0123::n0124::n0125::n0126::n0127::n0128::n0129::n0130::n0131::n0132::n0133::n0134::n0135::n0136::n0137::n0138::n0139::n0140::n0141::n0142::n0143::n0144::n0145::n0146::n0147::n0148::n0149::n0150::n0151::n0152::n0153::n0154::n0155::n0156::n0157::n0158::n0159::n0160::n0161::n0162::n0163::n0164::n0165::n0166::n0167::n0168::n0169::n0170::n0171::n0172::n0173::n0174::n0175::n0176::n0177::n0178::n0179::n0180::n0181::n0182::n0183::n0184::n0185::n0186::n0187::n0188::n0189::n0190::n0191::n0192::n0193::n0194::n0195::n0196::n0197::n0198::n0199::n0200::n0201::n0202::n0203::n0204::n0205::n0206::n0207::n0208::n0209::n0210::n0211::n0212::n0213::n0214::n0215::n0216::n0217::n0218::n0219::n0220::n0221::n0222::n0223::n0224::n0225::n0226::n0227::n0228::n0229::n0230::n0231::n0232::n0233::n0234::n0235::n0236::n0237::n0238::n0239::n0240::n0241::n0242::n0243::n0244::n0245::n0246::n0247::n0248::n0249::n0250::n0251::n0252::n0253::n0254::n0255__xa618845ad8c42d4b::leaf","verdict":"AGREES(256)"},{"function":"n0000::n0001::n0002::n0003::n0004::n0005::n0006::n0007::n0008::n0009::n0010::n0011::n0012::n0013::n0014::n0015::n0016::n0017::n0018::n0019::n0020::n0021::n0022::n0023::n0024::n0025::n0026::n0027::n0028::n0029::n0030::n0031::n0032::n0033::n0034::n0035::n0036::n0037::n0038::n0039::n0040::n0041::n0042::n0043::n0044::n0045::n0046::n0047::n0048::n0049::n0050::n0051::n0052::n0053::n0054::n0055::n0056::n0057::n0058::n0059::n0060::n0061::n0062::n0063::n0064::n0065::n0066::n0067::n0068::n0069::n0070::n0071::n0072::n0073::n0074::n0075::n0076::n0077::n0078::n0079::n0080::n0081::n0082::n0083::n0084::n0085::n0086::n0087::n0088::n0089::n0090::n0091::n0092::n0093::n0094::n0095::n0096::n0097::n0098::n0099::n0100::n0101::n0102::n0103::n0104::n0105::n0106::n0107::n0108::n0109::n0110::n0111::n0112::n0113::n0114::n0115::n0116::n0117::n0118::n0119::n0120::n0121::n0122::n0123::n0124::n0125::n0126::n0127::n0128::n0129::n0130::n0131::n0132::n0133::n0134::n0135::n0136::n0137::n0138::n0139::n0140::n0141::n0142::n0143::n0144::n0145::n0146::n0147::n0148::n0149::n0150::n0151::n0152::n0153::n0154::n0155::n0156::n0157::n0158::n0159::n0160::n0161::n0162::n0163::n0164::n0165::n0166::n0167::n0168::n0169::n0170::n0171::n0172::n0173::n0174::n0175::n0176::n0177::n0178::n0179::n0180::n0181::n0182::n0183::n0184::n0185::n0186::n0187::n0188::n0189::n0190::n0191::n0192::n0193::n0194::n0195::n0196::n0197::n0198::n0199::n0200::n0201::n0202::n0203::n0204::n0205::n0206::n0207::n0208::n0209::n0210::n0211::n0212::n0213::n0214::n0215::n0216::n0217::n0218::n0219::n0220::n0221::n0222::n0223::n0224::n0225::n0226::n0227::n0228::n0229::n0230::n0231::n0232::n0233::n0234::n0235::n0236::n0237::n0238::n0239::n0240::n0241::n0242::n0243::n0244::n0245::n0246::n0247::n0248::n0249::n0250::n0251::n0252::n0253::n0254::n0255__xa618845ad8c42d4b::leaf","verdict":"AGREES(256)"}], + "tests/stages/kuna-symbolnamechars.xml": [{"function":"main","verdict":"AGREES(256)"},{"function":"a_x2a_x2fb","verdict":"AGREES(256)"},{"function":"a_x0ab","verdict":"AGREES(256)"},{"function":"a_x80b","verdict":"AGREES(256)"},{"function":"a_x81b","verdict":"AGREES(256)"}], + "tests/stages/kuna-symbolnamerepair.xml": [{"function":"anonymous_namespace::top_helper","verdict":"AGREES(256)"},{"function":"outer::anonymous_namespace::nested_helper","verdict":"AGREES(256)"},{"function":"outer::anonymous_namespace::Widget::emit","verdict":"AGREES(256)"}], + "tests/stages/kuna-syscallregs-aarch64.xml": [{"function":"pair","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"fence","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIFFERS(return)"},{"function":"after","verdict":"DIFFERS(return)"},{"function":"fence","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIVERGES(syscall-result)"}], + "tests/stages/kuna-syscallregs-arm.xml": [{"function":"pair","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"fence","verdict":"AGREES(256)"},{"function":"discard","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"rd_into_global","verdict":"AGREES(256)"},{"function":"return_snapshot","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIFFERS(return)"},{"function":"after","verdict":"DIFFERS(return)"},{"function":"fence","verdict":"AGREES(256)"},{"function":"discard","verdict":"AGREES(256)"},{"function":"keep","verdict":"AGREES(256)"},{"function":"rd_into_global","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIVERGES(syscall-result)"}], + "tests/stages/kuna-syscallregs-cortexm.xml": [{"function":"xPortRaisePrivilege","verdict":"UNKNOWN(unsupported-op)"},{"function":"xPortRaisePrivilege","verdict":"UNKNOWN(unsupported-op)"},{"function":"xPortRaisePrivilege","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-syscallregs-mips-a3.xml": [{"function":"rd","verdict":"AGREES(256)"},{"function":"wr","verdict":"AGREES(256)"},{"function":"both","verdict":"AGREES(256)"},{"function":"rd_nocancel","verdict":"AGREES(256)"},{"function":"rb","verdict":"AGREES(256)"},{"function":"rd","verdict":"DIFFERS(return)"},{"function":"wr","verdict":"DIFFERS(call at 0x100058 to 0x100020)"},{"function":"both","verdict":"DIFFERS(return)"},{"function":"rd_nocancel","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-syscallregs-mips.xml": [{"function":"number","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"number","verdict":"DIFFERS(return)"},{"function":"after","verdict":"DIFFERS(return)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"number","verdict":"DIVERGES(syscall-result)"}], + "tests/stages/kuna-syscallregs-ppc-cr0.xml": [{"function":"rdp","verdict":"AGREES(256)"},{"function":"rdp2","verdict":"AGREES(256)"},{"function":"cmp","verdict":"AGREES(256)"},{"function":"join","verdict":"AGREES(256)"},{"function":"rdp","verdict":"DIFFERS(return)"},{"function":"rdp2","verdict":"DIFFERS(return)"},{"function":"cmp","verdict":"DIFFERS(return)"}], + "tests/stages/kuna-syscallregs-ppc.xml": [{"function":"pair","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"pair","verdict":"DIFFERS(return)"},{"function":"after","verdict":"DIFFERS(return)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"pair","verdict":"DIVERGES(syscall-result)"}], + "tests/stages/kuna-syscallregs-riscv.xml": [{"function":"pair","verdict":"AGREES(256)"},{"function":"after","verdict":"AGREES(256)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"retry","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIFFERS(return)"},{"function":"after","verdict":"DIFFERS(return)"},{"function":"fence","verdict":"UNKNOWN(unsupported-op)"},{"function":"retry","verdict":"AGREES(256)"},{"function":"pair","verdict":"DIVERGES(syscall-result)"}], + "tests/stages/kuna-tailcallsaved.xml": [{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailcycle-intreturn.xml": [{"function":"forward_char","verdict":"AGREES(256)"},{"function":"backward_char","verdict":"AGREES(256)"},{"function":"forward_char","verdict":"AGREES(256)"},{"function":"backward_char","verdict":"AGREES(256)"},{"function":"via_ptr","verdict":"AGREES(256)"},{"function":"mixed","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailcycle-pairreturn.xml": [{"function":"pair64","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailform-model.xml": [{"function":"__do_global_dtors_aux","verdict":"AGREES(256)"},{"function":"note_if_zero","verdict":"AGREES(256)"},{"function":"__do_global_dtors_aux","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailform-noreturn.xml": [{"function":"scaled","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"lookup","verdict":"AGREES(148)"},{"function":"store","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"lookup","verdict":"AGREES(148)"},{"function":"store","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailform-voidreturn.xml": [{"function":"__do_global_dtors_aux","verdict":"AGREES(256)"},{"function":"__do_global_dtors_aux","verdict":"AGREES(256)"}], + "tests/stages/kuna-tailform.xml": [{"function":"note_if_zero","verdict":"AGREES(256)"},{"function":"record_pair","verdict":"AGREES(256)"},{"function":"record_above","verdict":"AGREES(256)"},{"function":"replay","verdict":"AGREES(256)"},{"function":"walk_list","verdict":"AGREES(11)"},{"function":"first_value","verdict":"AGREES(256)"},{"function":"note_if_zero","verdict":"AGREES(256)"},{"function":"record_pair","verdict":"AGREES(256)"},{"function":"record_above","verdict":"AGREES(256)"},{"function":"replay","verdict":"AGREES(256)"},{"function":"walk_list","verdict":"AGREES(11)"},{"function":"first_value","verdict":"AGREES(256)"},{"function":"walk_list","verdict":"AGREES(11)"}], + "tests/stages/kuna-thumb-stmia-writeback.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-thumb2-logical-carry.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-thumbswitch.xml": [], + "tests/stages/kuna-thunkentry.xml": [{"function":"sub_401030","verdict":"AGREES(256)"}], + "tests/stages/kuna-thunknames.xml": [{"function":"drop_box","verdict":"AGREES(256)"},{"function":"drop_two","verdict":"AGREES(256)"},{"function":"drop_box","verdict":"AGREES(256)"},{"function":"drop_two","verdict":"AGREES(256)"},{"function":"mips_caller","verdict":"AGREES(256)"},{"function":"mips_caller","verdict":"AGREES(256)"}], + "tests/stages/kuna-tiedphitrim.xml": [{"function":"sum_msvc","verdict":"AGREES(256)"},{"function":"sum_gcc","verdict":"AGREES(256)"},{"function":"sum_clang","verdict":"AGREES(256)"},{"function":"store_loop","verdict":"UNKNOWN(uninitialized-local)"},{"function":"store_join","verdict":"AGREES(256)"},{"function":"outparam_join","verdict":"AGREES(256)"},{"function":"accum_loop","verdict":"AGREES(12)"},{"function":"xa11","verdict":"AGREES(256)"},{"function":"xa13","verdict":"AGREES(256)"},{"function":"outparam_walk","verdict":"AGREES(256)"},{"function":"t8","verdict":"AGREES(256)"},{"function":"t1","verdict":"AGREES(256)"},{"function":"t1b","verdict":"AGREES(256)"}], + "tests/stages/kuna-truncarg.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"k","verdict":"AGREES(256)"},{"function":"neg_","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"d","verdict":"AGREES(256)"},{"function":"bl","verdict":"AGREES(256)"},{"function":"band","verdict":"AGREES(256)"},{"function":"bfit","verdict":"AGREES(256)"},{"function":"fwd1","verdict":"AGREES(256)"},{"function":"fwd7","verdict":"AGREES(256)"}], + "tests/stages/kuna-truncptrflow.xml": [{"function":"sum_ten","verdict":"AGREES(256)"},{"function":"pointer_ninth","verdict":"AGREES(256)"}], + "tests/stages/kuna-typemerge.xml": [{"function":"count","verdict":"AGREES(43)"},{"function":"count","verdict":"AGREES(43)"},{"function":"run","verdict":"AGREES(256)"},{"function":"run","verdict":"AGREES(256)"},{"function":"count","verdict":"AGREES(43)"}], + "tests/stages/kuna-typeorder.xml": [], + "tests/stages/kuna-typevote.xml": [{"function":"put_u32_be","verdict":"AGREES(256)"},{"function":"put_u32_be","verdict":"AGREES(256)"}], + "tests/stages/kuna-ucomiss-unordered.xml": [{"function":"above","verdict":"AGREES(256)"},{"function":"at_least","verdict":"AGREES(256)"},{"function":"not_above","verdict":"AGREES(256)"},{"function":"not_at_least","verdict":"AGREES(256)"},{"function":"pick","verdict":"AGREES(256)"},{"function":"above_branch","verdict":"AGREES(256)"},{"function":"nan_or_huge","verdict":"AGREES(256)"},{"function":"ordered_below_pair","verdict":"AGREES(256)"},{"function":"nan_or_above","verdict":"AGREES(256)"},{"function":"nan_or_above","verdict":"AGREES(256)"},{"function":"nan_or_above","verdict":"AGREES(256)"},{"function":"ordered_below","verdict":"AGREES(256)"},{"function":"ordered_below","verdict":"AGREES(256)"},{"function":"ordered_below","verdict":"AGREES(256)"},{"function":"jp_jbe","verdict":"AGREES(256)"},{"function":"guarded_below","verdict":"AGREES(256)"},{"function":"guarded_sum","verdict":"AGREES(256)"},{"function":"guarded_below_os","verdict":"AGREES(256)"},{"function":"guarded_sum_os","verdict":"AGREES(256)"},{"function":"not_above","verdict":"AGREES(256)"}], + "tests/stages/kuna-udtrap.xml": [{"function":"add_trap","verdict":"UNKNOWN(unsupported-op)"},{"function":"add_ubsan","verdict":"UNKNOWN(unsupported-op)"},{"function":"free_then_trap","verdict":"UNKNOWN(unsupported-op)"},{"function":"xen_cpuid","verdict":"UNKNOWN(unsupported-op)"},{"function":"kvm_fep","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-unmappedentry.xml": [{"function":"gh558","verdict":"AGREES(256)"}], + "tests/stages/kuna-unsignedread.xml": [{"function":"widen","verdict":"AGREES(256)"},{"function":"shift","verdict":"AGREES(256)"},{"function":"sel","verdict":"AGREES(256)"},{"function":"mul_low","verdict":"AGREES(256)"},{"function":"mul_shr","verdict":"AGREES(256)"}], + "tests/stages/kuna-unwindstarts.xml": [{"function":"sub_1000003bc","verdict":"AGREES(256)"}], + "tests/stages/kuna-varargsave.xml": [{"function":"report","verdict":"AGREES(256)"},{"function":"scaled","verdict":"AGREES(256)"},{"function":"firstd","verdict":"AGREES(256)"},{"function":"dsum","verdict":"AGREES(103)"},{"function":"report","verdict":"AGREES(256)"}], + "tests/stages/kuna-varargstackargs.xml": [{"function":"ask","verdict":"AGREES(256)"}], + "tests/stages/kuna-variantnames.xml": [{"function":"ret_three","verdict":"AGREES(256)"}], + "tests/stages/kuna-varsources.xml": [{"function":"copy_home","verdict":"AGREES(256)"},{"function":"loop_home","verdict":"UNKNOWN(budget)"},{"function":"merged_homes","verdict":"AGREES(256)"},{"function":"arithmetic_home","verdict":"AGREES(256)"},{"function":"constant_home","verdict":"AGREES(256)"},{"function":"joined_home","verdict":"AGREES(256)"},{"function":"joined_helper","verdict":"AGREES(256)"},{"function":"stack_home","verdict":"AGREES(256)"},{"function":"stack_home","verdict":"AGREES(256)"},{"function":"byte_source","verdict":"AGREES(256)"},{"function":"cmov_source","verdict":"AGREES(256)"},{"function":"parameter_source","verdict":"AGREES(256)"},{"function":"parameter_source","verdict":"AGREES(256)"},{"function":"outgoing_only","verdict":"AGREES(256)"},{"function":"outgoing_definition","verdict":"AGREES(256)"},{"function":"outgoing_rmw","verdict":"AGREES(256)"},{"function":"outgoing_local_use","verdict":"AGREES(256)"},{"function":"outgoing_indirect","verdict":"AGREES(256)"},{"function":"durable_call_result","verdict":"AGREES(256)"},{"function":"stack_outgoing","verdict":"AGREES(256)"},{"function":"outgoing_independent_write","verdict":"AGREES(256)"},{"function":"arithmetic_home","verdict":"AGREES(256)"}], + "tests/stages/kuna-vcallthis-a64.xml": [{"function":"call_c","verdict":"AGREES(256)"},{"function":"call_c_then","verdict":"AGREES(256)"},{"function":"call_other","verdict":"AGREES(256)"},{"function":"call_cb","verdict":"AGREES(256)"},{"function":"call_c","verdict":"AGREES(256)"},{"function":"call_c_then","verdict":"AGREES(256)"},{"function":"call_other","verdict":"AGREES(256)"},{"function":"call_cb","verdict":"AGREES(256)"}], + "tests/stages/kuna-vcallthis.xml": [{"function":"call_c","verdict":"AGREES(256)"},{"function":"call_c_then","verdict":"AGREES(256)"},{"function":"call_other","verdict":"AGREES(256)"},{"function":"call_cb","verdict":"AGREES(256)"},{"function":"call_c","verdict":"AGREES(256)"},{"function":"call_c_then","verdict":"AGREES(256)"},{"function":"call_other","verdict":"AGREES(256)"},{"function":"call_cb","verdict":"AGREES(256)"}], + "tests/stages/kuna-vcmp-carry.xml": [{"function":"a32_hi","verdict":"AGREES(256)"},{"function":"a32_ls","verdict":"AGREES(256)"},{"function":"a32_cs","verdict":"AGREES(256)"},{"function":"a32_cc","verdict":"AGREES(256)"},{"function":"a32_cs_zero","verdict":"AGREES(256)"}], + "tests/stages/kuna-veneer-tailcall.xml": [{"function":"veneer","verdict":"UNKNOWN(unsupported-op)"},{"function":"thumb_veneer","verdict":"UNKNOWN(unsupported-op)"},{"function":"far_veneer","verdict":"UNKNOWN(unsupported-op)"},{"function":"open_veneer","verdict":"AGREES(256)"},{"function":"plain_veneer","verdict":"AGREES(256)"},{"function":"bare_veneer","verdict":"UNKNOWN(unsupported-op)"},{"function":"ret_veneer","verdict":"AGREES(256)"},{"function":"veneer","verdict":"AGREES(256)"},{"function":"thumb_veneer","verdict":"AGREES(256)"},{"function":"far_veneer","verdict":"UNKNOWN(unsupported-op)"},{"function":"open_veneer","verdict":"AGREES(256)"},{"function":"plain_veneer","verdict":"AGREES(256)"},{"function":"bare_veneer","verdict":"AGREES(256)"},{"function":"ret_veneer","verdict":"AGREES(256)"}], + "tests/stages/kuna-voidtailreturn.xml": [{"function":"vt_fn","verdict":"AGREES(256)"},{"function":"vt_fn","verdict":"AGREES(256)"}], + "tests/stages/kuna-volatile-qualifiers.xml": [{"function":"ReadTwice","verdict":"AGREES(256)"},{"function":"ReadPointer","verdict":"AGREES(256)"},{"function":"UnusedReads","verdict":"AGREES(256)"}], + "tests/stages/kuna-wholeinputarg-be.xml": [{"function":"veneer_int","verdict":"AGREES(256)"},{"function":"veneer_char","verdict":"AGREES(256)"},{"function":"veneer_real","verdict":"AGREES(256)"},{"function":"veneer_long","verdict":"AGREES(256)"},{"function":"fwd","verdict":"AGREES(256)"},{"function":"two","verdict":"AGREES(256)"},{"function":"zfwd","verdict":"AGREES(256)"},{"function":"sfwd","verdict":"AGREES(256)"},{"function":"zread","verdict":"AGREES(256)"},{"function":"sfld","verdict":"AGREES(256)"},{"function":"vfmt","verdict":"AGREES(256)"}], + "tests/stages/kuna-wholeinputarg.xml": [{"function":"veneer_int","verdict":"AGREES(256)"},{"function":"veneer_char","verdict":"AGREES(256)"},{"function":"veneer_real","verdict":"AGREES(256)"},{"function":"veneer_long","verdict":"AGREES(256)"},{"function":"fwd","verdict":"AGREES(256)"},{"function":"two","verdict":"AGREES(256)"},{"function":"zfwd","verdict":"AGREES(256)"},{"function":"sfwd","verdict":"AGREES(256)"},{"function":"zread","verdict":"AGREES(256)"},{"function":"sfld","verdict":"AGREES(256)"},{"function":"vfmt","verdict":"AGREES(256)"}], + "tests/stages/kuna-wide-shifts.xml": [{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"},{"function":"shift31","verdict":"AGREES(256)"},{"function":"shift63","verdict":"AGREES(256)"},{"function":"widened_shift31","verdict":"AGREES(256)"}], + "tests/stages/kuna-wideslice.xml": [{"function":"byte_sum","verdict":"AGREES(16)"}], + "tests/stages/kuna-widestrings32.xml": [{"function":"wide","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"ornull","verdict":"AGREES(256)"},{"function":"table","verdict":"AGREES(256)"},{"function":"weekly","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"code","verdict":"AGREES(256)"}], + "tests/stages/kuna-word-index-scalar.xml": [{"function":"scalar_index","verdict":"AGREES(256)"},{"function":"cell_pointer","verdict":"AGREES(256)"},{"function":"load_cell","verdict":"AGREES(256)"},{"function":"entry_ref","verdict":"AGREES(256)"},{"function":"selected_index","verdict":"AGREES(256)"},{"function":"selected_entry","verdict":"AGREES(256)"}], + "tests/stages/kuna-wordreturn.xml": [{"function":"status","verdict":"AGREES(256)"},{"function":"failed","verdict":"AGREES(256)"},{"function":"shifted","verdict":"AGREES(256)"},{"function":"magic","verdict":"AGREES(256)"},{"function":"whole","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"name","verdict":"AGREES(256)"},{"function":"status","verdict":"AGREES(256)"},{"function":"failed","verdict":"AGREES(256)"},{"function":"wide","verdict":"AGREES(256)"},{"function":"umax","verdict":"AGREES(256)"},{"function":"lbit","verdict":"AGREES(256)"},{"function":"ineg","verdict":"AGREES(256)"}], + "tests/stages/kuna-wrapadd.xml": [{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"},{"function":"word_wrap","verdict":"AGREES(256)"}], + "tests/stages/kuna-wrapsplit-be.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"}], + "tests/stages/kuna-wrapsplit.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"g","verdict":"AGREES(256)"},{"function":"h","verdict":"AGREES(256)"},{"function":"k","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-wsignload-a64.xml": [{"function":"lsh","verdict":"AGREES(256)"},{"function":"lsb","verdict":"AGREES(256)"},{"function":"lsh_idx","verdict":"AGREES(256)"},{"function":"lsb_idx","verdict":"AGREES(256)"},{"function":"lsh_neg","verdict":"AGREES(256)"},{"function":"lsb_neg","verdict":"AGREES(256)"},{"function":"lsh_pre","verdict":"AGREES(256)"},{"function":"lsb_post","verdict":"AGREES(256)"},{"function":"tbl","verdict":"AGREES(256)"},{"function":"lsh64","verdict":"AGREES(256)"},{"function":"lsb_neg64","verdict":"AGREES(256)"}], + "tests/stages/kuna-x64syscall.xml": [{"function":"kernel_call","verdict":"DIFFERS(return)"},{"function":"plain_add","verdict":"AGREES(256)"},{"function":"split_setup","verdict":"DIFFERS(return)"},{"function":"pointer_before","verdict":"AGREES(256)"},{"function":"kernel_call","verdict":"AGREES(256)"},{"function":"plain_add","verdict":"AGREES(256)"},{"function":"split_setup","verdict":"AGREES(256)"},{"function":"pointer_before","verdict":"UNKNOWN(unsupported-op)"},{"function":"kernel_call","verdict":"AGREES(256)"},{"function":"plain_add","verdict":"AGREES(256)"},{"function":"split_setup","verdict":"AGREES(256)"},{"function":"pointer_before","verdict":"AGREES(256)"}], + "tests/stages/kuna-x86-16-fpuemu.xml": [{"function":"scale","verdict":"UNKNOWN(unsupported-op)"},{"function":"scale","verdict":"UNKNOWN(unsupported-op)"},{"function":"fles","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-x86-16-protected-rel16.xml": [], + "tests/stages/kuna-x86-16-real-rel16.xml": [{"function":"com_main","verdict":"UNKNOWN(unsupported-op)"},{"function":"far_caller","verdict":"UNKNOWN(unsupported-op)"},{"function":"f","verdict":"UNKNOWN(unsupported-op)"},{"function":"r","verdict":"UNKNOWN(unsupported-op)"},{"function":"k","verdict":"UNKNOWN(unsupported-op)"},{"function":"s","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/kuna-x86-directalias-freed.xml": [{"function":"freed_call","verdict":"AGREES(256)"}], + "tests/stages/kuna-x86-directalias.xml": [{"function":"static_frame","verdict":"AGREES(256)"},{"function":"later_vla","verdict":"AGREES(256)"}], + "tests/stages/kuna-x86listingswitch.xml": [{"function":"sub_100400","verdict":"AGREES(256)"},{"function":"sub_100400","verdict":"AGREES(256)"}], + "tests/stages/kuna-x87intrinsics.xml": [{"function":"_polar","verdict":"UNKNOWN(unsupported-op)"},{"function":"_angles","verdict":"AGREES(256)"},{"function":"spin","verdict":"AGREES(256)"}], + "tests/stages/kuna-zeroloopfield.xml": [{"function":"nl","verdict":"AGREES(256)"}], + "tests/stages/kuna-zextpair.xml": [{"function":"ins16","verdict":"AGREES(256)"},{"function":"zadd","verdict":"AGREES(256)"},{"function":"zsh","verdict":"AGREES(256)"},{"function":"zsel","verdict":"AGREES(256)"},{"function":"zmix","verdict":"AGREES(256)"}], + "tests/stages/kuna-zextword.xml": [{"function":"z32m","verdict":"AGREES(256)"},{"function":"zu","verdict":"AGREES(256)"},{"function":"zc","verdict":"AGREES(256)"},{"function":"ru","verdict":"AGREES(256)"},{"function":"rus","verdict":"AGREES(256)"},{"function":"z32m","verdict":"AGREES(256)"},{"function":"zu","verdict":"AGREES(256)"},{"function":"zc","verdict":"AGREES(256)"},{"function":"ru","verdict":"AGREES(256)"},{"function":"rus","verdict":"AGREES(256)"}], + "tests/stages/modes-aggressive.xml": [{"function":"f","verdict":"AGREES(256)"},{"function":"f","verdict":"AGREES(256)"}], + "tests/stages/mulblob-wide-multiply-operands.xml": [{"function":"widemul","verdict":"AGREES(256)"}], + "tests/stages/namestyle.xml": [{"function":"target","verdict":"AGREES(103)"},{"function":"target","verdict":"AGREES(103)"}], + "tests/stages/overlapbranch.xml": [{"function":"overlap","verdict":"UNKNOWN(unsupported-op)"},{"function":"overlap","verdict":"DIFFERS(call 1 at 0x8048824 to 0xb0c48ac)"}], + "tests/stages/oxidizer-cleanupcode.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}], + "tests/stages/oxidizer-securitycheck.xml": [{"function":"pick","verdict":"AGREES(256)"},{"function":"pick","verdict":"DIVERGES(panic-check)"}], + "tests/stages/powerpc-isa-hint.xml": [{"function":"select_value","verdict":"UNKNOWN(unsupported-op)"}], + "tests/stages/re-checker-stack-aggregate.xml": [{"function":"stack_aggregate","verdict":"AGREES(256)"}], + "tests/stages/re-constselectjump.xml": [{"function":"csjmp","verdict":"AGREES(256)"},{"function":"csjmp","verdict":"AGREES(256)"}], + "tests/stages/realtypes-fauxware.xml": [{"function":"authenticate","verdict":"AGREES(256)"}], + "tests/stages/regionstructure-edgeorder.xml": [{"function":"cross","verdict":"AGREES(256)"},{"function":"cross","verdict":"AGREES(256)"}], + "tests/stages/regionstructure-loop-refine.xml": [{"function":"mexit","verdict":"AGREES(256)"},{"function":"mexit","verdict":"AGREES(256)"}], + "tests/stages/regionstructure-loop.xml": [{"function":"loopproof","verdict":"AGREES(103)"},{"function":"loopproof","verdict":"AGREES(103)"}], + "tests/stages/regionstructure-seq.xml": [{"function":"proof_fn","verdict":"AGREES(256)"},{"function":"proof_fn","verdict":"AGREES(256)"}], + "tests/stages/regionstructure-shortcircuit.xml": [{"function":"testElseIf","verdict":"AGREES(66)"},{"function":"testElseIf","verdict":"AGREES(66)"}], + "tests/stages/regionstructure-switch.xml": [{"function":"dispatch","verdict":"AGREES(256)"},{"function":"dispatch","verdict":"AGREES(256)"}], + "tests/stages/structheadless-any.xml": [{"function":"mode_of","verdict":"AGREES(256)"},{"function":"by_link","verdict":"AGREES(256)"},{"function":"mode_of","verdict":"AGREES(256)"},{"function":"by_link","verdict":"AGREES(256)"}], + "tests/stages/structheadless-closed-only.xml": [{"function":"mode_of","verdict":"AGREES(256)"},{"function":"mode_of","verdict":"AGREES(256)"}], + "tests/stages/structmerge-siblings.xml": [{"function":"off_a","verdict":"AGREES(256)"},{"function":"off_b","verdict":"AGREES(256)"},{"function":"off_a","verdict":"AGREES(256)"},{"function":"on_a","verdict":"AGREES(256)"},{"function":"on_b","verdict":"AGREES(256)"},{"function":"on_a","verdict":"AGREES(256)"}], + "tests/stages/structsynth-hole-member.xml": [{"function":"hole","verdict":"AGREES(256)"},{"function":"hole","verdict":"AGREES(256)"}], + "tests/stages/structsynth-locals.xml": [{"function":"make","verdict":"AGREES(256)"},{"function":"weigh","verdict":"AGREES(256)"},{"function":"label","verdict":"AGREES(256)"},{"function":"either","verdict":"AGREES(256)"},{"function":"tmpl","verdict":"AGREES(256)"},{"function":"post","verdict":"AGREES(256)"},{"function":"make","verdict":"AGREES(256)"},{"function":"weigh","verdict":"AGREES(256)"},{"function":"label","verdict":"AGREES(256)"},{"function":"either","verdict":"AGREES(256)"},{"function":"tmpl","verdict":"AGREES(256)"},{"function":"post","verdict":"AGREES(256)"}], + "tests/stages/structsynth-nest.xml": [{"function":"use_outer","verdict":"AGREES(256)"},{"function":"treewalk","verdict":"AGREES(256)"},{"function":"use_outer","verdict":"AGREES(256)"},{"function":"treewalk","verdict":"AGREES(256)"}], + "tests/stages/structsynth-overlap-layout.xml": [{"function":"overlap","verdict":"AGREES(256)"},{"function":"overlap","verdict":"AGREES(256)"}], + "tests/stages/structsynth-param-struct.xml": [{"function":"two_fields","verdict":"AGREES(256)"},{"function":"two_fields","verdict":"AGREES(256)"}], + "tests/stages/structsynth-shared-layout.xml": [{"function":"three_fields","verdict":"AGREES(256)"},{"function":"two_fields","verdict":"AGREES(256)"},{"function":"three_fields","verdict":"AGREES(256)"},{"function":"two_fields","verdict":"AGREES(256)"},{"function":"four_words","verdict":"AGREES(256)"},{"function":"two_words","verdict":"AGREES(256)"},{"function":"big_if","verdict":"AGREES(256)"},{"function":"small_if","verdict":"AGREES(256)"},{"function":"for_like","verdict":"AGREES(256)"},{"function":"if_like","verdict":"AGREES(256)"},{"function":"case_like","verdict":"AGREES(256)"},{"function":"items_like","verdict":"AGREES(256)"},{"function":"spec_like","verdict":"AGREES(256)"},{"function":"queue_like","verdict":"AGREES(256)"}], + "tests/stages/structsynth-unclaimed-bytes.xml": [{"function":"full","verdict":"AGREES(256)"},{"function":"rd_c8","verdict":"AGREES(256)"},{"function":"rd_c9","verdict":"AGREES(256)"},{"function":"rd_c10","verdict":"AGREES(256)"}], + "tests/stages/switchsharedcase-b2sum.xml": [{"function":"main","verdict":"UNKNOWN(budget)"},{"function":"main","verdict":"UNKNOWN(budget)"}], + "tests/stages/tailcallframe.xml": [{"function":"caller","verdict":"AGREES(256)"},{"function":"caller","verdict":"AGREES(256)"}] + } +} diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md index 8a0b693136..c27b980da0 100644 --- a/docs/features/diffverify/README.md +++ b/docs/features/diffverify/README.md @@ -19,6 +19,7 @@ K=decompiler/target/release/kuna-verify $K check ./prog main parse_args # some functions of a binary $K check ./prog --all --jobs 10 # every function $K corpus tests/datatests tests/stages # every function the test corpus decompiles +make verify-corpus # the same against docs/baseline-verify.json ``` A difference looks like this (#794's fixture, with the option that brings the bug back): @@ -114,7 +115,7 @@ ins16 DIFFERS (run 1 of 256) | `SKIPPED(reason)` | reserved for Tier S. | Exit status: 1 when a function differs, 3 when a file could not be checked, 2 for a usage -error, and 0 otherwise. +error, and 0 otherwise. With `--baseline`, it is 1 only for a regression (§6). ### Reading a report @@ -140,7 +141,7 @@ error, and 0 otherwise. ```sh kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... -kuna-verify corpus ... [--jobs N] [--file-seconds S] +kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] [--file-seconds S] common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] @@ -230,21 +231,40 @@ The crate is grouped by folder; the old module paths (`crate::check`, `crate::ca | `abi/` | `mod.rs`, `calls.rs`, `contract.rs`, `divergence.rs` | calling conventions, per-call facts both sides share, C contracts, declared divergences | | `compare/` | `check.rs`, `observe.rs`, `setup.rs` | the runs and the verdict; comparing calls, memory and system calls; each run's starting state | | `tools/` | `localize.rs`, `mutate.rs` | rule localization, mutation testing | -| `report/` | `mod.rs` | output | +| `report/` | `mod.rs`, `baseline.rs` | output; the corpus baseline | A later tier gets a folder of its own (`symbolic/` for Tier S, `printer/` for Tier P). ## 6. In CI -Not yet. A corpus baseline that CI compares each change against, and the CI step that -runs it, are a separate change. Until then `corpus` over `tests/datatests` and -`tests/stages` gives the same verdicts to compare by hand. +`make verify-corpus` runs `corpus` over `tests/datatests` and `tests/stages` against +`docs/baseline-verify.json`. It runs as a non-gating step of the parity-gates job, which +uploads the verdict table and its own recording of the baseline. + +The baseline keeps each function's verdict class, not its values: `AGREES(n)` with its +run count, `DIFFERS(where)` with the place it first differs (`return`, `unassigned`, +`call 1 at 0x18000c005`, `memory at exit`), `DIVERGES(id)`, and `UNKNOWN(reason)` without +addresses. A change that moves no verdict leaves the file as it is. + +| change | result | +|---|---| +| a function that agreed, or a new function, now differs; a file can no longer be checked | regression: fails the step | +| a function that agreed now has a difference traced to a guess (`UNKNOWN(prototype-suspect)` and the like) | regression | +| a function that agreed is `UNKNOWN`, no longer checked, or agrees on at most half the runs it agreed on | lost coverage: a warning | +| a function that differed now differs elsewhere, agrees, or is `UNKNOWN` | listed | + +A difference that moves stays a notice so a change that rewrites an output the check +already flags does not have to re-record the baseline, while the reviewer still sees it. +Rows are paired by function and occurrence, so a file whose function list changed is +still compared. Re-record the baseline with +`make verify-corpus VERIFY_ARGS='--save-baseline docs/baseline-verify.json'`, and say why +in the commit. ## 7. As a check on pull requests The check is deterministic: its verdict comes from running the machine code, not from a model's judgement, so it holds every pull request to the same bar whichever agent wrote -it. It has done two things review did not: +it. It has done three things review did not: - **Found bugs in merged code.** The decbench run found seven kuna bugs (#1916–#1922) and three errors in the vendored SLEIGH specs (Tier L), all in code that @@ -252,6 +272,8 @@ it. It has done two things review did not: - **Confirmed fixes on its own.** The stage tests #1924 and #1927 added give `DIFFERS` in their pass with the fix turned off and `AGREES` in the default pass, without anyone reading the printed C. +- **Gates regressions.** `make verify-corpus` (§6) names every function a change makes + differ. It is not a replacement for review. What it does not cover: diff --git a/docs/features/diffverify/proposal.md b/docs/features/diffverify/proposal.md index 324d8bc0c2..e7a497eaf9 100644 --- a/docs/features/diffverify/proposal.md +++ b/docs/features/diffverify/proposal.md @@ -337,14 +337,18 @@ first, and S1 reuses C5's expressions. gate only once the `DIFFERS` set is empty or every entry is a declared divergence, with a baseline file like `docs/baseline.json`. -That job, `make verify-corpus` and a `continue-on-error` step of the parity-gates job -in `.github/workflows/tests.yml`, comes in a change of its own. Each function's verdict -class over `tests/datatests` + `tests/stages` is pinned in `docs/baseline-verify.json`: -- `AGREES`, `DIFFERS`, `DIVERGES(id)` or `UNKNOWN(reason)`; -- no run count and no address, so the file changes only when a verdict does. +That job exists: `make verify-corpus`, and a `continue-on-error` step of the parity-gates +job in `.github/workflows/tests.yml`. Each function's verdict class over +`tests/datatests` + `tests/stages` is pinned in `docs/baseline-verify.json`: +- `AGREES(n)`, `DIFFERS(where)`, `DIVERGES(id)` or `UNKNOWN(reason)`, where `where` is + the place a run first differs (`return`, `call 1 at 0x10`, `memory at exit`); +- no values and no address an `UNKNOWN` names, so the file changes only when a verdict + or the place of a difference does. A function that now differs, or a file that can no longer be checked, is an error -annotation, and `make verify-corpus` exits 1. Every other change is a notice. The step +annotation, and `make verify-corpus` exits 1. A function that agreed and agrees no +longer, or on at most half the runs, is a warning. Every other change, a difference +that moved among them, is a notice. The step uploads the verdict table and its own recording of the baseline. Re-record: `make verify-corpus VERIFY_ARGS='--save-baseline docs/baseline-verify.json'`. From 78c1a74ca3b09fdbabd6a720255e1cb8c894a9f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 09:49:34 +0900 Subject: [PATCH 5/7] [AUTOMATED] Add concolic inputs to kuna-verify (--concolic N) After the random runs, the machine side records each run's path as expressions over the input bytes. `--concolic N` negates one recorded branch condition at a time and asks z3 (a subprocess speaking SMT-LIB 2) for an input that takes the other way, up to N queries per function. z3 only picks inputs; the verdict still comes from running both sides. With no z3, the report says no concolic run was made. Slice C5 of the diffverify proposal. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 7 + .../crates/kuna-verify/src/bin/kuna-verify.rs | 10 +- .../crates/kuna-verify/src/compare/check.rs | 58 +- decompiler/crates/kuna-verify/src/lib.rs | 3 +- .../crates/kuna-verify/src/machine/mod.rs | 115 ++++ .../crates/kuna-verify/src/machine/tests.rs | 10 +- .../crates/kuna-verify/src/report/baseline.rs | 2 +- .../crates/kuna-verify/src/report/mod.rs | 17 +- .../crates/kuna-verify/src/state/mod.rs | 49 ++ .../crates/kuna-verify/src/tools/concolic.rs | 560 ++++++++++++++++++ .../crates/kuna-verify/src/tools/mod.rs | 4 +- .../kuna-verify/tests/verdict_guards.rs | 43 ++ docs/features/diffverify/README.md | 20 +- .../diffverify/c4-decbench-results.md | 4 +- docs/features/diffverify/c5-results.md | 96 +++ docs/features/diffverify/mutation.md | 10 +- 16 files changed, 975 insertions(+), 33 deletions(-) create mode 100644 decompiler/crates/kuna-verify/src/tools/concolic.rs create mode 100644 docs/features/diffverify/c5-results.md diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 22aa3cd0d7..5f057529e2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -292,7 +292,14 @@ jobs: exit 1 fi + # kuna-verify's solver tests return early without z3; KUNA_REQUIRE_Z3 + # makes a missing solver fail them here instead. + - name: Install z3 + run: sudo apt-get update -q && sudo apt-get install -y z3 + - name: make rust-test -- the full cargo workspace suite + env: + KUNA_REQUIRE_Z3: "1" run: | df -h . make rust-test diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs index 91a87d01ca..45d8e008ef 100644 --- a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -5,7 +5,7 @@ //! kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] //! kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] -//! common: [--runs N] [--seed S] [--budget OPS] [--json] [--sleighpath DIR] +//! common: [--runs N] [--seed S] [--budget OPS] [--concolic QUERIES] [--json] [--sleighpath DIR] //! ``` //! //! `corpus --jobs N` checks N files at a time, each in a worker process of @@ -39,7 +39,7 @@ const USAGE: &str = "usage: kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] -options: --runs N (256) --seed S --budget OPS (200000) --call-reruns N (4) --json --trace --sleighpath DIR"; +options: --runs N (256) --seed S --budget OPS (200000) --concolic QUERIES (0) --call-reruns N (4) --json --trace --sleighpath DIR"; struct Args { positional: Vec, @@ -99,6 +99,11 @@ fn parse(argv: &[String]) -> Result { let v = it.next().ok_or("--option needs NAME VALUE")?; a.options.push((n.clone(), v.clone())); } + "--concolic" => { + let v = it.next(); + a.opts.concolic = u32::try_from(num(v, "--concolic")?).map_err(|_| "--concolic: too large")?; + a.forward.extend(["--concolic".to_string(), v.cloned().unwrap_or_default()]); + } "--call-reruns" => { let v = it.next(); a.opts.call_reruns = u32::try_from(num(v, "--call-reruns")?).map_err(|_| "--call-reruns: too large")?; @@ -402,6 +407,7 @@ fn run_chunk( lines: Vec::new(), suspects: Vec::new(), elapsed: std::time::Duration::ZERO, + concolic: None, }; on_row(Row::from(&report)); let rest: Vec = chunk.iter().zip(&seen).skip(first + 1).filter(|(_, s)| !**s).map(|(f, _)| f.clone()).collect(); diff --git a/decompiler/crates/kuna-verify/src/compare/check.rs b/decompiler/crates/kuna-verify/src/compare/check.rs index f532bef95f..33253e17fe 100644 --- a/decompiler/crates/kuna-verify/src/compare/check.rs +++ b/decompiler/crates/kuna-verify/src/compare/check.rs @@ -40,6 +40,9 @@ pub struct Options { pub budget_runs: u32, /// Add both sides' calls to a `DIFFERS` report. pub trace: bool, + /// C5: z3 queries per function for concolic inputs after the random + /// runs; 0 runs none. + pub concolic: u32, /// Calls per run whose callee read an argument kuna passes otherwise /// that get a machine rerun with kuna's value. A run with more is not /// counted as agreeing. @@ -48,7 +51,7 @@ pub struct Options { impl Default for Options { fn default() -> Self { - Options { runs: 256, seed: 0x6b75_6e61, budget: 200_000, budget_runs: 4, trace: false, call_reruns: 4 } + Options { runs: 256, seed: 0x6b75_6e61, budget: 200_000, budget_runs: 4, trace: false, concolic: 0, call_reruns: 4 } } } @@ -111,6 +114,12 @@ impl UpperWatch { } } +/// C5: the random runs whose paths are recorded for z3 to branch from. +const RECORDED_RUNS: u32 = 16; + +/// C5: z3's time per query. +const CONCOLIC_MILLIS: u32 = 300; + /// Runs that may stop on an operation the model cannot run before the /// function is given up as `UNKNOWN(unsupported-op)`: such a function is /// `UNKNOWN` whatever its other runs show, unless one of them differs, and @@ -160,7 +169,7 @@ impl<'e, 'p> Shared<'e, 'p> { } fn early(fd: &Funcdata, started: Instant, verdict: Verdict) -> Report { - Report { function: fd.get_name().to_string(), verdict, lines: Vec::new(), suspects: Vec::new(), elapsed: started.elapsed() } + Report { function: fd.get_name().to_string(), verdict, lines: Vec::new(), suspects: Vec::new(), elapsed: started.elapsed(), concolic: None } } /// Build `fd`'s machine-side setup; a report when the function cannot be @@ -209,11 +218,12 @@ pub fn check_shared(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, shared } fn check_prepared(prog: &ConsoleProgram, fd: &Funcdata, contract: Option<&Contract>, opts: &Options, shared: &Shared, keep: bool) -> Report { - let mut report = check_runs(prog, fd, contract, opts, None, &mut None, shared, keep); + let mut work = crate::concolic::Worklist::default(); + let mut report = check_runs(prog, fd, contract, opts, &mut work, None, &mut None, shared, keep); if shared.prepared.assumed && matches!(report.verdict, Verdict::Agrees(_)) { - let free = Options { runs: opts.runs.min(DOMAIN_RUNS), ..*opts }; + let free = Options { runs: opts.runs.min(DOMAIN_RUNS), concolic: 0, ..*opts }; let wide = match prepare(prog, fd, &free, true) { - Ok(p) => check_runs(prog, fd, contract, &free, None, &mut None, &Shared::new(&p), false), + Ok(p) => check_runs(prog, fd, contract, &free, &mut crate::concolic::Worklist::default(), None, &mut None, &Shared::new(&p), false), Err(r) => r, }; if matches!(wide.verdict, Verdict::Differs { .. }) { @@ -234,6 +244,16 @@ fn check_prepared(prog: &ConsoleProgram, fd: &Funcdata, contract: Option<&Contra }; } } + if opts.concolic > 0 { + let s = work.summary(); + let why = match s.solver { + crate::concolic::SolverState::Unavailable => "; z3 could not be started, so no concolic run was made", + crate::concolic::SolverState::Broken => "; z3 stopped answering as expected and was not asked again", + _ => "", + }; + report.lines.push(format!("concolic {} z3 queries, {} inputs found{why}", s.queries, s.models)); + report.concolic = Some(s); + } report } @@ -246,9 +266,10 @@ pub fn check_mutant(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, m: cra /// `check_mutant` on a shared setup, reusing the machine's runs. pub fn check_mutant_shared(prog: &ConsoleProgram, fd: &Funcdata, opts: &Options, m: crate::mutate::Mutation, shared: &Shared) -> Option<(Report, String, bool)> { + let mut work = crate::concolic::Worklist::default(); let mut got = None; let reached = std::rc::Rc::new(std::cell::Cell::new(false)); - let report = check_runs(prog, fd, None, opts, Some((m, std::rc::Rc::clone(&reached))), &mut got, shared, true); + let report = check_runs(prog, fd, None, opts, &mut work, Some((m, std::rc::Rc::clone(&reached))), &mut got, shared, true); got.map(|what| (report, what, reached.get())) } @@ -257,6 +278,7 @@ fn check_runs<'e, 'p>( fd: &Funcdata, contract: Option<&Contract>, opts: &Options, + work: &mut crate::concolic::Worklist, mutation: Option<(crate::mutate::Mutation, std::rc::Rc>)>, mutated: &mut Option, shared: &Shared<'e, 'p>, @@ -264,7 +286,7 @@ fn check_runs<'e, 'p>( ) -> Report { let started = Instant::now(); let finish = |verdict: Verdict, lines: Vec, suspects: Vec| { - Report { function: fd.get_name().to_string(), verdict, lines, suspects, elapsed: started.elapsed() } + Report { function: fd.get_name().to_string(), verdict, lines, suspects, elapsed: started.elapsed(), concolic: None } }; let env: &'e Env<'p> = &shared.prepared.env; let claim = &shared.prepared.claim; @@ -280,6 +302,7 @@ fn check_runs<'e, 'p>( let mut machine_calls = std::borrow::Cow::Borrowed(&shared.prepared.machine_calls); let mut calls = machine_calls.as_ref().clone(); let mut program: Program = program::compile(prog, fd, &calls); + let keep = keep && opts.concolic == 0; let mut noreturn_site = None; if let Some((m, reached)) = mutation { program.reached = reached; @@ -332,10 +355,25 @@ fn check_runs<'e, 'p>( let perturb = unassigned(prog, env, fd, claim, &program, &calls); let mut perturbed_runs = 0u32; let mut kernel_shows = false; - for run in 0..opts.runs { + let mut queue: std::collections::VecDeque<(u32, Option, Option)> = + (0..opts.runs).map(|r| (r, None, None)).collect(); + loop { + let (run, inputs, aim) = match queue.pop_front() { + Some(x) => x, + None => match (opts.concolic > 0).then(|| work.next(opts.concolic, CONCOLIC_MILLIS)).flatten() { + Some((r, inputs, at)) => (r, Some(inputs), Some(at)), + None => break, + }, + }; + *env.concolic_inputs.borrow_mut() = inputs.clone(); + env.record_path.set(opts.concolic > 0 && (inputs.is_some() || run < RECORDED_RUNS)); let short = both_budget_runs >= opts.budget_runs; let run_budget = if short { opts.budget / SHORT_BUDGET } else { opts.budget }; let mut m = base_machine(run, run_budget); + env.record_path.set(false); + if let Some(path) = m.as_ref().ok().and_then(|mo| mo.path.clone()).filter(|p| !p.branches.is_empty()) { + work.add(run, inputs.clone(), path); + } let mut g = graph::run(env, &program, run, run_budget, &calls, m.as_ref().map(|mo| mo.calls.as_slice()).unwrap_or(&[]), None); if short && matches!(m, Err(Halt::Budget)) != matches!(g, Err(Halt::Budget)) { m = base_machine(run, opts.budget); @@ -424,6 +462,9 @@ fn check_runs<'e, 'p>( let differs = |mut lines: Vec| { let at = usize::from(lines.first().is_some_and(|l| l.starts_with("contract"))); lines.insert(at, input_line(prog, env, run, claim)); + if let Some(a) = aim { + lines.insert(at + 1, format!("concolic an input z3 gave to take the branch at {a:#x} the other way")); + } for (site, callee) in &mo.followed { lines.push(format!("note the machine ran {callee:#x} from {site:#x} itself: kuna has no call there")); } @@ -680,6 +721,7 @@ fn check_runs<'e, 'p>( } agreed += 1; } + *env.concolic_inputs.borrow_mut() = None; let mut suspects = abi::unclaimed_inputs(prog, env, fd, claim); suspects.extend(call_suspects); if agreed >= opts.runs { diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs index b0bb86cae6..124d694d4c 100644 --- a/decompiler/crates/kuna-verify/src/lib.rs +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -26,7 +26,7 @@ pub use compare::check; pub use graph::program; pub use report::baseline; pub use semantics::{storage, value, x87}; -pub use tools::{localize, mutate}; +pub use tools::{concolic, localize, mutate}; use std::time::{Duration, Instant}; @@ -79,6 +79,7 @@ pub fn check_binary_each( lines: Vec::new(), suspects: Vec::new(), elapsed: Duration::ZERO, + concolic: None, }; emit(pos, report); } diff --git a/decompiler/crates/kuna-verify/src/machine/mod.rs b/decompiler/crates/kuna-verify/src/machine/mod.rs index de5a036bc0..05c3cb1857 100644 --- a/decompiler/crates/kuna-verify/src/machine/mod.rs +++ b/decompiler/crates/kuna-verify/src/machine/mod.rs @@ -146,6 +146,92 @@ fn decodes_in(env: &Env, target: u64, mode: Option) -> bool { }) } +/// C5's view of one run: what expression of the inputs each written byte +/// holds, with the byte's concrete value when it was written, so a later +/// overwrite by code the view does not follow (a callee, a stub) drops it. +#[derive(Clone, Default)] +struct Shadow { + bytes: std::collections::HashMap<(i32, u64), (Rc, u32, u8)>, + path: crate::concolic::Path, +} + +/// Branches a recorded path keeps. +const PATH_BRANCHES: usize = 256; + +impl Machine<'_, '_, '_> { + /// C5: the expression `vn` holds, given its concrete value; `None` when it + /// depends on no input. + fn sym_read(&mut self, vn: &VarnodeData, value: u128) -> Option> { + use crate::concolic::Expr; + self.shadow.as_ref()?; + let spc = Rc::clone(vn.space.as_ref()?); + if spc.get_type() == spacetype::IPTR_CONSTANT { + return None; + } + let n = vn.size; + let big = spc.is_big_endian(); + let mut pieces = Vec::with_capacity(n as usize); + let mut symbolic = false; + for i in 0..u64::from(n) { + let at = spc.wrap_offset(vn.offset.wrapping_add(i)); + let shift = if big { u64::from(n) - 1 - i } else { i }; + let cb = (value >> (8 * shift)) as u8; + let known = self.shadow.as_ref()?.bytes.get(&(spc.get_index(), at)).filter(|(_, _, conc)| *conc == cb).cloned(); + let piece = match known { + Some((e, idx, _)) => Some(crate::concolic::byte(&e, idx)), + None if self.state.untouched(&spc, at) => self.env.input_place(&spc, at).map(|place| { + let name: Rc = format!("v{}_{at:x}", place.space).into(); + if let Some(s) = self.shadow.as_mut() { + s.path.inputs.insert(Rc::clone(&name), place); + } + Rc::new(Expr::Var(name)) + }), + None => None, + }; + symbolic |= piece.is_some(); + pieces.push(piece.unwrap_or_else(|| Rc::new(Expr::Const(u128::from(cb), 8)))); + } + if !symbolic { + return None; + } + if !big { + pieces.reverse(); + } + Some(if pieces.len() == 1 { pieces.pop()? } else { Rc::new(Expr::Concat(pieces)) }) + } + + /// C5: `vn` now holds `value`, and the expression `e` when it has one. + fn sym_write(&mut self, vn: &VarnodeData, value: u128, e: Option>) { + let Some(shadow) = self.shadow.as_mut() else { return }; + let Some(spc) = vn.space.as_ref() else { return }; + let n = u64::from(vn.size); + for i in 0..n { + let at = spc.wrap_offset(vn.offset.wrapping_add(i)); + let shift = if spc.is_big_endian() { n - 1 - i } else { i }; + let key = (spc.get_index(), at); + match &e { + Some(e) => { + shadow.bytes.insert(key, (Rc::clone(e), shift as u32, (value >> (8 * shift)) as u8)); + } + None => { + shadow.bytes.remove(&key); + } + } + } + } + + fn sym_branch(&mut self, at: u64, op: usize, cond: &VarnodeData, value: u128) { + if self.shadow.as_ref().is_none_or(|s| s.path.branches.len() >= PATH_BRANCHES) { + return; + } + if let Some(e) = self.sym_read(cond, value) { + if let Some(s) = self.shadow.as_mut() { + s.path.branches.push(crate::concolic::Branch { at, op: op as u32, cond: e, taken: value != 0 }); + } + } + } +} + /// How far past a call a callee may return: a delay slot (MIPS, SPARC) puts /// the return address one instruction further. const RETURN_SLACK: u64 = 8; @@ -180,6 +266,8 @@ pub struct Outcome<'e, 'p> { pub narrowed: bool, /// System calls and traps, in order. pub events: Vec, + /// C5: the run's path, when `Env::record_path` was on. + pub path: Option, /// Every call site the run reached, a discarded callee run's included. pub sites_reached: Vec, } @@ -227,6 +315,8 @@ struct Machine<'e, 'p, 'c> { /// Register offsets a callee run for real changed although the calling /// convention says the call preserves them, by call address. convention: Vec<(u64, u64)>, + /// C5: each byte's expression over the inputs, and the path so far. + shadow: Option, sites_reached: Vec, } @@ -246,6 +336,7 @@ struct MachineCheckpoint<'e, 'p> { narrowed: bool, copies: Vec<(u64, u64, u32)>, restoring: Vec<(u64, u64)>, + shadow: Option, } impl<'e, 'p> MachineCheckpoint<'e, 'p> { @@ -264,6 +355,7 @@ impl<'e, 'p> MachineCheckpoint<'e, 'p> { narrowed: m.narrowed, copies: m.copies.clone(), restoring: m.restoring.clone(), + shadow: m.shadow.clone(), } } @@ -281,6 +373,7 @@ impl<'e, 'p> MachineCheckpoint<'e, 'p> { m.narrowed = self.narrowed; m.copies = self.copies; m.restoring = self.restoring; + m.shadow = self.shadow; } } @@ -310,6 +403,7 @@ impl<'e, 'p, 'c> Machine<'e, 'p, 'c> { copies: Vec::new(), restoring: Vec::new(), convention: Vec::new(), + shadow: env.record_path.get().then(Shadow::default), sites_reached: Vec::new(), } } @@ -678,6 +772,7 @@ impl<'e, 'p, 'c> Machine<'e, 'p, 'c> { narrowed: self.narrowed, events: self.events, convention: self.convention, + path: self.shadow.map(|s| s.path), sites_reached: self.sites_reached, } } @@ -864,6 +959,9 @@ fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option { let c = read(&mut m.state, arg(1)?)?; + if top && m.shadow.is_some() { + m.sym_branch(addr, i, arg(1)?, c); + } if c != 0 { let t = arg(0)?; if space(t)?.get_type() != spacetype::IPTR_CONSTANT && tail(addr, t.offset) { @@ -1075,6 +1173,10 @@ fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option { @@ -1093,6 +1195,10 @@ fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option { let out = op.out.as_ref().ok_or_else(|| Halt::Unsupported(get_opname(opc).to_string()))?; let mut ins = crate::value::Inputs::default(); + let track = top && m.shadow.is_some(); + let mut syms = Vec::new(); for vn in &op.ins { let v = read(&mut m.state, vn)?; + if track { + syms.push((m.sym_read(vn, v), v, vn.size)); + } ins.push((v, vn.size)); } let by_zero = matches!(opc, OpCode::CPUI_INT_DIV | OpCode::CPUI_INT_SDIV) @@ -1123,6 +1234,10 @@ fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option, pub suspects: Vec, pub elapsed: Duration, + /// With `--concolic`: what the exploration did, z3 failing included. + pub concolic: Option, } impl Report { @@ -71,6 +73,8 @@ pub struct Row { pub lines: Vec, pub suspects: Vec, pub ms: f64, + /// `(queries, inputs found, solver state)` with `--concolic`. + pub concolic: Option<(u32, u32, String)>, } impl From<&Report> for Row { @@ -86,6 +90,7 @@ impl From<&Report> for Row { lines: r.lines.clone(), suspects: r.suspects.clone(), ms: r.elapsed.as_secs_f64() * 1e3, + concolic: r.concolic.map(|s| (s.queries, s.models, s.solver.name().to_string())), } } } @@ -116,7 +121,7 @@ impl Row { } pub fn to_json(&self) -> Value { - json!({ + let mut v = json!({ "function": self.function, "verdict": self.class, "label": self.label, @@ -124,7 +129,11 @@ impl Row { "lines": self.lines, "suspects": self.suspects, "ms": self.ms, - }) + }); + if let Some((q, m, s)) = &self.concolic { + v["z3"] = json!({"queries": q, "models": m, "solver": s}); + } + v } pub fn from_json(v: &Value) -> Option { @@ -143,6 +152,9 @@ impl Row { lines: strings("lines")?, suspects: strings("suspects")?, ms: v.get("ms")?.as_f64()?, + concolic: v.get("z3").and_then(|c| { + Some((c.get("queries")?.as_u64()? as u32, c.get("models")?.as_u64()? as u32, c.get("solver")?.as_str()?.to_string())) + }), }) } } @@ -159,6 +171,7 @@ mod tests { lines: vec!["machine r1:r0 = 0x1".into()], suspects: vec!["reads r2".into()], elapsed: Duration::from_micros(1500), + concolic: Some(crate::concolic::Summary { queries: 3, models: 1, solver: crate::concolic::SolverState::Ran }), }; let row = Row::from(&r); assert_eq!(Row::from_json(&row.to_json()), Some(row.clone())); diff --git a/decompiler/crates/kuna-verify/src/state/mod.rs b/decompiler/crates/kuna-verify/src/state/mod.rs index 79cb009959..8f1d9bd1af 100644 --- a/decompiler/crates/kuna-verify/src/state/mod.rs +++ b/decompiler/crates/kuna-verify/src/state/mod.rs @@ -150,6 +150,10 @@ pub struct Env<'p> { /// says it preserves, as it left them: the rerun that tells whether a /// violation decides a run. pub keep_clobbers: Cell, + /// C5: input bytes a z3 model sets for this run, over the random state. + pub concolic_inputs: RefCell>, + /// C5: the machine records its path on this run. + pub record_path: Cell, /// ARM and AArch64 divide by zero to 0 instead of trapping. pub divide_by_zero_is_zero: bool, /// Image pages by base address; `None` for a page not mapped whole. @@ -295,6 +299,8 @@ impl<'p> Env<'p> { kernel: Cell::new(true), stub_recovered: Cell::new(false), keep_clobbers: Cell::new(false), + concolic_inputs: RefCell::new(None), + record_path: Cell::new(false), divide_by_zero_is_zero: ["ARM", "AARCH64"].iter().any(|a| prog.arch().archid.starts_with(a)), image: RefCell::new(HashMap::default()), mapped, @@ -421,6 +427,9 @@ impl<'p> Env<'p> { } fn random_byte(&self, run: u32, space: &AddrSpace, off: u64) -> u8 { + if let Some(b) = self.concolic_inputs.borrow().as_ref().and_then(|m| m.get(&(space.get_index(), off))) { + return *b; + } let g = u64::from(self.granule); Self::byte_of(self.word(run, space.get_index(), off / g), off % g, g, space.is_big_endian()) } @@ -560,6 +569,46 @@ impl<'p> Env<'p> { self.clobbered_byte(run, call + 1, &self.register, off) } + /// C5: where an input byte is, when the run's random state chooses the + /// byte at `off`: not a tracked register, the stack pointer, the extended + /// part of an argument, the image, the frame below the entry stack + /// pointer, or a temporary. + pub fn input_place(&self, space: &AddrSpace, off: u64) -> Option { + let idx = space.get_index(); + let place = |boolean| Some(crate::concolic::Place { space: idx, off, boolean }); + if self.tracked.iter().any(|&(sp, t, size, _)| sp == idx && off >= t && off < t + u64::from(size)) { + return None; + } + if let Some(&(_, b, size)) = self.booleans.iter().find(|&&(sp, b, size)| sp == idx && off >= b && off < b + u64::from(size)) { + let low = if space.is_big_endian() { b + u64::from(size) - 1 } else { b }; + return if off == low { place(true) } else { None }; + } + if self.unique.as_ref().is_some_and(|u| u.get_index() == idx) { + return None; + } + if idx == self.register.get_index() { + let (sp_off, sp_size) = self.sp; + if off >= sp_off && off < sp_off + u64::from(sp_size) { + return None; + } + let extended = self.extensions.iter().any(|x| { + let (c, cs) = x.container; + let (p, ps) = x.param; + x.space == idx && off >= c && off < c + u64::from(cs) && !(off >= p && off < p + u64::from(ps)) + }); + return if extended { None } else { place(false) }; + } + if idx == self.ram.get_index() { + if self.in_stack(off, 1) { + return if off >= self.sp0 { place(false) } else { None }; + } + if self.image_byte(off).is_some() { + return None; + } + } + place(false) + } + pub fn initial_byte(&self, run: u32, space: &AddrSpace, off: u64) -> u8 { let idx = space.get_index(); if let Some(&(_, t, size, val)) = diff --git a/decompiler/crates/kuna-verify/src/tools/concolic.rs b/decompiler/crates/kuna-verify/src/tools/concolic.rs new file mode 100644 index 0000000000..a8df325791 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/tools/concolic.rs @@ -0,0 +1,560 @@ +//! diffverify C5: concolic inputs. A machine run can record, next to each +//! value, an expression over the function's input bytes, and the condition of +//! every branch the function's own code takes. Negating one branch of a +//! recorded path, with the path before it held, gives z3 a question whose model +//! is an input that takes the other way. The model's bytes replace those inputs +//! in a new run, the rest of the state stays the base run's, and both sides +//! run and compare as on any run: z3 only picks inputs, it never decides a +//! verdict. +//! +//! An input byte is one whose value the run's random state chose: a register +//! or stack argument, or memory outside the image and the frame. A value that +//! goes through an operation the encoding does not cover, a call, or memory a +//! call may change, is concrete from there on; a model that misses its branch +//! for that is only a run that did not reach it. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::fmt::Write as _; +use std::io::Write as _; +use std::process::{Command, Stdio}; +use std::rc::Rc; + +use kuna_num::opcodes::OpCode; + +/// A bit-vector expression; booleans are one byte, 0 or 1, as in p-code. +#[derive(Debug)] +pub enum Expr { + /// An input byte. + Var(Rc), + Const(u128, u32), + Op(&'static str, Vec>, u32), + Extract(Rc, u32, u32), + Concat(Vec>), + ZeroExt(Rc, u32), + SignExt(Rc, u32), + /// `(ite (op a b) 1 0)` as one byte. + Test(&'static str, Rc, Rc), + /// Select an arm using a nonzero bit-vector guard. + Select(Rc, Rc, Rc), + /// A signed overflow test of `+` (`true`) or `-`, as one byte. + Overflow(bool, Rc, Rc), +} + +impl Expr { + pub fn width(&self) -> u32 { + match self { + Expr::Var(_) => 8, + Expr::Const(_, w) | Expr::Op(_, _, w) => *w, + Expr::Extract(_, hi, lo) => hi - lo + 1, + Expr::Concat(parts) => parts.iter().map(|p| p.width()).sum(), + Expr::ZeroExt(e, k) | Expr::SignExt(e, k) => e.width() + k, + Expr::Test(..) | Expr::Overflow(..) => 8, + Expr::Select(_, yes, _) => yes.width(), + } + } +} + +fn konst(v: u128, w: u32) -> Rc { + let m = if w >= 128 { u128::MAX } else { (1u128 << w) - 1 }; + Rc::new(Expr::Const(v & m, w)) +} + +fn fit(e: Rc, w: u32) -> Rc { + let ew = e.width(); + match ew.cmp(&w) { + std::cmp::Ordering::Equal => e, + std::cmp::Ordering::Less => Rc::new(Expr::ZeroExt(e, w - ew)), + std::cmp::Ordering::Greater => Rc::new(Expr::Extract(e, w - 1, 0)), + } +} + +/// The expression of p-code op `opc` with output `out` bytes over `ins`, each +/// an expression or a concrete value of its size; `None` for an op the +/// encoding does not cover (the output is then concrete). +pub fn op(opc: OpCode, out: u32, ins: &[(Option>, u128, u32)]) -> Option> { + if ins.iter().all(|(e, _, _)| e.is_none()) { + return None; + } + let ow = out * 8; + let arg = |k: usize| -> Option> { + let (e, v, s) = ins.get(k)?; + Some(e.clone().unwrap_or_else(|| konst(*v, s * 8))) + }; + let same = |a: &Rc, b: &Rc| a.width() == b.width(); + use OpCode::*; + let bin = |name: &'static str| -> Option> { + let (a, b) = (arg(0)?, arg(1)?); + (same(&a, &b) && a.width() == ow).then(|| Rc::new(Expr::Op(name, vec![a, b], ow))) + }; + let test = |name: &'static str, swap: bool| -> Option> { + let (a, b) = (arg(0)?, arg(1)?); + if !same(&a, &b) || out != 1 { + return None; + } + Some(Rc::new(if swap { Expr::Test(name, b, a) } else { Expr::Test(name, a, b) })) + }; + let truth = |a: Rc| Rc::new(Expr::Test("distinct", a.clone(), konst(0, a.width()))); + let logic = |name: &'static str| -> Option> { + let (a, b) = (arg(0)?, arg(1)?); + (ow == 8).then(|| Rc::new(Expr::Op(name, vec![truth(a), truth(b)], 8))) + }; + let shift = |name: &'static str, signed: bool| -> Option> { + let (a, b) = (arg(0)?, arg(1)?); + if a.width() != ow { + return None; + } + let wide = ow.max(b.width()) + 1; + let a = if signed { Rc::new(Expr::SignExt(a, wide - ow)) } else { fit(a, wide) }; + let r = Rc::new(Expr::Op(name, vec![a, fit(b, wide)], wide)); + Some(Rc::new(Expr::Extract(r, ow - 1, 0))) + }; + match opc { + CPUI_COPY | CPUI_CAST => arg(0).filter(|a| a.width() == ow), + CPUI_INT_ADD => bin("bvadd"), + CPUI_INT_SUB => bin("bvsub"), + CPUI_INT_MULT => bin("bvmul"), + CPUI_INT_DIV => bin("bvudiv"), + CPUI_INT_SDIV => bin("bvsdiv"), + CPUI_INT_REM => bin("bvurem"), + CPUI_INT_SREM => bin("bvsrem"), + CPUI_INT_AND => bin("bvand"), + CPUI_INT_OR => bin("bvor"), + CPUI_INT_XOR => bin("bvxor"), + CPUI_BOOL_AND => logic("bvand"), + CPUI_BOOL_OR => logic("bvor"), + CPUI_BOOL_XOR => logic("bvxor"), + CPUI_INT_NEGATE => arg(0).filter(|a| a.width() == ow).map(|a| Rc::new(Expr::Op("bvnot", vec![a], ow))), + CPUI_INT_2COMP => arg(0).filter(|a| a.width() == ow).map(|a| Rc::new(Expr::Op("bvneg", vec![a], ow))), + CPUI_BOOL_NEGATE => arg(0).filter(|_| ow == 8).map(|a| Rc::new(Expr::Test("=", a.clone(), konst(0, a.width())))), + CPUI_INT_LEFT => shift("bvshl", false), + CPUI_INT_RIGHT => shift("bvlshr", false), + CPUI_INT_SRIGHT => shift("bvashr", true), + CPUI_INT_EQUAL => test("=", false), + CPUI_INT_NOTEQUAL => test("distinct", false), + CPUI_INT_LESS => test("bvult", false), + CPUI_INT_SLESS => test("bvslt", false), + CPUI_INT_LESSEQUAL => test("bvule", false), + CPUI_INT_SLESSEQUAL => test("bvsle", false), + CPUI_INT_CARRY => { + let (a, b) = (arg(0)?, arg(1)?); + if !same(&a, &b) || out != 1 { + return None; + } + let sum = Rc::new(Expr::Op("bvadd", vec![a.clone(), b], a.width())); + Some(Rc::new(Expr::Test("bvult", sum, a))) + } + CPUI_INT_SCARRY | CPUI_INT_SBORROW => { + let (a, b) = (arg(0)?, arg(1)?); + (same(&a, &b) && out == 1).then(|| Rc::new(Expr::Overflow(opc == CPUI_INT_SCARRY, a, b))) + } + CPUI_INT_ZEXT => { + let a = arg(0)?; + (ow > a.width()).then(|| Rc::new(Expr::ZeroExt(a.clone(), ow - a.width()))) + } + CPUI_INT_SEXT => { + let a = arg(0)?; + (ow > a.width()).then(|| Rc::new(Expr::SignExt(a.clone(), ow - a.width()))) + } + CPUI_PIECE => { + let (hi, lo) = (arg(0)?, arg(1)?); + (hi.width() + lo.width() == ow).then(|| Rc::new(Expr::Concat(vec![hi, lo]))) + } + CPUI_SUBPIECE => { + let a = arg(0)?; + let (_, c, _) = ins.get(1)?; + let lo = u32::try_from(*c).ok()?.checked_mul(8)?; + let a = fit(a.clone(), a.width().max(lo + ow)); + Some(Rc::new(Expr::Extract(a, lo + ow - 1, lo))) + } + _ => None, + } +} + +/// The bytes of `e`, from the least significant. +pub fn byte(e: &Rc, i: u32) -> Rc { + Rc::new(Expr::Extract(Rc::clone(e), 8 * i + 7, 8 * i)) +} + +/// One recorded branch of the function's own code: its instruction's address, +/// the index of its p-code op in that instruction, its condition, and whether +/// it was taken. +#[derive(Clone)] +pub struct Branch { + pub at: u64, + pub op: u32, + pub cond: Rc, + pub taken: bool, +} + +/// An input byte's place: space index and offset. A `bool` argument's byte +/// is 0 or 1. +#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)] +pub struct Place { + pub space: i32, + pub off: u64, + pub boolean: bool, +} + +/// A recorded run: its branches and the input bytes they read. +#[derive(Clone, Default)] +pub struct Path { + pub branches: Vec, + pub inputs: BTreeMap, Place>, +} + +/// Input bytes a model sets. +pub type Inputs = Rc>; + +#[derive(Default)] +pub(crate) struct Emitter { + ids: HashMap<*const Expr, usize>, + defs: String, +} + +impl Emitter { + pub(crate) fn name(&mut self, e: &Rc) -> String { + if let Expr::Var(v) = &**e { + return v.to_string(); + } + let key = Rc::as_ptr(e); + if let Some(&id) = self.ids.get(&key) { + return format!("n{id}"); + } + let body = match &**e { + Expr::Var(_) => unreachable!(), + Expr::Const(v, w) => format!("(_ bv{v} {w})"), + Expr::Op(name, args, _) => { + let a: Vec = args.iter().map(|x| self.name(x)).collect(); + format!("({name} {})", a.join(" ")) + } + Expr::Extract(x, hi, lo) => format!("((_ extract {hi} {lo}) {})", self.name(x)), + Expr::Concat(parts) => { + let a: Vec = parts.iter().map(|x| self.name(x)).collect(); + if a.len() == 1 { a[0].clone() } else { format!("(concat {})", a.join(" ")) } + } + Expr::ZeroExt(x, k) => format!("((_ zero_extend {k}) {})", self.name(x)), + Expr::SignExt(x, k) => format!("((_ sign_extend {k}) {})", self.name(x)), + Expr::Test(name, a, b) => format!("(ite ({name} {} {}) #x01 #x00)", self.name(a), self.name(b)), + Expr::Select(guard, yes, no) => format!( + "(ite (distinct {} (_ bv0 {})) {} {})", + self.name(guard), guard.width(), self.name(yes), self.name(no) + ), + Expr::Overflow(add, a, b) => { + let (x, y, w) = (self.name(a), self.name(b), a.width()); + let r = if *add { format!("(bvadd {x} {y})") } else { format!("(bvsub {x} {y})") }; + let sign = |t: &str| format!("((_ extract {} {}) {t})", w - 1, w - 1); + let cond = if *add { + format!("(and (= {} {}) (distinct {} {}))", sign(&x), sign(&y), sign(&x), sign(&r)) + } else { + format!("(and (distinct {} {}) (distinct {} {}))", sign(&x), sign(&y), sign(&x), sign(&r)) + }; + format!("(ite {cond} #x01 #x00)") + } + }; + let id = self.ids.len(); + self.ids.insert(key, id); + let _ = writeln!(self.defs, "(define-fun n{id} () (_ BitVec {}) {body})", e.width()); + format!("n{id}") + } +} + +/// One z3 process kept for a function's queries: each query is pushed, +/// checked and popped, so z3 starts once. +pub struct Solver { + child: std::process::Child, + out: std::io::BufReader, +} + +impl Solver { + fn start(millis: u32) -> Option { + let mut child = Command::new("z3") + .args(["-in", "-smt2", &format!("-t:{millis}")]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let out = std::io::BufReader::new(child.stdout.take()?); + let mut s = Solver { child, out }; + s.send("(set-option :print-success false)\n(set-logic QF_BV)\n")?; + Some(s) + } + + fn send(&mut self, text: &str) -> Option<()> { + let stdin = self.child.stdin.as_mut()?; + stdin.write_all(text.as_bytes()).ok()?; + stdin.flush().ok() + } + + fn line(&mut self) -> Option { + let mut l = String::new(); + (std::io::BufRead::read_line(&mut self.out, &mut l).ok()? > 0).then_some(l) + } + + /// One balanced s-expression of the output. + fn sexpr(&mut self) -> Option { + let mut text = String::new(); + let mut depth = 0i32; + loop { + let l = self.line()?; + depth += l.matches('(').count() as i32 - l.matches(')').count() as i32; + text.push_str(&l); + if depth <= 0 && text.contains('(') { + return Some(text); + } + } + } +} + +impl Drop for Solver { + fn drop(&mut self) { + let _ = self.send("(exit)\n"); + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +/// What one query gave. +enum Answer { + Model(HashMap<(i32, u64), u8>), + /// Unsatisfiable, unknown in the time given, or nothing to ask. + None, + /// z3 did not answer as expected: the process is not used again. + Broken, +} + +/// Ask z3 for inputs that hold `path.branches[..k]` and take `branches[k]` +/// the other way. The query's scope is popped whatever the answer. +fn solve(solver: &mut Solver, path: &Path, k: usize) -> Answer { + let mut em = Emitter { ids: HashMap::new(), defs: String::new() }; + let mut asserts = String::new(); + for (i, b) in path.branches[..=k].iter().enumerate() { + let c = em.name(&b.cond); + let taken = if i == k { !b.taken } else { b.taken }; + let _ = writeln!(asserts, "(assert ({} {c} #x00))", if taken { "distinct" } else { "=" }); + } + let mut script = String::from("(push 1)\n"); + let mut used = BTreeSet::new(); + for (name, place) in &path.inputs { + if em_mentions(&em, &asserts, name) { + used.insert(Rc::clone(name)); + let _ = writeln!(script, "(declare-const {name} (_ BitVec 8))"); + if place.boolean { + let _ = writeln!(script, "(assert (bvule {name} #x01))"); + } + } + } + if used.is_empty() { + return Answer::None; + } + script.push_str(&em.defs); + script.push_str(&asserts); + script.push_str("(check-sat)\n"); + if solver.send(&script).is_none() { + return Answer::Broken; + } + let names: Vec<&str> = used.iter().map(|n| &**n).collect(); + let answer = match solver.line().as_deref().map(str::trim) { + Some("sat") => match model(solver, path, &names) { + Some(m) => Answer::Model(m), + None => Answer::Broken, + }, + Some("unsat" | "unknown") => Answer::None, + _ => Answer::Broken, + }; + if solver.send("(pop 1)\n").is_none() { + return Answer::Broken; + } + answer +} + +/// The input bytes of a satisfiable query. +fn model(solver: &mut Solver, path: &Path, names: &[&str]) -> Option> { + solver.send(&format!("(get-value ({}))\n", names.join(" ")))?; + let text = solver.sexpr()?; + let mut model = HashMap::new(); + for name in names { + let at = text.find(&format!("({name} "))? + name.len() + 2; + let v = text[at..].split(|c: char| c == ')' || c.is_whitespace()).next()?; + let byte = if let Some(h) = v.strip_prefix("#x") { + u8::from_str_radix(h, 16).ok()? + } else { + u8::from_str_radix(v.strip_prefix("#b")?, 2).ok()? + }; + let place = path.inputs.get(*name)?; + model.insert((place.space, place.off), byte); + } + Some(model) +} + +fn em_mentions(em: &Emitter, asserts: &str, name: &str) -> bool { + let token = |s: &str| s.split(|c: char| c == '(' || c == ')' || c.is_whitespace()).any(|t| t == name); + token(&em.defs) || token(asserts) +} + +/// Which branch to flip next: across every recorded path, the first branch +/// whose other direction no run has taken. A direction is asked about once per +/// path prefix (the branches before it and how they went): unsatisfiable after +/// one prefix, it may not be after another. +#[derive(Default)] +pub struct Worklist { + solver: Option, + /// z3 could not be started. + pub unavailable: bool, + /// z3 stopped answering as expected and was not used again. + pub broken: bool, + paths: Vec<(u32, Option, Path)>, + covered: HashSet<(u64, u32, bool)>, + tried: HashSet<(u64, u32, bool, u64)>, + pub queries: u32, + pub found: u32, +} + +/// What concolic exploration did for one function. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Summary { + pub queries: u32, + pub models: u32, + pub solver: SolverState, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SolverState { + /// No branch needed a query. + Unused, + Ran, + Unavailable, + Broken, +} + +impl SolverState { + pub fn name(self) -> &'static str { + match self { + SolverState::Unused => "unused", + SolverState::Ran => "ran", + SolverState::Unavailable => "unavailable", + SolverState::Broken => "broken", + } + } +} + +fn prefix(branches: &[Branch]) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + for b in branches { + (b.at, b.op, b.taken).hash(&mut h); + } + h.finish() +} + +impl Worklist { + pub fn add(&mut self, run: u32, inputs: Option, path: Path) { + for b in &path.branches { + self.covered.insert((b.at, b.op, b.taken)); + } + self.paths.push((run, inputs, path)); + } + + pub fn summary(&self) -> Summary { + let solver = if self.unavailable { + SolverState::Unavailable + } else if self.broken { + SolverState::Broken + } else if self.queries > 0 { + SolverState::Ran + } else { + SolverState::Unused + }; + Summary { queries: self.queries, models: self.found, solver } + } + + /// The next run to make: its base run, the input bytes to set (the base + /// run's own merged with the model's), and the branch it aims at. + pub fn next(&mut self, max_queries: u32, millis: u32) -> Option<(u32, Inputs, u64)> { + let mut p = 0; + while p < self.paths.len() { + let n = self.paths[p].2.branches.len(); + for k in 0..n { + if self.queries >= max_queries || self.unavailable || self.broken { + return None; + } + let branches = &self.paths[p].2.branches; + let b = &branches[k]; + let want = (b.at, b.op, !b.taken); + if self.covered.contains(&want) || !self.tried.insert((want.0, want.1, want.2, prefix(&branches[..k]))) { + continue; + } + if self.solver.is_none() { + self.solver = Solver::start(millis); + if self.solver.is_none() { + self.unavailable = true; + return None; + } + } + self.queries += 1; + let solver = self.solver.as_mut()?; + match solve(solver, &self.paths[p].2, k) { + Answer::Model(model) => { + self.found += 1; + let (run, base, _) = &self.paths[p]; + let mut inputs: HashMap<(i32, u64), u8> = base.as_deref().cloned().unwrap_or_default(); + inputs.extend(model); + return Some((*run, Rc::new(inputs), want.0)); + } + Answer::None => {} + Answer::Broken => { + self.solver = None; + self.broken = true; + return None; + } + } + } + p += 1; + } + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eval(e: &Expr) -> u128 { + match e { + Expr::Const(v, _) => *v, + Expr::Op(name, a, w) => { + let (x, y) = (eval(&a[0]), a.get(1).map_or(0, |b| eval(b))); + let v = match *name { + "bvand" => x & y, + "bvor" => x | y, + "bvxor" => x ^ y, + other => panic!("{other}"), + }; + v & ((1u128 << w) - 1) + } + Expr::Test(name, a, b) => { + let (x, y) = (eval(a), eval(b)); + u128::from(match *name { + "=" => x == y, + "distinct" => x != y, + other => panic!("{other}"), + }) + } + other => panic!("{other:?}"), + } + } + + /// p-code's boolean ops read any nonzero byte as true, as the concrete + /// evaluator does, and give 0 or 1. + #[test] + fn boolean_ops_normalize_their_inputs() { + let two = Rc::new(Expr::Const(2, 8)); + let ins = |a: &Rc, b: u128| vec![(Some(Rc::clone(a)), 0, 1), (None, b, 1)]; + let at = |opc, ins: &[(Option>, u128, u32)]| eval(&op(opc, 1, ins).unwrap()); + assert_eq!(at(OpCode::CPUI_BOOL_AND, &ins(&two, 1)), 1); + assert_eq!(at(OpCode::CPUI_BOOL_OR, &ins(&two, 1)), 1); + assert_eq!(at(OpCode::CPUI_BOOL_XOR, &ins(&two, 1)), 0); + assert_eq!(at(OpCode::CPUI_BOOL_NEGATE, &[(Some(two), 0, 1)]), 0); + assert_eq!(at(OpCode::CPUI_INT_AND, &ins(&Rc::new(Expr::Const(2, 8)), 1)), 0); + } +} diff --git a/decompiler/crates/kuna-verify/src/tools/mod.rs b/decompiler/crates/kuna-verify/src/tools/mod.rs index 29c8f1427d..fdc3359542 100644 --- a/decompiler/crates/kuna-verify/src/tools/mod.rs +++ b/decompiler/crates/kuna-verify/src/tools/mod.rs @@ -1,4 +1,6 @@ -//! Tools built on the check: rule localization and mutation testing. +//! Tools built on the check: rule localization, mutation testing and concolic +//! inputs. +pub mod concolic; pub mod localize; pub mod mutate; diff --git a/decompiler/crates/kuna-verify/tests/verdict_guards.rs b/decompiler/crates/kuna-verify/tests/verdict_guards.rs index 702fadd05e..b1e837bc94 100644 --- a/decompiler/crates/kuna-verify/tests/verdict_guards.rs +++ b/decompiler/crates/kuna-verify/tests/verdict_guards.rs @@ -876,3 +876,46 @@ fn a_mutant_checked_on_shared_runs_ends_as_it_does_alone() { assert!(operators.contains("NoReturn") && operators.contains("Branch") && operators.contains("Constant"), "{operators:?}"); assert!(killed > 0); } + +/// C5: `x == 0x1badb002` is a branch no random run takes; with concolic +/// queries z3 gives the input that takes it, and one more run agrees. Skipped +/// where z3 is not installed. +#[test] +fn concolic_inputs_reach_a_branch_random_runs_miss() { + if Command::new("z3").arg("-version").output().is_err() { + assert!(std::env::var_os("KUNA_REQUIRE_Z3").is_none(), "KUNA_REQUIRE_Z3 is set and z3 does not run"); + return; + } + let text = [ + 0x55, 0x48, 0x89, 0xe5, 0x89, 0xf9, 0x83, 0xe1, 0x01, 0x81, 0xff, 0x02, 0xb0, 0xad, 0x1b, 0xb8, 0x07, 0x00, 0x00, 0x00, + 0x0f, 0x45, 0xc1, 0x5d, 0xc3, + ]; + let path = object("magic", &text, &[("magic", 0, text.len() as u64)], &[]); + let report = |concolic| check(&path, &["magic"], &Options { runs: 64, concolic, ..Options::default() }).remove(0); + assert_eq!(report(0).verdict.label(), "AGREES(64)"); + let r = report(8); + assert_eq!(r.verdict.label(), "AGREES(65)"); + let s = r.concolic.unwrap(); + assert_eq!((s.models, s.solver), (1, kuna_verify::concolic::SolverState::Ran), "{}", r.render()); +} + +/// `--concolic` with no z3 to run says so, in the lines and the JSON, instead +/// of an `AGREES` that looks like the random runs and the concolic ones both +/// passed. +#[test] +fn concolic_without_z3_says_so() { + let text = [ + 0x55, 0x48, 0x89, 0xe5, 0x89, 0xf9, 0x83, 0xe1, 0x01, 0x81, 0xff, 0x02, 0xb0, 0xad, 0x1b, 0xb8, 0x07, 0x00, 0x00, 0x00, + 0x0f, 0x45, 0xc1, 0x5d, 0xc3, + ]; + let path = object("magic_noz3", &text, &[("magic", 0, text.len() as u64)], &[]); + let out = Command::new(env!("CARGO_BIN_EXE_kuna-verify")) + .args(["check", &path.to_string_lossy(), "magic", "--runs", "16", "--concolic", "4", "--json", "--sleighpath", &specs()]) + .env("PATH", "") + .output() + .unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + let row: serde_json::Value = text.lines().find(|l| l.starts_with('{')).map(|l| serde_json::from_str(l).unwrap()).unwrap(); + assert_eq!(row["z3"]["solver"], "unavailable", "{text}"); + assert!(row["lines"].as_array().unwrap().iter().any(|l| l.as_str().unwrap().contains("z3 could not be started")), "{text}"); +} diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md index c27b980da0..1879dde7f8 100644 --- a/docs/features/diffverify/README.md +++ b/docs/features/diffverify/README.md @@ -131,11 +131,12 @@ error, and 0 otherwise. With `--baseline`, it is 1 only for a regression (§6). | `memory before call N` / `memory at exit` | the first byte that differs, and how many do | | `kuna's result depends on ... which its C never assigns` | rerunning kuna's side with another value there changes its result: the C reads something it never set | | `note` | not a difference: runs left out (trapped on both sides, or ended at a call only kuna says does not return), a call the machine ran itself | +| `concolic` | with `--concolic`: z3 queries, the inputs found, and whether z3 ran | | `trace` | with `--trace`: every call of the failing run on each side | | `PROTOTYPE_SUSPECT(...)` | kuna's prototype for this function or a callee disagrees with what the run showed. This is not a verdict. | `--json` prints the same as one object per function (`function`, `verdict`, `label`, -`run`, `lines`, `suspects`, `ms`). A summary line follows. +`run`, `lines`, `suspects`, `ms`, and `z3` with `--concolic`). A summary line follows. ## 4. Commands @@ -144,7 +145,7 @@ kuna-verify check ... | --all [--jobs N] [--fn-second kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] [--file-seconds S] -common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] +common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--concolic QUERIES (0)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] ``` - **`check`** loads a binary with the options `kuna decompile` turns on (the Listing, and @@ -172,6 +173,9 @@ common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--call-reruns N (4) - **`mutate`** plants faults in kuna's side and reports how many the check catches (`mutation.md`). A file or function that fails to load, or a worker that fails to finish, gives exit status 3. +- **`--concolic N`** adds up to `N` z3 queries per function, for inputs that take a branch + the random runs did not. z3 only picks inputs; the verdict still comes from running both + sides (`c5-results.md`). ## 5. How a check runs @@ -230,7 +234,7 @@ The crate is grouped by folder; the old module paths (`crate::check`, `crate::ca | `graph/` | `mod.rs`, `program.rs` | kuna's side: compiling a `Funcdata` for repeated runs, and running it | | `abi/` | `mod.rs`, `calls.rs`, `contract.rs`, `divergence.rs` | calling conventions, per-call facts both sides share, C contracts, declared divergences | | `compare/` | `check.rs`, `observe.rs`, `setup.rs` | the runs and the verdict; comparing calls, memory and system calls; each run's starting state | -| `tools/` | `localize.rs`, `mutate.rs` | rule localization, mutation testing | +| `tools/` | `localize.rs`, `mutate.rs`, `concolic.rs` | rule localization, mutation testing, z3 inputs | | `report/` | `mod.rs`, `baseline.rs` | output; the corpus baseline | A later tier gets a folder of its own (`symbolic/` for Tier S, `printer/` for Tier P). @@ -363,10 +367,9 @@ run yet. owns and kuna may fold into variables, and then the caller's frame; a write there is not compared yet. Telling the two apart needs the incoming argument area's size from the machine side, not from kuna's prototype. -- **Replaying a counterexample.** A `DIFFERS` prints its inputs as text; there is no - `--replay` of a saved input. -- **Inputs random runs rarely hit.** A branch taken on one value in 2^32 is seldom - run. Concolic inputs from z3 (slice C5, `proposal.md`) are a separate change. +- **Replaying a counterexample, and concolic paths of failed runs.** A `DIFFERS` + prints its inputs as text; there is no `--replay` of a saved input, and a run that + ran past the budget or trapped gives the concolic worklist no branches. - **Unmapped stack arguments.** The x86-32 `cdecl` replay starts from stack slots identified by call recovery and uses the callee's reads to check those slots. Finding outgoing arguments that call recovery missed entirely requires independent evidence @@ -409,7 +412,7 @@ run yet. checked to be a call to that stub. Where the stub leads comes from relocations the machine side does not apply, so kuna's choice of target is not checked. - **Speed.** Comparing memory by page rather than by byte, a lifting cache shared by a - worker's functions. None is at the top of the + worker's functions, and overlapping z3 queries with runs. None is at the top of the current profile. - **The pull-request experiment** of §7 has not been run. @@ -424,6 +427,7 @@ run yet. | `c3-results.md` | slice C3: rule localization | | `c4-results.md` | slice C4 on the test corpus: precision and recall against restored bugs | | `c4-decbench-results.md` | slice C4 on the decbench binaries: harness defects found, every `DIFFERS` sorted by cause, the issues filed | +| `c5-results.md` | slice C5: concolic inputs | | `triage.md` | how to decide whether a difference is the spec's, the emulator's, the checker's or the harness's | | `mutation.md` | mutation testing: what share of planted faults the check catches | | `record.json` | the slices' measured numbers, for scripts | diff --git a/docs/features/diffverify/c4-decbench-results.md b/docs/features/diffverify/c4-decbench-results.md index 9bdb307406..52c01b73ad 100644 --- a/docs/features/diffverify/c4-decbench-results.md +++ b/docs/features/diffverify/c4-decbench-results.md @@ -201,8 +201,8 @@ of the 249 agrees after #1924 or #1927. | i386 stack offsets after `memset`/`memcpy` | 4 | #1920 | | a return widened in a tail-call cycle | 2 | #1921 | -`transfer_entries` does not differ again: 64 concolic z3 queries (slice C5) over -eight seeds give `AGREES` or `UNKNOWN(budget)`. +`transfer_entries` (`c5-results.md` §2) does not differ again: `--concolic 64` over +eight seeds gives `AGREES` or `UNKNOWN(budget)`. ### The budget rule diff --git a/docs/features/diffverify/c5-results.md b/docs/features/diffverify/c5-results.md new file mode 100644 index 0000000000..d7e678f1ca --- /dev/null +++ b/docs/features/diffverify/c5-results.md @@ -0,0 +1,96 @@ +# diffverify — slice C5 results (concolic inputs) + +C5 adds inputs that random runs do not reach. A machine run can record an expression +over the function's input bytes next to each value, and the condition of each branch the +function's own code takes. Negating one branch, with the branches before it held, is a +question for z3 whose model is an input that goes the other way. The model's bytes +replace those inputs in a new run, and both sides run and compare as on any run. z3 only +picks inputs; it never decides a verdict. + +```sh +kuna-verify check ... --concolic 16 +``` + +`--concolic N` spends up to `N` z3 queries per function after its random runs. With 0, +the default, nothing changes: the corpus baseline is the same. + +## 1. How it works + +- **Input bytes** (`Env::input_place`) are the ones the run's random state chooses: + - register and stack arguments; + - memory outside the image and the frame, before any call. + + Not inputs: tracked registers, the stack pointer, the extended part of an argument, and + temporaries. A `bool` argument's byte is constrained to 0 or 1. +- **Expressions** (`src/tools/concolic.rs`) cover integer arithmetic, logic, shifts, + comparisons, carries, extensions, `PIECE` and `SUBPIECE`. A value that goes through + anything else, through a call, or through memory a call may change, is concrete from + there on. Each byte's expression is kept with the byte's concrete value. A later + overwrite the recording does not follow (a callee, a stub) changes the value and drops + the expression. +- **Branches:** only the function's own code is recorded, internal p-code branches + included (an x86 `cmov` is one). Up to 256 branches per path are kept, from the first 16 + random runs and from every concolic run. +- **Choosing a query:** the worklist takes, over every recorded path, the first branch + whose other direction no run has taken. A branch is its instruction's address and + the index of its p-code op there, so the branches inside one instruction (a `rep` + prefix's count test and the loop's) are told apart. A direction is asked about once + per path prefix, the branches before it and how they went: unsatisfiable after one + prefix, it can be satisfiable after another. +- **z3:** one process per function, each query pushed and popped, with 300 ms per + query. The scope is popped whatever the answer; an answer that is not `sat`, + `unsat` or `unknown`, or a model that does not parse, ends the use of that process. + A model's bytes are merged with the base run's, so the rest of the state stays the + base run's. +- **Booleans:** p-code's `BOOL_AND`, `BOOL_OR`, `BOOL_XOR` and `BOOL_NEGATE` read any + nonzero byte as true, as the concrete evaluation does; the encoding tests each input + against zero before combining them, so a byte other than 0 or 1 is not read + bitwise. +- **Reports:** a `DIFFERS` on a concolic run says so: + `concolic an input z3 gave to take the branch at 0x… the other way`. Every function + checked with `--concolic` gets a line `concolic N z3 queries, M inputs found`, and + in `--json` a `z3` object (`queries`, `models`, `solver`: `ran`, `unused`, + `unavailable` or `broken`). Without z3 the line says that no concolic run was made, + so an `AGREES` from the random runs alone is not read as a concolic one. +- **Determinism:** results are the same from run to run and for any `--jobs`, because + the queries are made in a fixed order. + +## 2. Results + +**A branch random runs miss.** `magic(x)` returns 7 when `x == 0x1badb002`. A local +fault, never committed, made kuna compare against `0x1badb003`: + +| | without `--concolic` | `--concolic 16` | +|---|---|---| +| `magic`, fault in kuna | `AGREES(256)` | `DIFFERS`: `x=0x1badb002`, `machine EAX = 7`, `kuna = 0` | + +**The decbench sample set** (250 functions), `--concolic 16`: +- 49 functions get one or more concolic runs, 80 runs in all. +- No new `DIFFERS`. +- Two functions become `DIVERGES(divide-by-zero)`: Betaflight `mspProcessInCommand` + and `usart_set_baudrate`. z3 found a zero divisor no random run had. ARM and AArch64 + divide by zero to 0, which the machine side now models. kuna's C `/` is undefined + there, so this is a declared divergence, not a kuna bug. +- One function becomes `UNKNOWN(budget)`: the concolic input sent `parseRFCStructuredData` + around a long loop. + +**`coreutils` `ls`** (`O2`, 405 functions, ten workers), as first measured: +- 105 functions get 237 concolic runs. +- Wall time goes from 3.3 s to 13.4 s. + - With a z3 process per query it was 41 s. + - With 2 s per query it was 58 s. + +With the path-aware worklist, z3 runs for 140 functions: 697 queries, 454 inputs found, +33.6 s against 13.2 s without `--concolic` on a machine busy with other builds. The +verdicts are the same. + +One run with a z3 process per query reported `transfer_entries` `DIFFERS`: kuna's loop +calls the hash function once more before `abort()` than the machine does. The +persistent solver gives other models and does not reach it. It is not triaged yet. + +## 3. Recall + +C4 §6's misses are mostly not path problems. Of its eleven remaining misses, only #564 +(`end == cap`) is one. #564's fix is no longer a guard that can be turned back alone: +forcing `access_cannot_reach_call` false leaves the stage test passing. So the recall +table is not re-measured. diff --git a/docs/features/diffverify/mutation.md b/docs/features/diffverify/mutation.md index f897c93bb0..da088b6319 100644 --- a/docs/features/diffverify/mutation.md +++ b/docs/features/diffverify/mutation.md @@ -7,7 +7,7 @@ many the check reports as `DIFFERS`. ```sh kuna-verify mutate tests/datatests tests/stages --jobs 10 # the test corpus -kuna-verify mutate --all --jobs 10 # a binary +kuna-verify mutate --all --jobs 10 [--concolic 16] # a binary kuna-verify mutate ... --per-function 6 --json # some functions ``` @@ -75,8 +75,8 @@ With the machine side's call facts kept apart from kuna's: | `opcode` | 79.0% | 79.4% | 75.6% | | `swap` | 78.2% | 89.3% | 79.6% | -Concolic inputs (slice C5, a separate change) at 16 z3 queries per function raised -`constant` on `ls` (measured before `noreturn` was added) from 57.8% to 70.4%. +`--concolic 16` raises `constant` on `ls` (measured before `noreturn` was added) from 57.8% +to 70.4%. `noreturn` on `ls` and `find` is mostly a claim about an imported function. It has no name the lists know and no body in the image to run, so the run ends on kuna's word and @@ -86,8 +86,8 @@ is not counted. That is 36 of 60 mutants on `ls` and 63 of 114 on `find`, report What is left, by kind: - **Values random runs rarely hit.** `x <= 9` against `x < 9`, a constant `0x3b9aca07` - against `0x3b9aca06`: the two differ on one input. Concolic inputs (slice C5) raise - `constant` on `ls` from 57.8% to 70.4%. + against `0x3b9aca06`: the two differ on one input. `--concolic` raises `constant` on `ls` + from 57.8% to 70.4%. - **Arguments a stub never reads.** A callee outside the image gets the stub, which does not depend on its integer arguments. An argument kuna drops along with a recovered parameter is seen only where the callee runs for real and reads it (`the callee reads From ded13a11b635e2095cf082e2c53969960f6b56b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 09:50:00 +0900 Subject: [PATCH 6/7] [AUTOMATED] Add Tier L to kuna-verify: one instruction's p-code against Unicorn `kuna-verify step` runs one instruction's SLEIGH p-code from random register values and prints each case as JSON; `scripts/diffverify/tier_l.py` runs the same cases under Unicorn and compares registers, flags, memory writes and the next address. Both sides of the Tier C check share the SLEIGH specs and the p-code op semantics, so this is the check that can see an error in either. Co-Authored-By: Claude Opus 5.5 --- .../crates/kuna-verify/src/bin/kuna-verify.rs | 44 +++ decompiler/crates/kuna-verify/src/lib.rs | 2 +- .../crates/kuna-verify/src/tools/mod.rs | 5 +- .../crates/kuna-verify/src/tools/step.rs | 332 ++++++++++++++++++ .../kuna-verify/tests/verdict_guards.rs | 22 ++ docs/features/diffverify/README.md | 16 +- docs/features/diffverify/proposal.md | 2 +- docs/features/diffverify/tier-l-results.md | 77 ++++ docs/features/diffverify/triage.md | 4 +- scripts/diffverify/tier_l.py | 230 ++++++++++++ 10 files changed, 722 insertions(+), 12 deletions(-) create mode 100644 decompiler/crates/kuna-verify/src/tools/step.rs create mode 100644 docs/features/diffverify/tier-l-results.md create mode 100644 scripts/diffverify/tier_l.py diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs index 45d8e008ef..6eb3f86b17 100644 --- a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -4,6 +4,7 @@ //! kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] //! kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... +//! kuna-verify step --regs R,R.. [--flags F,F..] [--states N] [--per-form N] [--limit N] [--canonical] //! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] //! common: [--runs N] [--seed S] [--budget OPS] [--concolic QUERIES] [--json] [--sleighpath DIR] //! ``` @@ -38,6 +39,7 @@ const USAGE: &str = "usage: kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... + kuna-verify step --regs R,R.. [--flags F,F..] [--states N] [--per-form N] [--limit N] [--canonical] kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] options: --runs N (256) --seed S --budget OPS (200000) --concolic QUERIES (0) --call-reruns N (4) --json --trace --sleighpath DIR"; @@ -56,6 +58,12 @@ struct Args { /// a worker process, which is what a time limit can stop. timed: bool, per_function: usize, + regs: Vec, + flags: Vec, + canonical: bool, + states: u32, + per_form: usize, + limit: usize, baseline: Option, save_baseline: Option, pass: Option, @@ -77,6 +85,12 @@ fn parse(argv: &[String]) -> Result { file_seconds: 1200, timed: false, per_function: 6, + regs: Vec::new(), + flags: Vec::new(), + canonical: false, + states: 4, + per_form: 2, + limit: 2000, baseline: None, save_baseline: None, pass: None, @@ -136,6 +150,14 @@ fn parse(argv: &[String]) -> Result { a.timed = true; } "--per-function" => a.per_function = num(it.next(), "--per-function")?.max(1) as usize, + "--regs" | "--flags" => { + let v: Vec = it.next().ok_or(format!("{arg} needs names"))?.split(',').filter(|s| !s.is_empty()).map(str::to_string).collect(); + if arg == "--regs" { a.regs = v } else { a.flags = v } + } + "--states" => a.states = num(it.next(), "--states")?.max(1) as u32, + "--canonical" => a.canonical = true, + "--per-form" => a.per_form = num(it.next(), "--per-form")?.max(1) as usize, + "--limit" => a.limit = num(it.next(), "--limit")? as usize, "--pass" => { let p = num(it.next(), "--pass")?; a.pass = Some(usize::try_from(p).ok().filter(|&p| p > 0).ok_or("--pass counts from 1")?); @@ -746,6 +768,27 @@ fn run_localize(a: &Args) -> Result { }) } +/// Tier L's kuna side: one JSON line per instruction and state. +fn run_step(a: &Args) -> Result { + let [binary] = a.positional.as_slice() else { + return Err(USAGE.to_string()); + }; + if a.regs.is_empty() { + return Err("step needs --regs".to_string()); + } + let roots = spec_roots(a.sleighpath.as_deref()); + let opts = + kuna_verify::step::Options { seed: a.opts.seed, states: a.states, per_form: a.per_form, limit: a.limit, sweep: 4096, canonical: a.canonical }; + session::with_program(binary, &a.options, &roots, |prog| { + let regs = kuna_verify::step::registers(prog, &a.regs, &a.flags)?; + let mut out = std::io::stdout().lock(); + kuna_verify::step::run(prog, ®s, &opts, |v| { + let _ = writeln!(out, "{v}"); + }) + })??; + Ok(ExitCode::SUCCESS) +} + /// `corpus`: the file count and the wall time of the whole run; a file count /// of 0 is a `check` run over workers, which has a wall time but no files. fn print_summary(a: &Args, slowest: &[(f64, String)], rows: &[Row], corpus: Option<(usize, f64)>) { @@ -798,6 +841,7 @@ fn main() -> ExitCode { "corpus" => run_corpus(&a), "shard" => run_shard(&a), "chunk" => run_chunk_worker(&a), + "step" => run_step(&a), "localize" => run_localize(&a), "mutate" => run_mutate(&a), _ => Err(USAGE.to_string()), diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs index 124d694d4c..a98f3554f4 100644 --- a/decompiler/crates/kuna-verify/src/lib.rs +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -26,7 +26,7 @@ pub use compare::check; pub use graph::program; pub use report::baseline; pub use semantics::{storage, value, x87}; -pub use tools::{concolic, localize, mutate}; +pub use tools::{concolic, localize, mutate, step}; use std::time::{Duration, Instant}; diff --git a/decompiler/crates/kuna-verify/src/tools/mod.rs b/decompiler/crates/kuna-verify/src/tools/mod.rs index fdc3359542..04b4016b92 100644 --- a/decompiler/crates/kuna-verify/src/tools/mod.rs +++ b/decompiler/crates/kuna-verify/src/tools/mod.rs @@ -1,6 +1,7 @@ -//! Tools built on the check: rule localization, mutation testing and concolic -//! inputs. +//! Tools built on the check: rule localization, mutation testing, concolic +//! inputs and Tier L's single-instruction step. pub mod concolic; pub mod localize; pub mod mutate; +pub mod step; diff --git a/decompiler/crates/kuna-verify/src/tools/step.rs b/decompiler/crates/kuna-verify/src/tools/step.rs new file mode 100644 index 0000000000..5075c4f2c3 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/tools/step.rs @@ -0,0 +1,332 @@ +//! diffverify Tier L, kuna's side: one instruction's p-code, run from a +//! random state of the named registers, with what it read from and wrote to +//! memory and where it goes next. A driver runs the same instruction from the +//! same state under Unicorn (`scripts/diffverify/tier_l.py`) and compares. +//! +//! The instruction's p-code and each op's semantics are the ones Tier C's +//! machine side runs (`machine::lift`, `value::eval`), so a difference here is +//! a difference in what the check believes the machine does. +//! +//! Instructions are picked per form: the mnemonic and its operands with every +//! number replaced, a few of each, from a linear sweep of each function. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::rc::Rc; + +use kuna_base::address::Address; +use kuna_base::space::{spacetype, AddrSpace}; +use kuna_console::engine::ConsoleProgram; +use kuna_num::opcodes::{get_opname, OpCode}; +use kuna_num::pcoderaw::VarnodeData; +use serde_json::{json, Value}; + +use crate::machine::lift; +use crate::state::Env; +use crate::value::{eval, mask, Inputs}; + +/// A register the driver sets and reads back: its name and storage. +pub struct Reg { + pub name: String, + pub offset: u64, + pub size: u32, + /// A one-byte flag, given 0 or 1. + pub flag: bool, +} + +pub struct Options { + pub seed: u64, + pub states: u32, + pub per_form: usize, + pub limit: usize, + pub sweep: usize, + /// Keep 8-byte registers below 2^47, so a pointer among them is one the + /// 48-bit virtual address space of x86-64 and AArch64 can hold. + pub canonical: bool, +} + +fn splitmix(mut z: u64) -> u64 { + z = z.wrapping_add(0x9e37_79b9_7f4a_7c15); + z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); + z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); + z ^ (z >> 31) +} + +/// The registers named in `names`, flags in `flags`. +pub fn registers(prog: &ConsoleProgram, names: &[String], flags: &[String]) -> Result, String> { + let mut out = Vec::new(); + for (n, flag) in names.iter().map(|n| (n, false)).chain(flags.iter().map(|n| (n, true))) { + let vn = prog.arch().translate().get_register_data(n).map_err(|_| format!("no register {n}"))?; + out.push(Reg { name: n.clone(), offset: vn.offset, size: vn.size, flag }); + } + Ok(out) +} + +struct Machine<'a> { + env: &'a Env<'a>, + register: i32, + regs: HashMap, + unique: HashMap, + mem: BTreeMap, + reads: BTreeMap, + writes: BTreeMap, + unlisted: BTreeSet, + seed: u64, +} + +impl Machine<'_> { + fn byte(&mut self, space: &Rc, off: u64) -> u8 { + let idx = space.get_index(); + if idx == self.register { + if let Some(&b) = self.regs.get(&off) { + return b; + } + let name = self.env.prog.arch().translate().as_sleigh().map(|s| s.base().get_register_name(space, off, 1)); + self.unlisted.insert(name.map(|n| String::from_utf8_lossy(&n).into_owned()).unwrap_or_else(|| format!("{off:#x}"))); + return 0; + } + if space.get_type() == spacetype::IPTR_INTERNAL { + return self.unique.get(&off).copied().unwrap_or(0); + } + if let Some(&b) = self.mem.get(&off) { + return b; + } + let image = self.env.prog.read_bytes_at(&Address::new(Rc::clone(space), off), 1).map(|v| v[0]); + let b = image.unwrap_or_else(|| splitmix(self.seed ^ off.wrapping_mul(0xc2b2_ae3d_27d4_eb4f)) as u8); + self.mem.insert(off, b); + self.reads.insert(off, b); + b + } + + fn put(&mut self, space: &Rc, off: u64, b: u8) { + let idx = space.get_index(); + if idx == self.register { + self.regs.insert(off, b); + } else if space.get_type() == spacetype::IPTR_INTERNAL { + self.unique.insert(off, b); + } else { + self.mem.insert(off, b); + self.writes.insert(off, b); + } + } + + fn read(&mut self, vn: &VarnodeData) -> Result { + let spc = vn.space.as_ref().ok_or("varnode without a space")?; + if spc.get_type() == spacetype::IPTR_CONSTANT { + return Ok(u128::from(vn.offset) & mask(vn.size)); + } + Ok(self.load(&Rc::clone(spc), vn.offset, vn.size)) + } + + fn load(&mut self, spc: &Rc, off: u64, size: u32) -> u128 { + let mut v = 0u128; + for i in 0..u64::from(size) { + let b = u128::from(self.byte(spc, spc.wrap_offset(off.wrapping_add(i)))); + v = if spc.is_big_endian() { (v << 8) | b } else { v | (b << (8 * i)) }; + } + v + } + + fn store(&mut self, spc: &Rc, off: u64, size: u32, v: u128) { + for i in 0..u64::from(size) { + let shift = if spc.is_big_endian() { u64::from(size) - 1 - i } else { i }; + self.put(spc, spc.wrap_offset(off.wrapping_add(i)), (v >> (shift * 8)) as u8); + } + } + + fn write(&mut self, vn: &VarnodeData, v: u128) -> Result<(), String> { + let spc = Rc::clone(vn.space.as_ref().ok_or("varnode without a space")?); + self.store(&spc, vn.offset, vn.size, v); + Ok(()) + } + + fn mem_space(&self, vn: &VarnodeData) -> Result, String> { + vn.get_space_from_const(self.env.prog.arch().manage()).ok_or_else(|| "bad LOAD/STORE space id".into()) + } + + /// Run the instruction at `addr`; the address it goes to next. + fn run(&mut self, addr: u64) -> Result { + let insn = lift(self.env, addr).map_err(|h| h.render())?; + let mut i = 0usize; + let mut steps = 0; + while i < insn.ops.len() { + steps += 1; + if steps > 100_000 { + return Err("the instruction's p-code does not finish".into()); + } + let op = &insn.ops[i]; + let arg = |k: usize| op.ins.get(k).ok_or_else(|| format!("{} lacks input {k}", get_opname(op.opc))); + match op.opc { + OpCode::CPUI_BRANCH | OpCode::CPUI_CBRANCH => { + let taken = op.opc == OpCode::CPUI_BRANCH || self.read(arg(1)?)? != 0; + if !taken { + i += 1; + continue; + } + let t = arg(0)?; + if t.space.as_ref().is_some_and(|s| s.get_type() == spacetype::IPTR_CONSTANT) { + i = (t.offset as u32).wrapping_add(i as u32) as i32 as usize; + continue; + } + return Ok(t.offset); + } + OpCode::CPUI_BRANCHIND | OpCode::CPUI_CALLIND | OpCode::CPUI_RETURN => return Ok(self.read(arg(0)?)? as u64), + OpCode::CPUI_CALL => return Ok(arg(0)?.offset), + OpCode::CPUI_CALLOTHER => { + let name = crate::program::userop_name(self.env.prog, arg(0)?.offset); + let quiet = crate::machine::EXIT_ONLY_USEROPS.contains(&name.as_str()) + || crate::machine::NO_EFFECT_USEROPS.contains(&name.as_str()); + if !(quiet && op.out.is_none()) { + return Err(format!("CALLOTHER {name}")); + } + } + OpCode::CPUI_LOAD => { + let spc = self.mem_space(arg(0)?)?; + let ptr = self.read(arg(1)?)? as u64; + let out = op.out.as_ref().ok_or("LOAD without output")?; + let at = spc.wrap_offset(AddrSpace::address_to_byte(ptr, spc.get_word_size())); + let v = self.load(&spc, at, out.size); + self.write(out, v)?; + } + OpCode::CPUI_STORE => { + let spc = self.mem_space(arg(0)?)?; + let ptr = self.read(arg(1)?)? as u64; + let val = arg(2)?; + let v = self.read(val)?; + let at = spc.wrap_offset(AddrSpace::address_to_byte(ptr, spc.get_word_size())); + self.store(&spc, at, val.size, v); + } + opc => { + let out = op.out.as_ref().ok_or_else(|| format!("{} without output", get_opname(opc)))?; + let mut ins = Inputs::default(); + for vn in &op.ins { + ins.push((self.read(vn)?, vn.size)); + } + let v = eval(opc, out.size, ins.as_slice()).map_err(|h| h.render())?; + self.write(out, v)?; + } + } + i += 1; + } + Ok(addr.wrapping_add(insn.len)) + } +} + +fn hex(v: u128) -> String { + format!("{v:#x}") +} + +/// The form an instruction is picked by: its mnemonic and operands with every +/// number replaced by `#`. +fn form(mnemonic: &str, body: &str) -> String { + let mut out = format!("{} ", mnemonic.to_lowercase()); + let mut in_number = false; + for c in body.chars() { + let digit = c.is_ascii_digit() || (in_number && (c.is_ascii_hexdigit() || c == 'x')); + if digit { + if !in_number { + out.push('#'); + } + in_number = true; + } else { + in_number = false; + out.push(c); + } + } + out +} + +/// Pick instructions from `prog` and run each from `opts.states` states. +pub fn run(prog: &ConsoleProgram, regs: &[Reg], opts: &Options, mut emit: impl FnMut(Value)) -> Result<(), String> { + let canonical = opts.canonical; + let env = Env::new(prog, opts.seed).map_err(|h| h.render())?; + let register = env.register.get_index(); + let sleigh = prog.arch().translate().as_sleigh().ok_or("not a SLEIGH translator")?; + let mut entries: Vec = prog + .function_entries_executable() + .into_iter() + .filter(|e| prog.entry_bytes_mapped(&e.addr)) + .map(|e| e.addr.get_offset()) + .collect(); + entries.sort_unstable(); + entries.dedup(); + let mut seen: HashMap = HashMap::new(); + let mut picked = 0usize; + let (mut mnemonic, mut body) = (String::new(), String::new()); + for (k, &entry) in entries.iter().enumerate() { + let end = entries.get(k + 1).copied().unwrap_or(u64::MAX); + let mut addr = entry; + for _ in 0..opts.sweep { + if addr >= end || picked >= opts.limit { + break; + } + let at = Address::new(Rc::clone(&env.code), addr); + let Ok(len) = sleigh.print_assembly_into(&at, &mut mnemonic, &mut body) else { break }; + let key = form(&mnemonic, &body); + let count = seen.entry(key.clone()).or_default(); + if *count < opts.per_form { + *count += 1; + picked += 1; + let bytes = prog.read_bytes_at(&at, len.max(1) as usize).unwrap_or_default(); + for s in 0..opts.states { + let seed = splitmix(opts.seed ^ addr.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ u64::from(s)); + emit(one(&env, register, regs, addr, &bytes, &mnemonic, &body, &key, seed, canonical)); + } + } + addr = addr.wrapping_add(len.max(1) as u64); + } + } + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn one(env: &Env, register: i32, regs: &[Reg], addr: u64, bytes: &[u8], mnemonic: &str, body: &str, key: &str, seed: u64, canonical: bool) -> Value { + let mut m = Machine { + env, + register, + regs: HashMap::new(), + unique: HashMap::new(), + mem: BTreeMap::new(), + reads: BTreeMap::new(), + writes: BTreeMap::new(), + unlisted: BTreeSet::new(), + seed, + }; + let mut input = serde_json::Map::new(); + for (k, r) in regs.iter().enumerate() { + let h = splitmix(seed ^ (k as u64 + 1).wrapping_mul(0xd6e8_feb8_6659_fd93)); + let v = if r.flag { + u128::from(h & 1) + } else if canonical && r.size == 8 { + u128::from(h & 0x7fff_ffff_ffff) + } else { + (u128::from(h) | (u128::from(splitmix(h)) << 64)) & mask(r.size) + }; + for i in 0..u64::from(r.size) { + m.regs.insert(r.offset + i, (v >> (8 * i)) as u8); + } + input.insert(r.name.clone(), json!(hex(v))); + } + let next = m.run(addr); + let mut output = serde_json::Map::new(); + for r in regs { + let mut v = 0u128; + for i in 0..u64::from(r.size) { + v |= u128::from(m.regs.get(&(r.offset + i)).copied().unwrap_or(0)) << (8 * i); + } + output.insert(r.name.clone(), json!(hex(v))); + } + let bytes_of = |map: &BTreeMap| map.iter().map(|(a, b)| (format!("{a:#x}"), json!(b))).collect::>(); + json!({ + "addr": hex(u128::from(addr)), + "bytes": bytes.iter().map(|b| format!("{b:02x}")).collect::(), + "asm": format!("{mnemonic} {body}").trim().to_string(), + "form": key, + "in": input, + "out": output, + "reads": bytes_of(&m.reads), + "writes": bytes_of(&m.writes), + "next": next.as_ref().map(|n| hex(u128::from(*n))).ok(), + "error": next.err(), + "unlisted": m.unlisted.into_iter().collect::>(), + }) +} diff --git a/decompiler/crates/kuna-verify/tests/verdict_guards.rs b/decompiler/crates/kuna-verify/tests/verdict_guards.rs index b1e837bc94..66ada58539 100644 --- a/decompiler/crates/kuna-verify/tests/verdict_guards.rs +++ b/decompiler/crates/kuna-verify/tests/verdict_guards.rs @@ -919,3 +919,25 @@ fn concolic_without_z3_says_so() { assert_eq!(row["z3"]["solver"], "unavailable", "{text}"); assert!(row["lines"].as_array().unwrap().iter().any(|l| l.as_str().unwrap().contains("z3 could not be started")), "{text}"); } + +/// Tier L's kuna side runs one instruction from the named registers: `sub rsp, +/// 8` moves the stack pointer down 8, `call rax` pushes the return address +/// and goes to `rax`, and the same seed gives the same lines. +#[test] +fn step_runs_one_instruction_from_the_named_registers() { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../kuna-analysis/tests/fixtures/katavm_level1_x86_64"); + let path = path.to_string_lossy().into_owned(); + let specs = specs(); + let args = ["step", &path, "--regs", "RSP,RAX", "--flags", "CF,ZF", "--limit", "8", "--states", "1", "--canonical", "--sleighpath", &specs]; + let out = verify(&args); + assert_eq!(out.status.code(), Some(0), "{}", String::from_utf8_lossy(&out.stderr)); + let text = String::from_utf8_lossy(&out.stdout).into_owned(); + let lines: Vec = text.lines().map(|l| serde_json::from_str(l).unwrap()).collect(); + let hex = |v: &serde_json::Value| u64::from_str_radix(v.as_str().unwrap().trim_start_matches("0x"), 16).unwrap(); + let sub = lines.iter().find(|l| l["form"] == "sub RSP,#").expect("a sub rsp"); + assert_eq!(hex(&sub["out"]["RSP"]), hex(&sub["in"]["RSP"]) - 8); + let call = lines.iter().find(|l| l["form"] == "call RAX").expect("a call rax"); + assert_eq!(hex(&call["next"]), hex(&call["in"]["RAX"])); + assert_eq!(call["writes"].as_object().unwrap().len(), 8); + assert_eq!(String::from_utf8_lossy(&verify(&args).stdout), text); +} diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md index 1879dde7f8..73ce9aca3f 100644 --- a/docs/features/diffverify/README.md +++ b/docs/features/diffverify/README.md @@ -59,10 +59,10 @@ ins16 DIFFERS (run 1 of 256) precedence, a type's spelling) is not in the IR, so `AGREES` cannot rule it out. That is Tier P, a separate axis (`proposal.md`). - **Shared semantics.** Both sides use the same p-code op semantics (`value.rs`). A wrong - op semantic, or a wrong SLEIGH spec, is the same on both sides and invisible here. So are - the calling-convention models (`.cspec`): where arguments and return values live, what - a call preserves and what it pops. Checking those against an independent emulator and - against compiled code is a later tier's job (Tier L, `proposal.md`). + op semantic, or a wrong SLEIGH spec, is the same on both sides and invisible here. Tier + L checks the spec and the op semantics against Unicorn, one instruction at a time + (`tier-l-results.md`). The calling-convention models (`.cspec`) are shared the same + way: where arguments and return values live, what a call preserves and what it pops. - **What the machine side takes from kuna.** It runs the machine code, but it still has to know where each call's arguments live and whether a call returns. It does not take kuna's word that a call does not return. It stops there only on evidence of its own: @@ -144,6 +144,7 @@ error, and 0 otherwise. With `--baseline`, it is 1 only for a regression (§6). kuna-verify check ... | --all [--jobs N] [--fn-seconds S] [--contract FILE.c] [--option NAME VALUE]... kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... +kuna-verify step --regs R,R.. [--flags F,F..] [--states N] [--per-form N] [--limit N] [--canonical] kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] [--file-seconds S] common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--concolic QUERIES (0)] [--call-reruns N (4)] [--json] [--trace] [--sleighpath DIR] ``` @@ -170,6 +171,8 @@ common: [--runs N (256)] [--seed S] [--budget OPS (200000)] [--concolic QUERIES at, not a proof that it is the first or the only cause. Holding a rule back also changes which rules apply after it, so a culprit may be one side of an interaction rather than the direct cause. +- **`step`** is Tier L's kuna side: one instruction's p-code from random register values, + as JSON. `scripts/diffverify/tier_l.py` runs it against Unicorn. - **`mutate`** plants faults in kuna's side and reports how many the check catches (`mutation.md`). A file or function that fails to load, or a worker that fails to finish, gives exit status 3. @@ -234,7 +237,7 @@ The crate is grouped by folder; the old module paths (`crate::check`, `crate::ca | `graph/` | `mod.rs`, `program.rs` | kuna's side: compiling a `Funcdata` for repeated runs, and running it | | `abi/` | `mod.rs`, `calls.rs`, `contract.rs`, `divergence.rs` | calling conventions, per-call facts both sides share, C contracts, declared divergences | | `compare/` | `check.rs`, `observe.rs`, `setup.rs` | the runs and the verdict; comparing calls, memory and system calls; each run's starting state | -| `tools/` | `localize.rs`, `mutate.rs`, `concolic.rs` | rule localization, mutation testing, z3 inputs | +| `tools/` | `localize.rs`, `mutate.rs`, `concolic.rs`, `step.rs` | rule localization, mutation testing, z3 inputs, Tier L's kuna side | | `report/` | `mod.rs`, `baseline.rs` | output; the corpus baseline | A later tier gets a folder of its own (`symbolic/` for Tier S, `printer/` for Tier P). @@ -271,7 +274,7 @@ model's judgement, so it holds every pull request to the same bar whichever agen it. It has done three things review did not: - **Found bugs in merged code.** The decbench run found seven kuna bugs (#1916–#1922) - and three errors in the vendored SLEIGH specs (Tier L), all in code that + and three errors in the vendored SLEIGH specs (`tier-l-results.md`), all in code that had passed its tests and review. - **Confirmed fixes on its own.** The stage tests #1924 and #1927 added give `DIFFERS` in their pass with the fix turned off and `AGREES` in the default pass, without anyone @@ -428,6 +431,7 @@ run yet. | `c4-results.md` | slice C4 on the test corpus: precision and recall against restored bugs | | `c4-decbench-results.md` | slice C4 on the decbench binaries: harness defects found, every `DIFFERS` sorted by cause, the issues filed | | `c5-results.md` | slice C5: concolic inputs | +| `tier-l-results.md` | Tier L: SLEIGH p-code against Unicorn, the spec errors found | | `triage.md` | how to decide whether a difference is the spec's, the emulator's, the checker's or the harness's | | `mutation.md` | mutation testing: what share of planted faults the check catches | | `record.json` | the slices' measured numbers, for scripts | diff --git a/docs/features/diffverify/proposal.md b/docs/features/diffverify/proposal.md index e7a497eaf9..20dd58aaca 100644 --- a/docs/features/diffverify/proposal.md +++ b/docs/features/diffverify/proposal.md @@ -326,7 +326,7 @@ library rather than stubbed. | C5 | concolic inputs: expressions over the inputs on both sides, branch conditions negated through z3, capped paths and queries | a fixture whose difference appears only on one 32-bit value gives `DIFFERS`, where 256 random runs give `AGREES`; new paths reached per function on the corpus **Done** (`c5-results.md`: `--concolic N`; a value-specific fault caught that 256 random runs miss; on decbench, concolic runs in 49 of 250 sample functions and 105 of 405 `ls` functions) | | S1 | Tier S for loop-free `AGREES` functions that pass the static entry condition, under the budget | `EQUIVALENT` and `UNKNOWN(budget)` counts on the same corpus; every `sat` replays or is classified | | S2 | bounded loops; budget baseline and budget-regression flag | `EQUIVALENT(≤k)` counts; a deliberately bloating rule change is flagged by budget alone | -| L1 | Tier L for x86-64, AArch64, ARM | per-arch mismatch report with skip list. **Done** (8,805 instruction forms against Unicorn; x86-64 differs only in the `AF` the spec does not compute; three SLEIGH spec errors on AArch64 and Thumb) | +| L1 | Tier L for x86-64, AArch64, ARM | per-arch mismatch report with skip list. **Done** (`tier-l-results.md`: 8,805 instruction forms against Unicorn; x86-64 differs only in the `AF` the spec does not compute; three SLEIGH spec errors on AArch64 and Thumb) | | M | mutation testing of the check: one semantic fault planted at a time in kuna's side of a function that agrees | recall per fault kind, the faults reached counted apart. **Done** (`mutation.md`: 76% of reached mutants caught on the corpus, 74–75% on `ls` and `find`; the gaps it showed in the check are fixed, and claims the check cannot verify are reported as such) | | P | separate proposal | — | diff --git a/docs/features/diffverify/tier-l-results.md b/docs/features/diffverify/tier-l-results.md new file mode 100644 index 0000000000..ccf0a5012a --- /dev/null +++ b/docs/features/diffverify/tier-l-results.md @@ -0,0 +1,77 @@ +# diffverify — Tier L results (the lift against Unicorn) + +Before naming a cause for any difference here, follow `triage.md`: a difference against +Unicorn can be the spec's, Unicorn's, kuna-verify's evaluator's, the driver's or the +architecture's own. + +Tier L checks the machine side of Tier C: one instruction's SLEIGH p-code, run with the +op semantics the check uses (`machine::lift`, `value::eval`), against Unicorn (QEMU's +TCG as a library) from the same state (proposal, Tier L). + +```sh +python3 scripts/diffverify/tier_l.py x86-64|aarch64|thumb BINARY [--limit N] [--states N] +``` + +- **kuna side:** `kuna-verify step BINARY --regs R,R.. --flags F,F..` sweeps each + function and picks a few instructions of each form: the mnemonic, with every number in + the operands replaced. It runs each instruction from random values of the named + registers and prints one JSON line with the registers before and after, the memory + bytes it read and wrote, and the next address. `--canonical` keeps 8-byte registers + below 2^47, so a pointer among them is one the 48-bit address space can hold. +- **Unicorn side:** the driver maps the instruction bytes and the bytes kuna read, sets + the same registers and flags, runs one instruction, and compares: + - the registers; + - the flags the architecture defines after that instruction (the Intel SDM's undefined + flags are left out by mnemonic); + - the bytes written; + - the next address; + - any byte Unicorn reads that kuna did not. + +Left out and counted: +- instructions that read a register outside the named set (x87, MMX, NEON); +- user ops the step does not run (`syscall`, `cpuid`, coprocessor access); +- Thumb instructions inside an IT block, whose condition comes from ITSTATE, which one + instruction run alone does not carry. + +## 1. Results + +Four states per instruction, two instructions per form, from the decbench binaries +(x86-64 and Cortex-M Thumb) and the C++ sample set's AArch64 builds. + +| binaries | forms | same | `AF` only | differ | left out | +|---|---:|---:|---:|---:|---:| +| x86-64: `ls`, `bash`, `certtool` (`O2`), `ssh-add` (`O0`) | 6,686 | 5,263 | 1,391 | 0 | 32 | +| Thumb: `RTOSDemo`, `cf2.elf` (`O2`), `ch.elf` (`O0`) | 1,330 | 933 | — | 16 | 381 | +| AArch64: `ninja`, `libsnappy` (`O2`), `libdouble-conversion` (`O0`) | 789 | 697 | — | 8 | 84 | + +x86's `AF`: Ghidra's x86 spec does not compute the auxiliary carry in `addflags`, +`subflags` and most other arithmetic; it leaves it as it was. No decompiled C reads it, +so these are counted apart, not as differences. + +## 2. What differs + +| instructions | forms | kuna | Unicorn (the architecture) | where | +|---|---:|---|---|---| +| AArch64 `ldrsh`/`ldrsb` into a `W` register | 8 | sign-extends into all 64 bits of `X` | sign-extends to 32 bits, zeroes the top 32 | `AARCH64base.sinc`: the 32-bit forms write `Rt_GPR64 = sext(...)` | +| Thumb `stmia Rn!` with `Rn` in the list | 7 | no writeback | `Rn += 4 × count`, always | `ARMTHUMBinstructions.sinc`: `Rn_exclaim_WB`, the LDM rule, is used for STM too | +| Thumb-2 `ands`, `bics`, `mvns` with an expanded immediate or a shifted register | 4 | `C` unchanged | `C` = the shifter's carry-out | `thSBIT_ZN` sets `Z` and `N` only; `ThumbExpandImm12` computes `shift_carry` and nothing reads it | +| VFP `vcvt.s32/u32.f32` out of range | 2 | x86's integer indefinite | saturates | p-code's `TRUNC` leaves it undefined | +| VFP `vfma`, `vfnma` | 2 | one ulp off | fused | the spec multiplies and adds with a rounding between | +| VFP `vsqrt` of a negative | 1 | `0xffc00000` | `0x7fc00000`, ARM's default NaN | the default NaN differs by architecture | + +The first three are errors in the vendored SLEIGH specs. Every decompile of those +instructions has them, not only this check: +- After `ldrsh w0, [x1]`, kuna's IR holds a 64-bit sign extension where the machine holds + a zero-extended 32-bit value, so a later use of `x0` (an address or a 64-bit compare) + is wrong. +- After a Thumb `stmia`, kuna's base register is too low by the bytes stored. +- After a flag-setting Thumb-2 logical op, a `bcs`/`bcc` reads a stale carry. + +The VFP rows are p-code under-specifying the operation. Tier C runs the same semantics on +both sides, so they do not turn into `DIFFERS` there. + +One difference found on the way is fixed in the check: +- **A NaN operand to `+ − × ÷`** now comes back quieted, as SSE and ARM (with default-NaN + mode off) return it, instead of the host's default NaN. + +`hlt`, whose spec branches to itself, is left out as a system instruction. diff --git a/docs/features/diffverify/triage.md b/docs/features/diffverify/triage.md index 821fe164d2..f014d72877 100644 --- a/docs/features/diffverify/triage.md +++ b/docs/features/diffverify/triage.md @@ -27,7 +27,7 @@ not the cause. Each suspect has produced a difference that, at first sight, looked like another one. -**Spec errors (confirmed).** Three, all in Tier L: +**Spec errors (confirmed).** Three, all in Tier L (`tier-l-results.md` §2): - AArch64 `ldrsh`/`ldrsb` into a `W` register sign-extend into all 64 bits of `X`. The Arm ARM's pseudocode sign-extends to the register size, 32 bits for a `W` register, and a write to a `W` register zeroes the top half of `X`. Confirmed by running the @@ -41,7 +41,7 @@ Each suspect has produced a difference that, at first sight, looked like another pseudocode and Unicorn; no hardware. NationalSecurityAgency/ghidra#10274. **Under-specified p-code (not errors in the same sense).** VFP `vcvt` out of range, `vfma` -and `vfnma`, and the default NaN of `vsqrt` (Tier L): the spec's p-code +and `vfnma`, and the default NaN of `vsqrt` (`tier-l-results.md` §2): the spec's p-code cannot say what the architecture defines (`TRUNC` leaves out-of-range undefined; p-code has no fused multiply-add; NaN payloads are not modelled). These are reported as gaps, not as errors. diff --git a/scripts/diffverify/tier_l.py b/scripts/diffverify/tier_l.py new file mode 100644 index 0000000000..01a380e2ec --- /dev/null +++ b/scripts/diffverify/tier_l.py @@ -0,0 +1,230 @@ +"""diffverify Tier L: kuna's lift of one instruction against Unicorn. + +`kuna-verify step` runs one instruction's SLEIGH p-code from a random state of +the named registers and prints what it read, wrote and where it went next. +This driver runs the same bytes from the same state under Unicorn (QEMU's TCG +as a library) and compares the registers, the flags the architecture defines, +the memory written and the next address. + + python3 scripts/diffverify/tier_l.py x86-64 BINARY [--limit N] [--states N] + +Prints one line per instruction form that differs, and a summary. Memory the +kuna side read is mapped for Unicorn with the same bytes; a byte Unicorn reads +that kuna did not is itself a difference. +""" + +import argparse +import collections +import json +import os +import subprocess +import sys + +import unicorn +from unicorn import arm64_const as A64 +from unicorn import arm_const as ARM +from unicorn import x86_const as X86 + +PAGE = 0x1000 +ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +class Arch: + def __init__(self, name, uc_arch, uc_mode, regs, flags, pc, undefined, spec_gaps=()): + self.name, self.uc_arch, self.uc_mode = name, uc_arch, uc_mode + self.regs, self.flags, self.pc, self.undefined = regs, flags, pc, undefined + # Flags the SLEIGH spec does not compute at all, counted apart. + self.spec_gaps = set(spec_gaps) + + +X86_REGS = {n: getattr(X86, f"UC_X86_REG_{n}") for n in + ["RAX", "RBX", "RCX", "RDX", "RSI", "RDI", "RBP", "RSP", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15"] + + [f"XMM{i}" for i in range(16)]} +X86_REGS["FS_OFFSET"] = X86.UC_X86_REG_FS_BASE +X86_FLAGS = {"CF": 0, "PF": 2, "AF": 4, "ZF": 6, "SF": 7, "DF": 10, "OF": 11} +ALL6 = {"CF", "PF", "AF", "ZF", "SF", "OF"} + +# Flags the Intel SDM leaves undefined after an instruction, by mnemonic. +X86_UNDEFINED = { + **{m: {"AF"} for m in ["and", "or", "xor", "test"]}, + **{m: {"SF", "ZF", "AF", "PF"} for m in ["mul", "imul"]}, + **{m: ALL6 for m in ["div", "idiv"]}, + **{m: {"AF", "OF"} for m in ["shl", "sal", "shr", "sar", "shld", "shrd"]}, + **{m: {"OF"} for m in ["rol", "ror", "rcl", "rcr"]}, + **{m: {"CF", "OF", "SF", "AF", "PF"} for m in ["bsf", "bsr"]}, + **{m: {"OF", "SF", "AF", "PF"} for m in ["bt", "bts", "btr", "btc"]}, + **{m: {"CF", "OF", "SF", "AF", "PF"} for m in ["lzcnt", "tzcnt"]}, +} +ARM_CONDITIONS = {"eq", "ne", "cs", "cc", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le"} + + +def in_it_block(form): + """A Thumb IT instruction, or one inside an IT block: its condition comes + from ITSTATE, which one instruction run alone does not carry.""" + mnemonic = form.split()[0] if form.split() else "" + parts = mnemonic.split(".") + return parts[0] in ("it", "itt", "ite", "ittt", "itte", "itet", "itee", "itttt", "ittte", "ittet", "ittee", + "itett", "itete", "iteet", "iteee") or any(p in ARM_CONDITIONS for p in parts[1:]) + + +# Privileged or system instructions whose effect is the kernel's. +X86_SKIP = {"hlt", "syscall", "int", "int3", "cpuid", "rdtsc", "rdtscp", "xgetbv"} + +A64_REGS = {**{f"x{i}": getattr(A64, f"UC_ARM64_REG_X{i}") for i in range(29)}, + "x29": A64.UC_ARM64_REG_X29, "x30": A64.UC_ARM64_REG_X30, "sp": A64.UC_ARM64_REG_SP} +A64_FLAGS = {"NG": 31, "ZR": 30, "CY": 29, "OV": 28} + +ARM_REGS = {**{f"r{i}": getattr(ARM, f"UC_ARM_REG_R{i}") for i in range(13)}, "sp": ARM.UC_ARM_REG_SP, "lr": ARM.UC_ARM_REG_LR, + **{f"s{i}": getattr(ARM, f"UC_ARM_REG_S{i}") for i in range(32)}} +ARM_FLAGS = {"NG": 31, "ZR": 30, "CY": 29, "OV": 28} + +ARCHES = { + # Ghidra's x86 spec leaves AF alone in addflags/subflags and most other + # arithmetic: a known gap no decompiled C reads. + "x86-64": Arch("x86-64", unicorn.UC_ARCH_X86, unicorn.UC_MODE_64, X86_REGS, X86_FLAGS, X86.UC_X86_REG_RIP, X86_UNDEFINED, ["AF"]), + "aarch64": Arch("aarch64", unicorn.UC_ARCH_ARM64, unicorn.UC_MODE_ARM, A64_REGS, A64_FLAGS, A64.UC_ARM64_REG_PC, {}), + "thumb": Arch("thumb", unicorn.UC_ARCH_ARM, unicorn.UC_MODE_THUMB | unicorn.UC_MODE_MCLASS, ARM_REGS, ARM_FLAGS, ARM.UC_ARM_REG_PC, {}), +} + + +def flags_reg(arch): + return {"x86-64": X86.UC_X86_REG_EFLAGS, "aarch64": A64.UC_ARM64_REG_NZCV, "thumb": ARM.UC_ARM_REG_CPSR}[arch.name] + + +def run_unicorn(arch, case): + addr = int(case["addr"], 16) + code = bytes.fromhex(case["bytes"]) + reads = {int(a, 16): b for a, b in case["reads"].items()} + uc = unicorn.Uc(arch.uc_arch, arch.uc_mode) + mapped = set() + + def ensure(at, size=1): + for page in range(at & ~(PAGE - 1), (at + size + PAGE - 1) & ~(PAGE - 1), PAGE): + if page not in mapped: + uc.mem_map(page, PAGE) + mapped.add(page) + + ensure(addr, len(code)) + for a, b in reads.items(): + ensure(a) + uc.mem_write(a, bytes([b])) + uc.mem_write(addr, code) + for name, v in case["in"].items(): + if name in arch.regs: + uc.reg_write(arch.regs[name], int(v, 16)) + word = 0 + for name, bit in arch.flags.items(): + if name in case["in"]: + word |= (int(case["in"][name], 16) & 1) << bit + if arch.name == "x86-64": + word |= 2 + elif arch.name == "thumb": + word |= 1 << 24 + uc.reg_write(flags_reg(arch), word) + seen_reads, writes, stray = set(), {}, set() + + def on_read(_uc, _access, at, size, _value, _data): + for i in range(size): + seen_reads.add(at + i) + + def on_write(_uc, _access, at, size, value, _data): + for i in range(size): + writes[at + i] = (value >> (8 * i)) & 0xff + + def on_unmapped(_uc, access, at, size, _value, _data): + if access == unicorn.UC_MEM_READ_UNMAPPED: + for i in range(size): + stray.add(at + i) + ensure(at, size) + return True + + uc.hook_add(unicorn.UC_HOOK_MEM_READ, on_read) + uc.hook_add(unicorn.UC_HOOK_MEM_WRITE, on_write) + uc.hook_add(unicorn.UC_HOOK_MEM_UNMAPPED, on_unmapped) + start = addr | 1 if arch.name == "thumb" else addr + uc.emu_start(start, 0xffff_ffff_ffff_ffff if arch.name != "thumb" else 0xffff_ffff, count=1) + out = {name: uc.reg_read(r) for name, r in arch.regs.items()} + word = uc.reg_read(flags_reg(arch)) + for name, bit in arch.flags.items(): + out[name] = (word >> bit) & 1 + pc = uc.reg_read(arch.pc) + return out, writes, pc, (seen_reads | stray) - set(reads) - set(range(addr, addr + len(code))) + + +def compare(arch, case): + if arch.name == "x86-64" and case["form"].split()[:1] and case["form"].split()[0] in X86_SKIP: + return "skip", "system instruction" + if arch.name == "thumb" and in_it_block(case["form"]): + return "skip", "inside an IT block" + if case.get("error") or case.get("unlisted"): + return "skip", case.get("error") or "reads " + ",".join(case["unlisted"]) + try: + out, writes, pc, extra = run_unicorn(arch, case) + except unicorn.UcError as e: + return "skip", f"unicorn: {e}" + mnemonic = case["form"].split()[0] if case["form"].split() else "" + undefined = arch.undefined.get(mnemonic, set()) + diffs, gaps = [], [] + for name, v in case["out"].items(): + if name in undefined or name not in out: + continue + if int(v, 16) != out[name]: + (gaps if name in arch.spec_gaps else diffs).append(f"{name}: kuna {v}, unicorn {out[name]:#x}") + kw = {int(a, 16): b for a, b in case["writes"].items()} + if kw != writes: + only_k = sorted(set(kw) - set(writes)) + only_u = sorted(set(writes) - set(kw)) + bad = sorted(a for a in set(kw) & set(writes) if kw[a] != writes[a]) + diffs.append(f"writes: kuna-only {[hex(a) for a in only_k[:4]]} unicorn-only {[hex(a) for a in only_u[:4]]} differing {[hex(a) for a in bad[:4]]}") + if case.get("next") and int(case["next"], 16) != pc: + diffs.append(f"next: kuna {case['next']}, unicorn {pc:#x}") + if extra: + diffs.append(f"unicorn reads bytes kuna did not: {[hex(a) for a in sorted(extra)[:4]]}") + if diffs: + return "differs", "; ".join(diffs) + return ("gap", "; ".join(gaps)) if gaps else ("same", "") + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("arch", choices=sorted(ARCHES)) + p.add_argument("binary") + p.add_argument("--limit", type=int, default=2000) + p.add_argument("--states", type=int, default=4) + p.add_argument("--per-form", type=int, default=2) + p.add_argument("--kuna-verify", default=os.path.join(ROOT, "decompiler/target/release/kuna-verify")) + p.add_argument("--sleighpath", default=os.path.join(ROOT, "specs")) + p.add_argument("--json", action="store_true") + a = p.parse_args() + arch = ARCHES[a.arch] + cmd = [a.kuna_verify, "step", a.binary, "--regs", ",".join(arch.regs), "--flags", ",".join(arch.flags), + "--states", str(a.states), "--per-form", str(a.per_form), "--limit", str(a.limit), "--sleighpath", a.sleighpath] + if arch.name in ("x86-64", "aarch64"): + cmd.append("--canonical") + proc = subprocess.run(cmd, capture_output=True, text=True) + if proc.returncode != 0: + sys.exit(proc.stderr.strip()) + by_form = collections.defaultdict(list) + for line in proc.stdout.splitlines(): + case = json.loads(line) + by_form[case["form"]].append((case, compare(arch, case))) + counts = collections.Counter() + for form, results in sorted(by_form.items()): + kinds = {k for _, (k, _) in results} + kind = next((k for k in ("differs", "gap", "same") if k in kinds), "skip") + counts[kind] += 1 + if kind == "differs": + case, (_, why) = next(r for r in results if r[1][0] == "differs") + if a.json: + print(json.dumps({"form": form, "asm": case["asm"], "addr": case["addr"], "why": why})) + else: + print(f"DIFFERS {case['addr']} {case['asm']:<40} {why}") + skips = collections.Counter(why.split(":")[0][:40] for rs in by_form.values() for _, (k, why) in rs if k == "skip") + print(f"forms {len(by_form)} same {counts['same']} differs {counts['differs']} " + f"spec-gap only {counts['gap']} skipped {counts['skip']}", file=sys.stderr) + for why, n in skips.most_common(8): + print(f" skipped {n:5} {why}", file=sys.stderr) + + +if __name__ == "__main__": + main() From a81154158585e9dbfd9f903db1a054ab8eead10b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=B9=80=EC=84=B1=EC=A3=BC?= Date: Thu, 3 Dec 2026 09:50:31 +0900 Subject: [PATCH 7/7] [AUTOMATED] Add a replayable function oracle to kuna-verify (oracle-case) `kuna-verify oracle-case` runs one explicit x86-64 case (named input registers and memory bytes, external entries that stop the run) on the function's raw p-code and on kuna's final IR, and prints both observations as JSON with the ELF and spec digests. `scripts/diffverify/function_oracle.py` runs the same case in Unicorn and compares the three. `make test-diffverify-tools` runs the scripts' tests, as a CI step that installs Unicorn, z3 and clang. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/tests.yml | 9 + Makefile | 9 +- .../crates/kuna-verify/src/bin/kuna-verify.rs | 55 ++ .../crates/kuna-verify/src/graph/mod.rs | 8 +- decompiler/crates/kuna-verify/src/lib.rs | 1 + .../crates/kuna-verify/src/machine/mod.rs | 31 +- .../crates/kuna-verify/src/oracle/elf.rs | 106 ++++ .../crates/kuna-verify/src/oracle/mod.rs | 469 ++++++++++++++++++ .../crates/kuna-verify/src/state/explicit.rs | 69 +++ .../crates/kuna-verify/src/state/mod.rs | 34 +- docs/features/diffverify/README.md | 1 + docs/features/diffverify/function-oracle.md | 152 ++++++ .../fixtures/function_oracle_x86_64.c | 180 +++++++ scripts/diffverify/function_oracle.py | 312 ++++++++++++ scripts/diffverify/oracle_compare.py | 310 ++++++++++++ scripts/diffverify/oracle_protocol.py | 23 + scripts/diffverify/oracle_replay.py | 71 +++ scripts/diffverify/test_function_oracle.py | 129 +++++ 18 files changed, 1964 insertions(+), 5 deletions(-) create mode 100644 decompiler/crates/kuna-verify/src/oracle/elf.rs create mode 100644 decompiler/crates/kuna-verify/src/oracle/mod.rs create mode 100644 decompiler/crates/kuna-verify/src/state/explicit.rs create mode 100644 docs/features/diffverify/function-oracle.md create mode 100644 scripts/diffverify/fixtures/function_oracle_x86_64.c create mode 100644 scripts/diffverify/function_oracle.py create mode 100644 scripts/diffverify/oracle_compare.py create mode 100644 scripts/diffverify/oracle_protocol.py create mode 100644 scripts/diffverify/oracle_replay.py create mode 100644 scripts/diffverify/test_function_oracle.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 5f057529e2..7f833b3fe1 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -190,6 +190,15 @@ jobs: } >> "$GITHUB_STEP_SUMMARY" exit $status + # The oracle, replay and proof scripts need Unicorn, z3 and clang, ld.lld and + # llvm-nm, which nothing else in this job installs. + - name: diffverify oracle and solver scripts + run: | + sudo apt-get update -q && sudo apt-get install -y z3 clang lld llvm + python3 -m venv "$RUNNER_TEMP/oracle" + "$RUNNER_TEMP/oracle/bin/pip" install unicorn==2.1.2 + make test-diffverify-tools PYTHON="$RUNNER_TEMP/oracle/bin/python" + - name: Upload the diffverify verdicts if: always() && steps.diffverify.outcome != 'skipped' uses: actions/upload-artifact@v4 diff --git a/Makefile b/Makefile index e60bee390d..e34987e8ed 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,7 @@ PYTHON ?= python3 # (inside target/, which is gitignored, so a failed run leaves no repo litter). GHIDRA_SIM_LOG := $(ENGINE)/target/ghidra-sim.log -.PHONY: all binaries specs test test-stages test-jvm verify-corpus test-cli test-tools test-ghidra rust rust-test lint clean check-spec version observatory coverage +.PHONY: all binaries specs test test-stages test-jvm verify-corpus test-cli test-tools test-diffverify-tools test-ghidra rust rust-test lint clean check-spec version observatory coverage all: binaries specs @@ -108,6 +108,13 @@ test-tools: $(PYTHON) $(ROOT)/scripts/check_test_layout.py PYTHONPATH=$(ROOT) $(PYTHON) -m unittest discover -s $(ROOT)/scripts/tests -p 'test_*.py' +# diffverify's oracle, replay and proof scripts (scripts/diffverify/). They need +# `unicorn==2.1.2` in $(PYTHON), `z3`, `clang`, `ld.lld` and `llvm-nm` on PATH, and +# the release kuna-verify and slacomp; CI installs all of them (docs/features/diffverify/function-oracle.md). +test-diffverify-tools: + cd $(ENGINE) && cargo build --$(PROFILE) -p kuna-verify -p kuna-slacomp + PYTHONPATH=$(ROOT)/scripts/diffverify $(PYTHON) -m unittest discover -s $(ROOT)/scripts/diffverify -p 'test_*.py' + # Print the repo version as MAJOR.MINOR (VERSION file + release count -- the # scheme release CI tags with; see docs/release.md). version: diff --git a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs index 6eb3f86b17..cb2173b4ff 100644 --- a/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs +++ b/decompiler/crates/kuna-verify/src/bin/kuna-verify.rs @@ -5,6 +5,7 @@ //! kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] //! kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... //! kuna-verify step --regs R,R.. [--flags F,F..] [--states N] [--per-form N] [--limit N] [--canonical] +//! kuna-verify oracle-case [--input-reg NAME HEX]... [--external-entry ADDR ARITY]... [--seed S] [--budget OPS] [--sleighpath DIR] //! kuna-verify mutate ... | ... | --all [--per-function N] [--jobs N] //! common: [--runs N] [--seed S] [--budget OPS] [--concolic QUERIES] [--json] [--sleighpath DIR] //! ``` @@ -40,6 +41,7 @@ const USAGE: &str = "usage: kuna-verify corpus ... [--jobs N] [--file-seconds S] [--baseline FILE] [--save-baseline FILE] kuna-verify localize [--pass N] [--contract FILE.c] [--option NAME VALUE]... kuna-verify step --regs R,R.. [--flags F,F..] [--states N] [--per-form N] [--limit N] [--canonical] + kuna-verify oracle-case [--input-reg NAME HEX]... [--external-entry ADDR ARITY]... [--seed S] [--budget OPS] [--sleighpath DIR] kuna-verify mutate ... | ... | --all [--per-function N (6)] [--jobs N] [--file-seconds S] options: --runs N (256) --seed S --budget OPS (200000) --concolic QUERIES (0) --call-reruns N (4) --json --trace --sleighpath DIR"; @@ -61,6 +63,10 @@ struct Args { regs: Vec, flags: Vec, canonical: bool, + input_regs: Vec<(String, String)>, + external_entries: BTreeMap, + opcode_mutant: Option, + initial_memory: BTreeMap, states: u32, per_form: usize, limit: usize, @@ -88,6 +94,10 @@ fn parse(argv: &[String]) -> Result { regs: Vec::new(), flags: Vec::new(), canonical: false, + input_regs: Vec::new(), + external_entries: BTreeMap::new(), + opcode_mutant: None, + initial_memory: BTreeMap::new(), states: 4, per_form: 2, limit: 2000, @@ -154,6 +164,32 @@ fn parse(argv: &[String]) -> Result { let v: Vec = it.next().ok_or(format!("{arg} needs names"))?.split(',').filter(|s| !s.is_empty()).map(str::to_string).collect(); if arg == "--regs" { a.regs = v } else { a.flags = v } } + "--input-reg" => { + let name = it.next().ok_or("--input-reg needs NAME HEX")?; + let value = it.next().ok_or("--input-reg needs NAME HEX")?; + a.input_regs.push((name.clone(), value.clone())); + } + "--external-entry" => { + let address = num(it.next(), "--external-entry ADDR")?; + let arity = num(it.next(), "--external-entry ARITY")?; + let arity = u8::try_from(arity).ok().filter(|&n| n <= 6) + .ok_or("--external-entry arity must be between 0 and 6")?; + if a.external_entries.insert(address, arity).is_some() { + return Err(format!("external entry {address:#x} specified twice")); + } + } + "--opcode-mutant" => { + let op = num(it.next(), "--opcode-mutant")?; + a.opcode_mutant = Some(usize::try_from(op).map_err(|_| "--opcode-mutant is too large")?); + } + "--memory-byte" => { + let addr = num(it.next(), "--memory-byte address")?; + let value = u8::try_from(num(it.next(), "--memory-byte value")?) + .map_err(|_| "--memory-byte expects a value from 0 to 255")?; + if a.initial_memory.insert(addr, value).is_some() { + return Err(format!("initial memory byte {addr:#x} specified twice")); + } + } "--states" => a.states = num(it.next(), "--states")?.max(1) as u32, "--canonical" => a.canonical = true, "--per-form" => a.per_form = num(it.next(), "--per-form")?.max(1) as usize, @@ -837,6 +873,8 @@ fn main() -> ExitCode { return ExitCode::from(2); }; let result = parse(rest).and_then(|a| match cmd.as_str() { + cmd if cmd != "oracle-case" && (!a.input_regs.is_empty() || !a.external_entries.is_empty() || a.opcode_mutant.is_some() || !a.initial_memory.is_empty()) => + Err("--input-reg, --external-entry, --opcode-mutant and --memory-byte are for oracle-case".into()), "check" => run_check(&a), "corpus" => run_corpus(&a), "shard" => run_shard(&a), @@ -844,6 +882,7 @@ fn main() -> ExitCode { "step" => run_step(&a), "localize" => run_localize(&a), "mutate" => run_mutate(&a), + "oracle-case" => run_oracle_case(&a), _ => Err(USAGE.to_string()), }); match result { @@ -855,6 +894,22 @@ fn main() -> ExitCode { } } +fn run_oracle_case(a: &Args) -> Result { + let [path, function] = a.positional.as_slice() else { + return Err("oracle-case needs an ELF and a function".into()); + }; + let roots = spec_roots(a.sleighpath.as_deref()); + let config = kuna_verify::oracle::RunConfig { + seed: a.opts.seed, budget: a.opts.budget, input_regs: &a.input_regs, + external_entries: &a.external_entries, + opcode_mutant: a.opcode_mutant, + memory: &a.initial_memory, + }; + let case = kuna_verify::oracle::capture(path, function, &a.options, &roots, config)?; + println!("{case}"); + Ok(ExitCode::SUCCESS) +} + fn mutant_json(o: &kuna_verify::mutate::Outcome) -> Value { json!({ "function": o.function, diff --git a/decompiler/crates/kuna-verify/src/graph/mod.rs b/decompiler/crates/kuna-verify/src/graph/mod.rs index e6aed0b7fc..77dfdd98ca 100644 --- a/decompiler/crates/kuna-verify/src/graph/mod.rs +++ b/decompiler/crates/kuna-verify/src/graph/mod.rs @@ -458,6 +458,12 @@ impl Run<'_, '_, '_> { let wide = target.is_some_and(|t| self.state.env.code_mapped(t)); let writes = self.state.writes_at_call(&args, wide); crate::calls::record(&mut self.records, Record { at, target, indirect, args, writes, effect: None, frame_reads: None, live_in: None, stack_in: None, whole: Vec::new() })?; + if target.is_some_and(|t| self.state.env.explicit.as_ref().is_some_and(|case| case.external_entries.contains_key(&t))) { + self.events.push(crate::calls::UserEvent { + at, name: "external-call".to_owned(), ins: Vec::new(), file: Vec::new(), + }); + return Ok(Flow::NoReturn); + } let site = self.calls.site(at); if site.noreturn { return Ok(Flow::NoReturn); @@ -509,7 +515,7 @@ impl Run<'_, '_, '_> { } let k = self.events.len(); self.events.push(crate::calls::UserEvent { at, name: name.clone(), ins, file: Vec::new() }); - if trap { + if trap || self.state.env.explicit.is_some() { return Ok(Flow::NoReturn); } if let Some(out) = op.out.as_ref() { diff --git a/decompiler/crates/kuna-verify/src/lib.rs b/decompiler/crates/kuna-verify/src/lib.rs index a98f3554f4..7c31c9aa98 100644 --- a/decompiler/crates/kuna-verify/src/lib.rs +++ b/decompiler/crates/kuna-verify/src/lib.rs @@ -15,6 +15,7 @@ pub mod abi; pub mod compare; pub mod graph; pub mod machine; +pub mod oracle; pub mod report; pub mod semantics; pub mod session; diff --git a/decompiler/crates/kuna-verify/src/machine/mod.rs b/decompiler/crates/kuna-verify/src/machine/mod.rs index 05c3cb1857..b45a226f12 100644 --- a/decompiler/crates/kuna-verify/src/machine/mod.rs +++ b/decompiler/crates/kuna-verify/src/machine/mod.rs @@ -51,6 +51,9 @@ impl PcodeEmit for Collect { } pub(crate) fn lift(env: &Env, addr: u64) -> Result, Halt> { + if let Some(explicit) = &env.explicit { + explicit.check(addr, 1, b'x')?; + } if let Some(i) = env.insns.borrow().get(&addr) { return Ok(Rc::clone(i)); } @@ -62,6 +65,13 @@ pub(crate) fn lift(env: &Env, addr: u64) -> Result, Halt> { .one_instruction(&mut emit, &Address::new(Rc::clone(&env.code), addr)) .map_err(|e| Halt::Unsupported(format!("lift at {addr:#x}: {}", e.explain())))?; let insn = Rc::new(Insn { len: len.max(1) as u64, ops: emit.0 }); + if let Some(explicit) = &env.explicit { + explicit.check(addr, insn.len, b'x')?; + let bytes = env.prog.read_bytes_at(&Address::new(Rc::clone(&env.code), addr), insn.len as usize); + if !bytes.is_some_and(|bytes| bytes.iter().copied().eq((addr..addr + insn.len).map(|at| explicit.byte(at)))) { + return Err(Halt::Unsupported(format!("loader bytes differ from the explicit case at {addr:#x}"))); + } + } env.insns.borrow_mut().insert(addr, Rc::clone(&insn)); Ok(insn) } @@ -530,6 +540,9 @@ impl<'e, 'p, 'c> Machine<'e, 'p, 'c> { } fn tail_call(&mut self, at: u64, target: u64, indirect: bool) -> Result { + if self.stop_at_external(at, target, indirect)? { + return Ok(Exit::NoReturn); + } let args = self.record(at, Some(target), indirect)?; if self.calls.site(at).noreturn { return Ok(match self.stops_at(at, target, &args)? { @@ -550,6 +563,17 @@ impl<'e, 'p, 'c> Machine<'e, 'p, 'c> { Ok(Exit::Return) } + fn stop_at_external(&mut self, at: u64, target: u64, indirect: bool) -> Result { + if !self.env.explicit.as_ref().is_some_and(|case| case.external_entries.contains_key(&target)) { + return Ok(false); + } + self.record(at, Some(target), indirect)?; + self.events.push(crate::calls::UserEvent { + at, name: "external-call".to_owned(), ins: Vec::new(), file: Vec::new(), + }); + Ok(true) + } + /// Record a call and give it the stub's effect. `true` when it does not /// return. fn call(&mut self, at: u64, target: Option, indirect: bool) -> Result { @@ -981,7 +1005,7 @@ fn exec_body(m: &mut Machine, entry: u64, mode: Mode, depth: u32, back: Option Result, String> { + regions_for( + image, + elf::EM_X86_64, + "oracle-case requires a fixed-address x86-64 ELF executable", + ) +} + +fn regions_for(image: &[u8], machine: u16, invalid_image: &str) -> Result, String> { + let file = ElfFile64::::parse(image) + .map_err(|e| format!("expected a little-endian ELF64: {e}"))?; + let endian = file.endian(); + let header = file.elf_header(); + if header.e_machine(endian) != machine || header.e_type(endian) != elf::ET_EXEC { + return Err(invalid_image.into()); + } + if machine == elf::EM_RISCV && header.e_flags(endian) & elf::EF_RISCV_RVE != 0 { + return Err("the formal RV64 leaf uses the standard integer register file".into()); + } + if file.elf_section_table().iter().any(|s| { + matches!( + s.sh_type(endian), + elf::SHT_REL | elf::SHT_RELA | elf::SHT_RELR + ) && s.sh_size(endian) != 0 + && s.sh_flags(endian) & u64::from(elf::SHF_ALLOC) != 0 + }) { + return Err("ELF contains allocated relocation entries".into()); + } + let mut regions = Vec::new(); + let mut mapped_size = 0; + for ph in file.elf_program_headers() { + match ph.p_type(endian) { + elf::PT_DYNAMIC | elf::PT_INTERP | elf::PT_TLS => { + return Err( + "dynamic loading, relocations and TLS are outside the ELF case model".into(), + ); + } + elf::PT_LOAD => {} + _ => continue, + } + let size = ph.p_memsz(endian); + if size == 0 && ph.p_filesz(endian) == 0 { + continue; + } + let at = ph.p_vaddr(endian); + let base = at & !(PAGE - 1); + let prefix = at - base; + let end = at + .checked_add(size) + .and_then(|end| end.checked_add(PAGE - 1)) + .map(|end| end & !(PAGE - 1)) + .filter(|&end| end <= 1 << 47) + .ok_or("ELF load segment is outside the low canonical half")?; + mapped_size += end - base; + if mapped_size > MAX_MAPPED { + return Err("ELF load segments exceed the explicit case size limit".into()); + } + let (offset, file_size) = ph.file_range(endian); + if file_size > size || offset % PAGE != prefix { + return Err("invalid ELF load segment extent or alignment".into()); + } + let bytes = if file_size == 0 { + Vec::new() + } else { + let start = (offset - prefix) as usize; + let end = offset + .checked_add(file_size) + .and_then(|end| usize::try_from(end).ok()) + .ok_or("ELF load segment file range overflows")?; + image + .get(start..end) + .ok_or("truncated ELF load segment")? + .to_vec() + }; + let permissions = match ph.p_flags(endian) { + elf::PF_R => "r", + READ_WRITE => "rw", + READ_EXECUTE => "rx", + elf::PF_X => "x", + _ => return Err("unsupported ELF load segment permissions".into()), + }; + regions.push(Region { + address: base, + size: end - base, + bytes, + permissions, + observe: permissions == "rw", + }); + } + if regions.is_empty() { + return Err("ELF has no loadable pages".into()); + } + Ok(regions) +} diff --git a/decompiler/crates/kuna-verify/src/oracle/mod.rs b/decompiler/crates/kuna-verify/src/oracle/mod.rs new file mode 100644 index 0000000000..5b39b4f142 --- /dev/null +++ b/decompiler/crates/kuna-verify/src/oracle/mod.rs @@ -0,0 +1,469 @@ +//! Export a shared seed and memory map for concrete function execution. + +pub(crate) mod elf; + +use std::collections::BTreeMap; + +use kuna_console::engine::ConsoleProgram; +use kuna_decomp::funcdata::Funcdata; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +use crate::state::{ExplicitState, Region, State, Writes}; +use crate::storage::Storage; +use crate::value::Halt; +use crate::{abi, calls, graph, machine, program, session, state::Env}; + +pub(crate) const PAGE: u64 = 4096; +pub(crate) const STACK: u64 = 0x7000_0000; +pub(crate) const CALLER: u64 = STACK + 3 * PAGE; +pub(crate) const SP: u64 = CALLER - 8; +pub(crate) const HEAP: u64 = 0x6000_0000; +const RETURN: u64 = 0x7100_0000; +const MAX_MAPPED: u64 = 16 * 1024 * 1024; +pub(crate) const GPR: [&str; 16] = [ + "RAX", "RBX", "RCX", "RDX", "RSI", "RDI", "RBP", "RSP", "R8", "R9", "R10", "R11", "R12", "R13", + "R14", "R15", +]; +const PRESERVED: [&str; 6] = ["RBX", "RBP", "R12", "R13", "R14", "R15"]; +const FLAGS: [&str; 21] = [ + "CF", "F1", "PF", "F3", "AF", "F5", "ZF", "SF", "TF", "IF", "DF", "OF", "IOPL", "NT", "F15", + "RF", "VM", "AC", "VIF", "VIP", "ID", +]; +pub(crate) const SYMBOLIC_FLAGS: [(&str, u8); 7] = [ + ("CF", 0), + ("PF", 2), + ("AF", 4), + ("ZF", 6), + ("SF", 7), + ("DF", 10), + ("OF", 11), +]; + +pub struct RunConfig<'a> { + pub seed: u64, + pub budget: u64, + pub input_regs: &'a [(String, String)], + pub external_entries: &'a BTreeMap, + pub opcode_mutant: Option, + pub memory: &'a BTreeMap, +} + +/// Run the Kuna interpreters and export the exact input for the external runner. +pub fn capture( + path: &str, + function: &str, + options: &[(String, String)], + spec_roots: &[String], + config: RunConfig<'_>, +) -> Result { + let inputs = parse_inputs(config.input_regs)?; + if config + .external_entries + .iter() + .any(|(&at, &arity)| at >= 1 << 47 || at == RETURN || arity > 6) + { + return Err( + "external entries require a low canonical address and at most six integer arguments" + .into(), + ); + } + let image = std::fs::read(path).map_err(|e| format!("{path}: {e}"))?; + let mut regions = elf::regions(&image)?; + let mut stack = vec![0; (SP - STACK) as usize]; + stack.extend_from_slice(&RETURN.to_le_bytes()); + regions.extend([ + Region { + address: STACK, + size: 3 * PAGE, + bytes: stack, + permissions: "rw", + observe: false, + }, + Region { + address: CALLER, + size: PAGE, + bytes: Vec::new(), + permissions: "rw", + observe: true, + }, + Region { + address: HEAP, + size: 2 * PAGE, + bytes: Vec::new(), + permissions: "rw", + observe: true, + }, + ]); + regions.sort_unstable_by_key(|r| r.address); + if regions.windows(2).any(|w| w[0].end() > w[1].address) { + return Err("overlapping mapped ELF or synthetic pages".into()); + } + if regions + .iter() + .any(|r| (r.address..r.end()).contains(&RETURN)) + { + return Err("image maps the synthetic return address".into()); + } + if regions.iter().map(|r| r.size).sum::() > MAX_MAPPED { + return Err("mapped pages exceed the explicit case size limit".into()); + } + for (&address, &value) in config.memory { + if (SP..SP + 8).contains(&address) { + return Err("initial memory override would replace the return sentinel".into()); + } + let region = regions + .iter_mut() + .find(|r| r.address <= address && address < r.end() && r.permissions == "rw") + .ok_or_else(|| { + format!("initial byte override at {address:#x} is outside writable memory") + })?; + let offset = (address - region.address) as usize; + if region.bytes.len() <= offset { + region.bytes.resize(offset + 1, 0); + } + region.bytes[offset] = value; + } + + let mut result = None; + let mut regions = Some(regions); + let commands = session::binary_script(path, &[function.to_owned()], options); + session::drive(commands, None, spec_roots, |prog, fd| { + if let Some(regions) = regions.take() { + result = Some(observe(prog, fd, &config, regions, &inputs)); + } + })?; + let mut capture = result.ok_or_else(|| "no decompiled function is available".to_string())??; + capture["decompile_options"] = json!(options); + capture["initial_memory_overrides"] = json!(config + .memory + .iter() + .map(|(at, byte)| (format!("{at:#x}"), format!("{byte:#04x}"))) + .collect::>()); + capture["provenance"]["elf_sha256"] = json!(bytes_hex(Sha256::digest(image).iter().copied())); + Ok(capture) +} + +fn parse_inputs(input_regs: &[(String, String)]) -> Result, String> { + let mut inputs = BTreeMap::new(); + for (name, hex) in input_regs { + let bits = if (GPR.contains(&name.as_str()) && name != "RSP") || name == "RFLAGS" { + 64 + } else if (0..16).any(|i| *name == format!("XMM{i}")) { + 128 + } else { + return Err(format!("cannot override {name} in this case model")); + }; + let digits = hex.strip_prefix("0x").unwrap_or_default(); + if digits.len() > bits / 4 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(format!( + "{name} requires a {bits}-bit hexadecimal input with 0x prefix" + )); + } + let value = u128::from_str_radix(digits, 16) + .map_err(|_| format!("{name} requires a hexadecimal input with 0x prefix"))?; + if name == "RFLAGS" && (value & !0xed7 != 0 || value & 2 == 0) { + return Err("RFLAGS requires fixed bit 1 and only arithmetic flags, DF or IF".into()); + } + if inputs.insert(name.as_str(), value).is_some() { + return Err(format!("{name} is specified twice")); + } + } + Ok(inputs) +} + +pub(crate) fn register(env: &Env, name: &str) -> Result { + env.prog + .arch() + .manage() + .register_lookup() + .and_then(|lookup| lookup.probe_register(name)) + .and_then(|r| Some(Storage::new(r.space.as_ref()?, r.offset, r.size))) + .ok_or_else(|| format!("x86-64 SLEIGH register {name} is unavailable")) +} + +fn initial_state( + env: &Env, + entry: u64, + regions: Vec, + inputs: &BTreeMap<&str, u128>, +) -> Result<(ExplicitState, BTreeMap), String> { + let mut explicit = ExplicitState { + regions, + ..ExplicitState::default() + }; + explicit.check(entry, 1, b'x').map_err(|e| e.render())?; + let mut regs = BTreeMap::new(); + let mut sampled = State::new(env, crate::state::EDGE_RUNS); + let mut set = + |sleigh: &str, external: Option<&str>, value: Option| -> Result<(), String> { + let st = register(env, sleigh)?; + let value = match value { + Some(value) => value, + None => sampled + .read_storage(&st.space, st.off, st.size) + .map_err(|e| e.render())?, + }; + for (i, byte) in value + .to_le_bytes() + .into_iter() + .take(st.size as usize) + .enumerate() + { + explicit.registers.insert(st.off + i as u64, byte); + } + if let Some(name) = external { + regs.insert(name.to_owned(), format!("{value:#x}")); + } + Ok(()) + }; + for name in GPR { + let value = if name == "RSP" { + Some(u128::from(SP)) + } else { + inputs.get(name).copied() + }; + set(name, Some(name), value)?; + } + for i in 0..16 { + let name = format!("XMM{i}"); + set(&name, Some(&name), inputs.get(name.as_str()).copied())?; + } + for i in 0..8 { + set(&format!("ST{i}"), Some(&format!("FP{i}")), Some(0))?; + } + let packed_flags = inputs.get("RFLAGS").copied().unwrap_or(2); + for (name, external, value) in [ + ("FS_OFFSET", Some("FS_BASE"), 0), + ("GS_OFFSET", Some("GS_BASE"), 0), + ("MXCSR", Some("MXCSR"), 0x1f80), + ("FPUControlWord", Some("FPCW"), 0x037f), + ("FPUStatusWord", Some("FPSW"), 0), + ("FPUTagWord", Some("FPTAG"), 0xffff), + ("rflags", Some("RFLAGS"), packed_flags), + ("RIP", None, u128::from(entry)), + ] { + set(name, external, Some(value))?; + } + for name in FLAGS { + let bit = SYMBOLIC_FLAGS + .iter() + .find_map(|&(flag, n)| (flag == name).then_some(n)) + .or(match name { + "F1" => Some(1), + "IF" => Some(9), + _ => None, + }); + let value = bit.map_or(0, |n| (packed_flags >> n) & 1); + set(name, None, Some(value))?; + } + Ok((explicit, regs)) +} + +fn observe( + prog: &ConsoleProgram, + fd: &Funcdata, + config: &RunConfig<'_>, + regions: Vec, + inputs: &BTreeMap<&str, u128>, +) -> Result { + let (seed, budget) = (config.seed, config.budget); + let mut env = Env::new(prog, seed).map_err(|e| e.render())?; + let entry = fd.get_address().get_offset(); + if config.external_entries.contains_key(&entry) { + return Err("an external entry cannot be the function entry".into()); + } + env.sp0 = SP; + env.ret_addr = Some(RETURN); + env.ret_slot = 8; + let (mut explicit, registers) = initial_state(&env, entry, regions, inputs)?; + explicit.external_entries = config.external_entries.clone(); + let external_calls: BTreeMap<_, _> = config + .external_entries + .iter() + .map(|(&at, &arity)| (format!("{at:#x}"), arity)) + .collect(); + let memory: Vec<_> = explicit + .regions + .iter() + .map(|region| { + json!({ + "address": format!("{:#x}", region.address), + "size": region.size, + "bytes": bytes_hex(region.bytes.iter().copied()), + "permissions": region.permissions, + "observe": region.observe, + }) + }) + .collect(); + env.explicit = Some(explicit); + env.fd = Some(fd); + let mut calls = calls::sites(fd, &env); + env.arg_regs = calls.input_regs.clone(); + let mut program = program::compile(prog, fd, &calls); + let mutation = apply_opcode_mutant(&mut program, &mut calls, &env, config.opcode_mutant)?; + let run = crate::state::EDGE_RUNS; + + let raw = machine::run(&env, run, entry, budget, &calls, None); + let replay = raw.as_ref().map(|r| r.calls.as_slice()).unwrap_or_default(); + let ir = graph::run(&env, &program, run, budget, &calls, replay, None); + let explicit = env + .explicit + .as_ref() + .expect("the case supplies explicit state"); + let ir = match ir { + Err(h) => halted("final-ir", h), + Ok(ir) => { + let status = if ir.noreturn + || ir.unmatched_switch + || ir.overlapping_copy.is_some() + || ir.read_uninitialized + || !ir.calls.is_empty() + || !ir.events.is_empty() + { + "incomplete" + } else { + "returned" + }; + let claim = abi::claim(prog, fd); + json!({ + "backend": "final-ir", + "status": status, + "return": ir.ret.zip(claim.storage).map(|(value, st)| json!({ + "storage": st.name(prog), "size": st.size, "value": format!("{value:#x}"), + })), + "calls": call_records(&ir.calls), + "events": event_records(&ir.events), + "raw_callee_effects_available": replay.iter().any(|r| r.effect.is_some()), + "unverified_arguments": ir.call_inputs.len() + ir.unkept_inputs, + "memory": observed_memory(explicit, env.ram.get_index(), &ir.writes), + }) + } + }; + let raw = match raw { + Err(h) => halted("raw-pcode", h), + Ok(mut raw) => { + let status = if raw.noreturn + || raw.bad_return.is_some() + || !raw.calls.is_empty() + || !raw.events.is_empty() + || !raw.followed.is_empty() + { + "incomplete" + } else { + "returned" + }; + let mut final_regs = BTreeMap::new(); + for name in GPR.into_iter().chain(["XMM0", "XMM1"]) { + let st = register(&env, name)?; + let value = raw + .state + .read_storage(&st.space, st.off, st.size) + .map_err(|e| e.render())?; + final_regs.insert(name, format!("{value:#x}")); + } + let mut violations: Vec<_> = PRESERVED + .into_iter() + .filter(|name| final_regs[*name] != registers[*name]) + .collect(); + if final_regs["RSP"] != format!("{:#x}", SP + 8) { + violations.push("RSP"); + } + json!({ + "backend": "raw-pcode", + "status": status, + "reason": raw.bad_return.as_ref().map(Halt::render), + "registers": final_regs, + "abi_violations": (status == "returned").then_some(violations), + "calls": call_records(&raw.calls), + "events": event_records(&raw.events), + "memory": observed_memory(explicit, env.ram.get_index(), &raw.state.writes()), + }) + } + }; + + Ok(json!({ + "version": 1, "function": fd.get_name(), "seed": format!("{seed:#x}"), + "mutation": mutation, + "provenance": { + "language": prog.arch().archid, + "sla_sha256": prog.arch().decode_recipe().map(|recipe| bytes_hex(Sha256::digest(recipe.sla.as_ref()).iter().copied())), + }, + "pcode_budget": budget, "case": { + "version": 1, "architecture": "x86-64", "abi": "sysv-amd64", "cpu_model": "qemu64", + "entry": format!("{entry:#x}"), "return_address": format!("{RETURN:#x}"), + "registers": registers, "memory": memory, + "external_entries": external_calls.keys().collect::>(), "external_calls": external_calls, + }, + "observations": {"raw": raw, "ir": ir}, + })) +} + +pub(crate) fn apply_opcode_mutant( + program: &mut program::Program, + calls: &mut calls::Calls, + env: &Env, + op: Option, +) -> Result, String> { + let Some(op) = op else { return Ok(None) }; + let mutation = crate::mutate::Mutation { + block: 0, + op, + operator: crate::mutate::Operator::Opcode, + }; + let description = crate::mutate::apply(program, calls, env, mutation) + .ok_or_else(|| format!("no opcode mutant at operation {op} in the entry block"))?; + Ok(Some( + json!({ "operator": "opcode", "block": 0, "op": op, "description": description }), + )) +} + +fn halted(backend: &str, halt: Halt) -> Value { + let status = if matches!(halt, Halt::Trap(_)) { + "trap" + } else { + "incomplete" + }; + json!({"backend": backend, "status": status, "reason": halt.render()}) +} + +fn call_records(calls: &[calls::Record]) -> Vec { + calls.iter().map(|c| json!({ + "address": format!("{:#x}", c.at), "target": c.target.map(|at| format!("{at:#x}")), + "indirect": c.indirect, "arguments": c.args.iter().map(|a| format!("{a:#x}")).collect::>(), + "concrete_effect": c.effect.is_some(), + })).collect() +} + +fn event_records(events: &[calls::UserEvent]) -> Vec { + events + .iter() + .map(|e| { + json!({ + "address": format!("{:#x}", e.at), "name": e.name, + "inputs": e.ins.iter().map(|v| format!("{v:#x}")).collect::>(), + }) + }) + .collect() +} + +fn observed_memory(explicit: &ExplicitState, ram: i32, writes: &Writes) -> Vec { + explicit.regions.iter().filter(|r| r.observe).map(|region| { + let mut bytes = region.bytes.clone(); + bytes.resize(region.size as usize, 0); + for (&(_, at), &value) in writes.bytes.range((ram, region.address)..(ram, region.end())) { + bytes[(at - region.address) as usize] = value; + } + json!({"address": format!("{:#x}", region.address), "bytes": bytes_hex(bytes.into_iter())}) + }).collect() +} + +fn bytes_hex(bytes: impl Iterator) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut result = String::with_capacity(bytes.size_hint().0.saturating_mul(2)); + for byte in bytes { + result.push(char::from(HEX[(byte >> 4) as usize])); + result.push(char::from(HEX[(byte & 15) as usize])); + } + result +} diff --git a/decompiler/crates/kuna-verify/src/state/explicit.rs b/decompiler/crates/kuna-verify/src/state/explicit.rs new file mode 100644 index 0000000000..305b90b83c --- /dev/null +++ b/decompiler/crates/kuna-verify/src/state/explicit.rs @@ -0,0 +1,69 @@ +use std::collections::BTreeMap; + +use crate::value::Halt; + +pub(crate) struct Region { + pub address: u64, + pub size: u64, + pub bytes: Vec, + pub permissions: &'static str, + pub observe: bool, +} + +impl Region { + pub fn end(&self) -> u64 { + self.address + self.size + } + + pub fn initial_byte(&self, at: u64) -> u8 { + self.bytes + .get((at - self.address) as usize) + .copied() + .unwrap_or(0) + } +} + +#[derive(Default)] +pub(crate) struct ExplicitState { + pub regions: Vec, + pub registers: BTreeMap, + pub external_entries: BTreeMap, +} + +impl ExplicitState { + fn region(&self, at: u64) -> Option<&Region> { + let i = self + .regions + .partition_point(|r| r.address <= at) + .checked_sub(1)?; + self.regions.get(i).filter(|r| at < r.end()) + } + + pub fn byte(&self, at: u64) -> u8 { + self.region(at).map_or(0, |r| r.initial_byte(at)) + } + + pub fn observable(&self, at: u64) -> bool { + self.region(at).is_some_and(|r| r.observe) + } + + pub fn check(&self, at: u64, size: u64, permission: u8) -> Result<(), Halt> { + let end = at + .checked_add(size) + .ok_or_else(|| Halt::Unsupported("explicit memory access wraps".into()))?; + let mut cursor = at; + while cursor < end { + let region = self + .region(cursor) + .filter(|r| r.permissions.as_bytes().contains(&permission)); + let Some(region) = region else { + return Err(Halt::Trap(format!( + "explicit memory access ({}) at {cursor:#x}", + char::from(permission) + ))); + }; + cursor = region.end(); + } + Ok(()) + } +} diff --git a/decompiler/crates/kuna-verify/src/state/mod.rs b/decompiler/crates/kuna-verify/src/state/mod.rs index 8f1d9bd1af..fd16c1fbd4 100644 --- a/decompiler/crates/kuna-verify/src/state/mod.rs +++ b/decompiler/crates/kuna-verify/src/state/mod.rs @@ -7,6 +7,7 @@ //! pointer is fixed, and image-backed memory reads the load image. Each side then //! keeps its own writes on top. +mod explicit; mod mem; mod stack_inputs; #[cfg(test)] @@ -14,6 +15,7 @@ mod tests; pub(crate) use stack_inputs::StackInputs; pub use mem::*; +pub(crate) use explicit::{ExplicitState, Region}; use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -138,6 +140,7 @@ pub struct Env<'p> { /// Bytes a call pushes for its return address on the stack (0 when the /// model keeps it in a register). pub ret_slot: u32, + pub(crate) explicit: Option, /// Register parameters of type `bool`: a caller passes 0 or 1. pub booleans: Vec<(i32, u64, u32)>, /// The machine's system calls write the kernel's result registers. @@ -295,6 +298,7 @@ impl<'p> Env<'p> { tracked: Vec::new(), ret_addr: None, ret_slot: 0, + explicit: None, booleans: Vec::new(), kernel: Cell::new(true), stub_recovered: Cell::new(false), @@ -475,6 +479,9 @@ impl<'p> Env<'p> { /// Memory either side's caller can observe after the function: anything /// but registers, temporaries and the stack. pub fn observable(&self, space: &AddrSpace, off: u64) -> bool { + if let Some(explicit) = &self.explicit { + return space.get_index() == self.ram.get_index() && explicit.observable(off); + } self.is_memory(space) && !(space.get_index() == self.ram.get_index() && self.in_stack(off, 1)) } @@ -611,6 +618,14 @@ impl<'p> Env<'p> { pub fn initial_byte(&self, run: u32, space: &AddrSpace, off: u64) -> u8 { let idx = space.get_index(); + if let Some(explicit) = &self.explicit { + if idx == self.register.get_index() { + return explicit.registers.get(&off).copied().unwrap_or(0); + } + if idx == self.ram.get_index() { + return explicit.byte(off); + } + } if let Some(&(_, t, size, val)) = self.tracked.iter().find(|&&(sp, t, size, _)| sp == idx && off >= t && off < t + u64::from(size)) { @@ -1202,6 +1217,19 @@ impl<'e, 'p> State<'e, 'p> { if size > MAX_SIZE { return Err(Halt::Unsupported(format!("{size}-byte value"))); } + if let Some(explicit) = &self.env.explicit { + if space.get_index() == self.env.ram.get_index() { + explicit.check(off, size.into(), b'r')?; + } + if space.get_index() == self.env.register.get_index() { + for at in off..off.saturating_add(u64::from(size)) { + let present = self.flags.get(at as usize).is_some_and(|f| f & PRESENT != 0); + if !present && !explicit.registers.contains_key(&at) { + return Err(Halt::Unsupported(format!("unmodeled initial register byte {at:#x}"))); + } + } + } + } if self.is_unique(space) { if let Some(v) = self.unique.exact(off, size) { return Ok(v); @@ -1239,6 +1267,10 @@ impl<'e, 'p> State<'e, 'p> { /// code traps, as it does on the target; one that leaves it as it is (the /// decompiler's value of a global, kept across a call) does nothing. pub fn write(&mut self, space: &AddrSpace, off: u64, size: u32, val: u128) -> Result<(), Halt> { + let explicit_ram = self.env.explicit.as_ref().filter(|_| space.get_index() == self.env.ram.get_index()); + if let Some(explicit) = explicit_ram { + explicit.check(off, size.into(), b'w')?; + } if !self.saved.is_empty() && space.get_index() == self.env.ram.get_index() { let dead: Vec = self.saved.range(off..=off.saturating_add(u64::from(size).max(1) - 1)).map(|(k, _)| *k).collect(); for k in dead { @@ -1266,7 +1298,7 @@ impl<'e, 'p> State<'e, 'p> { } return Ok(()); } - if space.get_index() == self.env.ram.get_index() + if explicit_ram.is_none() && space.get_index() == self.env.ram.get_index() && (self.env.is_readonly(off, size.into()) || self.env.in_code_section(off)) { if self.read(space, off, size)? == val & crate::value::mask(size) { diff --git a/docs/features/diffverify/README.md b/docs/features/diffverify/README.md index 73ce9aca3f..f8a61db59c 100644 --- a/docs/features/diffverify/README.md +++ b/docs/features/diffverify/README.md @@ -432,6 +432,7 @@ run yet. | `c4-decbench-results.md` | slice C4 on the decbench binaries: harness defects found, every `DIFFERS` sorted by cause, the issues filed | | `c5-results.md` | slice C5: concolic inputs | | `tier-l-results.md` | Tier L: SLEIGH p-code against Unicorn, the spec errors found | +| `function-oracle.md` | Replayable three-way function observations with Unicorn | | `triage.md` | how to decide whether a difference is the spec's, the emulator's, the checker's or the harness's | | `mutation.md` | mutation testing: what share of planted faults the check catches | | `record.json` | the slices' measured numbers, for scripts | diff --git a/docs/features/diffverify/function-oracle.md b/docs/features/diffverify/function-oracle.md new file mode 100644 index 0000000000..c92d8e428c --- /dev/null +++ b/docs/features/diffverify/function-oracle.md @@ -0,0 +1,152 @@ +# Function-level Unicorn oracle + +An explicit function case records its original executable bytes, register +state, launch address and mapped memory. Unicorn executes the case without +loading SLEIGH or interpreting p-code. The raw p-code and final IR interpreters +start from the same declared case. The three observations can be examined +independently of the sampled Tier C verdicts. + +## Reproduce + +Use an installed Clang and LLD with the x86-64 ELF target, built SLEIGH specs, +and Python 3.11 or later with `unicorn==2.1.2`. Newer Unicorn releases leave `CR4` +at 0 after the CPU model is chosen, which traps every SSE instruction; the backend sets +`CR4.OSFXSR` and `CR4.OSXMMEXCPT` itself, so a `trap` is the code's. `make +test-diffverify-tools` runs these scripts' tests, as CI does with `z3` installed. + +```sh +(cd decompiler && cargo build --release -p kuna-verify) +python3 scripts/diffverify/test_function_oracle.py +python3 scripts/diffverify/test_function_oracle_integration.py +``` + +To save a case and run it separately: + +```sh +clang --target=x86_64-linux-gnu -O2 -g -ffreestanding -fno-pic \ + -fno-stack-protector -c scripts/diffverify/fixtures/function_oracle_x86_64.c -o fixture.o +ld.lld -static -z separate-loadable-segments -e add fixture.o -o fixture.elf +decompiler/target/release/kuna-verify oracle-case fixture.elf store_loop \ + --sleighpath specs --seed 0x6b756e61 > case.json +python3 scripts/diffverify/function_oracle.py case.json > unicorn.json +``` + +The JSON envelope holds the reusable `case`, the explicit decompiler options +and the two Kuna `observations`. The Unicorn runner also accepts the case on +its own. The fixtures were checked on macOS arm64 with Clang 22.1.8, LLD +22.1.6 and Unicorn 2.1.2. + +| Fixture | Observations | +|---|---| +| `add`, `add_double` | All three give the expected integer or scalar double return bits. | +| `store_loop` | All three give the expected return and writes to initialized and zero-initialized globals. A low raw p-code budget makes the run incomplete. | +| `pointer_update` | All three write the expected bytes through a pointer passed in RDI into the synthetic heap. | +| `call_inner` | The internal call returns with the expected result and memory. Kuna's observations disclose the raw callee effect that the IR can replay. | +| `clobber_rbx` | Unicorn and raw p-code both register an RBX preservation violation. The final IR reports the return value. | +| `caller_write` | Unicorn and raw p-code write a caller-owned stack slot. The final IR leaves its bytes unchanged. A separate Tier C run reports `AGREES(32)`. | +| `system_boundary` | All three reach the system call and preserve the preceding store. The syscall's effects are outside this case model. | +| `unmapped_read` | All three stop on an unmapped load. Unicorn reports a memory fault and Kuna reports a trap. | + +The Tier C control runs matched the pinned reference's 5,079 corpus verdicts +and 1,654 real-image verdicts. The corpus file error also matched. At 32 +input runs per function, all 19,047 individual mutation records matched +after removing timings. + +## Compare observations + +```sh +python3 scripts/diffverify/oracle_compare.py case.json unicorn.json --return RAX:8 +``` + +Declare the observed return storage explicitly as `REGISTER:BYTES` or +`void`. For the `add_double` fixture use `XMM0:8`. This scope comes from +the caller or a known signature. When the final IR reports a different +physical return location or width, the comparison records that limitation. +The Unicorn observation includes a SHA-256 digest of the literal case, +covering the input registers, bytes, memory map and declared machine limits. +The evidence also records the ELF and loaded SLEIGH image digests. + +```sh +python3 scripts/diffverify/oracle_replay.py case.json fixture.elf --return RAX:8 +``` + +Replay takes the same ELF and spec root, regenerates the input and both +Kuna observations, and then executes the archived case in Unicorn. It +checks the image digests, regenerated case and archived Kuna observations. + +- `CROSS_BACKEND_AGREEMENT` records a single completed sample under the + selected return and memory scope. Final IR exposes no full physical + register file. The ABI checks use the two physical executions. +- `COUNTEREXAMPLE` records a disagreement involving Unicorn. The JSON + reports the differing return or termination, a representative byte + address per memory disagreement pattern, or a mismatch at a shared + system-call boundary. At that boundary it compares the call number and + the observed memory prefix. For declared external calls it compares the + target, declared integer inputs and observed memory prefix. Candidate + causes are diagnostic hypotheses. +- `INCONCLUSIVE` retains the evidence from available observations. + A matching trap, a shared ABI violation, an incomplete execution, + replayed callee effects, or missing return coverage limits the result. + The comparator also retains disagreements found only within the two + Kuna executions so they can be inspected. + +The fixture tests use an isolated SLEIGH build that changes a register +`ADD` into subtraction. Raw p-code and final IR agree on the same wrong +return and writes. Unicorn runs the unchanged ELF and the three-way +report identifies both differences. Build `slacomp` for this test +(`cargo build --release -p kuna-slacomp` from `decompiler`). + +Use `--external-entry ADDR ARITY` on `oracle-case` to treat the first +declared external call reached by the selected function as an observation +boundary. `ARITY` counts full-width SysV integer arguments in registers. +The comparison requires all three runs to stop at the same call site before +any of them models the call's effects. It reports the prefix separately +from returned runs. Floating-point and stack arguments, nested external +boundaries and the call's effects remain outside this projection. + +## Input model and coverage + +- The exporter handles fixed-address, little-endian x86-64 ELF executables + with nonoverlapping load pages. It reads the `PT_LOAD` bytes directly via + the ELF headers and zero-fills the rest of each declared region. It + rejects interpreters, dynamic segments, allocated relocations and TLS. + The runner can also execute a hand-authored map with pre-applied + relocations. It has no process loader or OS environment. +- The version 1 case records SysV AMD64 and the Unicorn `qemu64` CPU model. + Entry state includes general-purpose and XMM registers, arithmetic flags, + segment bases and initial SSE/x87 environment. The exporter supplies + seeded words, an aligned stack, a synthetic heap and an unmapped return + sentinel. It observes writable ELF data, the heap and the modeled caller + stack page above the synthetic return slot. Use `--input-reg RDI 0x60000100` + to pass a heap pointer, and supply other integer or vector register arguments + the same way. +- `memory` entries have a page-aligned hexadecimal `address`, byte `size`, + `permissions` (`r`, `rw`, `rx` or `x`), optional initial `bytes` in hex, + and optional `observe: true` for writable pages. The total is capped at + 16 MiB. Only the declared map is available for guest accesses. Checkpoints + use named registers with hexadecimal values, including up to 128 bits in + XMM registers. The runner checks the return slot contents and stack + alignment at entry. +- Unicorn reports the reached return, trap, fault or incomplete boundary, + captures registers and watched memory, and checks the ABI-preserved + integer registers and RSP on return. Declared external entry addresses + stop execution and record physical argument registers as well as the + predecessor PC. System calls and unsupported environmental dependencies + such as timestamp reads stop before any modeled effect. Limits default + to 10,000 Unicorn instructions and a 1 s emulator timeout. Kuna reports + a separate p-code operation budget. +- The Kuna executor records raw calls and any concrete effects available + for graph replay. Calls limit coverage since graph replay can share the + raw execution's effects and stubs can supply hypothetical outcomes. + Final IR reports its claimed return storage, width and value. Physical + registers absent from the IR are available only from the raw and Unicorn + sides. Failed interpreter runs can lack a final memory snapshot. +- CPU features and the syscall ABI are limited to the declared model. + Comparison support for floating point beyond the scalar fixture, system + ABI variants, runtime relocations and external interactions requires + further validation. Unicorn shares QEMU's execution lineage. A recorded + run provides evidence only for its particular map, entry state and + observed effects. + +See the [verification roadmap](verification-roadmap.md) for the reference +measurements, dependency audit and subsequent equivalence checks. diff --git a/scripts/diffverify/fixtures/function_oracle_x86_64.c b/scripts/diffverify/fixtures/function_oracle_x86_64.c new file mode 100644 index 0000000000..fd95fcd601 --- /dev/null +++ b/scripts/diffverify/fixtures/function_oracle_x86_64.c @@ -0,0 +1,180 @@ +typedef unsigned long long u64; + +volatile u64 counter = 0x123456789abcdef0ULL; +volatile u64 zeroed; +volatile u64 loop_memory; + +u64 add(u64 a, u64 b) { + return a + b; +} + +u64 extend_signed(int a) { + return (u64)(long long)a; +} + +u64 extend_unsigned(unsigned a) { + return (u64)a; +} + +u64 bit_ops(u64 a, u64 b) { + return ((a >> 13) + (b << 9)) ^ b; +} + +u64 rotate(u64 a) { + return (a >> 13) | (a << 51); +} + +u64 select_cmov(u64 a, u64 yes, u64 no) { + __asm__("testq %2, %2; cmovneq %1, %0" : "+r"(no) : "r"(yes), "r"(a) : "cc"); + return no; +} + +u64 partial_register(u64 a, u64 b) { + __asm__("movb %b1, %b0" : "+&a"(a) : "q"(b)); + return a; +} + +u64 add_carry(u64 a, u64 b) { + unsigned char carry; + __asm__("addq %2, %0; setc %1" : "+&r"(a), "=q"(carry) : "r"(b) : "cc"); + return a + carry; +} + +u64 signed_overflow(u64 a, u64 b) { + unsigned char overflow; + __asm__("addq %2, %0; seto %1" : "+&r"(a), "=q"(overflow) : "r"(b) : "cc"); + return a + overflow; +} + +u64 select_branch(u64 flag, u64 yes, u64 no) { + return flag ? yes : no; +} + +u64 store_if(u64 *p, u64 flag) { + if (flag & 1) + *p = 17; + return *p; +} + +__attribute__((noinline, optnone)) u64 frame_add(u64 a, u64 b) { + return a + b; +} + +u64 count_down(u64 n) { + __asm__("1: decq %0; jne 1b" : "+r"(n) : : "cc"); + return n; +} + +u64 add_with_loop(u64 a, u64 b, u64 n) { + u64 result = a + b; + __asm__("1: addq $3, %0; decq %1; jne 1b" : "+&r"(result), "+r"(n) : : "cc"); + return result; +} + +u64 add_to_observed_global(u64 count) { +#pragma clang loop unroll(disable) + do { + loop_memory += 3; + --count; + } while (count); + return loop_memory; +} + +__asm__( + ".type repeated_caller_write,@function\n" + ".globl repeated_caller_write\n" + "repeated_caller_write:\n" + "1: mov %rdi, 8(%rsp)\n" + " dec %rsi\n" + " jne 1b\n" + " mov %rdi, %rax\n" + " ret\n" + ".size repeated_caller_write, .-repeated_caller_write\n" +); + +u64 loop_with_duplicate_paths(u64 value, u64 count, u64 flag) { + __asm__("1: testq %2, %2; jz 2f; addq $3, %0; jmp 3f; " + "2: leaq 3(%0), %0; 3: decq %1; jne 1b" + : "+&r"(value), "+&r"(count) : "r"(flag) : "cc"); + return value; +} + +u64 cannot_rank_all_inputs(u64 n) { + __asm__("1: addq $2, %0; jne 1b" : "+r"(n) : : "cc"); + return n; +} + +u64 dispatch(u64 selector, u64 x) { + switch (selector) { + case 0: return x + 15; + case 1: return x * 17; + case 2: return x ^ 7923; + case 3: return x << 4; + case 4: return x - 16; + case 5: return x | 0x13; + default: return x ^ 0x7fff; + } +} + +double add_double(double a, double b) { + return a + b; +} + +u64 pointer_update(u64 *p, u64 a) { + u64 result = *p + a; + *p = result; + return result; +} + +__attribute__((noinline)) static u64 inner(u64 a) { + u64 result = counter + a; + counter = result; + return result; +} + +u64 call_inner(u64 a) { + return inner(a) + 1; +} + +u64 store_loop(u64 a, u64 n) { + u64 result = counter; +#pragma clang loop unroll(disable) + for (n &= 7; n != 0; --n) { + result = result * 3 + a; + counter = result; + } + zeroed = result; + return result; +} + +__asm__( + ".type clobber_rbx,@function\n" + ".globl clobber_rbx\n" + "clobber_rbx:\n" + " mov $42, %ebx\n" + " lea 1(%rdi), %rax\n" + " ret\n" + ".size clobber_rbx, .-clobber_rbx\n" + ".type system_boundary,@function\n" + ".globl system_boundary\n" + "system_boundary:\n" + " movq $7, counter(%rip)\n" + " mov $39, %eax\n" + " syscall\n" + " movq $42, counter(%rip)\n" + " ret\n" + ".size system_boundary, .-system_boundary\n" + ".type unmapped_read,@function\n" + ".globl unmapped_read\n" + "unmapped_read:\n" + " mov 0, %rax\n" + " ret\n" + ".size unmapped_read, .-unmapped_read\n" + ".type caller_write,@function\n" + ".globl caller_write\n" + "caller_write:\n" + " mov %rdi, 8(%rsp)\n" + " mov %rdi, %rax\n" + " ret\n" + ".size caller_write, .-caller_write\n" +); diff --git a/scripts/diffverify/function_oracle.py b/scripts/diffverify/function_oracle.py new file mode 100644 index 0000000000..72762fb8b0 --- /dev/null +++ b/scripts/diffverify/function_oracle.py @@ -0,0 +1,312 @@ +"""Execute an explicit DiffVerify function case with Unicorn. + +Run with `python3 scripts/diffverify/function_oracle.py CASE.json`. +The request describes original bytes, a CPU model, and the full address +space available to the guest. The runner emits one JSON observation. +""" + +import argparse +import json +import sys +from dataclasses import dataclass + +import unicorn as uc +from unicorn import x86_const as x86 +from oracle_protocol import DEFAULT_LIMITS, MAX_MAPPED, case_digest, load_request + +VERSION = 1 +PAGE = 4096 +MAX_USER_ADDRESS = 1 << 47 +GPR = ("RAX", "RBX", "RCX", "RDX", "RSI", "RDI", "RBP", "RSP", *(f"R{i}" for i in range(8, 16))) +PRESERVED = ("RBX", "RBP", "R12", "R13", "R14", "R15") +INTEGER_ARGS = ("RDI", "RSI", "RDX", "RCX", "R8", "R9") +VECTOR_ARGS = tuple(f"XMM{i}" for i in range(8)) +FP = tuple(f"FP{i}" for i in range(8)) +DEFAULTS = dict.fromkeys((*GPR, "FS_BASE", "GS_BASE", *(f"XMM{i}" for i in range(16)), *FP), 0) +DEFAULTS.update(RFLAGS=2, MXCSR=0x1f80, FPCW=0x037f, FPSW=0, FPTAG=0xffff) +REGISTER_WIDTHS = {name: 64 for name in (*GPR, "FS_BASE", "GS_BASE", "RFLAGS")} +REGISTER_WIDTHS.update({f"XMM{i}": 128 for i in range(16)}) +REGISTER_WIDTHS.update({name: 80 for name in FP}) +REGISTER_WIDTHS.update(MXCSR=32, FPCW=16, FPSW=16, FPTAG=16) +PERMISSIONS = {"r": uc.UC_PROT_READ, "w": uc.UC_PROT_WRITE, "x": uc.UC_PROT_EXEC} + + +def unsigned(value, bits, name): + if not isinstance(value, str) or not value.startswith("0x"): + raise ValueError(f"{name} requires a hexadecimal string") + digits = value[2:] + if not digits or any(c not in "0123456789abcdefABCDEF" for c in digits) or len(digits) > (bits + 3) // 4: + raise ValueError(f"{name} requires an unsigned {bits}-bit value") + n = int(digits, 16) + if n >= 1 << bits: + raise ValueError(f"{name} requires an unsigned {bits}-bit value") + return n + + +def count(value, low, high, name): + if type(value) is not int or not low <= value <= high: + raise ValueError(f"{name} must be an integer in [{low}, {high}]") + return value + + +def read_register(machine, name): + value = machine.reg_read(getattr(x86, f"UC_X86_REG_{name}")) + if name in FP: + mantissa, sign_exponent = value + return mantissa | (sign_exponent << 64) + return value + + +def write_register(machine, name, value): + if name in FP: + value = (value & ((1 << 64) - 1), value >> 64) + machine.reg_write(getattr(x86, f"UC_X86_REG_{name}"), value) + + +@dataclass(frozen=True) +class Region: + start: int + size: int + permissions: str + data: bytes + observe: bool + + def contains(self, at, length=1): + return self.start <= at and at + length <= self.start + self.size + + +@dataclass(frozen=True) +class Case: + entry: int + sentinel: int + registers: dict + regions: tuple + external_entries: frozenset + instructions: int + timeout_us: int + + @classmethod + def parse(cls, spec): + count(spec["version"], VERSION, VERSION, "version") + if spec["architecture"] != "x86-64" or spec["abi"] != "sysv-amd64": + raise ValueError("expected version 1, x86-64, sysv-amd64") + if spec.get("cpu_model", "qemu64") != "qemu64": + raise ValueError("unsupported x86 CPU model") + entry = unsigned(spec["entry"], 47, "entry") + sentinel = unsigned(spec["return_address"], 47, "return_address") + if not sentinel: + raise ValueError("return_address must be nonzero") + registers = DEFAULTS.copy() + supplied = spec["registers"] + if "RSP" not in supplied: + raise ValueError("the caller must supply RSP") + for name, value in supplied.items(): + if name not in REGISTER_WIDTHS: + raise ValueError(f"unsupported register {name}") + registers[name] = unsigned(value, REGISTER_WIDTHS[name], name) + if registers["RFLAGS"] & ~0xed7 or not (registers["RFLAGS"] & 2): + raise ValueError("only the arithmetic flags, DF, IF and fixed bit 1 are supported") + if registers["RSP"] % 16 != 8: + raise ValueError("SysV AMD64 function entry requires RSP mod 16 = 8") + regions = [] + for item in spec["memory"]: + at = unsigned(item["address"], 47, "memory address") + size = count(item["size"], PAGE, MAX_MAPPED, "region size") + if (at | size) & (PAGE - 1) or at + size > MAX_USER_ADDRESS: + raise ValueError("memory regions must be page aligned within the low canonical half") + permissions = item["permissions"] + if permissions not in ("r", "rw", "rx", "x"): + raise ValueError(f"unsupported memory permissions {permissions!r}") + data = bytes.fromhex(item.get("bytes", "")) + if len(data) > size: + raise ValueError("region bytes exceed its declared size") + observe = item.get("observe", False) + if type(observe) is not bool or (observe and permissions != "rw"): + raise ValueError("observe requires a writable region") + regions.append(Region(at, size, permissions, data, observe)) + regions.sort(key=lambda r: r.start) + if sum(r.size for r in regions) > MAX_MAPPED or any(a.start + a.size > b.start for a, b in zip(regions, regions[1:])): + raise ValueError("memory regions overlap or exceed the mapping budget") + if not any(r.contains(entry) and "x" in r.permissions for r in regions): + raise ValueError("entry is outside executable memory") + if any(r.contains(sentinel) for r in regions): + raise ValueError("return address must be an unmapped sentinel") + rsp = registers["RSP"] + stack = next((r for r in regions if r.contains(rsp, 8) and r.permissions == "rw"), None) + if stack is None: + raise ValueError("RSP must name a writable region") + off = rsp - stack.start + if int.from_bytes(stack.data[off:off + 8], "little") != sentinel: + raise ValueError("the initial stack return slot must contain the sentinel") + external = frozenset(unsigned(v, 47, "external entry") for v in spec.get("external_entries", [])) + if entry in external or sentinel in external: + raise ValueError("external entries cannot coincide with the entry or return address") + limit = spec.get("limits", {}) + instructions = count(limit.get("instructions", DEFAULT_LIMITS["instructions"]), 1, 1_000_000, "instruction limit") + timeout_us = count(limit.get("timeout_us", DEFAULT_LIMITS["timeout_us"]), 1, 10_000_000, "timeout_us") + return cls(entry, sentinel, registers, tuple(regions), external, instructions, timeout_us) + + +def near_return(code): + return code == b"\xc3" or code == b"\xf3\xc3" or (len(code) == 3 and code[0] == 0xc2) + + +def unmodeled_environment(code): + prefixes = b"\xf0\xf2\xf3\x2e\x36\x3e\x26\x64\x65\x66\x67" + bytes(range(0x40, 0x50)) + instruction = code.lstrip(prefixes) + if instruction in (b"\x0f\x31", b"\x0f\x01\xf9"): + return "timestamp-counter" + if instruction[:2] == b"\x0f\xc7" and len(instruction) == 3 and instruction[2] >= 0xf0: + return "hardware-random" + if instruction and instruction[0] in range(0x6c, 0x70): + return "string-port-io" + return None + + +CR4_SSE = 0x600 +"""CR4's OSFXSR and OSXMMEXCPT bits. Unicorn 2.1.4 leaves CR4 at 0 after +`ctl_set_cpu_model`, and every SSE instruction then traps.""" + + +class UnicornBackend: + """One execution backend for the versioned function case.""" + + def run(self, case): + machine = uc.Uc(uc.UC_ARCH_X86, uc.UC_MODE_64) + machine.ctl_set_cpu_model(x86.UC_CPU_X86_QEMU64) + machine.reg_write(x86.UC_X86_REG_CR4, machine.reg_read(x86.UC_X86_REG_CR4) | CR4_SSE) + for region in case.regions: + mask = sum(PERMISSIONS[p] for p in region.permissions) + machine.mem_map(region.start, region.size, mask) + if region.data: + machine.mem_write(region.start, region.data) + for name, value in case.registers.items(): + write_register(machine, name, value) + + status, reason, event = None, None, None + steps, last_pc, last_returns = 0, None, False + + def stop(outcome, why, observed_event=None): + nonlocal status, reason, event + status, reason, event = outcome, why, observed_event + machine.emu_stop() + + def regs(names): + return {name: hex(read_register(machine, name)) for name in names} + + def external(at): + stop("incomplete", "external-entry", { + "kind": "external-entry", "target": hex(at), "from": None if last_pc is None else hex(last_pc), + "registers": regs((*INTEGER_ARGS, *VECTOR_ARGS, "RAX", "RSP")), + }) + + def on_code(_machine, at, size, _user): + nonlocal steps, last_pc, last_returns + if at in case.external_entries: + external(at) + return + steps += 1 + last_pc = at + last_returns = False + if not 1 <= size <= 15: + return + code = bytes(machine.mem_read(at, size)) + last_returns = near_return(code) + boundary = unmodeled_environment(code) + if boundary: + stop("incomplete", boundary, {"kind": boundary, "address": hex(at)}) + + def on_invalid_memory(_machine, access, at, size, _value, _user): + if access == uc.UC_MEM_FETCH_UNMAPPED and at in case.external_entries: + external(at) + else: + stop("fault", "memory-access", {"kind": "memory-access", "access": access, "address": hex(at), "size": size}) + return False + + def on_syscall(_machine, _user): + stop("incomplete", "system-call", { + "kind": "system-call", "address": hex(last_pc), + "registers": regs(("RAX", "RDI", "RSI", "RDX", "R10", "R8", "R9")), + }) + + def on_interrupt(_machine, number, _user): + stop("trap", "interrupt", {"kind": "interrupt", "number": number}) + + def on_port_in(_machine, port, size, _user): + stop("incomplete", "port-read", {"kind": "port-read", "port": port, "size": size}) + return 0 + + def on_port_out(_machine, port, size, value, _user): + stop("incomplete", "port-write", {"kind": "port-write", "port": port, "size": size, "value": hex(value)}) + + machine.hook_add(uc.UC_HOOK_CODE, on_code) + machine.hook_add(uc.UC_HOOK_MEM_INVALID, on_invalid_memory) + machine.hook_add(uc.UC_HOOK_INTR, on_interrupt) + machine.hook_add(uc.UC_HOOK_INSN, on_syscall, None, 1, 0, x86.UC_X86_INS_SYSCALL) + machine.hook_add(uc.UC_HOOK_INSN, on_syscall, None, 1, 0, x86.UC_X86_INS_SYSENTER) + machine.hook_add(uc.UC_HOOK_INSN, on_port_in, None, 1, 0, x86.UC_X86_INS_IN) + machine.hook_add(uc.UC_HOOK_INSN, on_port_out, None, 1, 0, x86.UC_X86_INS_OUT) + + try: + machine.emu_start(case.entry, case.sentinel, timeout=case.timeout_us, count=case.instructions) + except uc.UcError as error: + if status is None: + status = "trap" if error.errno == uc.UC_ERR_INSN_INVALID else "incomplete" + reason = f"unicorn-error-{error.errno}" + + rip = machine.reg_read(x86.UC_X86_REG_RIP) + rsp = read_register(machine, "RSP") + if status is None: + if machine.query(uc.UC_QUERY_TIMEOUT): + status, reason = "incomplete", "timeout" + elif rip == case.sentinel: + if last_returns: + status = "returned" + else: + status, reason = "incomplete", "non-return-transfer-to-sentinel" + elif steps >= case.instructions: + status, reason = "incomplete", "instruction-limit" + else: + status, reason = "incomplete", "stopped-before-return" + + return { + "version": VERSION, + "backend": "unicorn", + "backend_version": uc.__version__, + "cpu_model": "qemu64", + "status": status, + "reason": reason, + "event": event, + "instructions": steps, + "pc": hex(rip), + "registers": regs(DEFAULTS), + "memory": [ + {"address": hex(r.start), "bytes": bytes(machine.mem_read(r.start, r.size)).hex()} + for r in case.regions if r.observe + ], + "abi_violations": [ + name for name in PRESERVED if read_register(machine, name) != case.registers[name] + ] + (["RSP"] if rsp != case.registers["RSP"] + 8 else []) if status == "returned" else [], + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("case", help="JSON case file, or - for standard input") + args = parser.parse_args() + try: + if args.case == "-": + request = load_request(sys.stdin.buffer) + else: + with open(args.case, "rb") as file: + request = load_request(file) + spec = request.get("case", request) + observation = UnicornBackend().run(Case.parse(spec)) + observation["case_sha256"] = case_digest(spec) + print(json.dumps(observation, sort_keys=True)) + except (AttributeError, KeyError, TypeError, ValueError, OSError, uc.UcError) as error: + parser.exit(2, f"function oracle: {error}\n") + + +if __name__ == "__main__": + main() diff --git a/scripts/diffverify/oracle_compare.py b/scripts/diffverify/oracle_compare.py new file mode 100644 index 0000000000..fc0bf172c0 --- /dev/null +++ b/scripts/diffverify/oracle_compare.py @@ -0,0 +1,310 @@ +"""Compare a saved kuna-verify oracle-case and its Unicorn observation.""" + +import argparse +import json +from dataclasses import dataclass +from itertools import combinations + +from oracle_protocol import DEFAULT_LIMITS, MAX_MAPPED, case_digest, load_request + +BACKENDS = ("unicorn", "raw-pcode", "final-ir") +PRESERVED = ("RBX", "RBP", "R12", "R13", "R14", "R15", "RSP") +CALL_ARGUMENTS = ("RDI", "RSI", "RDX", "RCX", "R8", "R9") +INTEGER_RETURN_NAMES = { + "RAX": {1: "AL", 2: "AX", 4: "EAX", 8: "RAX"}, + "RDX": {1: "DL", 2: "DX", 4: "EDX", 8: "RDX"}, +} + + +@dataclass(frozen=True) +class Return: + register: str + size: int + ir_storage: str + + @classmethod + def parse(cls, text): + if text == "void": + return cls("", 0, "") + reg, colon, width = text.partition(":") + if not colon or width not in ("1", "2", "4", "8", "16"): + raise ValueError("return must be void or REGISTER:BYTES") + size = int(width) + if reg in INTEGER_RETURN_NAMES: + storage = INTEGER_RETURN_NAMES[reg].get(size) + elif reg in ("XMM0", "XMM1"): + storage = {4: reg + "_Da", 8: reg + "_Qa", 16: reg}.get(size) + else: + storage = None + if storage is None: + raise ValueError("unsupported return register or width") + return cls(reg, size, storage) + + +def named_observations(capture, unicorn): + observations = capture["observations"] + results = dict(zip(BACKENDS, (unicorn, observations["raw"], observations["ir"]))) + if any(obs["backend"] != name for name, obs in results.items()): + raise ValueError("observation backend labels do not match the envelope") + return results + + +def differences(values): + if len(values) < 2 or len(set(values.values())) == 1: + return None + candidates = { + "unicorn": ["shared-lift-or-pcode-semantics", "isa-or-environment-model"], + "raw-pcode": ["raw-pcode-execution", "machine-abi-model"], + "final-ir": ["decompiler-transformation", "final-ir-execution", "recovered-abi"], + } + outlier = next((side for side, value in values.items() if sum(v == value for v in values.values()) == 1), None) + plausible = ( + candidates[outlier] if len(values) == 3 and len(set(values.values())) == 2 + else ["unresolved-backend-disagreement"] + ) + return {"values": values, "candidate_causes": plausible} + + +def add_difference(findings, observable, values, **location): + difference = differences(values) + if difference: + findings.append({"observable": observable, **location, **difference}) + + +def watched_regions(case): + watched = {} + total = 0 + for region in case["memory"]: + if not region.get("observe"): + continue + at, size = int(region["address"], 16), region["size"] + if type(size) is not int or size <= 0 or at in watched: + raise ValueError("invalid observed memory region in case") + total += size + if total > MAX_MAPPED: + raise ValueError("observed memory exceeds the case mapping limit") + watched[at] = size + return watched + + +def memory_snapshot(observation, watched): + snapshot = {} + for region in observation["memory"]: + at = int(region["address"], 16) + if at in snapshot or at not in watched or len(region["bytes"]) != 2 * watched[at]: + raise ValueError("observation memory does not match the declared regions") + data = bytes.fromhex(region["bytes"]) + if len(data) != watched[at]: + raise ValueError("observation memory contains an invalid hex byte") + snapshot[at] = data + if set(snapshot) != set(watched): + raise ValueError("observation omits declared memory regions") + return snapshot + + +def compare_memory(findings, case, observations): + watched = watched_regions(case) + snapshots = {name: memory_snapshot(obs, watched) for name, obs in observations.items()} + for at in sorted(watched): + names = tuple(snapshots) + regions = [snapshot[at] for snapshot in snapshots.values()] + if len(set(regions)) <= 1: + continue + # One witness for each combination of agreeing backends in the region. + patterns = set() + for off, byte_values in enumerate(zip(*regions)): + if len(set(byte_values)) == 1: + continue + pattern = tuple(lhs == rhs for lhs, rhs in combinations(byte_values, 2)) + if not all(pattern) and pattern not in patterns: + patterns.add(pattern) + values = dict(zip(names, map(hex, byte_values))) + add_difference(findings, "memory-byte", values, address=hex(at + off)) + if len(patterns) == (1 if len(names) == 2 else 4): + break + + +def compare_return(findings, returned, expected, limitations): + if not expected.size: + if "final-ir" in returned and returned["final-ir"].get("return") is not None: + limitations.append("final-ir-return-declaration-differs-from-void-scope") + return + values = {} + mask = (1 << (expected.size * 8)) - 1 + for name, obs in returned.items(): + if name == "final-ir": + declared = obs.get("return") + if not declared or declared["storage"] != expected.ir_storage or declared["size"] != expected.size: + limitations.append("final-ir-return-storage-outside-projection") + continue + value = int(declared["value"], 16) + if not 0 <= value <= mask: + raise ValueError("final IR return exceeds the reported width") + else: + value = int(obs["registers"][expected.register], 16) & mask + values[name] = hex(value) + add_difference(findings, "return", values, register=expected.register, bytes=expected.size) + + +def syscall_prefix(observations): + unicorn, raw, ir = [observations[name] for name in BACKENDS] + event = unicorn.get("event") + if unicorn["status"] != "incomplete" or unicorn.get("reason") != "system-call" or not event: + return None + for obs in (raw, ir): + trace = obs.get("events", []) + if obs["status"] != "incomplete" or obs.get("calls") or len(trace) != 1: + return None + if trace[0]["name"] != "syscall" or trace[0]["address"] != event["address"]: + return None + return event + + +def external_call_prefix(findings, case, observations): + unicorn, raw, ir = (observations[name] for name in BACKENDS) + event = unicorn.get("event") + if unicorn["status"] != "incomplete" or unicorn.get("reason") != "external-entry" or not event: + return False + signatures = case.get("external_calls", {}) + at = event["from"] + targets = {"unicorn": event["target"]} + for name, obs in (("raw-pcode", raw), ("final-ir", ir)): + calls, events = obs.get("calls", []), obs.get("events", []) + if obs["status"] != "incomplete" or len(calls) != 1 or len(events) != 1: + return False + if calls[0]["address"] != at or events[0]["address"] != at or events[0]["name"] != "external-call": + return False + targets[name] = calls[0]["target"] + if any(target not in signatures for target in targets.values()): + raise ValueError("external call is outside the declared signatures") + + compare_memory(findings, case, observations) + add_difference(findings, "external-call-target", targets, address=at) + if len(set(targets.values())) == 1: + arity = signatures[event["target"]] + if type(arity) is not int or not 0 <= arity <= len(CALL_ARGUMENTS): + raise ValueError("invalid external call arity") + args = ir["calls"][0]["arguments"] + add_difference(findings, "external-call-arity", { + "unicorn": arity, "raw-pcode": arity, "final-ir": len(args), + }, address=at) + for i, register in enumerate(CALL_ARGUMENTS[:arity]): + values = { + "unicorn": hex(int(event["registers"][register], 16)), + "raw-pcode": hex(int(raw["registers"][register], 16)), + } + if i < len(args): + values["final-ir"] = hex(int(args[i], 16)) + add_difference(findings, "external-call-argument", values, address=at, index=i, register=register) + return True + + +def compare(capture, unicorn, expected): + case = capture["case"] + if (capture["version"], case["version"], unicorn["version"]) != (1, 1, 1): + raise ValueError("unsupported oracle format version") + if (case["architecture"], case["abi"]) != ("x86-64", "sysv-amd64"): + raise ValueError("case is outside the x86-64 SysV comparison model") + digest = case_digest(case) + if unicorn.get("case_sha256") != digest or unicorn.get("cpu_model") != case["cpu_model"]: + raise ValueError("Unicorn observation does not identify the same case and CPU model") + observations = named_observations(capture, unicorn) + statuses = {name: obs["status"] for name, obs in observations.items()} + returned = {name: obs for name, obs in observations.items() if obs["status"] == "returned"} + findings, limitations = [], [] + if len(returned) != 3: + limitations.append("one-or-more-backends-did-not-complete") + terminal = { + name: "returned" if status == "returned" else "fault-or-trap" + for name, status in statuses.items() if status in ("returned", "fault", "trap") + } + add_difference(findings, "termination", terminal) + compare_return(findings, returned, expected, limitations) + if len(returned) >= 2: + compare_memory(findings, case, returned) + syscall = syscall_prefix(observations) + if syscall: + compare_memory(findings, case, observations) + number = {"unicorn": hex(int(syscall["registers"]["RAX"], 16))} + number["raw-pcode"] = hex(int(observations["raw-pcode"]["registers"]["RAX"], 16)) + inputs = observations["final-ir"]["events"][0]["inputs"] + if inputs: + number["final-ir"] = hex(int(inputs[0], 16)) + add_difference(findings, "syscall-number", number, address=syscall["address"]) + limitations.append("system-call-effects-and-argument-arity-unmodeled") + external = external_call_prefix(findings, case, observations) + if external: + limitations.append("external-call-effects-unmodeled") + physical = {name: obs for name, obs in returned.items() if name != "final-ir"} + if len(physical) == 2: + for register in PRESERVED: + values = { + name: hex(int(obs["registers"][register], 16)) for name, obs in physical.items() + } + add_difference(findings, "abi-preserved-register", values, register=register) + if any(obs["abi_violations"] for obs in physical.values()): + limitations.append("machine-execution-violated-abi") + if any(obs.get("raw_callee_effects_available") for obs in observations.values()): + limitations.append("raw-callee-effects-available-to-final-ir") + + confirmed = any("unicorn" in finding["values"] for finding in findings) + classification = ( + "COUNTEREXAMPLE" if confirmed else + "INCONCLUSIVE" if findings or limitations else + "CROSS_BACKEND_AGREEMENT" + ) + return { + "version": 1, + "function": capture["function"], + "classification": classification, + "case_sha256": digest, + "entry": case["entry"], + "decompile_options": capture.get("decompile_options", []), + "provenance": capture.get("provenance", {}), + "coverage": { + "return": "void" if not expected.size else f"{expected.register}:{expected.size}", + "declared_memory_bytes": sum(watched_regions(case).values()), + "memory_backends": list(observations) if syscall or external else (list(returned) if len(returned) >= 2 else []), + "physical_abi_backends": list(physical) if len(physical) == 2 else [], + "boundary": ( + "external-call-prefix" if external else "syscall-prefix" if syscall else + "function-return" if returned else None + ), + "full_return_comparison": len(returned) == 3 and not any( + limitation.startswith("final-ir-return") for limitation in limitations + ), + "backend_status": statuses, + }, + "backends": { + "unicorn": unicorn["backend_version"], + "raw-pcode": "Kuna SLEIGH/p-code", + "final-ir": "Kuna final IR/p-code", + }, + "assumptions": [case["abi"], case["cpu_model"], "raw-pcode-and-final-ir-share-sleigh-and-pcode-semantics"], + "limits": {"pcode_budget": capture["pcode_budget"], "unicorn": {**DEFAULT_LIMITS, **case.get("limits", {})}}, + "findings": findings, + "limitations": limitations, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("capture", help="JSON envelope from kuna-verify oracle-case") + parser.add_argument("unicorn", help="JSON observation from function_oracle.py") + parser.add_argument("--return", dest="return_spec", required=True, help="void or REGISTER:BYTES") + args = parser.parse_args() + try: + expected = Return.parse(args.return_spec) + with open(args.capture, "rb") as file: + capture = load_request(file) + with open(args.unicorn, "rb") as file: + result = compare(capture, load_request(file), expected) + except (AttributeError, KeyError, TypeError, ValueError, OSError) as error: + parser.exit(2, f"oracle comparison: {error}\n") + print(json.dumps(result, sort_keys=True)) + if result["classification"] == "COUNTEREXAMPLE": + parser.exit(1) + + +if __name__ == "__main__": + main() diff --git a/scripts/diffverify/oracle_protocol.py b/scripts/diffverify/oracle_protocol.py new file mode 100644 index 0000000000..a901492a75 --- /dev/null +++ b/scripts/diffverify/oracle_protocol.py @@ -0,0 +1,23 @@ +"""Shared helpers for the versioned function-oracle JSON protocol.""" + +import hashlib +import json + +MAX_MAPPED = 16 * 1024 * 1024 +MAX_REQUEST = 6 * MAX_MAPPED + 2 * 1024 * 1024 +DEFAULT_LIMITS = {"instructions": 10_000, "timeout_us": 1_000_000} + + +def case_digest(spec): + canonical = json.dumps(spec, sort_keys=True, separators=(",", ":"), ensure_ascii=True) + return hashlib.sha256(canonical.encode("ascii")).hexdigest() + + +def load_request(file): + data = file.read(MAX_REQUEST + 1) + if len(data) > MAX_REQUEST: + raise ValueError("request exceeds the byte limit") + decoded = json.loads(data) + if not isinstance(decoded, dict): + raise ValueError("request must be a JSON object") + return decoded diff --git a/scripts/diffverify/oracle_replay.py b/scripts/diffverify/oracle_replay.py new file mode 100644 index 0000000000..dbb97da898 --- /dev/null +++ b/scripts/diffverify/oracle_replay.py @@ -0,0 +1,71 @@ +"""Rerun all three backends for an archived Kuna function case.""" + +import argparse +import json +import subprocess +import sys +from hashlib import file_digest +from pathlib import Path + +from oracle_compare import Return, compare +from oracle_protocol import load_request + +ROOT = Path(__file__).resolve().parents[2] +RUNNER = Path(__file__).with_name("function_oracle.py") +GPR_INPUTS = ("RAX", "RBX", "RCX", "RDX", "RSI", "RDI", "RBP", *(f"R{i}" for i in range(8, 16))) +INPUTS = (*GPR_INPUTS, *(f"XMM{i}" for i in range(16)), "RFLAGS") + + +def replay(capture, binary, specs, verify, expected): + case = capture["case"] + recorded = capture["provenance"] + with open(binary, "rb") as file: + if file_digest(file, "sha256").hexdigest() != recorded["elf_sha256"]: + raise ValueError("ELF does not match the archived case") + command = [ + verify, "oracle-case", binary, case["entry"], "--sleighpath", specs, + "--seed", capture["seed"], "--budget", str(capture["pcode_budget"]), + ] + for name, value in capture["decompile_options"]: + command.extend(("--option", name, value)) + for address, arity in case.get("external_calls", {}).items(): + command.extend(("--external-entry", address, str(arity))) + for address, value in capture.get("initial_memory_overrides", {}).items(): + command.extend(("--memory-byte", address, value)) + if mutation := capture.get("mutation"): + command.extend(("--opcode-mutant", str(mutation["op"]))) + for register in INPUTS: + command.extend(("--input-reg", register, case["registers"][register])) + reproduced = json.loads(subprocess.check_output(command, timeout=60)) + if reproduced["case"] != case or reproduced["provenance"] != recorded: + raise ValueError("ELF, SLEIGH configuration or regenerated input differs") + if reproduced["observations"] != capture["observations"]: + raise ValueError("regenerated Kuna observations differ from the archive") + if reproduced.get("mutation") != capture.get("mutation"): + raise ValueError("regenerated mutant differs from the archive") + invocation = (sys.executable, RUNNER, "-") + oracle = json.loads(subprocess.check_output(invocation, input=json.dumps(case).encode("utf-8"), timeout=15)) + return compare(reproduced, oracle, expected) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("capture", help="archived JSON envelope from kuna-verify oracle-case") + parser.add_argument("binary", help="the ELF used to produce the capture") + parser.add_argument("--sleighpath", default=ROOT / "specs") + parser.add_argument("--verify", default=ROOT / "decompiler/target/release/kuna-verify") + parser.add_argument("--return", dest="return_spec", required=True, help="void or REGISTER:BYTES") + args = parser.parse_args() + try: + with open(args.capture, "rb") as file: + capture = load_request(file) + result = replay(capture, args.binary, args.sleighpath, args.verify, Return.parse(args.return_spec)) + except (AttributeError, KeyError, TypeError, ValueError, OSError, subprocess.SubprocessError) as error: + parser.exit(2, f"oracle replay: {error}\n") + print(json.dumps(result, sort_keys=True)) + if result["classification"] == "COUNTEREXAMPLE": + parser.exit(1) + + +if __name__ == "__main__": + main() diff --git a/scripts/diffverify/test_function_oracle.py b/scripts/diffverify/test_function_oracle.py new file mode 100644 index 0000000000..99b5e2d957 --- /dev/null +++ b/scripts/diffverify/test_function_oracle.py @@ -0,0 +1,129 @@ +import struct +import unittest +from unittest import mock + +import unicorn as uc +from unicorn import x86_const as x86 + +from function_oracle import Case, UnicornBackend + +CODE = 0x400000 +SENTINEL = 0x600000 +STACK = 0x700000 +RSP = STACK + 0x808 +DATA = 0x800000 + + +def request(code, **registers): + return { + "version": 1, + "architecture": "x86-64", + "abi": "sysv-amd64", + "entry": hex(CODE), + "return_address": hex(SENTINEL), + "registers": {"RSP": hex(RSP), **{r: hex(v) for r, v in registers.items()}}, + "memory": [ + {"address": hex(CODE), "size": 4096, "permissions": "rx", "bytes": code}, + {"address": hex(STACK), "size": 4096, "permissions": "rw", + "bytes": (bytes(RSP - STACK) + struct.pack("> 11) & 7 + self.assertEqual(int(result["registers"][f"FP{top}"], 16), (0x3fff << 64) | (1 << 63)) + + def test_instruction_limit_is_incomplete(self): + spec = request("ebfe") + spec["limits"] = {"instructions": 10} + result = self.execute(spec) + self.assertEqual((result["status"], result["reason"], result["instructions"]), ("incomplete", "instruction-limit", 10)) + + def test_timestamp_requires_an_environment_model(self): + result = self.execute(request("0f31c3")) + self.assertEqual((result["status"], result["reason"]), ("incomplete", "timestamp-counter")) + self.assertEqual(result["event"]["address"], hex(CODE)) + + def test_trap_and_unmapped_data_access_are_distinct(self): + self.assertEqual(self.execute(request("0f0b"))["status"], "trap") + result = self.execute(request("488b07c3", RDI=0x810000)) + self.assertEqual(result["status"], "fault") + self.assertEqual(result["event"]["address"], "0x810000") + + def test_external_entry_records_arguments_without_executing_the_target(self): + spec = request("e8fbff0f00c3", RDI=5, RDX=11) + spec["external_entries"] = ["0x500000"] + result = self.execute(spec) + event = result["event"] + self.assertEqual(result["status"], "incomplete") + self.assertEqual(event["target"], "0x500000") + self.assertEqual(event["from"], hex(CODE)) + self.assertEqual(event["registers"]["RDI"], "0x5") + self.assertEqual(event["registers"]["RDX"], "0xb") + + def test_syscall_stops_before_an_environment_effect(self): + result = self.execute(request("0f05c3", RAX=1, R10=4)) + self.assertEqual(result["status"], "incomplete") + self.assertEqual(result["event"]["kind"], "system-call") + self.assertEqual(result["event"]["registers"]["RAX"], "0x1") + self.assertEqual(result["event"]["registers"]["R10"], "0x4") + + def test_rejects_conflicting_mappings(self): + spec = request("c3") + spec["memory"].append(spec["memory"][0].copy()) + with self.assertRaisesRegex(ValueError, "overlap"): + Case.parse(spec) + + +if __name__ == "__main__": + unittest.main()