Skip to content

[AUTOMATED] diffverify: kuna-verify, differential semantic checking (C1–C5, Tier L, CI baseline) - #1830

Open
sjkim1127 wants to merge 99 commits into
Noelo-Lab:mainfrom
sjkim1127:feat/diffverify-c2
Open

sjkim1127 wants to merge 99 commits into
Noelo-Lab:mainfrom
sjkim1127:feat/diffverify-c2

Conversation

@sjkim1127

@sjkim1127 sjkim1127 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

[AUTOMATED]

DiffVerify is Kuna’s developer tool for finding decompiler regressions that change program behavior. Give kuna-verify check a binary and a function. It runs the function’s SLEIGH p-code and Kuna’s final IR from the same sampled machine states. When they disagree, it reports the input and what each execution did.

The ARM fixture from #794 shows how an incorrect return type changes a 64-bit result.

printf '%s\n' 'typedef unsigned long long u64;' \
  'u64 ins16(unsigned a, unsigned short b) { return ((a + 1) << 16) | b; }' > ins16.c
clang --target=arm-linux-gnueabi -O2 -c ins16.c -o ins16.o
make specs && (cd decompiler && cargo build --release -p kuna-verify)
decompiler/target/release/kuna-verify check ins16.o ins16 --contract ins16.c --option returnpair single
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

Omit --option returnpair single to get AGREES(256).

What DiffVerify checks

  • Tier C compares function calls and arguments, observable memory writes, and return values. Use check --all for a whole binary and corpus to track verdicts against a regression baseline.

  • localize suggests decompiler rules to inspect, --concolic searches for inputs that reach new paths, and mutate measures detection of deliberate IR changes. Tier L cross-checks individual instruction semantics against Unicorn. Usage guide

  • The function oracle compares Unicorn execution of fixed-address x86-64 ELF bytes with raw p-code and final IR. prove checks returns and memory with SMT. It supports bounded loops and induction for selected single-header x86-64 loops that carry register or shared-memory values. Sail provides an independent reference for selected RV64 integer instructions. Function oracle · Symbolic validation · Sail RV64

Evidence and limits

  • SMT proof certificates can be checked with cvc5 and Ethos. The evidence records the proof's assumptions and bounds. Proof certificates

  • The published DecBench run covered 49,184 functions. Tier L covered 8,805 instruction forms. Mutation testing caught 76% of reached corpus mutants. DecBench · Tier L · Mutation testing

  • AGREES(n) means n sampled runs agreed. Tier C’s two executions share SLEIGH and p-code semantics. Its coverage excludes emitted C and writes to caller-owned stack objects at function exit. Coverage and verdicts

Model: Claude Opus 5.5, GPT-6.2 Sol

sjkim1127 and others added 14 commits November 19, 2026 12:17
…nd kuna

[AUTOMATED] Design only. Adds docs/features/diffverify/{analysis.md,
proposal.md,record.json}: a dev-only kuna-verify crate that checks, per
function, that kuna's Band B p-code computes what the lifted p-code computes
(z3 over SMT-LIB 2), that the lift matches the machine (Unicorn/qemu-user),
and later that the printed C matches the binary. No engine or emitted-C change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…age honestly

[AUTOMATED] Reorders the tiers: concrete execution of the binary
(EmulatePcodeCache) against the finished Funcdata (an interpreter on
EmulatePcodeOp) comes first and needs no phase hooks; z3 proves only
functions that already agree. Classifies the 56 P3/P4 fixes since June
(~15 body rewrites, ~29 prototype/ABI claims, ~12 not visible) instead of
claiming all of them, spells out why equivalence is hard, and adds a
declared-divergence list keyed by option.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
[AUTOMATED] Adds how Noelo-Lab#1534's symbolic p-code emulator, the Noelo-Lab#1641/Noelo-Lab#1699
phase hooks, the Noelo-Lab#317 ghidra-sim harness, the per-PR compile-and-compare
oracles and DecBench byte_match relate to this proposal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… loop-free code

Tier S now runs every proof under a deterministic budget (z3 rlimit, unroll
and query caps; wall clock only as a safety net) and unrolls loops to a bound,
reporting EQUIVALENT(<=k) for bounded proofs. The spent budget is recorded in
the baseline, so a change that makes a function exhaust it is flagged as a
regression. angr or binsec may encode the machine side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
One p-code-to-SMT encoder serves both sides, a sat model replays exactly in
Tier C, and no second lifter toolchain is needed. Independence from SLEIGH
stays with Tier L. Closes the open question on angr or binsec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
D-Helix (USENIX Security 2024) is the closest prior design. The proposal now
cites it and says where it differs: no recompilation for Tier C, stores and
calls observed besides the return value, prototype read through the ABI
(the cause of all D-Helix false negatives), concrete call replay, globals
from the load image, and culprit search over fired rules only.

Also: identical scratch addresses on both sides; localization rejects
subsets that add a difference, reports when no rule set explains one, and
tries past culprits first; a Cost section; C1-C3 now measure time,
bisection cost, precision and recall (reverted fixes); Tier P expectations
from D-Helix's recompile rates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… honest bounds

- Return values: compare only the bytes the physical ABI defines for the
  claimed type; a width or signedness verdict needs a typed contract (fixture
  source, DWARF). Noelo-Lab#794 is a DIFFERS against its source's u64 contract.
- Inputs: both sides start from the same raw state; an undeclared live-in is
  PROTOTYPE_SUSPECT, not a poison-induced DIFFERS.
