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

* feat(native): recover ELF function ranges from unwind tables

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.

* fix(elf): keep unresolved unwind facts out of reported ranges

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.

* fix(scripts): run the ELF unwind verifier under owned process trees

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.

* docs(elf): move ELF unwind ranges guide under docs/guides/native

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.

* fix(elf): give unwind text limits their own recovery and skip indirect 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.

* fix(elf): resolve header count and table forms and name IFUNC resolvers

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.

* fix(elf): require allocated unwind pointer bases

* fix(elf): map unwind header relative base

* fix(elf): validate unwind load mappings

* test(elf): cover mapped nonallocated frame agreement

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-09 21:42:53 +08:00
1 parent f21fda0fc0
commit 43f06eb1e8
46 files changed
+7087 -4

No files matched your search

@@ -2,7 +2,7 @@
name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "61"
version: "62"
---
# REA
@@ -307,6 +307,15 @@ explicit path or endpoint and do not need it.
build-id or ABI-tag fields. A missing table is observed absence of those
declarations, not proof the image never carried notes. See the
[ELF notes guide](https://github.com/morluto/rea/blob/main/docs/elf-notes.md).
- ELF unwind function ranges: `inspect_elf_unwind_ranges` with the explicit
local ELF32/ELF64 file. This built-in target-free inspection requires no
disassembler. Preserve FDE start, end, size, containing section, exact
symbol name, CIE index, LSDA, and personality. Page with `offset` and
`limit`. A missing `.eh_frame` is observed absence of that declaration,
not proof the image has no functions. `.debug_frame` is reported present
or absent and is not decoded. CFA instructions are counted and not
evaluated. See the
[ELF unwind ranges guide](https://github.com/morluto/rea/blob/main/docs/guides/native/elf-unwind-ranges.md).
- Apple `.ips` crash reports: `inspect_apple_ips` with the explicit local
file. This built-in target-free inspection requires no Xcode, atos, or
pwntools. Preserve first-line metadata, `bug_type` as a string, process and
@@ -199,6 +199,22 @@ absence of those declarations, not proof the image never carried notes in
another container. See
[ELF note tables](https://github.com/morluto/rea/blob/main/docs/elf-notes.md).
## ELF unwind function ranges
Use `inspect_elf_unwind_ranges` for an explicit local ELF32/ELF64 image when
the question concerns function starts and lengths that survive `strip`, which
functions have an LSDA, or which ranges have no exact symbol. No
`open_binary` or target execution is required. The CLI equivalent is
`inspect-elf-unwind-ranges PATH`. Preserve artifact SHA-256, FDE start and
end, containing section, exact symbol name, CIE index, LSDA, and personality.
Page later ranges with `offset` and `limit`. A missing `.eh_frame` is
observed absence of that declaration and of `PT_GNU_EH_FRAME`, not proof the
image has no functions. Header disagreement is a limitation and does not drop
decoded ranges. `.debug_frame` is reported present or absent and is not
decoded. CFA instructions are counted and not evaluated. Indirect EH pointers
are not dereferenced. See
[ELF unwind function ranges](https://github.com/morluto/rea/blob/main/docs/guides/native/elf-unwind-ranges.md).
## Apple IPS crash reports
Use `inspect_apple_ips` for an explicit local Apple `.ips` file when the
+5
View File
@@ -43,6 +43,11 @@ export const documentationSections = [
source: "guides/native/binary-diagnostics.md",
route: "/binary-diagnostics",
},
{
text: "ELF unwind function ranges",
source: "guides/native/elf-unwind-ranges.md",
route: "/elf-unwind-ranges",
},
{
text: "Linux kernel build config",
source: "guides/native/kernel-build-config.md",
+1
View File
@@ -16,6 +16,7 @@ product pages. The VitePress documentation source is this `docs/` tree.
- [Native binary investigation](guides/native/native-investigation.md)
- [Go binary build metadata](guides/native/go-binaries.md)
- [Offline binary diagnostics](guides/native/binary-diagnostics.md)
- [ELF unwind function ranges](guides/native/elf-unwind-ranges.md)
- [Linux kernel build config](guides/native/kernel-build-config.md)
- [Recorded crash evidence](guides/native/recorded-crashes.md)
- [Windows Shell Link shortcuts](guides/native/windows-shortcut.md)
+14
View File
@@ -462,6 +462,20 @@ The workflow reports note owners, types, descriptor hashes, and GNU build-id
or ABI-tag fields when those descriptors match. A missing note table is
observed absence of those declarations. See [ELF note tables](../elf-notes.md).
Inspect ELF unwind function ranges without executing the image:
```bash
rea inspect-elf-unwind-ranges /absolute/path/to/program --json
```
The workflow reports FDE start, end, and size, the containing section, an exact
symbol name when one exists, CIE identity, LSDA, and personality. Coverage
counts ranges that match a symbol, ranges without a symbol, and whether the
`.eh_frame_hdr` search table agrees with the decoded FDEs. `.debug_frame` is
reported present, absent, or incomplete and is not decoded. A missing unwind table is
observed absence of those declarations. See
[ELF unwind function ranges](../guides/native/elf-unwind-ranges.md).
Inspect an Apple `.ips` crash report without executing a target:
```bash
+177
View File
@@ -0,0 +1,177 @@
# ELF unwind function ranges
`inspect_elf_unwind_ranges` / `inspect-elf-unwind-ranges` reads `.eh_frame`
and `.eh_frame_hdr` from one selected local ELF32/ELF64 image and lists the
function ranges those tables name. It reads the file without executing it and
does not require a disassembler.
```bash
rea inspect-elf-unwind-ranges /absolute/path/to/program --json
```
The CLI resolves relative paths against the caller's working directory. MCP
requires an absolute filesystem path and preserves that exact selection:
```json
{
"name": "inspect_elf_unwind_ranges",
"arguments": { "path": "/artifacts/program" }
}
```
Pass `--offset` and `--limit` (MCP `offset` and `limit`) to page the ranges.
The default page starts at 0 and returns at most 256 ranges.
## Observations
The inline Evidence result contains the artifact path, SHA-256, and byte
length, plus ELF class, byte order, machine, and object type.
`eh_frame.status` is `present`, `absent`, `incomplete`, or `unknown`. A
present table names its source: `section` when section headers name
`.eh_frame`, or `program` when section headers are missing and
`PT_GNU_EH_FRAME` supplies the bytes. `location` is the file range that was
examined. A `.eh_frame` section that is `SHT_NOBITS` or lies outside the file
is `incomplete` with a null `location`. One that runs past the end of the
file is `incomplete`, `location` is clamped to its in-file bytes, and the
records in those bytes are still decoded. Only the first `.eh_frame` and
`.eh_frame_hdr` section is decoded, and only the first `PT_GNU_EH_FRAME`
program header. A duplicate section, or a duplicate `PT_GNU_EH_FRAME` when no
`.eh_frame_hdr` section supplies the header, keeps `coverage.status` at
`incomplete`.
`eh_frame_hdr` reports version, the three pointer encodings, the `.eh_frame`
pointer, the declared FDE count, and how many binary-search table entries
were decoded. A header section that is `SHT_NOBITS` or extends past the end of
the file is `incomplete` with a null `location` and is not decoded.
`coverage.eh_frame_hdr_agreement` is `agree` when the table has exactly one
row per decoded FDE, the sorted starts match including repeats, and each row
points at a distinct FDE with that start. It is `disagree` otherwise, and
`unavailable` when the header is absent, unknown, or incomplete. Disagreement
is a limitation. The decoded FDEs stay in the result. The search table is
read for at most `max_ranges` rows, and for no more rows than the header bytes
can hold. When the declared FDE count is larger than either bound, the header
is `incomplete`, `table_entries` counts only the rows read, the comparison is
`unavailable`, and a limitation names the cap. A declared count that does not fit
in 32 bits is not decoded: `fde_count` is null, the header is `incomplete`,
and the decoded FDEs stay in the result. A header whose FDE count encoding is
`DW_EH_PE_omit` (`0xff`), as GNU ld writes when it cannot build the search
table, is `present` with a null `fde_count`, no table rows, and comparison
`unavailable`; it does not make coverage incomplete. A header that declares
an FDE count but writes `DW_EH_PE_omit` as its table encoding is `present`
with that count, no table rows, and comparison `unavailable`, and also keeps
coverage complete. A non-zero FDE count under an indirect encoding is the
address of a slot that is not followed, so `fde_count` is null, the header is
`incomplete`, and the table is not read.
When section headers name both `.eh_frame_hdr` and `PT_GNU_EH_FRAME`, the
section is decoded. A limitation names the segment as ignored only when it
declares different bytes than the section. When no `.eh_frame_hdr` section is
named, the header is read from `PT_GNU_EH_FRAME` even if a `.eh_frame`
section is present.
A record whose length word is `0xffffffff` uses the 64-bit extended length
that follows it. In `.eh_frame` the CIE ID and CIE pointer after that length
stay 4 bytes wide.
`DW_EH_PE_datarel` fields in `.eh_frame_hdr` are relative to the header
address. In `.eh_frame` they are relative to the GOT: `DT_PLTGOT` when the
dynamic table names it, otherwise the `.got.plt` or `.got` section address.
A limitation names the base that was used. When no GOT base is declared,
those values are unresolved: the affected record is not reported and
`coverage.status` is `incomplete`.
`debug_frame.status` is `present`, `absent`, `incomplete`, or `unknown`. It
is `unknown` when the image has no section headers or unreadable section
names. It is `incomplete`, with a null `location` and `coverage.status` at
`incomplete`, when the section is `SHT_NOBITS` or its bytes are not all in
the file. The `.eh_frame` results stay in the report. This command does not
decode `.debug_frame`.
`cies` lists the CIEs that the returned page's ranges name, in index order,
so its length never exceeds the page size. Each `cie_index` in `ranges`
matches the `index` of one entry in `cies`. `coverage.total_cies` counts every
decoded CIE, including CIEs no FDE on this page uses. Each CIE reports
version 1 or 3, augmentation, code and data alignment,
return-address register, pointer encoding, LSDA encoding, personality address
when the augmentation carries one, signal-frame and B-key flags, and the byte
length of the CFA program. CFA instructions are counted and not evaluated.
A CIE whose augmentation has a letter other than `z`, `L`, `P`, `R`, `S`, or
`B` is not decoded: the encodings of later letters cannot be trusted, so its
FDEs are not decoded either. A limitation counts those FDEs and coverage is
`incomplete`.
`ranges` is one page of FDEs. Each range has `start`, `end`, decimal `size`,
the containing `SHF_ALLOC` section, an exact symbol name when a symbol starts
at that address, the CIE index, LSDA, and personality. A function symbol is
preferred, then an `STT_GNU_IFUNC` symbol, then an untyped one. An IFUNC name
is the resolver that starts at that address, not the implementation it
selects at run time, and a limitation says so. Symbol names, section names,
and augmentation strings are target-derived and untrusted. Indirect EH
pointers are not dereferenced. An FDE whose initial location is indirect names
a pointer slot, not its function, so it is not reported as a range; a
limitation counts those FDEs and coverage is `incomplete`. An indirect
`eh_frame_ptr` does not locate `.eh_frame`, and the header is `incomplete`.
A search table with an indirect encoding is not read: the header is
`incomplete`, the comparison is `unavailable`, and the table does not bound a
header-located `.eh_frame`.
An encoded pointer whose stored value is zero is a null pointer, as libgcc
reads it: no PC-relative, text, data, or function base is added and an
indirect pointer is not followed. A resolved address, and an FDE `end`,
wraps at the ELF address width (32 or 64 bits), as libgcc's pointer
arithmetic does. A zero LSDA pointer is reported as a null
`lsda`, even when the CIE declares an LSDA encoding. An FDE whose initial
location is zero marks a function the linker discarded. It is not reported
as a range, `examined_records` still counts it, and a limitation counts how
many were skipped. In a relocatable object an unrelocated initial location
is also zero, so those FDEs are skipped too.
`page` reports `offset`, `limit`, `returned`, `total`, and `next_offset`.
`next_offset` is null when the page reaches the end of the decoded list.
`coverage` counts every decoded range, every decoded CIE, how many ranges
match a symbol, and how many do not. `examined_records` counts CIE and FDE records visited, including
records that could not be decoded.
A missing `.eh_frame` section and a missing `PT_GNU_EH_FRAME` segment are
observed absence of those declarations. That absence is not proof the image
has no functions. Program headers come from the shared ELF section
directory, which rejects an image whose program-header table cannot be read,
so a missing `PT_GNU_EH_FRAME` is always observed absence. When section
headers are missing too, section names are unknown, so a missing header is
`unknown` rather than `absent`.
A `.eh_frame` located only through the `.eh_frame_hdr` `eh_frame_ptr` has no
section size, so it is read up to the end of its `PT_LOAD` segment. Other
data, such as `.gcc_except_table`, can follow it there. When the search table
was decoded, the scan stops after the last FDE the table names, as libgcc's
`PT_GNU_EH_FRAME` lookup only binary-searches that table. Later bytes are not
decoded and a limitation says so. Without a usable table, the scan stops at
the first record that fails to decode, as libgcc's linear FDE search does,
and `coverage.status` is `incomplete`. A CIE with an unrecognized
augmentation letter, or an FDE that uses one, also stops that scan. Reaching the end of the segment with
no terminator also keeps coverage `incomplete`, because the table's extent is
then unknown.
Addresses map to file offsets through `SHF_ALLOC` sections, then `PT_LOAD`
segments. A section without `SHF_ALLOC`, such as `.comment` or `.debug_*`,
is not loaded, so its `sh_addr` is never used for translation and it is never
reported as the section containing a range. A record that ends past the table, or non-zero bytes after
the terminator, keeps `coverage.status` at `incomplete`. Relocatable objects
stay incomplete because relocations are not applied.
## Limits and failures
The selected file is limited to 64 MiB by default (512 MiB maximum).
`max_ranges` defaults to 8192 and caps at 65536. That ceiling applies
separately to CIE records and to FDEs. Exceeding either budget fails without
partial success. One page returns at most 4096 ranges. Symbol lookup stops
after 65536 entries across `.symtab` and `.dynsym` combined. Reaching that
cap keeps `coverage.status` at `incomplete`. Only symbols at decoded FDE
starts are kept, and a name is decoded only for a returned range. The names
on one page share a fixed 16 MiB text allowance; a page that exceeds it fails
with a resource error whose recovery is a smaller `limit`, because
`max_ranges` and `max_file_bytes` do not raise it.
Malformed ELF headers fail without partial success. This workflow does not
execute the image, evaluate CFA programs, or follow indirect pointers.
+1 -1
View File
@@ -52,7 +52,7 @@ The [documentation directory](README.md) lists every guide by domain.
| Task | Guides |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Identify a desktop installation | [Runtime candidates, evidence and follow-up files](desktop-applications.md) |
| Inspect native functions, references, or types | [Native binaries](guides/native/native-investigation.md), [Go metadata](guides/native/go-binaries.md), [Rust dependencies](rust-binaries.md), [CPython pyc files](python-pyc.md), [PE certificates](pe-certificates.md), [PE imports](pe-imports.md), [PE TLS/load config](pe-load-config.md), [ELF notes](elf-notes.md), [Linux kernel modules](kernel-modules.md), [Linux kernel build config](guides/native/kernel-build-config.md), [Apple IPS](apple-ips.md), [Erlang BEAM](erlang-beam.md), [offline ELF layout](guides/native/binary-diagnostics.md), [recorded crashes](guides/native/recorded-crashes.md) |
| Inspect native functions, references, or types | [Native binaries](guides/native/native-investigation.md), [Go metadata](guides/native/go-binaries.md), [Rust dependencies](rust-binaries.md), [CPython pyc files](python-pyc.md), [PE certificates](pe-certificates.md), [PE imports](pe-imports.md), [PE TLS/load config](pe-load-config.md), [ELF notes](elf-notes.md), [ELF unwind ranges](guides/native/elf-unwind-ranges.md), [Linux kernel modules](kernel-modules.md), [Linux kernel build config](guides/native/kernel-build-config.md), [Apple IPS](apple-ips.md), [Erlang BEAM](erlang-beam.md), [offline ELF layout](guides/native/binary-diagnostics.md), [recorded crashes](guides/native/recorded-crashes.md) |
| Select a native provider or import format | [Ghidra semantics](providers/ghidra-provider.md), [Windows](providers/windows-ghidra-p0.md), [DOS](providers/ghidra-dos.md), [raw bytes](providers/raw-binary.md), [GameCube DOL](ghidra-dol.md), [MIPS](providers/ghidra-mips.md), [RISC-V](providers/ghidra-riscv.md), [PowerPC](ghidra-ppc.md), [PSP](providers/ghidra-psp.md), [NativeAOT](providers/ghidra-nativeaot.md), [IDA](providers/ida-provider.md), [Kuna](kuna-provider.md), [JEB](providers/jeb-analysis.md) |
| Analyze JavaScript or Electron artifacts | [Static analysis](guides/javascript/javascript-artifact-reconstruction.md), [tracing and comparisons](guides/javascript/javascript-application-workflows.md), [application graph](guides/javascript/javascript-application-graph.md), [source recovery](guides/javascript/javascript-recovery.md) |
| Compare static JavaScript with runtime observations | [Runtime attribution](guides/javascript/javascript-runtime-observation.md), [reconciliation](guides/javascript/javascript-runtime-reconciliation.md), [Electron observation](guides/javascript/electron-observation.md), [Electron fuses](electron-fuses.md) |
+2
View File
@@ -15,5 +15,7 @@ for the specification lifecycle, roadmap granularity and producer-owned contract
- [Go static string-header literal recovery](native/go-string-literals/spec.md)
([plan](native/go-string-literals/plan.md), [tasks](native/go-string-literals/tasks.md))
- [ELF unwind function ranges](native/elf-unwind-ranges/spec.md)
([plan](native/elf-unwind-ranges/plan.md), [tasks](native/elf-unwind-ranges/tasks.md))
- [Linux kernel build config](native/kernel-build-config/spec.md)
([plan](native/kernel-build-config/plan.md), [tasks](native/kernel-build-config/tasks.md))
@@ -0,0 +1,35 @@
# Implementation plan
## Boundary and contract
`src/domain/native/elfUnwindRanges.ts` owns the input and result schemas,
limits and the shared limitation strings. `src/native/elf/ElfUnwindTables.ts`
decodes `.eh_frame` and `.eh_frame_hdr` over the existing ELF image reader.
Dynamic entries use the shared `readElfDynamicEntry`.
`src/native/elf/ElfIntervalIndex.ts` builds the section address and file-offset
indexes once per image.
`src/application/binaryDiagnostics/ElfUnwindRangesService.ts` depends on the
domain and its port and validates the report shape. It is composed and
registered beside the sibling binary diagnostics tools in
`src/composition/` and `src/server/createServer.ts`.
## Incremental work and validation
1. Define the schemas, limits and limitations, with domain tests.
2. Decode CIEs and FDEs over synthetic fixtures for both widths and
endiannesses, including pointer encodings and extended lengths.
3. Decode `.eh_frame_hdr`, compare it with the FDEs, and bound the search
table.
4. Resolve symbols and containing sections through indexes, with a combined
symbol budget.
5. Register the CLI command and MCP tool, then add acceptance, filesystem and
MCP boundary tests.
6. Add the `verify:elf:unwind-ranges` script against a compiled C++ program.
7. Write the guide and the CLI reference entry, update the skill reference,
and run focused tests, lint, typecheck and docs checks.
## Effects and compatibility
Additive: one new read-only tool, one CLI command and one verifier script.
Existing tools and Evidence shapes do not change.
@@ -0,0 +1,92 @@
# ELF unwind function ranges
## Problem and outcome
A stripped ELF often has no symbol table, but its `.eh_frame` still names the
start and end of nearly every function so exceptions can unwind. REA can list
symbols and disassemble with a provider, but it cannot recover function
boundaries from unwind tables, so an agent without a disassembler has no
function list for a stripped binary.
This feature adds `inspect_elf_unwind_ranges` and
`inspect-elf-unwind-ranges`. They read `.eh_frame` and `.eh_frame_hdr` from one
selected local ELF32 or ELF64 image and list the function ranges those tables
name, without executing the image.
[ELF unwind function ranges](../../../guides/native/elf-unwind-ranges.md) describes the
current behavior and limitations. This directory is the feature
specification, implementation plan and task list. The guide does not replace
these files.
## Requirements
1. `.eh_frame` comes from section headers, or from `PT_GNU_EH_FRAME` when
section headers are missing. The source and examined file range are
reported. `SHT_NOBITS`, out-of-file and truncated tables are `incomplete`.
Program headers come from the shared section directory, which rejects an
unreadable program-header table, so a missing `PT_GNU_EH_FRAME` is observed
absence. An `.eh_frame` located only through the header's `eh_frame_ptr`
is read no further than the last FDE a decoded search table names. Without
a usable table it stops at the first undecodable record, including a CIE
with an unrecognized augmentation and its FDEs, or at the end of
its `PT_LOAD` without a terminator, and coverage is `incomplete`.
2. CIEs report version, augmentation, alignment factors, return-address
register, pointer and LSDA encodings, personality, and signal-frame and
B-key flags. A page returns only the CIEs its ranges name, so CIE output is
bounded by `limit`, and `coverage.total_cies` counts every decoded CIE.
CFA programs are counted, not evaluated. A CIE with an
unrecognized augmentation letter is not decoded, its FDEs are skipped
with a counted limitation, and coverage is `incomplete`.
3. FDEs become ranges with start, end, size, containing `SHF_ALLOC` section, an exact
symbol name when one starts at that address (a function, then an
`STT_GNU_IFUNC` resolver, then an untyped symbol), CIE index, LSDA and
personality, paged by `offset` and `limit`.
4. Encoded pointers follow the `DW_EH_PE` rules. A raw zero is a null pointer.
Resolved addresses and FDE ends wrap at the ELF32 or ELF64 address width.
`datarel` in `.eh_frame` resolves against `DT_PLTGOT`, then `.got.plt` or
`.got`, and an unresolved base leaves the record out with coverage
`incomplete`. Indirect pointers are not dereferenced: an FDE with an
indirect initial location is skipped with a counted limitation, and an
indirect `eh_frame_ptr` does not locate `.eh_frame`, and a search table
with an indirect encoding is neither compared nor used as a scan bound.
Each leaves coverage `incomplete`.
5. A 64-bit extended length keeps the `.eh_frame` CIE ID and pointer at 4
bytes.
6. An FDE with a zero initial location is a discarded function. It is counted
as examined, not reported, and a limitation gives the count.
7. `.eh_frame_hdr` is decoded and its search table compared with the decoded
FDEs as `agree`, `disagree` or `unavailable`. The table is read for at most
`max_ranges` rows and no more rows than its bytes hold. A larger declared
count makes the header `incomplete` with a limitation. A declared count
with an omitted table is a `present` header with comparison
`unavailable`. A non-zero indirect count is not followed, so the count is
unknown and the header `incomplete`.
8. `.debug_frame` presence is reported but not decoded.
9. Budgets bound the file size, CIE and FDE counts, page size and the symbol
lookup across `.symtab` and `.dynsym`. Only symbols at decoded FDE starts
are kept, names are decoded only for the returned page, and that text has a
fixed 16 MiB allowance whose recovery is a smaller `limit`. Only the first `PT_GNU_EH_FRAME` is read; a
duplicate one that supplies the header makes coverage `incomplete`. Section and symbol lookups use
indexes built once per image, so cost does not grow as sections times
entries. Address translation uses `SHF_ALLOC` sections, then
`PT_LOAD`; a non-ALLOC section's `sh_addr` is never used.
10. Symbol names, section names and augmentation strings are marked
target-derived and untrusted. MCP requires an absolute path.
## Acceptance
- Unit tests cover CIE and FDE decoding for both widths and endiannesses,
pointer encodings, extended lengths, zero pointers, discarded FDEs, header
agreement and caps, and the GOT base.
- Service tests validate the report shape, including incomplete headers and
null LSDAs.
- CLI acceptance, filesystem boundary and MCP boundary tests exercise the
public contract.
- `npm run verify:elf:unwind-ranges` compares the reported FDE starts with
`readelf` or `llvm-dwarfdump` on a compiled C++ program.
## Non-goals
- Decoding `.debug_frame` or evaluating CFA programs.
- Applying relocations in relocatable objects.
- Following indirect EH pointers.
@@ -0,0 +1,9 @@
# Tasks
- [x] Define the single-feature scope, contract and implementation plan.
- [x] Decode CIEs and FDEs with pointer encodings and extended lengths.
- [x] Decode and bound `.eh_frame_hdr`, and compare it with the FDEs.
- [x] Resolve symbols and sections through per-image indexes.
- [x] Register the CLI command and MCP tool with acceptance and boundary tests.
- [x] Verify FDE starts against `llvm-dwarfdump` on a C++ program built with zig.
- [x] Document the guide, CLI reference and skill reference.
+1
View File
@@ -204,6 +204,7 @@
"verify:pcap": "npm run build:cached && node scripts/verify-pcap.mjs",
"verify:pe:load-config": "npm run build:cached && node scripts/verify-pe-load-config.mjs",
"verify:binary-hardening": "node scripts/verify-binary-hardening.mjs",
"verify:elf:unwind-ranges": "npm run build:cached && node scripts/verify-elf-unwind-ranges.mjs",
"verify:flutter": "npm run build:cached && node scripts/verify-flutter.mjs",
"verify:adb": "npm run build:cached && node scripts/verify-adb.mjs",
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
+246
View File
@@ -0,0 +1,246 @@
/**
* Build a stripped C++ ELF and compare .eh_frame FDE starts with readelf.
* Not part of the default check. Exits non-zero when the host has no ELF
* C++ compiler or no readelf.
*/
import assert from "node:assert/strict";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
import { createVerifierCommands } from "./lib/verify-commands.mjs";
/**
* Every probe, compiler driver and inspection runs as an owned process tree,
* so a timeout or close also stops the children a driver starts. Close it
* before removing the compiled outputs.
*/
const commands = await createVerifierCommands();
/**
* Ctrl-C or SIGTERM aborts the running command instead of ending Node, so the
* owned process trees and the compiled outputs are still cleaned up below.
*/
const interruption = new AbortController();
const interrupt = (signal) =>
interruption.abort(
new Error(`ELF unwind ranges verifier interrupted by ${signal}`),
);
process.on("SIGINT", interrupt);
process.on("SIGTERM", interrupt);
const run = (command, args, timeout) =>
commands.exec(command, args, {
maxBuffer: 64 * 1024 * 1024,
timeout,
signal: interruption.signal,
});
const available = async (command) => {
// zig has no --version flag; it reports through the `version` subcommand.
const probe = command === "zig" ? ["version"] : ["--version"];
try {
await run(command, probe, 30000);
return true;
} catch (failure) {
// An absent tool or a failing probe means the candidate is unavailable.
if (failure?.code === "ENOENT" || typeof failure?.code === "number")
return false;
throw failure;
}
};
const firstAvailable = async (candidates) => {
for (const command of candidates)
if (await available(command)) return command;
return null;
};
const sourceText = `
struct Guard { ~Guard(); };
Guard::~Guard() {}
int may_throw(int value) {
Guard guard;
if (value < 0) throw value;
return value + 1;
}
int main() {
try { return may_throw(1); }
catch (int) { return 2; }
}
`;
const compileArguments = (compiler, source, output) => {
if (compiler === "zig")
return [
"c++",
"-target",
"x86_64-linux-musl",
"-O0",
"-g",
source,
"-o",
output,
];
if (compiler === "clang++")
return [
"--target=x86_64-linux-gnu",
"-O0",
"-g",
"-fexceptions",
source,
"-o",
output,
];
return ["-O0", "-g", "-fexceptions", source, "-o", output];
};
const compile = async (compiler, source, output) => {
await run(compiler, compileArguments(compiler, source, output), 120000);
};
const stripArguments = (stripper, input, output) => {
if (stripper === "llvm-strip") return ["--strip-all", "-o", output, input];
if (stripper === "llvm-objcopy") return ["--strip-all", input, output];
if (stripper === "zig") return ["objcopy", "--strip-all", input, output];
return ["-o", output, input];
};
const stripCopy = async (stripper, input, output) => {
await run(stripper, stripArguments(stripper, input, output), 30000);
};
// llvm-readelf has no --debug-dump=frames; llvm-dwarfdump --eh-frame prints
// the same `pc=<start>..<end>` FDE ranges under an `.eh_frame contents:` head.
const frameDump = async (readelf, path) =>
(
await run(
readelf,
readelf === "llvm-dwarfdump"
? ["--eh-frame", path]
: ["--debug-dump=frames", path],
30000,
)
).stdout;
const ehFrameStarts = async (readelf, path) => {
const stdout = await frameDump(readelf, path);
const starts = new Set();
let inEhFrame = false;
for (const line of stdout.split("\n")) {
if (/Contents of the \.eh_frame\b|^\.eh_frame contents:/u.test(line)) {
inEhFrame = true;
continue;
}
if (/Contents of the \.debug_frame\b|^\.\w+ contents:/u.test(line)) {
inEhFrame = false;
continue;
}
if (!inEhFrame) continue;
const match = /pc=(0x[0-9a-fA-F]+|[0-9a-fA-F]+)\.\./u.exec(line);
// readelf and llvm-dwarfdump print bare hex; BigInt needs the 0x prefix.
if (match?.[1] !== undefined)
starts.add(
BigInt(match[1].startsWith("0x") ? match[1] : `0x${match[1]}`),
);
}
return starts;
};
const inspectedStarts = async (path) => {
const starts = new Set();
let offset = 0;
for (;;) {
const { stdout: output } = await run(
process.execPath,
[
resolve("scripts/rea.mjs"),
"inspect-elf-unwind-ranges",
path,
"--json",
"--offset",
String(offset),
"--limit",
"4096",
"--max-ranges",
"65536",
],
60000,
);
const report = JSON.parse(output).normalized_result;
for (const range of report.ranges) starts.add(BigInt(range.start));
if (report.page.next_offset === null) {
assert.equal(report.eh_frame.status, "present");
assert.equal(starts.size, report.coverage.total_ranges);
return starts;
}
offset = report.page.next_offset;
}
};
// The root holds every compiled image. Remove it only after the owned
// commands have settled, and keep it when their cleanup failed.
let root;
let commandsClosed = false;
let unavailable = false;
await withVerifierCleanup(async () => {
const compiler = await firstAvailable(["zig", "clang++", "g++"]);
const readelf = await firstAvailable([
"readelf",
"greadelf",
"llvm-dwarfdump",
]);
const stripper = await firstAvailable([
"llvm-strip",
"llvm-objcopy",
"zig",
"strip",
]);
if (compiler === null || readelf === null || stripper === null) {
console.error(
"verify:elf:unwind-ranges needs an ELF C++ compiler (zig, clang++, or g++) and readelf (readelf, greadelf, or llvm-dwarfdump), plus a stripper.",
);
unavailable = true;
return;
}
root = await mkdtemp(join(tmpdir(), "rea-elf-unwind-"));
const source = join(root, "ranges.cpp");
const unstripped = join(root, "ranges.unstripped");
const stripped = join(root, "ranges.stripped");
await writeFile(source, sourceText);
await compile(compiler, source, unstripped);
await stripCopy(stripper, unstripped, stripped);
const expected = await ehFrameStarts(readelf, unstripped);
const observed = await inspectedStarts(stripped);
assert.ok(expected.size > 0, "readelf listed no .eh_frame FDEs");
const missing = [...expected].filter((start) => !observed.has(start));
const extra = [...observed].filter((start) => !expected.has(start));
assert.deepEqual(
{ missing: missing.map(String), extra: extra.map(String) },
{ missing: [], extra: [] },
);
console.log(
JSON.stringify({
compiler,
readelf,
fde_starts: expected.size,
}),
);
}, [
async () => {
await commands.close();
commandsClosed = true;
},
async () => {
if (commandsClosed && root !== undefined)
await rm(root, { recursive: true, force: true });
},
async () => {
process.off("SIGINT", interrupt);
process.off("SIGTERM", interrupt);
},
]);
// A signal that lands outside a command, such as during the final rm, is still
// a failed run. An earlier failure already left through the rejection above.
if (interruption.signal.aborted) throw interruption.signal.reason;
if (unavailable) process.exitCode = 1;
+1
View File
@@ -630,6 +630,7 @@ const workflowAvailabilityFor = (
return { reason: "available", remediation: null };
if (
name === "inspect_elf_notes" ||
name === "inspect_elf_unwind_ranges" ||
name === "inspect_devicetree" ||
name === "inspect_kernel_module" ||
name === "inspect_kernel_build_config" ||
@@ -0,0 +1,20 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
ElfUnwindRanges,
InspectElfUnwindRangesInput,
} from "../../domain/native/elfUnwindRanges.js";
import type { Result } from "../../domain/result.js";
/** Stable read and ELF unwind-table decoding, independent of a disassembler session. */
export interface ElfUnwindRangesPort {
readonly identity: ProviderIdentity;
close?(): Promise<void>;
inspect(
input: InspectElfUnwindRangesInput,
options?: ExecutionOptions,
): Promise<Result<ElfUnwindRanges, AnalysisError>>;
}
@@ -0,0 +1,424 @@
import { expect, it } from "vitest";
import { ElfUnwindRangesService } from "./ElfUnwindRangesService.js";
import { ELF_UNWIND_RANGES_PROVIDER } from "../../domain/investigationProviders.js";
import {
elfUnwindRangesSchema,
inspectElfUnwindRangesInputSchema,
type ElfUnwindRanges,
} from "../../domain/native/elfUnwindRanges.js";
import { parseElfUnwindRanges } from "../../native/elf/ElfUnwindTables.js";
import {
elfUnwindAbsentFixture,
elfUnwindFixture,
elfUnwindSectionlessFixture,
} from "../../native/elf/ElfUnwindTables.fixture.js";
import { ok } from "../../domain/result.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
const identity = ELF_UNWIND_RANGES_PROVIDER;
const undecodableHeaderPointer = (): Buffer => {
const bytes = elfUnwindSectionlessFixture();
bytes[Number(bytes.readBigUInt64LE(64 + 56 + 8)) + 1] = 0x0f;
return bytes;
};
const report: ElfUnwindRanges = {
artifact: {
path: "/artifacts/app",
sha256: "a".repeat(64),
bytes: 512,
},
format: "elf64",
byte_order: "little",
machine: 62,
type: 3,
type_name: "shared",
eh_frame: { status: "absent", source: null, location: null },
eh_frame_hdr: {
status: "absent",
location: null,
version: null,
eh_frame_pointer_encoding: null,
fde_count_encoding: null,
table_encoding: null,
eh_frame_pointer: null,
fde_count: null,
table_entries: 0,
},
debug_frame: { status: "absent", location: null },
cies: [],
ranges: [],
page: {
offset: 0,
limit: 256,
returned: 0,
total: 0,
next_offset: null,
},
coverage: {
status: "complete",
total_ranges: 0,
total_cies: 0,
ranges_with_symbols: 0,
ranges_without_symbols: 0,
eh_frame_hdr_agreement: "unavailable",
examined_records: 0,
},
limitations: [
"No .eh_frame section or PT_GNU_EH_FRAME segment was declared.",
"No .eh_frame_hdr section or PT_GNU_EH_FRAME segment was declared.",
"CFA instructions are counted but not evaluated.",
".debug_frame is absent; only .eh_frame was examined.",
"Symbol names, section names, and augmentation strings are target-derived and untrusted.",
],
};
const parsed = (
bytes: Buffer,
raw: Readonly<Record<string, unknown>> = {},
): ElfUnwindRanges => {
const input = inspectElfUnwindRangesInputSchema.parse({
path: "/artifacts/unwind.elf",
...raw,
});
return parseElfUnwindRanges(
bytes,
{
path: input.path,
sha256: "a".repeat(64),
bytes: bytes.length,
},
input,
);
};
const accept = async (
value: ElfUnwindRanges,
raw: Readonly<Record<string, unknown>> = {},
) => {
const input = inspectElfUnwindRangesInputSchema.parse({
path: value.artifact.path,
...raw,
});
return new ElfUnwindRangesService({
identity,
inspect: () => Promise.resolve(ok(value)),
}).inspect(input);
};
it("rejects a relative path and extra arguments before reading", async () => {
let calls = 0;
const service = new ElfUnwindRangesService({
identity,
inspect: () => {
calls += 1;
return Promise.resolve(ok(report));
},
});
const relative = await service.inspect({ path: "app" });
const extra = await service.inspect({
path: report.artifact.path,
extra: true,
});
expect(relative.ok).toBe(false);
expect(extra.ok).toBe(false);
if (!relative.ok) expect(relative.error).toBeInstanceOf(AnalysisInputError);
if (!extra.ok) expect(extra.error).toBeInstanceOf(AnalysisInputError);
expect(calls).toBe(0);
});
it("records an absent unwind table for the selected ELF", async () => {
const result = await accept(report);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
confidence: "observed",
subject: { format: "elf", architecture: "x86_64" },
normalized_result: report,
});
expect(result.value.locations).toEqual([
{ kind: "artifact-path", path: report.artifact.path },
]);
});
it.each([
["elf64 mismatch", elfUnwindFixture()],
["elf64 agreement", elfUnwindFixture({ header: "match" })],
[
"elf32 big-endian",
elfUnwindFixture({ bits: 32, little: false, machine: 20, header: "match" }),
],
["sectionless", elfUnwindSectionlessFixture()],
["undecodable header pointer", undecodableHeaderPointer()],
["absent", elfUnwindAbsentFixture()],
["truncated", elfUnwindFixture({ truncate: true })],
["trailing", elfUnwindFixture({ trailingByte: true, header: "match" })],
["no header", elfUnwindFixture({ header: "absent" })],
["version 3", elfUnwindFixture({ version3: true, header: "match" })],
["dynsym", elfUnwindFixture({ symbolSource: "dynsym", header: "match" })],
["no symbols", elfUnwindFixture({ symbolSource: "none", header: "match" })],
[
"NOBITS .debug_frame",
elfUnwindFixture({
header: "match",
backing: { section: ".debug_frame", kind: "nobits" },
}),
],
[
".debug_frame past end of file",
elfUnwindFixture({
backing: { section: ".debug_frame", kind: "past-eof" },
}),
],
[
".eh_frame past end of file",
elfUnwindFixture({
header: "match",
backing: { section: ".eh_frame", kind: "past-eof" },
}),
],
[
"NOBITS .eh_frame",
elfUnwindFixture({ backing: { section: ".eh_frame", kind: "nobits" } }),
],
[
"NOBITS .eh_frame_hdr",
elfUnwindFixture({ backing: { section: ".eh_frame_hdr", kind: "nobits" } }),
],
[
".eh_frame_hdr past end of file",
elfUnwindFixture({
backing: { section: ".eh_frame_hdr", kind: "past-eof" },
}),
],
[
"64-bit .eh_frame lengths",
elfUnwindFixture({ header: "match", extendedLength: true }),
],
[
"DT_PLTGOT datarel",
elfUnwindFixture({ header: "match", datarel: "dynamic" }),
],
[
"overstated .eh_frame_hdr fde_count",
elfUnwindFixture({ header: "match", headerCount: 0x7fffffff }),
],
] as const)("accepts parser output for %s", async (_label, bytes) => {
const value = parsed(bytes);
const result = await accept(value);
expect(result.ok, _label).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toEqual(value);
});
it("accepts a paged parser report without changing coverage", async () => {
const value = parsed(elfUnwindFixture(), { offset: 1, limit: 1 });
const result = await accept(value, { offset: 1, limit: 1 });
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
page: { offset: 1, limit: 1, returned: 1, total: 2, next_offset: null },
coverage: { total_ranges: 2, ranges_with_symbols: 1 },
});
});
it("bounds CIE Evidence locations by the page, not by the CIE count", async () => {
const value = parsed(elfUnwindFixture({ extraCies: 500 }), {
offset: 1,
limit: 1,
});
expect(value.coverage.total_cies).toBe(502);
const result = await accept(value, { offset: 1, limit: 1 });
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
cies: [{ index: 1 }],
});
// Artifact path, .eh_frame, .eh_frame_hdr, .debug_frame, one CIE, one FDE.
expect(result.value.locations).toHaveLength(6);
});
it("rejects a page that returns a CIE none of its ranges name", async () => {
const full = parsed(elfUnwindFixture({ extraCies: 2 }));
const page = parsed(elfUnwindFixture({ extraCies: 2 }), {
offset: 1,
limit: 1,
});
const extra = full.cies[0];
if (extra === undefined) throw new Error("fixture has no CIE");
const result = await accept(
{ ...page, cies: [extra, ...page.cies] },
{ offset: 1, limit: 1 },
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("accepts an FDE with a zero LSDA under a CIE that declares an LSDA encoding", async () => {
const value = parsed(elfUnwindFixture({ zeroLsda: true }));
expect(value.cies[1]?.lsda_encoding?.raw).toBe(0x1b);
expect(value.ranges[1]?.lsda).toBeNull();
const result = await accept(value);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
ranges: [{ lsda: null }, { lsda: null }],
});
});
it("accepts a header that declares a count but omits its search table", async () => {
const bytes = elfUnwindFixture({ header: "match" });
const shoff = Number(bytes.readBigUInt64LE(40));
const sections = bytes.readUInt16LE(60);
const names = Number(
bytes.readBigUInt64LE(shoff + bytes.readUInt16LE(62) * 64 + 24),
);
for (let index = 1; index < sections; index += 1) {
const at = shoff + index * 64;
const nameAt = names + bytes.readUInt32LE(at);
if (
bytes.toString("latin1", nameAt, bytes.indexOf(0, nameAt)) ===
".eh_frame_hdr"
)
bytes[Number(bytes.readBigUInt64LE(at + 24)) + 3] = 0xff;
}
const value = parsed(bytes);
expect(value.eh_frame_hdr).toMatchObject({
status: "present",
fde_count: 2,
table_encoding: { raw: 0xff },
});
const result = await accept(value);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
coverage: { status: "complete", eh_frame_hdr_agreement: "unavailable" },
});
});
it("accepts a null personality stored under an indirect encoding", async () => {
const value = parsed(elfUnwindFixture({ nullPersonality: true }));
expect(value.cies[1]?.personality).toMatchObject({
address: "0x0",
indirect: false,
encoding: { raw: 0x9b },
});
const result = await accept(value);
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
ranges: [{ personality: null }, { personality: { address: "0x0" } }],
});
});
it("rejects a direct personality reported as indirect", async () => {
const value = parsed(elfUnwindFixture({ nullPersonality: true }));
const cie = value.cies[1];
if (cie?.personality == null) throw new Error("fixture has no personality");
cie.personality.encoding = { raw: 0x1b, name: "pcrel|sdata4" };
cie.personality.indirect = true;
const result = await accept(value);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it.each([
[
"symbol totals",
(value: ElfUnwindRanges) => {
value.coverage.ranges_with_symbols += 1;
},
],
[
"range outside the file",
(value: ElfUnwindRanges) => {
value.ranges[0]!.location.offset = value.artifact.bytes;
},
],
[
"short page",
(value: ElfUnwindRanges) => {
value.ranges.pop();
value.page.returned = 1;
value.page.next_offset = 1;
},
],
[
"agreement without the mismatch limitation",
(value: ElfUnwindRanges) => {
value.limitations = value.limitations.filter(
(text) => !text.includes("does not match"),
);
},
],
] as const)("rejects parser output with %s", async (_label, mutate) => {
const value = structuredClone(parsed(elfUnwindFixture()));
mutate(value);
const result = await accept(value);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("reports a header capped by max_ranges as an incomplete Result", async () => {
const value = parsed(elfUnwindFixture({ header: "duplicate-row" }), {
max_ranges: 2,
});
const result = await accept(value, { max_ranges: 2 });
expect(result.ok).toBe(true);
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
eh_frame_hdr: { status: "incomplete", fde_count: 3, table_entries: 2 },
coverage: { status: "incomplete", eh_frame_hdr_agreement: "unavailable" },
});
});
it("rejects header table entries beyond the max_ranges budget", async () => {
const value = structuredClone(
parsed(elfUnwindFixture({ header: "duplicate-row" }), { max_ranges: 2 }),
);
value.eh_frame_hdr.table_entries = 3;
const result = await accept(value, { max_ranges: 2 });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("rejects a report whose artifact path is not the selected file", async () => {
const value = structuredClone(parsed(elfUnwindFixture()));
value.artifact.path = "/artifacts/other";
const result = await new ElfUnwindRangesService({
identity,
inspect: () => Promise.resolve(ok(value)),
}).inspect({ path: "/artifacts/unwind.elf" });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("rejects a report that fails the output schema", async () => {
const value = structuredClone(report);
value.format = "elf128" as ElfUnwindRanges["format"];
expect(elfUnwindRangesSchema.safeParse(value).success).toBe(false);
const result = await accept(value);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("discards an observation if the caller cancels while the provider completes", async () => {
const controller = new AbortController();
const service = new ElfUnwindRangesService({
identity,
inspect: () => {
controller.abort();
return Promise.resolve(ok(report));
},
});
const result = await service.inspect(
{ path: report.artifact.path },
{ signal: controller.signal },
);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisCancelledError);
});
@@ -0,0 +1,399 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { ElfUnwindRangesPort } from "./ElfUnwindRangesPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { elfObjectTypeName } from "../../domain/native/elfNotes.js";
import {
ELF_UNWIND_LIMITATIONS,
elfEhPointerEncodingName,
inspectElfUnwindRangesInputSchema,
elfUnwindRangesSchema,
MAX_INSPECT_ELF_UNWIND_RANGES,
type ElfUnwindRanges,
} from "../../domain/native/elfUnwindRanges.js";
import { BINARY_ARCHITECTURES } from "../../domain/binaryTargetTypes.js";
import { elfArchitecture } from "../../domain/elfFixedHeader.js";
import { err, type Result } from "../../domain/result.js";
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
import { parseAnalysisInput } from "../AnalysisInput.js";
const OPERATION = "inspect_elf_unwind_ranges";
const {
cfa: CFA_LIMITATION,
untrusted: UNTRUSTED_LIMITATION,
indirect: INDIRECT_LIMITATION,
headerMismatch: HEADER_MISMATCH,
frameAbsent: FRAME_ABSENT,
headerAbsent: HEADER_ABSENT,
debugPresent: DEBUG_PRESENT,
debugAbsent: DEBUG_ABSENT,
debugUnknown: DEBUG_UNKNOWN,
debugOutside: DEBUG_OUTSIDE,
} = ELF_UNWIND_LIMITATIONS;
type Range = { readonly offset: number; readonly bytes: number };
type Encoding = { readonly raw: number; readonly name: string };
/** Shared caller validation, output parsing and Evidence provenance for CLI/MCP. */
export class ElfUnwindRangesService {
constructor(readonly provider: ElfUnwindRangesPort) {}
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const input = parseAnalysisInput(
OPERATION,
rawInput,
inspectElfUnwindRangesInputSchema,
options?.signal,
);
if (!input.ok) return input;
const result = await this.provider.inspect(input.value, options);
if (!result.ok) return result;
const report = elfUnwindRangesSchema.safeParse(result.value);
if (
!report.success ||
report.data.artifact.path !== input.value.path ||
!validReport(
report.data,
input.value.max_ranges,
input.value.max_file_bytes,
input.value.offset,
input.value.limit,
)
)
return err(
new AnalysisOutputError(
OPERATION,
"ELF unwind provider returned malformed output or changed artifact identity.",
),
);
const value = report.data;
const architecture = BINARY_ARCHITECTURES.find(
(supported) => supported === elfArchitecture(value.machine),
);
const locations = [
{ kind: "artifact-path" as const, path: value.artifact.path },
...rangesOf(value).map((range) => ({
kind: "file-offset-range" as const,
start: range.offset,
end: range.offset + range.bytes,
})),
];
return completeProviderEvidence(
createEvidence(
{
path: value.artifact.path,
format: "elf",
sha256: value.artifact.sha256,
...(architecture === undefined ? {} : { architecture }),
},
this.provider.identity,
{
operation: OPERATION,
parameters: input.value,
result: value,
confidence: "observed",
limitations: value.limitations,
locations,
},
),
options?.signal,
);
}
}
const inside =
(fileBytes: number) =>
(range: Range): boolean =>
range.bytes <= fileBytes && range.offset <= fileBytes - range.bytes;
const rangesOf = (report: ElfUnwindRanges): Range[] => {
const found: Range[] = [];
const add = (range: Range | null): void => {
if (range !== null) found.push(range);
};
add(report.eh_frame.location);
add(report.eh_frame_hdr.location);
add(report.debug_frame.location);
for (const cie of report.cies) add(cie.location);
for (const range of report.ranges) add(range.location);
return found;
};
const encodingOk = (encoding: Encoding | null): boolean =>
encoding === null || encoding.name === elfEhPointerEncodingName(encoding.raw);
const has = (report: ElfUnwindRanges, text: string): boolean =>
report.limitations.includes(text);
const frameOk = (report: ElfUnwindRanges): boolean => {
const frame = report.eh_frame;
if (frame.status === "absent" || frame.status === "unknown") {
if (
frame.source !== null ||
frame.location !== null ||
report.cies.length !== 0 ||
report.coverage.total_cies !== 0 ||
report.coverage.total_ranges !== 0
)
return false;
if (frame.status === "unknown")
return report.coverage.status === "incomplete";
return has(report, FRAME_ABSENT);
}
if (frame.status === "present")
return frame.source !== null && frame.location !== null;
return (
report.coverage.status === "incomplete" &&
(frame.location === null || frame.source !== null)
);
};
const headerOk = (report: ElfUnwindRanges, maxRanges: number): boolean => {
const header = report.eh_frame_hdr;
const encodings = [
header.eh_frame_pointer_encoding,
header.fde_count_encoding,
header.table_encoding,
];
// A declared fde_count may exceed the budget, but decoded rows never may.
if (!encodings.every(encodingOk) || header.table_entries > maxRanges)
return false;
if (header.status === "absent" || header.status === "unknown") {
if (
header.location !== null ||
header.version !== null ||
header.eh_frame_pointer !== null ||
header.fde_count !== null ||
header.table_entries !== 0 ||
encodings.some((encoding) => encoding !== null) ||
report.coverage.eh_frame_hdr_agreement !== "unavailable"
)
return false;
return (
header.status === "unknown" ||
report.eh_frame.status === "unknown" ||
has(report, HEADER_ABSENT)
);
}
if (header.status === "incomplete")
return (
report.coverage.status === "incomplete" &&
report.coverage.eh_frame_hdr_agreement === "unavailable" &&
(header.fde_count === null || header.table_entries <= header.fde_count)
);
if (
header.location === null ||
header.version !== 1 ||
header.eh_frame_pointer === null ||
encodings.some((encoding) => encoding === null)
)
return false;
// A header whose count encoding is DW_EH_PE_omit carries no search table.
if (header.fde_count_encoding?.raw === 0xff)
return (
header.fde_count === null &&
header.table_entries === 0 &&
report.coverage.eh_frame_hdr_agreement === "unavailable"
);
// A header may declare a count but omit its search table.
if (header.table_encoding?.raw === 0xff)
return (
header.fde_count !== null &&
header.table_entries === 0 &&
report.coverage.eh_frame_hdr_agreement === "unavailable"
);
if (
header.fde_count === null ||
header.table_entries !== header.fde_count ||
encodings.some((encoding) => encoding === null)
)
return false;
if (report.coverage.eh_frame_hdr_agreement === "agree")
return !has(report, HEADER_MISMATCH);
if (report.coverage.eh_frame_hdr_agreement === "disagree")
return has(report, HEADER_MISMATCH);
return false;
};
const debugOk = (report: ElfUnwindRanges): boolean => {
const debug = report.debug_frame;
if (debug.status === "present")
return debug.location !== null && has(report, DEBUG_PRESENT);
if (debug.location !== null) return false;
if (debug.status === "incomplete")
return (
report.coverage.status === "incomplete" && has(report, DEBUG_OUTSIDE)
);
return has(report, debug.status === "absent" ? DEBUG_ABSENT : DEBUG_UNKNOWN);
};
// The page returns exactly the CIEs its ranges name, in ascending index order,
// so CIE output is bounded by the page size rather than by max_ranges.
const cieOk = (report: ElfUnwindRanges): boolean => {
const named = new Set(report.ranges.map((range) => range.cie_index));
if (report.cies.length !== named.size) return false;
let previous = -1;
for (const cie of report.cies) {
if (
!named.has(cie.index) ||
cie.index <= previous ||
cie.index >= report.coverage.total_cies ||
!cieEncodingsOk(cie)
)
return false;
previous = cie.index;
}
return true;
};
const cieEncodingsOk = (cie: ElfUnwindRanges["cies"][number]): boolean =>
encodingOk(cie.pointer_encoding) &&
encodingOk(cie.lsda_encoding) &&
(cie.personality === null ||
(encodingOk(cie.personality.encoding) &&
personalityIndirectOk(cie.personality)));
/**
* Only an indirect encoding yields an indirect personality, but a raw zero is
* a null pointer the decoder never dereferences, so it stays direct.
*/
const personalityIndirectOk = (
personality: NonNullable<ElfUnwindRanges["cies"][number]["personality"]>,
): boolean => {
const indirectEncoding = (personality.encoding.raw & 0x80) !== 0;
return personality.indirect
? indirectEncoding
: !indirectEncoding || personality.address === "0x0";
};
/** `end` is `start + size` wrapped at the ELF address width, as libgcc computes it. */
const addressSpan = (
bits: 32 | 64,
start: string,
end: string,
size: string,
): boolean => {
const length = BigInt(size);
return (
length < 1n << BigInt(bits) &&
BigInt(end) === BigInt.asUintN(bits, BigInt(start) + length)
);
};
const rangeOk = (report: ElfUnwindRanges): boolean => {
const byIndex = new Map(report.cies.map((cie) => [cie.index, cie]));
return report.ranges.every((range, position) => {
const cie = byIndex.get(range.cie_index);
if (cie === undefined || range.index !== report.page.offset + position)
return false;
if (
!addressSpan(
report.format === "elf32" ? 32 : 64,
range.start,
range.end,
range.size,
)
)
return false;
if (cie.personality === null)
return range.personality === null && lsdaOk(cie, range);
return (
range.personality !== null &&
range.personality.address === cie.personality.address &&
range.personality.indirect === cie.personality.indirect &&
lsdaOk(cie, range)
);
});
};
const lsdaOk = (
cie: ElfUnwindRanges["cies"][number],
range: ElfUnwindRanges["ranges"][number],
): boolean => {
// A CIE with an LSDA encoding still admits a zero (null) LSDA per FDE.
const encoding = cie.lsda_encoding;
return range.lsda === null || (encoding !== null && encoding.raw !== 0xff);
};
const pageOk = (report: ElfUnwindRanges): boolean => {
const { page, coverage, ranges } = report;
if (
page.total !== coverage.total_ranges ||
page.returned !== ranges.length ||
page.returned > page.limit
)
return false;
const available = page.offset >= page.total ? 0 : page.total - page.offset;
if (page.returned !== Math.min(page.limit, available)) return false;
const end = page.offset + page.returned;
if (page.returned === 0)
return page.offset >= page.total && page.next_offset === null;
if (end > page.total) return false;
return page.next_offset === (end >= page.total ? null : end);
};
const coverageOk = (report: ElfUnwindRanges, maxRanges: number): boolean => {
const { coverage, cies, ranges } = report;
const pageSymbols = ranges.filter((range) => range.symbol !== null).length;
if (
coverage.ranges_with_symbols + coverage.ranges_without_symbols !==
coverage.total_ranges ||
coverage.ranges_with_symbols > coverage.total_ranges ||
cies.length > ranges.length ||
coverage.total_cies > maxRanges ||
coverage.total_ranges > maxRanges ||
coverage.examined_records > maxRanges * 2 ||
coverage.examined_records < coverage.total_cies + coverage.total_ranges ||
pageSymbols > coverage.ranges_with_symbols ||
ranges.length - pageSymbols > coverage.ranges_without_symbols
)
return false;
if (report.page.offset === 0 && report.page.returned === report.page.total)
return pageSymbols === coverage.ranges_with_symbols;
return true;
};
const indirectVisible = (report: ElfUnwindRanges): boolean =>
report.cies.some((cie) => cie.personality?.indirect === true) ||
report.ranges.some(
(range) =>
range.lsda?.indirect === true || range.personality?.indirect === true,
);
const validReport = (
report: ElfUnwindRanges,
maxRanges: number,
maxBytes: number,
offset: number,
limit: number,
): boolean => {
if (maxRanges > MAX_INSPECT_ELF_UNWIND_RANGES) return false;
if (
report.artifact.bytes > maxBytes ||
report.type_name !== elfObjectTypeName(report.type) ||
report.page.offset !== offset ||
report.page.limit !== limit ||
!rangesOf(report).every(inside(report.artifact.bytes)) ||
!has(report, CFA_LIMITATION) ||
!has(report, UNTRUSTED_LIMITATION) ||
(indirectVisible(report) && !has(report, INDIRECT_LIMITATION))
)
return false;
return (
frameOk(report) &&
headerOk(report, maxRanges) &&
debugOk(report) &&
cieOk(report) &&
rangeOk(report) &&
pageOk(report) &&
coverageOk(report, maxRanges)
);
};
+46
View File
@@ -10,6 +10,7 @@ import {
createRecordedCrashService,
createBinaryLayoutService,
createElfNotesService,
createElfUnwindRangesService,
createAppleIpsService,
createDevicetreeService,
createKernelModuleService,
@@ -35,6 +36,7 @@ import { inspectPeImportsInputSchema } from "../domain/native/peImports.js";
import { inspectWindowsShortcutInputSchema } from "../domain/native/windowsShortcut.js";
import { inspectNativeExportsInputSchema } from "../domain/native/nativeExports.js";
import { inspectElfNotesInputSchema } from "../domain/native/elfNotes.js";
import { inspectElfUnwindRangesInputSchema } from "../domain/native/elfUnwindRanges.js";
import { inspectAppleIpsInputSchema } from "../domain/native/appleIps.js";
import { inspectKernelModuleInputSchema } from "../domain/native/kernelModule.js";
import { inspectKernelBuildConfigInputSchema } from "../domain/native/kernelBuildConfig.js";
@@ -92,6 +94,50 @@ export const registerBinaryDiagnosticsCommands = (
);
}),
});
cli.command(CLI_COMMANDS.inspectElfUnwindRanges, {
description:
"Inspect ELF unwind function ranges without executing the image",
args: z.object({
path: localPathStringSchema.describe("Local ELF32/ELF64 image"),
}),
options: z.object({
maxFileBytes: cliDecimalField(
inspectElfUnwindRangesInputSchema.shape.max_file_bytes,
),
maxRanges: cliDecimalField(
inspectElfUnwindRangesInputSchema.shape.max_ranges,
),
offset: cliDecimalField(inspectElfUnwindRangesInputSchema.shape.offset),
limit: cliDecimalField(inspectElfUnwindRangesInputSchema.shape.limit),
}),
run: ({ args, options }) =>
withCommandCancellation(async (signal) => {
const unwind = createElfUnwindRangesService();
return await logCliCommand(
logger,
CLI_COMMANDS.inspectElfUnwindRanges,
async () =>
finishCliEvidenceCommand(
args.path,
() =>
unwind.inspect(
{
path: absoluteCallerPath(args.path),
max_file_bytes: options.maxFileBytes,
max_ranges: options.maxRanges,
offset: options.offset,
limit: options.limit,
},
{ signal },
),
unwind,
"rea-elf-unwind-ranges",
"inspect_elf_unwind_ranges",
signal,
).then(projectCliAnalysisResult),
);
}),
});
cli.command(CLI_COMMANDS.inspectAppleIps, {
description:
"Inspect an Apple .ips crash report without executing a target",
+1
View File
@@ -83,6 +83,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectNativeExports: "inspect-native-exports",
inspectDevicetree: "inspect-devicetree",
inspectElfNotes: "inspect-elf-notes",
inspectElfUnwindRanges: "inspect-elf-unwind-ranges",
inspectAppleIps: "inspect-apple-ips",
inspectKernelModule: "inspect-kernel-module",
inspectKernelBuildConfig: "inspect-kernel-build-config",
+6
View File
@@ -18,6 +18,8 @@ import { WindowsShortcutService } from "../application/binaryDiagnostics/Windows
import { WindowsShortcutProvider } from "../native/windows/WindowsShortcutProvider.js";
import { ElfNotesService } from "../application/binaryDiagnostics/ElfNotesService.js";
import { ElfNotesProvider } from "../native/elf/ElfNotesProvider.js";
import { ElfUnwindRangesService } from "../application/binaryDiagnostics/ElfUnwindRangesService.js";
import { ElfUnwindRangesProvider } from "../native/elf/ElfUnwindRangesProvider.js";
import { AppleIpsService } from "../application/binaryDiagnostics/AppleIpsService.js";
import { AppleIpsProvider } from "../native/apple/AppleIpsProvider.js";
import { KernelModuleService } from "../application/binaryDiagnostics/KernelModuleService.js";
@@ -58,6 +60,10 @@ export const createNativeExportsService = (): NativeExportsService =>
export const createElfNotesService = (): ElfNotesService =>
new ElfNotesService(new ElfNotesProvider());
/** Portable ELF unwind-range inspection with no engine or disassembler. */
export const createElfUnwindRangesService = (): ElfUnwindRangesService =>
new ElfUnwindRangesService(new ElfUnwindRangesProvider());
/** Portable Apple .ips inspection with no engine, Xcode or target acquisition. */
export const createAppleIpsService = (): AppleIpsService =>
new AppleIpsService(new AppleIpsProvider());
@@ -30,6 +30,7 @@ import {
BYTE_ENTROPY_PROVIDER,
DEVICETREE_PROVIDER,
ELF_NOTES_PROVIDER,
ELF_UNWIND_RANGES_PROVIDER,
HARMONY_APPLICATION_PROVIDER,
JAVASCRIPT_APPLICATION_PROVIDER,
JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER,
@@ -259,6 +260,13 @@ export const CAPABILITY_DECLARATIONS = {
elfNotes: {
providers: [providerBinding(ELF_NOTES_PROVIDER, ["inspect_elf_notes"])],
},
elfUnwindRanges: {
providers: [
providerBinding(ELF_UNWIND_RANGES_PROVIDER, [
"inspect_elf_unwind_ranges",
]),
],
},
erlangBeam: {
providers: [
providerBinding(ERLANG_BEAM_PROVIDER_IDENTITY, {
+2
View File
@@ -81,6 +81,7 @@ import {
pwntoolsHostSupported,
createDevicetreeService,
createElfNotesService,
createElfUnwindRangesService,
createAppleIpsService,
createKernelModuleService,
createKernelBuildConfigService,
@@ -361,6 +362,7 @@ const modules = {
nativeExports: service(() => createNativeExportsService()),
devicetree: service(() => createDevicetreeService()),
elfNotes: service(() => createElfNotesService()),
elfUnwindRanges: service(() => createElfUnwindRangesService()),
appleIps: service(() => createAppleIpsService()),
kernelModule: service(() => createKernelModuleService()),
kernelBuildConfig: service(() => createKernelBuildConfigService()),
@@ -52,6 +52,10 @@ import {
inspectElfNotesInputSchema,
elfNotesSchema,
} from "../../domain/native/elfNotes.js";
import {
inspectElfUnwindRangesInputSchema,
elfUnwindRangesSchema,
} from "../../domain/native/elfUnwindRanges.js";
import {
inspectAppleIpsInputSchema,
appleIpsSchema,
@@ -148,6 +152,21 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
},
],
},
{
name: "inspect_elf_unwind_ranges",
...toolContractMetadata("inspect_elf_unwind_ranges"),
kind: "native-provider",
description:
"Inspect one explicit local ELF32/ELF64 image's .eh_frame and .eh_frame_hdr without executing it or opening a disassembler. Returns a page of FDE function ranges with start, end, size, containing section, exact symbol name when one exists, CIE index, LSDA, and personality, plus version, augmentation, alignments, return-address register, and pointer encoding for only the CIEs those ranges name, with a total CIE count in coverage. Coverage counts ranges that match a symbol, ranges without a symbol, and whether the .eh_frame_hdr search table agrees with the decoded FDEs. .debug_frame is reported present, absent, or incomplete and is not decoded. A missing unwind table is observed absence of those declarations, not proof the image has no functions. Truncated records stay incomplete coverage. Reads a stable regular file; malformed ELF headers and exhausted CIE or FDE budgets return no partial success. CFA instructions are counted and not evaluated. Indirect EH pointers are not dereferenced. Portable on supported Node hosts.",
inputSchema: inspectElfUnwindRangesInputSchema,
outputSchema: evidenceResultOf(elfUnwindRangesSchema),
examples: [
{
title: "List function ranges from ELF unwind tables",
input: { path: "/artifacts/program" },
},
],
},
{
name: "inspect_apple_ips",
...toolContractMetadata("inspect_apple_ips"),
+1
View File
@@ -293,6 +293,7 @@ const TOOL_EFFECT_AUDIT: Readonly<Record<string, EffectAudit>> = {
inspect_windows_shortcut: evidence,
inspect_native_exports: evidence,
inspect_elf_notes: evidence,
inspect_elf_unwind_ranges: evidence,
inspect_apple_ips: evidence,
inspect_devicetree: evidence,
inspect_kernel_module: evidence,
+1
View File
@@ -33,6 +33,7 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_pe_resources"
| "inspect_pe_certificates"
| "inspect_elf_notes"
| "inspect_elf_unwind_ranges"
| "inspect_devicetree"
| "inspect_api_contract"
| "inspect_playwright_trace"
+7
View File
@@ -60,6 +60,13 @@ export const ELF_NOTES_PROVIDER = Object.freeze({
version: "1",
} as const);
/** Provider identity for portable, execution-free ELF unwind-table decoding. */
export const ELF_UNWIND_RANGES_PROVIDER = Object.freeze({
id: "rea-elf-unwind-ranges",
name: "REA ELF unwind range parser",
version: "1",
} as const);
/** Provider identity for portable, execution-free Apple .ips crash-report decoding. */
export const APPLE_IPS_PROVIDER = Object.freeze({
id: "rea-apple-ips",
+75
View File
@@ -0,0 +1,75 @@
import { expect, it } from "vitest";
import {
elfEhPointerEncodingName,
elfUnwindRangesSchema,
inspectElfUnwindRangesInputSchema,
} from "./elfUnwindRanges.js";
it("names DW_EH_PE encodings without dropping application or indirect bits", () => {
expect(elfEhPointerEncodingName(0x1b)).toBe("pcrel|sdata4");
expect(elfEhPointerEncodingName(0x9b)).toBe("pcrel|sdata4|indirect");
expect(elfEhPointerEncodingName(0x3b)).toBe("datarel|sdata4");
expect(elfEhPointerEncodingName(0x03)).toBe("udata4");
expect(elfEhPointerEncodingName(0)).toBe("absptr");
expect(elfEhPointerEncodingName(0xff)).toBe("omit");
});
it("rejects extra caller arguments and admits an empty unwind inventory", () => {
expect(
inspectElfUnwindRangesInputSchema.safeParse({
path: "/artifacts/app",
extra: true,
}).success,
).toBe(false);
const parsed = inspectElfUnwindRangesInputSchema.parse({
path: "/artifacts/app",
});
expect(parsed.max_ranges).toBe(8192);
expect(parsed.limit).toBe(256);
const report = elfUnwindRangesSchema.parse({
artifact: {
path: "/artifacts/app",
sha256: "a".repeat(64),
bytes: 512,
},
format: "elf64",
byte_order: "little",
machine: 62,
type: 3,
type_name: "shared",
eh_frame: { status: "absent", source: null, location: null },
eh_frame_hdr: {
status: "absent",
location: null,
version: null,
eh_frame_pointer_encoding: null,
fde_count_encoding: null,
table_encoding: null,
eh_frame_pointer: null,
fde_count: null,
table_entries: 0,
},
debug_frame: { status: "absent", location: null },
cies: [],
ranges: [],
page: {
offset: 0,
limit: 256,
returned: 0,
total: 0,
next_offset: null,
},
coverage: {
status: "complete",
total_ranges: 0,
total_cies: 0,
ranges_with_symbols: 0,
ranges_without_symbols: 0,
eh_frame_hdr_agreement: "unavailable",
examined_records: 0,
},
limitations: ["CFA instructions are counted but not evaluated."],
});
expect(report.ranges).toEqual([]);
expect(report.coverage.total_ranges).toBe(0);
});
+239
View File
@@ -0,0 +1,239 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { ELF_OBJECT_TYPE_NAMES } from "./elfNotes.js";
const uint = z.number().int().min(0).max(0xffffffff);
const hexAddress = z.string().regex(/^0x[0-9a-f]+$/u);
const decimalSize = z.string().regex(/^(?:0|[1-9][0-9]*)$/u);
const range = z.strictObject({ offset: uint, bytes: uint });
/** Hard ceiling on the caller-selected input read budget. */
export const MAX_INSPECT_ELF_UNWIND_FILE_BYTES = 536870912;
/** Hard ceiling on decoded CIE records and, separately, on decoded FDEs. */
export const MAX_INSPECT_ELF_UNWIND_RANGES = 65536;
/** Hard ceiling on one returned page of FDE ranges. */
export const MAX_INSPECT_ELF_UNWIND_PAGE = 4096;
/** Hard ceiling on symbol-table entries scanned, across all tables, for exact-start names. */
export const MAX_ELF_UNWIND_SYMBOLS = 65536;
/** Fixed allowance on symbol-name text decoded for one returned page. */
export const MAX_ELF_UNWIND_SYMBOL_TEXT_BYTES = 16 * 1024 * 1024;
/**
* Limitation texts the parser emits and the application layer checks for.
* One owner keeps the producer and the report validation in step.
*/
export const ELF_UNWIND_LIMITATIONS = {
cfa: "CFA instructions are counted but not evaluated.",
untrusted:
"Symbol names, section names, and augmentation strings are target-derived and untrusted.",
indirect: "Indirect EH pointers were not dereferenced.",
headerMismatch:
"The .eh_frame_hdr binary search table does not match the decoded FDEs.",
frameAbsent: "No .eh_frame section or PT_GNU_EH_FRAME segment was declared.",
headerAbsent:
"No .eh_frame_hdr section or PT_GNU_EH_FRAME segment was declared.",
debugPresent: ".debug_frame is present and was not decoded.",
debugAbsent: ".debug_frame is absent; only .eh_frame was examined.",
debugUnknown: ".debug_frame presence is unknown.",
debugOutside:
".debug_frame is declared but its bytes are not in the file; it was not examined.",
} as const;
const FORMAT_NAMES: Readonly<Record<number, string>> = {
0: "absptr",
1: "uleb128",
2: "udata2",
3: "udata4",
4: "udata8",
9: "sleb128",
0x0a: "sdata2",
0x0b: "sdata4",
0x0c: "sdata8",
};
const APPLICATION_NAMES: Readonly<Record<number, string>> = {
0x10: "pcrel",
0x20: "textrel",
0x30: "datarel",
0x40: "funcrel",
0x50: "aligned",
};
/** DW_EH_PE name such as `pcrel|sdata4` or `pcrel|sdata4|indirect`. */
export const elfEhPointerEncodingName = (raw: number): string => {
const encoding = raw & 0xff;
if (encoding === 0xff) return "omit";
const format =
FORMAT_NAMES[encoding & 0x0f] ?? `unknown${(encoding & 0x0f).toString(16)}`;
const application = encoding & 0x70;
const parts: string[] = [];
if (application !== 0)
parts.push(
APPLICATION_NAMES[application] ?? `unknown${application.toString(16)}`,
);
parts.push(format);
if ((encoding & 0x80) !== 0) parts.push("indirect");
return parts.join("|");
};
const untrustedText = z.strictObject({
text: z.string().min(1),
trust: z.literal("untrusted"),
});
const untrustedAugmentation = z.strictObject({
text: z.string(),
trust: z.literal("untrusted"),
});
const encodingSchema = z.strictObject({
raw: z.number().int().min(0).max(255),
name: z.string().min(1),
});
const tableStatus = z.enum(["present", "absent", "incomplete", "unknown"]);
/** Caller-selected page of ELF unwind function ranges. */
export const inspectElfUnwindRangesInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF image",
),
max_file_bytes: z
.number()
.int()
.min(64)
.max(MAX_INSPECT_ELF_UNWIND_FILE_BYTES)
.default(67108864)
.describe("Maximum stable artifact bytes to read (default 64 MiB)"),
max_ranges: z
.number()
.int()
.min(1)
.max(MAX_INSPECT_ELF_UNWIND_RANGES)
.default(8192)
.describe(
"Maximum CIE records and, separately, maximum FDEs to decode; exceeding either budget fails without partial success",
),
offset: z
.number()
.int()
.min(0)
.max(0xffffffff)
.default(0)
.describe("Zero-based index of the first FDE range to return"),
limit: z
.number()
.int()
.min(1)
.max(MAX_INSPECT_ELF_UNWIND_PAGE)
.default(256)
.describe("Maximum FDE ranges to return in this page"),
});
const cieSchema = z.strictObject({
index: uint,
version: z.union([z.literal(1), z.literal(3)]),
augmentation: untrustedAugmentation,
code_alignment: z.number().int().nonnegative(),
data_alignment: z.number().int(),
return_address_register: z.number().int().nonnegative(),
pointer_encoding: encodingSchema,
lsda_encoding: encodingSchema.nullable(),
personality: z
.strictObject({
address: hexAddress,
encoding: encodingSchema,
indirect: z.boolean(),
})
.nullable(),
signal_frame: z.boolean(),
b_key: z.boolean(),
instruction_bytes: uint,
location: range,
});
const functionRangeSchema = z.strictObject({
index: uint,
start: hexAddress,
end: hexAddress,
size: decimalSize,
section: untrustedText.nullable(),
symbol: untrustedText.nullable(),
cie_index: uint,
lsda: z
.strictObject({
address: hexAddress,
indirect: z.boolean(),
})
.nullable(),
personality: z
.strictObject({
address: hexAddress,
indirect: z.boolean(),
})
.nullable(),
location: range,
});
/** Observed .eh_frame function ranges. Truncation is incomplete, not absence. */
export const elfUnwindRangesSchema = z.strictObject({
artifact: z.strictObject({
path: z.string().min(1),
sha256: digestSchema,
bytes: uint,
}),
format: z.enum(["elf32", "elf64"]),
byte_order: z.enum(["little", "big"]),
machine: uint,
type: uint,
type_name: z.enum(ELF_OBJECT_TYPE_NAMES),
eh_frame: z.strictObject({
status: tableStatus,
source: z.enum(["section", "program"]).nullable(),
location: range.nullable(),
}),
eh_frame_hdr: z.strictObject({
status: tableStatus,
location: range.nullable(),
version: uint.nullable(),
eh_frame_pointer_encoding: encodingSchema.nullable(),
fde_count_encoding: encodingSchema.nullable(),
table_encoding: encodingSchema.nullable(),
eh_frame_pointer: hexAddress.nullable(),
fde_count: uint.nullable(),
table_entries: uint,
}),
debug_frame: z.strictObject({
/** `incomplete`: declared, but NOBITS or outside the file. */
status: z.enum(["present", "absent", "incomplete", "unknown"]),
location: range.nullable(),
}),
/** Decoded CIEs named by this page's ranges, in index order. */
cies: z.array(cieSchema),
ranges: z.array(functionRangeSchema),
page: z.strictObject({
offset: uint,
limit: uint,
returned: uint,
total: uint,
next_offset: uint.nullable(),
}),
coverage: z.strictObject({
status: z.enum(["complete", "incomplete"]),
total_ranges: uint,
/** Every decoded CIE, including ones this page does not return. */
total_cies: uint,
ranges_with_symbols: uint,
ranges_without_symbols: uint,
eh_frame_hdr_agreement: z.enum(["agree", "disagree", "unavailable"]),
examined_records: uint,
}),
limitations: z.array(z.string()),
});
export type ElfUnwindRanges = z.infer<typeof elfUnwindRangesSchema>;
export type InspectElfUnwindRangesInput = z.infer<
typeof inspectElfUnwindRangesInputSchema
>;
+1 -1
View File
@@ -6,5 +6,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "61",
skillVersion: "62",
} as const;
+43
View File
@@ -0,0 +1,43 @@
import { expect, it } from "vitest";
import { buildIntervalIndex } from "./ElfIntervalIndex.js";
it("returns the preferred overlapping interval and nothing in gaps", () => {
const lookup = buildIntervalIndex(
[
{ low: 0n, high: 100n, value: "wide" },
{ low: 10n, high: 20n, value: "narrow" },
{ low: 200n, high: 210n, value: "far" },
{ low: 5n, high: 5n, value: "empty" },
],
(left, right) =>
left === "narrow"
? -1
: right === "narrow"
? 1
: left.localeCompare(right),
);
expect(lookup(0n)).toBe("wide");
expect(lookup(9n)).toBe("wide");
expect(lookup(10n)).toBe("narrow");
expect(lookup(19n)).toBe("narrow");
expect(lookup(20n)).toBe("wide");
expect(lookup(99n)).toBe("wide");
expect(lookup(100n)).toBeUndefined();
expect(lookup(205n)).toBe("far");
expect(lookup(210n)).toBeUndefined();
expect(lookup(-1n)).toBeUndefined();
});
it("answers many lookups over many overlapping intervals", () => {
const intervals = Array.from({ length: 65535 }, (_, index) => ({
low: BigInt(index * 16),
high: BigInt(index * 16 + 32),
value: index,
}));
const lookup = buildIntervalIndex(intervals, (left, right) => left - right);
expect(lookup(0n)).toBe(0);
expect(lookup(16n)).toBe(0);
expect(lookup(32n)).toBe(1);
expect(lookup(BigInt(65534 * 16 + 31))).toBe(65534);
});
+80
View File
@@ -0,0 +1,80 @@
/** One half-open `[low, high)` range owned by `value`. */
export interface IndexedInterval<T> {
readonly low: bigint;
readonly high: bigint;
readonly value: T;
}
const compareBig = (left: bigint, right: bigint): number =>
left < right ? -1 : left > right ? 1 : 0;
/** First index whose boundary is greater than `key`. */
const upperBound = (boundaries: readonly bigint[], key: bigint): number => {
let low = 0;
let high = boundaries.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (boundaries[middle]! <= key) low = middle + 1;
else high = middle;
}
return low;
};
/** First index whose boundary is at least `key`. */
const lowerBound = (boundaries: readonly bigint[], key: bigint): number => {
let low = 0;
let high = boundaries.length;
while (low < high) {
const middle = (low + high) >>> 1;
if (boundaries[middle]! < key) low = middle + 1;
else high = middle;
}
return low;
};
/**
* Builds a lookup that returns, for any key, the highest-priority interval
* containing it (`prefer(a, b) < 0` means `a` wins). Overlaps are resolved
* once at build time, so each lookup is a binary search instead of a scan of
* every interval.
*/
export const buildIntervalIndex = <T>(
intervals: readonly IndexedInterval<T>[],
prefer: (left: T, right: T) => number,
): ((key: bigint) => T | undefined) => {
const usable = intervals.filter((interval) => interval.high > interval.low);
const boundaries = [
...new Set(usable.flatMap((interval) => [interval.low, interval.high])),
].sort(compareBig);
const segments = Math.max(0, boundaries.length - 1);
const owners: Array<T | undefined> = Array.from({ length: segments });
// next[i] is the first unpainted segment at or after i (path-compressed).
const next = Int32Array.from({ length: segments + 1 }, (_, index) => index);
const find = (index: number): number => {
let root = index;
while (next[root] !== root) root = next[root]!;
let cursor = index;
while (next[cursor] !== root) {
const following = next[cursor]!;
next[cursor] = root;
cursor = following;
}
return root;
};
const ordered = [...usable].sort((left, right) =>
prefer(left.value, right.value),
);
for (const interval of ordered) {
const last = lowerBound(boundaries, interval.high);
let segment = find(lowerBound(boundaries, interval.low));
while (segment < last) {
owners[segment] = interval.value;
next[segment] = segment + 1;
segment = find(segment + 1);
}
}
return (key) => {
const segment = upperBound(boundaries, key) - 1;
return segment < 0 || segment >= segments ? undefined : owners[segment];
};
};
+258
View File
@@ -0,0 +1,258 @@
import {
projectStableArtifactFailure,
stableArtifactInputRecovery,
projectArtifactCloseFailure,
} from "../../artifacts/StableArtifactFailure.js";
import { isSelectedRegularFileError } from "../../filesystem/RegularFile.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { readStableArtifact } from "../../artifacts/readStableArtifact.js";
import {
artifactFilePrimaryFacts,
type ArtifactFilePrimaryFacts,
artifactFileCancellationCause,
} from "../../artifacts/ArtifactFileOperation.js";
import { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { ElfUnwindRangesPort } from "../../application/binaryDiagnostics/ElfUnwindRangesPort.js";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import {
AnalysisAccessDeniedError,
AnalysisArtifactChangedError,
AnalysisCancelledError,
AnalysisInputError,
AnalysisResourceConstraintError,
AnalysisUnsupportedTargetError,
} from "../../domain/analysisErrorCore.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import {
MAX_INSPECT_ELF_UNWIND_FILE_BYTES,
MAX_INSPECT_ELF_UNWIND_RANGES,
type InspectElfUnwindRangesInput,
} from "../../domain/native/elfUnwindRanges.js";
import { err, ok } from "../../domain/result.js";
import { ELF_UNWIND_RANGES_PROVIDER } from "../../domain/investigationProviders.js";
import {
BinaryFormatFailure,
BinaryResourceFailure,
} from "../metadata/BinaryContainer.js";
import {
ElfUnwindSymbolTextFailure,
parseElfUnwindRanges,
} from "./ElfUnwindTables.js";
const OPERATION = "inspect_elf_unwind_ranges";
/** Portable parser over one bounded, identity-checked regular file. */
export class ElfUnwindRangesProvider implements ElfUnwindRangesPort {
readonly identity = ELF_UNWIND_RANGES_PROVIDER;
readonly #resources = new ArtifactResourceScope();
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause: unknown) {
throw projectArtifactCloseFailure(
cause,
ELF_UNWIND_RANGES_PROVIDER.id,
OPERATION,
);
}
}
async inspect(
input: InspectElfUnwindRangesInput,
options?: ExecutionOptions,
) {
try {
return await this.#resources.run(async () => {
const snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
undefined,
this.#resources,
);
return ok(
parseElfUnwindRanges(
snapshot.bytes,
{
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
input,
options?.signal,
),
);
});
} catch (cause) {
return err(elfUnwindFailure(cause, input));
}
}
}
const inputBudgetRemediation = (
boundary: "file-size" | "capacity",
input: InspectElfUnwindRangesInput,
): string =>
boundary === "file-size"
? input.max_file_bytes >= MAX_INSPECT_ELF_UNWIND_FILE_BYTES
? `The image exceeds the ${String(MAX_INSPECT_ELF_UNWIND_FILE_BYTES)}-byte input ceiling this operation accepts; select a smaller artifact.`
: `Raise max_file_bytes above ${String(input.max_file_bytes)} bytes or select a smaller artifact; the limit is the caller-selected input read budget.`
: input.max_ranges >= MAX_INSPECT_ELF_UNWIND_RANGES
? `The image exceeds the ${String(MAX_INSPECT_ELF_UNWIND_RANGES)}-record unwind ceiling this operation accepts; select a smaller artifact.`
: `Raise max_ranges above ${String(input.max_ranges)} or select a smaller artifact; the limit is the caller-selected unwind record budget.`;
const elfUnwindFailurePrimary = (
facts: ArtifactFilePrimaryFacts,
input: InspectElfUnwindRangesInput,
) => {
const { cause, origin } = facts;
// The page's symbol-name text allowance is fixed; only a smaller page avoids it.
if (cause instanceof ElfUnwindSymbolTextFailure)
return new AnalysisResourceConstraintError(
OPERATION,
"capacity",
cause.message,
{ limit: input.limit, maximum_bytes: cause.maximumBytes },
{
cause,
retryable: false,
remediationAction: `Request a smaller limit than ${String(input.limit)}, or page with offset; the ${String(cause.maximumBytes)}-byte symbol-name text allowance is fixed, and max_ranges and max_file_bytes do not raise it.`,
},
);
if (cause instanceof BinaryResourceFailure)
return new AnalysisResourceConstraintError(
OPERATION,
"memory",
cause.message,
{ max_file_bytes: input.max_file_bytes },
{
cause,
...fixedAllowanceOptions(
"The 16 MiB ELF structural decoding budget",
"parser",
),
},
);
if (cause instanceof BinaryFormatFailure)
return cause.kind === "unsupported"
? new AnalysisUnsupportedTargetError(
OPERATION,
input.path,
cause.message,
{ cause },
)
: new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_format",
message: cause.message,
},
]);
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "integrity"
)
return new AnalysisArtifactChangedError(
OPERATION,
input.path,
cause.message,
{ cause },
);
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure &&
cause.reason === "cancelled"
)
return new AnalysisCancelledError(OPERATION, {
cause: artifactFileCancellationCause(cause),
});
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
) {
if (cause.reason === "limit") {
const structural = cause.boundary === "memory";
return new AnalysisResourceConstraintError(
OPERATION,
cause.boundary ?? "memory",
cause.message,
{
max_file_bytes: input.max_file_bytes,
max_ranges: input.max_ranges,
},
{
cause,
...(cause.boundary === undefined
? {}
: structural
? fixedAllowanceOptions(
"The ELF unwind structural decoding budget",
"parser",
)
: {
retryable: false as const,
remediationAction: inputBudgetRemediation(
cause.boundary,
input,
),
}),
},
);
}
if (cause.reason === "path" || cause.reason === "format")
return new AnalysisInputError(
OPERATION,
{ cause, ...stableArtifactInputRecovery(cause) },
[
{
path: ["path"],
reason: "invalid_format",
message: cause.message,
},
],
);
}
if (cause instanceof Error && "code" in cause) {
if (cause.code === "EACCES" || cause.code === "EPERM")
return new AnalysisAccessDeniedError(OPERATION, input.path, cause.code, {
cause,
});
if (isSelectedRegularFileError(cause))
return new AnalysisInputError(OPERATION, { cause }, [
{
path: ["path"],
reason: "invalid_value",
message: `Selected ELF image could not be read (${String(cause.code)}): ${input.path}.`,
},
]);
}
return new ArtifactOperationError(
OPERATION,
origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure
? cause.reason
: "io",
undefined,
cause instanceof Error ? cause.message : "ELF unwind inspection failed.",
{ cause },
);
};
const elfUnwindFailure = (
cause: unknown,
input: InspectElfUnwindRangesInput,
) => {
const primary = elfUnwindFailurePrimary(
artifactFilePrimaryFacts(cause),
input,
);
return projectStableArtifactFailure(
cause,
primary,
input.path,
ELF_UNWIND_RANGES_PROVIDER.id,
OPERATION,
);
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,9 @@
import { expect, it } from "vitest";
import { pe } from "../../domain/binaryTarget.fixture.js";
import { elfHardeningFixture } from "../hardening/BinaryHardening.fixture.js";
import { elfUnwindSectionlessFixture } from "../elf/ElfUnwindTables.fixture.js";
import {
ELF_PT_GNU_EH_FRAME,
ELF_PT_GNU_RELRO,
ELF_PT_GNU_STACK,
ELF_PT_INTERP,
@@ -64,6 +66,22 @@ it("admits PT_INTERP, PT_GNU_STACK and PT_GNU_RELRO program headers", () => {
);
});
it("retains PT_GNU_EH_FRAME with its file and address span", () => {
const bytes = elfUnwindSectionlessFixture();
const directory = readElfDirectoryFromBuffer(bytes);
expect(directory.programs.map((program) => program.type)).toEqual([
1,
ELF_PT_GNU_EH_FRAME,
]);
expect(directory.programs[1]).toMatchObject({
type: ELF_PT_GNU_EH_FRAME,
header_offset: 64 + 56,
file_offset: bytes.readBigUInt64LE(64 + 56 + 8),
virtual_address: bytes.readBigUInt64LE(64 + 56 + 16),
file_size: bytes.readBigUInt64LE(64 + 56 + 32),
});
});
it("retains a confirmed overlapping PE when the COFF record extends past EOF", () => {
const bytes = Buffer.alloc(64);
bytes.write("MZ", 0, "ascii");
@@ -47,9 +47,10 @@ export interface NativeSection {
readonly alignment: bigint;
readonly file_backed: boolean;
}
/** Program header types retained for load, dynamic, and hardening consumers. */
/** Program header types retained for load, dynamic, hardening, and unwind consumers. */
export const ELF_PT_NOTE = 4 as const;
export const ELF_PT_INTERP = 3 as const;
export const ELF_PT_GNU_EH_FRAME = 0x6474e550 as const;
export const ELF_PT_GNU_STACK = 0x6474e551 as const;
export const ELF_PT_GNU_RELRO = 0x6474e552 as const;
export const ELF_PT_GNU_PROPERTY = 0x6474e553 as const;
@@ -70,6 +71,7 @@ export type ElfProgramDeclaration =
| ({ readonly type: 2; readonly header_offset: number } & ElfDynamicSegment)
| ({ readonly type: typeof ELF_PT_NOTE } & ElfProgramSpan)
| ({ readonly type: typeof ELF_PT_INTERP } & ElfProgramSpan)
| ({ readonly type: typeof ELF_PT_GNU_EH_FRAME } & ElfProgramSpan)
| ({ readonly type: typeof ELF_PT_GNU_STACK } & ElfProgramSpan)
| ({ readonly type: typeof ELF_PT_GNU_RELRO } & ElfProgramSpan)
| ({ readonly type: typeof ELF_PT_GNU_PROPERTY } & ElfProgramSpan);
@@ -184,6 +186,8 @@ export function* readElfSectionDirectory(
programDeclarations.push({ type: ELF_PT_NOTE, ...span });
else if (type === ELF_PT_INTERP)
programDeclarations.push({ type: ELF_PT_INTERP, ...span });
else if (type === ELF_PT_GNU_EH_FRAME)
programDeclarations.push({ type: ELF_PT_GNU_EH_FRAME, ...span });
else if (type === ELF_PT_GNU_STACK)
programDeclarations.push({ type: ELF_PT_GNU_STACK, ...span });
else if (type === ELF_PT_GNU_RELRO)
+9
View File
@@ -19,6 +19,7 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js";
import { captureProviderEnvironment } from "./providerEnvironment.js";
import { createByteEntropyService } from "../composition/binaryDiagnostics.js";
import { registerElfNotesTool } from "./registerElfNotesTool.js";
import { registerElfUnwindRangesTool } from "./registerElfUnwindRangesTool.js";
import { registerAppleIpsTool } from "./registerAppleIpsTool.js";
import { registerKernelModuleTool } from "./registerKernelModuleTool.js";
import { registerKernelBuildConfigTool } from "./registerKernelBuildConfigTool.js";
@@ -220,6 +221,7 @@ export const createServer = (
nativeExports,
devicetree,
elfNotes,
elfUnwindRanges,
appleIps,
kernelModule,
kernelBuildConfig,
@@ -501,6 +503,13 @@ export const createServer = (
recordEvidence,
analysisAdmission,
);
registerElfUnwindRangesTool(
server,
elfUnwindRanges,
toolLogger,
recordEvidence,
analysisAdmission,
);
registerAppleIpsTool(
server,
appleIps,
+31
View File
@@ -0,0 +1,31 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { ElfUnwindRangesService } from "../application/binaryDiagnostics/ElfUnwindRangesService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import { createEvidenceToolHandler } from "./contractToolHandler.js";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register the explicit-file ELF unwind-range workflow and retain its complete Evidence. */
export const registerElfUnwindRangesTool = (
server: EvidenceMcpServer,
service: ElfUnwindRangesService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
): void => {
const contract = toolContract("inspect_elf_unwind_ranges");
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
};
+144
View File
@@ -0,0 +1,144 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../src/contracts/toolContracts.js";
import {
UNWIND_FN_A,
UNWIND_FN_B,
UNWIND_LSDA,
elfUnwindFixture,
} from "../../src/native/elf/ElfUnwindTables.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const address = (value: number): string => `0x${value.toString(16)}`;
cliTest(
"reports two unwind ranges, a symbol, an LSDA, and a header mismatch",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-unwind-cli-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const result = await cli.run({
arguments: ["inspect-elf-unwind-ranges", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract(
"inspect_elf_unwind_ranges",
).outputSchema.parse(result.json);
const report = evidence.normalized_result;
expect(report.ranges).toHaveLength(2);
expect(report.ranges[0]).toMatchObject({
start: address(UNWIND_FN_A),
symbol: { text: "alpha", trust: "untrusted" },
lsda: null,
});
expect(report.ranges[1]).toMatchObject({
start: address(UNWIND_FN_B),
symbol: null,
lsda: { address: address(UNWIND_LSDA), indirect: false },
});
expect(report.coverage).toMatchObject({
status: "complete",
total_ranges: 2,
ranges_with_symbols: 1,
ranges_without_symbols: 1,
eh_frame_hdr_agreement: "disagree",
});
expect(report.limitations).toContain(
"The .eh_frame_hdr binary search table does not match the decoded FDEs.",
);
},
);
cliTest(
"resolves a relative ELF path against the working directory",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-unwind-cli-rel-");
await writeFile(join(root, "program"), elfUnwindFixture());
const result = await cli.run({
arguments: ["inspect-elf-unwind-ranges", "program", "--json"],
cwd: root,
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract(
"inspect_elf_unwind_ranges",
).outputSchema.parse(result.json);
expect(evidence.subject?.local_path).toBe(join(root, "program"));
expect(evidence.normalized_result.coverage.total_ranges).toBe(2);
},
);
cliTest("reports a non-ELF file as invalid input", async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-unwind-cli-bad-");
const path = join(root, "broken");
await writeFile(path, Buffer.from("not an elf"));
const result = await cli.run({
arguments: ["inspect-elf-unwind-ranges", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_elf_unwind_ranges" },
});
});
cliTest("pages unwind ranges with --offset and --limit", async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-unwind-cli-page-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const result = await cli.run({
arguments: [
"inspect-elf-unwind-ranges",
path,
"--json",
"--offset",
"1",
"--limit",
"1",
],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_elf_unwind_ranges").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.ranges.map((range) => range.index)).toEqual(
[1],
);
expect(evidence.normalized_result.ranges[0]?.start).toBe(
address(UNWIND_FN_B),
);
expect(evidence.normalized_result.page).toEqual({
offset: 1,
limit: 1,
returned: 1,
total: 2,
next_offset: null,
});
expect(evidence.normalized_result.coverage.total_ranges).toBe(2);
});
cliTest("decodes an ELF32 big-endian unwind table", async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-unwind-cli-be-");
const path = join(root, "program");
await writeFile(
path,
elfUnwindFixture({ bits: 32, little: false, machine: 20, header: "match" }),
);
const result = await cli.run({
arguments: ["inspect-elf-unwind-ranges", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = toolContract("inspect_elf_unwind_ranges").outputSchema.parse(
result.json,
);
expect(evidence.normalized_result.format).toBe("elf32");
expect(evidence.normalized_result.byte_order).toBe("big");
expect(evidence.normalized_result.machine).toBe(20);
expect(evidence.normalized_result.ranges.map((range) => range.start)).toEqual(
[address(UNWIND_FN_A), address(UNWIND_FN_B)],
);
expect(evidence.normalized_result.coverage.eh_frame_hdr_agreement).toBe(
"agree",
);
});
@@ -16,6 +16,7 @@ const fileCommands = [
"decode-signal-recording",
"inspect-model-artifact",
"inspect-elf-notes",
"inspect-elf-unwind-ranges",
"inspect-kernel-module",
"inspect-kernel-build-config",
"inspect-byte-entropy",
@@ -250,6 +250,7 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
["inspect_windows_shortcut", { path: nul }],
["inspect_native_exports", { path: nul }],
["inspect_elf_notes", { path: nul }],
["inspect_elf_unwind_ranges", { path: nul }],
["inspect_apple_ips", { path: nul }],
["inspect_devicetree", { path: nul }],
["inspect_kernel_module", { path: nul }],
@@ -0,0 +1,144 @@
import { symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createElfUnwindRangesService } from "../../../src/composition/binaryDiagnostics.js";
import { elfUnwindFixture } from "../../../src/native/elf/ElfUnwindTables.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("ELF unwind range stable filesystem boundary", () => {
it("reports non-file and malformed ELF selections as caller input errors", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-files-");
const path = join(root, "program");
const alias = join(root, "alias");
const malformed = join(root, "malformed");
await writeFile(path, elfUnwindFixture());
await writeFile(malformed, Buffer.from("not an elf"));
await symlink(path, alias);
const service = createElfUnwindRangesService();
try {
for (const [candidate, reason] of [
[root, "invalid_format"],
[alias, "invalid_format"],
[malformed, "invalid_format"],
[join(root, "missing"), "invalid_value"],
[join(path, "child"), "invalid_value"],
] as const) {
const result = await service.inspect({ path: candidate });
if (result.ok) throw new Error("Expected file acquisition failure");
expect(result.error).toMatchObject({
_tag: "AnalysisInputError",
operation: "inspect_elf_unwind_ranges",
issues: [
{
path: ["path"],
reason,
message: expect.any(String),
},
],
});
}
} finally {
await service.close();
}
});
it("accepts a header whose search table is omitted, as GNU ld writes it", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-omit-");
const path = join(root, "program");
await writeFile(
path,
elfUnwindFixture({ header: "match", headerCount: "omit" }),
);
const service = createElfUnwindRangesService();
try {
const result = await service.inspect({ path });
if (!result.ok) throw result.error;
expect(result.value.normalized_result).toMatchObject({
eh_frame_hdr: { status: "present", fde_count: null, table_entries: 0 },
coverage: { status: "complete", eh_frame_hdr_agreement: "unavailable" },
});
} finally {
await service.close();
}
});
it("returns an ELF32 range whose end wraps at the address width", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-wrap-");
const path = join(root, "program");
await writeFile(
path,
elfUnwindFixture({
bits: 32,
header: "match",
unsignedPcrel: { size: 0xffffff00 },
}),
);
const service = createElfUnwindRangesService();
try {
const result = await service.inspect({ path });
if (!result.ok) throw result.error;
const report = result.value.normalized_result as {
ranges: { start: string; end: string; size: string }[];
};
const first = report.ranges[0];
if (first === undefined) throw new Error("Expected a range");
expect(first.size).toBe(String(0xffffff00));
expect(BigInt(first.end)).toBe(
BigInt.asUintN(32, BigInt(first.start) + 0xffffff00n),
);
} finally {
await service.close();
}
});
it("tells a caller over the symbol-name text allowance to request a smaller page", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-names-");
const path = join(root, "program");
await writeFile(
path,
elfUnwindFixture({ header: "absent", suffixNames: 300 }),
);
const service = createElfUnwindRangesService();
try {
const result = await service.inspect({ path, limit: 300 });
if (result.ok) throw new Error("Expected symbol-name text failure");
expect(result.error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
retryable: false,
});
const remediation =
"remediationAction" in result.error
? result.error.remediationAction
: undefined;
expect(remediation).toContain("smaller limit than 300");
expect(remediation).not.toContain("Raise max_ranges");
const smaller = await service.inspect({ path, limit: 200 });
expect(smaller.ok).toBe(true);
} finally {
await service.close();
}
});
it("returns typed resource and cancellation failures", async () => {
const root = await createTestTempDirectory("rea-elf-unwind-budget-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const service = createElfUnwindRangesService();
try {
const tooSmall = await service.inspect({ path, max_file_bytes: 64 });
if (tooSmall.ok) throw new Error("Expected resource budget failure");
expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError");
const tooMany = await service.inspect({ path, max_ranges: 1 });
if (tooMany.ok) throw new Error("Expected range budget failure");
expect(tooMany.error._tag).toBe("AnalysisResourceConstraintError");
const cancelled = await service.inspect(
{ path },
{ signal: AbortSignal.abort() },
);
if (cancelled.ok) throw new Error("Expected cancellation");
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
} finally {
await service.close();
}
});
});
@@ -26,6 +26,7 @@ const CONTRACTS = [
const PATH_FIELDS = {
inspect_apple_ips: ["path"],
inspect_elf_notes: ["path"],
inspect_elf_unwind_ranges: ["path"],
inspect_kernel_module: ["path"],
inspect_byte_entropy: ["path"],
inspect_api_contract: ["path", "operations_path"],
@@ -125,6 +126,7 @@ it("rejects one relative path field at a time on tools/list", async () => {
expect(checked).toEqual([
"inspect_apple_ips.path",
"inspect_elf_notes.path",
"inspect_elf_unwind_ranges.path",
"inspect_kernel_module.path",
"inspect_byte_entropy.path",
"inspect_api_contract.path",
@@ -0,0 +1,155 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import {
UNWIND_FN_A,
UNWIND_FN_B,
UNWIND_LSDA,
elfUnwindFixture,
} from "../../../src/native/elf/ElfUnwindTables.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";
const address = (value: number): string => `0x${value.toString(16)}`;
const connect = async (mcp: TestMcp) => {
const session = createTestBinarySession(() => {
throw new Error("ELF unwind inspection must not start a deep provider");
});
const client = await mcp.connect(createServer({ kind: "session", session }));
return { client, session };
};
mcpTest(
"advertises inspect_elf_unwind_ranges and reads FDE ranges",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_elf_unwind_ranges",
);
expect(advertised?.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
const root = await createTestTempDirectory("rea-elf-unwind-mcp-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const response = await client.callTool({
name: "inspect_elf_unwind_ranges",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = toolContract(
"inspect_elf_unwind_ranges",
).outputSchema.parse(response.structuredContent);
const report = evidence.normalized_result;
expect(report.format).toBe("elf64");
expect(report.ranges[0]).toMatchObject({
start: address(UNWIND_FN_A),
symbol: { text: "alpha", trust: "untrusted" },
});
expect(report.ranges[1]?.lsda).toEqual({
address: address(UNWIND_LSDA),
indirect: false,
});
expect(report.coverage.eh_frame_hdr_agreement).toBe("disagree");
expect(report.limitations).toContain(
"CFA instructions are counted but not evaluated.",
);
} finally {
await session.close();
}
},
);
mcpTest(
"requires an absolute path for inspect_elf_unwind_ranges",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const response = await client.callTool({
name: "inspect_elf_unwind_ranges",
arguments: { path: "program" },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_elf_unwind_ranges" },
});
} finally {
await session.close();
}
},
);
mcpTest("pages one unwind range over MCP", async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const root = await createTestTempDirectory("rea-elf-unwind-mcp-page-");
const path = join(root, "program");
await writeFile(path, elfUnwindFixture());
const response = await client.callTool({
name: "inspect_elf_unwind_ranges",
arguments: { path, offset: 1, limit: 1 },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = toolContract(
"inspect_elf_unwind_ranges",
).outputSchema.parse(response.structuredContent);
expect(
evidence.normalized_result.ranges.map((range) => range.start),
).toEqual([address(UNWIND_FN_B)]);
expect(evidence.normalized_result.page).toMatchObject({
offset: 1,
limit: 1,
returned: 1,
total: 2,
next_offset: null,
});
} finally {
await session.close();
}
});
mcpTest(
"decodes an ELF32 big-endian unwind table over MCP",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const root = await createTestTempDirectory("rea-elf-unwind-mcp-be-");
const path = join(root, "program");
await writeFile(
path,
elfUnwindFixture({
bits: 32,
little: false,
machine: 20,
header: "match",
}),
);
const response = await client.callTool({
name: "inspect_elf_unwind_ranges",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = toolContract(
"inspect_elf_unwind_ranges",
).outputSchema.parse(response.structuredContent);
expect(evidence.normalized_result).toMatchObject({
format: "elf32",
byte_order: "big",
machine: 20,
});
expect(evidence.normalized_result.coverage.eh_frame_hdr_agreement).toBe(
"agree",
);
} finally {
await session.close();
}
},
);
@@ -111,6 +111,7 @@ import { inspectPythonPycInputSchema } from "../../src/domain/python/pythonPyc.j
import { PeResourcesProvider } from "../../src/native/pe/PeResourcesProvider.js";
import { Il2cppMetadataProvider } from "../../src/il2cpp/Il2cppMetadataProvider.js";
import { ElfNotesProvider } from "../../src/native/elf/ElfNotesProvider.js";
import { ElfUnwindRangesProvider } from "../../src/native/elf/ElfUnwindRangesProvider.js";
import { AppleIpsProvider } from "../../src/native/apple/AppleIpsProvider.js";
import { KernelModuleProvider } from "../../src/native/elf/KernelModuleProvider.js";
import { KernelBuildConfigProvider } from "../../src/native/elf/KernelBuildConfigProvider.js";
@@ -120,6 +121,7 @@ import { WindowsShortcutProvider } from "../../src/native/windows/WindowsShortcu
import { NativeExportsProvider } from "../../src/native/exports/NativeExportsProvider.js";
import { BeamProvider } from "../../src/erlang/BeamProvider.js";
import { inspectElfNotesInputSchema } from "../../src/domain/native/elfNotes.js";
import { inspectElfUnwindRangesInputSchema } from "../../src/domain/native/elfUnwindRanges.js";
import { inspectAppleIpsInputSchema } from "../../src/domain/native/appleIps.js";
import { inspectKernelModuleInputSchema } from "../../src/domain/native/kernelModule.js";
import { inspectKernelBuildConfigInputSchema } from "../../src/domain/native/kernelBuildConfig.js";
@@ -1002,6 +1004,7 @@ it.each([
const stableArtifactProviders = [
...staticProviders,
["ELF notes", () => new ElfNotesProvider()],
["ELF unwind ranges", () => new ElfUnwindRangesProvider()],
["Apple IPS", () => new AppleIpsProvider()],
["kernel module", () => new KernelModuleProvider()],
["kernel build config", () => new KernelBuildConfigProvider()],
@@ -1035,6 +1038,11 @@ const inspectFileFailure = (
inspectElfNotesInputSchema.parse({ path }),
options,
);
if (provider instanceof ElfUnwindRangesProvider)
return provider.inspect(
inspectElfUnwindRangesInputSchema.parse({ path }),
options,
);
if (provider instanceof AppleIpsProvider)
return provider.inspect(
inspectAppleIpsInputSchema.parse({ path }),
@@ -1121,6 +1129,7 @@ it.each(
expect(result.error._tag).toBe(
expectedTag ??
(provider instanceof ElfNotesProvider ||
provider instanceof ElfUnwindRangesProvider ||
provider instanceof KernelModuleProvider ||
provider instanceof KernelBuildConfigProvider ||
provider instanceof PeCertificatesProvider ||