Skip to content

[AUTOMATED] feat(p1): dynrelocs — apply a linked image's dynamic relocations (DIV-84) - #328

Merged
mahaloz merged 3 commits into
mainfrom
feat/dynrelocs
Aug 22, 2026
Merged

mahaloz merged 3 commits into
mainfrom
feat/dynrelocs

Conversation

@mahaloz

@mahaloz mahaloz commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

The gap

kuna's ELF loader maps the PT_LOAD bytes the linker wrote, which is not the image a process runs. Every slot filled by a dynamic relocation — R_*_RELATIVE, R_*_GLOB_DAT, R_*_JUMP_SLOT — is left at 0 for the run-time loader to complete, and in a PIE (the default link mode of every current toolchain) that is the whole .got plus every relocated function pointer in .data.rel.ro.

So a call through a pointer the linker itself resolved reads a null target and can never deindirect. kuna printed (*dat_e0dc8)(...) for a callee it had already named. Zero is not an ambiguity to be judged — it is a byte the run-time image never holds.

ET_REL .o files were already covered (relocobjects / relocrebase); linked images were not.

What this does

New loader-tier option dynrelocs (on|off, default ON, DIV-84).

1. Apply the relocations. kuna-analysis/src/loader/kuna_dynrelocs.rs (resolve) walks .rela.dyn / .rel.dyn / .rela.plt and writes what the dynamic loader would:

  • RELATIVE → load bias + addend (kuna maps a linked image at its declared vaddrs, so the bias is 0);
  • GLOB_DAT / JUMP_SLOT → the symbol address, and only when that symbol is defined in this same image. An undefined one is an import whose value lives in another object; there is nothing to write, the existing PLT/import naming already covers the call, and it is skipped — so that path (DIV-8/DIV-9) is byte-identical, lazy-binding stub contents included.
  • COPY / IRELATIVE / TLS* are not statically knowable and are skipped.

Architectures by relocation triple: x86-64, AArch64, i386 and ARM. Both RELA (explicit addend) and REL (in-place addend, 32-bit ELF) tables. All four are covered by hand-built synthetic-ELF unit tests; x86-64 additionally by a real PIE fixture and by the measurements below. i386 is done, not deferred.

2. Make the value foldable — the half that actually turns the call into a name. .got is SHF_WRITE, so nothing downstream trusts it, and the constant fold of read-only storage is gated program-wide by option readonly (readonlypropagate, default off; turning it on would fold every .rodata read in the program — a far larger change than this one, and measurably so).

The narrow warrant is PT_GNU_RELRO: the linker's own statement that the range is mprotected read-only once startup relocation finishes. The written slots RELRO covers are reported twice — through getReadonly (painting Varnode::readonly, as for any read-only section) and separately as ObjectLoadImage::dynreloc_const_ranges → Architecture::dynreloc_const → the per-function handle, where ActionVarnodeProps folds a read-only varnode inside one of those ranges with global propagation still off.

So the blast radius is exactly the relocated RELRO slots, not the program's read-only data. Slots outside RELRO (a RELATIVE pointer in ordinary .data) are still filled in — that IS the value at process start — but are never declared constant, because the program may legitimately overwrite them.

The two halves are useless apart: relocating without the constancy leaves the load unfolded; declaring constancy without relocating would fold the call target to zero.

Loader-tier, so the gate is the KUNA_DYNRELOCS env bridge (the image is snapshotted inside load file, upstream of every per-function option), set by the CLI on the decomp_dbg subprocess and on its own process for the in-process drivers — the relocrebase / relocobjects / i386_pie_plt pattern. --option dynrelocs off restores the pre-fix bytes exactly.

Measurements

Test binary: a 4.9 MB static-PIE Rust executable (1,539 R_X86_64_RELATIVE, 640 of them pointing into .text). Not committable; not committed.

1. The showcase — kuna decompile ./FakeCrypt --addr 0x55300

Off vs on, same build, whole diff:

-  let mut v19: u64;                 // stack - 0x7c0
+  let mut v19: *mut *const ();      // stack - 0x7c0
@@
-  v2 = (*dat_e0dc8)(&mut v5,&mut v7);
+  v2 = read_to_end(&mut v5,&mut v7);
@@
-    v19 = dat_e0e38;
+    v19 = fmt;
@@
-    (*dat_e0dd0)(&mut v8);
+    _eprint(&mut v8);

2 unnamed indirect calls → 0, plus one dat_... argument resolving to a named global. No other line changes.

2. Whole-binary — kuna decompile-all ./FakeCrypt --json

off on
functions 4,194 4,194 (inventory identical)
unnamed indirect call sites 2,853 560 (−80.4%)
functions carrying ≥1 1,172 276
functions whose code changed — 1,077

3. C collateral (option off vs on, whole-binary decompile-all)