- Calls: stubs write reachable memory and the decompiled side replays it;
  Tier S models calls as (regs, memory) -> (regs, memory) and never encodes a
  function Tier C could not fully execute.
- The Funcdata interpreter is new work; EmulateFunction's stores are no-ops.
  Unsupported ops give UNKNOWN(unsupported-op).
- EQUIVALENT(<=k) covers inputs on which both sides finish within the bound;
  one-sided overruns are replayed, not dropped. Unreplayable sat models are
  separated from encoder bugs.
- Localization reports a 1-minimal candidate set; log2 k only for a single
  culprit.
- Declared divergences are predicates (option, arch, observable, pattern).
- Slices: C1 pure integer, C2 memory and calls, C3 localization, C4 corpus.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ts, register-only C1

- Tier S admission no longer rests on Tier C's sampled runs: every op
  reachable in both CFGs must have complete SMT semantics and every call's
  reachable memory must be bounded, else SKIPPED(unencodable).
- A call stub's reachable memory includes every writable global, not only
  pointer arguments and escaped memory.
- C1 is register-only leaf functions (no memory access except read-only
  image loads); C2 adds stack, pointer-argument and global memory.
- record.json measurements follow the C1-C4 slices.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Unresolved indirect branches and calls, jump tables without a proved bound,
and unproved no-return calls make a function SKIPPED(incomplete-cfg).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…one state

Add the dev-only kuna-verify crate. The machine side lifts each instruction
with the program's SLEIGH translator and evaluates it with the OpBehavior
table; the decompiled side interprets the final Funcdata. Both start from the
same raw state, with argument registers extended as the ABI documents. Return
values are compared under the physical ABI and, given C source, against a
typed contract. Calls and memory beyond the frame are SKIPPED (slice C2).

Reverting Noelo-Lab#794 (returnpair single) gives DIFFERS against its source contract.
Over tests/datatests and tests/stages: 3,979 functions, 4 DIFFERS (3 are the
narrowext bug its stage test pins, 1 is a relocation harness limit), 3
DIVERGES (switchrunon-cut-row). Results: docs/features/diffverify/c1-results.md.

kuna_narrowext::rules_for exposes the rules for a given mode; rules() is
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Random inputs rarely reach a branch on one value. A small symbolic executor
records branch conditions over the inputs on both sides, and z3 supplies
inputs that take the other side; verdicts still come only from concrete runs.
C5 follows C2 and precedes S1, which reuses its expressions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

# Conflicts:
#	docs/features/diffverify/proposal.md
The decompiled function is compiled into a flat program every run reuses,
registers live in a dense memoized file, and a function stops after four runs
that exhaust the step budget. `corpus` runs one worker process per core and
prints in file order; `--json` and `check --all` are new. Stage tests pin the
harness fixes found while building C1.

Every verdict over tests/datatests and tests/stages is unchanged, sequential
and parallel. Check time 49.8 s -> 3.6 s; wall time 111 s -> 20.6 s.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both sides now load and store anywhere and run the same stub at each call: it
records kuna's arguments and the memory the callee could read, kills the
registers the model kills, and lazily rewrites the image's writable data and
memory near pointers passed so far. INDIRECTs move after the op they guard.
Where kuna has no call to code in the image, the machine runs the callee
itself. Calls are compared on the instruction address; arguments are DIFFERS
against a declared callee prototype and PROTOTYPE_SUSPECT otherwise. Switch
rows now map to out-edges through the jump table, not by address.

A fault injected in a local build for Noelo-Lab#801 and for a call that keeps a global
across it both give DIFFERS; the default build agrees. Over the corpus, every
C1 verdict is unchanged; 2,482 agree, 500 differ (untriaged, C4).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sjkim1127 sjkim1127 changed the title [AUTOMATED] diffverify C2: memory and call effects [AUTOMATED] diffverify: kuna-verify, differential semantic checking (C1, C2) Nov 20, 2026
sjkim1127 and others added 2 commits November 20, 2026 14:54
A callee in the image of one of kuna's calls now runs for real on the machine
side, inside a step cap, and the decompiled side replays what it did: memory
writes, the calls it made, and the killed registers it left. Registers the
convention preserves are restored and a change to one is reported as a
suspect; a callee the model cannot run falls back to the stub. Callees kuna
inlined run in an inline mode whose calls are kuna's.

Harness fixes found while triaging: tail calls only to targets outside the
function (SPARC delay-slot calls), memory INDIRECTs write their input before
the guarded op, address-less synthesized calls are a declared divergence,
context-tracked registers and bool parameters constrain the inputs, arguments
are compared only at the callee prototype's storage, a large frame stays in
the stack region, and differences after a doubtful argument or a read of an
uninitialized local are UNKNOWN, not DIFFERS. --trace prints both sides'
calls. DIFFERS over the corpus: 500 -> 118.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Harness fixes from triaging the corpus: a call value kept in a temporary is
read from the register a copy moves it to; a return folded to a constant is
compared at the register the model returns its type in; stack bool
parameters start as 0 or 1; real callees spend a step pool of their own; the
MIPS ISA bit is dropped from computed targets; a return to a pushed address
continues there; a read of the frame is undefined only when both sides read
bytes C leaves undefined, the stub's return-address slot and callee-saved
spills included.

From review: a run that traps on both sides is no longer counted as agreeing;
a declared return divergence no longer skips the memory comparison; a call
kuna resolved to a direct one is compared against the machine's target when
both are code; --runs 0 is a usage error and a file that cannot be checked
exits 3.

Over tests/datatests + tests/stages: 2,952 agree, 29 differ, all triaged in
docs/features/diffverify/c4-results.md: 5 kuna bugs, 8 passes a test pins on
purpose, 3 source-level UB, 13 harness limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phix33

