Skip to content

fix(ghidra): prevent loader relocations from constant folding - #4198

Closed
arslanbasharat-o-o wants to merge 13 commits into
morluto:mainfrom
arslanbasharat-o-o:fix/ghidra-copy-relocation-relro
Closed

arslanbasharat-o-o wants to merge 13 commits into
morluto:mainfrom
arslanbasharat-o-o:fix/ghidra-copy-relocation-relro

Conversation

@arslanbasharat-o-o

@arslanbasharat-o-o arslanbasharat-o-o commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #4177.

Ghidra now treats loader-initialized relocation destinations in non-writable loaded memory as uncertain during decompilation. This prevents RELRO copy-relocation values such as stderr from being presented as trustworthy file-backed constants.

Problem and expected behavior

OpenWrt's non-PIE MIPS usign contains a copy-relocated stderr in RELRO. The file stores zero at the destination while the runtime loader supplies the stream pointer. Ghidra could constant-propagate the on-disk zero, making fprintf(stderr, ...) appear to write through a null stream.

A loader-populated destination must not be presented as a known runtime constant. Evidence reports uncertainty only when an instruction reads an address covered by a loader relocation.

Change and scope

  • Mark blocks containing loaded, initialized, non-writable relocation destinations volatile before decompiler initialization, without changing permissions or source FileBytes.
  • Handle ELF ET_DYN PIEs and shared objects even though Ghidra also marks their relocation table relocatable. Keep relocatable object files and core files outside this mitigation.
  • Match Evidence references against the full byte range affected by each relocation and filter out writes/address-only references.
  • Version the Ghidra analysis profile so old snapshots are not reused under changed decompiler semantics.
  • Add a real Linux ELF importer regression. It verifies the ET_DYN case, read/write reference handling, the affected-byte range, and baseline/protected pseudocode. A full-RELRO -fno-plt caller checks that external GOT calls retain the same pseudocode after relocation blocks become volatile.
  • The Buildathon container workflow has been moved into follow-up PR #6912, leaving this PR focused on the Ghidra relocation fix.