binary functions differing verdict
tests/bug-repro/grep (PIE) 449 0 —
tests/bug-repro/sort (PIE) 490 0 —
tests/bug-repro/faillog 69 2 improvement
tests/bug-repro/libselinux.so.1 621 31 improvement
tests/bug-repro/betaflight_STM32F405.elf (ARM firmware) 5,797 0 no dynamic relocs — inert as designed

Function inventories are identical on every one. grep/sort are PIE and do have .rela.dyn, but their RELATIVE slots are .init_array / .data.rel.ro entries that no function reads as a call target, so nothing moves.

Every one of the 33 changed functions is an improvement. faillog:

-  dat_62a0 = *dat_5ff8;
+  dat_62a0 = stderr;

libselinux.so.1 — a GOT slot for a defined global now reads its own name, and the pointer temp disappears:

-  unsigned long *v1;
-  v1 = dat_2bf40;
-  free((void *)*dat_2bf40);
-  *v1 = 0;
+  free(selinux_mnt);
+  selinux_mnt = NULL;
-        v6 = (*dat_2d920)(dat_2bfb8);
+        v5 = (*dat_2d920)(avc_netlink_loop);

No regressions found in any of the 33.

4. Speed (interleaved, never batched)

measurement off on delta
sanctioned gate (scripts.pipeline.timeit, showcase function, median of 5, budget +5%) 471.8 ms 331.7 ms −29.7% ✅
kuna functions on the 4.9 MB PIE — load + discovery only, min of 5 1.324 s 1.317 s −0.50%
decompile-all grep, min of 5 13.552 s 13.574 s +0.16%
decompile-all libselinux.so.1, min of 5 8.029 s 7.963 s −0.81%
decompile-all faillog, min of 5 0.489 s 0.487 s −0.33%
decompile-all on the 4.9 MB PIE, min of 2 137.6 s 172.9 s +25.7%

Reported honestly: the last row is a real cost. It is not the relocation walk — the load-only measurement isolates that at −0.5%, and every binary where nothing new resolves is within noise. It is the price of decompiling 2,293 newly-resolved direct calls (prototype recovery, deindirect restarts) that were previously dead ends. Per-function, resolving the call makes the decompile faster, which is what the sanctioned gate measures.

