Skip to content

feat(native): recover ELF function ranges from unwind tables - #9585

Merged
morluto merged 11 commits into
morluto:mainfrom
mvanhorn:fix/elf-unwind-function-ranges
Nov 9, 2026
Merged

morluto merged 11 commits into
morluto:mainfrom
mvanhorn:fix/elf-unwind-function-ranges

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A stripped ELF binary has no symbol table, but it almost always keeps .eh_frame so exceptions and backtraces work. Every FDE in that table names the start and end of one function. That makes it the most reliable function-boundary map available without a disassembler, and it survives stripping. REA had no way to read it.

This adds inspect_elf_unwind_ranges (CLI inspect-elf-unwind-ranges). It decodes .eh_frame and .eh_frame_hdr from one local ELF32 or ELF64 image and lists the function ranges they name, with the CIE each range uses, its LSDA and personality, and an exact symbol name when one exists. It also checks whether the header's binary-search table agrees with the FDEs. No issue is linked. This is a proposed new read-only capability.

Problem and expected behavior

Use case: an analyst has a stripped Linux or Android binary and wants its function boundaries before choosing what to decompile, without loading it into a disassembler provider.

Observable outcome:

  • ranges is a paged list of FDEs with start, end, size, the containing SHF_ALLOC section, an exact symbol when a symbol starts at that address, the CIE index, LSDA and personality. cies holds only the CIEs the page's ranges use, and coverage.total_cies counts all of them.
  • eh_frame_hdr reports the header's version, encodings and FDE count. coverage.eh_frame_hdr_agreement is agree, disagree or unavailable.
  • .eh_frame is found through section headers, or through PT_GNU_EH_FRAME when the image has none. A table located only through the header is bounded by the header's search table, or by the first undecodable record, so trailing data is never reported as ranges.
  • CIEs with unknown augmentation letters, discarded FDEs (zero initial location), unresolved datarel bases and duplicate or truncated tables are reported as limitations with coverage.status incomplete, never as silent absence. So are FDEs whose initial location is indirect, and duplicate PT_GNU_EH_FRAME declarations. A CIE with an unrecognized augmentation ends a header-located scan that has no search table.

Change and scope

Decoding lives in src/native/elf/ElfUnwindTables.ts, with the report schema in src/domain/native/elfUnwindRanges.ts and a small address-interval index in src/native/elf/ElfIntervalIndex.ts. Program headers come from the existing src/native/metadata/NativeSectionDirectory.ts. That shared directory now also keeps PT_GNU_EH_FRAME entries, and its other callers pick out only the entry types they already use. ElfUnwindRangesService.ts checks the provider's output for internal consistency before returning Evidence.

The tool is registered through the existing binary-diagnostics composition, CLI command table, capability declarations and MCP server, like the other native inspection tools. Docs: a new docs/guides/native/elf-unwind-ranges.md guide with nav and index entries, a spec under docs/specs/native/elf-unwind-ranges/, and lines in the authored skill reference, which bumps skillVersion in src/generatedPackageMetadata.ts. scripts/verify-elf-unwind-ranges.mjs and the verify:elf:unwind-ranges package script add an opt-in real-toolchain check, which is not part of the default checks. It runs every child process through the repository's owned command runner and removes its temporary directory only after they close.

Bounded by default: the file is limited by max_file_bytes (64 MiB, 512 MiB max), max_ranges defaults to 8192 (65536 max) for CIEs and FDEs separately, a page returns at most 4096 ranges, and symbol lookup stops after 65536 entries. Symbol names are kept only for FDE starts and decoded only for the returned page, within a 16 MiB text allowance.

Not included: decoding .debug_frame, evaluating CFA programs, following indirect pointers, or applying relocations in relocatable objects.

Follow the contribution scope.
Unresolved scope, authority, side effects, or required verification block
integration. Link the required maintainer scope decision for new providers or
capabilities involving target execution, injection, mutation, or protection
recovery; ordinary fixes within existing boundaries may state "not applicable".
Draft PRs may leave the scope decision pending and the readiness and merge checklists
unchecked. Maintainers can help resolve open questions.

