Repository navigation
feat(native): list ELF and Mach-O initializer and finalizer functions - #9574
Conversation
inspect_native_initializers and inspect-native-initializers list the functions an ELF or Mach-O image runs before and after main: ELF DT_INIT, DT_FINI, preinit, init and fini arrays and .ctors/.dtors, and Mach-O __mod_init_func, __mod_term_func and __init_offsets, with slot addresses, resolved targets, symbols where available and relocation facts for relocatable objects. Nothing is executed. Slot, symbol, relocation and note budgets are shared across tables, sentinels are matched at the image width, and target-derived names are bounded and marked untrusted.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
[Medium impact] The PR adds a bounded inspection workflow for caller-selected local native files. Do not merge yet: FindingsFix with agent prompt### Issue 1
src/native/initializers/MachoInitializers.ts:614
On watchOS `arm64_32`, Mach-O has a 64-bit header but four-byte pointers. `readMachoImage` derives `bits` from the header, so `walk.image.bits / 8` becomes eight. Two adjacent initializer pointers become one false address, and a single four-byte entry is omitted.
Derive the pointer width from the CPU once and use it for slots and object relocations, or explicitly reject this architecture.
### Issue 2
src/native/initializers/MachoInitializers.ts:103-108
A crafted Mach-O can stall the MCP server through this new call. `parsePointerFixups` expands legacy rebase runs synchronously before the initializer slot walk. Its work allowance is twice the file size, so a 64 MiB image can request roughly 134 million visits, even for one initializer. No yield or cancellation check runs during that loop.
Make this walk yield to other requests and stop when the caller cancels.
> **How this was verified:** The selected file reaches `readMachoInitializers` on the request path, and its rebase opcodes drive a synchronous per-address loop before the next signal check.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryAdds
Validation was source-only; no tests were run. GitHub authentication was unavailable, so supersession status could not be checked. Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
CLI["CLI command"] --> Service["NativeInitializersService"]
MCP["MCP tool"] --> Service
Service --> Provider["NativeInitializersProvider"]
Provider --> Read["Read one stable local file"]
Read --> Select["Select the image or universal slice"]
Select --> ELF["ELF declarations and relocations"]
Select --> MachO["Mach-O sections and fixups"]
ELF --> Report["Page entries and retain limitations"]
MachO --> Report
Report --> Evidence["Return Evidence"]
Reviews (2) · Last reviewed commit: "docs(native): move initializer guide und..." · Reviewed by Greptile |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 44c3fe5856
ℹ️ 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".
…verage is partial A skipped, unreadable or over-budget section relocation table now keeps every slot it could reach unresolved instead of reading the stored word as raw or dropping a .ctors slot as a sentinel. Dynamic writes that only partly overlap a slot, or write it twice, leave it unresolved. Linked images no longer reapply retained non-SHF_ALLOC link-time records. The dynamic relocation walk now pauses at the shared reader's step boundaries and observes cancellation there, resolved targets need only their first byte mapped, and unreadable symbol names make the report incomplete.
…olved Object files now apply their own section relocations: an UNSIGNED entry against a defined symbol gives symbol_addend, one against an undefined symbol gives unresolved_import, and any other entry leaves the slot unresolved. Linked images without a fixup decoder, such as 32-bit ones, keep pointer slots unresolved when an LC_DYLD_INFO bind stream or LC_DYSYMTAB external relocations could replace the stored word. LC_DYLD_INFO rebases now report dyld_info_rebase instead of chained_fixup, and unreadable symbol names make the report incomplete. Section headers keep their declared reloff and nreloc for this.
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 /native-initializers route is unchanged. The guide and spec also describe per-slot relocation coverage, retained link-time records, Mach-O object relocations, undecoded bind streams, the dyld_info_rebase resolution and unreadable names.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2d8802b7bb
ℹ️ 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".
…resolved An absolute relocation against an STT_GNU_IFUNC symbol no longer reports the resolver address as the target. Section relocation records now use their real write width, so a record that writes only part of a slot, starts inside it or repeats it leaves the slot unresolved instead of reading a raw zero or dropping a .ctors slot as a sentinel. On 32-bit ARM the Thumb bit is cleared when locating a target's section and file offset, while value_va keeps the stored callable value.
…_32 with a 64-bit header On CPU_TYPE_ARM the Thumb bit is cleared when locating and naming a target, since nlist values do not carry it. An arm64_32 image that declares a 64-bit header is rejected as malformed rather than read with 8-byte slots. The guide and spec describe IFUNC relocations, partly relocated section slots, Thumb targets and this rejection.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e5283933e9
ℹ️ 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".
…pings unknown ELF and Mach-O initializer lookups now build the shared file mapping index once per image, so each slot and target lookup is logarithmic in the number of load segments rather than a scan of every mapping. An address that load segments map ambiguously no longer falls back to a section header offset. Its file offset is reported as unknown and the report is incomplete; only genuinely unmapped spans use the section fallback.
A bound import name longer than the 1024-byte name budget was dropped without a trace, although it is the only identity of an unresolved initializer target. It now counts toward the over-long name limitation and makes the report incomplete.
…regression The load-mapping regression asserted a wall-clock bound, which is sensitive to machine load. It now spies on the shared mapping module and requires the same number of mapping scans and index builds for 8 and 64 slots, so a per-slot scan of every load segment fails deterministically on a small fixture.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c9de2e1038
ℹ️ 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".
# Conflicts: # src/native/AppleMachoFixups.ts
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cef035bcbe
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1bc0ff5f8f
ℹ️ 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".
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 42245d963a
ℹ️ 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".
| note(scan, AMBIGUOUS_MAPPING); | ||
| return null; | ||
| } | ||
| return index.fileOffsetAt(address, size); |
There was a problem hiding this comment.
Leave unmapped ELF targets without a file offset
For a linked ELF with an unmapped initializer value, including the zero slots deliberately retained by this tool, this fallback can translate the value through non-SHF_ALLOC sections such as .comment or .symtab, whose sh_addr is zero but is not a load address. In an isolated parser run on a GNU-linked x86-64 ET_EXEC, initializer words 0 and 0x10 received value_file_offset values 0x2000 and 0x2010 inside .comment, with complete coverage, although neither VA belongs to a PT_LOAD. Preserve a null target file offset when the linked image's load mappings do not cover it rather than publishing metadata bytes as the target location.
AGENTS.md reference: AGENTS.md:L19-L19
Useful? React with 👍 / 👎.
| for (let index = 0; index < read; index += 1) { | ||
| if (index % 4096 === 0) assertArtifactReadActive(walk.signal); |
There was a problem hiding this comment.
Yield while scanning Mach-O object relocations
For an MH_OBJECT with a large initializer relocation table, this synchronous loop prevents its periodic signal checks from observing cancellation until the entire table has been indexed. Unlike the now-asynchronous ELF section scanner, objectRelocations is called by slotsOf before its first await. An isolated 8 MiB, 524,288-record parser probe delayed an already-scheduled abort by 259–290 ms; the accepted record allowance is twice that size. Yield between bounded batches in the owning relocation scanner so cancellation and other event-loop work can run during indexing, not only during the subsequent slot walk.
AGENTS.md reference: AGENTS.md:L31-L33
Useful? React with 👍 / 👎.
|
Many thanks for the reviews and merges, @morluto. This one lists ELF and Mach-O initializer and finalizer functions, and the rest landed alongside it: #7859 reads Windows Shell Link (.lnk) shortcuts, #9387 keeps strict module checks unproven when alias walks exhaust their budget, #9573 reports a kernel image's version banner and embedded build config, #9585 recovers ELF function ranges from unwind tables, and #8527 inventories and extracts Deno compile executables. |
Summary
Code that runs before
mainor at exit is a common first question in native triage: static constructors,__attribute__((constructor))hooks, injected libraries and packer stubs all live there. In ELF it is declared throughDT_INIT,DT_INIT_ARRAY,DT_PREINIT_ARRAY,DT_FINI_ARRAYand the legacy.ctors/.dtorssections. In Mach-O it is declared through__mod_init_func,__init_offsetsand__mod_term_func. REA had no single read-only view of these declarations, and on PIE images the array slots are usually zero on disk until relocations are applied.This adds
inspect_native_initializers(CLIinspect-native-initializers). It lists every declared initializer and finalizer slot in one local ELF or Mach-O image (witharchitectureselecting a universal slice), resolves each slot through relative, RELR, symbolic and chained-fixup relocations where it can, and names the target section and symbol. No issue is linked. This is a proposed new read-only capability.Problem and expected behavior
Use case: an analyst opens an unfamiliar binary or shared library and wants to know which functions it declares to run before
mainor at exit, without a disassembler provider or running it.Observable outcome:
entries[]lists slots in declaration order withkind(preinit_array,init,init_array,ctors,fini,fini_array,dtors,mod_init,init_offsets,mod_term), the slot's address, file offset and section, and the resolved target's address, file offset, section and exactly matching symbol.resolutionsays how each value was obtained (raw,relative_addend,relr,symbol_addend,chained_fixup,dyld_info_rebase,offset_table,unresolved_import,unresolved). A zero PIE slot is never reported as its stored zero when its relocation could not be decoded. A slot is only reported as raw when every relocation table that could reach it was read, and a slot touched by partial, offset or conflicting writes stays unresolved. In linked ELF images, non-SHF_ALLOCrelocation sections are treated as already applied. Mach-O object files apply their own section relocations, and linked images without a fixup decoder keep slots unresolved when bind streams or external relocations could replace them..ctors/.dtorssentinels are omitted at the image's pointer width, and stored zeros in arrays stay listed so the array length is visible.incompletewith a limitation, never a silently shorter list.Change and scope
The ELF reader is
src/native/initializers/ElfInitializers.tswith symbol lookup inElfInitializerSymbols.ts, the Mach-O reader isMachoInitializers.ts, and the report schema issrc/domain/native/nativeInitializers.ts. Relocations come from the existingsrc/native/metadata/ElfPointerRelocations.ts. That shared reader now also exposes each record'ssymbol_indexandaddendand the machine's word-sized absolute relocation type, so this feature does not re-parse relocation tables. Its existing callers ignore the new fields.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/native-initializers.mdguide with nav and index entries, a spec underdocs/specs/native/native-initializers/, and lines in the authored skill reference.Bounded by default: the file is limited by
max_file_bytes(64 MiB, 512 MiB max), at most 65536 slots, 65536 symbols across all symbol tables, 1048576 section relocation records, and 40 limitation lines. Results are paged withoffsetandlimit. The dynamic relocation walk is asynchronous and yields between records, so a large table can be cancelled.Not included: proving that a listed function runs, reconstructing runtime order (which the guide describes), Android packed relocations, or disassembling the targets.
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
src/native/initializers/and report schema insrc/domain/native/, exposed through the binary-diagnostics service. Additive fields on the shared ELF relocation reader.inspect-native-initializerscommand andinspect_native_initializerstool. The MCP input requires an absolute path, matching the other local path tools.native-initializersnormalized result. Symbol and section names are marked as observed and untrusted. Universal Mach-O file offsets are relative to the whole file.docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs andskills/; edit authored instructions in.agents/skills/reverse-engineer-anything/and never commit build outputs): authored skill reference lines, the new guide and its nav and index entries, and the spec. No build output is committed. The## Nativeentry indocs/specs/README.mdmay conflict textually with my other open native-spec PRs; the entries are independent.Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.
Evidence and regression coverage
src/native/initializers/NativeInitializersParsers.test.ts(fixtures inNativeInitializers.fixture.ts) covering ELF32/ELF64, PIE relocations, RELR, relocatable.ctors, Mach-O chained fixups and__init_offsets, sentinels and every budget; schema, service, address-index and relocation-reader tests; a filesystem boundary test, an MCP boundary test and a CLI acceptance test.mainthere is no command that lists initializer declarations. On this commit I compiled one C++ file with a global object (constructor and destructor), an__attribute__((constructor))function and an__attribute__((destructor))function, then rannode scripts/rea.mjs inspect-native-initializers <file> --json:zig c++ -target x86_64-linux-gnu -O0: three entries, complete.init_arrayslots at0x10c1ab0and0x10c1ab8resolve to_ZL5earlyv(0x10289b0) and_GLOBAL__sub_I_init.cpp(0x1028a10), and thefini_arrayslot at0x10c1ac0resolves to_ZL4latev(0x10289c0). These matchllvm-objdump -s -j .init_array -j .fini_arrayandllvm-nmexactly.clang++ -O0): threeinit_offsetsentries, complete, resolving to__ZL5earlyv(0x100000628),__GLOBAL__sub_I_init.cpp(0x100000704) and___GLOBAL_init_65535(0x100000718). These match the__init_offsetswords andllvm-nm. The third is clang's stub that registers the destructor function at0x10000062cwith__cxa_atexit, so it appears as an initializer rather than amod_termentry.--jsonresult for the ELF build.{ "format": "elf", "status": "parsed", "coverage": { "status": "complete", "examined_entries": 3, "total_entries": 3, "returned_entries": 3 }, "entries": [ { "index": 0, "kind": "init_array", "slot_va": "0x10c1ab0", "value_va": "0x10289b0", "section": ".text", "symbol": "_ZL5earlyv", "resolution": "raw" }, { "index": 1, "kind": "init_array", "slot_va": "0x10c1ab8", "value_va": "0x1028a10", "section": ".text", "symbol": "_GLOBAL__sub_I_init.cpp", "resolution": "raw" }, { "index": 2, "kind": "fini_array", "slot_va": "0x10c1ac0", "value_va": "0x10289c0", "section": ".text", "symbol": "_ZL4latev", "resolution": "raw" } ] }.ctorsand Mach-O__mod_init_funcchained fixups comes from synthetic fixtures only. No shared library from a distribution or an Android.sowas tested. The real-binary check is not committed as a script. Separately, the existingmappedFileOffsethelper insrc/native/metadata/BinaryContainer.tswalks segments linearly; this PR does not change it.For boundary fixes, identify the applicable boundary regressions
and lifecycle regressions
covered by the evidence above, and explain relevant gaps.
For evidence-bearing changes:
Validation performed
ELF boundary follow-up (
eb583a49b3): linked section-fallback slots are checked against their load mapping while retaining declared offsets; section-relocation scanning yields between batches. The mapping and real scheduled-cancellation regressions fail on1bc0ff5f8fand pass after repair. The 58 parser tests, 8 CLI/filesystem/MCP boundary tests andnpm run check:fastpassed. The 335-source/162-boundary runs below predate this final follow-up; real-artifact comparisons below also predate it.Deep-review fixes (
adcb4ad0e0, merged with main ine843a3976f): partially overrun ELF section relocations and identical repeated dynamic writes keep affected slots unresolved. Legacy bind queries have explicit per-query and per-image candidate allowances; exhaustion preserves incomplete coverage, while bind-stream and initializer batches yield for cancellation. The synchronous dispatch adapter used only by tests moved into a fixture helper. All four new regressions failed against1bc0ff5f8ffor the intended reasons and passed after repair.On the combined branch: 335 source tests and 162 CLI/MCP/filesystem/IL2CPP boundary tests passed;
npm run check:fastandnpm run docs:checkpassed. Four freshly compiled artifacts (ELF shared library, Mach-O executable, Mach-O object and watchOS arm64_32 object) retained identical initializer entries and complete coverage through the public CLI. These artifacts were inspected without executing them. No full-suite run or real IL2CPP/dispatch target verification was performed. Sparse adversarial bind descriptions can now yield incomplete results by design; no end-to-end performance improvement or CPU/memory/token measurements are claimed for this repair.Latest initializer review fixes: 206 source tests, 160 CLI/MCP/binary boundary tests and
npm run check:fastpassed. Partial legacy fixups remain unresolved rather than reporting raw pointers; bind lookup uses a shared index. On three alternating warm synthetic 16,384-run CLI inspections, median elapsed time was 1.354 s before and 0.495 s after, with matching normalized results; sampled process-family peak RSS medians were 275.4 and 254.1 MiB. CPU sampling included monitoring overhead; cold, token and real-binary costs were not measured. No real provider was tested for these changes.Initializer mapping and reporting: 138 source tests across initializers, ELF relocations and Mach-O fixups passed; 8 focused CLI/MCP/filesystem tests passed;
npm run check:fastpassed. Synthetic regressions cover mapping mismatch, ELF no-op relocation, UTF-8/invalid symbol names, and page-independent name omissions. The object cross-slot relocation case is fixed; legacy overlap and bind query work are addressed by the follow-ups below. Real-provider cases were not rerun.Cooperative Mach-O fixup decoding:
npm run check:fastpassed; source tests for initializer parsing, Mach-O fixups and Apple dispatch passed (242 tests); focused IL2CPP and initializer boundary tests passed (183 tests). The new initializer cancellation regression fails on the prior head and passes with this change. Rebase work yields between bounded batches for initializer, IL2CPP and dispatch request paths. This is synthetic coverage; no real-provider run or representative task performance measurements were performed for this fix.Run on this commit on macOS with Node 24.22.1:
npx --no-install vitest runon every changed test file plus the shared relocation reader's consumer tests (16 files): 362 passed.llvm-objdumpandllvm-nmdescribed above.Compatibility, safety, and release
Author readiness
Human owner: @mvanhorn
Before merge
type(scope): outcome.AI was used for assistance.