Contract and boundary impact

  • Semantic owner and earliest changed stage: Ghidra bridge memory semantics immediately before decompiler initialization.
  • Contribution scope fit: existing-provider bug fix; the Buildathon container workflow is isolated in follow-up PR #6912.
  • CLI and MCP/tool-catalog contract: no schema or operation changes; the analysis profile digest changes intentionally.
  • Provider, bridge, target-format, or platform compatibility: ELF ET_DYN and executable relocations are eligible; ET_REL object files and other Ghidra programs still marked relocatable are skipped.
  • Evidence, artifact, provenance, or reconstruction contract: only read references to bytes affected by a relocation add the loader-value limitation. Source FileBytes remain unchanged.
  • Target selection, authority, upstream behavior, and cleanup details: the fixture is imported into an ephemeral Ghidra project; no target code is executed or modified. The bridge changes only the analysis database.
  • Generated metadata, package, or installation impact: no generated catalogs or package metadata changed.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process. (Ghidra only; no target process.)
  • Inject instrumentation or run scripts/code. (The Ghidra bridge and regression probe run.)
  • Change process memory, registers, files, or configuration. (Ghidra's ephemeral analysis database only.)
  • Contact network services. (The Ghidra analysis and regression lane run locally.)
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: importer-backed Ghidra probe for the dynamic ELF skip guard, relocation ranges, read/write references, full-RELRO GOT pseudocode stability, source bytes, and permissions; the CI scope classifier selects the change-triggered Linux Ghidra lane for the verifier and its fixtures.
  • Base reproduction or other evidence: the prior guard skipped the PR's own PIE fixture because Ghidra marks ET_DYN relocation tables relocatable. The probe now requires an ELF shared-object file type and a relocatable table, then verifies the production bridge makes the destination volatile.
  • User-visible CLI/MCP output: no CLI/MCP response shape changed.
  • Remaining proof gaps: this macOS host has no Ghidra installation or Linux ELF linker, so the native importer/decompiler lane has not run locally. It is wired into the change-selected Linux Ghidra CI lane and must pass with Ghidra 12.1.4 and its native decompiler before merge. GitHub CI and PR title are action_required and need maintainer approval; Greptile passed on the latest head after the test-path selection fix.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm ci with Node 24.22.1 and npm 11.16.0 — passed.
  • npm run check:fast — passed.
  • npm run format:check — passed.
  • vitest run src/ghidra/GhidraProvider.behavior.test.ts -t "commits exact provider, isolation, and resource semantics" — 1 passed.
  • npm run test:local -- tests/conformance/readmeConsistency.test.ts — 9 passed.
  • npm run test:focused -- tests/boundary/filesystem/ciChangeScope.test.ts — 279 passed, including verifier/fixture lane selection.
  • npm run verify:test-discovery — 2,178 test files discovered exactly once.
  • npm run build:cached — passed.
  • node --check scripts/verify-real-ghidra-loader-relocation.mjs and clang -fsyntax-only -Wall -Wextra tests/conformance/ghidra/loader-relocation.c tests/conformance/ghidra/loader-relocation-provider.c — passed.
  • git diff --check — passed.
  • npm run verify:ghidra:bridge-sources — unavailable because GHIDRA_INSTALL_DIR is not set; the host has no Ghidra installation.

Compatibility, safety, and release

  • Breaking changes or migration steps: none to CLI/MCP inputs or outputs; the profile digest intentionally invalidates stale Ghidra snapshots.
  • Real Hopper/Ghidra, browser, or OS coverage: focused Node/C checks passed; Linux Ghidra importer/decompiler validation remains pending as described above.
  • Package or release metadata impact: no package version or generated metadata change.
  • Security, privacy, process, or containment review: no target execution, injection, or target mutation; the Ghidra analysis database is ephemeral and original source bytes remain unchanged.

Author readiness

Human owner: @arslanbasharat-o-o

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved for the final Ghidra-only diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@arslanbasharat-o-o
arslanbasharat-o-o marked this pull request as ready for review October 15, 2026 18:12
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-15T18:13:39.443758Z 9670a68 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge; the previous CI selection issue is fixed.

Summary

Prevents Ghidra from treating loader-filled values in non-writable memory as known constants.

  • Ghidra treats loader-filled bytes in read-only memory as uncertain.

No new actionable issues were found in the changes since the previous review. Native Ghidra execution was not verified during this review. Whether another PR supersedes this one could not be checked because GitHub access was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Import target] --> B[Find eligible relocation destinations]
  B --> C[Mark containing blocks volatile]
  C --> D[Initialize decompiler]
  D --> E[Return pseudocode and read-specific uncertainty]
Loading

Reviews (10) · Last reviewed commit: "test(ci): select loader relocation Ghidr..." · Reviewed by Greptile

Comment thread Dockerfile Resolved
Comment thread .dockerignore Resolved
@RishTheFish21

RishTheFish21 commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

Ran this on Apple Silicon (macOS, Ghidra 12.1.4 with the native decompiler built), which should cover the decompiler gap mentioned above.

  • npm run verify:ghidra:loader-relocation passes with decompiler_verified: true, and pseudocode_does_not_use_file_constant passes.
  • Regression check on an ordinary arm64 Mach-O (main calling malloc/snprintf/puts/free): _main pseudocode is identical on main and this branch, and no loader-relocation limitation is added. So normal Mach-O output doesn't seem affected.