Contract and boundary impact

  • Semantic owner and earliest changed stage: new unwind-table decoder in src/native/elf/ and report schema in src/domain/native/, exposed through the binary-diagnostics service. The shared section directory gains PT_GNU_EH_FRAME entries.
  • Contribution scope fit and linked maintainer decision: read-only inspection of one local file the caller selected, with no target execution, injection, mutation or protection recovery. Not applicable as a required decision. Whether REA wants this tool is for maintainers to judge, and I have not assumed approval.
  • CLI and MCP/tool-catalog contract: additive. New inspect-elf-unwind-ranges command and inspect_elf_unwind_ranges tool. The MCP input requires an absolute path, matching the other local path tools.
  • Provider, bridge, target-format, or platform compatibility: no external provider or bridge. Pure byte parsing on any host. Addresses wrap at the ELF class width, as libgcc's pointer arithmetic does.
  • Evidence, artifact, provenance, or reconstruction contract: new elf-unwind-ranges normalized result. Symbol names, section names and augmentation strings are marked as target-derived and untrusted. Evidence locations are bounded by the page.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): uses the existing stable artifact read. No retained resources.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): authored skill reference lines with the matching skillVersion bump, the new guide and its nav and index entries, the spec, and one opt-in package script. No build output is committed. The ## Native entry in docs/specs/README.md and the skillVersion line may conflict textually with my other open native PRs; the changes are independent.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • 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: decoder tests in src/native/elf/ElfUnwindTables.test.ts (fixtures in ElfUnwindTables.fixture.ts) covering ELF64 and ELF32 address wraparound, 64-bit extended lengths, PC-relative, data-relative and indirect pointers, unknown augmentations, discarded FDEs and zero LSDA pointers, header agreement and disagreement, PT_GNU_EH_FRAME-only images, header-located tables with and without a terminator, truncated and out-of-file sections, budgets, cancellation and CIE paging. Also interval-index, schema, service and section-directory tests, a filesystem boundary test, an MCP boundary test and a CLI acceptance test.
  • Base reproduction or other evidence: on main there is no command that reads unwind tables. On this commit, scripts/verify-elf-unwind-ranges.mjs compiles a small C++ program with exceptions using zig c++ -target x86_64-linux-musl -O0 -g (statically linked, so libc and libc++ FDEs are included), strips a copy with llvm-strip --strip-all, and pages through inspect-elf-unwind-ranges on the stripped copy. It then compares every FDE start with the pc= starts that llvm-dwarfdump --eh-frame lists for the unstripped build. The two sets are identical, with no missing or extra starts: {"compiler":"zig","readelf":"llvm-dwarfdump","fde_starts":1585}.
  • User-visible CLI/MCP output (if applicable): the same program built by hand and stripped with llvm-strip --strip-all, then inspected with inspect-elf-unwind-ranges --json --limit 4096 --max-ranges 65536. The stripped file has no symbols, yet may_throw(int) and main come back with the exact pc= ranges llvm-dwarfdump --eh-frame prints for the unstripped build (0x10319a0..0x1031a93 and 0x1031aa0..0x1031b0a). The personality address 0x10a2130 is __gxx_personality_v0 in the unstripped symbol table. Summarized:
{
  "format": "elf64",
  "eh_frame": { "status": "present", "source": "section" },
  "eh_frame_hdr": { "status": "present", "version": 1, "fde_count": 1585, "table_entries": 1585 },
  "coverage": {
    "status": "complete",
    "total_ranges": 1585,
    "total_cies": 3,
    "eh_frame_hdr_agreement": "agree",
    "examined_records": 1588
  },
  "ranges": [
    {
      "index": 1540,
      "start": "0x10319a0",
      "end": "0x1031a93",
      "size": "243",
      "section": { "text": ".text", "trust": "untrusted" },
      "symbol": null,
      "cie_index": 1,
      "lsda": { "address": "0x1000238", "indirect": false },
      "personality": { "address": "0x10a2130", "indirect": false }
    }
  ]
}
  • Remaining proof gaps: macOS host only, with one zig-built x86-64 binary. GNU readelf, GCC output, ELF32, Android and PT_GNU_EH_FRAME-only images are covered by synthetic fixtures only, not real toolchains. Big-endian images are not covered by a test. The verifier is opt-in and not run in CI.

