feat(elf): inspect dynamic dependencies and required symbol versions

Add offline ELF dependency, search-path, symbol-version and import inspection with retained Evidence summaries and pages. Bound GNU-hash work and preserve cancellation, stable identity and caller-selected parameters across CLI/MCP.

Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
Matt Van Hornandgensokyo-dev authored and GitHub committed 2026-11-17 08:19:52 +00:00
1 parent af062e7a2d
commit e9c72dbd1f
100 files changed
+7137 -89

No files matched your search

@@ -316,6 +316,21 @@ 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 load-time dynamic dependencies: `inspect_elf_dependencies` with the
explicit local ELF32/ELF64 `ET_EXEC` or `ET_DYN` file. This built-in
target-free inspection requires no disassembler or dynamic loader. Preserve
ordered `DT_NEEDED` names (duplicates included), `DT_SONAME`, `DT_RPATH` /
`DT_RUNPATH` as written including `$ORIGIN` / `$LIB` / `$PLATFORM` tokens,
decoded `DT_FLAGS` / `DT_FLAGS_1`, `PT_INTERP`, GNU version requirements and
definitions, derived per-namespace maxima, and undefined `.dynsym` imports
joined to `library@version` when known. A missing `PT_DYNAMIC` is an observed
empty inventory, not proof another overlay carried dynamic metadata.
Relocatable objects use `inspect_kernel_module`; core dumps use
`inspect_recorded_crash`. For large inventories prefer `detail: "summary"`
plus `inspect_analysis_view` kind `elf-dependencies`. CLI summary requires
`--evidence_output`. See the
[ELF dependencies guide](https://github.com/morluto/rea/blob/main/docs/elf-dependencies.md).
- Code that runs before `main` or at exit in ELF or Mach-O:
`inspect_native_initializers` with the explicit local file (and
`architecture` for a universal Mach-O). This built-in inspection requires no
@@ -174,3 +174,20 @@ coverage describes selected retained rows; `summary.coverage` or `exports.covera
still describes the source table, so an empty partial page does not prove absence.
CLI `inspect-native-exports --detail summary --evidence_output PATH` saves the
complete bundle for later `inspect-analysis-view --evidence-bundle PATH` requests.
For an ELF load-time dependency question, `inspect_elf_dependencies` accepts
`detail: "summary"` and retains the complete inventory. Query
`inspect_analysis_view` with `view: {kind: "elf-dependencies", collection:
"needed" | "versions" | "definitions" | "maxima" | "imports", names:
["selected_name"], fields: ["name"], offset: 0, limit: 32}` and the reported
parent Evidence ID. Collection `"maxima"` matches `names` against namespaces
such as `GLIBC` and selects `fields` from `namespace`, `maximum`, and
`evidence_kind`, for example `fields: ["namespace", "maximum"]`. Collection
`"issues"` takes only `indices`, `offset`, and `limit`.
Duplicate `DT_NEEDED` names survive; use `source_index` with the parent ID for
stable identity. Page coverage describes selected retained rows;
`summary.coverage` or `dependencies.coverage` still describes the source
tables, so an empty partial page does not prove absence. CLI
`inspect-elf-dependencies --detail summary --evidence_output PATH` saves the
complete bundle for later `inspect-analysis-view --evidence-bundle PATH`
requests.
@@ -209,6 +209,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 dynamic dependencies
Use `inspect_elf_dependencies` for an explicit local ELF32/ELF64 `ET_EXEC` or
`ET_DYN` image when the question concerns needed libraries, SONAME, rpath /
runpath, GNU symbol versions, or undefined dynamic imports. No `open_binary`,
dynamic loader, or `ldd` is required. The CLI equivalent is
`inspect-elf-dependencies PATH`. Preserve artifact SHA-256, `DT_NEEDED` order
and duplicates, search-path tokens as written, decoded `DT_FLAGS` /
`DT_FLAGS_1`, `PT_INTERP`, GNU version names, and `library@version` joins when
`.gnu.version` names a verneed record. `$ORIGIN`, `$LIB`, and `$PLATFORM` are
not expanded. A missing `PT_DYNAMIC` is observed absence of that inventory,
not proof the image never needed libraries in another container. Relocatable
objects use `inspect_kernel_module`. Core dumps use `inspect_recorded_crash`.
See
[ELF dynamic dependencies](https://github.com/morluto/rea/blob/main/docs/elf-dependencies.md).
## ELF and Mach-O initializer functions
Use `inspect_native_initializers` for an explicit local ELF or Mach-O image
@@ -316,6 +316,21 @@ 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 load-time dynamic dependencies: `inspect_elf_dependencies` with the
explicit local ELF32/ELF64 `ET_EXEC` or `ET_DYN` file. This built-in
target-free inspection requires no disassembler or dynamic loader. Preserve
ordered `DT_NEEDED` names (duplicates included), `DT_SONAME`, `DT_RPATH` /
`DT_RUNPATH` as written including `$ORIGIN` / `$LIB` / `$PLATFORM` tokens,
decoded `DT_FLAGS` / `DT_FLAGS_1`, `PT_INTERP`, GNU version requirements and
definitions, derived per-namespace maxima, and undefined `.dynsym` imports
joined to `library@version` when known. A missing `PT_DYNAMIC` is an observed
empty inventory, not proof another overlay carried dynamic metadata.
Relocatable objects use `inspect_kernel_module`; core dumps use
`inspect_recorded_crash`. For large inventories prefer `detail: "summary"`
plus `inspect_analysis_view` kind `elf-dependencies`. CLI summary requires
`--evidence_output`. See the
[ELF dependencies guide](https://github.com/morluto/rea/blob/main/docs/elf-dependencies.md).
- Code that runs before `main` or at exit in ELF or Mach-O:
`inspect_native_initializers` with the explicit local file (and
`architecture` for a universal Mach-O). This built-in inspection requires no
@@ -174,3 +174,20 @@ coverage describes selected retained rows; `summary.coverage` or `exports.covera
still describes the source table, so an empty partial page does not prove absence.
CLI `inspect-native-exports --detail summary --evidence_output PATH` saves the
complete bundle for later `inspect-analysis-view --evidence-bundle PATH` requests.
For an ELF load-time dependency question, `inspect_elf_dependencies` accepts
`detail: "summary"` and retains the complete inventory. Query
`inspect_analysis_view` with `view: {kind: "elf-dependencies", collection:
"needed" | "versions" | "definitions" | "maxima" | "imports", names:
["selected_name"], fields: ["name"], offset: 0, limit: 32}` and the reported
parent Evidence ID. Collection `"maxima"` matches `names` against namespaces
such as `GLIBC` and selects `fields` from `namespace`, `maximum`, and
`evidence_kind`, for example `fields: ["namespace", "maximum"]`. Collection
`"issues"` takes only `indices`, `offset`, and `limit`.
Duplicate `DT_NEEDED` names survive; use `source_index` with the parent ID for
stable identity. Page coverage describes selected retained rows;
`summary.coverage` or `dependencies.coverage` still describes the source
tables, so an empty partial page does not prove absence. CLI
`inspect-elf-dependencies --detail summary --evidence_output PATH` saves the
complete bundle for later `inspect-analysis-view --evidence-bundle PATH`
requests.
@@ -209,6 +209,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 dynamic dependencies
Use `inspect_elf_dependencies` for an explicit local ELF32/ELF64 `ET_EXEC` or
`ET_DYN` image when the question concerns needed libraries, SONAME, rpath /
runpath, GNU symbol versions, or undefined dynamic imports. No `open_binary`,
dynamic loader, or `ldd` is required. The CLI equivalent is
`inspect-elf-dependencies PATH`. Preserve artifact SHA-256, `DT_NEEDED` order
and duplicates, search-path tokens as written, decoded `DT_FLAGS` /
`DT_FLAGS_1`, `PT_INTERP`, GNU version names, and `library@version` joins when
`.gnu.version` names a verneed record. `$ORIGIN`, `$LIB`, and `$PLATFORM` are
not expanded. A missing `PT_DYNAMIC` is observed absence of that inventory,
not proof the image never needed libraries in another container. Relocatable
objects use `inspect_kernel_module`. Core dumps use `inspect_recorded_crash`.
See
[ELF dynamic dependencies](https://github.com/morluto/rea/blob/main/docs/elf-dependencies.md).
## ELF and Mach-O initializer functions
Use `inspect_native_initializers` for an explicit local ELF or Mach-O image
+1
View File
@@ -206,6 +206,7 @@ Additional tools and host support depend on the target:
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](docs/pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](docs/guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](docs/elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](docs/elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](docs/binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and documented crash classes | Built-in static JSON inspection; [Apple IPS](docs/apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](docs/kernel-modules.md) |
+5
View File
@@ -564,6 +564,11 @@ export const documentationSections = [
route: "/electron-fuses",
},
{ text: "ELF note tables", source: "elf-notes.md", route: "/elf-notes" },
{
text: "ELF dependency tables",
source: "elf-dependencies.md",
route: "/elf-dependencies",
},
{
text: "Erlang BEAM files",
source: "erlang-beam.md",
+1
View File
@@ -177,6 +177,7 @@ the exact commit messages and references from the release they describe.
- [Flattened devicetree inspection](devicetree.md)
- [Electron fuse state](electron-fuses.md)
- [ELF note tables](elf-notes.md)
- [ELF dependency tables](elf-dependencies.md)
- [Erlang BEAM files](erlang-beam.md)
- [ESP images](esp-image.md)
- [GameCube DOL analysis through Ghidra](ghidra-dol.md)
+3 -1
View File
@@ -239,7 +239,9 @@ POSIX lane isolates `GROK_HOME`, an independent Git workspace and additional
skill roots, disables foreign configuration discovery, guards setup writes,
preserves unrelated registrations/backups and checks idempotence. Call mode
loads the full skill through native `read_file`, queries all REA names and input
schemas through native `search_tool`, and calls analysis through `use_tool`.
schemas through bounded native `search_tool` keyword queries, checking the
collected union against the complete catalog, and calls analysis through
`use_tool`.
If discovery reports `partial`, the native agent diagnoses REA registration and
retries discovery. No startup-timeout override or fixed readiness delay is used.
A larger Unicode-path fixture exercises native result offloading: the full
+113
View File
@@ -0,0 +1,113 @@
# ELF dynamic dependencies
`inspect_elf_dependencies` / `inspect-elf-dependencies` answers which libraries
one selected local ELF32/ELF64 `ET_EXEC` or `ET_DYN` image declares it needs to
load, which search paths and interpreter it names, which GNU symbol versions it
requires, and which undefined `.dynsym` imports carry a `library@version` when
that join is known. It reads the file without executing it and does not invoke
the dynamic loader, `ldd`, or a disassembler.
```bash
rea inspect-elf-dependencies /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_dependencies",
"arguments": { "path": "/artifacts/program" }
}
```
The [feature specification](specs/native/elf-dependencies/spec.md),
[plan](specs/native/elf-dependencies/plan.md) and
[tasks](specs/native/elf-dependencies/tasks.md) record the requirements and
verification.
Relocatable objects are not this inventory; use `inspect_kernel_module` for
Linux kernel modules. Core dumps are not this inventory; use
`inspect_recorded_crash`.
## Observations
The inline Evidence result contains the artifact path, SHA-256, and byte length.
`needed[]` lists every `DT_NEEDED` string in dynamic-table order, including
duplicate names. `dynamic.soname` is the `DT_SONAME` string when that tag is
present. `dynamic.rpath` and `dynamic.runpath` keep the raw `DT_RPATH` /
`DT_RUNPATH` string, the `:`-split entries without dropping empties, and any
`$ORIGIN`, `$LIB`, or `$PLATFORM` tokens as written, including `${...}` forms.
Those tokens are not expanded against the host filesystem.
`dynamic.flags` and `dynamic.flags_1` decode `DT_FLAGS` and `DT_FLAGS_1` into
named bits (`BIND_NOW` / `NOW`, `ORIGIN`, `PIE`, `NODEFLIB`, and the other
documented `DF_*` / `DF_1_*` names). Unrecognized bits stay numeric.
`interpreter` is the `PT_INTERP` path when that program header is present.
`version_requirements` walks `.gnu.version_r` / `DT_VERNEED`: each needed file
and its required version names, hashes, weak flags, and version indices.
`derived_version_maxima` is a derived per-namespace maximum over GNU-style
`NAME_x.y` requirement strings (for example the highest `GLIBC_x.y`) and is
labelled `evidence_kind: "derived"`. Names that do not match that pattern stay
out of the derived set. `version_definitions` summarizes the image's own
`.gnu.version_d` names and the `VER_FLG_BASE` flag.
`imports[]` lists undefined `.dynsym` symbols. When `.gnu.version` is present,
each import keeps its version index, hidden bit, and a resolved
`library@version` when a matching verneed record exists. Index 0 and 1 stay
`unversioned`. A missing matching record is `unknown` and is an issue.
A missing `PT_DYNAMIC` is an observed empty load-time dependency inventory. It
is not proof another overlay or container carried dynamic linking metadata.
`DT_*` entries are the load-time facts. A section header is used for a table
only when it names the same address, maps to the same file bytes, and agrees
on any declared size or entry width; a disagreeing section is reported as an
issue and the `DT_*` declaration is used. When section headers are stripped,
tables are located from `PT_DYNAMIC` and `DT_*` virtual addresses through
`PT_LOAD`. Coverage is `partial` when a table
cannot be located or a string cannot be read. Complete coverage never retains
issues.
## Limits and failures
The selected file is limited to 64 MiB by default (512 MiB maximum). At most
1024 `DT_NEEDED` entries, 4096 GNU version records, and 65536 undefined
dynamic symbols are examined by default (65536 / 65536 / 262144 maximum).
Omitted budgets use these defaults during analysis and stay omitted in
Evidence parameters. Explicitly selecting a default value records that choice.
GNU hash decoding has a fixed allowance of 262144 bucket, bloom, or symbol
entries per table component; it yields between bounded steps so cancellation
can stop the walk. This work allowance has no runtime override.
Exceeding a named budget fails with no partial success. Decoded dynamic
strings share one scan and retained-text budget fixed by the admitted image
length, so names repeated by many rows cannot expand past the input size; this
budget has no runtime override. A failure after the file was read keeps its
path, SHA-256, and byte count as a partial observation. Cyclic `vn_next` /
`vna_next` chains, duplicate unique dynamic tags, malformed ELF headers, and
unsupported ELF extended numbering return no complete inventory.
Each dynamic string and `PT_INTERP` path is scanned for its terminator across at
most 65536 bytes. Unreadable dynamic strings, `PT_INTERP` paths that are
unterminated or end past that limit, and tables that cannot be located from
section headers or `DT_*` tags are reported as partial coverage with `issues`.
When the symbol count from `DT_HASH` or `DT_GNU_HASH` exceeds the located
`.dynsym` table, only the symbols inside that table are read and coverage is
partial. A GNU version chain whose links and declared count
disagree keeps the records read before the conflict, marks that table
`unreadable`, and reports partial coverage. `$ORIGIN`, `$LIB`, and `$PLATFORM` remain unexpanded.
Derived version maxima do not establish ABI compatibility.
Omitted or `complete` detail returns the inventory inline. `detail: "summary"`
retains the complete Evidence and returns identity, counts, and source
coverage. Query `inspect_analysis_view` with `kind: "elf-dependencies"` and
collection `needed`, `versions`, `definitions`, `maxima`, or `imports`, using
exact names (namespaces for `maxima`) or original indices, selected fields, and
matching-row pagination. Collection `issues` accepts original indices and
pagination only; its rows are returned whole and have no name filter. Summaries and pages report
version-definition and derived-maximum counts; those rows are paged through
their own collections. CLI summary
requires `--evidence_output`.
This workflow does not execute the image, invoke the dynamic loader, or resolve
`DT_NEEDED` paths against the host filesystem.
+10
View File
@@ -478,6 +478,16 @@ 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 needed libraries and required symbol versions without executing
the image or invoking the dynamic loader:
```bash
rea inspect-elf-dependencies /absolute/path/to/program --json
```
The fields, coverage rules and delivery options are documented in
[ELF dynamic dependencies](../elf-dependencies.md).
List ELF and Mach-O initializer and finalizer functions without executing the
image:
+14
View File
@@ -498,3 +498,17 @@ Export directories in PE headers are read like those in sections. An export or
dynamic symbol table above 262144 entries, more than 262144 rows, or more than
16 MiB of retained names fails without partial success. Export rows do not establish that a symbol is reachable, safe to call
or loaded at runtime.
## Portable ELF dependencies
`inspect_elf_dependencies` / `inspect-elf-dependencies` reads the load-time
dynamic-dependency inventory of an explicit ELF32/ELF64 `ET_EXEC` or `ET_DYN`
image on any supported host, without executing it, invoking the dynamic
loader, or opening a disassembler:
```sh
rea inspect-elf-dependencies ./program --json
```
It reports needed libraries, search paths, symbol versions and versioned
imports. See [ELF dynamic dependencies](../../elf-dependencies.md).
+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), [initializer functions](guides/native/native-initializers.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) |
| 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 dependencies](elf-dependencies.md), [initializer functions](guides/native/native-initializers.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), [Release exposure](release-exposure.md) |
+1
View File
@@ -165,6 +165,7 @@ npx rea-agents@latest setup
| شيفرة EVM البايتية | محددات التوجيه، وإزاحات البايتات، والمعاملات المستنتجة، وقابلية تغيير الحالة | مدخل محلي يحمل بايتات خامًا أو تمثيلًا سداسيًا عشريًا على Linux x64؛ [دليل EVM دون تشغيل](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -215,6 +215,7 @@ npm. Допълнителните инструменти и поддържани
| PE импорти | Имена на импортирани и отложено зареждани (delay-load) DLL библиотеки, ординали, IAT RVA адреси и pefile хеш на импортите | Вградена статична проверка на PE; [PE импорти](../pe-imports.md) |
| Windows преки пътища | Цел, аргументи, работна директория и данни от Shell Link | Вградена статична проверка на LNK; [Windows преки пътища](../guides/native/windows-shortcut.md) |
| ELF бележки | Собственици и типове на PT_NOTE/SHT_NOTE, полета GNU build-id и ABI-tag | Вградена статична проверка на ELF; [ELF бележки](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Защита на бинарни файлове | PIE, NX, RELRO, CFG и свързаните с тях флагове в заглавните части на ELF, PE и Mach-O | Вградена статична проверка на заглавните части; [защита на бинарни файлове](../binary-hardening.md) |
| Сривове на Apple (IPS) | Метаданни от .ips, нишки, образи, регистри и документирани класове сривове | Вградена статична проверка на JSON; [Apple IPS](../apple-ips.md) |
| Модули на ядрото на Linux | Ключове от .modinfo, CRC стойности от __versions, наличие на this_module и подпис в края на файла | Вградена статична проверка на ELF; [модули на ядрото](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA benötigt Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) oder 26+ (>=26.12.1) so
| EVM-Bytecode | Dispatch-Selektoren, Byte-Offsets, abgeleitete Argumente und Veränderbarkeit des Zustands | Lokale Eingabe mit Rohbytes oder Hexdarstellung unter Linux x64; [Offline-EVM-Leitfaden](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ npx rea-agents@latest setup
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA requiere Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) o 26+ (>=26.12.1), adem
| Bytecode EVM | Selectores de despacho, desplazamientos en bytes, argumentos inferidos y mutabilidad | Entrada local con bytes sin procesar o representación hexadecimal, en Linux x64; [guía de EVM sin ejecutar](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -157,6 +157,7 @@ REA به Node.js 22.x (>=22.23.4)، 24.x (>=24.22.1) یا 26+ (>=26.12.1)، به
| بایت‌کد EVM | selectorهای dispatch، offsetهای بایتی، آرگومان‌های استنباط‌شده و قابلیت تغییر وضعیت | دادهٔ خام/hex محلی روی Linux x64؛ [راهنمای EVM آفلاین](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA nécessite Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) ou 26+ (>=26.12.1), ai
| Bytecode EVM | Sélecteurs de dispatch, offsets en octets, arguments inférés et mutabilité | Fichier local brut ou hexadécimal sous Linux x64 ; [guide EVM hors ligne](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -168,6 +168,7 @@ Alat tambahan dan dukungan sistem host bergantung pada target yang dianalisis:
| Bytecode EVM | Selector dispatch, offset byte, argumen yang disimpulkan, dan sifat mutabilitas | Pembawa data raw/hex lokal di Linux x64; [panduan EVM offline](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA richiede Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) o 26+ (>=26.12.1), oltre
| Bytecode EVM | Selettori di dispatch, offset dei byte, argomenti inferiti e mutabilità | Carrier raw/hex locale su Linux x64; [guida EVM offline](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ REA には Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)、または 26+ (>=
| EVM バイトコード | ディスパッチセレクター、バイトオフセット、推定された引数と状態変更の可否 | Linux x64 上のローカルの生バイト/16 進数の入力ファイル;[オフライン EVM ガイド](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA에는 Node.js 22.x(>=22.23.4), 24.x(>=24.22.1) 또는 26+ (>=26.12.1)와 npm
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA-യ്ക്ക് Node.js 22.x (>=22.23.4), 24.x (>=24.22.1), അല്ല
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ REA wymaga Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) lub 26+ (>=26.12.1) oraz n
| Kod bajtowy EVM | Selektory wywołań, przesunięcia bajtowe, wywnioskowane argumenty i mutowalność | Lokalny plik z surowymi bajtami lub zapisem szesnastkowym w systemie Linux x64; [przewodnik EVM offline](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ O REA requer Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) ou 26+ (>=26.12.1), alé
| Bytecode EVM | Seletores de despacho, offsets de bytes, argumentos inferidos e mutabilidade | Entrada local com bytes brutos ou representação hexadecimal no Linux x64; [guia de EVM sem execução](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -203,6 +203,7 @@ Uneltele suplimentare și platformele acceptate depind de ținta analizată:
| Importuri PE | Numele DLL-urilor importate și încărcate întârziat, ordinale, RVA-uri ale IAT și hash-ul importurilor calculat de pefile | Inspectare statică integrată a fișierelor PE; [importuri PE](../pe-imports.md) |
| Scurtături Windows | Țintă Shell Link, argumente, director de lucru, ExtraData și identificatori Tracker | Inspectare statică integrată a fișierelor LNK; [scurtături Windows](../guides/native/windows-shortcut.md) |
| Note ELF | Proprietari și tipuri PT_NOTE/SHT_NOTE, câmpuri GNU build-id și ABI-tag | Inspectare statică integrată a fișierelor ELF; [note ELF](../elf-notes.md) |
| Dependențe ELF | Biblioteci DT_NEEDED, SONAME, căi RPATH/RUNPATH, versiuni GNU și importuri nedefinite | Inspectare statică integrată a fișierelor ELF; [dependențe ELF](../elf-dependencies.md) |
| Întărire binară | PIE, NX, RELRO, CFG și indicatori de antet pentru ELF, PE și Mach-O | Inspecție statică integrată a antetelor; [întărire binară](../binary-hardening.md) |
| Rapoarte Apple IPS de eroare fatală | Metadate .ips, fire de execuție, imagini binare, registre și clase documentate de erori fatale | Inspectare statică integrată a datelor JSON; [Apple IPS](../apple-ips.md) |
| Module de kernel Linux | Chei .modinfo, CRC-uri din __versions, prezența this_module și structura semnăturii de la sfârșitul fișierului | Inspectare statică integrată a fișierelor ELF; [module de kernel](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA требует Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) или 26+ (>=26.1
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ REA ต้องใช้ Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) หรื
| ไบต์โค้ด EVM | ตัวเลือกฟังก์ชันสำหรับการเรียก ออฟเซ็ตไบต์ อาร์กิวเมนต์และความสามารถในการเปลี่ยนสถานะที่อนุมานได้ | ไฟล์บนเครื่องที่มีไบต์ดิบหรือข้อมูลเลขฐานสิบหกบน Linux x64; [คู่มือ EVM แบบออฟไลน์](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -163,6 +163,7 @@ REA; Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) veya 26+ (>=26.12.1) ve npm gere
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -165,6 +165,7 @@ REA потребує Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) або 26+ (>=26
| Байт-код EVM | Селектори диспетчеризації, зміщення байтів, виведені припущення про аргументи та змінюваність стану | Локальні необроблені байти або шістнадцяткове представлення у Linux x64; [посібник EVM без запуску](../guides/evm/evm-bytecode.md) |
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -204,6 +204,7 @@ Mazeed tools aur host support target par depend karte hain:
| PE imports | Import aur delay-load DLL names, ordinals, IAT RVAs aur pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id aur ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, imports, lambdas aur Code header | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -165,6 +165,7 @@ REA yêu cầu Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) hoặc 26+ (>=26.12.1)
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
+1
View File
@@ -166,6 +166,7 @@ REA 需要 Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)或 26+ (>=26.12.1)
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -166,6 +166,7 @@ REA 需要 Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)或 26+ (>=26.12.1)
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
| ELF notes | PT_NOTE/SHT_NOTE owners, types, GNU build-id and ABI-tag fields | Built-in static ELF inspection; [ELF notes](../elf-notes.md) |
| ELF dependencies | DT_NEEDED, SONAME, RPATH/RUNPATH, GNU versions, and undefined imports | Built-in static ELF inspection; [ELF dependencies](../elf-dependencies.md) |
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
+1
View File
@@ -31,6 +31,7 @@ for new work, roadmap granularity and producer-owned contracts.
- [Solidity terminal metadata inspection](solidity/cbor-metadata/spec.md) ([plan](solidity/cbor-metadata/plan.md), [tasks](solidity/cbor-metadata/tasks.md), [verification](solidity/cbor-metadata/verification.md))
- [Inspect a V8 code cache container](v8/code-cache-inspection/spec.md) ([plan](v8/code-cache-inspection/plan.md), [tasks](v8/code-cache-inspection/tasks.md))
- [Deno compile executable inventory and extraction](artifacts/deno-standalone/spec.md) ([plan](artifacts/deno-standalone/plan.md), [tasks](artifacts/deno-standalone/tasks.md))
- [ELF dynamic dependencies](native/elf-dependencies/spec.md) ([plan](native/elf-dependencies/plan.md), [tasks](native/elf-dependencies/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))
- [Native initializers](native/native-initializers/spec.md) ([plan](native/native-initializers/plan.md), [tasks](native/native-initializers/tasks.md))
@@ -0,0 +1,38 @@
# Implementation plan
## Boundary and contract
`src/domain/native/elfDependencies.ts` owns the input and result schemas,
limits and the shared limitation strings, and
`src/domain/analysisView/elfDependenciesView.ts` owns the retained-Evidence
view. `src/native/elf/ElfDependencyParser.ts` decodes the dynamic table,
GNU version tables and dynamic symbols over the existing ELF image reader, and
`src/native/elf/ElfDependenciesProvider.ts` admits the selected file and
applies the budgets.
`src/application/binaryDiagnostics/ElfDependenciesService.ts` depends on the
domain and `src/ports/binaryDiagnostics/ElfDependenciesPort.ts` and validates
the report shape. It is composed beside the sibling binary diagnostics tools in
`src/composition/binaryDiagnostics.ts` and bound in
`src/server/serviceToolBindings.ts`.
## Incremental work and validation
1. Define the schemas, limits and limitations, with domain tests.
2. Decode `PT_DYNAMIC`, the `DT_*` strings and flags, and `PT_INTERP` over
synthetic fixtures for both widths and endiannesses.
3. Walk `.gnu.version_r` and `.gnu.version_d`, derive the per-namespace
maxima, and join undefined `.dynsym` imports to `library@version`.
4. Locate tables from section headers only when they agree with `DT_*`, and
from `PT_LOAD` when section headers are stripped, with partial coverage
for anything unreadable.
5. Add the summary view and its `inspect_analysis_view` collections.
6. Register the CLI command and MCP tool, then add acceptance, filesystem and
MCP boundary tests.
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 analysis view kind.
Existing tools and Evidence shapes do not change.
@@ -0,0 +1,82 @@
# ELF dynamic dependencies
## Problem and outcome
An agent looking at a Linux program often needs to know what it loads before
it runs: the libraries it names, the paths it searches, its interpreter and the
GNU symbol versions it requires. Today that means `ldd`, which invokes the
dynamic loader, or `readelf`, which is not always installed and is not
Evidence.
This feature adds `inspect_elf_dependencies` and `inspect-elf-dependencies`.
They read the load-time dynamic-dependency inventory of one selected local
ELF32 or ELF64 `ET_EXEC` or `ET_DYN` image, without executing it, invoking the
dynamic loader or opening a disassembler.
[ELF dynamic dependencies](../../../elf-dependencies.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. `needed[]` lists every `DT_NEEDED` string in dynamic-table order, keeping
duplicates. `DT_SONAME`, `DT_RPATH` and `DT_RUNPATH` are reported as
written, with `:`-split entries that keep empties and `$ORIGIN`, `$LIB` and
`$PLATFORM` tokens unexpanded, including `${...}` forms.
2. `DT_FLAGS` and `DT_FLAGS_1` decode into named `DF_*` and `DF_1_*` bits;
unrecognized bits stay numeric. `PT_INTERP` is reported when present.
3. `version_requirements` walks `.gnu.version_r` / `DT_VERNEED` with each
needed file's version names, hashes, weak flags and indices.
`version_definitions` summarizes `.gnu.version_d` and `VER_FLG_BASE`.
4. `derived_version_maxima` takes the highest `NAME_x.y` requirement per
namespace and is labelled `evidence_kind: "derived"`. Names outside that
pattern stay out of the derived set, and maxima do not establish ABI
compatibility.
5. `imports[]` lists undefined `.dynsym` symbols. With `.gnu.version`, each
keeps its version index, hidden bit and a resolved `library@version` when a
matching verneed record exists. Indices 0 and 1 are `unversioned`; a
missing record is `unknown` and an issue.
6. `DT_*` entries are the load-time facts. A section header is used for a
table only when it agrees with the `DT_*` address, file bytes, size and
entry width; a disagreeing section is an issue and the `DT_*` declaration
is used. Without section headers, tables are located from `PT_DYNAMIC` and
`DT_*` addresses through `PT_LOAD`.
7. A missing `PT_DYNAMIC` is an observed empty inventory. A table that cannot
be located, an unreadable string, an unterminated `PT_INTERP`, a hash-table
symbol count past the located `.dynsym`, or a GNU version chain whose links
and count disagree make coverage `partial` with issues. Complete coverage
never retains issues.
8. Budgets bound the file size (64 MiB default, 512 MiB maximum), `DT_NEEDED`
entries, GNU version records and undefined dynamic symbols, and each string
scan to 65536 bytes. Decoded strings share one scan and retained-text budget
fixed by the admitted image length. Exceeding a named budget fails with no
partial success. Cyclic version chains, duplicate unique dynamic tags,
malformed headers and unsupported extended numbering return no complete
inventory.
9. `detail: "summary"` retains the complete Evidence and returns identity,
counts and coverage. `inspect_analysis_view` with `kind:
"elf-dependencies"` pages `needed`, `versions`, `definitions`, `maxima`,
`imports` and `issues`. CLI summary requires `--evidence_output`.
10. Library, symbol and version names are target-derived and untrusted. MCP
requires an absolute path; the CLI resolves relative paths against the
caller's working directory.
## Acceptance
- Parser unit tests cover both widths and endiannesses, duplicate needed
names, search-path tokens, flag decoding, verneed and verdef walks, import
version joins, stripped section headers, disagreeing sections, budgets and
partial coverage.
- Domain and service tests validate the report shape and the derived maxima.
- View tests and application acceptance tests cover summary delivery and the
`inspect_analysis_view` collections.
- CLI acceptance, filesystem boundary and MCP boundary tests exercise the
public contract.
## Non-goals
- Resolving `DT_NEEDED` names or expanding search-path tokens against the
host filesystem.
- Invoking the dynamic loader or `ldd`, or executing the image.
- Relocatable objects and core dumps, which `inspect_kernel_module` and
`inspect_recorded_crash` cover.
@@ -0,0 +1,10 @@
# Tasks
- [x] Define the single-feature scope, contract and implementation plan.
- [x] Decode `DT_NEEDED`, `DT_SONAME`, search paths, flags and `PT_INTERP`.
- [x] Walk GNU version requirements and definitions, and derive the maxima.
- [x] Join undefined `.dynsym` imports to `library@version`.
- [x] Locate tables without section headers and report partial coverage.
- [x] Add the summary view and its analysis-view collections.
- [x] Register the CLI command and MCP tool with acceptance and boundary tests.
- [x] Document the guide, CLI reference and skill reference.
+1
View File
@@ -343,6 +343,7 @@ export const ENTRY_FILES = Object.freeze(
"NativeMacOSProviderMetadata.ts",
"NativeMacosProviderIdentity.ts",
"apple/AppleIpsProvider.ts",
"elf/ElfDependenciesProvider.ts",
"elf/ElfNotesProvider.ts",
"elf/ElfUnwindRangesProvider.ts",
"elf/KernelBuildConfigProvider.ts",
+40 -9
View File
@@ -55,6 +55,13 @@ let diagnosticsVerified = false;
let lastTool;
let catalogChecked = false;
let catalogSize = null;
// The native keyword search limit is uint8. Keep each query through partial
// replies, then query missing canonical names and verify the complete union.
const searchLimit = 255;
const discovered = new Map();
const searchedQueries = new Set();
const discoveryPages = [];
let pendingQuery = "rea";
let schemasChecked = 0;
let analysisRequested = false;
let evidenceSeen = false;
@@ -107,10 +114,6 @@ await withVerifierCleanup(async () => {
`export function extra${index}() { return { index: ${index}, tag: "GROK_LARGE_FIXTURE" }; }`,
).join("\n"),
);
assert(
expectedNames.length <= 255,
"Native search_tool limit is uint8; this full-catalog query cannot cover more than 255 tools",
);
const schemaValidator = new Ajv2020({
strict: false,
validateFormats: false,
@@ -253,10 +256,34 @@ await withVerifierCleanup(async () => {
diagnosticsVerified = true;
}
if (discovery?.status !== "ready")
return call("search_tool", { query: "rea", limit: 255 });
const inventory = discovery.results
return call("search_tool", {
query: pendingQuery,
limit: searchLimit,
});
discoveryPages.push({ query: pendingQuery, response: discovery });
searchedQueries.add(pendingQuery);
for (const tool of discovery.results
.filter((result) => result.server === "rea")
.flatMap((result) => result.tools);
.flatMap((result) => result.tools)) {
const previous = discovered.get(tool.tool_name);
if (previous !== undefined)
assert.deepEqual(
previous.input_schema,
tool.input_schema,
`${tool.tool_name}: native input schema changed between queries`,
);
discovered.set(tool.tool_name, tool);
}
const missing = expectedNames.filter((name) => !discovered.has(name));
const nextQuery = missing.find((name) => !searchedQueries.has(name));
if (nextQuery !== undefined) {
pendingQuery = nextQuery;
return call("search_tool", {
query: pendingQuery,
limit: searchLimit,
});
}
const inventory = [...discovered.values()];
catalogSize = inventory.length;
assert.deepEqual(
inventory.map((tool) => tool.tool_name).sort(),
@@ -274,7 +301,10 @@ await withVerifierCleanup(async () => {
);
schemasChecked++;
}
await writeFile(join(lab, "native-discovery.json"), last);
await writeFile(
join(lab, "native-discovery.json"),
JSON.stringify(discoveryPages),
);
catalogChecked = true;
analysisRequested = true;
return call("use_tool", {
@@ -524,9 +554,10 @@ enabled = false
discovery:
"native GROK_HOME, isolated additional skill directory, disabled foreign compatibility sources; default OS-home skill discovery and Windows unverified",
interface:
"default native search_tool/use_tool with a complete explicit inventory query; asynchronous partial discovery may trigger native REA diagnosis; large MCP outputs are queried via native terminal",
"default native search_tool/use_tool with bounded keyword queries checked against the complete catalog; asynchronous partial discovery may trigger native REA diagnosis; large MCP outputs are queried via native terminal",
catalogChecked,
catalogSize,
discoveryQueries: discoveryPages.map((page) => page.query),
schemasChecked,
skillLoaded,
diagnosticsRequested,
@@ -0,0 +1,9 @@
{
"schemas": {
"input compact": "6ecf88aeaa9d79da",
"output compact": "4bda7c3651bfc579"
},
"patterns": {
"input": ["^[^\\x00]*$"]
}
}
+16
View File
@@ -3,6 +3,22 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { cancelledBy } from "../domain/analysisErrorCore.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../domain/result.js";
import { isRecord } from "../kernel/isRecord.js";
/** Keep top-level caller selections separate from defaults resolved for execution. */
export const callerAnalysisParameters = (rawInput: unknown) => {
const selected = new Set(
isRecord(rawInput)
? Object.keys(rawInput).filter((name) => rawInput[name] !== undefined)
: [],
);
return <Input extends object>(resolved: Input): Partial<Input> => {
const parameters = { ...resolved };
for (const name of Object.keys(parameters))
if (!selected.has(name)) Reflect.deleteProperty(parameters, name);
return parameters;
};
};
/** Validate an application request, honoring cancellation before admission when supplied. */
export const parseAnalysisInput = <T>(
@@ -1,12 +1,14 @@
import { expect, it } from "vitest";
import { ElfNotesService } from "./ElfNotesService.js";
import { KernelModuleService } from "./KernelModuleService.js";
import { ElfDependenciesService } from "./ElfDependenciesService.js";
import { PeCertificatesService } from "./PeCertificatesService.js";
import { PeImportsService } from "./PeImportsService.js";
import { WindowsShortcutService } from "./WindowsShortcutService.js";
import {
ELF_NOTES_PROVIDER,
KERNEL_MODULE_PROVIDER,
ELF_DEPENDENCIES_PROVIDER,
PE_CERTIFICATES_PROVIDER,
PE_IMPORTS_PROVIDER,
WINDOWS_SHORTCUT_PROVIDER,
@@ -38,6 +40,14 @@ it.each([
() =>
new KernelModuleService({ identity: KERNEL_MODULE_PROVIDER, inspect }),
],
[
"ELF dependencies",
() =>
new ElfDependenciesService({
identity: ELF_DEPENDENCIES_PROVIDER,
inspect,
}),
],
[
"Windows shortcut",
() =>
@@ -0,0 +1,185 @@
import { expect, it } from "vitest";
import { ElfDependenciesService } from "./ElfDependenciesService.js";
import { ELF_DEPENDENCIES_PROVIDER } from "../../domain/investigationProviders.js";
import type { ElfDependencies } from "../../domain/native/elfDependencies.js";
import { ok } from "../../domain/result.js";
import { parseEvidence } from "../../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
const identity = ELF_DEPENDENCIES_PROVIDER;
const digest = "a".repeat(64);
const report: ElfDependencies = {
artifact: { path: "/artifacts/program", sha256: digest, bytes: 512 },
format: "elf64",
byte_order: "little",
machine: 62,
architecture: "amd64",
type: 3,
type_name: "shared",
interpreter: { status: "absent", path: null, location: null },
dynamic: {
status: "absent",
location: null,
soname: null,
rpath: null,
runpath: null,
flags: null,
flags_1: null,
},
needed: [],
version_requirements: { status: "absent", location: null, files: [] },
version_definitions: { status: "absent", location: null, names: [] },
derived_version_maxima: [],
imports: [],
coverage: {
status: "complete",
reason: null,
examined_needed: 0,
examined_versions: 0,
examined_imports: 0,
},
issues: [],
limitations: [
"No PT_DYNAMIC program header was declared. That is an observed empty load-time dependency inventory, not proof another overlay or container carried dynamic linking metadata.",
],
};
it("rejects a relative path and extra arguments before reading", async () => {
let calls = 0;
const service = new ElfDependenciesService({
identity,
inspect: () => {
calls += 1;
return Promise.resolve(ok(report));
},
});
const relative = await service.inspect({ path: "program" });
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 empty PT_DYNAMIC inventory and its x86_64 architecture", async () => {
const result = await new ElfDependenciesService({
identity,
inspect: () => Promise.resolve(ok(report)),
}).inspect({ path: report.artifact.path });
if (!result.ok) throw result.error;
expect(result.value).toMatchObject({
confidence: "observed",
subject: {
identity: {
kind: "file",
format: "elf",
architecture: "x86_64",
sha256: report.artifact.sha256,
},
local_path: report.artifact.path,
},
normalized_result: report,
});
});
it.each([undefined, 1024, 2])(
"preserves caller budget selection (%s) separately from execution defaults",
async (maxNeeded) => {
let resolved: number | undefined;
const rawInput = {
path: report.artifact.path,
...(maxNeeded === undefined ? {} : { max_needed: maxNeeded }),
};
const result = await new ElfDependenciesService({
identity,
inspect: (input) => {
resolved = input.max_needed;
return Promise.resolve(ok(report));
},
}).inspect(rawInput);
if (!result.ok) throw result.error;
expect(resolved).toBe(maxNeeded ?? 1024);
expect(result.value.parameters).toEqual(rawInput);
},
);
it("rejects a report whose needed coverage does not match retained rows", async () => {
const result = await new ElfDependenciesService({
identity,
inspect: () =>
Promise.resolve(
ok({
...report,
coverage: { ...report.coverage, examined_needed: 1 },
}),
),
}).inspect({ path: report.artifact.path });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("rejects complete coverage that still retains table issues", async () => {
const result = await new ElfDependenciesService({
identity,
inspect: () =>
Promise.resolve(
ok({
...report,
issues: [
{
code: "name_unreadable",
location: "DT_SONAME",
message: "unterminated",
},
],
}),
),
}).inspect({ path: report.artifact.path });
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toBeInstanceOf(AnalysisOutputError);
});
it("retains a completed observation if the caller cancels while the provider completes", async () => {
const controller = new AbortController();
const reason = { request: "late ELF dependency cancellation" };
const service = new ElfDependenciesService({
identity,
inspect: () => {
controller.abort(reason);
return Promise.resolve(ok(report));
},
});
const late = await service.inspect(
{ path: report.artifact.path },
{ signal: controller.signal },
);
expect(late).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
if (late.ok) throw new Error("Expected late cancellation");
expect(late.error).toBeInstanceOf(AnalysisCancelledError);
expect(late.error.cause).toBe(reason);
expect(parseEvidence(late.error.partialObservation)).toMatchObject({
operation: "inspect_elf_dependencies",
confidence: "observed",
subject: {
identity: {
kind: "file",
format: "elf",
architecture: "x86_64",
sha256: report.artifact.sha256,
},
local_path: report.artifact.path,
},
normalized_result: report,
});
});
@@ -0,0 +1,138 @@
import { isAbsolute } from "node:path";
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
import type { ElfDependenciesPort } from "../../ports/binaryDiagnostics/ElfDependenciesPort.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisInputError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
elfDependenciesSchema,
inspectElfDependenciesInputSchema,
type ElfDependencies,
type InspectElfDependenciesInput,
} from "../../domain/native/elfDependencies.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 {
callerAnalysisParameters,
parseAnalysisInput,
} from "../AnalysisInput.js";
const OPERATION = "inspect_elf_dependencies";
/** Shared caller validation, output parsing and Evidence provenance for CLI/MCP. */
export class ElfDependenciesService {
constructor(readonly provider: ElfDependenciesPort) {}
close(): Promise<void> {
return this.provider.close?.() ?? Promise.resolve();
}
async inspect(
rawInput: unknown,
options?: ExecutionOptions,
): Promise<Result<Evidence, AnalysisError>> {
const input = parseAnalysisInput(
OPERATION,
rawInput,
inspectElfDependenciesInputSchema,
options?.signal,
);
if (!input.ok) return input;
if (!isAbsolute(input.value.path))
return err(
new AnalysisInputError(OPERATION, undefined, [
{
path: ["path"],
reason: "invalid_format",
message: "Expected an absolute filesystem path on this host.",
},
]),
);
const parameters = callerAnalysisParameters(rawInput)(input.value);
const result = await this.provider.inspect(input.value, options);
if (!result.ok) return result;
const report = elfDependenciesSchema.safeParse(result.value);
if (
!report.success ||
report.data.artifact.path !== input.value.path ||
!validReport(report.data, input.value)
)
return err(
new AnalysisOutputError(
OPERATION,
"ELF dependency provider returned malformed output or changed artifact identity.",
),
);
const value = report.data;
const mapped = elfArchitecture(value.machine);
const architecture = BINARY_ARCHITECTURES.find(
(supported) => supported === mapped,
);
return completeProviderEvidence(
createEvidence(
{
path: value.artifact.path,
format: "elf",
sha256: value.artifact.sha256,
...(architecture === undefined ? {} : { architecture }),
},
this.provider.identity,
{
operation: OPERATION,
parameters,
result: value,
confidence: "observed",
limitations: value.limitations,
locations: [
{ kind: "artifact-path", path: value.artifact.path },
...rangesOf(value).map((range) => ({
kind: "file-offset-range" as const,
start: range.offset,
end: range.offset + range.bytes,
})),
],
},
),
options?.signal,
);
}
}
const rangesOf = (
report: ElfDependencies,
): { offset: number; bytes: number }[] => {
const found: { offset: number; bytes: number }[] = [];
const add = (
range: { offset: number; bytes: number } | null | undefined,
): void => {
if (range !== null && range !== undefined) found.push(range);
};
add(report.interpreter.location);
add(report.dynamic.location);
add(report.version_requirements.location);
add(report.version_definitions.location);
return found;
};
const validReport = (
report: ElfDependencies,
input: InspectElfDependenciesInput,
): boolean => {
if (
report.artifact.bytes > input.max_file_bytes ||
report.needed.length > input.max_needed ||
report.imports.length > input.max_imports ||
report.coverage.examined_versions > input.max_versions
)
return false;
const fileBytes = report.artifact.bytes;
return rangesOf(report).every(
(range) =>
range.bytes <= fileBytes && range.offset <= fileBytes - range.bytes,
);
};
+6 -3
View File
@@ -16,7 +16,10 @@ import {
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { parseAnalysisInput } from "./AnalysisInput.js";
import {
callerAnalysisParameters,
parseAnalysisInput,
} from "./AnalysisInput.js";
import { ok } from "../domain/result.js";
/** Operations the direct workflow can perform without a persistent session. */
@@ -104,8 +107,8 @@ export const admitOneShotOperation = <Name extends OneShotOperation>(
// Admission owns the selected request: preserve top-level omissions for
// Evidence and snapshot identity while carrying each selected parsed value.
// Nested defaults remain in the owning field's parsed value.
const selected = Object.fromEntries(
Object.entries(parsed.value).filter(([key]) => Object.hasOwn(input, key)),
const selected = callerAnalysisParameters(input)(
parsed.value,
) as SelectedInput;
return ok({ name, input: selected });
};
+17
View File
@@ -16,6 +16,7 @@ import {
createPeImportsService,
createWindowsShortcutService,
createNativeExportsService,
createElfDependenciesService,
} from "../composition/binaryDiagnostics.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
@@ -295,6 +296,22 @@ export const registerBinaryDiagnosticsCommands = (
},
deliverWithService(createNativeExportsService, "rea-native-exports"),
);
registerContractCommand(
cli,
logger,
contract("inspect_elf_dependencies"),
{
description:
"Inspect ELF needed libraries and required symbol versions without executing the image",
positionals: ["path"],
callerPaths: ["path"],
evidenceDelivery: true,
fields: {
path: { description: "Local ELF32/ELF64 ET_EXEC or ET_DYN image" },
},
},
deliverWithService(createElfDependenciesService, "rea-elf-dependencies"),
);
const layout = createBinaryLayoutService(environment);
registerContractCommand(
cli,
+22 -15
View File
@@ -1111,22 +1111,14 @@ const branchOnlyField = (
/**
* An option that must stay omitted when the caller omits it, because the
* input branch or route the caller selects applies its own default on
* admission. Help and `--schema` still state the default, in the
* description and as JSON Schema `default`.
* admission. Help and `--schema` still state the default through the
* schema metadata.
*/
export const withoutDefault = (schema: z.ZodType): z.ZodType => {
if (!(schema instanceof z.ZodDefault)) return schema;
const value: unknown = schema.parse(undefined);
const omittable = (schema.removeDefault() as z.ZodType).optional();
const shown = typeof value === "string" ? value : JSON.stringify(value);
return omittable.meta({
...schema.meta(),
description:
schema.description === undefined
? `Default: ${shown}`
: `${schema.description} (default: ${shown})`,
default: value,
});
return omittable.meta({ ...schema.meta(), default: value });
};
/**
@@ -1941,12 +1933,15 @@ export const describeContractCommand = <
schema = schema.default(projected.default as never);
if (described !== undefined) schema = schema.describe(described);
}
const description =
const described =
projected?.description ??
schema.description ??
describedThroughWrappers(declared);
if (description !== undefined && description !== schema.description)
schema = schema.describe(description);
if (described !== undefined && described !== schema.description)
schema = schema.describe(described);
if (!delivery && projected?.default === undefined)
schema = withoutDefault(schema);
const description = schema.description ?? described;
const value = core(declared);
const selector = selectorOptions[field];
let selectorOption: ContractCliSelectorOption | undefined;
@@ -2350,7 +2345,19 @@ export const describeContractCommand = <
};
return [{ path: [flag], message, issue }];
});
const result = contractChecks.safeParse(toContractInput(options));
// Checks observe execution defaults, while the command retains the
// caller's raw selections. Resolve only omitted fields: supplied
// options have already passed argv admission, and JSON text is not
// decoded until the command runs.
const checkInput = toContractInput(options);
if (checks.length > 0)
for (const [field, declared] of Object.entries(shape)) {
if (Object.hasOwn(checkInput, field)) continue;
const omitted = declared.safeParse(undefined);
if (omitted.success && omitted.data !== undefined)
checkInput[field] = omitted.data;
}
const result = contractChecks.safeParse(checkInput);
return result.success
? conflicts
: [
+18 -15
View File
@@ -78,17 +78,28 @@ const typeName = (field: z.ZodType): string => {
/** A shown default; empty arrays and a `false` boolean default are not shown. */
const shownDefault = (field: z.ZodType, type: string): unknown => {
const metadata = field.meta();
const value =
field instanceof z.ZodDefault
? (field.def.defaultValue as unknown)
: field instanceof z.ZodOptional
? shownDefault(field.unwrap() as z.ZodType, type)
: undefined;
metadata !== undefined && Object.hasOwn(metadata, "default")
? metadata.default
: field instanceof z.ZodDefault
? (field.def.defaultValue as unknown)
: field instanceof z.ZodOptional
? shownDefault(field.unwrap() as z.ZodType, type)
: undefined;
if (Array.isArray(value) && value.length === 0) return undefined;
if (type === "boolean" && value === false) return undefined;
return value;
};
const fieldDescription = (field: z.ZodType, type = typeName(field)): string => {
const defaultValue = shownDefault(field, type);
const description = field.description ?? "";
return defaultValue === undefined
? description
: `${description} (default: ${String(defaultValue)})`;
};
const optionRows = (
options: z.ZodObject,
alias: Readonly<Record<string, string>> | undefined,
@@ -99,15 +110,7 @@ const optionRows = (
const short = alias?.[key];
const value = type === "boolean" ? "" : ` <${type}>`;
const label = `--${optionFlagName(key)}${short === undefined ? "" : `, -${short}`}${value}`;
const defaultValue = shownDefault(field, type);
const description = field.description ?? "";
return {
label,
description:
defaultValue === undefined
? description
: `${description} (default: ${String(defaultValue)})`,
};
return { label, description: fieldDescription(field, type) };
},
);
@@ -200,7 +203,7 @@ export const formatCommandHelp = (name: string, help: CommandHelp): string => {
(help.args?.shape ?? {}) as Readonly<Record<string, z.ZodType>>,
).map(([key, field]) => ({
label: key,
description: field.description ?? "",
description: fieldDescription(field),
}));
if (args.length > 0) lines.push("", "Arguments:", ...alignedRows(args));
const options =
+6
View File
@@ -26,6 +26,8 @@ import { AppleIpsService } from "../application/binaryDiagnostics/AppleIpsServic
import { AppleIpsProvider } from "../native/apple/AppleIpsProvider.js";
import { KernelModuleService } from "../application/binaryDiagnostics/KernelModuleService.js";
import { KernelModuleProvider } from "../native/elf/KernelModuleProvider.js";
import { ElfDependenciesService } from "../application/binaryDiagnostics/ElfDependenciesService.js";
import { ElfDependenciesProvider } from "../native/elf/ElfDependenciesProvider.js";
import { KernelBuildConfigService } from "../application/binaryDiagnostics/KernelBuildConfigService.js";
import { KernelBuildConfigProvider } from "../native/elf/KernelBuildConfigProvider.js";
import type { ArtifactResourceScope } from "../resources/index.js";
@@ -77,6 +79,10 @@ export const createKernelModuleService = (): KernelModuleService =>
export const createKernelBuildConfigService = (): KernelBuildConfigService =>
new KernelBuildConfigService(new KernelBuildConfigProvider());
/** Portable ELF dynamic-dependency inspection with no loader or host `ldd`. */
export const createElfDependenciesService = (): ElfDependenciesService =>
new ElfDependenciesService(new ElfDependenciesProvider());
/** Compose the offline adapter without import-time I/O or dependency acquisition. */
export const createBinaryLayoutService = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
@@ -31,6 +31,7 @@ import {
BINARY_HARDENING_PROVIDER,
BYTE_ENTROPY_PROVIDER,
DEVICETREE_PROVIDER,
ELF_DEPENDENCIES_PROVIDER,
ELF_NOTES_PROVIDER,
ELF_UNWIND_RANGES_PROVIDER,
HARMONY_APPLICATION_PROVIDER,
@@ -261,6 +262,11 @@ export const CAPABILITY_DECLARATIONS = {
]),
],
},
elfDependencies: {
providers: [
providerBinding(ELF_DEPENDENCIES_PROVIDER, ["inspect_elf_dependencies"]),
],
},
elfNotes: {
providers: [providerBinding(ELF_NOTES_PROVIDER, ["inspect_elf_notes"])],
},
+2
View File
@@ -80,6 +80,7 @@ import {
createElfUnwindRangesService,
createAppleIpsService,
createKernelModuleService,
createElfDependenciesService,
createKernelBuildConfigService,
} from "./binaryDiagnostics.js";
import { pwntoolsHostSupported } from "../native/pwntools/PwntoolsDecoder.js";
@@ -377,6 +378,7 @@ const modules = {
elfUnwindRanges: service(() => createElfUnwindRangesService()),
appleIps: service(() => createAppleIpsService()),
kernelModule: service(() => createKernelModuleService()),
elfDependencies: service(() => createElfDependenciesService()),
kernelBuildConfig: service(() => createKernelBuildConfigService()),
peLoadConfig: service(() => createPeLoadConfigService()),
binaryHardening: service(() => createBinaryHardeningService()),
@@ -6,6 +6,7 @@ import {
devicetreeSummaryViewResultSchema,
binaryLayoutSummaryViewResultSchema,
nativeExportsSummaryViewResultSchema,
elfDependenciesSummaryViewResultSchema,
} from "../../domain/analysisView/analysisViewResult.js";
import {
inspectPeLoadConfigInputSchema,
@@ -72,6 +73,10 @@ import {
inspectKernelModuleInputSchema,
kernelModuleSchema,
} from "../../domain/native/kernelModule.js";
import {
inspectElfDependenciesInputSchema,
elfDependenciesSchema,
} from "../../domain/native/elfDependencies.js";
import {
inspectKernelBuildConfigInputSchema,
kernelBuildConfigSchema,
@@ -88,6 +93,9 @@ export const inspectBinaryLayoutRequestSchema =
export const inspectNativeExportsRequestSchema =
inspectNativeExportsInputSchema.extend({ detail: analysisDetailSchema });
export const inspectElfDependenciesRequestSchema =
inspectElfDependenciesInputSchema.extend({ detail: analysisDetailSchema });
/** Public byte-entropy input retains the producer schema's closed-object policy. */
export const inspectByteEntropyRequestSchema =
inspectByteEntropyInputSchema.extend({ detail: analysisDetailSchema });
@@ -245,6 +253,26 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
},
],
},
{
name: "inspect_elf_dependencies",
availability: "standalone",
cli: true,
...toolContractMetadata("inspect_elf_dependencies", evidenceEffects),
kind: "native-provider",
description:
"Inspect one explicit local ELF32/ELF64 ET_EXEC or ET_DYN image's load-time dynamic dependencies without executing it, invoking the dynamic loader, or opening a disassembler. Returns ordered DT_NEEDED libraries (duplicates preserved), DT_SONAME, DT_RPATH and DT_RUNPATH as written including $ORIGIN/$LIB/$PLATFORM tokens, decoded DT_FLAGS and DT_FLAGS_1, PT_INTERP, GNU version requirements and definitions, derived per-namespace version maxima, and undefined .dynsym imports joined to library@version when known. A missing PT_DYNAMIC is an observed empty inventory. Relocatable objects use inspect_kernel_module; core dumps use inspect_recorded_crash. Reads a stable regular file; cyclic version chains and exhausted named budgets return no partial success. Unreadable strings or missing tables are reported as partial coverage with issues; complete coverage never retains issues. Omitted/complete detail preserves inline delivery. Select detail summary to retain complete Evidence and return identity, counts and source coverage. Query inspect_analysis_view kind elf-dependencies, collection needed, versions, definitions, maxima or imports, with exact names/original indices, fields and matching-row pagination; collection issues takes original indices and pagination only. Portable on supported Node hosts.",
inputSchema: inspectElfDependenciesRequestSchema,
outputSchema: analysisDetailOutputSchemaOf(
elfDependenciesSchema,
elfDependenciesSummaryViewResultSchema,
),
examples: [
{
title: "Inspect ELF needed libraries and required symbol versions",
input: { path: "/artifacts/program" },
},
],
},
{
name: "inspect_kernel_build_config",
availability: "standalone",
+2
View File
@@ -16,6 +16,7 @@ import { byteEntropySchema } from "../native/byteEntropy.js";
import { projectErlangBeamView } from "./erlangBeamView.js";
import { projectPythonPycView } from "./pythonPycView.js";
import { projectNativeExportsView } from "./nativeExportsView.js";
import { projectElfDependenciesView } from "./elfDependenciesView.js";
import { projectByteEntropyView } from "./byteEntropyView.js";
import {
parseAnalysisViewResult,
@@ -198,6 +199,7 @@ const retainedViewProjectors = new Map<string, RetainedViewProjector>([
retain("inspect_erlang_beam", projectErlangBeamView),
retain("inspect_devicetree", projectDevicetreeView),
retain("inspect_native_exports", projectNativeExportsView),
retain("inspect_elf_dependencies", projectElfDependenciesView),
retain("inspect_native_load_image", projectNativeLoadImageView),
retain("inspect_python_pyc", projectPythonPycView),
retain("frida_session_status", projectFridaSessionStatusView),
@@ -13,6 +13,7 @@ import { apkSignatureViewRequestSchema } from "../apkSignature/apkSignatureQuery
import { erlangBeamViewRequestSchema } from "./erlangBeamView.js";
import { pythonPycViewRequestSchema } from "./pythonPycView.js";
import { nativeExportsViewRequestSchema } from "./nativeExportsView.js";
import { elfDependenciesViewRequestSchema } from "./elfDependenciesView.js";
import { javaScriptRoutesViewRequestSchema } from "./javascriptRoutesView.js";
import { webBundleViewRequestSchema } from "./webBundleView.js";
import { sourceToBundleViewRequestSchema } from "./sourceToBundleView.js";
@@ -86,6 +87,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
erlangBeamViewRequestSchema,
pythonPycViewRequestSchema,
nativeExportsViewRequestSchema,
elfDependenciesViewRequestSchema,
javaScriptRoutesViewRequestSchema,
webBundleViewRequestSchema,
nativeFunctionMatchingViewRequestSchema,
@@ -82,6 +82,11 @@ import {
nativeExportsViewItemsSchema,
nativeExportsSummarySchema,
} from "./nativeExportsView.js";
import {
elfDependenciesViewRequestSchema,
elfDependenciesViewItemsSchema,
elfDependenciesSummarySchema,
} from "./elfDependenciesView.js";
import { procedurePseudocodeSummarySchema } from "./procedurePseudocodeSchemas.js";
import { byteEntropySummarySchema } from "./byteEntropyView.js";
import {
@@ -369,6 +374,7 @@ const viewResultBase = {
"inspect_devicetree",
"inspect_byte_entropy",
"inspect_native_exports",
"inspect_elf_dependencies",
"inspect_binary_layout",
"inspect_go_binary",
"gdb_console",
@@ -540,6 +546,12 @@ export const byteEntropySummaryViewResultSchema = z.strictObject({
parent_operation: z.literal("inspect_byte_entropy"),
});
export const elfDependenciesSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_elf_dependencies"),
summary: elfDependenciesSummarySchema,
});
export const nativeExportsSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_native_exports"),
@@ -1374,6 +1386,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
devicetreeSummaryViewResultSchema,
pythonPycSummaryViewResultSchema,
nativeExportsSummaryViewResultSchema,
elfDependenciesSummaryViewResultSchema,
byteEntropySummaryViewResultSchema,
gdbCommandSummaryViewResultSchema,
objdumpSummaryViewResultSchema,
@@ -1436,6 +1449,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
exports: nativeExportsSummarySchema,
items: nativeExportsViewItemsSchema,
}),
z.strictObject({
...viewResultBase,
kind: z.literal("elf-dependencies"),
parent_operation: z.literal("inspect_elf_dependencies"),
view: elfDependenciesViewRequestSchema,
dependencies: elfDependenciesSummarySchema,
items: elfDependenciesViewItemsSchema,
}),
z.strictObject({
...viewResultBase,
...nativeViewSourceContext,
@@ -0,0 +1,364 @@
import { z } from "zod";
import {
elfDependenciesReportSchema,
elfDependenciesSchema,
type ElfDependencies,
} from "../native/elfDependencies.js";
import { err, ok } from "../result.js";
import type { AnalysisViewParent } from "./analysisViewParent.js";
import {
assertOwnedView,
type AdmittedView,
type SummaryAnalysisView,
} from "./analysisViewShape.js";
import { analysisViewInputError } from "./analysisViewErrors.js";
import { createAnalysisViewResultReader } from "./analysisViewParent.js";
import {
boundedViewMessages,
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
import { selectViewRows } from "./selectViewRows.js";
const neededRow = elfDependenciesReportSchema.shape.needed.element;
const importRow = elfDependenciesReportSchema.shape.imports.element;
const issueRow = elfDependenciesReportSchema.shape.issues.element;
const definitionTable = elfDependenciesReportSchema.shape.version_definitions;
const definitionRow = definitionTable.shape.names.element;
const maximumRow =
elfDependenciesReportSchema.shape.derived_version_maxima.element;
const sourceIndex = { source_index: z.int().nonnegative() };
const page = {
kind: z.literal("elf-dependencies"),
offset: z.int().nonnegative().default(0),
limit: z.int().positive().default(64),
};
const versionRowSchema = z.strictObject({
file: z.string().min(1).nullable(),
name: z.string().min(1).nullable(),
hash: z.number().int().min(0).max(0xffffffff),
flags: z.strictObject({ weak: z.boolean() }),
index: z.number().int().min(0).max(0x7fff),
});
/** Exact names preserve duplicate DT_NEEDED rows; indices are scoped to the complete parent. */
export const elfDependenciesViewRequestSchema = z.discriminatedUnion(
"collection",
[
z.strictObject({
...page,
collection: z.literal("needed"),
names: z
.array(z.string())
.optional()
.describe(
"Exact DT_NEEDED names. Omitted includes all names; [] matches none.",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(neededRow.keyof()).optional(),
}),
z.strictObject({
...page,
collection: z.literal("versions"),
names: z
.array(z.string())
.optional()
.describe(
"Exact version names. Omitted includes all names; [] matches none.",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(versionRowSchema.keyof()).optional(),
}),
z.strictObject({
...page,
collection: z.literal("definitions"),
names: z
.array(z.string())
.optional()
.describe(
"Exact GNU version-definition names. Omitted includes all names; [] matches none.",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(definitionRow.keyof()).optional(),
}),
z.strictObject({
...page,
collection: z.literal("maxima"),
names: z
.array(z.string())
.optional()
.describe(
"Exact version namespaces, such as GLIBC. Omitted includes all namespaces; [] matches none.",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(maximumRow.keyof()).optional(),
}),
z.strictObject({
...page,
collection: z.literal("imports"),
names: z
.array(z.string())
.optional()
.describe(
"Exact undefined-symbol names. Omitted includes all names; [] matches none.",
),
indices: z.array(z.int().nonnegative()).optional(),
fields: z.array(importRow.keyof()).optional(),
}),
z.strictObject({
...page,
collection: z.literal("issues"),
indices: z.array(z.int().nonnegative()).optional(),
}),
],
);
export const elfDependenciesViewItemsSchema = z.union([
z.array(neededRow.partial().extend(sourceIndex)),
z.array(versionRowSchema.partial().extend(sourceIndex)),
z.array(definitionRow.partial().extend(sourceIndex)),
z.array(maximumRow.partial().extend(sourceIndex)),
z.array(importRow.partial().extend(sourceIndex)),
z.array(issueRow.extend(sourceIndex)),
]);
const counts = {
needed_count: z.int().nonnegative(),
version_count: z.int().nonnegative(),
definition_count: z.int().nonnegative(),
derived_maximum_count: z.int().nonnegative(),
import_count: z.int().nonnegative(),
issue_count: z.int().nonnegative(),
limitation_count: z.int().nonnegative(),
};
/** Source coverage remains distinct from page coverage, including an empty partial page. */
export const elfDependenciesSummarySchema = elfDependenciesReportSchema
.omit({
needed: true,
imports: true,
issues: true,
limitations: true,
version_requirements: true,
version_definitions: true,
derived_version_maxima: true,
})
.extend({
...counts,
version_definitions: definitionTable.omit({ names: true }),
});
const readReport = createAnalysisViewResultReader(elfDependenciesSchema);
const flattenVersions = (report: ElfDependencies) =>
report.version_requirements.files.flatMap((file) =>
file.versions.map((version) => ({
file: file.file,
name: version.name,
hash: version.hash,
flags: version.flags,
index: version.index,
})),
);
/** Read selected dynamic-dependency facts without reopening the artifact. */
export const projectElfDependenciesView = (
parent: AnalysisViewParent,
view: AdmittedView,
) => {
const invalid = (message: string) =>
err(
analysisViewInputError([
{ path: ["view"], reason: "invalid_value", message },
]),
);
if (view.kind !== "summary" && view.kind !== "elf-dependencies")
return invalid(
"ELF dependency Evidence supports summary and elf-dependencies views.",
);
assertOwnedView<
SummaryAnalysisView | z.output<typeof elfDependenciesViewRequestSchema>
>(view, "summary", "elf-dependencies");
const parsed = readReport(parent);
if (!parsed.ok) return parsed;
const report = parsed.value;
const versions = flattenVersions(report);
const summary = {
artifact: report.artifact,
format: report.format,
byte_order: report.byte_order,
machine: report.machine,
architecture: report.architecture,
type: report.type,
type_name: report.type_name,
interpreter: report.interpreter,
dynamic: report.dynamic,
version_definitions: {
status: report.version_definitions.status,
location: report.version_definitions.location,
},
coverage: report.coverage,
needed_count: report.needed.length,
version_count: versions.length,
definition_count: report.version_definitions.names.length,
derived_maximum_count: report.derived_version_maxima.length,
import_count: report.imports.length,
issue_count: report.issues.length,
limitation_count: report.limitations.length,
};
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_elf_dependencies" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: boundedViewMessages(
[...parent.limitations, ...report.limitations],
parent.evidenceId,
"limitations",
),
unknowns:
report.coverage.status === "complete"
? []
: [
report.coverage.reason ??
"Dynamic-dependency coverage is incomplete; no-match pages do not prove absence.",
],
};
if (view.kind === "summary")
return ok({
...shared,
kind: "summary" as const,
view,
summary,
coverage: completeWithinViewCoverage(report.needed.length),
});
const indices =
view.indices === undefined ? undefined : new Set(view.indices);
if (view.collection === "issues") {
const selected =
indices === undefined
? {
rows: report.issues
.slice(view.offset, view.offset + view.limit)
.map((row, index) => ({
...row,
source_index: view.offset + index,
})),
total: report.issues.length,
}
: selectViewRows(
report.issues,
view,
(_, index) => indices.has(index),
(row, source_index) => ({ ...row, source_index }),
);
return ok({
...shared,
kind: "elf-dependencies" as const,
view,
dependencies: summary,
items: selected.rows,
coverage: pageViewCoverage(
view.offset,
selected.rows.length,
selected.total,
),
});
}
const names = view.names === undefined ? undefined : new Set(view.names);
const pageRows = <Row extends Record<string, unknown>>(
rows: readonly Row[],
allowed: readonly string[],
fieldsOf: readonly string[] | undefined,
label: string,
nameOf: (row: Row) => string | null,
) => {
const fields = fieldsOf === undefined ? allowed : [...new Set(fieldsOf)];
if (fields.some((field) => !allowed.includes(field)))
return invalid(
`Selected ${label} fields do not belong to those rows; available fields: ${allowed.join(", ")}.`,
);
const columns = new Set<string>(fields);
const projectRow = (row: Row, source_index: number) => ({
...Object.fromEntries(
Object.entries(row).filter(([key]) => columns.has(key)),
),
source_index,
});
const selected =
names === undefined && indices === undefined
? {
rows: rows
.slice(view.offset, view.offset + view.limit)
.map((row, index) => projectRow(row, view.offset + index)),
total: rows.length,
}
: selectViewRows(
rows,
view,
(row, index) => {
const name = nameOf(row);
return (
(indices === undefined || indices.has(index)) &&
(names === undefined || (name !== null && names.has(name)))
);
},
projectRow,
);
return ok({
...shared,
kind: "elf-dependencies" as const,
view,
dependencies: summary,
items: selected.rows,
coverage: pageViewCoverage(
view.offset,
selected.rows.length,
selected.total,
),
});
};
switch (view.collection) {
case "needed":
return pageRows(
report.needed,
neededRow.keyof().options,
view.fields,
"needed",
(row) => row.name,
);
case "versions":
return pageRows(
versions,
versionRowSchema.keyof().options,
view.fields,
"version",
(row) => row.name,
);
case "definitions":
return pageRows(
report.version_definitions.names,
definitionRow.keyof().options,
view.fields,
"version-definition",
(row) => row.name,
);
case "maxima":
return pageRows(
report.derived_version_maxima,
maximumRow.keyof().options,
view.fields,
"derived-maximum",
(row) => row.namespace,
);
case "imports":
return pageRows(
report.imports,
importRow.keyof().options,
view.fields,
"import",
(row) => row.name,
);
}
};
+1
View File
@@ -83,6 +83,7 @@ export class ArtifactOperationError extends AnalysisError {
| "inspect_api_contract"
| "inspect_playwright_trace"
| "inspect_kernel_module"
| "inspect_elf_dependencies"
| "inspect_kernel_build_config"
| "inspect_erlang_beam"
| "inspect_v8_code_cache"
+7
View File
@@ -80,6 +80,13 @@ export const KERNEL_MODULE_PROVIDER = Object.freeze({
version: "1",
} as const);
/** Provider identity for portable, execution-free ELF dynamic-dependency inventories. */
export const ELF_DEPENDENCIES_PROVIDER = Object.freeze({
id: "rea-elf-dependencies",
name: "REA ELF dependency parser",
version: "1",
} as const);
/** Provider identity for portable, execution-free ELF and Mach-O initializer and finalizer tables. */
export const NATIVE_INITIALIZERS_PROVIDER = Object.freeze({
id: "rea-native-initializers",
+139
View File
@@ -0,0 +1,139 @@
import { expect, it } from "vitest";
import {
decodeElfDynamicFlags,
derivedElfVersionMaxima,
DF_1_FLAG_BITS,
DF_FLAG_BITS,
elfSearchPathTokens,
inspectElfDependenciesInputSchema,
splitElfSearchPath,
} from "./elfDependencies.js";
it("rejects extra caller arguments and applies dependency budgets", () => {
expect(
inspectElfDependenciesInputSchema.safeParse({
path: "/artifacts/program",
extra: true,
}).success,
).toBe(false);
expect(
inspectElfDependenciesInputSchema.parse({ path: "/artifacts/program" }),
).toMatchObject({
max_file_bytes: 67108864,
max_needed: 1024,
max_versions: 4096,
max_imports: 65536,
});
});
it("splits search paths without dropping empty entries and reports tokens as written", () => {
expect(splitElfSearchPath("$ORIGIN/../lib:$LIB:${PLATFORM}/lib:")).toEqual([
"$ORIGIN/../lib",
"$LIB",
"${PLATFORM}/lib",
"",
]);
expect(
elfSearchPathTokens("$ORIGIN/../lib:$LIB:${PLATFORM}/lib:$ORIGIN"),
).toEqual(["$ORIGIN", "$LIB", "$PLATFORM"]);
expect(elfSearchPathTokens("/usr/lib")).toEqual([]);
});
it("derives the highest GNU-style NAME_x.y string per namespace", () => {
expect(
derivedElfVersionMaxima([
"GLIBC_2.2.5",
"GLIBC_2.34",
"GLIBCXX_3.4.29",
"not-a-version",
]),
).toEqual([
{ namespace: "GLIBC", maximum: "GLIBC_2.34", evidence_kind: "derived" },
{
namespace: "GLIBCXX",
maximum: "GLIBCXX_3.4.29",
evidence_kind: "derived",
},
]);
});
it("compares large version components exactly and skips empty namespaces", () => {
expect(
derivedElfVersionMaxima([
"LIB_9007199254740993",
"LIB_9007199254740992",
"LIB_9007199254740994",
"_2.5",
]),
).toEqual([
{
namespace: "LIB",
maximum: "LIB_9007199254740994",
evidence_kind: "derived",
},
]);
expect(
derivedElfVersionMaxima(["LIB_9007199254740992", "LIB_9007199254740993"]),
).toEqual([
{
namespace: "LIB",
maximum: "LIB_9007199254740993",
evidence_kind: "derived",
},
]);
});
it("decodes named DT_FLAGS and DT_FLAGS_1 bits without expanding unrecognized values", () => {
expect(decodeElfDynamicFlags(0x9, DF_FLAG_BITS)).toEqual({
raw: 0x9,
names: ["ORIGIN", "BIND_NOW"],
unrecognized: 0,
});
expect(decodeElfDynamicFlags(0x08000881, DF_1_FLAG_BITS)).toEqual({
raw: 0x08000881,
names: ["NOW", "ORIGIN", "NODEFLIB", "PIE"],
unrecognized: 0,
});
expect(decodeElfDynamicFlags(0x80000008, DF_FLAG_BITS)).toEqual({
raw: 0x80000008,
names: ["BIND_NOW"],
unrecognized: 0x80000000,
});
expect(decodeElfDynamicFlags(0x100000008, DF_FLAG_BITS)).toEqual({
raw: 0x100000008,
names: ["BIND_NOW"],
unrecognized: 0x100000000,
});
});
it("orders dotted suffixes by integer components", () => {
const long = Array.from({ length: 30000 }, () => "1").join(".");
expect(
derivedElfVersionMaxima([
"A_1.9",
"A_01.10",
"B_1.2",
"B_1.2.0.1",
"C_1.0",
"C_1",
`D_${long}`,
`D_${long}.0.2`,
`D_${long}.0.1`,
]).map((entry) => entry.maximum),
).toEqual(["A_01.10", "B_1.2.0.1", "C_1.0", `D_${long}.0.2`]);
});
it("does not rescan a long saved maximum for each shorter equal version", () => {
const zeros = Array.from({ length: 30000 }, () => "0").join(".");
const names = [`A_1.${zeros}`, ...Array.from({ length: 4094 }, () => "A_1")];
const started = performance.now();
expect(derivedElfVersionMaxima(names).map((entry) => entry.maximum)).toEqual([
`A_1.${zeros}`,
]);
expect(performance.now() - started).toBeLessThan(500);
expect(
derivedElfVersionMaxima(["B_1.0.0", "B_1", "B_1.0.1", "B_1.0.01.0"]).map(
(entry) => entry.maximum,
),
).toEqual(["B_1.0.1"]);
});
+433
View File
@@ -0,0 +1,433 @@
import { z } from "zod";
import { digestSchema } from "../digests.js";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import { ELF_OBJECT_TYPE_NAMES } from "./elfNotes.js";
import { coverageStatusSchema } from "../coverage.js";
const uint = z.number().int().min(0).max(0xffffffff);
const range = z.strictObject({ offset: uint, bytes: uint });
/** Hard ceiling on the caller-selected input read budget. */
export const MAX_INSPECT_ELF_DEPENDENCY_FILE_BYTES = 536870912;
/** Hard ceiling on DT_NEEDED entries examined in one image. */
export const MAX_INSPECT_ELF_DEPENDENCY_NEEDED = 65536;
/** Hard ceiling on GNU version requirement and definition records. */
export const MAX_INSPECT_ELF_DEPENDENCY_VERSIONS = 65536;
/** Hard ceiling on undefined dynamic symbols examined as imports. */
export const MAX_INSPECT_ELF_DEPENDENCY_IMPORTS = 262144;
/** DT_FLAGS bits decoded by name. Unrecognized bits stay numeric. */
export const DF_FLAG_BITS = [
[0x00000001, "ORIGIN"],
[0x00000002, "SYMBOLIC"],
[0x00000004, "TEXTREL"],
[0x00000008, "BIND_NOW"],
[0x00000010, "STATIC_TLS"],
] as const;
/** DT_FLAGS_1 bits decoded by name. Unrecognized bits stay numeric. */
export const DF_1_FLAG_BITS = [
[0x00000001, "NOW"],
[0x00000002, "GLOBAL"],
[0x00000004, "GROUP"],
[0x00000008, "NODELETE"],
[0x00000010, "LOADFLTR"],
[0x00000020, "INITFIRST"],
[0x00000040, "NOOPEN"],
[0x00000080, "ORIGIN"],
[0x00000100, "DIRECT"],
[0x00000200, "TRANS"],
[0x00000400, "INTERPOSE"],
[0x00000800, "NODEFLIB"],
[0x00001000, "NODUMP"],
[0x00002000, "CONFALT"],
[0x00004000, "ENDFILTEE"],
[0x00008000, "DISPRELDNE"],
[0x00010000, "DISPRELPND"],
[0x00020000, "NODIRECT"],
[0x00040000, "IGNMULDEF"],
[0x00080000, "NOKSYMS"],
[0x00100000, "NOHDR"],
[0x00200000, "EDITED"],
[0x00400000, "NORELOC"],
[0x00800000, "SYMINTPOSE"],
[0x01000000, "GLOBAUDIT"],
[0x02000000, "SINGLETON"],
[0x04000000, "STUB"],
[0x08000000, "PIE"],
[0x10000000, "KMOD"],
[0x20000000, "WEAKFILTER"],
[0x40000000, "NOCOMMON"],
] as const;
export const ELF_DEPENDENCY_SEARCH_TOKENS = [
"$ORIGIN",
"$LIB",
"$PLATFORM",
] as const;
export const ELF_DEPENDENCY_ISSUE_CODES = [
"malformed_entry",
"name_unreadable",
"table_unavailable",
"version_unresolved",
] as const;
const searchTokenSchema = z.enum(ELF_DEPENDENCY_SEARCH_TOKENS);
/** Named DT_FLAGS / DT_FLAGS_1 bits plus any bits the table did not name. */
export const decodeElfDynamicFlags = (
raw: number,
bits: readonly (readonly [number, string])[],
): { raw: number; names: string[]; unrecognized: number } => {
// ELF64 flag words outrun the 32-bit bitwise operators.
const word = BigInt(raw);
const names: string[] = [];
let unrecognized = word;
for (const [mask, name] of bits) {
const bit = BigInt(mask);
if ((word & bit) !== 0n) {
names.push(name);
unrecognized &= ~bit;
}
}
return { raw, names, unrecognized: Number(unrecognized) };
};
/** Split a DT_RPATH / DT_RUNPATH value on ':' without dropping empty entries. */
export const splitElfSearchPath = (raw: string): string[] => raw.split(":");
/** Report $ORIGIN / $LIB / $PLATFORM tokens as written, including ${...} forms. */
export const elfSearchPathTokens = (
raw: string,
): (typeof ELF_DEPENDENCY_SEARCH_TOKENS)[number][] => {
const found: (typeof ELF_DEPENDENCY_SEARCH_TOKENS)[number][] = [];
const seen = new Set<string>();
const pattern = /\$(?:\{(ORIGIN|LIB|PLATFORM)\}|(ORIGIN|LIB|PLATFORM)\b)/g;
for (const match of raw.matchAll(pattern)) {
const name = match[1] ?? match[2];
if (name === undefined) continue;
const token = `$${name}` as (typeof ELF_DEPENDENCY_SEARCH_TOKENS)[number];
if (seen.has(token)) continue;
seen.add(token);
found.push(token);
}
return found;
};
const VERSION_NAME = /^(.*)_([0-9]+(?:\.[0-9]+)*)$/u;
/** Compare two unsigned decimal strings by integer value. */
const compareDecimal = (left: string, right: string): number => {
let l = 0;
while (l < left.length - 1 && left[l] === "0") l += 1;
let r = 0;
while (r < right.length - 1 && right[r] === "0") r += 1;
const a = left.slice(l);
const b = right.slice(r);
if (a.length !== b.length) return a.length < b.length ? -1 : 1;
return a === b ? 0 : a < b ? -1 : 1;
};
/**
* Canonical form of a dotted version suffix: leading zeros removed from each
* component and trailing zero components dropped, so `1.02.0.0` reads `1.2`.
* Built once per name; two equal versions then have equal canonical strings.
*/
const canonicalVersionSuffix = (suffix: string): string => {
const components = suffix
.split(".")
.map((component) => component.replace(/^0+(?=.)/u, ""));
let length = components.length;
while (length > 1 && components[length - 1] === "0") length -= 1;
return components.slice(0, length).join(".");
};
/**
* Integer order on canonical dotted version suffixes, missing components
* reading as 0. A canonical suffix ends in a nonzero component, so when one
* runs out first the other is greater: the walk stops at the shorter suffix,
* and a long saved maximum is never rescanned past it.
*/
const compareVersionSuffixes = (left: string, right: string): number => {
if (left === right) return 0;
const componentEnd = (value: string, start: number): number => {
const dot = value.indexOf(".", start);
return dot === -1 ? value.length : dot;
};
let l = 0;
let r = 0;
while (l < left.length && r < right.length) {
const lEnd = componentEnd(left, l);
const rEnd = componentEnd(right, r);
const order = compareDecimal(left.slice(l, lEnd), right.slice(r, rEnd));
if (order !== 0) return order;
l = lEnd + 1;
r = rEnd + 1;
}
if (l < left.length) return left === "0" ? 0 : 1;
if (r < right.length) return right === "0" ? 0 : -1;
return 0;
};
/**
* Highest GNU-style NAME_x.y string per namespace. Comparison is exact integer
* order on the dotted suffix; names that do not match, or that have an empty
* namespace, stay out of the derived set while their requirements remain.
*/
export const derivedElfVersionMaxima = (
names: readonly string[],
): { namespace: string; maximum: string; evidence_kind: "derived" }[] => {
const best = new Map<string, { maximum: string; suffix: string }>();
for (const name of names) {
const match = VERSION_NAME.exec(name);
if (match === null || match[1] === undefined || match[2] === undefined)
continue;
const namespace = match[1];
if (namespace.length === 0) continue;
const suffix = canonicalVersionSuffix(match[2]);
const current = best.get(namespace);
if (
current === undefined ||
compareVersionSuffixes(suffix, current.suffix) > 0
)
best.set(namespace, { maximum: name, suffix });
}
return [...best.entries()].map(([namespace, value]) => ({
namespace,
maximum: value.maximum,
evidence_kind: "derived" as const,
}));
};
/** Complete bounded inspection of one loadable ELF dynamic-dependency inventory. */
export const inspectElfDependenciesInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute filesystem path to an ELF32/ELF64 ET_EXEC or ET_DYN image",
),
max_file_bytes: z
.number()
.int()
.min(64)
.max(MAX_INSPECT_ELF_DEPENDENCY_FILE_BYTES)
.default(67108864)
.describe("Maximum stable artifact bytes to read (default 64 MiB)"),
max_needed: z
.number()
.int()
.min(1)
.max(MAX_INSPECT_ELF_DEPENDENCY_NEEDED)
.default(1024)
.describe(
"Maximum DT_NEEDED entries to examine; exceeding the budget fails without partial success",
),
max_versions: z
.number()
.int()
.min(1)
.max(MAX_INSPECT_ELF_DEPENDENCY_VERSIONS)
.default(4096)
.describe(
"Maximum GNU version requirement and definition records to examine; exceeding the budget fails without partial success",
),
max_imports: z
.number()
.int()
.min(1)
.max(MAX_INSPECT_ELF_DEPENDENCY_IMPORTS)
.default(65536)
.describe(
"Maximum undefined dynamic symbols to examine as imports; exceeding the budget fails without partial success",
),
});
export type InspectElfDependenciesInput = z.infer<
typeof inspectElfDependenciesInputSchema
>;
/** A whole flag word: ELF64 values may set bits above the low 32. */
const flagWord = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const flagsSchema = z.strictObject({
raw: flagWord,
names: z.array(z.string().min(1)),
unrecognized: flagWord,
});
const searchPathSchema = z.strictObject({
raw: z.string(),
entries: z.array(z.string()),
tokens: z.array(searchTokenSchema),
});
/** A dynamic string offset: ELF64 values may exceed 32 bits. */
const stringOffset = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const neededEntrySchema = z.strictObject({
index: uint,
name: z.string().min(1).nullable(),
name_offset: stringOffset,
});
const versionNeedSchema = z.strictObject({
name: z.string().min(1).nullable(),
hash: uint,
flags: z.strictObject({ weak: z.boolean() }),
index: z.number().int().min(0).max(0x7fff),
});
const versionNeedFileSchema = z.strictObject({
file: z.string().min(1).nullable(),
versions: z.array(versionNeedSchema),
});
const versionDefinitionSchema = z.strictObject({
name: z.string().min(1).nullable(),
index: z.number().int().min(0).max(0x7fff),
base: z.boolean(),
});
const derivedMaximumSchema = z.strictObject({
namespace: z.string().min(1),
maximum: z.string().min(1),
evidence_kind: z.literal("derived"),
});
const importVersionSchema = z.strictObject({
index: z.number().int().min(0).max(0x7fff),
hidden: z.boolean(),
name: z.string().min(1).nullable(),
file: z.string().min(1).nullable(),
status: z.enum(["unversioned", "resolved", "unknown"]),
});
const importSchema = z.strictObject({
index: uint,
name: z.string().min(1).nullable(),
binding: z.enum(["local", "global", "weak", "unique", "other"]),
type: z.enum(["function", "object", "ifunc", "tls", "other"]),
version: importVersionSchema.nullable(),
});
const issueSchema = z.strictObject({
code: z.enum(ELF_DEPENDENCY_ISSUE_CODES),
location: z.string().min(1).nullable(),
message: z.string().min(1),
});
const coverageSchema = z.strictObject({
status: coverageStatusSchema,
reason: z.string().min(1).nullable(),
examined_needed: uint,
examined_versions: uint,
examined_imports: uint,
});
/** Static load-time dependency inventory of one ELF ET_EXEC/ET_DYN image. */
export const elfDependenciesReportSchema = 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,
architecture: z.string().min(1),
type: uint,
type_name: z.enum(ELF_OBJECT_TYPE_NAMES),
interpreter: z.strictObject({
status: z.enum(["present", "absent", "unreadable"]),
path: z.string().min(1).nullable(),
location: range.nullable(),
}),
dynamic: z.strictObject({
status: z.enum(["present", "absent"]),
location: range.nullable(),
soname: z
.strictObject({
name: z.string().min(1).nullable(),
name_offset: stringOffset,
})
.nullable(),
rpath: searchPathSchema.nullable(),
runpath: searchPathSchema.nullable(),
flags: flagsSchema.nullable(),
flags_1: flagsSchema.nullable(),
}),
needed: z.array(neededEntrySchema),
version_requirements: z.strictObject({
status: z.enum(["present", "absent", "unreadable"]),
location: range.nullable(),
files: z.array(versionNeedFileSchema),
}),
version_definitions: z.strictObject({
status: z.enum(["present", "absent", "unreadable"]),
location: range.nullable(),
names: z.array(versionDefinitionSchema),
}),
derived_version_maxima: z.array(derivedMaximumSchema),
imports: z.array(importSchema),
coverage: coverageSchema,
issues: z.array(issueSchema),
limitations: z.array(z.string().min(1)),
});
export const elfDependenciesSchema = elfDependenciesReportSchema.superRefine(
(value, context) => {
if (value.coverage.examined_needed !== value.needed.length)
context.addIssue({
code: "custom",
path: ["coverage", "examined_needed"],
message:
"Needed coverage count must equal the retained DT_NEEDED rows.",
});
if (value.coverage.examined_imports !== value.imports.length)
context.addIssue({
code: "custom",
path: ["coverage", "examined_imports"],
message:
"Import coverage count must equal the retained undefined-symbol rows.",
});
if (value.coverage.status === "complete" && value.issues.length > 0)
context.addIssue({
code: "custom",
path: ["coverage", "status"],
message: "Complete coverage cannot retain table issues.",
});
if (value.coverage.status === "partial" && value.issues.length === 0)
context.addIssue({
code: "custom",
path: ["coverage", "status"],
message: "Partial coverage requires at least one table issue.",
});
if (value.dynamic.status === "absent") {
if (
value.dynamic.location !== null ||
value.dynamic.soname !== null ||
value.dynamic.rpath !== null ||
value.dynamic.runpath !== null ||
value.dynamic.flags !== null ||
value.dynamic.flags_1 !== null ||
value.needed.length !== 0
)
context.addIssue({
code: "custom",
path: ["dynamic"],
message:
"An absent PT_DYNAMIC inventory cannot retain dynamic entries.",
});
} else if (value.dynamic.location === null)
context.addIssue({
code: "custom",
path: ["dynamic", "location"],
message: "A present dynamic segment must retain its file range.",
});
},
);
export type ElfDependencies = z.infer<typeof elfDependenciesSchema>;
export type ElfDependencyNeeded = z.infer<typeof neededEntrySchema>;
export type ElfDependencyImport = z.infer<typeof importSchema>;
export type ElfDependencyIssue = z.infer<typeof issueSchema>;
export type ElfVersionNeedFile = z.infer<typeof versionNeedFileSchema>;
export type ElfVersionDefinition = z.infer<typeof versionDefinitionSchema>;
+975
View File
@@ -0,0 +1,975 @@
/** SysV ELF hash used by GNU version aux records. */
export const elfHash = (name: string): number => {
let h = 0;
for (const byte of Buffer.from(name, "latin1")) {
h = ((h << 4) + byte) >>> 0;
const g = h & 0xf0000000;
if (g !== 0) h ^= g >>> 24;
h = (h & ~g) >>> 0;
}
return h;
};
const concat = (...parts: readonly Buffer[]): Buffer => Buffer.concat(parts);
const write16 = (
bytes: Buffer,
offset: number,
value: number,
little: boolean,
): void => {
if (little) bytes.writeUInt16LE(value, offset);
else bytes.writeUInt16BE(value, offset);
};
const write32 = (
bytes: Buffer,
offset: number,
value: number,
little: boolean,
): void => {
if (little) bytes.writeUInt32LE(value, offset);
else bytes.writeUInt32BE(value, offset);
};
const writeWord = (
bytes: Buffer,
offset: number,
value: number,
bits: 32 | 64,
little: boolean,
): void => {
if (bits === 64) {
const wide = BigInt(value);
if (little) bytes.writeBigUInt64LE(wide, offset);
else bytes.writeBigUInt64BE(wide, offset);
return;
}
write32(bytes, offset, value, little);
};
export interface ElfDependencyImportSpec {
readonly name: string;
readonly binding?: number;
readonly type?: number;
readonly version?: number;
}
export interface ElfDependencyVersionSpec {
readonly name: string;
readonly index: number;
readonly flags?: number;
readonly hash?: number;
}
export interface ElfDependencyVerneedSpec {
readonly file: string;
readonly versions: readonly ElfDependencyVersionSpec[];
}
export interface ElfDependencyVerdefSpec {
readonly name: string;
readonly index: number;
readonly flags?: number;
}
export interface ElfDependencyFixtureOptions {
readonly bits?: 32 | 64;
readonly little?: boolean;
readonly type?: number;
readonly machine?: number;
readonly interpreter?: string | null;
readonly needed?: readonly string[];
/** Replaces the first DT_NEEDED and the DT_SONAME string offsets. */
readonly wideNameOffset?: number;
readonly soname?: string | null;
readonly rpath?: string | null;
readonly runpath?: string | null;
readonly flags?: number | null;
readonly flags1?: number | null;
readonly imports?: readonly ElfDependencyImportSpec[];
readonly verneed?: readonly ElfDependencyVerneedSpec[];
readonly verdef?: readonly ElfDependencyVerdefSpec[];
readonly stripped?: boolean;
readonly omitDynamic?: boolean;
readonly omitHash?: boolean;
readonly gnuHash?: boolean;
readonly gnuBucketBelowFirstSymbol?: boolean;
readonly gnuEmptyBuckets?: boolean;
/** Gives the first record of this chain a zero link before its count ends. */
readonly earlyVersionLinkEnd?: "verneed" | "vernaux";
/** Gives the final record of this chain a nonzero link past its count. */
readonly danglingVersionLink?: "verneed" | "vernaux" | "verdef";
/** Writes revision 0 into the first record of this table. */
readonly unsupportedVersionRevision?: "verneed" | "verdef";
/** Overrides vd_cnt and vda_next of the first version definition. */
readonly verdefAuxiliary?: { readonly count: number; readonly next: number };
readonly truncateDynstr?: boolean;
readonly duplicateSoname?: boolean;
/** Declares this section's size past the end of the file. */
readonly oversizedSection?: string;
/** Places this section's file offset past the end of the file. */
readonly displacedSection?: string;
/** Keeps the .hash section but leaves DT_HASH out of the dynamic table. */
readonly omitHashTag?: boolean;
/** Overrides the size these section headers declare, by section name. */
readonly sectionSizes?: Readonly<Record<string, number>>;
/** Overrides the entry size these section headers declare, by section name. */
readonly sectionEntrySizes?: Readonly<Record<string, number>>;
/** Leaves DT_SYMENT out of the dynamic table. */
readonly omitSymentTag?: boolean;
/** Splits the identity PT_LOAD in two halfway through the .hash table. */
readonly splitLoadAtHash?: boolean;
}
const defaultNeeded = (): string[] => [
"libstdc++.so.6",
"libm.so.6",
"libc.so.6",
];
const defaultImports = (): ElfDependencyImportSpec[] => [
{ name: "printf", version: 3 },
{ name: "memcpy", version: 2 },
{ name: "_ZSt4cout", type: 1, version: 4 },
{ name: "abort", version: 1 },
{ name: "_exit", version: 0x8002 },
];
const defaultVerneed = (): ElfDependencyVerneedSpec[] => [
{
file: "libc.so.6",
versions: [
{ name: "GLIBC_2.2.5", index: 2 },
{ name: "GLIBC_2.34", index: 3 },
],
},
{
file: "libstdc++.so.6",
versions: [{ name: "GLIBCXX_3.4.29", index: 4 }],
},
];
const defaultVerdef = (): ElfDependencyVerdefSpec[] => [
{ name: "libdemo.so.1", index: 1, flags: 1 },
];
class StringTable {
readonly #parts: Buffer[] = [Buffer.from([0])];
readonly #offsets = new Map<string, number>([["", 0]]);
#size = 1;
intern(value: string): number {
const existing = this.#offsets.get(value);
if (existing !== undefined) return existing;
const offset = this.#size;
const encoded = Buffer.from(`${value}\0`, "latin1");
this.#parts.push(encoded);
this.#offsets.set(value, offset);
this.#size += encoded.length;
return offset;
}
bytes(options: { readonly dropLastNul?: boolean } = {}): Buffer {
const table = Buffer.concat(this.#parts);
if (options.dropLastNul === true && table.length > 1)
return table.subarray(0, table.length - 1);
return table;
}
}
const symbolBytes = (
nameOffset: number,
info: number,
sectionIndex: number,
bits: 32 | 64,
little: boolean,
): Buffer => {
const bytes = Buffer.alloc(bits === 64 ? 24 : 16);
write32(bytes, 0, nameOffset, little);
if (bits === 64) {
bytes[4] = info;
bytes[5] = 0;
write16(bytes, 6, sectionIndex, little);
return bytes;
}
write32(bytes, 4, 0, little);
write32(bytes, 8, 0, little);
bytes[12] = info;
bytes[13] = 0;
write16(bytes, 14, sectionIndex, little);
return bytes;
};
const dynamicEntry = (
tag: number,
value: number,
bits: 32 | 64,
little: boolean,
): Buffer => {
const bytes = Buffer.alloc(bits === 64 ? 16 : 8);
writeWord(bytes, 0, tag, bits, little);
writeWord(bytes, bits === 64 ? 8 : 4, value, bits, little);
return bytes;
};
const verneedRecord = (
fileOffset: number,
versions: readonly ElfDependencyVersionSpec[],
nameOffsets: readonly number[],
next: number,
little: boolean,
zeroFirstAuxLink: boolean,
finalAuxLink = 0,
revision = 1,
): Buffer => {
const header = Buffer.alloc(16);
write16(header, 0, revision, little);
write16(header, 2, versions.length, little);
write32(header, 4, fileOffset, little);
write32(header, 8, 16, little);
write32(header, 12, next, little);
const aux = versions.map((version, index) => {
const record = Buffer.alloc(16);
write32(record, 0, version.hash ?? elfHash(version.name), little);
write16(record, 4, version.flags ?? 0, little);
write16(record, 6, version.index, little);
write32(record, 8, nameOffsets[index] ?? 0, little);
const last = index + 1 === versions.length;
const auxLink = last ? finalAuxLink : 16;
write32(record, 12, zeroFirstAuxLink && index === 0 ? 0 : auxLink, little);
return record;
});
return concat(header, ...aux);
};
const verdefRecord = (
nameOffset: number,
index: number,
flags: number,
hash: number,
next: number,
little: boolean,
revision = 1,
auxiliary = { count: 1, next: 0 },
): Buffer => {
const bytes = Buffer.alloc(28);
write16(bytes, 0, revision, little);
write16(bytes, 2, flags, little);
write16(bytes, 4, index, little);
write16(bytes, 6, auxiliary.count, little);
write32(bytes, 8, hash, little);
write32(bytes, 12, 20, little);
write32(bytes, 16, next, little);
write32(bytes, 20, nameOffset, little);
write32(bytes, 24, auxiliary.next, little);
return bytes;
};
const sysvHash = (symbolCount: number, little: boolean): Buffer => {
const bytes = Buffer.alloc(8 + 4 + 4 * symbolCount);
write32(bytes, 0, 1, little);
write32(bytes, 4, symbolCount, little);
return bytes;
};
/** Minimal GNU hash whose nchain walk yields `symbolCount` including the null entry. */
const gnuHashTable = (
symbolCount: number,
bits: 32 | 64,
little: boolean,
layout: "chained" | "bucketBelowFirstSymbol" | "emptyBuckets",
): Buffer => {
const bucketBelowFirstSymbol = layout === "bucketBelowFirstSymbol";
// GNU ld's table for an image with no hashable exports: one empty bucket and
// a first-symbol index of 1 whatever the import count.
if (layout === "emptyBuckets") {
const empty = Buffer.alloc(16 + (bits === 64 ? 8 : 4) + 4);
write32(empty, 0, 1, little);
write32(empty, 4, 1, little);
write32(empty, 8, 1, little);
return empty;
}
const firstSymbol = bucketBelowFirstSymbol
? Math.min(2, symbolCount)
: Math.min(1, symbolCount);
const hashed = Math.max(0, symbolCount - firstSymbol);
const header = Buffer.alloc(16);
write32(header, 0, 1, little);
write32(header, 4, firstSymbol, little);
write32(header, 8, 1, little);
write32(header, 12, 0, little);
const bloom = Buffer.alloc(bits === 64 ? 8 : 4);
const buckets = Buffer.alloc(4);
write32(
buckets,
0,
bucketBelowFirstSymbol ? 1 : hashed === 0 ? 0 : firstSymbol,
little,
);
const chains = Buffer.alloc(hashed * 4);
if (hashed > 0) write32(chains, (hashed - 1) * 4, 1, little);
return concat(header, bloom, buckets, chains);
};
const writeProgramHeader = (
bytes: Buffer,
at: number,
bits: 32 | 64,
little: boolean,
type: number,
flags: number,
offset: number,
size: number,
align: number,
vaddr = offset,
): void => {
write32(bytes, at, type, little);
if (bits === 64) {
write32(bytes, at + 4, flags, little);
writeWord(bytes, at + 8, offset, bits, little);
writeWord(bytes, at + 16, vaddr, bits, little);
writeWord(bytes, at + 24, vaddr, bits, little);
writeWord(bytes, at + 32, size, bits, little);
writeWord(bytes, at + 40, size, bits, little);
writeWord(bytes, at + 48, align, bits, little);
return;
}
writeWord(bytes, at + 4, offset, bits, little);
writeWord(bytes, at + 8, vaddr, bits, little);
writeWord(bytes, at + 12, vaddr, bits, little);
writeWord(bytes, at + 16, size, bits, little);
writeWord(bytes, at + 20, size, bits, little);
write32(bytes, at + 24, flags, little);
writeWord(bytes, at + 28, align, bits, little);
};
const writeSectionHeader = (
bytes: Buffer,
at: number,
bits: 32 | 64,
little: boolean,
nameOffset: number,
type: number,
flags: number,
addr: number,
offset: number,
size: number,
link: number,
info: number,
entsize: number,
): void => {
write32(bytes, at, nameOffset, little);
write32(bytes, at + 4, type, little);
writeWord(bytes, at + 8, flags, bits, little);
writeWord(bytes, at + (bits === 64 ? 16 : 12), addr, bits, little);
writeWord(bytes, at + (bits === 64 ? 24 : 16), offset, bits, little);
writeWord(bytes, at + (bits === 64 ? 32 : 20), size, bits, little);
write32(bytes, at + (bits === 64 ? 40 : 24), link, little);
write32(bytes, at + (bits === 64 ? 44 : 28), info, little);
writeWord(bytes, at + (bits === 64 ? 48 : 32), 1, bits, little);
writeWord(bytes, at + (bits === 64 ? 56 : 36), entsize, bits, little);
};
interface FixtureConfig {
readonly bits: 32 | 64;
readonly little: boolean;
readonly type: number;
readonly machine: number;
readonly omitDynamic: boolean;
readonly stripped: boolean;
readonly needed: readonly string[];
readonly imports: readonly ElfDependencyImportSpec[];
readonly verneed: readonly ElfDependencyVerneedSpec[];
readonly verdef: readonly ElfDependencyVerdefSpec[];
readonly interpreter: string | null;
readonly soname: string | null;
readonly runpath: string | null;
readonly rpath: string | null;
readonly flags: number | null;
readonly flags1: number | null;
readonly omitHash: boolean;
readonly gnuHash: boolean;
readonly gnuBucketBelowFirstSymbol: boolean;
readonly gnuEmptyBuckets: boolean;
readonly earlyVersionLinkEnd: ElfDependencyFixtureOptions["earlyVersionLinkEnd"];
readonly danglingVersionLink: ElfDependencyFixtureOptions["danglingVersionLink"];
readonly unsupportedVersionRevision: ElfDependencyFixtureOptions["unsupportedVersionRevision"];
readonly verdefAuxiliary: ElfDependencyFixtureOptions["verdefAuxiliary"];
readonly truncateDynstr: boolean;
readonly duplicateSoname: boolean;
readonly wideNameOffset: number | undefined;
readonly oversizedSection: string | undefined;
readonly displacedSection: string | undefined;
readonly omitHashTag: boolean;
readonly sectionSizes: Readonly<Record<string, number>>;
readonly sectionEntrySizes: Readonly<Record<string, number>>;
readonly omitSymentTag: boolean;
readonly splitLoadAtHash: boolean;
}
interface DependencyTables {
readonly neededOffsets: readonly number[];
readonly sonameOffset: number;
readonly runpathOffset: number;
readonly rpathOffset: number;
readonly dynstrBytes: Buffer;
readonly dynsym: Buffer;
readonly versym: Buffer;
readonly hash: Buffer;
readonly gnuHashBytes: Buffer;
readonly verneedBytes: Buffer;
readonly verdefBytes: Buffer;
readonly interpBytes: Buffer;
}
interface DependencyLayout {
readonly headerSize: number;
readonly phent: number;
readonly shent: number;
readonly programCount: number;
readonly phoff: number;
readonly interpOff: number;
readonly hashOff: number;
readonly gnuHashOff: number;
readonly dynsymOff: number;
readonly dynstrOff: number;
readonly versymOff: number;
readonly verneedOff: number;
readonly verdefOff: number;
readonly dynamicBytes: Buffer;
readonly dynamicOff: number;
readonly shstr: StringTable;
readonly shstrBytes: Buffer;
readonly shstrOff: number;
readonly shnum: number;
readonly shoff: number;
readonly fileSize: number;
}
const SECTION_NAMES = [
".interp",
".hash",
".dynsym",
".dynstr",
".gnu.version",
".gnu.version_r",
".gnu.version_d",
".dynamic",
".shstrtab",
] as const;
const fixtureConfig = (options: ElfDependencyFixtureOptions): FixtureConfig => {
const bits = options.bits ?? 64;
const little = options.little ?? true;
return {
bits,
little,
type: options.type ?? 3,
machine: options.machine ?? (bits === 64 ? 62 : little ? 3 : 8),
omitDynamic: options.omitDynamic === true,
stripped: options.stripped === true,
needed: [...(options.needed ?? defaultNeeded())],
imports: [...(options.imports ?? defaultImports())],
verneed: [...(options.verneed ?? defaultVerneed())],
verdef: [...(options.verdef ?? defaultVerdef())],
interpreter:
options.interpreter === null
? null
: (options.interpreter ??
(bits === 64 ? "/lib64/ld-linux-x86-64.so.2" : "/lib/ld-linux.so.2")),
soname: options.soname === null ? null : (options.soname ?? "libdemo.so.1"),
runpath:
options.runpath === null ? null : (options.runpath ?? "$ORIGIN/../lib"),
rpath: options.rpath ?? null,
flags: options.flags === undefined ? 0x9 : options.flags,
flags1: options.flags1 === undefined ? 0x08000881 : options.flags1,
omitHash: options.omitHash === true,
gnuHash: options.gnuHash === true,
gnuBucketBelowFirstSymbol: options.gnuBucketBelowFirstSymbol === true,
gnuEmptyBuckets: options.gnuEmptyBuckets === true,
earlyVersionLinkEnd: options.earlyVersionLinkEnd,
danglingVersionLink: options.danglingVersionLink,
unsupportedVersionRevision: options.unsupportedVersionRevision,
verdefAuxiliary: options.verdefAuxiliary,
truncateDynstr: options.truncateDynstr === true,
duplicateSoname: options.duplicateSoname === true,
wideNameOffset: options.wideNameOffset,
oversizedSection: options.oversizedSection,
displacedSection: options.displacedSection,
omitHashTag: options.omitHashTag === true,
sectionSizes: options.sectionSizes ?? {},
sectionEntrySizes: options.sectionEntrySizes ?? {},
omitSymentTag: options.omitSymentTag === true,
splitLoadAtHash: options.splitLoadAtHash === true,
};
};
const buildDependencyTables = (config: FixtureConfig): DependencyTables => {
const { bits, little, imports, verneed, verdef } = config;
const dynstr = new StringTable();
const neededOffsets = config.needed.map((name) => dynstr.intern(name));
const sonameOffset =
config.soname === null ? 0 : dynstr.intern(config.soname);
const runpathOffset =
config.runpath === null ? 0 : dynstr.intern(config.runpath);
const rpathOffset = config.rpath === null ? 0 : dynstr.intern(config.rpath);
const importOffsets = imports.map((entry) => dynstr.intern(entry.name));
const verneedFileOffsets = verneed.map((entry) => dynstr.intern(entry.file));
const verneedNameOffsets = verneed.map((entry) =>
entry.versions.map((version) => dynstr.intern(version.name)),
);
const verdefNameOffsets = verdef.map((entry) => dynstr.intern(entry.name));
const symbols = [
symbolBytes(0, 0, 0, bits, little),
...imports.map((entry, index) =>
symbolBytes(
importOffsets[index] ?? 0,
((entry.binding ?? 1) << 4) | (entry.type ?? 2),
0,
bits,
little,
),
),
];
const versym = Buffer.alloc(symbols.length * 2);
write16(versym, 0, 0, little);
imports.forEach((entry, index) => {
write16(versym, (index + 1) * 2, entry.version ?? 1, little);
});
const verneedBytes = concat(
...verneed.map((entry, index) => {
const auxBytes = 16 * entry.versions.length;
const last = index + 1 === verneed.length;
const dangling = last && config.danglingVersionLink === "verneed";
const next =
config.earlyVersionLinkEnd === "verneed" && index === 0
? 0
: dangling
? 32
: last
? 0
: 16 + auxBytes;
return verneedRecord(
verneedFileOffsets[index] ?? 0,
entry.versions,
verneedNameOffsets[index] ?? [],
next,
little,
config.earlyVersionLinkEnd === "vernaux" && index === 0,
last && config.danglingVersionLink === "vernaux" ? 16 : 0,
index === 0 && config.unsupportedVersionRevision === "verneed" ? 0 : 1,
);
}),
);
return {
neededOffsets,
sonameOffset,
runpathOffset,
rpathOffset,
dynstrBytes: dynstr.bytes({ dropLastNul: config.truncateDynstr }),
dynsym: Buffer.concat(symbols),
versym,
hash: config.omitHash ? Buffer.alloc(0) : sysvHash(symbols.length, little),
gnuHashBytes: config.gnuHash
? gnuHashTable(
symbols.length,
bits,
little,
config.gnuEmptyBuckets
? "emptyBuckets"
: config.gnuBucketBelowFirstSymbol
? "bucketBelowFirstSymbol"
: "chained",
)
: Buffer.alloc(0),
verneedBytes,
verdefBytes: concat(
...verdef.map((entry, index) =>
verdefRecord(
verdefNameOffsets[index] ?? 0,
entry.index,
entry.flags ?? 0,
elfHash(entry.name),
index + 1 < verdef.length || config.danglingVersionLink === "verdef"
? 28
: 0,
little,
index === 0 && config.unsupportedVersionRevision === "verdef" ? 0 : 1,
index === 0 ? config.verdefAuxiliary : undefined,
),
),
),
interpBytes:
config.interpreter === null
? Buffer.alloc(0)
: Buffer.from(`${config.interpreter}\0`, "latin1"),
};
};
const buildDynamicTags = (
config: FixtureConfig,
tables: DependencyTables,
offsets: {
readonly hashOff: number;
readonly gnuHashOff: number;
readonly dynsymOff: number;
readonly dynstrOff: number;
readonly versymOff: number;
readonly verneedOff: number;
readonly verdefOff: number;
},
): Buffer => {
const { bits, little } = config;
const tags: Buffer[] = [];
const addTag = (tag: number, value: number): void => {
tags.push(dynamicEntry(tag, value, bits, little));
};
tables.neededOffsets.forEach((offset, index) =>
addTag(1, index === 0 ? (config.wideNameOffset ?? offset) : offset),
);
if (config.soname !== null) {
addTag(14, config.wideNameOffset ?? tables.sonameOffset);
if (config.duplicateSoname) addTag(14, tables.sonameOffset);
}
if (config.rpath !== null) addTag(15, tables.rpathOffset);
if (config.runpath !== null) addTag(29, tables.runpathOffset);
if (config.flags !== null) addTag(30, config.flags);
if (tables.hash.length !== 0 && !config.omitHashTag)
addTag(4, offsets.hashOff);
if (tables.gnuHashBytes.length !== 0) addTag(0x6ffffef5, offsets.gnuHashOff);
addTag(5, offsets.dynstrOff);
addTag(6, offsets.dynsymOff);
addTag(10, tables.dynstrBytes.length);
if (!config.omitSymentTag) addTag(11, bits === 64 ? 24 : 16);
addTag(0x6ffffff0, offsets.versymOff);
if (tables.verneedBytes.length !== 0) {
addTag(0x6ffffffe, offsets.verneedOff);
addTag(
0x6fffffff,
config.earlyVersionLinkEnd === "verneed"
? Math.max(config.verneed.length, 2)
: config.verneed.length,
);
}
if (tables.verdefBytes.length !== 0) {
addTag(0x6ffffffc, offsets.verdefOff);
addTag(0x6ffffffd, config.verdef.length);
}
if (config.flags1 !== null) addTag(0x6ffffffb, config.flags1);
addTag(0, 0);
return concat(...tags);
};
const layoutDependencyImage = (
config: FixtureConfig,
tables: DependencyTables,
): DependencyLayout => {
const headerSize = config.bits === 64 ? 64 : 52;
const phent = config.bits === 64 ? 56 : 32;
const shent = config.bits === 64 ? 64 : 40;
const programCount =
(config.interpreter === null ? 0 : 1) +
(config.splitLoadAtHash ? 2 : 1) +
(config.omitDynamic ? 0 : 1);
const phoff = headerSize;
let cursor = phoff + programCount * phent;
const place = (size: number): number => {
const offset = cursor;
cursor += size;
return offset;
};
const interpOff =
config.interpreter === null ? 0 : place(tables.interpBytes.length);
const hashOff = tables.hash.length === 0 ? 0 : place(tables.hash.length);
const gnuHashOff =
tables.gnuHashBytes.length === 0 ? 0 : place(tables.gnuHashBytes.length);
const dynsymOff = place(tables.dynsym.length);
const dynstrOff = place(tables.dynstrBytes.length);
const versymOff = place(tables.versym.length);
const verneedOff =
tables.verneedBytes.length === 0 ? 0 : place(tables.verneedBytes.length);
const verdefOff =
tables.verdefBytes.length === 0 ? 0 : place(tables.verdefBytes.length);
const dynamicBytes = config.omitDynamic
? Buffer.alloc(0)
: buildDynamicTags(config, tables, {
hashOff,
gnuHashOff,
dynsymOff,
dynstrOff,
versymOff,
verneedOff,
verdefOff,
});
const dynamicOff = config.omitDynamic ? 0 : place(dynamicBytes.length);
const shstr = new StringTable();
for (const name of SECTION_NAMES) shstr.intern(name);
const shstrBytes = shstr.bytes();
const shstrOff = config.stripped ? 0 : place(shstrBytes.length);
const shnum = config.stripped ? 0 : 10;
const shoff = config.stripped ? 0 : place(shnum * shent);
return {
headerSize,
phent,
shent,
programCount,
phoff,
interpOff,
hashOff,
gnuHashOff,
dynsymOff,
dynstrOff,
versymOff,
verneedOff,
verdefOff,
dynamicBytes,
dynamicOff,
shstr,
shstrBytes,
shstrOff,
shnum,
shoff,
fileSize: cursor,
};
};
const writeElfIdent = (
bytes: Buffer,
config: FixtureConfig,
layout: DependencyLayout,
): void => {
const { bits, little } = config;
bytes.writeUInt32LE(0x464c457f, 0);
bytes[4] = bits === 64 ? 2 : 1;
bytes[5] = little ? 1 : 2;
bytes[6] = 1;
write16(bytes, 16, config.type, little);
write16(bytes, 18, config.machine, little);
write32(bytes, 20, 1, little);
writeWord(bytes, bits === 64 ? 32 : 28, layout.phoff, bits, little);
writeWord(bytes, bits === 64 ? 40 : 32, layout.shoff, bits, little);
write16(bytes, bits === 64 ? 52 : 40, layout.headerSize, little);
write16(bytes, bits === 64 ? 54 : 42, layout.phent, little);
write16(bytes, bits === 64 ? 56 : 44, layout.programCount, little);
write16(bytes, bits === 64 ? 58 : 46, layout.shent, little);
write16(bytes, bits === 64 ? 60 : 48, layout.shnum, little);
write16(
bytes,
bits === 64 ? 62 : 50,
config.stripped ? 0 : layout.shnum - 1,
little,
);
};
const copyDependencyPayloads = (
bytes: Buffer,
config: FixtureConfig,
tables: DependencyTables,
layout: DependencyLayout,
): void => {
if (config.interpreter !== null)
tables.interpBytes.copy(bytes, layout.interpOff);
if (tables.hash.length !== 0) tables.hash.copy(bytes, layout.hashOff);
if (tables.gnuHashBytes.length !== 0)
tables.gnuHashBytes.copy(bytes, layout.gnuHashOff);
tables.dynsym.copy(bytes, layout.dynsymOff);
tables.dynstrBytes.copy(bytes, layout.dynstrOff);
tables.versym.copy(bytes, layout.versymOff);
if (tables.verneedBytes.length !== 0)
tables.verneedBytes.copy(bytes, layout.verneedOff);
if (tables.verdefBytes.length !== 0)
tables.verdefBytes.copy(bytes, layout.verdefOff);
if (!config.omitDynamic) layout.dynamicBytes.copy(bytes, layout.dynamicOff);
if (!config.stripped) layout.shstrBytes.copy(bytes, layout.shstrOff);
};
const writeDependencyPrograms = (
bytes: Buffer,
config: FixtureConfig,
tables: DependencyTables,
layout: DependencyLayout,
): void => {
let programIndex = 0;
const add = (
kind: number,
flags: number,
offset: number,
size: number,
align: number,
): void => {
writeProgramHeader(
bytes,
layout.phoff + programIndex * layout.phent,
config.bits,
config.little,
kind,
flags,
offset,
size,
align,
);
programIndex += 1;
};
if (config.interpreter !== null)
add(3, 4, layout.interpOff, tables.interpBytes.length, 1);
if (config.splitLoadAtHash) {
// Adjacent, identity-mapped loads: the .hash table crosses their boundary.
const split = layout.hashOff + 8;
add(1, 5, 0, split, 1);
add(1, 5, split, layout.fileSize - split, 1);
} else add(1, 5, 0, layout.fileSize, 0x1000);
if (!config.omitDynamic)
add(2, 6, layout.dynamicOff, layout.dynamicBytes.length, 8);
};
const writeDependencySections = (
bytes: Buffer,
config: FixtureConfig,
tables: DependencyTables,
layout: DependencyLayout,
): void => {
if (config.stripped) return;
const alloc = 2;
const { bits, little } = config;
const rows: readonly (readonly [
string,
number,
number,
number,
number,
number,
number,
number,
number,
])[] = [
["", 0, 0, 0, 0, 0, 0, 0, 0],
[
".interp",
1,
alloc,
layout.interpOff,
layout.interpOff,
tables.interpBytes.length,
0,
0,
0,
],
[
".hash",
5,
alloc,
layout.hashOff,
layout.hashOff,
tables.hash.length,
3,
0,
4,
],
[
".dynsym",
11,
alloc,
layout.dynsymOff,
layout.dynsymOff,
tables.dynsym.length,
4,
1,
bits === 64 ? 24 : 16,
],
[
".dynstr",
3,
alloc,
layout.dynstrOff,
layout.dynstrOff,
tables.dynstrBytes.length,
0,
0,
0,
],
[
".gnu.version",
0x6fffffff,
alloc,
layout.versymOff,
layout.versymOff,
tables.versym.length,
3,
0,
2,
],
[
".gnu.version_r",
0x6ffffffe,
alloc,
layout.verneedOff,
layout.verneedOff,
tables.verneedBytes.length,
4,
config.verneed.length,
0,
],
[
".gnu.version_d",
0x6ffffffd,
alloc,
layout.verdefOff,
layout.verdefOff,
tables.verdefBytes.length,
4,
config.verdef.length,
0,
],
[
".dynamic",
6,
alloc,
layout.dynamicOff,
layout.dynamicOff,
layout.dynamicBytes.length,
4,
0,
bits === 64 ? 16 : 8,
],
[".shstrtab", 3, 0, 0, layout.shstrOff, layout.shstrBytes.length, 0, 0, 0],
];
rows.forEach((row, index) => {
writeSectionHeader(
bytes,
layout.shoff + index * layout.shent,
bits,
little,
row[0] === "" ? 0 : layout.shstr.intern(row[0]),
row[1],
row[2],
row[3],
row[0] === config.displacedSection ? layout.fileSize * 2 : row[4],
// A multiple of both symbol entry sizes, so the size stays a plausible count.
row[0] === config.oversizedSection
? layout.fileSize * 48
: (config.sectionSizes[row[0]] ?? row[5]),
row[6],
row[7],
config.sectionEntrySizes[row[0]] ?? row[8],
);
});
};
/**
* Synthetic ET_EXEC/ET_DYN image with identity-mapped PT_LOAD so DT_* virtual
* addresses equal file offsets. Section headers are optional.
*/
export const elfDependencyFixture = (
options: ElfDependencyFixtureOptions = {},
): Buffer => {
const config = fixtureConfig(options);
const tables = buildDependencyTables(config);
const layout = layoutDependencyImage(config, tables);
const bytes = Buffer.alloc(layout.fileSize);
writeElfIdent(bytes, config, layout);
writeDependencyPrograms(bytes, config, tables, layout);
copyDependencyPayloads(bytes, config, tables, layout);
writeDependencySections(bytes, config, tables, layout);
return bytes;
};
@@ -0,0 +1,148 @@
import { createHash } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { setImmediate as immediate } from "node:timers/promises";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore.js";
import { inspectElfDependenciesInputSchema } from "../../domain/native/elfDependencies.js";
import { elfDependencyFixture } from "./ElfDependencies.fixture.js";
import { ElfDependenciesProvider } from "./ElfDependenciesProvider.js";
import { ParseFailureError } from "../../domain/parseFailure.js";
vi.mock("node:timers/promises", async () => {
const original = await vi.importActual<typeof import("node:timers/promises")>(
"node:timers/promises",
);
return { ...original, setImmediate: vi.fn(original.setImmediate) };
});
afterEach(() => vi.mocked(immediate).mockClear());
it("keeps the read file's identity when parsing fails", async () => {
const root = await createTestTempDirectory("rea-elf-dependencies-parse-");
const path = join(root, "not-elf");
const bytes = Buffer.from("not an ELF image, but it was read completely");
await writeFile(path, bytes);
const provider = new ElfDependenciesProvider();
try {
const result = await provider.inspect(
inspectElfDependenciesInputSchema.parse({ path }),
);
if (result.ok) throw new Error("Expected a parse failure");
expect(result.error.partialObservation).toEqual({
kind: "file-snapshot-hash",
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
});
} finally {
await provider.close();
}
});
const inspectWith = async (
bytes: Buffer,
budgets: Record<string, number> = {},
) => {
const root = await createTestTempDirectory("rea-elf-dependencies-limit-");
const path = join(root, "program");
await writeFile(path, bytes);
const provider = new ElfDependenciesProvider();
try {
return await provider.inspect(
inspectElfDependenciesInputSchema.parse({ path, ...budgets }),
);
} finally {
await provider.close();
}
};
const countLimitOf = async (
bytes: Buffer,
budgets: Record<string, number> = {},
) => {
const result = await inspectWith(bytes, budgets);
if (result.ok) throw new Error("Expected a limit failure");
expect(result.error).toBeInstanceOf(AnalysisResourceConstraintError);
const error = result.error as AnalysisResourceConstraintError;
expect(error.retryable).toBe(false);
expect(error.cause).toBeInstanceOf(ParseFailureError);
return error.reportedLimits;
};
it.each([
["max_needed", 65536],
["max_versions", 65536],
["max_imports", 262144],
] as const)(
"reports which budget failed and recovers when %s is raised",
async (parameter, ceiling) => {
const image = elfDependencyFixture();
expect(await countLimitOf(image, { [parameter]: 2 })).toMatchObject({
boundary: parameter,
maximum: 2,
required: 3,
});
const raised = await inspectWith(image, { [parameter]: ceiling });
if (!raised.ok) throw raised.error;
expect(raised.value.coverage.status).toBe("complete");
},
);
it("reports a fixed dynamic-symbol ceiling that a raised budget cannot clear", async () => {
const imports = Array.from({ length: 262145 }, (_, index) => ({
name: `s${String(index)}`,
}));
const image = elfDependencyFixture({ imports });
const ceiling = { boundary: "dynamic_symbols", maximum: 262144 };
expect(await countLimitOf(image)).toMatchObject(ceiling);
expect(await countLimitOf(image, { max_imports: 262144 })).toMatchObject(
ceiling,
);
});
it("cancels at a GNU hash checkpoint and remains reusable after cleanup", async () => {
const root = await createTestTempDirectory(
"rea-elf-dependencies-checkpoint-",
);
const path = join(root, "program");
const bytes = elfDependencyFixture({
stripped: true,
omitHash: true,
gnuHash: true,
});
await writeFile(path, bytes);
const provider = new ElfDependenciesProvider();
const controller = new AbortController();
const original = await vi.importActual<typeof import("node:timers/promises")>(
"node:timers/promises",
);
vi.mocked(immediate).mockImplementationOnce(async () => {
controller.abort();
await original.setImmediate();
});
try {
const input = inspectElfDependenciesInputSchema.parse({ path });
const cancelled = await provider.inspect(input, {
signal: controller.signal,
});
if (cancelled.ok)
throw new Error("Expected cancellation at the hash checkpoint");
expect(cancelled.error).toMatchObject({
_tag: "AnalysisCancelledError",
partialObservation: {
kind: "file-snapshot-hash",
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.length,
},
});
expect(immediate).toHaveBeenCalledTimes(1);
const retried = await provider.inspect(input);
if (!retried.ok) throw retried.error;
expect(retried.value.imports).toHaveLength(5);
} finally {
await provider.close();
}
});
+231
View File
@@ -0,0 +1,231 @@
import { setImmediate as immediate } from "node:timers/promises";
import {
isParseLimit,
parseFailureAnalysisError,
parseLimitConstraint,
} from "../../domain/parseFailureAnalysisError.js";
import { decodeLimit } from "../../domain/parseFailure.js";
import {
projectArtifactCloseFailure,
projectOwnedArtifactIdentityFailure,
projectSelectedArtifactFileFailure,
projectStableArtifactFailure,
stableArtifactInputFailure,
ArtifactReaderFailure,
readStableArtifact,
type StableArtifactSnapshot,
artifactFilePrimaryFacts,
type ArtifactFilePrimaryFacts,
ArtifactResourceScope,
assertArtifactReadActive,
imageFileSizeRemediation,
} from "../../resources/index.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import {
MAX_INSPECT_ELF_DEPENDENCY_FILE_BYTES,
MAX_INSPECT_ELF_DEPENDENCY_IMPORTS,
MAX_INSPECT_ELF_DEPENDENCY_NEEDED,
MAX_INSPECT_ELF_DEPENDENCY_VERSIONS,
type InspectElfDependenciesInput,
} from "../../domain/native/elfDependencies.js";
import { err, ok } from "../../domain/result.js";
import { ELF_DEPENDENCIES_PROVIDER } from "../../domain/investigationProviders.js";
import {
BinaryResourceFailure,
binaryResourceCeiling,
} from "../../domain/binaryContainer.js";
import { readElfDependenciesSteps } from "./ElfDependencyParser.js";
const OPERATION = "inspect_elf_dependencies";
/** Portable parser over one bounded, identity-checked regular file. */
/**
* Satisfies ElfDependenciesPort structurally; composition
* checks the fit, so this provider does not import the application layer.
*/
export class ElfDependenciesProvider {
readonly identity = ELF_DEPENDENCIES_PROVIDER;
readonly #resources = new ArtifactResourceScope();
async close(): Promise<void> {
try {
await this.#resources.close();
} catch (cause: unknown) {
throw projectArtifactCloseFailure(
cause,
ELF_DEPENDENCIES_PROVIDER.id,
OPERATION,
);
}
}
async inspect(
input: InspectElfDependenciesInput,
options?: { readonly signal?: AbortSignal },
) {
let completed: StableArtifactSnapshot | undefined;
try {
return await this.#resources.run(async () => {
const snapshot = await readStableArtifact(
input.path,
input.max_file_bytes,
options?.signal,
undefined,
this.#resources,
);
// Only a parser failure inherits this read's identity; finalization
// failures keep their own completion record.
completed = snapshot;
const steps = readElfDependenciesSteps(
snapshot.bytes,
{
path: input.path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
},
input,
);
assertArtifactReadActive(options?.signal);
let next = steps.next();
while (!next.done) {
await immediate();
assertArtifactReadActive(options?.signal);
next = steps.next();
}
assertArtifactReadActive(options?.signal);
completed = undefined;
return ok(next.value);
});
} catch (cause) {
return err(elfDependenciesFailure(cause, input, completed));
}
}
}
const COUNT_CEILINGS = {
max_needed: MAX_INSPECT_ELF_DEPENDENCY_NEEDED,
max_versions: MAX_INSPECT_ELF_DEPENDENCY_VERSIONS,
max_imports: MAX_INSPECT_ELF_DEPENDENCY_IMPORTS,
} as const;
const elfDependenciesFailurePrimary = (
facts: ArtifactFilePrimaryFacts,
input: InspectElfDependenciesInput,
) => {
const { cause, origin } = facts;
if (cause instanceof BinaryResourceFailure)
return parseLimitConstraint(
OPERATION,
"memory",
cause,
fixedAllowanceOptions(
"The ELF structural decoding allowance",
"parser",
binaryResourceCeiling(cause),
),
);
if (isParseLimit(cause, "elf-dependencies")) {
const limit = cause.failure.limit;
const parameter = (
Object.keys(COUNT_CEILINGS) as (keyof typeof COUNT_CEILINGS)[]
).find((name) => name === limit.name);
if (parameter !== undefined)
return parseLimitConstraint(OPERATION, "capacity", cause, {
path: input.path,
retryable: false,
remediationAction: `Raise ${parameter} above ${String(limit.maximum)}, up to ${String(COUNT_CEILINGS[parameter])}, or select a smaller artifact.`,
});
const text =
limit.name === "scanned_text_bytes" ||
limit.name === "retained_text_bytes";
const work = limit.name === "gnu_hash_entries";
return parseLimitConstraint(
OPERATION,
text ? "memory" : work ? "cpu" : "capacity",
cause,
{
path: input.path,
...fixedAllowanceOptions(
text
? "The ELF dependency text budget fixed by the admitted image length"
: `The ELF dependency ${limit.name} allowance`,
text ? "parser" : work ? "work" : "count",
{ limit: limit.maximum, unit: text ? "bytes" : "entries" },
),
},
);
}
const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause);
if (formatFailure !== undefined) return formatFailure;
const identityFailure = projectOwnedArtifactIdentityFailure(
facts,
OPERATION,
input.path,
);
if (identityFailure !== undefined) return identityFailure;
if (
origin === "owned-or-classified" &&
cause instanceof ArtifactReaderFailure
) {
if (cause.reason === "limit") {
return parseLimitConstraint(
OPERATION,
"file-size",
decodeLimit(
"elf-dependencies",
cause.message,
{ name: "max_file_bytes", maximum: input.max_file_bytes },
{ cause },
),
{
path: input.path,
retryable: false,
remediationAction: imageFileSizeRemediation(
input.max_file_bytes,
MAX_INSPECT_ELF_DEPENDENCY_FILE_BYTES,
),
},
);
}
if (cause.reason === "path" || cause.reason === "format")
return stableArtifactInputFailure(cause, OPERATION);
}
const fileFailure = projectSelectedArtifactFileFailure(
cause,
OPERATION,
input.path,
"ELF image",
);
if (fileFailure !== undefined) return fileFailure;
return new ArtifactOperationError(
OPERATION,
origin === "owned-or-classified" && cause instanceof ArtifactReaderFailure
? cause.reason
: "io",
undefined,
cause instanceof Error
? cause.message
: "ELF dependency inspection failed.",
{ cause },
);
};
const elfDependenciesFailure = (
cause: unknown,
input: InspectElfDependenciesInput,
completed: StableArtifactSnapshot | undefined,
) => {
const primary = elfDependenciesFailurePrimary(
artifactFilePrimaryFacts(cause),
input,
);
return projectStableArtifactFailure(
cause,
primary,
input.path,
ELF_DEPENDENCIES_PROVIDER.id,
OPERATION,
completed,
);
};
+208
View File
@@ -0,0 +1,208 @@
import { expect, it } from "vitest";
import { readElfDependenciesSteps } from "./ElfDependencyParser.js";
import { elfDependencyFixture } from "./ElfDependencies.fixture.js";
import { freezeJsonSnapshot } from "../../domain/immutableJson.js";
import { digestCanonicalValue } from "../../domain/canonicalDigest.js";
import { projectAnalysisView } from "../../domain/analysisView/analysisView.js";
import type { AnalysisViewParent } from "../../domain/analysisView/analysisViewParent.js";
import { analysisViewRequestSchema } from "../../domain/analysisView/analysisViewRequest.js";
const parseElfDependencies = (
...arguments_: Parameters<typeof readElfDependenciesSteps>
) => {
const steps = readElfDependenciesSteps(...arguments_);
for (let next = steps.next(); ; next = steps.next())
if (next.done) return next.value;
};
const artifact = {
path: "/artifacts/program",
sha256: "a".repeat(64),
bytes: 2048,
};
const parent = (report: unknown): AnalysisViewParent => ({
predicateType: "rea.analysis",
evidenceId: `ev_${"b".repeat(64)}`,
operation: "inspect_elf_dependencies",
normalizedResult: report,
limitations: [],
});
const project = (report: unknown, input: unknown) => {
const result = projectAnalysisView(
parent(report),
analysisViewRequestSchema.parse(input),
);
if (!result.ok) throw result.error;
return result.value;
};
const reportOf = () =>
parseElfDependencies(
elfDependencyFixture({
needed: ["libc.so.6", "libc.so.6", "libm.so.6"],
}),
artifact,
{
path: artifact.path,
max_file_bytes: 67108864,
max_needed: 1024,
max_versions: 4096,
max_imports: 65536,
},
);
it("pages duplicate DT_NEEDED names with original indices and selected fields", () => {
const report = reportOf();
const input = {
kind: "elf-dependencies",
collection: "needed",
names: ["libc.so.6"],
fields: ["name"],
limit: 1,
};
expect(project(report, input)).toMatchObject({
items: [{ source_index: 0, name: "libc.so.6" }],
dependencies: { needed_count: 3, coverage: { status: "complete" } },
coverage: { examined: 1, total: 2, next_offset: 1, exhausted: false },
});
expect(project(report, { ...input, offset: 1 })).toMatchObject({
items: [{ source_index: 1, name: "libc.so.6" }],
coverage: { total: 2, next_offset: null, exhausted: true },
});
expect(
project(report, { ...input, indices: [1, 1, 99], fields: [] }),
).toMatchObject({ items: [{ source_index: 1 }], coverage: { total: 1 } });
expect(project(report, { ...input, names: [] })).toMatchObject({
items: [],
coverage: { status: "empty", total: 0 },
});
});
it("pages GNU version requirements independently of definition rows", () => {
const report = reportOf();
expect(
project(report, {
kind: "elf-dependencies",
collection: "versions",
names: ["GLIBC_2.34"],
fields: ["file", "name", "index"],
}),
).toMatchObject({
items: [
{
source_index: 1,
file: "libc.so.6",
name: "GLIBC_2.34",
index: 3,
},
],
coverage: { total: 1 },
});
});
it("keeps import library@version identity through selected fields", () => {
const report = reportOf();
expect(
project(report, {
kind: "elf-dependencies",
collection: "imports",
names: ["printf"],
fields: ["name", "version"],
}),
).toMatchObject({
items: [
{
source_index: 0,
name: "printf",
version: {
name: "GLIBC_2.34",
file: "libc.so.6",
status: "resolved",
},
},
],
});
});
it("returns a summary without row bodies and a stable view digest", () => {
const report = reportOf();
freezeJsonSnapshot(report);
const viewed = project(report, { kind: "summary" });
expect(viewed).toMatchObject({
kind: "summary",
parent_operation: "inspect_elf_dependencies",
summary: {
needed_count: 3,
import_count: 5,
coverage: { status: "complete" },
},
});
expect(viewed).not.toHaveProperty("items");
const { view_digest, ...content } = viewed;
expect(view_digest).toBe(digestCanonicalValue(content, "Analysis view"));
});
it("pages version definitions and derived maxima instead of repeating them", () => {
const report = reportOf();
const summary = project(report, { kind: "summary" });
expect(summary).toMatchObject({
summary: {
version_definitions: { status: "present" },
definition_count: report.version_definitions.names.length,
derived_maximum_count: report.derived_version_maxima.length,
},
});
expect(summary).not.toHaveProperty("summary.derived_version_maxima");
expect(summary).not.toHaveProperty("summary.version_definitions.names");
expect(
project(report, {
kind: "elf-dependencies",
collection: "definitions",
fields: ["name", "base"],
limit: 1,
}),
).toMatchObject({
items: [{ source_index: 0, name: "libdemo.so.1", base: true }],
dependencies: { definition_count: 1 },
});
const maxima = project(report, {
kind: "elf-dependencies",
collection: "maxima",
names: ["GLIBC"],
fields: ["maximum"],
});
expect(maxima).toMatchObject({
items: [{ maximum: "GLIBC_2.34" }],
coverage: { total: 1 },
});
expect(maxima).not.toHaveProperty("dependencies.derived_version_maxima");
});
it("pages issues by original index and refuses name or field selection", () => {
const report = parseElfDependencies(
elfDependencyFixture({
truncateDynstr: true,
sectionSizes: { ".dynsym": 3 * 24 + 1 },
}),
artifact,
{
path: artifact.path,
max_file_bytes: 67108864,
max_needed: 1024,
max_versions: 4096,
max_imports: 65536,
},
);
expect(report.issues.length).toBeGreaterThan(1);
const view = { kind: "elf-dependencies", collection: "issues" };
expect(project(report, { ...view, indices: [1], limit: 1 })).toMatchObject({
items: [{ ...report.issues[1], source_index: 1 }],
coverage: { total: 1 },
});
for (const extra of [{ fields: ["code"] }, { names: ["name_unreadable"] }])
expect(
analysisViewRequestSchema.safeParse({ ...view, ...extra }).success,
).toBe(false);
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,20 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
ElfDependencies,
InspectElfDependenciesInput,
} from "../../domain/native/elfDependencies.js";
import type { Result } from "../../domain/result.js";
/** Stable read and ELF dynamic-dependency decoding, independent of a disassembler session. */
export interface ElfDependenciesPort {
readonly identity: ProviderIdentity;
close?(): Promise<void>;
inspect(
input: InspectElfDependenciesInput,
options?: ExecutionOptions,
): Promise<Result<ElfDependencies, AnalysisError>>;
}
+17 -7
View File
@@ -7,7 +7,22 @@ import {
completedStableArtifact,
} from "./readStableArtifact.js";
/** Completed file identity survives finalization; it does not establish decoded content. */
/** Identity facts of one completed stable read; they do not establish decoded content. */
export const stableArtifactObservation = (
snapshot: StableArtifactSnapshot,
path: string,
): FileSnapshotPartialObservation =>
fileSnapshotPartialObservationSchema.parse({
kind: "file-snapshot-hash",
path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
});
/**
* Completed file identity survives finalization and later decoding failures;
* `completed` is the snapshot a provider already holds when its parser fails.
*/
export const completedStableArtifactObservation = (
cause: unknown,
path: string,
@@ -16,10 +31,5 @@ export const completedStableArtifactObservation = (
const snapshot = completedSnapshot ?? completedStableArtifact(cause);
return snapshot === undefined
? undefined
: fileSnapshotPartialObservationSchema.parse({
kind: "file-snapshot-hash",
path,
sha256: snapshot.sha256,
bytes: snapshot.bytes.length,
});
: stableArtifactObservation(snapshot, path);
};
+46 -1
View File
@@ -192,7 +192,33 @@ it("routes bundle resource MCP calls with null executable identity and retained
});
});
it("exposes the production resource session through the MCP SDK for a keyless bundle", async () => {
const expectExplicitSelection = async (
client: Client,
request: {
readonly name: "decode_interface_builder" | "inspect_keyed_archive";
readonly parameters: Record<string, JsonValue>;
readonly previous: {
readonly normalized_result: unknown;
readonly evidence_id: string;
};
},
) => {
const response = await client.callTool({
name: request.name,
arguments: request.parameters,
});
expect(response.isError).not.toBe(true);
const evidence = toolContract(request.name).outputSchema.parse(
response.structuredContent,
);
expect(evidence.parameters).toEqual(request.parameters);
expect(evidence.normalized_result).toEqual(
request.previous.normalized_result,
);
expect(evidence.evidence_id).not.toBe(request.previous.evidence_id);
};
const createResourceMcpFixture = async () => {
const parent = await createTestTempDirectory(
"rea-bundle-resource-production-mcp-",
);
@@ -220,6 +246,13 @@ it("exposes the production resource session through the MCP SDK for a keyless bu
clientIdentity: { name: "production-bundle-resource-test", version: "1" },
});
return { client, session, alias, canonical };
};
it("exposes the production resource session through the MCP SDK for a keyless bundle", async () => {
const { client, session, alias, canonical } =
await createResourceMcpFixture();
const opened = await client.callTool({
name: "open_bundle_resources",
arguments: { path: alias },
@@ -256,6 +289,12 @@ it("exposes the production resource session through the MCP SDK for a keyless bu
},
},
});
expect(decodedEvidence.parameters).toEqual({});
await expectExplicitSelection(client, {
name: "decode_interface_builder",
parameters: { max_documents: 64 },
previous: decodedEvidence,
});
const decodedEvidenceId = z
.object({ evidence_id: z.string() })
.parse(decodedEvidence).evidence_id;
@@ -315,6 +354,12 @@ it("exposes the production resource session through the MCP SDK for a keyless bu
]),
},
});
expect(evidence.parameters).toEqual({ path: "Resources/Archive.plist" });
await expectExplicitSelection(client, {
name: "inspect_keyed_archive",
parameters: { path: "Resources/Archive.plist", offset: 0 },
previous: evidence,
});
const evidenceId = z
.object({ evidence_id: z.string() })
.parse(evidence).evidence_id;
+3 -1
View File
@@ -75,7 +75,7 @@ import {
const currentRequestSignal = new AsyncLocalStorage<AbortSignal>();
/** Capture structured issues from the canonical validation the SDK already performs. */
/** Capture caller selections and issues at the canonical SDK validation boundary. */
const captureInputValidation = <Schema extends StandardSchemaWithJSON>(
tool: string,
schema: Schema,
@@ -96,6 +96,8 @@ const captureInputValidation = <Schema extends StandardSchemaWithJSON>(
issues: result.issues as readonly z.core.$ZodIssue[],
input: value,
};
if (result.issues === undefined)
context?.captureCallerParameters(tool, value, result.value);
return result;
};
const result = standard.validate(value);
+35
View File
@@ -12,11 +12,21 @@ import {
} from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import { callerAnalysisParameters } from "../application/AnalysisInput.js";
import type { JsonValue } from "../domain/jsonValue.js";
const currentRequest = new AsyncLocalStorage<McpToolRequest>();
/** One SDK request owns validation, cancellation and its publication boundary. */
export class McpToolRequest {
readonly cancellation = new AbortController();
readonly #parameterSelections = new WeakMap<
object,
{
readonly tool: string;
readonly select: ReturnType<typeof callerAnalysisParameters>;
}
>();
validation?: {
readonly issues: readonly z.core.$ZodIssue[];
readonly input: unknown;
@@ -41,6 +51,31 @@ export class McpToolRequest {
readonly tool: string,
) {}
/** Capture only selected names at canonical validation, not the raw input tree. */
captureCallerParameters(tool: string, input: unknown, parsed: unknown): void {
if (parsed !== null && typeof parsed === "object")
this.#parameterSelections.set(parsed, {
tool,
select: callerAnalysisParameters(input),
});
}
/** The exact parsed object identifies its validation, including nested tool calls. */
callerParameters(
tool: string,
parsed: unknown,
parameters: Readonly<Record<string, JsonValue>>,
): Readonly<Record<string, JsonValue>> {
const selection =
parsed !== null && typeof parsed === "object"
? this.#parameterSelections.get(parsed)
: undefined;
// Dropping properties from a validated JSON object preserves its value type.
return (
selection?.tool === tool ? selection.select(parameters) : parameters
) as Readonly<Record<string, JsonValue>>;
}
beginHandler(): void {
this.#handlerStarted = true;
}
+4 -5
View File
@@ -44,6 +44,7 @@ import {
type DerivedSources,
createEvidenceToolHandler,
createRetainedSummaryToolHandler,
type RetainedSummaryOperation,
createValueToolHandler,
type ContractToolService,
type ValueOutcome,
@@ -287,9 +288,7 @@ type DerivedBinding = {
* Admit `detail`/`view` in the adapter, run the workflow on the remaining
* input, and retain the complete Evidence behind a summary.
*/
interface RetainedSummaryBinding<Input> {
readonly admission: ContractInputAdmission;
readonly summary: EvidenceOperation<Omit<Input, "detail" | "view">>;
type RetainedSummaryBinding<Input> = RetainedSummaryOperation<Input> & {
readonly run?: never;
readonly value?: never;
readonly derive?: never;
@@ -300,7 +299,7 @@ interface RetainedSummaryBinding<Input> {
readonly mutation?: never;
readonly query?: never;
readonly provider?: never;
}
};
/**
* Run an application workflow that completes Evidence from session-held
@@ -647,7 +646,7 @@ export const registerContractTools = (
: createRetainedSummaryToolHandler(
server,
contract as SummaryContract,
binding.summary,
binding,
logger,
retention,
withAdmittedAnalysis,
+31 -5
View File
@@ -27,6 +27,7 @@ import type { ToolContract } from "../contracts/toolContractTypes.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { isRecord } from "../kernel/isRecord.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
@@ -98,6 +99,23 @@ export const createContractToolHandler =
withAdmittedAnalysis,
)(contract);
/** Input admission owns whether inspection receives defaults or caller selections. */
export type RetainedSummaryOperation<Input> =
| {
readonly admission: "sdk";
readonly summary: (
input: Omit<Input, "detail" | "view">,
options: ExecutionOptions,
) => Promise<Result<Evidence, AnalysisError>>;
}
| {
readonly admission: "application";
readonly summary: (
input: unknown,
options: ExecutionOptions,
) => Promise<Result<Evidence, AnalysisError>>;
};
/** Validate delivery selection before inspection and retain its complete source for summaries. */
export const createRetainedSummaryToolHandler = <
Name extends string,
@@ -110,10 +128,7 @@ export const createRetainedSummaryToolHandler = <
>(
server: EvidenceMcpServer,
contract: ToolContract<Name, InputSchema>,
inspect: (
input: Omit<z.output<InputSchema>, "detail" | "view">,
options: ExecutionOptions,
) => Promise<Result<Evidence, AnalysisError>>,
operation: RetainedSummaryOperation<z.output<InputSchema>>,
logger: Logger,
retention: AnalysisViewRetention,
withAdmittedAnalysis?: WithAdmittedAnalysis,
@@ -136,7 +151,18 @@ export const createRetainedSummaryToolHandler = <
const ready = requireAnalysisViewRetention(contract.name, retention);
if (!ready.ok) return ready;
}
const inspected = await inspect(input, options);
const inspected = await (operation.admission === "sdk"
? operation.summary(input, options)
: operation.summary(
isRecord(rawInput)
? Object.fromEntries(
Object.entries(rawInput).filter(
([field]) => field !== "detail" && field !== "view",
),
)
: rawInput,
options,
));
return detail === "summary" && inspected.ok
? projectRetainedAnalysis(
inspected.value,
+2
View File
@@ -201,6 +201,7 @@ export const createServer = (
electronFuses,
releaseExposure,
pythonPyc,
elfDependencies,
webNetworkCapture,
javascriptRecovery,
artifactResources,
@@ -405,6 +406,7 @@ export const createServer = (
peImports,
windowsShortcut,
recordedCrash,
elfDependencies,
},
contractTools,
);
+11 -3
View File
@@ -27,6 +27,8 @@ import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
import { createOperationProgress } from "./operationProgress.js";
import { currentMcpToolRequest } from "./McpToolRequest.js";
/** A provider operation a tool contract names. */
export type ProviderOperation = Exclude<AnalysisOperation, "health">;
@@ -82,8 +84,14 @@ export const createProviderOperationToolHandler =
input: unknown,
context: ServerContext,
): Promise<CallToolResult> => {
const parameters = jsonObjectSchema.parse(input);
const ready = delivery?.preflight(parameters) ?? ok(null);
const resolved = jsonObjectSchema.parse(input);
const parameters =
currentMcpToolRequest()?.callerParameters(
contract.name,
input,
resolved,
) ?? resolved;
const ready = delivery?.preflight(resolved) ?? ok(null);
if (!ready.ok) return server.delivery.toCallToolResult(ready, contract);
const admitted = await dependencies.withAdmittedAnalysis(
contract.name,
@@ -147,7 +155,7 @@ export const createProviderOperationToolHandler =
server.delivery.toCallToolResult(evidence, contract),
);
const projected =
delivery?.projectEvidence(parameters, evidence.value) ??
delivery?.projectEvidence(resolved, evidence.value) ??
ok(evidence.value);
if (!projected.ok)
return progress.complete(
+7
View File
@@ -1,3 +1,4 @@
import type { ElfDependenciesService } from "../application/binaryDiagnostics/ElfDependenciesService.js";
import type { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
import type { AnalysisSettings } from "../application/AnalysisSettings.js";
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
@@ -846,6 +847,12 @@ const SERVICE_TOOL_BINDINGS = {
run: (input, options) => service.recover(input, options),
},
})) satisfies Bind<JavaScriptRecoveryService>,
elfDependencies: ((service) => ({
inspect_elf_dependencies: {
admission: "application",
summary: (input, options) => service.inspect(input, options),
},
})) satisfies Bind<ElfDependenciesService>,
guidance: ((resources) => ({
search_guidance: {
admission: "application",
@@ -0,0 +1,171 @@
import { rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { z } from "zod";
import { readEvidenceBundle } from "../../../src/application/EvidenceBundleFiles.js";
import { contractNamed } from "../../../src/cli/contractCliDescription.js";
import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "../../../src/contracts/analysisViewToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../../src/contracts/native/binaryDiagnosticsToolContracts.js";
import { evidenceSchema } from "../../../src/domain/evidence.js";
import { digestCanonicalValue } from "../../../src/domain/canonicalDigest.js";
import { analysisViewResultSchema } from "../../../src/domain/analysisView/analysisViewResult.js";
import { connectLocalToolsMcp } from "../../fixtures/localToolsMcp.js";
import { elfDependencyFixture } from "../../../src/native/elf/ElfDependencies.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const dependenciesContract = contractNamed(
BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
"inspect_elf_dependencies",
);
const viewContract = contractNamed(
ANALYSIS_VIEW_TOOL_CONTRACTS,
"inspect_analysis_view",
);
cliTest(
"queries retained ELF dependencies through CLI and actual stdio MCP after the source is deleted",
{ timeout: 60_000 },
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-dep-views-");
const path = join(root, "program");
await writeFile(
path,
elfDependencyFixture({
needed: ["libc.so.6", "libc.so.6", "libm.so.6"],
}),
);
const run = cli.run.bind(cli);
const complete = await run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(complete.exitCode, complete.stderr).toBe(0);
const parent = dependenciesContract.outputSchema.parse(complete.json);
const bundle = join(root, "complete.bundle.json");
const summarized = await run({
arguments: [
"inspect-elf-dependencies",
path,
"--detail",
"summary",
"--evidence_output",
bundle,
"--json",
],
});
expect(summarized.exitCode, summarized.stderr).toBe(0);
const delivered = z
.object({ summary: evidenceSchema })
.parse(summarized.json).summary;
expect(delivered.operation).toBe("inspect_analysis_view");
expect(delivered.normalized_result).toMatchObject({
parent_evidence_id: parent.evidence_id,
summary: {
needed_count: 3,
import_count: 5,
coverage: { status: "complete" },
},
});
const loaded = await readEvidenceBundle(bundle);
if (!loaded.ok) throw loaded.error;
expect(loaded.value.records).toEqual([parent]);
const call =
cli.sharedMcpCall === undefined
? (await connectLocalToolsMcp()).call
: await cli.sharedMcpCall();
const response = await call("inspect_elf_dependencies", {
path,
detail: "summary",
});
expect(response.isError).not.toBe(true);
expect(
dependenciesContract.outputSchema.parse(response.structuredContent)
.normalized_result,
).toEqual(delivered.normalized_result);
await rm(path);
const source = {
kind: "retained-evidence",
evidence_id: parent.evidence_id,
};
const request = {
source,
view: {
kind: "elf-dependencies",
collection: "needed",
names: ["libc.so.6"],
fields: ["name"],
offset: 1,
limit: 1,
},
};
const viewed = await call("inspect_analysis_view", request);
expect(viewed.isError).not.toBe(true);
const page = viewContract.outputSchema.parse(viewed.structuredContent);
expect(page.evidence_links).toContain(parent.evidence_id);
expect(page.normalized_result).toMatchObject({
kind: "elf-dependencies",
items: [{ source_index: 1, name: "libc.so.6" }],
dependencies: { coverage: { status: "complete" } },
coverage: { examined: 1, total: 2, next_offset: null, exhausted: true },
});
const offline = await run({
arguments: [
"inspect-analysis-view",
JSON.stringify(request),
"--evidence-bundle",
bundle,
"--json",
],
});
expect(offline.exitCode, offline.stderr).toBe(0);
expect(viewContract.outputSchema.parse(offline.json)).toEqual(page);
const projected = await call("inspect_analysis_view", {
...request,
view: {
...request.view,
collection: "imports",
names: ["printf"],
fields: ["name", "version"],
offset: 0,
limit: 1,
},
});
expect(projected.isError).not.toBe(true);
const projectedView = analysisViewResultSchema.parse(
viewContract.outputSchema.parse(projected.structuredContent)
.normalized_result,
);
expect(projectedView).toMatchObject({
items: [
{
source_index: 0,
name: "printf",
version: { name: "GLIBC_2.34", file: "libc.so.6" },
},
],
});
const { view_digest, ...content } = projectedView;
expect(view_digest).toBe(digestCanonicalValue(content, "Analysis view"));
},
);
cliTest(
"refuses CLI summary without a durable Evidence destination before reading",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"inspect-elf-dependencies",
"/rea-nonexistent/program",
"--detail",
"summary",
"--json",
],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { issues: [{ path: ["evidence_output"] }] },
});
},
);
+118
View File
@@ -0,0 +1,118 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { contractNamed } from "../../src/cli/contractCliDescription.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../src/contracts/native/binaryDiagnosticsToolContracts.js";
import { elfDependencyFixture } from "../../src/native/elf/ElfDependencies.fixture.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const dependenciesContract = contractNamed(
BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
"inspect_elf_dependencies",
);
cliTest(
"reports needed libraries, RUNPATH tokens, and versioned imports through the public CLI",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-dependencies-cli-");
const path = join(root, "program");
await writeFile(path, elfDependencyFixture());
const result = await cli.run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = dependenciesContract.outputSchema.parse(result.json);
expect(evidence.parameters).toEqual({ path });
const selected = await cli.run({
arguments: [
"inspect-elf-dependencies",
path,
"--max-needed",
"1024",
"--json",
],
});
expect(selected.exitCode, selected.stderr).toBe(0);
const explicitlySelected = dependenciesContract.outputSchema.parse(
selected.json,
);
expect(explicitlySelected.parameters).toEqual({ path, max_needed: 1024 });
expect(explicitlySelected.evidence_id).not.toBe(evidence.evidence_id);
expect(evidence.normalized_result).toMatchObject({
type_name: "shared",
needed: [
{ name: "libstdc++.so.6" },
{ name: "libm.so.6" },
{ name: "libc.so.6" },
],
dynamic: {
soname: { name: "libdemo.so.1" },
runpath: { raw: "$ORIGIN/../lib", tokens: ["$ORIGIN"] },
},
derived_version_maxima: expect.arrayContaining([
{ namespace: "GLIBC", maximum: "GLIBC_2.34", evidence_kind: "derived" },
]),
coverage: { status: "complete" },
});
expect(
(
evidence.normalized_result as { imports: { name: string | null }[] }
).imports.map((entry) => entry.name),
).toEqual(["printf", "memcpy", "_ZSt4cout", "abort", "_exit"]);
},
);
cliTest(
"resolves a relative ELF path against the working directory",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-dependencies-cli-rel-");
await writeFile(
join(root, "program"),
elfDependencyFixture({ omitDynamic: true, interpreter: null }),
);
const result = await cli.run({
arguments: ["inspect-elf-dependencies", "program", "--json"],
cwd: root,
});
expect(result.exitCode, result.stderr).toBe(0);
const evidence = dependenciesContract.outputSchema.parse(result.json);
expect(evidence.normalized_result).toMatchObject({
dynamic: { status: "absent" },
needed: [],
coverage: { status: "complete" },
});
expect(evidence.subject?.local_path).toBe(join(root, "program"));
expect(evidence.caller_input_path).toBe("program");
},
);
cliTest("reports a non-ELF file as invalid input", async ({ cli }) => {
const root = await createTestTempDirectory("rea-elf-dependencies-cli-bad-");
const path = join(root, "broken");
await writeFile(path, Buffer.from("not an elf"));
const result = await cli.run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_elf_dependencies" },
});
});
cliTest(
"reports a relocatable object as invalid input for this workflow",
async ({ cli }) => {
const root = await createTestTempDirectory(
"rea-elf-dependencies-cli-relobj-",
);
const path = join(root, "module.o");
await writeFile(path, elfDependencyFixture({ type: 1 }));
const result = await cli.run({
arguments: ["inspect-elf-dependencies", path, "--json"],
});
expect(result.exitCode).toBe(1);
expect(JSON.stringify(result.json)).toContain("inspect_kernel_module");
},
);
@@ -19,6 +19,7 @@ const fileCommands = [
"inspect-native-initializers",
"inspect-elf-unwind-ranges",
"inspect-kernel-module",
"inspect-elf-dependencies",
"inspect-kernel-build-config",
"inspect-byte-entropy",
"inspect-pe-resources",
@@ -256,6 +256,7 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
["inspect_apple_ips", { path: nul }],
["inspect_devicetree", { path: nul }],
["inspect_kernel_module", { path: nul }],
["inspect_elf_dependencies", { path: nul }],
["inspect_kernel_build_config", { path: nul }],
["inspect_pe_load_config", { path: nul }],
["audit_release_exposure", { path: nul }],
@@ -1391,7 +1391,9 @@ describe("Evidence delivery of contract commands", () => {
{ name: "probe", inputSchema },
{ command: "probe", description: "Probe" },
).parameters;
expect(format!.schema.parse(undefined)).toBe("json");
expect(format!.schema.parse(undefined)).toBeUndefined();
expect(inputJsonSchema(format!.schema).default).toBe("json");
expect(inputSchema.parse({})).toEqual({ format: "json" });
expect(format!.schema.safeParse("graphql").success).toBe(true);
expect(format!.schema.safeParse("xml").success).toBe(false);
});
@@ -241,6 +241,12 @@ describe("CLI advertised input schemas", () => {
});
expect(
parserSchema(cli, "inspect-keyed-archive", "args")?.parse({ path: "x" }),
).toEqual({ path: "x" });
expect(
parserSchema(cli, "inspect-keyed-archive", "args")?.parse({
path: "x",
archive: ".",
}),
).toEqual({ path: "x", archive: "." });
const help = await serve(cli, ["inspect-keyed-archive", "--help"]);
@@ -248,7 +254,7 @@ describe("CLI advertised input schemas", () => {
"Usage: rea inspect-keyed-archive <path> [archive] [options]",
);
expect(help.stdout).toContain(
"archive Relative archive path when the target is a bundle",
"archive Relative archive path when the target is a bundle (default: .)",
);
});
@@ -303,13 +309,14 @@ describe("firmware CLI advertised input schema", () => {
expect(options({ offset: maxOffset + 1 })).toBe(false);
expect(options({ length: maxOffset + 1 })).toBe(false);
expect(
parserSchema(cli, "extract-firmware", "options")?.parse({}),
).toMatchObject({
const parser = parserSchema(cli, "extract-firmware", "options");
expect(parser?.parse({})).toEqual({});
const selected = {
maxDepth: 3,
maxOutputBytes: 256 * 1024 * 1024,
maxOutputFiles: 10_000,
});
};
expect(parser?.parse(selected)).toEqual(selected);
});
});
@@ -0,0 +1,39 @@
import { expect, it } from "vitest";
import { registerCaptureCommands } from "../../../src/cli/captureCommands.js";
import { contractCommandDescriptions } from "../../../src/cli/contractCommand.js";
import { registerSignalCommands } from "../../../src/cli/signalCommands.js";
import { registerSqliteCommands } from "../../../src/cli/sqliteCommands.js";
import { silentLogger } from "../../../src/logger.js";
import { createCommandCli } from "../../support/cli/commandCli.js";
const cli = createCommandCli();
registerCaptureCommands(cli, silentLogger, {});
registerSignalCommands(cli, silentLogger, {});
registerSqliteCommands(cli, silentLogger, {});
it.each([
{ command: "inspect-packet-capture", options: { fields: ["ip.addr"] } },
{ command: "decode-signal-recording", options: { decoders: "uart" } },
{ command: "inspect-sqlite-database", options: {} },
])(
"$command resolves defaults only for cross-field checks and preserves caller omission",
({ command, options }) => {
const description = contractCommandDescriptions(cli).find(
(candidate) => candidate.command === command,
);
if (description === undefined)
throw new Error(`Missing command ${command}`);
// These JSON strings are decoded when the command runs, after argv checks.
// Checking defaults must not reparse already-admitted option values.
const limits = description.parameters.find(
(parameter) => parameter.field === "producer_limits",
);
const text = '{"input_bytes":1024}';
const values =
limits === undefined ? options : { ...options, [limits.key]: text };
expect(description.checkOptions?.(values)).toEqual([]);
expect(description.toContractInput(values)).toEqual(
limits === undefined ? options : { ...options, producer_limits: text },
);
},
);
+5 -3
View File
@@ -55,8 +55,6 @@ describe("decompile-all CLI", () => {
address_start: "0X1000",
address_end: "0X1040",
limit: 1,
layout: "address",
resume: false,
},
normalized_result: {
output_directory: join(root, "out"),
@@ -64,6 +62,8 @@ describe("decompile-all CLI", () => {
counts: { selected: 2, excluded: 2, written: 1, remaining: 1 },
},
});
expect(result.json).not.toHaveProperty("parameters.layout");
expect(result.json).not.toHaveProperty("parameters.resume");
expect(await readdir(join(root, "out", "functions"))).toEqual([
"0x1000.c",
]);
@@ -79,6 +79,8 @@ describe("decompile-all CLI", () => {
"--output",
"out",
"--resume",
"--layout",
"address",
"--address-start",
"0X1000",
"--address-end",
@@ -93,7 +95,7 @@ describe("decompile-all CLI", () => {
});
expect(resumed.exitCode, JSON.stringify(resumed.json)).toBe(0);
expect(resumed.json).toMatchObject({
parameters: { limit: 100001, resume: true },
parameters: { limit: 100001, resume: true, layout: "address" },
normalized_result: {
counts: { selected: 2, written: 1, skipped: 1, remaining: 0 },
},
@@ -101,8 +101,8 @@ it("advertises the optional integrity policy without an undefined union", async
expect(policy).toMatchObject({
type: "string",
enum: ["fail", "record-and-continue"],
description:
"Behavior when declared application integrity does not match (default: fail)",
default: "fail",
description: "Behavior when declared application integrity does not match",
});
expect(JSON.stringify(policy)).not.toContain("undefined");
});
+1 -1
View File
@@ -131,11 +131,11 @@ it("advertises each option's default without supplying it to routing", async ()
expect(schema.properties).toMatchObject({
mode: {
default: "fast",
description: "Default: fast",
},
policy: { default: JSON.stringify({ rules: [] }) },
report: { default: "text" },
});
expect(schema.properties.mode).not.toHaveProperty("description");
// A given option routes the input even when it spells the default.
const refused = await invoke("/x/program", { report: "text" });
expect(calls).toEqual([]);
@@ -51,7 +51,7 @@ it("forwards admitted original strings and caller-selected search/provider contr
);
});
it("keeps an omitted mask omitted", async () => {
it("keeps omitted mask and limit selections omitted", async () => {
const { cli, run } = registry();
await cli.serve(["search-bytes", "/selected", "AB", "--json"], {
stdout: () => undefined,
@@ -60,7 +60,7 @@ it("keeps an omitted mask omitted", async () => {
expect(run).toHaveBeenCalledExactlyOnceWith(
"/selected",
"search_bytes",
{ pattern: "AB", limit: 100 },
{ pattern: "AB" },
expect.any(Object),
);
});
@@ -0,0 +1,90 @@
import { symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { createElfDependenciesService } from "../../../src/composition/binaryDiagnostics.js";
import { elfDependencyFixture } from "../../../src/native/elf/ElfDependencies.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("ELF dependency stable filesystem boundary", () => {
it("reports non-file and malformed ELF selections as caller input errors", async () => {
const root = await createTestTempDirectory("rea-elf-dependencies-files-");
const path = join(root, "program");
const alias = join(root, "alias");
const malformed = join(root, "malformed");
await writeFile(path, elfDependencyFixture());
await writeFile(malformed, Buffer.from("not an elf"));
await symlink(path, alias);
const service = createElfDependenciesService();
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_dependencies",
issues: [
{
path: ["path"],
reason,
message: expect.any(String),
},
],
});
}
} finally {
await service.close();
}
});
it.each([".gnu.version_r", ".gnu.version_d"])(
"keeps the inventory when %s declares a range past the file end",
async (oversizedSection) => {
const root = await createTestTempDirectory("rea-elf-dependencies-range-");
const path = join(root, "program");
await writeFile(path, elfDependencyFixture({ oversizedSection }));
const service = createElfDependenciesService();
try {
const result = await service.inspect({ path });
if (!result.ok) throw new Error(result.error.message);
expect(result.value.normalized_result).toMatchObject({
artifact: { path },
coverage: { status: "partial" },
needed: expect.arrayContaining([
expect.objectContaining({ name: "libc.so.6" }),
]),
});
} finally {
await service.close();
}
},
);
it("returns typed resource and cancellation failures", async () => {
const root = await createTestTempDirectory("rea-elf-dependencies-budget-");
const path = join(root, "program");
await writeFile(path, elfDependencyFixture());
const service = createElfDependenciesService();
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_needed: 1 });
if (tooMany.ok) throw new Error("Expected entry 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();
}
});
});
@@ -83,6 +83,7 @@ const standaloneAnalysisCases = (
{ name: "inspect_sqlite_database", input: {} },
{ name: "inspect_pe_resources", input: {} },
{ name: "inspect_native_exports", input: {} },
{ name: "inspect_elf_dependencies", input: {} },
{ name: "inspect_electron_fuses", input: {} },
{ name: "inspect_packet_capture", input: { fields: ["ip.addr"] } },
{
@@ -1,4 +1,5 @@
import { expect } from "vitest";
import { z } from "zod";
import {
TOOL_CONTRACTS,
toolContract,
@@ -23,6 +24,92 @@ const evidenceServer = () =>
createToolResultDelivery(undefined),
);
mcpTest(
"application summary admission preserves nested caller omissions",
async ({ mcp }) => {
const received: unknown[] = [];
const contract = {
...toolContract("inspect_elf_dependencies"),
name: "inspect_nested_fixture",
inputSchema: z.strictObject({
path: z.string(),
policy: z.strictObject({
count: z.int().default(12),
mode: z.string().default("full"),
}),
detail: z.enum(["complete", "summary"]).default("complete"),
}),
};
const server = evidenceServer();
registerContractTools(
server,
{
inspect_nested_fixture: {
admission: "application",
summary: (input: unknown) => {
received.push(input);
return Promise.resolve(
err(new AnalysisInputError("inspect_nested_fixture")),
);
},
},
} as ContractToolBindings,
{ logger: silentLogger },
[contract],
);
const client = await mcp.connect(server);
const request = { path: "/fixture", policy: { count: 2 } };
const reply = await client.callTool({
name: contract.name,
arguments: request,
});
expect(reply.isError).toBe(true);
expect(received).toEqual([request]);
},
);
for (const admission of ["sdk", "application"] as const)
mcpTest(
`${admission} summary admission preserves its input-default ownership`,
async ({ mcp }) => {
const received: unknown[] = [];
const inspect = (input: unknown) => {
received.push(input);
return Promise.resolve(
err(new AnalysisInputError("inspect_elf_dependencies")),
);
};
const server = evidenceServer();
registerContractTools(
server,
{ inspect_elf_dependencies: { admission, summary: inspect } },
{ logger: silentLogger },
[toolContract("inspect_elf_dependencies")],
);
const client = await mcp.connect(server);
for (const selected of [undefined, 1024, 2]) {
const request = {
path: "/fixture",
...(selected === undefined ? {} : { max_needed: selected }),
};
const reply = await client.callTool({
name: "inspect_elf_dependencies",
arguments: { ...request, detail: "complete" },
});
expect(reply.isError).toBe(true);
const source = received.at(-1);
if (admission === "application") expect(source).toEqual(request);
else
expect(source).toMatchObject({
path: request.path,
max_needed: selected ?? 1024,
max_file_bytes: 67108864,
});
expect(source).not.toHaveProperty("detail");
}
},
);
mcpTest(
"registers a contract added to the registry from its binding alone",
async ({ mcp }) => {
@@ -0,0 +1,133 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { contractNamed } from "../../../src/cli/contractCliDescription.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "../../../src/contracts/native/binaryDiagnosticsToolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
import { elfDependencyFixture } from "../../../src/native/elf/ElfDependencies.fixture.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";
const dependenciesContract = contractNamed(
BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
"inspect_elf_dependencies",
);
const connect = async (mcp: TestMcp) => {
const session = createTestBinarySession(() => {
throw new Error("ELF dependency inspection must not start a deep provider");
});
const client = await mcp.connect(createServer({ kind: "session", session }));
return { client, session };
};
mcpTest(
"advertises inspect_elf_dependencies and reads a 32-bit big-endian image",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const advertised = (await client.listTools()).tools.find(
(tool) => tool.name === "inspect_elf_dependencies",
);
expect(advertised?.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
const root = await createTestTempDirectory("rea-elf-dependencies-mcp-");
const path = join(root, "program");
await writeFile(path, elfDependencyFixture({ bits: 32, little: false }));
const response = await client.callTool({
name: "inspect_elf_dependencies",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = dependenciesContract.outputSchema.parse(
response.structuredContent,
);
expect(evidence.parameters).toEqual({ path });
const selected = await client.callTool({
name: "inspect_elf_dependencies",
arguments: { path, max_needed: 1024 },
});
expect(selected.isError).not.toBe(true);
const explicitlySelected = dependenciesContract.outputSchema.parse(
selected.structuredContent,
);
expect(explicitlySelected.parameters).toEqual({
path,
max_needed: 1024,
});
expect(explicitlySelected.evidence_id).not.toBe(evidence.evidence_id);
expect(evidence.normalized_result).toMatchObject({
format: "elf32",
byte_order: "big",
machine: 8,
dynamic: { runpath: { tokens: ["$ORIGIN"] } },
});
expect(
(evidence.normalized_result as { needed: { name: string | null }[] })
.needed[0]?.name,
).toBe("libstdc++.so.6");
expect(evidence.subject?.identity).toMatchObject({
kind: "file",
architecture: "mips",
});
} finally {
await session.close();
}
},
);
mcpTest(
"requires an absolute path for inspect_elf_dependencies",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const response = await client.callTool({
name: "inspect_elf_dependencies",
arguments: { path: "program" },
});
expect(response.isError).toBe(true);
expect(parseMcpToolError(response).error).toMatchObject({
code: "invalid_request",
details: { operation: "inspect_elf_dependencies" },
});
} finally {
await session.close();
}
},
);
mcpTest(
"reports a stripped image from program headers without a disassembler session",
async ({ mcp }) => {
const { client, session } = await connect(mcp);
try {
const root = await createTestTempDirectory(
"rea-elf-dependencies-stripped-mcp-",
);
const path = join(root, "program");
await writeFile(path, elfDependencyFixture({ stripped: true }));
const response = await client.callTool({
name: "inspect_elf_dependencies",
arguments: { path },
});
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = dependenciesContract.outputSchema.parse(
response.structuredContent,
);
expect(evidence.normalized_result).toMatchObject({
coverage: { status: "complete" },
needed: [
{ name: "libstdc++.so.6" },
{ name: "libm.so.6" },
{ name: "libc.so.6" },
],
});
} finally {
await session.close();
}
},
);
+11 -9
View File
@@ -87,7 +87,7 @@ const invalidArguments = [
] as const;
describe("official operation arguments", () => {
it("dispatches equivalent CLI and MCP arguments while retaining omissions and defaults", async () => {
it("dispatches equivalent CLI and MCP selections while retaining omissions and explicit defaults", async () => {
const [path] = await createBinarySessionTargets();
const calls: Array<{
name: string;
@@ -130,29 +130,31 @@ describe("official operation arguments", () => {
createManagedBinarySession: createSession,
};
const client = await connect({ execute });
for (const [name, mcpParameters, cliParameters] of [
["procedure_pseudo_code", { procedure: "main" }, { procedure: "main" }],
["search_bytes", { pattern: "48 ??" }, { pattern: "48 ??", limit: 100 }],
for (const [name, parameters] of [
["procedure_pseudo_code", { procedure: "main" }],
["search_bytes", { pattern: "48 ??" }],
["search_bytes", { pattern: "48 ??", limit: 100 }],
["search_strings", { pattern: "entry" }],
[
"search_strings",
{ pattern: "entry" },
{ pattern: "entry", mode: "literal", case_sensitive: false },
],
] as const) {
const cli = parseEvidence(
await runDirectAnalysis(dependencies, path, name, cliParameters).then(
await runDirectAnalysis(dependencies, path, name, parameters).then(
projectCliAnalysisResult,
),
);
const mcp = await client.callTool({ name, arguments: mcpParameters });
const mcp = await client.callTool({ name, arguments: parameters });
expect(mcp.isError).not.toBe(true);
expect(calls.slice(-2)).toEqual([
{ name, parameters: cliParameters },
{ name, parameters: cliParameters },
{ name, parameters },
{ name, parameters },
]);
expect(mcp.structuredContent).toMatchObject({
parameters: cli.parameters,
});
expect(cli.parameters).toEqual(parameters);
expect(cli.parameters).not.toHaveProperty("document");
}
});
@@ -9,6 +9,7 @@ import { inspectPeCertificatesInputSchema } from "../../../src/domain/native/peC
import { inspectPeImportsInputSchema } from "../../../src/domain/native/peImports.js";
import { inspectElfNotesInputSchema } from "../../../src/domain/native/elfNotes.js";
import { inspectKernelModuleInputSchema } from "../../../src/domain/native/kernelModule.js";
import { inspectElfDependenciesInputSchema } from "../../../src/domain/native/elfDependencies.js";
import { inspectNativeExportsInputSchema } from "../../../src/domain/native/nativeExports.js";
import { inspectAppleIpsInputSchema } from "../../../src/domain/native/appleIps.js";
import { inspectWindowsShortcutInputSchema } from "../../../src/domain/native/windowsShortcut.js";
@@ -18,6 +19,7 @@ import { PeCertificatesProvider } from "../../../src/native/pe/PeCertificatesPro
import { PeImportsProvider } from "../../../src/native/pe/PeImportsProvider.js";
import { ElfNotesProvider } from "../../../src/native/elf/ElfNotesProvider.js";
import { KernelModuleProvider } from "../../../src/native/elf/KernelModuleProvider.js";
import { ElfDependenciesProvider } from "../../../src/native/elf/ElfDependenciesProvider.js";
import { NativeExportsProvider } from "../../../src/native/exports/NativeExportsProvider.js";
import { AppleIpsProvider } from "../../../src/native/apple/AppleIpsProvider.js";
import { WindowsShortcutProvider } from "../../../src/native/windows/WindowsShortcutProvider.js";
@@ -91,6 +93,19 @@ const cases = [
};
},
},
{
name: "ELF dependencies",
make: () => {
const provider = new ElfDependenciesProvider();
return {
inspect: (path: string, signal: AbortSignal) =>
provider.inspect(inspectElfDependenciesInputSchema.parse({ path }), {
signal,
}),
close: () => provider.close(),
};
},
},
{
name: "native exports",
make: () => {
@@ -60,6 +60,12 @@ export const PROVIDER_CAPABILITY_CONFORMANCE: Readonly<
electronFuses: { cases: ["tests/acceptance/electronFusesCli.test.ts"] },
electronObservation: { cases: ["tests/boundary/cli/electronCli.test.ts"] },
elfNotes: { cases: ["tests/acceptance/elfNotesCli.test.ts"] },
elfDependencies: {
cases: [
"tests/acceptance/elfDependenciesCli.test.ts",
"tests/boundary/mcp/elfDependenciesMcp.test.ts",
],
},
elfUnwindRanges: { cases: ["tests/acceptance/elfUnwindRangesCli.test.ts"] },
erlangBeam: { cases: ["tests/acceptance/erlangBeamCli.test.ts"] },
evmInterface: { cases: ["tests/boundary/mcp/evmInterfaceMcp.test.ts"] },
@@ -118,6 +118,7 @@ import { NativeInitializersProvider } from "../../src/native/initializers/Native
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 { ElfDependenciesProvider } from "../../src/native/elf/ElfDependenciesProvider.js";
import { KernelBuildConfigProvider } from "../../src/native/elf/KernelBuildConfigProvider.js";
import { PeCertificatesProvider } from "../../src/native/pe/PeCertificatesProvider.js";
import { PeImportsProvider } from "../../src/native/pe/PeImportsProvider.js";
@@ -129,6 +130,7 @@ import { inspectNativeInitializersInputSchema } from "../../src/domain/native/na
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 { inspectElfDependenciesInputSchema } from "../../src/domain/native/elfDependencies.js";
import { inspectKernelBuildConfigInputSchema } from "../../src/domain/native/kernelBuildConfig.js";
import { inspectPeCertificatesInputSchema } from "../../src/domain/native/peCertificates.js";
import { inspectPeImportsInputSchema } from "../../src/domain/native/peImports.js";
@@ -1017,6 +1019,7 @@ const stableArtifactProviders = [
["ELF unwind ranges", () => new ElfUnwindRangesProvider()],
["Apple IPS", () => new AppleIpsProvider()],
["kernel module", () => new KernelModuleProvider()],
["ELF dependencies", () => new ElfDependenciesProvider()],
["kernel build config", () => new KernelBuildConfigProvider()],
["PE certificates", () => new PeCertificatesProvider()],
["PE load configuration", () => new PeLoadConfigProvider()],
@@ -1069,6 +1072,11 @@ const inspectFileFailure = (
inspectKernelModuleInputSchema.parse({ path }),
options,
);
if (provider instanceof ElfDependenciesProvider)
return provider.inspect(
inspectElfDependenciesInputSchema.parse({ path }),
options,
);
if (provider instanceof KernelBuildConfigProvider)
return provider.inspect(
inspectKernelBuildConfigInputSchema.parse({ path }),
@@ -1149,6 +1157,7 @@ it.each(
(provider instanceof ElfNotesProvider ||
provider instanceof ElfUnwindRangesProvider ||
provider instanceof KernelModuleProvider ||
provider instanceof ElfDependenciesProvider ||
provider instanceof KernelBuildConfigProvider ||
provider instanceof PeCertificatesProvider ||
provider instanceof PeResourcesProvider
@@ -1283,6 +1283,15 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly<
),
),
),
"rea-elf-dependencies": inProcess(
covered(
test(
"tests/acceptance/elfDependenciesCli.test.ts",
"reports needed libraries, RUNPATH tokens, and versioned imports through the public CLI",
),
),
typedFailures("tests/boundary/filesystem/elfDependencies.test.ts"),
),
"rea-elf-notes": inProcess(
covered(
test(