phix33 commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Really like this PR. Wanted to help:

Result: Seven outstanding findings; issue #8 is fixed. Original numbering is retained.

These findings apply to the pinned commit (805eac3) and were re-validated after finding. Note that issue #1 deliberately mutates decompiled output to test the verifier's ability to detect an error; it does not claim the decompiler naturally produces that mutation.

Outstanding issues

1. [P1] Stack objects passed to callees are omitted from comparison

Root cause: Call snapshots reuse an exit-time memory filter that excludes stack bytes, including initialized locals whose addresses are passed to a callee (state.rs:569).
Revalidation: Still present and now documented: changing a pointed-to local from 1 to 2 still yields AGREES(64); including reachable stack bytes in call snapshots makes the same mutation yield DIFFERS.

Simple example: Machine code represents int x = 1; sink(&x);, while deliberately mutated decompiled output represents int x = 2; sink(&x);; the verifier still reports agreement.

2. [P1] Empty loops escape the execution budget

Root cause: The graph runner increments its step counter only for operations in block.ops, so traversing empty blocks consumes no budget (graph.rs:296).
Revalidation: A valid final graph containing an empty self-loop times out with --runs 1 --budget 1000; charging each block visit makes the same input terminate with UNKNOWN(budget).

Simple example: An empty block whose only successor is itself keeps running indefinitely despite a budget of 1,000 steps.

3. [P2] External-call stubs violate narrow-return ABI rules

Root cause: The call stub fills the entire output register with independent random bytes without applying the declared return type's ABI extension rules (state.rs:589).
Revalidation: Still present for external calls: an RV64 int return produces inconsistent upper register bits, and applying the required extension removes the mismatch; this revision reports UNKNOWN(uninitialized-local) because its return-address-write guard downgrades the mismatch.

Simple example: With unmapped extern int ri(int);, long ci(int k) { return ri(k); } sees stub a0 = 0x0e562cb114518521 versus graph 0x0000000014518521, producing a spurious UNKNOWN.

4. [P2] Stub fallback destroys registers preserved by the callee

Root cause: The fallback's killed() set uses generic ABI clobbers instead of the effective callee's register-preservation information (calls.rs:117).
Revalidation: Short helpers now agree, but a long helper that exceeds the 50,000-operation emulation allowance still falsely differs; removing only preserved EDX from the fallback's killed set restores agreement.

Simple example: A caller keeps 0xff in EDX across a helper that never modifies EDX; when helper emulation exhausts its allowance, the stub overwrites EDX and the caller falsely reports DIFFERS.

5. [P2] Abbreviated decompile commands silently omit verification

Root cause: The callback checks the raw command for the exact word decompile, although the console also accepts and resolves dec (session.rs:74).
Revalidation: Changing only <com>dec</com> to <com>decompile</com> in pointersub.xml changes the result from zero verification reports to getOuter AGREES(1).

Simple example: A corpus case using dec decompiles its function but produces no verification verdict; spelling out decompile produces the verdict.

6. [P2] Pointer contracts select integer return registers

Root cause: Contract return types lose their pointer category, and ABI assignment chooses only signed or unsigned integer types of the same width (abi.rs:86).
Revalidation: On ColdFire, a correct pointer-returning function agrees without a contract but falsely differs with a matching contract; preserving the pointer category selects A0 instead of D0 and restores agreement.

Simple example: void *f(void) correctly returns 0x2000 in A0, but its contract makes the verifier compare D0, which contains 0xf.

7. [P2] Failed function loads reuse the previously selected function

Root cause: A failed name lookup leaves the previous function selected, while error recovery clears only console flags and continues to the queued decompile command (session.rs:71).
Revalidation: Checking missing good produces two reports, but checking good missing produces three: good AGREES(1), missing UNKNOWN(decompile ...), then another good AGREES(1).

Simple example: check good.o good missing verifies good twice after loading missing fails.

Fixed issue

8. [Fixed; previously P2] Corpus file errors returned a successful exit status

Original root cause: Corpus file errors were collected separately and omitted from the exit-status calculation; the revised calculation now returns 3 when file errors exist and no function differs (kuna-verify.rs:167).
Revalidation: Fixed at the reviewed commit: a missing corpus XML file now exits with status 3, whereas the original reviewed version exited with status 0.

Simple example: corpus missing.xml --jobs 1 now exits with status 3, allowing automation to detect that the file could not be checked.

@sjkim1127

Copy link
Copy Markdown
Contributor Author

@phix33

Thank you for your feedback! I'll incorporate your suggestions.

A local whose address a call receives is now compared at the call, within
the extent of kuna's local symbol for that address: kuna's side finds it
among the CALL op's inputs, the machine in the convention's argument
registers, and only objects both find are compared. A callee run for real
counts only the bytes it read, bytes a callee's code left in the object are
skipped, and the stub writes only that object, no longer a window that
reached the stack canary. An in-image callee the model cannot run that gets
a frame object makes later differences UNKNOWN(guessed-callee).

Also: block visits and empty instructions spend the step budget; a stub
extends a narrow return as `narrowext abi` documents; it kills what the
call's own effect list says, keeping registers kuna proved preserved;
abbreviated decompile commands are checked (the console records the command
a line resolved to); pointer contracts select the model's pointer storage;
a decompile after a failed load is not checked.

Corpus: 4,030 functions (51 more, from abbreviated commands), 2,977 agree,
the same 29 differ. A local mutation storing 2 for 1 in a passed local now
gives DIFFERS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sjkim1127