One concern with that decompiler check, though. The pseudocode it produced is return _rea_loader_value;, so the decompiler is reading through the real rea_loader_pointer in __DATA_CONST,__const, not the synthetic REA_RELRO block at 0x7000000000. The probe adds a reference from the first instruction to that block, but no instruction actually loads from it. The 0x11111111 it checks for comes from that block, which the code never reads, so I think pseudocode_does_not_use_file_constant would pass even without protectLoaderInitializedRelocations. Could the decompiler assertion use a read that really goes through the protected block, ideally a real ELF where the importer itself places a relocation in RELRO (closer to the musl R_MIPS_COPY case in #4177)? It would also help to show that the same read does fold to the file constant when the block isn't marked volatile.

I couldn't test ELF here; I can't link a normal ELF program on macOS. So whether whole-block volatility affects GOT calls in RELRO on ELF is still open. Separately, the Dockerfile / Makefile / README container workflow looks unrelated to #4177. Might be easier to review as its own PR.

@arslanbasharat-o-o

Copy link
Copy Markdown
Contributor Author

@morluto @RishTheFish21 Thanks for catching the flaw in the Mach-O probe. I pushed c56d336 (test(ghidra): verify ELF loader relocations) to replace the synthetic relocation path with a real Linux PIE ELF fixture.\n\nThe revised probe now:\n\n- requires an importer-created relocation at the real rea_loader_pointer symbol;\n- requires the actual rea_loader_reader instruction to have a read reference to that relocation destination;\n- requires the destination to be loaded, initialized, file-backed, and non-writable;\n- captures baseline pseudocode before protection and requires it to fold the file-backed 0x11111111 sentinel;\n- invokes the production protection method, then requires a fresh pseudocode result that no longer contains that constant;\n- checks the loader-value Evidence limitation, unchanged source FileBytes, and preserved permissions.\n\nThe lane is now explicitly Linux-only because it needs an ELF linker. I could not execute the real Ghidra lane on this macOS host, but the fixture/probe and local JS/C checks pass. The Apple Silicon result remains useful as ordinary Mach-O non-regression evidence, but is no longer being used as proof of the relocation decompiler behavior.\n\nOn the container files: I left them in this PR because this Buildathon submission explicitly requires the reproducible Dockerfile/Makefile/README workflow. They are isolated in commits 9670a68 and d48fc9d; I can split those into a separate PR if the project review process requires it.

@arslanbasharat-o-o

Copy link
Copy Markdown
Contributor Author

@morluto I pushed 8ecee31b2f4752c26c0d79d2a69aed012410b8f7 to fix a CI documentation issue: the reproducible-development section added an extra .nvmrc hyperlink that broke canonical/translated README link parity. The added reference now uses inline code, and the canonical link inventory matches the pre-PR README.

The new fork workflows currently report action_required. Could you approve the workflows so the updated head can be validated?

The earlier run also failed in browser cancellation and packet/signal cleanup tests, outside this PR's changed files. Please review those remaining CI results before considering a merge into main. I am keeping the branch available for review.

@CassieFox23 CassieFox23 left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TL;DR: Main still lacks this fix, and the Java change reads sensibly. No GitHub checks have run on this head, and the author says the new Linux Ghidra check has not been run. The PR also carries unrelated container files, and the body does not follow the template.

Edit (24 Oct): I re-read the new commits on 5ad9987. The follow-up is here.

Edit (22 Oct): I was wrong about line 930. It skips PIE files and shared objects too, not just object files. So the protection never runs on the PR's own fixture. See the follow-up.

Findings

Should fix

  • No workflow has run on this head. The CI, PR title and three "Real ..." runs all say action_required, so a maintainer has to approve them. The author asked for that on 19 Oct. Only PR readiness and Greptile report, and both pass. The last head that did run (0f3bbfb) failed Docs Generation, Source tests, Test shard (3/5) and Portable tests. The log shows documentationFacts.test.ts failing. The test name is "keeps translated readmes linked to canonical setup and tool details". Portable tests also fails PlaywrightBrowserScenarioProvider.test.ts ("cancels an active action and still closes the session"). The second file is not in this PR, and I did not check whether main fails it too. The head commit 8ecee31 changes the README link to fix the first one, but that is unproven until CI runs. I did not read the Source tests log or the tshark and sigrok failures.
  • The new regression has never run on Linux. The author says here that the macOS host could not run the ELF lane. So two claims are still unproven. The baseline pseudocode folds 0x11111111. The protected pseudocode does not. RishTheFish21 asked one more thing. Does marking a whole block volatile hide GOT calls in RELRO on ELF? Nobody has answered that. Someone with Linux and Ghidra 12.1.4 should run npm run verify:ghidra:loader-relocation. A before and after pseudocode of a GOT-indirect call in the same block would settle the second question. This part is unverified.
  • The body does not keep the template as written. All eight "Expected effects" boxes are ticked. That includes "Documentation or usability only" and "Not sure yet". The body itself says no target process is launched or attached. The three "For evidence-bearing changes" boxes are gone. The "Related issue is linked" line lost its ending about the reason for not linking one. "Tests added or updated" names only the profile string test. But the PR now also adds a real-Ghidra script, a Java probe and a C fixture. The "Validation performed" list (540 test files) reads as one state. The "Follow-up validation" section reads as a different state. Please bring the body up to date.
  • The PR carries a Dockerfile, a Makefile and a .dockerignore. It adds a README section too, titled "Reproducible development". And it adds a make deploy target that pushes images. None of that touches #4177. RishTheFish21 raised this on 15 Oct. The author answered that a Buildathon submission needs them. The author also said commits 9670a68 and d48fc9d can be split out. The head still has them, and the "one focused outcome" box is ticked. I would split them into their own PR so the Ghidra fix can be reviewed alone. This is the maintainers' call.

Nit

  • The new note says "This procedure reads ...". But the loop at lines 3538-3543 adds it for any reference from the instruction. It has no isRead() check. The probe's own readerReference does check isRead(). A write or an address-of reference would also say "reads".
  • The lookup in that loop matches only the relocation's first address. A reference to a later byte of the same relocated object would not add the note. The block is volatile either way, so the pseudocode stays protected. I did not check how Ghidra reports such references, so this part is unverified.

Looks good

  • Main does not have the fix. A search of main for setVolatile, loader_relocation and protectLoaderInitializedRelocations finds nothing, and #4177 is still open.
  • protectLoaderInitializedRelocations() runs at line 239, right before initializeDecompiler(). It skips relocatable object files (line 930). It only touches loaded blocks. They must be initialized and non-writable. It leaves permissions and source bytes alone. The Javadoc says plainly that volatility is per block and conservative.
  • Old snapshots cannot replay. The new loader_relocation_semantics key sits in the profile parameters. analysisProfilesEqual compares the profile digest. The digest covers those parameters. I read this in the code and did not run it.
  • The three Greptile threads are resolved and fixed on this head. They were about a mocked test, a root user in the Dockerfile, and missing .dockerignore entries. The fixes are USER node, the website and results excludes, and a real ELF probe. The probe now needs three things. They are an importer-made relocation, a real read reference to it and a non-writable loaded block. That is what RishTheFish21 asked for.
  • The Dockerfile's node:24.18.0 matches .nvmrc (24.18.0).
  • It merges cleanly with main (bea6b98). I extracted base, main and head for the seven files that both sides touch and ran a three-way merge on each. There were no conflicts. The files are ReaGhidraBridge.java, GhidraAnalysisProfile.ts, GhidraProvider.behavior.test.ts, package.json, README.md, docs/testing.md and tests/conformance/ghidra/README.md.

Not run

  • No build and no tests. This is a read-only review of the diff against main.
  • The Ghidra lane (verify:ghidra:loader-relocation), the Docker build and the Java compile were not run.
  • I did not read the Source tests, tshark or sigrok failure logs from the earlier head.

Thanks, arslanbasharat-o-o, for the fix, and for swapping the mocked test for a real ELF check after review. Thanks, RishTheFish21, for running the first version on macOS.

Test setup

🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

@RishTheFish21

Copy link
Copy Markdown
Contributor

I tried to answer my own RELRO/GOT question on macOS by cross-linking Linux ELFs with clang and lld (no Linux host needed, since the fixture is -nostdlib). I found something that comes before it: at this head, the protection doesn't seem to run for PIE or shared objects at all, including the PR's own fixture.

Repro (macOS arm64, Ghidra 12.1.4, Homebrew LLD 23.1.4, this PR checked out and built with npm run build:cached):

clang --target=x86_64-linux-gnu -O0 -fPIE -pie -nostdlib -fuse-ld=lld -Wl,-z,relro,-z,now -Wl,-e,rea_loader_start tests/conformance/ghidra/loader-relocation.c -o loader.elf
node scripts/rea.mjs function loader.elf rea_loader_reader --provider ghidra --json

The layout is the one the lane expects. llvm-readelf shows .data.rel.ro inside GNU_RELRO, with R_X86_64_RELATIVE at 0x2358 for rea_loader_pointer. The run used this PR's code: the evidence profile carries loader_relocation_semantics: "volatile-read-only-relocation-blocks-v1". The result still folds:

undefined4 rea_loader_reader(void)
{
  return 0x11111111;
}

No "non-writable block" limitation is emitted.

Likely cause: the first line of protectLoaderInitializedRelocations():

if (currentProgram.getRelocationTable().isRelocatable()) return;

I think this is meant to skip relocatable object files. But RelocationTable.isRelocatable() reads the program's Relocatable property, and Ghidra's ELF importer sets that property to true for ET_REL, ET_DYN and ET_CORE (ElfProgramBuilder, the switch (elf.e_type()) before props.setBoolean(RelocationTable.RELOCATABLE_PROP_NAME, isRelocatable)). ElfHeader.isRelocatable() is the ET_REL-only check. So every PIE executable and shared library returns early, and the fixture built with -fPIE -pie is ET_DYN. Only a non-PIE ET_EXEC would reach the protection. I read this in Ghidra's current source and didn't step through it on 12.1.4, but it matches all three of my runs. A check of the ELF File Type program property ("relocatable"), or of the ELF header type, would skip only .o files.

On my earlier question (GOT calls in RELRO): this still needs answering once the early return is fixed. Ghidra applies relocations first and then marks the whole PT_GNU_RELRO range read-only (adjustReadOnlyMemoryRegions). With -z now, that range includes .got, which holds a GLOB_DAT/JUMP_SLOT relocation per slot. So .got would be one of the blocks made volatile. A quick case to check:

extern int rea_external_value;
extern int rea_external(int);
int rea_got_caller(int v) { return rea_external(v) + rea_external_value; }

Build it -fno-plt, as a full-RELRO PIE against a small shared library. Today it decompiles to rea_external(v) + _rea_external_value with and without this PR, because the protection never runs. It would be worth comparing again

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: I read Ghidra 12.1.4's source and this PR's code. All of it agrees with RishTheFish21. The early return skips PIE files and shared objects. So the protection does not run for the PR's own PIE fixture. I ran nothing, and my first review was wrong to say that line only skips object files.

Thanks, RishTheFish21, for the repro and for naming the exact line.

What the source says

  • The early return is at line 930 of ReaGhidraBridge.java at head 8ecee31: if (currentProgram.getRelocationTable().isRelocatable()) return;
  • isRelocatable() reads the program's Relocatable property. It guesses from the relocation count only if that property is missing (source).
  • The ELF importer sets that property to true for ET_REL, ET_DYN and ET_CORE. It sets it to false for ET_EXEC (importer source). A file can have relocations and still not be relocatable. Ghidra's own doc comment gives "ELF executables" as the example.
  • So only a non-PIE ET_EXEC reaches the protection. A different method is ElfHeader.isRelocatable(). It is the ET_REL-only check (ElfHeader source).
  • The same file stores the file type as a string. It says relocatable only for ET_REL (line 440 of the same ElfProgramBuilder.java). A check on that, as RishTheFish21 suggests, would skip only object files.

What the PR's own files say

  • The fixture is built with -fPIE -pie (the build script). A -pie link makes an ET_DYN file, which is general knowledge. I did not compile it.
  • The probe requires !currentProgram.getRelocationTable().isRelocatable() on that fixture (the probe). By the Ghidra source above, that check should fail for an ET_DYN fixture. It should fail before the probe reaches the protection call.
  • The PR body lists no run of verify:ghidra:loader-relocation, so I think the probe has not run against the fixture. That is unverified.

Not run

  • I ran nothing: no build, no Ghidra, no compiler. This is a static read of source at the Ghidra_12.1.4_build tag and of this head.
  • I did not check RishTheFish21's three macOS runs, and I did not look at the GOT-in-RELRO question.

🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

Comment thread Dockerfile Resolved
Comment thread Makefile Resolved
Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
@greptile-apps

greptile-apps Bot commented Oct 23, 2026

Copy link
Copy Markdown
Contributor

Want your agent to iterate on Greptile's feedback? Try greploops.

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: I read the new commits on 5ad9987, and most of my findings are now fixed in the code. The check now lets PIE and shared-object files through, and the container files are gone. GitHub has still run no workflow on this head, so the new Linux Ghidra check has no result yet.

My finding Now What I read
The early return skipped PIE files and shared objects addressed (read) The guard now also reads Ghidra's ELF File Type and lets shared object through. Ghidra 12.1.4 sets that value for ET_DYN. The probe now requires it on the fixture.
The new Linux Ghidra check had never run needs a run It is now part of the Linux Ghidra CI lane. That lane has not run yet (see the next row).
GOT calls in RELRO (RishTheFish21's question) needs a run The probe now compares the pseudocode of one -fno-plt GOT caller before and after the change. I can read the check. I cannot read its result.
No workflow had run on the head not addressed CI and PR title still say action_required. A maintainer has to approve the run, because this PR comes from a fork. Only the author-declaration checks and Greptile report, and all of those pass.
Container files in the PR addressed (read) The Dockerfile, Makefile, .dockerignore and README section are gone from the diff against main. The author moved them to draft PR #6912.
Nit: the note said "reads" with no read check addressed (read) The loop now skips references that are not reads.
Nit: the lookup matched only the first byte addressed (read) The lookup now covers the relocation's whole length. The probe checks the last byte.
PR body: evidence boxes, effects boxes, validation list addressed (read) The three evidence boxes are back. "Documentation only" and "Not sure yet" are no longer ticked. There is one validation list.
PR body: the repo template's own wording not addressed Three template lines are shortened or reworded, and the "Follow the contribution scope" paragraph is gone.

All 7 review threads are resolved. A three-way merge of the 9 files that both this PR and main (d24ad4f) changed has no conflicts.

Not run

  • Nothing was built or run this time: no Ghidra, no compiler, no tests. This is a read of the diff, of Ghidra 12.1.4's source, and of GitHub's check list.
  • Whether the new probe passes on Linux with Ghidra 12.1.4. This covers both of its pseudocode comparisons.
  • Whether the fixture's extern data (rea_external_value) ends up in a GOT slot in a read-only block. The probe's got_relocations_are_volatile check needs that. The compiler and linker decide it, and I did not compile the fixture.
  • What marking a whole read-only block volatile does to other functions in a PIE. The probe covers one reader and one GOT caller.

Thanks, arslanbasharat-o-o, for the quick fixes, and for the move of the container files to a PR of their own. Thanks, RishTheFish21, for the GOT question.

What I read
  • The guard is in ReaGhidraBridge.java, lines 939-945. It returns early only when the relocation table is relocatable and the file type is not shared object.
  • Ghidra's importer sets the file type per ELF type (source). ET_REL gives relocatable, ET_EXEC gives executable, ET_DYN gives shared object and ET_CORE gives core. ET_REL, ET_DYN and ET_CORE are marked relocatable. ET_EXEC is not. So the guard still skips object files and core files. It now protects PIE files and shared objects.
  • The importer makes the PT_GNU_RELRO range read-only once it has applied the relocations (source). So a RELRO .got or .data.rel.ro block is non-writable before the bridge runs. That is what the guard looks for.
  • The probe requires these four things:
  • The ghidra_bridge lane in ci.yml calls ghidra-bridge-sources.yml, which now runs npm run verify:ghidra:loader-relocation.
Test setup

🤖 Written with Claude Code (Sonnet 5.5, verified by Opus 5.5), posted with my OK 🦊

@Rinkia

Rinkia commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

TL;DR: Fixes the usign case from #4177. Thanks, arslanbasharat-o-o.

Build: this PR's head 5ad9987b0 (base b7ebccf8d), npm ci --ignore-scripts && npm run compile on Linux, Node 24.22.1, Ghidra 12.1.4.

Target: usr/bin/usign from OpenWrt 24.10.8 ath79-generic-tplink_archer-c7-v5-squashfs-sysupgrade.bin (image sha256 feeab4e3…d296003, signed release sha256sums). Extracted with unsquashfs; the file sha256 is 8e3fb886…e7e1, the same as in #4177.

rea decompile usign 0x403c20 --provider ghidra, all four stdio calls in the function:

6.8.0 This PR
fwrite("Cannot open message file\n",1,0x19, …) (FILE *)0x0 pFVar1
fwrite(__ptr,1,…, …) (FILE *)0x0 __s
fwrite(&DAT_00404498,1,3, …) (FILE *)0x0 pFVar1
uncertainty in the result none volatile-read-only-relocation-blocks-v1, "relocation at 0x41ff80 in non-writable block segment_5, which contains the relocation for stderr"

So the copy-relocated stderr in RELRO is no longer folded to its on-file zero, and the evidence says why. Not checked: other binaries with RELRO copy relocations, or any effect on decompilation elsewhere.

gensokyo-dev added a commit that referenced this pull request Nov 14, 2026
inspectGhidraInstallation became async on main after #4198's base, so the
verifier asserted on a pending Promise. Also wait for provider output to
close before reading it, like the sibling Ghidra verifiers, and keep the
workflow reference inside the docs site.

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
N0zoM1z0 added a commit that referenced this pull request Nov 14, 2026
* fix(ghidra): prevent loader relocations from constant folding

Ghidra imports loader relocation destinations with their file bytes. A
destination in a non-writable loaded block can be populated by the
runtime loader instead, for example a copy-relocated musl `stderr` in
RELRO, so the decompiler folded the on-disk zero and showed
`fprintf(NULL, ...)`.

Before initializing the decompiler, mark each loaded, initialized,
non-writable block containing a relocation destination volatile in the
ephemeral database, and add a limitation to procedures that read such a
destination. ELF shared objects and PIEs are included; relocatable
objects and core files are not. Permissions and source FileBytes are
unchanged.

Sessions without database-mutation authority (Windows P0 and existing
caller projects) record the limitation but do not mark blocks volatile,
and the analysis profile versions the two behaviors separately.

A real Linux Ghidra ELF probe runs in the Ghidra bridge CI lane.

Fixes #4177

Squashed from #4198 and rebased onto main. Rebase adaptations: the
read-only gate, the verifier renamed to verify-ghidra-loader-relocation
so it stays out of the manual-verifier glob, docs moved to
docs/testing-lanes.md and docs/providers/ghidra-provider.md.

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ghidra): await installation inspection in the relocation verifier

inspectGhidraInstallation became async on main after #4198's base, so the
verifier asserted on a pending Promise. Also wait for provider output to
close before reading it, like the sibling Ghidra verifiers, and keep the
workflow reference inside the docs site.

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ghidra): address relocation review findings

