Skip to content

feat(ghidra): run kuna as a drop-in, backwards-compatible decompiler backend for the stock Ghidra GUI (Phase 2 — real C) - #135

Merged
mahaloz merged 16 commits into
mainfrom
feat/ghidra-mode-phase2
Jul 7, 2026
Merged

mahaloz merged 16 commits into
mainfrom
feat/ghidra-mode-phase2

Conversation

@mahaloz

@mahaloz mahaloz commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Phase 2 — the engine bridge: kuna emits real C as Ghidra's decompiler core

Stacked on Phase 1 (#134, merged). This makes kuna's engine actually decompile a live Ghidra program over the wire protocol — first real C from kuna in ghidra mode, proven end to end. Each step landed as its own commit keeping make test at 675/675 datatest parity, make test-stages at 254/254, and make rust-test green — the change is additive to kuna-ghidra plus a new Architecture constructor; the standalone engine is untouched.

What landed (8 commits)

  1. EngineTranslate trait seam — Architecture.translate is now Box<dyn EngineTranslate> so a query-backed translator can replace Sleigh. Behavior-preserving; only Sleigh implements it today. (Design refinement vs the proposal: a trait object, not an enum — an enum variant naming kuna-ghidra's type would be a kuna-decomp↔kuna-ghidra cycle.)
  2. GhidraTranslate — p-code (getPcode per instruction) and registers from host queries; ContextGhidra is an empty-tracked-set stub (query-backed tracking is Phase 3).
  3. Architecture::from_engine_translate + SharedClient restructure — registerProgram builds a live engine from the wire specs; the process loop shares its query client with the engine's providers so they call back into Java mid-decompile (borrow discipline: never a client borrow across the decompile).
  4. Funcdata::encode — the <function>/<ast> response document (ref=get_create_index, uniq=get_time).
  5. PrintC token-markup — PrintEmit enum (no vtable on the hot path) + MarkupRef population + doc_function_markup; the plain-text datatest path stays byte-identical.
  6. decompileAt drives the engine — decode <addr> → name via getCodeLabel → decompile_func (flow-discovered extent) → emit the dual-<function> <doc> (fd.encode + spliced markup). Errors degrade to the clean incomplete-function shape.

Proof

kuna-ghidra/tests/decompile_at_e2e.rs::test_decompile_at_emits_c drives a full session (registerProgram → setAction → decompileAt) through a loopback MockJava that answers the callback queries, and asserts the response is a <doc> with a <function name> + non-empty <ast> and a second markup <function> whose opref/varref tokens resolve against that ast (the click-to-address contract).

Scope boundary (Phase 2 → Phase 3)

decompileAt runs against an empty scope, so simple, self-contained functions decompile now; unresolved global/type references degrade to placeholders (sub_ADDR/DAT_ADDR/default types) and no getMappedSymbols query fires. Correct names/types on global-heavy functions is exactly what Phase 3 adds (the lazy ScopeGhidra/TypeFactoryGhidra, wire <coretypes> decode, the query-backed inject library). See docs/ghidra-integration.md §12 and docs/rust-port/ghidra-phase2-plan.md.

Gates

make test 675/675 PARITY OK · make test-stages 254/254 PARITY OK · make rust-test green · cargo test -p kuna-ghidra all pass — every commit independently re-verified.

🤖 Generated with Claude Code

https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof

Running kuna in a real Ghidra instance

kuna is a drop-in, backwards-compatible backend: Ghidra's Java side is untouched — only the spawned decompiler process changes. The KunaDecompiler Ghidra extension (integrations/ghidra/KunaDecompiler/, plugin from Phase 1, refreshed here for the working Phase-2 backend) does the swap by reflectively pointing DecompileProcessFactory at the kuna_ghidra binary. One-command build + deploy:

cd integrations/ghidra/KunaDecompiler
GHIDRA_INSTALL_DIR=/abs/path/to/ghidra_12.2 ./build.sh   # build backend -> stage -> package zip

Then File → Install Extensions… (the zip) → restart → File → Configure (enable KunaDecompilerPlugin) → decompile. The Decompiler window shows kuna's C with working click-to-address. Full runbook + the dev-checkout (-Dghidra.external.modules) and no-code file-drop paths: integrations/ghidra/KunaDecompiler/README.md.


Next steps (real-Ghidra / GUI hardening — for the next iteration)

Follow-up work driving the stock Ghidra 12.x GUI end to end, validated on macOS/arm64 via the stock GUI plus a PyGhidra "decompile every function through the C markup" harness (the same document the Decompiler window renders).

Landed in this iteration (GUI now works on simple/self-contained functions):

  • 678aaf62 ghidra-mode context skip — registerProgram was failing on real pspecs (Non-existent context variable: addrsize); skip <context_data> like C++ ContextGhidra::decodeFromSpec.
  • b46936d6 setOptions accepts silently — a phase-1 warning on the success frame made DecompInterface init fail ("Unable to initialize the DecompilerInterface").
  • 0cf365ec vardecl symref — a function declaring a local aborted the markup decode ("Attribute symref is not present"); always write the symref.
  • Extension packaging without gradle (javac/jar/zip reproduction of buildExtension) + a headless PyGhidra runbook and an in-script enable/disable toggle in the extension README.

Open follow-ups (surfaced by the GUI-faithful sweep over /usr/bin/{fmt,head,wc,nl,uniq,od} + an x86-64 ELF):

  1. Graceful failure degradation. When a function hits an un-ported pass, decompile_func catches the panic and takes the incomplete-function branch, but the response still reaches Java as a decode error — Pcode: Decoding error: Expecting <doc> but did not scan an element — instead of a clean incomplete function. C++ writes an empty 14/15 payload and DecompileResults.decodeStream early-returns on isEmpty(); make the caught-panic degradation emit exactly that clean empty shape so failures render as a tidy "incomplete" message and never surface a decode error. (~27/1040 functions in a large static ELF.)
  2. Un-ported passes (LOSS-131). Those panics are the real M3-grind seams — porting them is what makes those functions actually decompilable; tracked separately from (1).
  3. External-stub name mismatch. One /usr/bin/head function fails with Function name mismatch: ____chkstk_darwin + <EXTERNAL>_____chkstk_darwin — reconcile the name kuna returns for an external/thunk against what the Java side expects.
  4. Real symref / <localdb>. The vardecl symref is currently a placeholder (the decl varnode's create index); Java logs an unresolvable ref. Encoding <localdb> (deferred in funcdata_encode.rs) supplies real HighSymbol ids so decl↔symbol linking (rename/nav) works — pairs with the Phase-3 lazy ScopeGhidra.
  5. setOptions applied. Options are accepted but not applied (no option database wired to the engine yet) — Phase 3.
  6. Land the GUI-faithful harness under integrations/ghidra/ as a regression driver (full analysis + decompile every function via the C markup).

Cross-host note: the standalone float suite is now deterministic across build hosts (5fa6c6ff canonicalizes generated-NaN sign to the x86 convention), so make rust-test/make test are green on macOS/arm64 as well as Linux/x86-64.

mahaloz and others added 4 commits July 5, 2026 18:13
…ge scaffolding

Phase 2 turns kuna-ghidra's stubbed decompileAt into real, marked-up C in the
stock Ghidra GUI. It is the first phase that touches kuna-decomp's core types
(the Translate seam, Funcdata::encode, PrintC's emitter), so per the repo's
standing requirement it goes through a [PROPOSAL] for go/no-go before the risky
work lands. This commit is that proposal plus the safe, additive scaffolding
that de-risks its central design question.

docs/rust-port/ghidra-phase2-plan.md — the plan: the provider->query
re-entrancy design (SharedClient), the Architecture-from-wire-specs path, the
Translate {Sleigh, GhidraTranslate} enum seam (the go/no-go linchpin — must land
as a behavior-preserving refactor), GhidraTranslate/ContextGhidra, Funcdata::
encode, and the PrintC->EmitMarkup wiring — each with its kuna type, its risk to
the standalone engine, and a sequencing plan that gates every standalone-touching
step behind make test / test-stages / rust-test. Symbols stay eager-minimal;
the lazy ScopeGhidra cache is deferred to Phase 3.

decompiler/crates/kuna-ghidra/src/provider.rs — the scaffolding: SharedClient
(Rc<RefCell<GhidraClient>>, the single-threaded analog of the C++ `glb`
back-pointer) and GhidraLoadImage, a real impl of kuna_sleigh's LoadImage trait
backed by the getBytes query. It proves the pattern the whole phase turns on —
the engine, mid-decompile, re-entrantly calling a provider that queries the host
on the same streams — end to end, entirely additively (no existing crate
touched). Two unit tests: a load_fill that pulls bytes with byte-exact getBytes
request framing, and the unmapped-address -> DataUnavail path.

Gates: make test 675/675 PARITY OK, make test-stages PARITY OK, make rust-test
green — the change is additive to kuna-ghidra only.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…seam (EngineTranslate)

The linchpin refactor: Architecture.translate becomes Box<dyn EngineTranslate>
instead of a concrete Sleigh, so a ghidra-mode translator (p-code from the Java
host per instruction, no local .sla) can replace Sleigh without kuna-decomp
naming any ghidra-specific type — the ghidra translator lives in kuna-ghidra
(which depends on kuna-decomp), so an enum variant would be a dependency cycle;
a trait object owned here is not. This supersedes the plan's enum sketch (a
design refinement forced by the crate DAG).

New infra/engine_translate.rs: trait EngineTranslate: Translate, adding only the
engine-owned surface Architecture reaches beyond the abstract Translate API
(manager/manager_rc/manager_mut, loader_rc/set_loader, read_loadimage_value,
get_register_varnode, the object-safe with_context_db_dyn, and as_sleigh/
as_sleigh_mut downcast hatches). impl EngineTranslate for Sleigh forwards to the
engine's inherent methods, so every routed call is behavior-identical.

Behavior-preserving no-op: only Sleigh implements the trait. The ~30 internal
architecture.rs sites route through the trait; the handful of external callers
that need the whole &Sleigh (analysis/FID/console, which never run on a
non-Sleigh engine) use as_sleigh().expect(...). Architecture::with_context_db_mut
keeps its generic value-returning signature, re-implemented over the object-safe
with_context_db_dyn (run-once semantics preserved).

Independently re-verified: cargo build --workspace clean, make test 675/675
PARITY OK, make test-stages PARITY OK, make rust-test green. No new clippy
warnings.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…slator

Port C++ GhidraTranslate into a live translator in kuna-ghidra: p-code and
register lookups come from getPcode/getRegister queries to the Java host instead
of a local .sla. GhidraTranslate<R,W> implements RegisterLookup + Translate + the
new EngineTranslate trait, so it can back an Architecture in place of Sleigh.

- one_instruction: the getPcode path (ghidra_translate.cc:120-156) — a getPcode
  query, decode <inst offset><addr/><op ...>* into the PcodeEmit; the
  BadData/Unimpl/JavaError ladder preserved exactly (empty response -> BadData,
  <unimpl> -> Unimpl carrying the length, catch(JavaError) -> lowlevel), which
  the flow decode-error handler depends on.
- RegisterLookup: get_register / get_register_name / get_exact_register_name with
  the nm2addr/addr2nm caches (C++ mutable maps -> RefCell<BTreeMap>).
- get_user_op_names: the index probe loop (getUserOpName 0,1,2,... until empty).
- EngineTranslate: manager/loader_rc/set_loader/read_loadimage_value/
  get_register_varnode/with_context_db_dyn over the shared client + a
  GhidraLoadImage loader; context is a ContextInternal stub (empty tracked sets;
  the host disassembles, so local context is essentially unused — the
  query-backed getTrackedRegisters + the &TrackedSet-from-&self borrow are
  TODO(phase-3)).

Refactor: the Phase-1 tspec-only struct is split into a client-free TspecModel
(the command loop, which owns the process streams and has no query client, uses
this) and the live GhidraTranslate<R,W> built via new(tspec, registry, client).

kuna-ghidra now depends on kuna-decomp (EngineTranslate) + kuna-num — an acyclic
new edge (kuna-decomp does not depend on kuna-ghidra). Additive: 31/31
kuna-ghidra tests; make test 675/675 PARITY OK, test-stages 254/254 PARITY OK,
rust-test green. Deviations from the plan: BTreeMap (workspace bans HashMap),
Rc<AddrSpaceManager> (the landed EngineTranslate::manager_rc requires it).

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
… response)

Port C++ Funcdata::encode into kuna-decomp (new substrate/funcdata_encode.rs),
v1: the minimal <function> the decompileAt response needs to satisfy Ghidra's
HighFunction.decode and the click-to-address contract — <function id name size
[nocode]> + <addr> + <ast>. Additive: the standalone engine never calls encode,
so the 675 datatests are untouched.

- encode_tree emits <ast> = <varnodes> (all non-IPTR_IOP varnodes, full addr
  form) + per basic block <block index> (cover <rangelist> + each <op>) + per
  in-edged block <blockedge index> (<edge>s), reusing block.rs's existing
  byte-identical encode_body/encode_edges (widened to pub(crate)).
- encode_op: the four-way input rule (null->void; INDIRECT iop input ->
  <iop value=indop.get_time()>; LOAD/STORE constant space operand -> <spaceid>;
  else bare <addr ref>), output <addr ref>/<void>. Bare-ref form inside <op>
  carries ONLY ATTRIB_REF (Varnode.decode short-circuits on a known ref);
  the full space/offset/flags form appears only under <varnodes>.
- The load-bearing invariant: <addr ref> = Varnode::get_create_index() and
  <seqnum uniq> = PcodeOp::get_time() — the SAME accessors EmitMarkup reads for
  its varref/opref, so the AST ref-ids equal the markup ref-ids by construction
  (no separate id table). Emit them unmodified.

New decompiler-scope marshal ids (ELEM_AST=115, ELEM_VARNODES=119, ELEM_IOP=113;
ATTRIB_ADDRTIED/GRP/INPUT/PERSISTS/UNAFF=30-34, ATTRIB_VOLATILE=65,
ATTRIB_NOCODE=84) — distinct from the coexisting SLEIGH-compiler attribute
namespace; encoding writes id.get_id() directly (no registry). ELEM_FUNCTION=116
placeholder in prettyprint.rs is now a re-export from here (same numeric id).

Deferred to later phases: <prototype> (FuncProto::encode, v1.1), <localdb>,
<highlist>/<jumptablelist> (Phase 4), <override>.

Tests: a synthetic single-block Funcdata exercising all four op-input branches +
the IOP filter, and an e2e that decompiles 5 real corpus functions and
round-trips each — both assert the ref==create_index / uniq==get_time invariant.
Gates (independently re-verified): build clean, kuna-decomp suite green, make
test 675/675 PARITY OK, make test-stages 254/254 PARITY OK, make rust-test green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
@mahaloz
mahaloz changed the base branch from feat/ghidra-mode to main July 5, 2026 21:05
mahaloz and others added 4 commits July 5, 2026 21:58
…f refs

Wire the ported-but-unreachable EmitMarkup into PrintC so a ghidra-mode
decompileAt can emit the Clang-markup <function> whose tokens carry opref/varref
attributes that resolve against the step-4 <ast>. The standalone datatest path
stays byte-identical.

- PrintEmit enum {NoMarkup(EmitNoMarkup), Markup(EmitMarkup)} + impl Emit that
  match-delegates the FULL Emit surface (all 31 required + 26 default-provided
  methods, via a pe_forward! macro) to the active variant — a concrete field, no
  vtable on the hot path, so the ~260 self.emit.<m>() sites are unchanged and
  EmitNoMarkup's overridden tag_line/clear always run in the leaf. Default is
  NoMarkup; only doc_function_markup flips it.
- set_markup(bool) swaps the variant; doc_function_full and doc_function_markup
  now share one private emit_function_document(fd, arch) (String vs Vec<u8>
  return) so they can't drift.
- MarkupRef population: the fd-free RPN engine carries slotmap arena keys, not
  get_time()/get_create_index(), so a scoped emit_fd: Option<*const Funcdata>
  (set for the extent of emit_function_document only, read-only, deref'd ONLY
  when emits_markup()) lets emit_atom/emit_op resolve a key back to the SAME
  accessors the <ast> stamps — varref=get_create_index (excluding IPTR_IOP,
  matching the <varnodes> filter), opref=get_time. The plain-text path does zero
  lookups, so make test is byte-identical. Structural keywords / storage /
  type_id / symref stay none() (their <highlist>/<localdb> targets are Phase 4).

Verification (tests/funcdata_encode_e2e.rs): for real corpus functions, assert
every markup opref/varref is a subset of the <ast>'s <seqnum uniq>/<addr ref>
sets (the click-to-address contract), plus a non-empty-refs tripwire against the
MarkupRef-still-none regression.

Not wired into kuna-ghidra/process.rs (the decompileAt bridge is the next step).
Gates (independently re-verified, corrected cwd): build clean, make test 675/675
PARITY OK byte-identical, make test-stages 254/254 PARITY OK, make rust-test green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…ecture in registerProgram

The integration: registerProgram now builds a live ghidra-mode engine, and the
process loop shares its query client with the engine's providers so they can
call back into the host mid-decompile. (decompileAt driving the engine is the
next/final step.)

Phase-0 assessment came out clean — no Phase-3-sized machinery needed, because
Architecture.translate is already Box<dyn EngineTranslate> (step 1), so the ctor
and init reach the translator through trait methods. The only Sleigh-specific
init call is the SLEIGH inject-snippet compile (parse_inject_all), guarded with
as_sleigh() (no-op on the ghidra path; the query-backed inject library is
Phase 3).

- Architecture::from_engine_translate(archid, Box<dyn EngineTranslate>): the new
  ctor; new(archid, Sleigh) delegates to it. Body reaches the manager via
  EngineTranslate::manager() (identical to base().manager() for Sleigh).
- SharedClient restructure: GhidraProcess owns client: SharedClient<R,W> instead
  of sin/sout; every framing read/write goes through a statement-scoped
  self.client.borrow_mut().sin_mut()/.sout_mut(). Invariant (commented +
  confirmed): the loop never holds a client borrow across raw_action, where the
  engine re-entrantly borrow_mut()s the same client for callback queries — the
  protocol is synchronous so borrows never overlap.
- registerProgram: Session holds a live Architecture; build_architecture =
  GhidraTranslate::new(tspec,...) -> from_engine_translate -> set_cspec_xml/
  set_pspec_xml (wire bytes) -> init_post_engine. That init issues the
  getUserOpName probe (exactly one query, nested in the open response). On
  construction failure the error ships on the 16/17 frame (slot bound before the
  fallible build) so Java detects registration failure.

Deferred to Phase 3 (plan §6): wire <coretypes> decode (uses the hardcoded
default build_core_types, which the 675 datatests prove sufficient), the
query-backed inject library, TypeFactoryGhidra. Bad tspec now fails construction
with a 16/17 warning (C++-faithful; was the old TODO(phase-2)).

Tests: protocol_e2e updated — the full-session test answers the getUserOpName
probe and asserts the new query burst in registerProgram's response
byte-exactly; plus test_register_program_builds_live_architecture. Gates
(independently re-verified): build clean, kuna-ghidra 32 tests, make test 675/675
PARITY OK, test-stages 254/254 PARITY OK, make rust-test green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…eal C in ghidra mode)

The final wire-up: decompileAt runs the live engine and emits the dual-<function>
<doc> response — the first real C from kuna as Ghidra's decompiler core, proven
end to end.

Phase-0 assessment: the minimal path is viable WITHOUT the full lazy symbol
scope (ScopeGhidra / a <mapsym> decoder = Phase 3). decompile_func(arch, name,
addr, 0) builds a Funcdata for a raw address via arch.new_funcdata (no
pre-registered symbol; size 0 = flow-discovered extent, the console
decompile-all path). The ghidra Architecture installs a plain empty
ScopeInternal, so unresolved symbol/type refs degrade to placeholders (accepted
Phase-2 quality) and no getMappedSymbols query fires; decompile_func's existing
catch_unwind degrades an un-ported seam to Err rather than crashing.

- decompileAt: decode <addr> -> name via getCodeLabel(addr) (fallback FUN_<off>)
  -> decompile_func(arch, name, addr, 0). On success, build_decompile_at_doc
  encodes <doc> = open + fd.encode(<function>/<ast>) + (if send_c_code &&
  action=="decompile") the spliced doc_function_markup bytes (the dual
  <function>) + close, into a Vec written inside the 14/15 burst. Any decompile
  error degrades to the C++ !isProcComplete incomplete shape (empty payload +
  16/17 warning) so a failure never desyncs the GUI.
- Borrow discipline (confirmed): getCodeLabel is a short-lived client borrow
  dropped before the decompile; the decompile runs holding only &mut Architecture
  (its providers re-borrow the client through their own Rc clones); the <doc> is
  written by re-borrowing the client only AFTER decompile_func returns — never a
  client borrow across the decompile. doc_function_markup uses the
  take_print/put_print split-borrow.

Proof — tests/decompile_at_e2e.rs (test_decompile_at_emits_c): a full session
(registerProgram -> setAction("decompile","c") -> decompileAt) through an
interactive loopback MockJava (sound: packed payloads are 0x00-free) that answers
each callback query on demand (getCodeLabel="myfunc", a canned RETURN <inst> for
getPcode, empty elsewhere). Asserts the response is a <doc> whose first
<function name> == myfunc with a non-empty <ast>, plus a second <function> (the
markup) whose opref/varref tokens are a non-empty subset of the ast's
op-times/varnode-create-indices — the click-to-address contract, end to end.
protocol_e2e's byte-exact full-session test drops decompileAt (a real decompile
isn't byte-deterministic; the e2e test covers it).

Gates (independently re-verified): build clean, kuna-ghidra 20 unit + e2e +
protocol_e2e all pass, make test 675/675 PARITY OK, test-stages 254/254 PARITY
OK, make rust-test green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…e boundary

Phase 2 (engine bridge → first C in the GUI) is done on feat/ghidra-mode-phase2:
check off every step, note the Box<dyn EngineTranslate> trait refinement vs the
plan's enum (avoids the kuna-decomp↔kuna-ghidra cycle), and record the scope
boundary — decompileAt runs against an empty ScopeInternal, so unresolved
refs degrade to placeholders and the lazy ScopeGhidra/TypeFactoryGhidra is
Phase 3.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
@mahaloz
mahaloz marked this pull request as ready for review July 5, 2026 23:58
@mahaloz mahaloz changed the title [PROPOSAL] feat(ghidra): Phase 2 — engine bridge (first real C in the Ghidra GUI) feat(ghidra): Phase 2 — engine bridge (first real C from kuna in ghidra mode) Jul 5, 2026
mahaloz and others added 2 commits July 6, 2026 00:41
…t-circuit

Line-faithful-port fidelity fix from the Phase 2 adversarial review. C++
GhidraTranslate::getExactRegisterName (ghidra_translate.cc:96-98) returns the
cached name from addr2nm before issuing any query; kuna's port dropped that
check and always queried the host, unlike its sibling get_register_name which
keeps it. A cache hit is keyed by a cached full register's exact vndata, so it
already satisfies the exact-size requirement — return it directly. Removes a
redundant host round-trip on every exact-name cache hit and the theoretical
dead-host mislabel (a swallowed query Err → "" → a real register mislabeled as
raw memory). Isolated to kuna-ghidra (a query-backed function off the standalone
path); kuna-ghidra tests green.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
…ension for Phase 2

The KunaDecompiler extension (added in Phase 1) now runs against the working
Phase-2 backend, so make it easy to actually run kuna inside a real Ghidra:

- build.sh: compiles the kuna_ghidra release binary, stages it into the right
  os/<platform>/ dir (mapped from uname to Ghidra's Platform enum names), and —
  if GHIDRA_INSTALL_DIR is set — packages the installable extension zip. One
  command from source to installable artifact; echoes which install it targets.
- README: status Phase 1 (protocol skeleton) -> Phase 2 (kuna decompiles — real
  C with click-to-address; placeholders for globals until the Phase-3 symbol
  scope), a step-by-step "Run the kuna backend in a real Ghidra instance" runbook
  leading with build.sh (build -> install zip -> enable plugin -> decompile), and
  a corrected Verify section (real C, not the old phase-1 per-function message).

The staged binary stays a gitignored artifact.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017t3eYSdxwUsPjN2s2oLGof
@mahaloz mahaloz changed the title feat(ghidra): Phase 2 — engine bridge (first real C from kuna in ghidra mode) feat(ghidra): run kuna as a drop-in, backwards-compatible decompiler backend for the stock Ghidra GUI (Phase 2 — real C) Jul 6, 2026
mahaloz and others added 6 commits July 6, 2026 21:14
…am registerProgram

Phase-2's e2e test used a synthetic context-free pspec, which masked a gap:
against a real Ghidra language the x86-64 pspec sends
`<context_data><context_set><set name="addrsize" .../>...`, but the wire tspec
(`<sleigh>`) carries only address spaces — no context-variable definitions. The
query-backed GhidraTranslate builds an empty context database (there is no `.sla`
parse to registerContext them), so parse_processor_config -> decode_from_spec
raised "Non-existent context variable: addrsize", registerProgram failed, and
nothing decompiled under a real Ghidra.

Upstream C++ ContextGhidra::decode/decodeFromSpec (ghidra_context.cc) are both a
bare decoder.skipElement() — "Ignore details handled by ghidra": the Java host
owns disassembly context and returns already-context-resolved p-code via
getPcode. Mirror that by skipping the <context_data> decode when the translate is
the query-backed engine (translate.as_sleigh().is_none()); the standalone Sleigh
path returns Some and still applies the paints, exactly as the 675 x86 datatests
(which need addrsize/opsize for 64-bit disassembly) require.

Verified end to end: preloading a stock Ghidra 12.x with the kuna core and driving
it via PyGhidra now decompiles real x86-64 self-contained functions (openProgram
-> True). make test 675/675, make test-stages 254/254, make rust-test green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…terministic across build hosts

FloatFormat emulated float ops by passing through the host FPU, so the sign of a
NaN produced by an invalid operation (sqrt(-1), 0/0, inf-inf, 0*inf) followed the
host: x86 yields the negative "real indefinite" (0xffc00000), Apple-Silicon/ARM
the positive default NaN (0x7fc00000). IEEE-754 leaves this host-defined and
Ghidra's own C++ inherits it (float.cc signbit(host)), so on macOS five tests
failed — make test Float print #6/#13 (the datatest constant-folds 0.0/0.0 at
analysis time) plus kuna-num golden_float, golden_opbehavior,
test_edge_inf_nan_arithmetic, and testfloatemu.

Add FloatFormat::encode_generated: when an op generates a NaN from non-NaN inputs,
pin the x86 indefinite sign; a propagated NaN (an input was already NaN) keeps its
host-deterministic sign. Applied in op_add/op_sub/op_mult/op_div/op_sqrt. This is
provably x86-invariant — on the oracle host the FPU already yields 0xffc00000, so
the forced value equals get_encoding and every golden vector / baseline byte is
unchanged — it only makes non-x86 hosts match. The engine's decompile output is
now deterministic across build hosts, which a decompiler wants regardless.

testfloatemu is the counterpart host-parity test (FloatFormat == native host FP);
its five arithmetic cases now canonicalize the host reference the same way
(canon_generated_nan4, a no-op on x86) so it stays meaningful off-x86.

Full suite green on macOS/ARM64: make test 675/675, make test-stages 254/254,
make rust-test 4237/0 across 275 binaries.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…n README

The GUI plugin can't load in a headless PyGhidra session, so document the
file-drop preload + a minimal pyghidra.open_program/DecompInterface snippet that
decompiles on the kuna core with no code changes, plus how to confirm/revert which
core is active. Snippet verified end to end against a real Ghidra install.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…e surgery)