For boundary fixes, identify the applicable boundary regressions
and lifecycle regressions
covered by the evidence above, and explain relevant gaps.

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

  • Latest review follow-up: 62 ELF unwind source tests and check:fast passed. Validation uses constructed artifacts; no real-target/provider verification was run for this follow-up.

  • Header address mapping: npm run test:local -- src/native/elf/ElfUnwindTables.test.ts passed (60 tests), and npm run check:fast passed. A synthetic non-allocated header mapped by PT_LOAD failed before the fix and now preserves header agreement; the reported real binary probe was not repeated.

  • Unwind pointer bases: npm run check:fast passed and npm run test:local -- src/native/elf/ElfUnwindTables.test.ts passed (59 tests). A synthetic non-allocated GOT regression failed before the fix and now reports incomplete coverage; .text fallback likewise requires an allocated section.

Run on this commit on macOS with Node 24.22.1:

  • npx --no-install vitest run on the twelve changed test files: 300 passed.
  • scripts/verify-elf-unwind-ranges.mjs with zig and llvm-dwarfdump: 1585 FDE starts, identical sets.

Compatibility, safety, and release

  • Breaking changes or migration steps: none. New command and tool only. The section directory gains an entry type its existing callers do not read.
  • Real disassembler, browser, or OS coverage: none needed. Real zig output compared with llvm-dwarfdump, on macOS.
  • Package or release metadata impact: one opt-in verify:elf:unwind-ranges script and the skillVersion bump. No new dependency.
  • Security, privacy, process, or containment review: the image is never executed. Record counts, search-table rows, pages, symbol scans and header-located scans are bounded, indirect pointers are not followed, and target-derived strings are marked untrusted.

Author readiness

Human owner: @mvanhorn

  • 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, and any required maintainer scope decision covers the final 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.

AI was used for assistance.

inspect_elf_unwind_ranges and inspect-elf-unwind-ranges read .eh_frame
and .eh_frame_hdr from one local ELF32 or ELF64 image and list the
function ranges its FDEs name, with CIE facts, LSDA and personality,
the containing section and an exact symbol where one starts at the
address. Nothing is executed and no disassembler is needed. Pointer
encodings follow the DW_EH_PE rules with raw zero as null, discarded
FDEs are counted and skipped, the .eh_frame_hdr search table is
compared with the decoded FDEs, and record, row and symbol budgets are
bounded. verify:elf:unwind-ranges compares the reported starts with
llvm-dwarfdump or readelf on a compiled C++ program.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-09T13:58:40.249945Z 03c4c3e New commits
ℹ️ 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 Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

[Medium impact] The change reaches people inspecting local ELF files through both command-line and MCP workflows.

Do not merge until an unloaded SHT_DYNAMIC section can no longer shift reported function addresses.

Findings

  1. P1 Unloaded tables shift function addresses ▶
  2. P2 Padded values drop valid ranges ▶
  3. P2 Thumb function names disappear ▶
  4. P2 Padding makes coverage look incomplete ▶
Fix with agent prompt
### Issue 1
src/native/elf/ElfUnwindTables.ts:undefined-1138
`resolveGotBase` accepts a file-backed `SHT_DYNAMIC` section without checking `SHF_ALLOC`. When no `PT_DYNAMIC` exists, an unloaded `.dynamic` section can supply `DT_PLTGOT` and override a valid allocated GOT. Affected `DW_EH_PE_datarel` ranges then point at the wrong addresses without making coverage incomplete.