- Version the existing-project analysis profile with the read-only
  relocation semantics, since those sessions now add the limitation.
- Inspect the installation through the verifier helper that owns the
  file-reader resources.
- Build the fixture with -fPIC: with -fPIE, GCC 12 emits a copy
  relocation of rea_external_value into writable .bss, so the probe's
  GOT check could not hold.
- Run probe cleanup through withVerifierCleanup so a cleanup failure
  does not hide the probe failure, and keep the workspace when owned
  Ghidra cleanup is incomplete.
- Link the workflow with a full GitHub URL, per the docs guide.

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(ghidra): reach the external data through the GOT with a weak extern

Building the whole fixture with -fPIC also turned the reader's direct
load of rea_loader_pointer into a GOT-relaxed lea plus two loads, and
the real-Ghidra lane then reported that the baseline no longer folds
the file constant. Keep -fPIE and declare only rea_external_value weak:
GCC and clang must reach a possibly absent symbol through a GOT entry,
which lands as R_X86_64_GLOB_DAT inside GNU_RELRO (checked with readelf
for GCC 12.2 and clang/lld).

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(ghidra): protect only relocations Ghidra could not apply

Running the real-Ghidra lane locally (Ghidra 12.1.4, JDK 21, GCC 12)
showed that marking every non-writable block that holds a relocation
volatile also marks full-RELRO .got. External calls then decompile as
opaque pointer calls (`(*pcVar2)(param_1)` through
`PTR_rea_external_...` instead of `rea_external(param_1)`), which the
probe's GOT-stability check caught.