5. securitycheck (#325, DIV-82) — it was measured dead on this binary

All seven rustc panic helpers in this binary are reached only through GOT slots (one R_X86_64_RELATIVE each: panic_bounds_check @ 0xe0cd0, slice_error_fail @ 0xe0d00, …). With dynrelocs off, securitycheck cannot see a single one:

functions securitycheck changes
dynrelocs off 0
dynrelocs on 85
 // core::ops::range::Range::index
-unsafe fn index(mut a0: u64, mut a1: u64, mut a2: u64) -> u64 {
+unsafe fn index(mut a0: u64, mut a1: u64) -> u64 {
   let mut v1: u64;
-  if a0 <= a2 { v1 = a1; return v1; }
-  slice_end_index_len_fail(a0,a2,0xdb358);
+  v1 = a1;
+  return v1;
 }

Gates (all four, verbatim)

$ make test
datatests: 675/675 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make test-stages
datatests: 501/501 assertions passed
exit: 0

=== baseline parity ===
PARITY OK

$ make rust-test
318 test suites ok, 0 failed (full cargo workspace suite + docs/options.md freshness). real 6m25s.

$ make check-spec
python3 tools/check_spec.py
check-spec OK (lenient mode)

$ python3 tools/check_spec.py --strict
check-spec OK (strict mode)

$ kuna catalog --check
catalog OK: documents exactly the registered kuna options

docs/baseline.json and docs/baseline-stages.json are unchanged — the XML <binaryimage> datatest path never reaches bootstrap_from_object, and the fold gate is additionally inert wherever dynreloc_const is empty.

Bookkeeping

  • phases.toml [[settable]] row with all 17 fields (tier = analysis, change_kind = correctness-fix, source_decompiler = kuna — chosen to dodge every pinned bucket in tests/stages/kuna-catalog.xml, which therefore needs no edit and forces no stages-baseline re-record).
  • Counts re-derived from the built artifact after rebasing onto [AUTOMATED] feat(p7): securitycheck — strip rustc bounds/overflow panic branches #325 + [AUTOMATED] feat(p2): cleanupcode - delete the Rust drop/deallocate call sites (DIV-81) #326: live catalog 114, catalog_bytecompat.rs 114, kuna_phases/tests.rs 114 / tiers (24, 50, 40) / },\n 113 / live readers 34, phase_catalog.json 114, docs/options.md 114.
  • Spec prose: docs/spec/01-program-prep.md §1.2 (the mechanism, two paragraphs, next to relocobjects/relocrebase) + §1.1 env-bridge list; docs/spec/03-ssa-and-simplification.md (the ActionVarnodeProps fold exception); docs/spec/00-overview.md env-bridge table — which was stale at "Four loader gates" and is corrected to seven (KUNA_RELOCREBASE, KUNA_IFUNCFPRET, KUNA_TYPEDEPTH were missing).
  • docs/history.md DIV-84.
  • Tests: 4 synthetic-ELF unit tests (x86-64 RELA, AArch64 numbering, i386 REL implicit addend, unhandled-machine inertness) + 1 real-PIE loader test on cet_pie_x86_64 (relocations applied, imports untouched, only the RELRO slots constant) + tests/verify_dynrelocs_gate.rs in its own test binary, because the gate is a process-global env var. No tests/stages/*.xml — the loader-tier precedent, which also spares the kuna-base/src/xml.rs corpus-count collision.

Known limitation

object's dynamic-relocation walk finds the tables through section headers. An image stripped of its section header table has no reachable .rela.dyn, so the pass is inert there rather than wrong. Reading the tables from DT_RELA/DT_REL/DT_JMPREL instead would close that; it is a self-contained follow-up.

Also scoped out deliberately: only the loader image is relocated, not the byte view the analysis passes re-parse. So e.g. .init_array discovery still reads zeroes on a PIE. That is the relocrebase-style "rebased view" shape and belongs in its own PR with its own discovery measurements.

🤖 Generated with Claude Code

https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9

mahaloz and others added 3 commits August 22, 2026 05:23
kuna's ELF loader maps the PT_LOAD bytes the *linker* wrote, which is not
the image a process runs. Every slot filled by a dynamic relocation
(R_*_RELATIVE / GLOB_DAT / JUMP_SLOT) is left at 0 for the run-time
loader, and in a PIE -- the default link mode of every current toolchain
-- that is the whole .got. A call through such a slot reads a null target
and can never resolve, so kuna rendered `(*dat_e0dc8)(...)` for a callee
that is a named function in the very same image.

`dynrelocs` (default-ON, DIV-84) walks .rela.dyn / .rel.dyn / .rela.plt
at load and writes the value the dynamic loader would store: RELATIVE
takes the load bias plus the addend; GLOB_DAT/JUMP_SLOT take the symbol
address, and ONLY when that symbol is defined in this same image -- an
undefined one is an import whose value lives elsewhere, so it is skipped
and the existing PLT/import naming path is untouched. x86-64, AArch64,
i386 and ARM; RELA and REL (in-place addend) tables both.

Applying the relocation is only half of it: .got is SHF_WRITE, so nothing
downstream would trust it, and the constant fold of read-only storage is
gated program-wide by `option readonly` (default off; turning it on would
fold every .rodata read in the program). The narrow warrant is
PT_GNU_RELRO -- the linker's own statement that the range is mprotected
read-only before main. The written slots RELRO covers are reported both
through getReadonly (painting Varnode::readonly) and separately as
Architecture::dynreloc_const, where ActionVarnodeProps folds them with
global propagation still off. So the blast radius is exactly the
relocated RELRO slots, not the program's read-only data.

Loader-tier, so the gate is the KUNA_DYNRELOCS env bridge (the image is
snapshotted inside `load file`, upstream of every per-function `option`);
`--option dynrelocs off` restores the pre-fix bytes exactly.

[AUTOMATED] Generated by an agent run.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
Records the measured effect of the default-ON flip (unnamed indirect call
sites 2,853 -> 560 on a static-PIE Rust binary; zero-collateral on
grep/sort/betaflight; faillog and libselinux.so.1 change only to name a
global they could not name before) and the second-order finding that
`securitycheck` (DIV-82) was measured dead on that binary -- all seven
rustc panic helpers are reached through GOT slots, so it stripped 0
functions before and 85 after.

Also guards `resolve` against an ET_REL object explicitly, so the
function's own contract matches its doc rather than relying on the caller
having taken the `relocobjects` branch first.

[AUTOMATED] Generated by an agent run.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
…l in DIV-84

Independent verification of the DIV-84 numbers reproduced the headline (unnamed
indirect call sites 2,860 -> 560, functions carrying one 1,174 -> 276) and the
whole-binary cost (129.9 s -> 168.3 s), but also turned up a consequence the row
did not record: FakeCrypt's error count goes 2 -> 5. Three functions cross
--mode fast's 10 s per-function budget once their calls resolve, and a reader of
the row would otherwise conclude nothing was lost.

Re-measured in isolation to rule out contention -- the slowdown is deterministic
(6.7->18.6, 12.6->20.6, 8.0->12.7 s). The trade is stated plainly: 3 functions
lost against 2,293 call sites named, recoverable with `--option dynrelocs off`
or a larger per-function budget.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_016WUuE4zdiEqZFWLL2YEUk9
@mahaloz
mahaloz merged commit 87c54a2 into main Aug 22, 2026
9 checks passed
@mahaloz
mahaloz deleted the feat/dynrelocs branch August 22, 2026 06:51
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