Skip to content

Make Kuna nicer to use as a library - #1602

Merged
mahaloz merged 19 commits into
Noelo-Lab:mainfrom
evanrichter:pr/librarification
Nov 16, 2026
Merged

mahaloz merged 19 commits into
Noelo-Lab:mainfrom
evanrichter:pr/librarification

Conversation

@evanrichter

Copy link
Copy Markdown
Contributor

Hi Zion! I'm using Kuna as a library in a side project and it's been great except for just a few rough edges. Mainly removing the "cli-isms" like allowing options from environment vars and reading spec files from disk. Also being able to load headerless images that will support firmware or raw shellcode loading directly.

Also, with this PR it's possible to embed the spec files/dirs into the kuna cli directly so that separate files aren't needed in the distribution. (although with how infrequently they change, I'm not sure if the binary size tradeoff would be worth it).

One thing in the new code that might be a future footgun: LoadOptions uses thread locals to manage binary load options. In a single threaded async runtime, it's technically possible for callers to yield one kuna analysis with one set of LoadOptions to another async task that was set up with a different LoadOptions. I think in practice this usage would be rare, but certainly the errors would be strange and possibly look like unexpected decompilation failures. We went with the implementation tradeoff of being able to more closely match the current code that took options from env. LMK if you want a second pass at that.

An automated PR description follows:


[AUTOMATED] Load binaries as a library: in-memory specs, explicit LoadOptions, one Bootstrap builder

A program that embeds Kuna can now load many binaries in one process, on several threads, each with its own settings, from specs it holds in memory.

On main, each load scans a specs/ directory and reparses every .ldefs. Each load also reads its settings from process-wide KUNA_* environment variables, and an object load writes KUNA_GOVERSION, so two threads cannot load with different settings.

use kuna_console::engine::{language_database, Bootstrap};
use kuna_decomp::kuna_loadoptions::LoadOptions;
use kuna_decomp::kuna_memoryspecs::MemorySpecs;

// One language's .ldefs, .sla, .pspec and .cspec, compiled into the caller.
static X86_64: &[(&str, &[u8])] = &[/* ("x86.ldefs", include_bytes!(..)), .. */];

let db = language_database(&[MemorySpecs::new(X86_64)])?; // scans once
let options = LoadOptions { load_strings: false, ..Default::default() };
let load = Bootstrap::new(&db).options(&options); // reads no environment
std::thread::scope(|s| {
    for path in ["a.so", "b.so"] {
        s.spawn(move || inspect(load.object(path)));
    }
});

On main this does not compile. These tests show it working:

make specs
cd decompiler
cargo test -p kuna-console --test integration -- verify_memoryspecs:: verify_language_database:: verify_bootstrap::
cargo test -p kuna-console --test verify_loadoptions

What changed

  • MemorySpecs holds a compiled spec tree as (path, bytes) pairs. Each bootstrap gains a *_with_specs form that takes directories, memory trees or both. One language's files, flat, form a complete tree.
  • LoadOptions holds every load setting: the load-time catalog options, the fat slice, the .pdb, .fid and FLIRT paths, the Go release and the KUNA_LOAD_* switches. A load with explicit LoadOptions neither reads nor writes the environment. The Architecture keeps its LoadOptions and re-enters them for analysis and decompilation.
  • language_database(roots) scans the specs once, and the *_with_db bootstraps reuse its result.
  • Bootstrap::new(&languages).target(..).isa(..).options(..) replaces the growing set of bootstrap_* variants. It has one method per input: object, image, file, raw, te, te_bytes, mz_bytes, xml_image, xml_root. The builder is Copy, so threads can share it.
  • Existing callers see no change. Each bootstrap_* function keeps its signature and calls the builder. A load without LoadOptions reads the environment as before.

Tests

  • Specs in memory decompile the fauxware fixture as the specs/ directory does, and never fall back to the filesystem.
  • Loads on separate threads keep their own LoadOptions and leave the environment untouched.
  • One database serves two threads, and a bootstrap over it does not rescan the specs.
  • For every input and setting, the builder builds the same program as the old entry point.

No existing expectation moved: make test stays at 675/675 and make test-stages at its baseline.

thotypous and others added 9 commits November 15, 2026 08:35
- The extrapop solver equated every input of a stack-pointer merge, so a path lowering SP by a runtime amount took the other path's constant and was rewritten away.
- Mark SP values moved by a non-constant amount, and merges they reach, as dynamic: no equation touches them and they are never rewritten.
- Regression: Open Watcom DOS alloca behind stackavail() at -od and -ox.
- Dynamic marks follow COPY, CAST, INDIRECT, INT_SUB and PTRADD/PTRSUB value inputs, not only merges.
- Only equations joining a dynamic value to a fixed one are dropped; relations among dynamic values stay, unanchored.
- PTRADD's element size is not an amount; INT_SUB(sp, c) gets the equation add sp,-c, so a constant reservation on one arm is solved instead of equated.
- A non-constant adjustment is often a constant not yet propagated (add sp,si with si == 2 after a push): a trial upstream solve implies a nonzero move there, so it stays solved as before.
- Only an adjustment whose solved move is zero (the merge equated it away) or that stays unsolved is treated as runtime. FreeDOS sweep: ARJ/GZIP return to main's output; FORMAT and JWASMR keep the Watcom alloca amount.
- mov ax,8; sub sp,ax is a fixed reservation: literal_value sees through the copy, so it is not marked runtime.
- is_const/const_off read literal_value, so mov ax,8; sub sp,ax is solved as an 8-byte adjustment instead of being equated through a merge.
- Document that confirm_dynamic is evidence, not proof: a runtime arm merged with a nonzero constant keeps upstream's answer.
- The regression test now requires the reservation arm's pointer to use the (n + 1) & ~1 amount.
A library caller can now pass its compiled specs as bytes instead of
shipping a specs/ directory. MemorySpecs holds a spec tree as
(path, contents) pairs, over a static table or over owned data such as
Vec<u8> or Arc<[u8]>. SpecRoot names a directory or such a tree.

Each public bootstrap gains a *_with_specs form that takes any list of
spec roots, and the &[String] functions delegate to it.
LanguageDatabase owns the trees it was given, so nothing is registered
process-wide.

A tree need not follow Ghidra's layout: one language's .ldefs, .sla,
.pspec and .cspec, flat, form a complete root. Tests check that
memory roots decompile the fauxware fixture as the specs directory
does, never fall back to the filesystem, and mix with directory roots.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Library callers can now load several images at once in one process
with different settings. LoadOptions holds every load-time option
(ppc32picimports, ifuncfpret, ppcapu, kernelcache, goabi,
symbolnamechars, libctypes, calltargettype, macho-arm64e, sourcelang,
objcivars, objcsdk, dyldimage, dyldcrossrefs), the fat slice, the .pdb,
.fid and FLIRT paths, the Go release, and the load-pass and mapping
switches that KUNA_LOAD_OBJC, KUNA_LOAD_STRINGS and KUNA_LOAD_MMAP set.
bootstrap_from_object_with_options and bootstrap_from_image_with_options
put it in force on the loading thread, and each Architecture keeps its
options and re-enters them around analysis, decompilation, name lookup
and console commands. An explicit-options load neither reads nor writes
the environment; environment_fallbacks() counts reads that fell back to
it on a thread.

The entry points that take no options load from the environment,
publish KUNA_GOVERSION, and build programs that read the environment
live. set_kuna_option and reset_wire_defaults write the environment for
a later load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A library that loads many binaries can now scan and parse the .ldefs
files once. language_database(spec_roots) scans the roots, and
bootstrap_from_object_with_db and bootstrap_from_image_with_db take the
database in place of the spec roots, alongside LoadOptions. A test
loads two images on two threads from one database and shows that a
bootstrap over it does not rescan the roots.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Kuna has 26 bootstrap_* entry points, one per combination
of input format, language source (spec roots or a scanned
LanguageDatabase), ARM ISA (environment, explicit) and load options
(environment, explicit). Each new setting doubled the set.

Bootstrap::new(&languages).target(..).arm_isa(..).options(&opts) now
holds those settings, and one method per input loads with them:
object, image, file, raw, te, te_bytes, mz_bytes, xml_image,
xml_root. LanguageSource, a sealed trait, accepts spec roots as a
slice, array or Vec, or a LanguageDatabase. The builder is Copy, so one
configured builder can load many inputs, on several threads.

Without options, a load puts the environment in force for that load on
the calling thread, and an unset ISA comes from KUNA_ARM_ISA. With
options it reads neither. Explicit options now also reach raw, TE, MZ
and XML loads.

Each bootstrap_* function becomes a one-line wrapper over the builder.
Tests check that explicit options reach every input without the
environment, that a builder without options reads the environment and
one with options does not, and that one builder loads the same program
on several threads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
thotypous and others added 7 commits November 16, 2026 09:09
Funcdata::clear stubbed upstream's localmap->clearUnlocked(), resetLocalWindow()
and funcp.clearUnlockedOutput(), so a restart began from the symbols and
prototype the previous pass recovered. A function that finds a lowered switch
late and restarts printed differently from a later decompile that installs
the saved switch first.

- Port ScopeInternal::clearUnlocked as Database::clear_unlocked: keep
  type-locked symbols (unlocked name reset, nolocalalias cleared, size-locked
  type reset to undefined), equates and asserted isolated identities.
- Call it from Funcdata::clear, reset the local window, clear the unlocked
  output, and clear unlocked inputs (the port keeps them in the prototype).
- Tests: clear_unlocked unit test; the floatret_restart CLI fixture now
  prints the restarted pass's unsigned int; the joined-callback stage's
  second() returns the call directly.
…n the spec

The load-time env-bridge section and the KUNA_GOVERSION prose still named the
environment as the only channel. They now describe explicit LoadOptions,
the precedence between explicit options and the environment, how a program
re-enters its own options, spec roots held in memory, and a language
database scanned once and shared across loads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
… for every load without options

A LoadScope restored the options it replaced, so dropping two scopes in the
wrong order left the thread with options no live scope held. Scopes now sit
on a per-thread stack and each removes only its own entry, so the innermost
live scope is always the one in force. The guard stays !Send.

A Bootstrap without options put the environment in force for object and
image loads but let raw, TE, MZ, XML loads and the file classifier inherit
whatever options the thread held, so with another program's scope held they
built a program frozen to that program's options. Every input without
options now loads under the environment.

environment_fallbacks() is test instrumentation and is hidden from the docs.
New tests: a program re-enters its own options after a later load on the same
thread (kernelcache, symbol names, dyld image, slice, pdb, objc sdk, Go
release, ARM ISA); a failed load leaves no options in force; a load without
options ignores a held scope; the console loads its next image from the
environment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
… builder replaces

The fifteen free functions added alongside Bootstrap were one-line calls
into it and had no user outside this change's own tests, which now call the
builder. The existing bootstrap_* functions keep their signatures. Two
inline comments move into their function headers, and the spec-copy test
follows symlinked .sla files, as a worktree that links its built specs has.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
…inter solver spec

The solver change had no prose in its owning chapter. Add it to
docs/spec/06 next to the StackSolver section: which adjustments are
runtime-sized, the trial solve, the forward mark, what is never rewritten,
the exact equations for constant adjustments, and the known limits (a
sibling nonzero constant, a guessed earlier pop, a reservation inside a
helper call, and that stack traffic after the reservation stays raw pointer
arithmetic so an unlocked callee there takes no stack arguments).

The CLI test now also requires the store into the reservation to survive,
and its header records the full Open Watcom 2.0 command line; both fixtures
rebuild byte for byte with it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
The console's `option calltargettype` sets only the decompile-time switch,
so a later `load file` still runs the DWARF function-pointer mapping; the
spec said every load-time option line reaches the next load. An explicit
load leaves the load-time variables alone, not every variable. The Go
release is read from the image's bytes, so it is set before the loader
parses them, not before the image is opened.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
@mahaloz

mahaloz commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

[AUTOMATED] Thanks for this, @evanrichter. Spec roots held in memory, explicit LoadOptions and the Bootstrap builder are a real improvement for anyone embedding kuna. The design is unchanged. I pushed four small commits on top of yours:

  • 3ddba2c Spec prose. The repo keeps docs/spec/ in sync with behaviour. Two places still described the environment as the only channel: the load-time env bridges section in 00-overview.md and the KUNA_GOVERSION paragraph in 01-program-prep.md. Both now cover LoadOptions and how it takes precedence over the environment, MemorySpecs, and language_database.
  • d75c5f7 Two scope fixes, with tests.
    • LoadScope restored the options it had replaced. If two guards were dropped in the wrong order, the thread kept options that no live guard held. Scopes now sit on a per-thread stack, and each guard removes only its own entry. The guard is still !Send.
    • A Bootstrap without options put the environment in force for object/image, but raw, te, te_bytes, mz_bytes, the XML inputs and file's classifier inherited whatever the thread held. With another program's scope held, this built a program frozen to that program's options. Repro: hold a.arch().load_scope() for a program loaded with kernelcache: Off, then call Bootstrap::new(&roots).te(path). The new program reported kernelcache off no matter what the environment said. Every input without options now loads under the environment. The console was never affected, because load file refuses while a program is loaded.
    • New tests: a program re-enters its own options after a later load on the same thread (kernelcache, symbol names, dyld image, slice, pdb, objc sdk, Go release, ARM ISA); a failed load leaves no options in force; a load without options ignores a held scope; the console loads its next image from the environment.
  • 5602dc1 Trimmed public surface. I removed the fifteen bootstrap_*_with_specs / *_with_options / *_with_db free functions. Your last commit's builder replaces them, and nothing outside this PR's tests called them. Those tests now use Bootstrap. The existing bootstrap_* functions keep their signatures. environment_fallbacks() is #[doc(hidden)], since it is test instrumentation. Two new inline comments moved into their function headers, per the repo's comment style. The spec-copy test now follows symlinked .sla files.
  • 080273e Spec corrections. Three sentences in that prose overstated things. The console's option calltargettype sets only the decompile-time switch, so unlike the other load-time options it does not reach a later load file (the DWARF function-pointer mapping follows KUNA_CALLTARGETTYPE). An explicit load leaves the load-time variables alone, not every variable. The Go release is read from the image's bytes before the loader parses them.

I byte-compared decompile-all --json, functions, strings and xrefs against main across every load path and each KUNA_* load-time variable. The output is unchanged, and so are load time and peak RSS.

Possible follow-ups, none of which block this PR:

  • Mark LoadOptions #[non_exhaustive] (callers would mutate a default()), so adding a load-time option later does not break struct literals.
  • Re-export LoadOptions, MemorySpecs and SpecRoot from kuna_console::engine, so an embedder needs only one crate.
  • Add a Bootstrap::raw_bytes for headerless images held in memory (firmware, shellcode). bootstrap_raw_image already takes bytes internally.
  • Over time, deprecate the older bootstrap_* free functions in favour of Bootstrap.

@mahaloz
mahaloz merged commit ae41f49 into Noelo-Lab:main Nov 16, 2026
coleleavitt added a commit to coleleavitt/kuna that referenced this pull request Nov 18, 2026
Brings the fork up to upstream main a42c036: the option-catalog restructuring
(Noelo-Lab#1522-Noelo-Lab#1532, 127 options made unconditional or folded into their parents),
the library-friendly bootstrap (Noelo-Lab#1602, LoadOptions/Languages), the mmap'd
image bytes (Noelo-Lab#1506), FID strict/evidence (Noelo-Lab#1547/Noelo-Lab#1549/Noelo-Lab#1550), FLIRT through
the flirt-sig crate (Noelo-Lab#1548/Noelo-Lab#1564), the Itanium ctor/dtor naming (Noelo-Lab#1606/Noelo-Lab#1607),
the MIPS relocation/$gp rework (Noelo-Lab#1520), Octeon atomics (Noelo-Lab#1516) and the rest.

Conflict resolutions that are more than taking both sides:
- fid/flirt: upstream's reviewed FID/FLIRT lineage replaces the fork's
  in-tree .sig reader and FID callee arbitration (`fidcallees`, `flirtsites`
  options dropped; FLIRT site checks are unconditional upstream).
- `callothernoreturn` dropped: upstream's `brktrap` ends the flow at the
  compiler-trap immediates only, and keeps the resumable `brk`s.
- `gortti` now defaults off: upstream's `gotypeglobals` (default on) names the
  same descriptors and itabs; both on named every address twice.
- `calleeretpurge` no longer runs under a Windows cspec, where upstream's
  `calleepurge` reads the callee's purge (and settles the other calls first).
- the prelinked-kernelcache peel declines upstream's mmap path, which has no
  owned bytes to rebase.
- stage tests that upstream pinned under its defaults turn the fork's
  default-on options off where those change the output (alloca, repstring,
  itaniumeh, tailcontract); fork tests re-pinned to upstream's renderings
  (partial global reads, libcnames stack objects, relocatable-object symbol
  names, the one-case switch RuleSwitchSingle folds).

Generated files re-derived: docs/options.md, phase_catalog.json, the catalog
counts (305 options), the stage corpus count (875 files + 83 datatests),
docs/baseline-stages.json (4958 assertions), and the AARCH64 slacomp digest
over the merged AARCH64neon.sinc. docs/baseline.json is untouched
(PARITY OK 675/675).
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