Require `SHF_ALLOC` for this fallback too; otherwise leave the base unresolved.

```suggestion
      .filter(
        (section) =>
          section.type === SHT_DYNAMIC &&
          section.file_backed &&
          (section.flags & SHF_ALLOC) !== 0n,
      )
```

### Issue 2
src/native/elf/ElfUnwindTables.ts:487-489
`readLeb` loses the sign of a ten-byte SLEB128 value. The valid padded encoding `fc ff ff ff ff ff ff ff ff 7f` represents `-4`, but this code returns `2^70 - 4` because `shift` is already 70. When a CIE uses this encoding for `data_alignment`, the value fails `safeInt`. The parser then drops that CIE and all its function ranges, leaving incomplete coverage for valid input.

Sign-extend the completed value and check that its high bits fit the supported width.

### Issue 3
src/native/elf/ElfUnwindTables.ts:1875-1881
`scanSymbols` compares raw `symbol.value` with FDE starts. In an ARM ELF, a Thumb function symbol has its low bit set, while its code address is even. A Thumb function covered by a DWARF FDE therefore loses its exact symbol name, and the symbol coverage counts are wrong.

Clear the Thumb bit for function-address lookup, as `AndroidJniLibrary` already does.

### Issue 4
src/native/elf/ElfUnwindTables.ts:816-819
The parser requires another four-byte length word before checking `tableBound`. If the last table-named FDE leaves only one to three bytes in its `PT_LOAD`, those unrelated trailing bytes mark `.eh_frame` incomplete. With four trailing bytes, the same scan correctly stops at `tableBound`.

Check the table bound before reading the next record so bytes outside the selected table cannot change its coverage.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds read-only ELF unwind inspection through the CLI and MCP, with paged function ranges, header comparison, symbol lookup, docs and an opt-in toolchain verifier.

  • ELF unwind records now give readers paged function ranges and coverage details.
  • Callers can request ELF unwind ranges through the CLI or MCP.
  • An opt-in check compares recovered ELF ranges with a toolchain’s frame dump.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  CLI["CLI command"] --> Service["ElfUnwindRangesService"]
  MCP["MCP tool"] --> Service
  Service --> Provider["ElfUnwindRangesProvider"]
  Provider --> Read["Stable local-file read"]
  Read --> Decode["Decode CIEs, FDEs and header"]
  Decode --> Page["Resolve names and select page"]
  Page --> Check["Check report consistency"]
  Check --> Evidence["Evidence with identity and coverage"]
Loading

Reviews (5) · Last reviewed commit: "chore: merge main and preserve native do..." · Reviewed by Greptile

Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread scripts/verify-elf-unwind-ranges.mjs Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3a06c96bc7

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Skip FDEs whose initial location is indirect and do not locate
.eh_frame through an indirect eh_frame_ptr, since pointer slots are
not functions. Stop an unbounded header-located scan at a CIE with an
unrecognized augmentation, report ignored duplicate PT_GNU_EH_FRAME
headers as incomplete coverage, and accept a null personality stored
under an indirect encoding.

Keep only symbols at decoded FDE starts, cache name observations per
string-table offset, and decode names only for the returned page under
a fixed 16 MiB text allowance, so repeated or long names no longer
grow memory with the symbol count.
Launch probes, compiler drivers, the stripper, the frame dump and the
inspection through createVerifierCommands, as verify-binary-hardening
does, so a timeout or interrupt stops the whole tree. The temporary
directory is removed only after the owned commands have closed.
The documentation guide assigns analyst workflows to docs/guides/<domain>/.
Move the guide there, place its navigation and directory entries in the
Native binaries group, and update links from the docs index, CLI guide,
spec and authored skill. The public /elf-unwind-ranges route is unchanged.
Comment thread src/native/elf/ElfUnwindTables.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1f9ca35425

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
…t tables

Throw a dedicated failure when a page's symbol names exceed the 16 MiB
text allowance, and map it to a resource error that tells the caller
to request a smaller limit rather than raise max_ranges.

