Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,53 @@ 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

# 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
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,
Expand Down Expand Up @@ -254,7 +301,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
Expand Down
21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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-diffverify-tools test-ghidra rust rust-test lint clean check-spec version observatory coverage

all: binaries specs

Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -96,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:
Expand Down
17 changes: 17 additions & 0 deletions decompiler/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 1 addition & 8 deletions decompiler/crates/kuna-cli/src/decompile/script.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -23,14 +24,6 @@ fn selected_vma(target: &str, by_address: bool) -> Option<u64> {
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']) {
Expand Down
15 changes: 15 additions & 0 deletions decompiler/crates/kuna-console/src/interface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)`).
Expand Down Expand Up @@ -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<String>,
}

/// An open bulk-output redirect (`openfile`/`openfile append`).
Expand Down Expand Up @@ -889,6 +900,7 @@ impl IfaceStatus {
datamap: BTreeMap::new(),
source,
command_seq: 0,
last_command: Vec::new(),
}
}

Expand Down Expand Up @@ -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);
}
Expand All @@ -1153,6 +1166,7 @@ impl IfaceStatus {
let mut expand: Vec<String> = 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");
Expand All @@ -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?;
Expand Down
7 changes: 7 additions & 0 deletions decompiler/crates/kuna-decomp/src/infra/action.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
89 changes: 89 additions & 0 deletions decompiler/crates/kuna-decomp/src/infra/kuna_rulecap.rs
Original file line number Diff line number Diff line change
@@ -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<String, u64>,
/// [`Mode::Limit`]: the op address of the limited rule's last application.
pub last: Option<u64>,
/// Every application's rule, in the order they were made.
pub sequence: Vec<String>,
}

thread_local! {
static ARMED: Cell<bool> = const { Cell::new(false) };
static STATE: RefCell<(Option<Mode>, 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());
}
}
1 change: 1 addition & 0 deletions decompiler/crates/kuna-decomp/src/infra/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
9 changes: 7 additions & 2 deletions decompiler/crates/kuna-decomp/src/p4_calls/kuna_narrowext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
Loading
Loading