The file-drop seam requires deleting the binary to revert. Add the recommended
headless path: reflectively set DecompileProcessFactory.exepath from Python
(enable_kuna/disable_kuna) — the same mechanism the GUI plugin's "Use Kuna Core"
checkbox uses — to flip the core on/off at runtime with no file changes. Keep the
file-drop as the persistent alternative for analyzeHeadless / system-wide use.
Toggle verified end to end in one PyGhidra session (stock -> kuna -> stock).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ecompilerInterface" in the GUI

The stock GUI's DecompInterface calls setOptions before opening the program.
kuna's phase-2 setOptions stub answered 't' but ALSO emitted a "N option
element(s) recorded but not applied (phase 1)" note on the 16/17 message frame.
initializeProcess() leaves that native message in place, and
openProgram()/isErrorMessage() (DecompInterface.java) treat any non-empty native
message that lacks the word "warning" as a FATAL init error — so the Decompiler
window showed "Unable to initialize the DecompilerInterface: kuna ghidra-mode:
setOptions: ..." even though the options were accepted and the function would
decompile. (Headless DecompInterface use with no setOptions call didn't hit this,
which is why the earlier PyGhidra smoke test passed.)

Upstream SetOptions::rawAction answers 't' with NO message on success. Match that:
consume the <optionslist> for protocol alignment and accept silently (the engine
still has no option database, so options remain unapplied — phase 3). Drop the now
-unused count_option_elements helper and the options_raw command field, and update
the protocol_e2e expectation (setOptions -> "t" + empty 16/17 frame).