Read a CIE augmentation with one bounded NUL search and keep it as a
byte view, decoded only for returned CIEs, so a long augmentation is
never built up character by character.

Leave an .eh_frame_hdr search table with an indirect encoding unread:
the header is incomplete, the comparison is unavailable, and the table
no longer bounds a header-located .eh_frame scan.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 66568f59b9

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Leave a non-zero .eh_frame_hdr FDE count under an indirect encoding
unresolved, since it is the address of a slot that is not followed, and
mark the header incomplete without reading the table.

Treat a DW_EH_PE_omit table encoding as an omitted search table before
testing the indirect bit, so a header that declares a count without a
table stays present with complete coverage, and accept that form in
output validation.

Match STT_GNU_IFUNC symbols at exact FDE starts after function symbols,
with a limitation that the name is the resolver, not the implementation
it selects at run time.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 23d841d2a8

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6d1446ea16

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 346e14a773

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/native/elf/ElfUnwindTables.ts Resolved
Comment thread src/native/elf/ElfUnwindTables.ts Resolved
@morluto
morluto enabled auto-merge (squash) November 9, 2026 13:41
@morluto
morluto merged commit 43f06eb into morluto:main Nov 9, 2026
1 check passed

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 03c4c3e7e6

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if (owner !== undefined) address += owner.address;
}
// Only a symbol at a decoded FDE start can name a range.
if (stringBytes === null || !wanted.has(address)) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Normalize Thumb function values before matching FDE starts

For ARM32 Thumb ELFs, STT_FUNC.st_value has bit 0 set, whereas the FDE starts at the even code address. In a decoder-only probe on a Clang-built ARMv7 shared library, alpha is exported at 0x1021d and its FDE starts at 0x1021c; this membership check therefore selects $t from .symtab, or returns no symbol when only .dynsym remains, instead of alpha, and miscounts symbol coverage. Normalize the Thumb tag in the function-symbol lookup key, as src/native/android/AndroidJniLibrary.ts:182 already does for code lookup, without changing the stored symbol value's semantics elsewhere.

Useful? React with 👍 / 👎.

Comment on lines +1871 to +1874
symbol.section_index >= SHN_LORESERVE &&
symbol.section_index !== SHN_ABS
)
continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve SHN_XINDEX before discarding reserved section indices

For ELF symbols using SHN_XINDEX (0xffff), this filter discards defined functions even when their actual section indices are available in the companion SHT_SYMTAB_SHNDX table. A decoder-only 4.2 MB fixture with 65,554 sections still returns both FDEs, but loses alpha at the exact FDE start 0x400100 and reports zero matched symbols with complete coverage; readelf resolves alpha to section 65,552. Resolve the extended index before filtering, or explicitly mark symbol lookup incomplete when it cannot be resolved, rather than reporting those names as absent.

AGENTS.md reference: AGENTS.md:L21-L21

Useful? React with 👍 / 👎.

? undefined
: { offset: dynamicProgram.offset, fileSize: dynamicProgram.size }) ??
directory.sections
.filter((section) => section.type === SHT_DYNAMIC && section.file_backed)

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.

P1 Unloaded tables shift function addresses

resolveGotBase accepts a file-backed SHT_DYNAMIC section without checking SHF_ALLOC. When no PT_DYNAMIC exists, an unloaded .dynamic section can supply DT_PLTGOT and override a valid allocated GOT. Affected DW_EH_PE_datarel ranges then point at the wrong addresses without making coverage incomplete.

Require SHF_ALLOC for this fallback too; otherwise leave the base unresolved.

Suggested change
.filter((section) => section.type === SHT_DYNAMIC && section.file_backed)
.filter(
(section) =>
section.type === SHT_DYNAMIC &&
section.file_backed &&
(section.flags & SHF_ALLOC) !== 0n,
)
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/elf/ElfUnwindTables.ts
Line: 1138

Comment:
**Unloaded tables shift function addresses**