Ghidra applies GLOB_DAT and RELATIVE relocations, so those bytes already
hold the loader's value and folding them is correct. The #4177 case is
a copy relocation, which Ghidra imports as UNSUPPORTED with the file's
zero in place. Protect only destinations whose relocation status is not
APPLIED or APPLIED_OTHER.

The fixture now reads a provider `const` object that the linker copies
into .data.rel.ro, the #4177 shape. The probe requires that relocation
to be unapplied and requires applied GOT relocations to stay
non-volatile. Ghidra 12.1.4 already shows this x86-64 read by name
without protection, so the probe records whether the baseline folds and
compares before and after only when it does. The profile value becomes
volatile-unapplied-relocation-blocks-v1.

Co-Authored-By: gensokyo-dev <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Arslan Basharat <[email protected]>
Co-authored-by: gensokyo-dev <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
@N0zoM1z0

Copy link
Copy Markdown
Collaborator

Thanks, arslanbasharat-o-o. This landed in #10483, squashed with your authorship kept and rebased onto main. Running the real-Ghidra lane showed that protecting every relocation also made full-RELRO .got volatile, so external calls lost their names. The merged version protects only relocations Ghidra could not apply (the copy-relocation case from #4177), and read-only sessions record only the limitation. Closing in favor of that merge.

@N0zoM1z0 N0zoM1z0 closed this Nov 14, 2026
@morluto morluto added bug Something isn't working provider: ghidra Analysis provider / engine: ghidra labels Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working provider: ghidra Analysis provider / engine: ghidra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Ghidra pseudocode shows musl stdio streams as NULL: copy-relocated stderr in RELRO is folded to its on-file zero

6 participants