Verified: replaying the GUI init sequence (setOptions then openProgram) headless now
returns openProgram -> True with an empty last message and decompiles. make test
675/675, make test-stages 254/254, make rust-test 4236/0.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…esent" in the GUI

A function that declares a local failed to decompile in the Ghidra GUI with
"Pcode: Decoding error: Attribute symref is not present". kuna's C-markup emitter
built the var-declaration MarkupRef once as MarkupRef::none() and reused it for
every declaration, so begin_var_decl never wrote a symref. Ghidra's
ClangVariableDecl.decode does a REQUIRED readUnsignedInteger(ATTRIB_SYMREF) —
an absent attribute aborts the entire markup decode (fatal), so the Decompiler
window showed nothing. C++ emitVarDecl(sym) always writes sym->getId()
(prettyprint.cc:154). (Toy functions with only parameters emit no <vardecl>, which
is why the earlier PyGhidra smoke tests missed it.)

Populate markup.symref per declaration with the declaration representative
Varnode's create index — the same id the <ast> and the token varref already carry.
Phase 2 does not yet encode <localdb> (funcdata_encode.rs), so no HighSymbol reaches
Java to resolve against, but Java only *logs* an unresolvable symref (non-fatal) and
still renders the declaration; a real symbol id follows with the lazy scope encoding
(Phase 3/4).

Verified with a GUI-faithful harness (full analysis + decompile every function
requesting the C markup): /usr/bin/fmt now 38/38 (was 34/38), and wc/nl/uniq/od all
clean. make test 675/675, make test-stages 254/254, make rust-test 4236/0.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
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.

1 participant