`resolveGotBase` accepts a file-backed `SHT_DYNAMIC` section without checking `SHF_ALLOC`. When no `PT_DYNAMIC` exists, an unloaded `.dynamic` section can supply `DT_PLTGOT` and override a valid allocated GOT. Affected `DW_EH_PE_datarel` ranges then point at the wrong addresses without making coverage incomplete.

Require `SHF_ALLOC` for this fallback too; otherwise leave the base unresolved.

```suggestion
      .filter(
        (section) =>
          section.type === SHT_DYNAMIC &&
          section.file_backed &&
          (section.flags & SHF_ALLOC) !== 0n,
      )
```

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +1875 to +1881
let address = symbol.value;
if (directory.elf_type === 1 && symbol.section_index !== SHN_ABS) {
const owner = byIndex.get(symbol.section_index);
if (owner !== undefined) address += owner.address;
}
// Only a symbol at a decoded FDE start can name a range.
if (stringBytes === null || !wanted.has(address)) continue;

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.

P2 Thumb function names disappear

scanSymbols compares raw symbol.value with FDE starts. In an ARM ELF, a Thumb function symbol has its low bit set, while its code address is even. A Thumb function covered by a DWARF FDE therefore loses its exact symbol name, and the symbol coverage counts are wrong.

Clear the Thumb bit for function-address lookup, as AndroidJniLibrary already does.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/elf/ElfUnwindTables.ts
Line: 1875-1881

Comment:
**Thumb function names disappear**

`scanSymbols` compares raw `symbol.value` with FDE starts. In an ARM ELF, a Thumb function symbol has its low bit set, while its code address is even. A Thumb function covered by a DWARF FDE therefore loses its exact symbol name, and the symbol coverage counts are wrong.

Clear the Thumb bit for function-address lookup, as `AndroidJniLibrary` already does.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +816 to +819
if (cursor + 4 > extent) {
fail(".eh_frame ended inside a record.");
frameStatus = "incomplete";
break;

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.

P2 Padding makes coverage look incomplete

The parser requires another four-byte length word before checking tableBound. If the last table-named FDE leaves only one to three bytes in its PT_LOAD, those unrelated trailing bytes mark .eh_frame incomplete. With four trailing bytes, the same scan correctly stops at tableBound.

Check the table bound before reading the next record so bytes outside the selected table cannot change its coverage.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/elf/ElfUnwindTables.ts
Line: 816-819

Comment:
**Padding makes coverage look incomplete**

The parser requires another four-byte length word before checking `tableBound`. If the last table-named FDE leaves only one to three bytes in its `PT_LOAD`, those unrelated trailing bytes mark `.eh_frame` incomplete. With four trailing bytes, the same scan correctly stops at `tableBound`.

Check the table bound before reading the next record so bytes outside the selected table cannot change its coverage.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +487 to +489
if (signed && shift < 64n && (byte & 0x40) !== 0)
result |= -1n << shift;
return { value: result, next: pos };

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.

P2 Padded values drop valid ranges

readLeb loses the sign of a ten-byte SLEB128 value. The valid padded encoding fc ff ff ff ff ff ff ff ff 7f represents -4, but this code returns 2^70 - 4 because shift is already 70. When a CIE uses this encoding for data_alignment, the value fails safeInt. The parser then drops that CIE and all its function ranges, leaving incomplete coverage for valid input.

Sign-extend the completed value and check that its high bits fit the supported width.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/native/elf/ElfUnwindTables.ts
Line: 487-489

Comment:
**Padded values drop valid ranges**

`readLeb` loses the sign of a ten-byte SLEB128 value. The valid padded encoding `fc ff ff ff ff ff ff ff ff 7f` represents `-4`, but this code returns `2^70 - 4` because `shift` is already 70. When a CIE uses this encoding for `data_alignment`, the value fails `safeInt`. The parser then drops that CIE and all its function ranges, leaving incomplete coverage for valid input.

Sign-extend the completed value and check that its high bits fit the supported width.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants