Skip to content

[AUTOMATED] fix(analysis): name PPC64 ELFv1 import stubs that end in bctr or load the environment word - #1600

Merged
mahaloz merged 30 commits into
Noelo-Lab:mainfrom
phix33:fix/elfv1-small-toc-environment-stub
Nov 16, 2026
Merged

mahaloz merged 30 commits into
Noelo-Lab:mainfrom
phix33:fix/elfv1-small-toc-environment-stub

Conversation

@phix33

@phix33 phix33 commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

GNU ld builds a 64-bit PowerPC ELFv1 import stub in one of eight basic layouts,
and kuna names only three of them. The plain bctr stub that ld gives an
executable which creates no threads is one of the other five, so in a stripped
binary the import is an anonymous function and a no-return import no longer
ends its block:

cat > next.c <<'EOF'
void exit(int);
int next(int x)
{
    if (x < 0)
        exit(1);
    return x + 1;
}
EOF
powerpc64-linux-gnu-gcc -O2 -fPIC -shared -nostdlib -Wl,--no-plt-thread-safe next.c -o next.so
powerpc64-linux-gnu-strip next.so
kuna decompile next.so next
long next(int a0) // warn: Control flow encountered bad instruction data
{
  if (0 <= a0)
    return a0 + 1;
  sub_280(1);
  halt_baddata(); // warn: Bad instruction - Truncating control flow here
}

-Wl,--plt-static-chain prints the same. With neither option the output is
exit(1); // no-return.

Fix

  • A stub is std r2,40(r1), an entry load from r2 or from an addis base,
    mtctr, and the TOC load, then bctr or the lazy-resolution tail. The
    environment load that --plt-static-chain adds is now optional in every
    layout, and either ending may follow. Before, bctr was accepted only after
    an environment load from an addis base, and the lazy tail only without one.
  • When r2 itself is the base, the environment load must precede the TOC load,
    which replaces r2. The same two loads in the other order stay unnamed.
  • Naming is otherwise unchanged. The displacement and every possible TOC must
    still select one zero-addend R_PPC64_JMP_SLOT, and a lazy tail must still
    reach that import's resolver entry. ld's rarer forms (an addi-adjusted
    base, the xor/add pair it uses when the resolver is out of branch range,
    and stubs without the TOC save) stay unnamed.

Tests

  • Unit tests take every base, environment and ending combination with either
    entry register, and decline each single deviation: a wrong offset, register
    or base in any load, a missing TOC load, the loads or the CTR move out of
    order, an entry register other than r11 or r12, an ending that is
    neither bctr nor the whole lazy tail, and the rarer forms above. They fail
    without the fix.
  • The linked-image CLI tests gain five stub forms. Each is named and marks
    __stack_chk_fail no-return; conflicting TOCs, a local-descriptor alias, a
    nonzero addend and a lazy tail that reaches another import's resolver entry
    stay unnamed. Two of these tests fail without the fix.
  • In radare2-testbins, elf/ppc64v1-more gains its 113 import names. Its 33
    halt_baddata truncations are gone, and 454 of its 457 import call sites
    match the C prototypes; the other three are as before. Four functions there
    lose 44 call sites that were reached only by running past a no-return call.
    Because main no longer runs into _start, the speculative gap-walk adds
    sub_4bc0 inside it; kuna misses the ELFv1 _start with or without this
    change.
    elf/ppc64v1-libz-static-chain.so gains its 50 names and prints all 176
    functions exactly as elf/ppc64v1-libz.so. No datatest or stage expectation
    moved.

thotypous and others added 30 commits November 15, 2026 07:32
…ame header

- ppc_64_le.cspec placed the first stack parameter at SP+112, the ELFv1 offset after a 48-byte header.
  ELFv2 (every ppc64le target) has a 32-byte header (back chain, CR, LR, TOC), so the ninth doubleword is at SP+96.
  Callers lost their stack arguments and callees read an unwritten slot.
- Stage test kuna-ppc64le-elfv2-stack-args: callee `return i + a;`, caller `f9(n,2,3,4,5,6,7,8,n + 9)`; both fail on main.
- 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.
… version 2

- Big-endian ELFv2 (musl, -mabi=elfv2) has the same 32-byte frame header as ppc64le, so stack parameters start at SP+96; the default big-endian spec stays ELFv1 (SP+112).
- New compiler spec ppc_64_be_elfv2.cspec (id elfv2), chosen by the loader when e_flags & 3 == 2.
- Stage test from real clang -mabi=elfv2 output (fails without the selector); loader unit test; baseline re-recorded (4344/4344).
- ELFv2 saves r2 at 0x18(r1); the copied ELFv1 inject wrote 0x28, inside the parameter save area. Only used under callmechanisms on.
- 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]>
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
…he spec

The program-preparation chapter now states how the ABI version in e_flags
picks the PowerPC64 compiler spec and why the first stack argument sits at
SP+96 under ELFv2 and SP+112 under ELFv1; the call-mechanisms paragraph notes
that the big-endian ELFv2 model saves the TOC at 0x18(r1).

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
Resolve the stage-corpus count (both sides added two stage tests: 760) and
re-synthesize docs/baseline-stages.json from both sides' additions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0179iMKQeLQDThvbHGNoGw8h
@mahaloz
mahaloz merged commit 75ac0bb into Noelo-Lab:main Nov 16, 2026
@phix33
phix33 deleted the fix/elfv1-small-toc-environment-stub branch November 16, 2026 22:05
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.

4 participants