Copy link
Copy Markdown
Contributor Author

[AUTOMATED]

Thanks, all seven are fixed in 70310cb, keeping your numbering. Over tests/datatests + tests/stages the set of 29 DIFFERS is unchanged, and 51 more functions are now checked (the ones scripts decompile with dec).

  1. Stack objects passed to callees. At each call, both sides now compare the frame object the pointer is into. The extent comes from kuna's local symbol for that address; a fixed window past the pointer also covers spills only the machine writes. kuna's side finds the object among the CALL op's inputs and the machine in the convention's argument registers, and only objects both find are compared, so this works for callees without a recovered prototype. A callee run for real counts only the bytes it read. Your mutation (int x = 1; sink(&x); stored as 2 on kuna's side) now gives DIFFERS: memory before call 1 to sink: machine 0x01, kuna 0x02. The stub now also writes only that object; the old window reached the stack canary in ptrtoarray passPtrToArray.
  2. Empty loops. Every block visit, and every instruction without p-code, now spends the step budget; an empty self-loop ends in UNKNOWN(budget) (tests/verdict_guards.rs).
  3. Narrow returns. The stub extends the callee's return value across its register as narrowext abi documents, so an RV64 int comes back sign-extended.
  4. Preserved registers. The fallback stub kills what the call's own effect list says (FuncProto::effect_list, which carries what kuna proved about the callee), not the model's generic list.
  5. Abbreviations. The console now records the command a line resolved to, and the check keys on that, so dec and any other abbreviation is checked.
  6. Pointer contracts. The contract keeps whether the return type is a pointer, and asks the model where a pointer goes: A0 on ColdFire.
  7. Failed loads. A decompile that follows a failed load is not checked; check good.o good missing gives two reports.

#1 and #7, plus the empty loop and the abbreviation, have tests in tests/verdict_guards.rs. #3, #4 and #6 have none yet; they need an RV64, a long-helper and a ColdFire fixture.

Each fix whose stage fixture the check can run was put back in a local
build (never committed) and its fixture checked. Of the 22 that restore a
semantic bug, 5 are caught without a contract and 9 with one. The misses
are classified in c4-results.md §6: a callee run for real shares its
effect, so a dropped argument changes nothing; storage kuna never
initialized holds the machine's value; a void or too-narrow return
compares nothing without a contract; a frame object at a callee that reads
nothing; no read-only store check; and C that is false but runs the same.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phix33

phix33 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

At commit 70310cb, the preserved-register fallback issue still seems to reproduce. Also, confirmed further gaps:

  1. Preserved registers are still overwritten when callee execution falls back to a stub.
    The fix reads prototype effects, but preservation facts established by calleepreserves are not necessarily stored there. Example: a helper preserves EDX=0xff, yet exceeding its execution allowance makes the stub overwrite EDX and falsely report DIFFERS. [Source](

    let mut out: Vec<(u64, u32)> = proto
    )

  2. Stack objects retained by earlier calls remain unobserved at later calls.
    Call snapshots include pointers passed in the current arguments, omitting pointers that escaped previously. Example: after save(&x); x=1; consume();, deliberately changing the decompiled assignment to x=2 still produces AGREES(64); including previously escaped objects correctly produces DIFFERS. [Source](

    pub fn writes_at_call(&self, args: &[u128]) -> Writes {
    )

  3. Changing a direct call’s destination can still report agreement.
    Direct call targets are excluded from target comparison, while recorded callee effects are replayed using only the call-site address. Example: deliberately redirecting the decompiled call from g(x) = x+1 to h(x) = x+2 still produces AGREES(16). [Comparison](

    let (mt, kt) = (code_target(env, mc.target), code_target(env, gc.target));
    ) · [Replay](
    let real = self.replay.get(k).filter(|r| r.at == at).and_then(|r| r.effect.clone());
    )

  4. unsigned __int128 contracts are silently interpreted as 32-bit integers.
    The parser accepts unsigned while ignoring the unrecognized __int128 token, weakening the return comparison. Example: a 128-bit multiplication with --option returnpair single reports AGREES(64); correcting only the contract width to 16 bytes exposes the missing upper return bits as DIFFERS. [Source](

    } else if has("int") || unsigned || has("signed") {
    )

  5. Normal return-address register writes suppress genuine mismatches.
    The stack-corruption guard treats writes to RV64’s ra register as an overwritten stack return address. Example: deliberately replacing a caller’s decompiled return value with zero produces UNKNOWN(uninitialized-local) instead of DIFFERS, despite neither side reading uninitialized memory. [Source](

    fn smashed(env: &Env, ms: &State) -> bool {
    )

  6. Empty commands reuse the previous command’s state.
    An empty line returns before last_command is cleared, duplicating verification or undoing the failed-load safeguard. Example: load f → decompile → load missing → empty line → decompile checks f again after the failed load. [Source](

    )

  7. Missing corpus directories still exit successfully without checking anything.
    Input discovery silently ignores nonexistent paths without an .xml extension and suppresses directory-read errors. Example: corpus nonexistent-directory --jobs 1 returns exit code 0, with 0 files and 0 functions checked. [Source](

    fn collect(path: &Path, out: &mut Vec<PathBuf>) {
    )

sjkim1127 and others added 3 commits November 20, 2026 20:31
…w's fixes

Two checks for the recall misses. A callee the machine runs for real has
the argument-register bytes it reads before writing them recorded (stack
spills excluded); kuna's call inputs are placed by the callee's parameter
storage, an entry-register input's own, or integer-register order, and
register pairs by their pieces. Where kuna passes other bytes or none, the
machine is rerun with kuna's bytes; only a changed result is DIFFERS, and
a declared callee prototype makes it a suspect. kuna's side is also rerun
with other values in what its C never assigns: argument or scratch
registers read at entry with no parameter, and killed registers read after
a call. A changed result is DIFFERS unless the machine, given the same
values, changes too.

From review: stubs keep the registers calleepreserves proves a callee
leaves; frame objects passed to any earlier call are compared at later
ones; direct call targets are compared through thunks, except calls kuna
bound past a PLT stub or replaced by an injection; __int128 contracts are
16 bytes and an unknown type word is an error; a register return address
written by calls no longer reads as a smashed frame; an empty script line
clears the resolved command; a missing corpus path is a usage error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…'s own result counts

A killed register the binary reads after a call is the binary's own
dependence only when it is not a register the call returns in: there the
binary reads the callee's value and kuna's C, never connecting it, reads
nothing. And given kuna's arguments, a callee run for real that returns or
writes something else makes the call differ even when the caller ignores
the result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sjkim1127

Copy link
Copy Markdown
Contributor Author

[AUTOMATED]

Thanks again, all seven are fixed in affaf9f (numbering kept):

  1. Preserved registers. You were right, calleepreserves answers per call and never writes the effect list. The stub's kill set now also drops every register callee_preserves_range proves the callee leaves alone.
  2. Earlier escapes. Every frame object passed to any earlier call is compared at each later call. Your save(&x); x=1; consume(); with x=2 on kuna's side now gives DIFFERS: memory before call 2 ...: machine 0x01, kuna 0x02 (tests/verdict_guards.rs pins the unmutated build's AGREES).
  3. Direct targets. Compared now, after following thunks (a jump, endbr64, a PLT slot's jmp [got], found by running the target from two states). Calls kuna bound past a PLT stub or replaced with an injection are left out, since the machine runs no dynamic linker or call fixup; comparing them gave false differences in kuna-pltlocal, kuna-elfaliasnames and injectoverride.
  4. __int128. 16 bytes, and an unknown word in a contract type is now an error rather than ignored.
  5. ra. Only a return address kept on the stack counts as smashed. This also turned three RISC-V narrowext off functions from UNKNOWN into the DIFFERS that pass is there to show.
  6. Empty lines. They clear the resolved command.
  7. Missing paths. corpus on a missing path, or a directory it cannot read, is a usage error.

The same commits add two checks for the gaps the recall measurement found (docs/features/diffverify/c4-results.md §6a). A callee run for real has the argument registers it reads compared with what kuna passes, confirmed by rerunning the machine with kuna's bytes. kuna's side is rerun with other values in storage its C never assigns. Over the corpus they add 49 DIFFERS, none a false positive on triage. Most are one kuna defect: arguments a caller passes straight through to a callee are dropped (v1 = add64(); for add64(a, b)), on x86-64, ARM, PPC, MIPS, eBPF, Rust and Swift fixtures. Recall on the restored fixes went from 5 to 7 of 22 without a contract, and from 9 to 11 with one.

sjkim1127 and others added 2 commits November 21, 2026 06:42
The image is read and cached a page at a time, with pages the loader does
not map whole read a byte at a time as asked; preserve_registers marks the
kept ranges once instead of scanning them per byte; temporaries live in a
hash map that keeps its capacity across instructions; thunk resolution is
cached per function; and a function stops after 16 runs that hit an
operation the model cannot run, as one that runs out of budget does.

Over tests/datatests + tests/stages every verdict is unchanged; total CPU
for the corpus falls by about a quarter, the checker's own time by about
half.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Float ops run on IEEE single and double through the shared OpBehavior table;
sign changes and a NaN's format conversion are exact bit operations that
keep its payload. A call input that sits in a float argument register is
placed there. 242 more corpus functions are judged (2,932 to 3,174 agree);
the 15 new DIFFERS are triaged in c4-results.md 6c, among them kuna's ARM
and AArch64 NaN compares and dropped float arguments. A float return that
differs only in a NaN's quiet bit matches the nan-quieting divergence,
nanignore's round-trip identity.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phix33

phix33 commented Nov 28, 2026

Copy link
Copy Markdown
Contributor

[AUTOMATED]

Review of 4088596a4, built and run on an AArch64 Linux host with z3 5.4.1. The Rust suite passes with z3 on PATH (38 unit, 72 integration tests), and truncated, mutated and random inputs gave no crash or hang. Five things to look at, each with a way to see it.

1. docs/baseline-verify.json is stale, so make verify-corpus fails

make verify-corpus
new DIFFERS or file errors (3):
  tests/stages/kuna-passthrough-filegap-arm.xml sst_tail: not in the baseline, DIFFERS
  tests/stages/kuna-passthrough-filegap.xml sst_tail: not in the baseline, DIFFERS
  tests/stages/kuna-passthroughfwdstack.xml getopt_long: not in the baseline, DIFFERS
AGREES 4211 -> 4529 of 4915 -> 5250 functions
BASELINE REGRESSION against docs/baseline-verify.json: 3 new

The baseline holds 917 of the 962 corpus files; the other 45 arrived with the merges of main. The three rows are the option-off pass of two-pass stage tests, so they are true detections that need recording. The file is also still in the unversioned format, which --save-baseline no longer writes.

2. A call argument cut to a narrower width reads as AGREES

compare/observe.rs compares each argument under mask(st.size), the width kuna's IR passes, so the bytes kuna dropped are never compared when the callee is a stub. An AArch64 PLT veneer whose stated pointer parameter kuna currently passes as (int4)p:

cat > veneer.xml <<'EOF'
<decompilertest>
<binaryimage arch="AARCH64:LE:64:v8A">
<bytechunk space="ram" offset="0x1000" readonly="true">
100000b0110240f91002009120021fd6
</bytechunk>
<bytechunk space="ram" offset="0x2000">0000000000000000</bytechunk>
<symbol space="ram" offset="0x1000" name="veneer"/>
</binaryimage>
<script>
  <com>parse line extern unsigned int veneer(char *p);</com>
  <com>lo fu veneer</com>
  <com>decompile</com>
  <com>print C</com>
  <com>quit</com>
</script>
</decompilertest>
EOF
decompiler/target/release/kuna-verify corpus veneer.xml
| veneer | veneer | AGREES(256) | 3.17 |

The machine passes all of x0; the printed C is v1 = (*dat_2000)((int4)p);. No suspect line is given either. mutate tests/datatests points the same way: drop-arg is caught for 29 of 58 reached mutants. A suspect line when the machine's argument register holds more defined bytes than kuna passes would cover it; the README's "their arguments" could say that width is kuna's.

3. CI runs none of the z3 or Unicorn code

grep -c -i -E 'z3|unicorn' .github/workflows/tests.yml   # 0
grep -n 'unittest discover' Makefile                     # only -s scripts/tests

The Rust solver tests return early when z3 -version fails, and scripts/diffverify/test_*.py is outside what make test-tools discovers. So prove, --concolic, the function oracle and the replay scripts are untested in CI, and report success there. Installing z3 in the job and adding the directory to test-tools would close it.

4. The function oracle traps on every SSE instruction under Unicorn 2.1.4

The docs name unicorn==2.1.2, but nothing checks it. With 2.1.4, ctl_set_cpu_model(UC_CPU_X86_QEMU64) leaves CR4 at 0:

import unicorn as uc
from unicorn import x86_const as x86
for model in (None, x86.UC_CPU_X86_QEMU64):
    m = uc.Uc(uc.UC_ARCH_X86, uc.UC_MODE_64)
    if model is not None:
        m.ctl_set_cpu_model(model)
    m.mem_map(0x400000, 4096)
    m.mem_write(0x400000, bytes.fromhex("660fefc0"))  # pxor xmm0, xmm0
    try:
        m.emu_start(0x400000, 0x400004); r = "ok"
    except uc.UcError as e:
        r = f"UcError {e.errno}"
    print(hex(m.reg_read(x86.UC_X86_REG_CR4)), r)
0x50200 ok
0x0 UcError 10

test_function_oracle.py then fails test_vector_write_uses_all_sixteen_bytes ('trap' != 'returned'); on 2.1.2 all 12 pass. Setting CR4.OSFXSR after choosing the model, or refusing other versions, would make the oracle's trap trustworthy.

5. kuna-verify embeds the build directory and searches it for specs

strings -a decompiler/target/release/kuna-verify | grep -c "$PWD/decompiler/crates/kuna-verify"   # 1

spec_roots always appends env!("CARGO_MANIFEST_DIR")/../../../specs. A binary built elsewhere carries the builder's path and loads specs from it if that path exists on the machine it runs on. kuna does not do this.

Smaller

  • funcdata.rs: the doc comment of get_heritage_pass now sits on vararg_folded.
  • check BINARY --all on a binary with no functions prints the usage text and exits 2.
  • A binary that cannot be loaded is reported as `option readonly on` failed: No load image present.
  • The baseline accepts 116 DIFFERS and one ERROR (kuna-aif-slot-edges, which does not load). A note saying which are option-off passes would make the rest easy to find.

Not covered: Tier L, localize, --concolic, and the soundness of symbolic/memory.rs, raw_function.rs and the loop unrolling beyond their own tests passing here. The mutation figure reproduces: 516 of 688 reached mutants caught on tests/datatests (75.0%).

Model: anthropic/claude-mythos-5-2

sjkim1127 and others added 8 commits November 28, 2026 14:55
…ake a jump to the continuation as a return

ARM's cspec lists lr and pc as unaffected, so a callee's own call or
return read as changing them and ARM functions became
UNKNOWN(abi-violation). Both are left out of the registers put back.

A callee returning with an indirect branch to its call's continuation
(ARM `ldr pc, [sp], Noelo-Lab#8`, x86 `pop rcx; jmp rcx`) was followed as a jump
inside the callee, so the caller ran on as the callee and its epilogue
read as the callee changing r4-r11. Such a jump is a return now.

On 18 decbench ARM binaries: 129 UNKNOWN(abi-violation) -> AGREES,
14 to another UNKNOWN reason (12 budget, 1 unsupported-op, 1
callee-replay: u-boot load_elf_image_phdr, a replay doubt the false
violation hid),
2 -> DIFFERS (betaflight sqrt: kuna passes __aeabi_ddiv two words of
its four), 1 AGREES -> UNKNOWN(budget) (_dtoa_r, whose body had run on
the callee step pool). Corpus, ls O0, find O2 and uname O2 unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- An argument kuna passes in part of a register (AArch64 `(int4)p` in x0)
  to a stub callee with a recovered prototype is now a suspect when the
  machine's register holds more than that part extended. It reads the
  argument's trial storage when the prototype has no parameter there. The
  suspect is a lead only: it does not turn a run that differs into UNKNOWN.
- kuna-verify no longer embeds its build directory: specs are looked for
  as kuna looks for them (the checkout from decompiler/target, beside the
  binary, the current directory).
- The function oracle sets CR4.OSFXSR and CR4.OSXMMEXCPT after choosing
  the CPU model; Unicorn 2.1.4 leaves CR4 at 0 and traps on every SSE
  instruction.
- CI installs z3 and Unicorn and runs the scripts/diffverify tests
  (`make test-diffverify-tools`); KUNA_REQUIRE_Z3 makes the Rust solver
  tests fail instead of passing when z3 is missing.
- `check --all` on a binary with no functions and a load that produces
  no image are errors that say so; a misplaced doc comment in funcdata.rs
  is back on get_heritage_pass.
- docs/baseline-verify.json is re-recorded in the versioned format for
  the 45 stage files main added. Three of them differ: getopt_long in
  kuna-passthroughfwdstack's `passthrough off` pass, and sst_tail in
  kuna-passthrough-filegap and its ARM twin, where kuna's call drops the
  double argument `sst` reads (a kuna finding, recorded as DIFFERS).

Corpus, uname O2, ls O0 and find O2 verdicts are unchanged; the new
suspect appears on 2 functions there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test used the review's AArch64 veneer, whose (int4)p was a kuna bug that
main's kuna_wholeinputarg (Noelo-Lab#2035) now fixes, so on the merge with main the
suspect was gone. It now uses the x86-64 thunk from kuna-protoorder-tailcallees,
which forwards its recovered int in the low half of RDI.

CI's oracle-script step also installs clang, lld and llvm, which the
cross-backend fixture needs to build.

docs/baseline-verify.json is re-recorded for the new stage tests from main;
no existing verdict moved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sjkim1127

Copy link
Copy Markdown
Contributor Author

[AUTOMATED]

Thanks. All five are addressed in 292321f, plus 9895b3c on top of a merge with main (numbering kept):

  1. Baseline. docs/baseline-verify.json is re-recorded in the versioned format, now for all 977 corpus files; make verify-corpus gives BASELINE OK. Of your three rows only getopt_long is an option-off pass. sst_tail in kuna-passthrough-filegap and its ARM twin differ in the default output: kuna's call drops the double that sst reads in xmm0. It is recorded as a DIFFERS.
  2. Narrowed arguments. When kuna passes part of a register to a callee it has no prototype for, and the machine's register holds more than that part extended, the call gets a suspect line: kuna passes 4 bytes of x0, whose other bytes the machine sets. The check reads the trial's storage, because a recovered callee has no parameter there. The suspect is a lead only, so a run that differs because of the cut still reads DIFFERS, not UNKNOWN. The README now says that the argument width is kuna's. Your veneer no longer shows it after the merge, because main's [AUTOMATED] fix(p4): pass a forwarded pointer whole when the caller returns a narrower value #2035 passes the stated pointer whole. The test uses the x86-64 thunk from kuna-protoorder-tailcallees instead, which forwards a recovered int in the low half of RDI.
  3. CI. The gates job installs z3, Unicorn 2.1.2 and clang/lld/llvm, then runs make test-diffverify-tools (the 65 scripts/diffverify tests). The workspace job installs z3 and sets KUNA_REQUIRE_Z3, so a missing solver fails the Rust tests instead of letting them return early.
  4. Unicorn 2.1.4. The oracle sets CR4.OSFXSR | CR4.OSXMMEXCPT after choosing the CPU model. A test zeroes CR4 after ctl_set_cpu_model and checks that SSE runs.
  5. Spec paths. CARGO_MANIFEST_DIR is gone. The binary looks for specs where kuna does: the checkout it sits in under decompiler/target, beside the binary, ../specs, and the current directory.

Smaller: the doc comment is back on get_heritage_pass. check --all with no functions exits 3 with no functions found to check. A load that produces no image reports `load …` loaded no image: <reason> instead of the readonly error. The note on which accepted DIFFERS are option-off passes is not done yet.

Model: claude-opus-5-5

sjkim1127 and others added 5 commits December 1, 2026 20:16
The 1 MiB output limit was checked only after the solver exited, so a solver
that kept printing filled its temporary files until the deadline. The poll
loop now kills it as soon as stdout or stderr passes the limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Both sides of diffverify take argument and return storage, preserved
registers and stack cleanup from the same .cspec, so an error there is
invisible to Tier C. `kuna-verify abi-model` prints what kuna's model assigns
for a declared prototype; scripts/diffverify/cspec_check.py builds probe
callers, callees and a register-pressure function with clang for x86-64,
i386, AArch64, ARM hard and soft float and RISC-V 64, runs them under Unicorn
and compares.

Everything agrees except ARM hard-float back-filling: AAPCS-VFP puts a float
in an s register a double skipped, and kuna's model takes s registers in
order (recorded in cspec_known.json). The tests plant a fault of each kind in
kuna's x86-64 model and check it is reported.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A storage the script cannot read, a probe kuna did not decompile, or a run
  that faulted or ran out of steps is `unsupported` and fails the run. Every
  run must end where it should (a callee back at its return address) before
  its registers count.
- A known finding must match in kind and text; a known entry whose finding
  changed (`changed`) or now matches (`fixed`) fails, so a new fault cannot
  hide behind an old one.
- `killedbycall` is checked: a call clobbering only those registers must leave
  the result alone, and no register may be in both lists.
- The preserved-register probe is split into integer and floating-point ones
  whose values come from calls and are combined with a value known only after
  the call. The old one let clang recompute or fold its values, which left
  ARM's r5-r11 and d8-d15 untested. Each unaffected register is now checked to
  be exercised; RISC-V gp and tp are reported as unexercised.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Profiling `check` on find O2 put most of the time in what every call does,
not in executing p-code:

- the no-return name check looked the callee's name up, through thunks, and
  matched it against every list at each call of each run; it is now worked
  out once per target and cached in Env;
- forgetting the memory a callee may write asked every written byte; a frame
  page no escaped pointer reaches is now kept whole;
- finding the frame pointers stored in memory read each word a byte at a time
  through the page map; a word inside one page is now read with one lookup;
- the cache of kuna's frame objects is a hash map instead of a B-tree.

Instructions retired on find O2 (659 functions, one process) fall from
439.6e9 to 356.6e9, 19% fewer. Every verdict on the corpus, uname O2, ls O0
and find O2 is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ritable bytes by page

- `State::writes` collected the written bytes in hash order into a B-tree,
  which sorted them all at every call. The pages are sorted instead, 64 times
  fewer, so the map is built from bytes already in order.
- Forgetting what a callee may write now decides a frame page, or one outside
  `ram`, with one mask of the bytes an escaped pointer reaches, unless the
  page also holds read-only data or code.

Instructions retired on find O2 (659 functions) fall from 356.6e9 to
338.9e9. Against the build before 548466f, with both changes: find O2
439.6e9 -> 338.9e9 (23% fewer), the corpus 3.39e12 -> 3.25e12, and `mutate`
on uname O2 133e9 -> 122e9. Every verdict and every mutant's outcome is
unchanged when both builds run with the same `--jobs`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mahaloz

mahaloz commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

[AUTOMATED] Thanks for the follow-ups on the last review. With #1947 and #1948 stacked on it, this has grown into a subsystem that is hard to review and land as one piece. Could you split it?

  1. The engine hooks kuna-verify needs (about 110 lines).
  2. The core checker (checks C1–C4) with its tests.
  3. localize.
  4. The CI step and docs/baseline-verify.json.

The z3 concolic mode, any QEMU step, and #1947/#1948 would then follow as their own PRs. One question for the CI piece: the baseline pins DIFFERS verdicts too, so as it stands every PR that changes decompiler output would also have to re-record it.

sjkim1127 and others added 2 commits December 2, 2026 09:25
… evaluate common integer ops without the behavior table

A mutant changes only kuna's side, so mutate now builds a function's setup
once and reuses the machine's runs of the unmutated check; a noreturn mutant
reuses only runs that never reached its call. eval takes the integer ops runs
spend most time in (operands of at most eight bytes) through a direct port of
the behavior table's arithmetic, checked against the table by a unit test.

Verdicts on the corpus, uname O2, ls O0 and find O2 and all 419 uname O2
mutant outcomes are unchanged. Retired instructions: mutate uname O2
122e9 -> 90e9, check find O2 339e9 -> 325e9, corpus 3.25e12 -> 3.20e12.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The check compared the bits in kuna's storage with the marker. A compiler
that builds a constant in a scratch register can leave the same bits in a
register the other side never reads: clang 22 materialises the double of
RISC-V `struct S_ld` through a1 (`fmv.d.x fa0, a1`), so kuna's a0 + a1 model
passed locally and failed in CI under clang 21.

The sinks and new `use_*` probes now store what they receive, and each
register and stack slot is changed in turn to see which stored values change.
A match needs the spots the code reads to be kuna's storage, and that storage
to hold the marker. Findings no longer quote leftover register contents, so a
known entry holds across compiler versions. A return that does not come back
no longer falls through to the location comparison.

The RISC-V lp64d structure of one integer and one floating-point field (a0 +
fa0, which riscv64-fp.cspec joins as a0 + a1) is a kuna model gap, listed in
cspec_known.json with its cause.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sjkim1127

Copy link
Copy Markdown
Contributor Author

[AUTOMATED] Split as asked, in that order. Each PR targets main and carries the commits of the one before it, so each says which commit to review from:

  1. [AUTOMATED] Add the engine hooks a differential checker needs #2107: the engine hooks (rule cap, vararg_folded, rules_for, console helpers). With every hook unset, kuna's output does not change.
  2. [AUTOMATED] Add kuna-verify, a differential check of the final IR against the machine code #2108: the core checker, C1, C2 and C4, with check, corpus, mutate and their tests. Concolic, Tier L/S, the function oracle and the cspec check are taken out, and every corpus verdict (5,707 functions) is the same as the unsplit tool's on the same base.
  3. [AUTOMATED] Add kuna-verify localize: name the rule application after which a function differs #2109: localize.
  4. [AUTOMATED] Run kuna-verify over both corpora in CI against a recorded baseline #2110: the CI step and docs/baseline-verify.json.

On the baseline question: a PR that changes decompiler output does not have to re-record it. Only a new difference fails the step, meaning a function that agreed (or a new function) now differs, or a file can no longer be checked. A function that already differed and still differs passes. #2110 now records where it first differs (DIFFERS(return), DIFFERS(call 1 at 0x40000c to 0x40002c)) without values, so a difference that moves is listed as a notice rather than unseen. One that stops differing is a notice too. A function that agreed and is now UNKNOWN, or agrees on at most half the runs it did, is a warning. Re-recording is only needed to clear those notices, and the step stays continue-on-error until the DIFFERS set is empty or all declared.

The z3 concolic mode, Tier L (with the objdump and radare2 checks for targets Unicorn does not run), Tier S, the function oracle and the cspec check will follow one at a time once these land, and #1947 and #1948 will be rebased onto them. The cspec check found that kuna's RISC-V lp64d model passes a {long, double} struct in a0 + a1 instead of a0 + fa0; that fix is separate, #2098. I'll close this PR once the four are in.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants