mirror of
https://github.com/morluto/rea.git
synced 2026-12-02 19:46:07 +00:00
feat(native): list Mach-O function starts and data-in-code entries offline (#14897)
* feat(native): list Mach-O function starts and data-in-code entries offline
The diff adds a static reader for LC_FUNCTION_STARTS and LC_DATA_IN_CODE
on one thin Mach-O or one selected slice of a universal file. Starts are
absolute VM addresses from ULEB128 deltas off the __TEXT vmaddr, and
each data-in-code entry reports offset, length, kind, and the function
start that owns its address, with one offset and limit applied to each
selected table and counts covering every entry.
inspect_macho_function_starts and inspect-macho-function-starts expose
that report, require architecture only for a universal file, and refuse
a combined table above max_entries with no partial result. The shared
load-command walk now yields each command once and stores the Mach-O
segment name and vmaddr on load regions, and the guides and limit docs
record coverage, paging, and the read and entry budgets.
* build: add advertised schema summary for inspect_macho_function_starts
* Address review feedback
* fix(native): bound function-start decoding and page before building rows
- Check each start against an interval index of executable segments, built
once, instead of scanning every segment per start.
- Walk LC_FUNCTION_STARTS once. Count and check every start and
data-in-code entry, but build result objects only for the requested page,
and resolve owners for that page during the same walk.
- Keep every declared Mach-O segment in the shared reader (macho_segments),
so a __TEXT with no file bytes still anchors the deltas, as
llvm-objdump does. LoadRegion no longer carries macho_segment.
- On 32-bit ARM, clear the Thumb tag (bit 0) from published starts and
report it as `thumb`, keeping the tagged value for the next delta, as
ld64 encodes and LLDB decodes. Wrap 32-bit images at 2^32.
- Intersect Evidence file ranges with the selected universal slice.
* refactor(native): normalize function-start format facts once
- One table, MACHO_DICE_KIND_NAMES, names data-in-code kinds for the
reader, the schema and the report check, which each had their own copy.
- Each linkedit command's dataoff/datasize is normalized once against the
slice (end, 32-bit fit, in-slice bytes) instead of the overflow check and
the in-slice length being recomputed in three helpers.
- Name CPU_TYPE_ARM, VM_PROT_EXECUTE and UINT32_MAX after their headers.
- Report coverage.text_not_at_header when __TEXT does not map file offset
0: llvm-objdump anchors the deltas on the __TEXT vmaddr and dyld on the
mach_header address, and they disagree there.
- Pin the fixture's expected starts to literal addresses.
* build: refresh the inspect_macho_function_starts schema summary after merging main
* fix(cli): keep lipo's flag name out of --architecture help text
The architecture help for four commands said "as lipo -thin does", which
the CLI option-alias check reads as a registered short flag `-thin`.
Describe the lipo behavior without spelling its flag.
* Revert "fix(cli): keep lipo's flag name out of --architecture help text"
This reverts commit 68f25adf74.
* refactor(cli): use the shared universal-slice help for inspect-macho-function-starts
* fix(native): bound decoding by max_entries and map data-in-code from the header
- Refuse a data table above max_entries from its byte count, and stop the
start walk at the remaining allowance, so the allowance bounds decoding
work. The refusal no longer claims a required_value it did not measure.
- Map each data-in-code offset as the mach_header's VM address plus the
offset, the way ld64 encodes it and dyld documents it. MH_OBJECT does not
map its header, so its base is 0. The shared container now carries
mach_header.filetype.
- Use the same header address for text_not_at_header, which also catches a
header shifted by SG_HIGHVM.
- Report a list that ends without its zero terminator as
unterminated_starts.
- Accept an observed empty section name in both result schemas.
* fix(native): tally LINKEDIT commands compactly and report a known entry total
- Count LC_FUNCTION_STARTS and LC_DATA_IN_CODE commands during the shared
load-command walk into a compact tally (two 32-bit words per command)
instead of retaining a view and an object for each one. The shared
visitor now hands over the image's byte order.
- When the image has no starts to decode, a data table above max_entries is
refused with its exact count as required_value.
* fix(native): report a non-Mach-O input as unrecognized, not malformed
Ask the shared Mach-O header recognizer before the thin reader. An ELF or
PE file passed without `architecture` has no Mach-O magic, so it is an
unrecognized target for this operation. A recognized Mach-O with a broken
or cut-off header still fails as malformed or truncated.
---------
Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
41 files changed
+4510
-12
No files matched your search
@@ -220,6 +220,21 @@ separate functions. Leaf functions have no entry, so a missing entry is not
|
||||
absence. Compare provider addresses minus `image_base` with the RVAs. See
|
||||
[PE x64 exception-directory function ranges](https://github.com/morluto/rea/blob/main/docs/guides/native/pe-unwind-ranges.md).
|
||||
|
||||
## Mach-O function starts and data in code
|
||||
|
||||
Use `inspect_macho_function_starts` for an explicit local thin Mach-O, or one
|
||||
slice of a universal Mach-O, when the question is which addresses the linker
|
||||
recorded as function starts, or which bytes inside code are jump tables or
|
||||
literal data. Pass `architecture` for a universal file. The CLI equivalent is
|
||||
`inspect-macho-function-starts PATH`. Starts are absolute VM addresses from
|
||||
`LC_FUNCTION_STARTS` (ULEB128 deltas from the `__TEXT` vmaddr). Data-in-code
|
||||
entries name offset, length, kind (`DICE_KIND_DATA`, `JUMP_TABLE8`,
|
||||
`JUMP_TABLE16`, `JUMP_TABLE32`, `ABS_JUMP_TABLE32`, or the numeric kind), and
|
||||
the function start that owns the address. Page with `offset` and `limit`.
|
||||
Counts cover every entry. A stripped image can still carry these tables. The
|
||||
reader does not disassemble. See
|
||||
[Mach-O function starts and data in code](https://github.com/morluto/rea/blob/main/docs/guides/native/macho-function-starts.md).
|
||||
|
||||
## PE overlay
|
||||
|
||||
Use `inspect_pe_overlay` for an explicit local PE32/PE32+ image when the
|
||||
|
||||
@@ -220,6 +220,21 @@ separate functions. Leaf functions have no entry, so a missing entry is not
|
||||
absence. Compare provider addresses minus `image_base` with the RVAs. See
|
||||
[PE x64 exception-directory function ranges](https://github.com/morluto/rea/blob/main/docs/guides/native/pe-unwind-ranges.md).
|
||||
|
||||
## Mach-O function starts and data in code
|
||||
|
||||
Use `inspect_macho_function_starts` for an explicit local thin Mach-O, or one
|
||||
slice of a universal Mach-O, when the question is which addresses the linker
|
||||
recorded as function starts, or which bytes inside code are jump tables or
|
||||
literal data. Pass `architecture` for a universal file. The CLI equivalent is
|
||||
`inspect-macho-function-starts PATH`. Starts are absolute VM addresses from
|
||||
`LC_FUNCTION_STARTS` (ULEB128 deltas from the `__TEXT` vmaddr). Data-in-code
|
||||
entries name offset, length, kind (`DICE_KIND_DATA`, `JUMP_TABLE8`,
|
||||
`JUMP_TABLE16`, `JUMP_TABLE32`, `ABS_JUMP_TABLE32`, or the numeric kind), and
|
||||
the function start that owns the address. Page with `offset` and `limit`.
|
||||
Counts cover every entry. A stripped image can still carry these tables. The
|
||||
reader does not disassemble. See
|
||||
[Mach-O function starts and data in code](https://github.com/morluto/rea/blob/main/docs/guides/native/macho-function-starts.md).
|
||||
|
||||
## PE overlay
|
||||
|
||||
Use `inspect_pe_overlay` for an explicit local PE32/PE32+ image when the
|
||||
|
||||
@@ -128,6 +128,11 @@ export const documentationSections = [
|
||||
source: "guides/native/elf-unwind-ranges.md",
|
||||
route: "/elf-unwind-ranges",
|
||||
},
|
||||
{
|
||||
text: "Mach-O function starts",
|
||||
source: "guides/native/macho-function-starts.md",
|
||||
route: "/macho-function-starts",
|
||||
},
|
||||
{
|
||||
text: "Linux kernel build config",
|
||||
source: "guides/native/kernel-build-config.md",
|
||||
|
||||
@@ -36,6 +36,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages.
|
||||
- [ELF separate debug files](guides/native/elf-debug-link.md)
|
||||
- [ELF and Mach-O initializer functions](guides/native/native-initializers.md)
|
||||
- [ELF unwind function ranges](guides/native/elf-unwind-ranges.md)
|
||||
- [Mach-O function starts and data in code](guides/native/macho-function-starts.md)
|
||||
- [Linux kernel build config](guides/native/kernel-build-config.md)
|
||||
- [Recorded crash evidence](guides/native/recorded-crashes.md)
|
||||
- [Windows Shell Link shortcuts](guides/native/windows-shortcut.md)
|
||||
|
||||
@@ -705,6 +705,18 @@ reported present, absent, or incomplete and is not decoded. A missing unwind tab
|
||||
observed absence of those declarations. See
|
||||
[ELF unwind function ranges](../guides/native/elf-unwind-ranges.md).
|
||||
|
||||
List Mach-O function starts and data-in-code entries without executing the
|
||||
image:
|
||||
|
||||
```bash
|
||||
rea inspect-macho-function-starts /absolute/path/to/program --json
|
||||
```
|
||||
|
||||
The workflow reports `LC_FUNCTION_STARTS` VM addresses and `LC_DATA_IN_CODE`
|
||||
entries (offset, length, kind, and the owning start). Universal Mach-O files
|
||||
need `--architecture`. Counts cover every entry. See
|
||||
[Mach-O function starts and data in code](../guides/native/macho-function-starts.md).
|
||||
|
||||
Inspect an Apple `.ips` crash report without executing a target:
|
||||
|
||||
```bash
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# Mach-O function starts and data in code
|
||||
|
||||
Use `inspect_macho_function_starts` to read `LC_FUNCTION_STARTS` and
|
||||
`LC_DATA_IN_CODE` from one thin Mach-O, or from one slice of a universal file.
|
||||
`LC_FUNCTION_STARTS` is the linker's ULEB128 delta list of function starts.
|
||||
Images that carry `LC_DATA_IN_CODE` mark jump tables and literal data inside
|
||||
`__TEXT`. The reader does not disassemble and does not execute the image.
|
||||
|
||||
```sh
|
||||
rea inspect-macho-function-starts /absolute/path/to/program --limit 0 --json
|
||||
rea inspect-macho-function-starts /absolute/path/to/program --architecture arm64 --kind starts --json
|
||||
```
|
||||
|
||||
MCP accepts `{ "path": "/absolute/path/to/program" }`. A universal file also
|
||||
needs `architecture`. CLI paths may be relative to the current directory; MCP
|
||||
paths must be absolute.
|
||||
|
||||
## What it reports
|
||||
|
||||
- `function_starts` and `data_in_code` give each command's `dataoff`,
|
||||
`datasize`, container `file_offset`, and whether that range sits in
|
||||
`__LINKEDIT`. `status` is `present` or `absent`.
|
||||
- Start addresses are absolute VM addresses. The first delta is added to the
|
||||
`vmaddr` of the first declared `__TEXT` segment, which need not have file
|
||||
bytes, as `llvm-objdump --function-starts` does. A zero delta ends the list.
|
||||
Zero bytes after that terminator are padding. A sum past the image's 32- or
|
||||
64-bit address space is a wrapped start. dyld adds the deltas to the
|
||||
`mach_header` address instead. The two agree when `__TEXT` maps file offset 0. When it doesn't, `coverage.text_not_at_header` is 1 and coverage is
|
||||
`partial`, because the base is disputed.
|
||||
- On 32-bit ARM, ld64 sets bit 0 of a Thumb start and takes the next delta
|
||||
from that tagged value. `vmaddr` clears that bit, as LLDB does, and `thumb`
|
||||
records whether it was set. Other architectures omit `thumb`.
|
||||
- Each start names the section that contains it, such as `__text`.
|
||||
- Each data-in-code entry has its `data_in_code_entry` `offset`, its VM
|
||||
address, `length`, and `kind`. ld64 writes the offset as the entry's address
|
||||
minus the `mach_header` address, and dyld documents it as a delta from the
|
||||
`mach_header`, so the VM address is that header address plus the offset. A
|
||||
relocatable object (`MH_OBJECT`) does not map its header, so its offset is
|
||||
the address itself. An entry whose header address is unknown or ambiguous,
|
||||
or whose address is outside every segment, has no VM address and counts as
|
||||
unmapped. The kinds are:
|
||||
- `DICE_KIND_DATA`
|
||||
- `JUMP_TABLE8`
|
||||
- `JUMP_TABLE16`
|
||||
- `JUMP_TABLE32`
|
||||
- `ABS_JUMP_TABLE32`
|
||||
- Any other kind stays the numeric `uint16`.
|
||||
- `owner` is the greatest decoded start at or before that VM address, with
|
||||
that start's index.
|
||||
- `coverage` counts every start and every complete 8-byte data entry. It also
|
||||
counts duplicate commands, commands whose `cmdsize` is not 16, tables outside
|
||||
`__LINKEDIT`, commands that extend past the file, truncated or overflowing
|
||||
ULEB128, wrapped addresses, addresses outside every executable segment, a
|
||||
missing `__TEXT` anchor, a `mach_header` not mapped at the `__TEXT` vmaddr,
|
||||
a list that ends without its zero terminator, nonzero bytes after the
|
||||
terminator, a data tail
|
||||
shorter than 8 bytes, entries that leave their section, offsets that are not
|
||||
strictly increasing, offsets outside every segment, and zero lengths. Any of
|
||||
those counters makes `coverage.status` `partial`.
|
||||
- `page` records `kind` (`all`, `starts`, or `data`), `offset`, `limit`, and
|
||||
the next offset of each selected table. The same offset and limit apply to
|
||||
each selected table. `limit: 0` returns counts only. Every entry is checked
|
||||
and counted, but only the returned page is built, so a small page of a large
|
||||
table stays small in memory.
|
||||
- The Evidence file ranges of the two tables stay inside the selected slice.
|
||||
A table declared past the slice's end keeps its declared `dataoff` and
|
||||
`file_offset`, but contributes no range in another slice's bytes.
|
||||
|
||||
## Reading the result
|
||||
|
||||
The starts are the addresses the linker recorded. A stripped image can still
|
||||
carry the list. A missing command is `absent`, and the standing limitations
|
||||
say what that absence leaves unknown. Compare a provider procedure address
|
||||
with `starts[].vmaddr`. A data-in-code entry names the start that owns its
|
||||
address, so a jump table or literal pool inside a function stays attached to
|
||||
that start.
|
||||
|
||||
When a command is declared more than once, the first one is decoded. Decoding
|
||||
stops at the first wrapped or out-of-text start, and that address stays in
|
||||
the list.
|
||||
|
||||
## Failures
|
||||
|
||||
A file that is not Mach-O, such as an ELF or PE image, is a target failure
|
||||
of kind `unrecognized`: this operation reads only Mach-O. A Mach-O whose
|
||||
header or load commands are broken, or a universal slice that cannot be read,
|
||||
is a target failure of kind `malformed` or `truncated`. `architecture` on a thin image is refused. A universal file
|
||||
without `architecture` is refused.
|
||||
|
||||
`max_entries` (default 2,097,152, at most 16,777,216; CLI `--max-entries`)
|
||||
bounds decoded starts plus complete data-in-code entries, and bounds the
|
||||
decoding work as well as the result. A data table larger than the allowance
|
||||
is refused from its byte count before any entry is examined, and the start
|
||||
walk stops once the combined count would pass it. When the image has no
|
||||
function starts to decode, the data count is the whole total and the refusal
|
||||
reports it as `required_value`. Otherwise decoding stopped before the total
|
||||
was measured, so `details.limit` omits `required_value`. The call returns no partial report.
|
||||
|
||||
The default [read allowance](../../reference/limits-and-recovery.md#static-reader-read-allowance)
|
||||
is 64 MiB (`max_file_bytes`, floor 64 bytes, ceiling 512 MiB). The identity
|
||||
pass stops at 4 GiB minus one byte, because `dataoff` and FAT32 slice offsets
|
||||
are 32-bit. `max_file_bytes` does not raise that ceiling.
|
||||
`max_structure_bytes` bounds the load-command table read.
|
||||
@@ -121,7 +121,8 @@ their per-call budgets (`max_file_bytes`, entry, depth and decoded-byte budgets,
|
||||
`max_output_bytes`/`max_output_files`, and `block_size` or `length`).
|
||||
`inspect_devicetree` bounds its estimated decoded representation with
|
||||
`max_decoded_bytes` (default 32 MiB, at most 256 MiB).
|
||||
`inspect_elf_dependencies`, `inspect_elf_unwind_ranges`, `inspect_apple_ips`,
|
||||
`inspect_elf_dependencies`, `inspect_elf_unwind_ranges`, `inspect_macho_function_starts`,
|
||||
`inspect_apple_ips`,
|
||||
`inspect_dwarf_units`, `inspect_native_initializers`, `inspect_pe_overlay`,
|
||||
`inspect_pe_resources` (`max_entries`), `inspect_api_contract` (`max_file_bytes`),
|
||||
`compare_wasm_interfaces` (`max_interface_bytes`),
|
||||
@@ -132,7 +133,7 @@ import and lambda rows combined; default 65,536, at most 1,048,576).
|
||||
|
||||
### Native table structure budget
|
||||
|
||||
`inspect_elf_unwind_ranges`, `inspect_kernel_module`, `inspect_elf_debug_link`,
|
||||
`inspect_elf_unwind_ranges`, `inspect_macho_function_starts`, `inspect_kernel_module`, `inspect_elf_debug_link`,
|
||||
`inspect_dwarf_units`, `inspect_binary_hardening`, `inspect_native_initializers`,
|
||||
`inspect_gpu_code_objects` and `inspect_native_exports` accept `max_structure_bytes` (CLI
|
||||
`--max-structure-bytes`, 64 bytes to 512 MiB, default 16 MiB). It bounds one
|
||||
@@ -170,7 +171,8 @@ whose declared count exceeds `max_entries` reports that count as
|
||||
### Static reader read allowance
|
||||
|
||||
`inspect_pe_imports`, `inspect_pe_resources`, `inspect_pe_load_config`,
|
||||
`inspect_pe_certificates`, `inspect_pe_unwind_ranges`, `inspect_binary_hardening` and
|
||||
`inspect_pe_certificates`, `inspect_pe_unwind_ranges`, `inspect_macho_function_starts`,
|
||||
`inspect_binary_hardening` and
|
||||
`inspect_native_exports` bound the bytes they read, not the file size.
|
||||
`max_file_bytes` (CLI `--max-file-bytes`) counts each positional read of
|
||||
headers, directory tables and the ranges they reference. Defaults are 64 MiB
|
||||
@@ -185,15 +187,18 @@ It is a lower bound, since later reads depend on structures not yet decoded, so
|
||||
the limit reports no `required_value`. Raise `max_file_bytes` and retry;
|
||||
`update_analysis_settings` does not change it.
|
||||
The identity pass has a fixed whole-file ceiling: 4 GiB minus one byte for the
|
||||
PE-only readers, whose file offsets are 32-bit, and 512 MiB for hardening and
|
||||
exports. A file above it is a `file-size` refusal naming that fixed allowance,
|
||||
which `max_file_bytes` does not raise.
|
||||
PE readers and `inspect_macho_function_starts` (their file offsets are 32-bit),
|
||||
and 512 MiB for hardening and exports. A file above it is a `file-size`
|
||||
refusal naming that fixed allowance, which `max_file_bytes` does not raise.
|
||||
|
||||
The PE readers also report `details.limit` for their per-call inventory budgets:
|
||||
Those readers also report `details.limit` for their per-call inventory budgets:
|
||||
`inspect_pe_imports` `max_dlls`, `max_functions` and `max_text_bytes` (decoded
|
||||
names, default 16 MiB, at most 256 MiB); `inspect_pe_load_config`
|
||||
`max_callbacks`; `inspect_pe_unwind_ranges` `max_entries` (default 2,097,152, at
|
||||
most 16,777,216; the declared count is its `required_value`); and
|
||||
most 16,777,216; the declared count is its `required_value`);
|
||||
`inspect_macho_function_starts` `max_entries` (default 2,097,152, at most
|
||||
16,777,216; the combined start and data-in-code count is its `required_value`);
|
||||
and
|
||||
`inspect_pe_resources` `max_entries` and `max_metadata_bytes` (the complete
|
||||
result, default 8 MiB, at most 256 MiB).
|
||||
|
||||
|
||||
@@ -357,6 +357,7 @@ export const ENTRY_FILES = Object.freeze(
|
||||
"NativeMacOSProviderMetadata.ts",
|
||||
"NativeMacosProviderIdentity.ts",
|
||||
"apple/AppleIpsProvider.ts",
|
||||
"apple/MachoFunctionStartsProvider.ts",
|
||||
"dwarf/DwarfUnitsProvider.ts",
|
||||
"elf/ElfDebugLinkProvider.ts",
|
||||
"elf/ElfDependenciesProvider.ts",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "6746e8a82cfb7ec9",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {
|
||||
"input": ["^[^\\x00]*$"]
|
||||
}
|
||||
}
|
||||
@@ -383,7 +383,7 @@
|
||||
"src/resources/artifactReadBudget.ts": {
|
||||
"ceiling.name": {
|
||||
"class": "forwarding",
|
||||
"reason": "Relays the whole-file identity ceiling its caller names: 4 GiB minus one byte for PE-only readers, whose file offsets are 32-bit (format), and the 512 MiB artifact-size bound of the hardening and exports result schemas. max_file_bytes, a per-call parameter with details.limit, bounds what the readers read."
|
||||
"reason": "Relays the whole-file identity ceiling its caller names: 4 GiB minus one byte for the PE-only readers and the Mach-O function-starts reader, whose file offsets (PE fields, LC_FUNCTION_STARTS and LC_DATA_IN_CODE dataoff, FAT32 slice offsets) are 32-bit (format), and the 512 MiB artifact-size bound of the hardening and exports result schemas. max_file_bytes, a per-call parameter with details.limit, bounds what the readers read."
|
||||
}
|
||||
},
|
||||
"src/sqlite/SqliteDatabaseFailures.ts": {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { bufferByteSource } from "../../domain/byteSource.js";
|
||||
import { MACHO_FUNCTION_STARTS_PROVIDER } from "../../domain/investigationProviders.js";
|
||||
import {
|
||||
inspectMachoFunctionStartsInputSchema,
|
||||
type MachoFunctionStarts,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import {
|
||||
arm64FunctionStartsImage,
|
||||
machoFunctionStartsUniversal,
|
||||
x64FunctionStartsImage,
|
||||
} from "../../native/apple/MachoFunctionStarts.fixture.js";
|
||||
import { parseMachoFunctionStartsFromHandle } from "../../native/apple/MachoFunctionStarts.js";
|
||||
import type { StableArtifactHandle } from "../../resources/index.js";
|
||||
import { expectInvalidInspectionInputs } from "../../../tests/support/expectInvalidInspectionInputs.js";
|
||||
import { lateCancellationEvidence } from "../../../tests/support/lateCancellationEvidence.js";
|
||||
import { MachoFunctionStartsService } from "./MachoFunctionStartsService.js";
|
||||
|
||||
const identity = MACHO_FUNCTION_STARTS_PROVIDER;
|
||||
const SHA = "b".repeat(64);
|
||||
|
||||
const parsed = (
|
||||
bytes: Buffer,
|
||||
raw: Readonly<Record<string, unknown>> = {},
|
||||
): Promise<MachoFunctionStarts> => {
|
||||
const input = inspectMachoFunctionStartsInputSchema.parse({
|
||||
path: "/artifacts/program",
|
||||
...raw,
|
||||
});
|
||||
const source = bufferByteSource(bytes);
|
||||
const handle: StableArtifactHandle = {
|
||||
sha256: SHA,
|
||||
size: source.size,
|
||||
prefix: source.prefix,
|
||||
readRange: source.readRange,
|
||||
};
|
||||
return parseMachoFunctionStartsFromHandle(
|
||||
handle,
|
||||
{ path: input.path, sha256: SHA, bytes: bytes.length },
|
||||
input,
|
||||
);
|
||||
};
|
||||
|
||||
const arm = await parsed(arm64FunctionStartsImage());
|
||||
|
||||
const accept = (value: MachoFunctionStarts) =>
|
||||
new MachoFunctionStartsService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(value)),
|
||||
}).inspect({ path: value.artifact.path });
|
||||
|
||||
it("rejects a relative path and extra arguments before reading", () =>
|
||||
expectInvalidInspectionInputs(
|
||||
arm,
|
||||
"program",
|
||||
(inspect) => new MachoFunctionStartsService({ identity, inspect }),
|
||||
));
|
||||
|
||||
it("records Mach-O function starts for the selected image", async () => {
|
||||
const result = await accept(arm);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
confidence: "observed",
|
||||
operation: "inspect_macho_function_starts",
|
||||
subject: { identity: { format: "mach-o", architecture: "arm64" } },
|
||||
normalized_result: arm,
|
||||
});
|
||||
expect(result.value.locations).toEqual([
|
||||
{ kind: "artifact-path", path: arm.artifact.path },
|
||||
{
|
||||
kind: "file-offset-range",
|
||||
start: 0x4000,
|
||||
end: 0x4000 + 11,
|
||||
},
|
||||
{
|
||||
kind: "file-offset-range",
|
||||
start: 0x4200,
|
||||
end: 0x4200 + 24,
|
||||
},
|
||||
]);
|
||||
expect(result.value.limitations).toEqual(arm.limitations);
|
||||
|
||||
const universal = await parsed(
|
||||
machoFunctionStartsUniversal(
|
||||
arm64FunctionStartsImage(),
|
||||
x64FunctionStartsImage(),
|
||||
),
|
||||
{ architecture: "x86_64" },
|
||||
);
|
||||
const selected = await new MachoFunctionStartsService({
|
||||
identity,
|
||||
inspect: () => Promise.resolve(ok(universal)),
|
||||
}).inspect({ path: universal.artifact.path, architecture: "x86_64" });
|
||||
if (!selected.ok) throw selected.error;
|
||||
expect(selected.value.subject.identity).toMatchObject({
|
||||
format: "mach-o-universal",
|
||||
architecture: "x86_64",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a report whose coverage status disagrees with its counters", async () => {
|
||||
for (const inconsistent of [
|
||||
{
|
||||
...arm,
|
||||
coverage: { ...arm.coverage, status: "partial" as const },
|
||||
},
|
||||
{
|
||||
...arm,
|
||||
coverage: {
|
||||
...arm.coverage,
|
||||
status: "complete" as const,
|
||||
duplicate_commands: 1,
|
||||
},
|
||||
},
|
||||
{
|
||||
...arm,
|
||||
limitations: arm.limitations.filter(
|
||||
(line) => line !== arm.limitations[0],
|
||||
),
|
||||
},
|
||||
]) {
|
||||
const result = await accept(inconsistent);
|
||||
expect(result.ok).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the completed report when cancellation lands after inspection", async () => {
|
||||
const evidence = await lateCancellationEvidence(
|
||||
arm,
|
||||
"inspect_macho_function_starts",
|
||||
(inspect) => new MachoFunctionStartsService({ identity, inspect }),
|
||||
);
|
||||
expect(evidence.normalized_result).toEqual(arm);
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
|
||||
import type { MachoFunctionStartsPort } from "../../ports/binaryDiagnostics/MachoFunctionStartsPort.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
MACHO_FUNCTION_STARTS_LIMITATIONS,
|
||||
inspectMachoFunctionStartsInputSchema,
|
||||
machoDataInCodeKind,
|
||||
machoFunctionStartsHasIssues,
|
||||
machoFunctionStartsSchema,
|
||||
type InspectMachoFunctionStartsInput,
|
||||
type MachoDataInCode,
|
||||
type MachoFunctionStarts,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import { metadataReportSubjectFormat } from "../../domain/apple/machoTargetSelection.js";
|
||||
import { observedFileEvidence } from "../observedFileEvidence.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
import { executeArtifactInspection } from "../ArtifactInspectionExecution.js";
|
||||
|
||||
const OPERATION = "inspect_macho_function_starts";
|
||||
|
||||
/** Shared caller validation, output parsing and Evidence provenance for CLI/MCP. */
|
||||
export class MachoFunctionStartsService {
|
||||
constructor(readonly provider: MachoFunctionStartsPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close?.() ?? Promise.resolve();
|
||||
}
|
||||
|
||||
inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
return executeArtifactInspection(
|
||||
{
|
||||
operation: OPERATION,
|
||||
inputSchema: inspectMachoFunctionStartsInputSchema,
|
||||
outputSchema: machoFunctionStartsSchema,
|
||||
provider: this.provider,
|
||||
retainCompletedReport: true,
|
||||
invalidOutputMessage:
|
||||
"Mach-O function-start provider returned malformed output or changed artifact identity.",
|
||||
toParameters: (input) => input,
|
||||
validateReport: (report, parameters) =>
|
||||
report.artifact.path === parameters.path &&
|
||||
validReport(report, parameters),
|
||||
buildEvidence: (value, identity, parameters) =>
|
||||
observedFileEvidence(
|
||||
value,
|
||||
identity,
|
||||
OPERATION,
|
||||
parameters,
|
||||
locations(value),
|
||||
{
|
||||
format: metadataReportSubjectFormat({
|
||||
format: value.format,
|
||||
...(value.selected_slice === undefined
|
||||
? {}
|
||||
: { selected_slice: value.selected_slice }),
|
||||
}),
|
||||
...(value.architecture === null
|
||||
? {}
|
||||
: { architecture: value.architecture }),
|
||||
},
|
||||
),
|
||||
},
|
||||
rawInput,
|
||||
options,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Observed file ranges of the two LINKEDIT tables, intersected with the
|
||||
* selected slice. A table that a malformed slice declares past its own end is
|
||||
* not evidence in the next slice's bytes; the command fields keep the declared
|
||||
* offsets.
|
||||
*/
|
||||
const locations = (report: MachoFunctionStarts) => {
|
||||
const sliceStart = report.selected_slice?.offset ?? 0;
|
||||
const sliceEnd = Math.min(
|
||||
report.artifact.bytes,
|
||||
report.selected_slice === undefined
|
||||
? report.artifact.bytes
|
||||
: report.selected_slice.offset + report.selected_slice.byte_length,
|
||||
);
|
||||
const ranges = [];
|
||||
for (const command of [report.function_starts, report.data_in_code]) {
|
||||
if (command.file_offset === null || command.datasize === null) continue;
|
||||
const start = Math.max(command.file_offset, sliceStart);
|
||||
const end = Math.min(sliceEnd, command.file_offset + command.datasize);
|
||||
if (start >= end) continue;
|
||||
ranges.push({ kind: "file-offset-range" as const, start, end });
|
||||
}
|
||||
return ranges;
|
||||
};
|
||||
|
||||
const pageLength = (total: number, offset: number, limit: number): number =>
|
||||
Math.min(limit, Math.max(0, total - offset));
|
||||
|
||||
const commandAgrees = (
|
||||
command: MachoFunctionStarts["function_starts"],
|
||||
total: number,
|
||||
): boolean =>
|
||||
command.status === "absent"
|
||||
? total === 0 &&
|
||||
command.dataoff === null &&
|
||||
command.datasize === null &&
|
||||
command.file_offset === null &&
|
||||
command.in_linkedit === null
|
||||
: (command.dataoff === null) === (command.datasize === null) &&
|
||||
(command.dataoff === null || typeof command.in_linkedit === "boolean");
|
||||
|
||||
/** A numeric kind must be one the shared table leaves unnamed. */
|
||||
const kindAgrees = (kind: MachoDataInCode["kind"]): boolean =>
|
||||
typeof kind === "string" || machoDataInCodeKind(kind) === kind;
|
||||
|
||||
/** The counts and page the reader reports must agree with each other. */
|
||||
const validReport = (
|
||||
report: MachoFunctionStarts,
|
||||
input: InspectMachoFunctionStartsInput,
|
||||
): boolean => {
|
||||
const { coverage, page, starts, data_in_code_entries: data } = report;
|
||||
const startsIncluded = input.kind !== "data";
|
||||
const dataIncluded = input.kind !== "starts";
|
||||
const startCount = startsIncluded
|
||||
? pageLength(coverage.total_starts, input.offset, input.limit)
|
||||
: 0;
|
||||
const dataCount = dataIncluded
|
||||
? pageLength(coverage.total_data_in_code, input.offset, input.limit)
|
||||
: 0;
|
||||
if (
|
||||
machoFunctionStartsHasIssues(coverage) ===
|
||||
(coverage.status === "complete") ||
|
||||
page.kind !== input.kind ||
|
||||
page.offset !== input.offset ||
|
||||
page.limit !== input.limit ||
|
||||
page.total_starts !== coverage.total_starts ||
|
||||
page.total_data !== coverage.total_data_in_code ||
|
||||
page.returned_starts !== starts.length ||
|
||||
page.returned_data !== data.length ||
|
||||
starts.length !== startCount ||
|
||||
data.length !== dataCount ||
|
||||
page.next_starts_offset !==
|
||||
(startsIncluded && input.offset + starts.length < coverage.total_starts
|
||||
? input.offset + starts.length
|
||||
: null) ||
|
||||
page.next_data_offset !==
|
||||
(dataIncluded && input.offset + data.length < coverage.total_data_in_code
|
||||
? input.offset + data.length
|
||||
: null) ||
|
||||
!commandAgrees(report.function_starts, coverage.total_starts) ||
|
||||
!commandAgrees(report.data_in_code, coverage.total_data_in_code) ||
|
||||
!report.limitations.includes(
|
||||
MACHO_FUNCTION_STARTS_LIMITATIONS.missingStarts,
|
||||
) ||
|
||||
!report.limitations.includes(
|
||||
MACHO_FUNCTION_STARTS_LIMITATIONS.missingData,
|
||||
) ||
|
||||
!report.limitations.includes(MACHO_FUNCTION_STARTS_LIMITATIONS.static)
|
||||
)
|
||||
return false;
|
||||
return (
|
||||
starts.every((entry, index) => entry.index === input.offset + index) &&
|
||||
data.every(
|
||||
(entry, index) =>
|
||||
entry.index === input.offset + index &&
|
||||
kindAgrees(entry.kind) &&
|
||||
(entry.owner === null || entry.owner.index < coverage.total_starts),
|
||||
)
|
||||
);
|
||||
};
|
||||
@@ -162,6 +162,32 @@ export const registerBinaryDiagnosticsCommands = (
|
||||
"rea-pe-unwind-ranges",
|
||||
),
|
||||
);
|
||||
registerContractCommand(
|
||||
cli,
|
||||
logger,
|
||||
contract("inspect_macho_function_starts"),
|
||||
{
|
||||
description:
|
||||
"List Mach-O function starts and data-in-code entries without executing the image",
|
||||
positionals: ["path"],
|
||||
callerPaths: ["path"],
|
||||
fields: {
|
||||
path: {
|
||||
description: "Local thin Mach-O or universal Mach-O image",
|
||||
},
|
||||
architecture: {
|
||||
description: UNIVERSAL_SLICE_ARCHITECTURE_HELP,
|
||||
},
|
||||
},
|
||||
},
|
||||
inspectWithService(
|
||||
async () =>
|
||||
(
|
||||
await import("../composition/binaryDiagnostics/machoFunctionStarts.js")
|
||||
).createMachoFunctionStartsService(),
|
||||
"rea-macho-function-starts",
|
||||
),
|
||||
);
|
||||
registerContractCommand(
|
||||
cli,
|
||||
logger,
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
import { MachoFunctionStartsService } from "../../application/binaryDiagnostics/MachoFunctionStartsService.js";
|
||||
import { MachoFunctionStartsProvider } from "../../native/apple/MachoFunctionStartsProvider.js";
|
||||
|
||||
export const createMachoFunctionStartsService =
|
||||
(): MachoFunctionStartsService =>
|
||||
new MachoFunctionStartsService(new MachoFunctionStartsProvider());
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
JAVASCRIPT_RUNTIME_RECONCILIATION_PROVIDER,
|
||||
KERNEL_BUILD_CONFIG_PROVIDER,
|
||||
KERNEL_MODULE_PROVIDER,
|
||||
MACHO_FUNCTION_STARTS_PROVIDER,
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
MANAGED_WORKFLOW_PROVIDER,
|
||||
NATIVE_EXPORTS_PROVIDER,
|
||||
@@ -432,6 +433,13 @@ export const CAPABILITY_DECLARATIONS = {
|
||||
kuna: {
|
||||
providers: [providerBinding(KUNA_PROVIDER_IDENTITY, KUNA_OPERATIONS)],
|
||||
},
|
||||
machoFunctionStarts: {
|
||||
providers: [
|
||||
providerBinding(MACHO_FUNCTION_STARTS_PROVIDER, [
|
||||
"inspect_macho_function_starts",
|
||||
]),
|
||||
],
|
||||
},
|
||||
managedStatic: {
|
||||
providers: [
|
||||
providerBinding(MANAGED_STATIC_PROVIDER, {
|
||||
|
||||
@@ -84,6 +84,7 @@ import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHo
|
||||
import { pcapCaptureHostSupported } from "../domain/pcap/pcapAnalysis.js";
|
||||
import { createPeLoadConfigService } from "./binaryDiagnostics/peLoadConfig.js";
|
||||
import { createPeUnwindRangesService } from "./binaryDiagnostics/peUnwindRanges.js";
|
||||
import { createMachoFunctionStartsService } from "./binaryDiagnostics/machoFunctionStarts.js";
|
||||
import { createPeOverlayService } from "./binaryDiagnostics/peOverlay.js";
|
||||
import { createBinaryHardeningService } from "./binaryDiagnostics/binaryHardening.js";
|
||||
import { createPeCertificatesService } from "./binaryDiagnostics/peCertificates.js";
|
||||
@@ -422,6 +423,7 @@ const modules = {
|
||||
peLoadConfig: service(() => createPeLoadConfigService()),
|
||||
peOverlay: service(() => createPeOverlayService()),
|
||||
peUnwindRanges: service(() => createPeUnwindRangesService()),
|
||||
machoFunctionStarts: service(() => createMachoFunctionStartsService()),
|
||||
binaryHardening: service(() => createBinaryHardeningService()),
|
||||
peCertificates: service(() => createPeCertificatesService()),
|
||||
peImports: service(() => createPeImportsService()),
|
||||
|
||||
@@ -14,6 +14,10 @@ import {
|
||||
peUnwindRangesSchema,
|
||||
inspectPeUnwindRangesInputSchema,
|
||||
} from "../../domain/native/peUnwindRanges.js";
|
||||
import {
|
||||
inspectMachoFunctionStartsInputSchema,
|
||||
machoFunctionStartsSchema,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import {
|
||||
binaryHardeningSchema,
|
||||
inspectBinaryHardeningInputSchema,
|
||||
@@ -300,6 +304,27 @@ export const BINARY_DIAGNOSTICS_TOOL_CONTRACTS = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_macho_function_starts",
|
||||
availability: "standalone",
|
||||
cli: true,
|
||||
...toolContractMetadata("inspect_macho_function_starts", evidenceEffects),
|
||||
kind: "native-provider",
|
||||
description:
|
||||
"Decode LC_FUNCTION_STARTS and LC_DATA_IN_CODE for one thin Mach-O or one selected universal slice: paged function-start VM addresses and data-in-code entries (offset, length, kind, owning start). Counts cover every entry. Duplicate commands, tables outside __LINKEDIT, truncated ULEB128, non-monotonic or out-of-text addresses, and data-in-code entries that leave their section are limitations. A missing command is observed absence. No execution or disassembler. A universal file requires architecture. A table larger than max_entries fails without partial success.",
|
||||
inputSchema: inspectMachoFunctionStartsInputSchema,
|
||||
outputSchema: evidenceResultOf(machoFunctionStartsSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "List Mach-O function starts and data-in-code entries",
|
||||
input: { path: "/artifacts/program" },
|
||||
},
|
||||
{
|
||||
title: "Count starts in one universal slice",
|
||||
input: { path: "/artifacts/program", architecture: "arm64", limit: 0 },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_apple_ips",
|
||||
availability: "standalone",
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { ElfDebugLink } from "./native/elfDebugLink.js";
|
||||
import type { ElfDependencies } from "./native/elfDependencies.js";
|
||||
import type { ElfNotes } from "./native/elfNotes.js";
|
||||
import type { ElfUnwindRanges } from "./native/elfUnwindRanges.js";
|
||||
import type { MachoFunctionStarts } from "./native/machoFunctionStarts.js";
|
||||
import type { PeUnwindRanges } from "./native/peUnwindRanges.js";
|
||||
import type { KernelBuildConfig } from "./native/kernelBuildConfig.js";
|
||||
import type { KernelModule } from "./native/kernelModule.js";
|
||||
@@ -736,6 +737,7 @@ export type AnalysisPartialObservation =
|
||||
| ElfDependencies
|
||||
| ElfNotes
|
||||
| ElfUnwindRanges
|
||||
| MachoFunctionStarts
|
||||
| PeUnwindRanges
|
||||
| KernelBuildConfig
|
||||
| KernelModule
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
type BinaryContainer,
|
||||
type ImageSection,
|
||||
type LoadRegion,
|
||||
type MachoSegmentDeclaration,
|
||||
} from "../binaryContainer.js";
|
||||
import {
|
||||
MachoLoadCommandCursor,
|
||||
@@ -35,10 +36,25 @@ export const readMachoImage = (
|
||||
): Extract<BinaryContainer, { format: "macho" }> =>
|
||||
readMachoImageCore(bytes, bytes.length, structureBytes);
|
||||
|
||||
/** Same thin Mach-O header and section read over a random-access source without buffering the full image. */
|
||||
/** One framed load command handed to a reader's visitor during the shared walk. */
|
||||
export interface MachoLoadCommandVisit {
|
||||
readonly command: number;
|
||||
readonly size: number;
|
||||
/** The whole command, `cmdsize` bytes from its `cmd` field. A view, not a copy. */
|
||||
readonly body: Buffer;
|
||||
/** Byte order of the image, so a visitor decodes fields without the result. */
|
||||
readonly littleEndian: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Same thin Mach-O header and section read over a random-access source without
|
||||
* buffering the full image. `visit` sees every framed load command during the
|
||||
* one shared walk, so a consumer needing other commands does not walk again.
|
||||
*/
|
||||
export const readMachoImageFromReader = async (
|
||||
source: ByteSource,
|
||||
structureBytes: number = DEFAULT_NATIVE_STRUCTURE_BYTES,
|
||||
visit?: (command: MachoLoadCommandVisit) => void,
|
||||
): Promise<Extract<BinaryContainer, { format: "macho" }>> => {
|
||||
const headerPrefix = await readByteSourceSlice(
|
||||
source,
|
||||
@@ -71,13 +87,14 @@ export const readMachoImageFromReader = async (
|
||||
0,
|
||||
table.headerSize + table.commandBytes,
|
||||
);
|
||||
return readMachoImageCore(tableBytes, source.size, structureBytes);
|
||||
return readMachoImageCore(tableBytes, source.size, structureBytes, visit);
|
||||
};
|
||||
|
||||
const readMachoImageCore = (
|
||||
bytes: Buffer,
|
||||
fileBytes: number,
|
||||
structureBytes: number,
|
||||
visit?: (command: MachoLoadCommandVisit) => void,
|
||||
): Extract<BinaryContainer, { format: "macho" }> => {
|
||||
const parsed = readMachoLoadCommandDeclarations(bytes, fileBytes);
|
||||
if (!parsed.ok) throw new BinaryFormatFailure("malformed", parsed.error);
|
||||
@@ -110,6 +127,7 @@ const readMachoImageCore = (
|
||||
const executableMappings: FileMapping[] = [];
|
||||
const zeroFills: ZeroFillMapping[] = [];
|
||||
const sections: ImageSection[] = [];
|
||||
const segmentDeclarations: MachoSegmentDeclaration[] = [];
|
||||
let chainedFixups = false;
|
||||
const commands = new MachoLoadCommandCursor(table);
|
||||
while (commands.nextOffset !== null) {
|
||||
@@ -117,6 +135,12 @@ const readMachoImageCore = (
|
||||
const frame = commands.read(bytes.subarray(offset, offset + 8));
|
||||
if (!frame.ok) throw new BinaryFormatFailure("malformed", frame.error);
|
||||
const { command, size } = frame.value;
|
||||
visit?.({
|
||||
command,
|
||||
size,
|
||||
body: bytes.subarray(offset, offset + size),
|
||||
littleEndian: little,
|
||||
});
|
||||
if (command === LC.DYLD_CHAINED_FIXUPS) chainedFixups = true;
|
||||
if (command === LC.SEGMENT || command === LC.SEGMENT_64) {
|
||||
const wide = command === LC.SEGMENT_64;
|
||||
@@ -167,6 +191,14 @@ const readMachoImageCore = (
|
||||
? undefined
|
||||
: { ...fileRange, address: fileAddress };
|
||||
const name = decodeMachoFixedName(nameBytes);
|
||||
segmentDeclarations.push({
|
||||
name,
|
||||
address: parsedSegment.value.address,
|
||||
memory_size: memorySize,
|
||||
file_offset: fileOffset,
|
||||
file_size: fileSize,
|
||||
protection,
|
||||
});
|
||||
if (mapping !== undefined && name !== "__PAGEZERO") {
|
||||
mappings.push(mapping);
|
||||
loadRegions.push({
|
||||
@@ -224,6 +256,8 @@ const readMachoImageCore = (
|
||||
return {
|
||||
format: "macho",
|
||||
macho_cpu_type: table.identity.cpuType,
|
||||
macho_file_type: table.fileType,
|
||||
macho_segments: segmentDeclarations,
|
||||
macho_chained_fixups: chainedFixups,
|
||||
architecture: names.get(cpu) ?? `macho-cpu-${cpu}`,
|
||||
bits,
|
||||
|
||||
@@ -297,9 +297,31 @@ export type BinaryContainer = BinaryContainerFacts &
|
||||
};
|
||||
}
|
||||
| { readonly format: "pe" }
|
||||
| { readonly format: "macho"; readonly macho_cpu_type: number }
|
||||
| {
|
||||
readonly format: "macho";
|
||||
readonly macho_cpu_type: number;
|
||||
/** `mach_header.filetype`, such as MH_OBJECT (1) or MH_EXECUTE (2). */
|
||||
readonly macho_file_type: number;
|
||||
/**
|
||||
* Every LC_SEGMENT/LC_SEGMENT_64 in declaration order, including
|
||||
* segments with no file bytes. `load_regions` holds only the
|
||||
* file-backed ones, so whether a segment was declared is read here.
|
||||
*/
|
||||
readonly macho_segments: readonly MachoSegmentDeclaration[];
|
||||
}
|
||||
);
|
||||
|
||||
/** One declared Mach-O segment command, whether or not it has file bytes. */
|
||||
export interface MachoSegmentDeclaration {
|
||||
readonly name: string;
|
||||
readonly address: bigint;
|
||||
readonly memory_size: bigint;
|
||||
readonly file_offset: bigint;
|
||||
readonly file_size: bigint;
|
||||
/** Initial VM protection (`initprot`). */
|
||||
readonly protection: number;
|
||||
}
|
||||
|
||||
/** All declared file-backed image memory, including PE headers at the image base. */
|
||||
export const imageFileMappings = (
|
||||
container: BinaryContainer,
|
||||
|
||||
@@ -233,6 +233,12 @@ export const PE_UNWIND_RANGES_PROVIDER = Object.freeze({
|
||||
version: "1",
|
||||
} as const);
|
||||
|
||||
export const MACHO_FUNCTION_STARTS_PROVIDER = Object.freeze({
|
||||
id: "rea-macho-function-starts",
|
||||
name: "REA Mach-O function-start parser",
|
||||
version: "1",
|
||||
} as const);
|
||||
|
||||
export const PE_LOAD_CONFIG_PROVIDER = Object.freeze({
|
||||
id: "rea-pe-load-config",
|
||||
name: "REA PE TLS/load-config parser",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
MACHO_FUNCTION_STARTS_ENTRY_BUDGET,
|
||||
inspectMachoFunctionStartsInputSchema,
|
||||
machoFunctionStartsEntryLimit,
|
||||
machoFunctionStartsHasIssues,
|
||||
machoFunctionStartsSchema,
|
||||
type MachoFunctionStarts,
|
||||
} from "./machoFunctionStarts.js";
|
||||
|
||||
const absent = {
|
||||
status: "absent" as const,
|
||||
dataoff: null,
|
||||
datasize: null,
|
||||
file_offset: null,
|
||||
in_linkedit: null,
|
||||
};
|
||||
|
||||
const counters = {
|
||||
duplicate_commands: 0,
|
||||
mis_sized_commands: 0,
|
||||
outside_linkedit: 0,
|
||||
truncated_commands: 0,
|
||||
uleb_truncated: 0,
|
||||
uleb_overflow: 0,
|
||||
non_monotonic: 0,
|
||||
out_of_text: 0,
|
||||
missing_text_anchor: 0,
|
||||
text_not_at_header: 0,
|
||||
unterminated_starts: 0,
|
||||
trailing_nonzero: 0,
|
||||
data_trailing_bytes: 0,
|
||||
section_crossings: 0,
|
||||
unsorted_data: 0,
|
||||
unmapped_data: 0,
|
||||
zero_length_data: 0,
|
||||
};
|
||||
|
||||
const report = (): MachoFunctionStarts => ({
|
||||
artifact: {
|
||||
path: "/artifacts/program",
|
||||
sha256: "a".repeat(64),
|
||||
bytes: 32,
|
||||
},
|
||||
format: "macho",
|
||||
architecture: "arm64",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
function_starts: absent,
|
||||
data_in_code: absent,
|
||||
coverage: {
|
||||
status: "complete",
|
||||
total_starts: 0,
|
||||
total_data_in_code: 0,
|
||||
...counters,
|
||||
},
|
||||
page: {
|
||||
kind: "all",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
returned_starts: 0,
|
||||
total_starts: 0,
|
||||
next_starts_offset: null,
|
||||
returned_data: 0,
|
||||
total_data: 0,
|
||||
next_data_offset: null,
|
||||
},
|
||||
starts: [],
|
||||
data_in_code_entries: [],
|
||||
limitations: ["observed"],
|
||||
});
|
||||
|
||||
it("defaults the per-call entry budget, page and read allowance", () => {
|
||||
expect(
|
||||
inspectMachoFunctionStartsInputSchema.parse({
|
||||
path: "/artifacts/program",
|
||||
}),
|
||||
).toMatchObject({
|
||||
max_entries: MACHO_FUNCTION_STARTS_ENTRY_BUDGET.default_value,
|
||||
max_file_bytes: 67_108_864,
|
||||
kind: "all",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
});
|
||||
expect(machoFunctionStartsEntryLimit(5)).toEqual({
|
||||
control_kind: "parameter",
|
||||
parameter: "max_entries",
|
||||
effective_value: 5,
|
||||
unit: "count",
|
||||
minimum: 1,
|
||||
maximum: 16_777_216,
|
||||
default_value: 2_097_152,
|
||||
applies_at: "next_call",
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a quiet report and rejects a start address that is not hex", () => {
|
||||
const value = report();
|
||||
expect(machoFunctionStartsHasIssues(value.coverage)).toBe(false);
|
||||
expect(
|
||||
machoFunctionStartsHasIssues({ ...value.coverage, out_of_text: 1 }),
|
||||
).toBe(true);
|
||||
expect(machoFunctionStartsSchema.parse(value)).toEqual(value);
|
||||
expect(
|
||||
machoFunctionStartsSchema.safeParse({
|
||||
...value,
|
||||
starts: [{ index: 0, vmaddr: "1000", section: "__text", issues: [] }],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,297 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
machoSliceArchitectureSchema,
|
||||
machoTargetSelectionSchema,
|
||||
} from "../apple/machoTargetSelection.js";
|
||||
import { BINARY_ARCHITECTURES } from "../binaryTargetTypes.js";
|
||||
import { knownCoverageStatusSchema } from "../coverage.js";
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { absoluteLocalPathStringSchema } from "../localPath.js";
|
||||
import type { AnalysisParameterLimit } from "../analysisSettings.js";
|
||||
import { maxStructureBytesSchema } from "./nativeStructureBudget.js";
|
||||
import {
|
||||
parameterBudgetLimit,
|
||||
parameterBudgetSchema,
|
||||
type ParameterBudget,
|
||||
} from "../parameterBudget.js";
|
||||
|
||||
const uint = z.number().int().min(0).max(0xffffffff);
|
||||
const hexAddress = z.string().regex(/^0x[0-9a-f]+$/u);
|
||||
|
||||
/**
|
||||
* Whole-file identity ceiling. `LC_FUNCTION_STARTS` and `LC_DATA_IN_CODE`
|
||||
* `dataoff` fields, and FAT32 slice offsets, are 32-bit. FAT64 files larger
|
||||
* than 4 GiB are outside this reader. `max_file_bytes` does not raise it.
|
||||
*/
|
||||
export const MACHO_FUNCTION_STARTS_FILE_CEILING_BYTES = 0xffffffff;
|
||||
/** Hard ceiling on the caller-selected input read budget. */
|
||||
export const MAX_INSPECT_MACHO_FUNCTION_STARTS_FILE_BYTES = 536870912;
|
||||
/** Hard ceiling on one returned page of either table. */
|
||||
export const MAX_INSPECT_MACHO_FUNCTION_STARTS_PAGE = 4096;
|
||||
|
||||
/**
|
||||
* Limitation texts the parser emits and the application layer checks for.
|
||||
* One owner keeps the producer and the report validation in step.
|
||||
*/
|
||||
export const MACHO_FUNCTION_STARTS_LIMITATIONS = {
|
||||
missingStarts:
|
||||
"A missing LC_FUNCTION_STARTS does not prove the image has no function starts.",
|
||||
missingData:
|
||||
"A missing LC_DATA_IN_CODE does not prove those bytes are instructions.",
|
||||
static: "This reader does not disassemble and does not execute the image.",
|
||||
duplicateStarts:
|
||||
"LC_FUNCTION_STARTS is declared more than once; the first command was decoded.",
|
||||
duplicateData:
|
||||
"LC_DATA_IN_CODE is declared more than once; the first command was decoded.",
|
||||
outsideStarts: "LC_FUNCTION_STARTS data is not in the __LINKEDIT segment.",
|
||||
outsideData: "LC_DATA_IN_CODE data is not in the __LINKEDIT segment.",
|
||||
misSizedStarts: "LC_FUNCTION_STARTS cmdsize is not 16.",
|
||||
misSizedData: "LC_DATA_IN_CODE cmdsize is not 16.",
|
||||
ulebTruncated: "LC_FUNCTION_STARTS ended inside a ULEB128 delta.",
|
||||
ulebOverflow: "LC_FUNCTION_STARTS ULEB128 delta does not fit in 64 bits.",
|
||||
wrapped: "LC_FUNCTION_STARTS address wrapped; later deltas were not decoded.",
|
||||
outOfText:
|
||||
"A function start is outside every executable segment; later deltas were not decoded.",
|
||||
missingText: "LC_FUNCTION_STARTS has no __TEXT segment to anchor its deltas.",
|
||||
textNotAtHeader:
|
||||
"The mach_header is not mapped at the __TEXT vmaddr. Starts are anchored on that vmaddr, as llvm-objdump does; dyld adds the deltas to the mach_header address, which differs here or is unknown.",
|
||||
trailing: "Bytes after the LC_FUNCTION_STARTS terminator are not zero.",
|
||||
startsPastFile:
|
||||
"LC_FUNCTION_STARTS extends past the file; only in-file bytes were decoded.",
|
||||
dataPastFile:
|
||||
"LC_DATA_IN_CODE extends past the file; only complete in-file entries were decoded.",
|
||||
dataTrailing:
|
||||
"LC_DATA_IN_CODE has trailing bytes shorter than one 8-byte entry.",
|
||||
crosses: "A data-in-code entry is not contained in one section.",
|
||||
unsorted: "data-in-code offsets are not strictly increasing.",
|
||||
zeroLength: "A data-in-code entry has length 0.",
|
||||
unmapped:
|
||||
"A data-in-code entry has no VM address: the mach_header address its offset is relative to is unknown, or the address is outside every segment.",
|
||||
unterminated:
|
||||
"LC_FUNCTION_STARTS ends without its zero terminator; the list may be cut off.",
|
||||
} as const;
|
||||
|
||||
/** `max_entries` of `inspect_macho_function_starts`: decoded starts plus data-in-code entries. */
|
||||
export const MACHO_FUNCTION_STARTS_ENTRY_BUDGET = {
|
||||
minimum: 1,
|
||||
maximum: 16_777_216,
|
||||
default_value: 2_097_152,
|
||||
unit: "count",
|
||||
} as const satisfies ParameterBudget;
|
||||
|
||||
/** The `max_entries` control that stopped a function-start decode. */
|
||||
export const machoFunctionStartsEntryLimit = (
|
||||
effectiveValue: number,
|
||||
): AnalysisParameterLimit =>
|
||||
parameterBudgetLimit(
|
||||
"max_entries",
|
||||
MACHO_FUNCTION_STARTS_ENTRY_BUDGET,
|
||||
effectiveValue,
|
||||
);
|
||||
|
||||
export const inspectMachoFunctionStartsInputSchema = z.strictObject({
|
||||
path: absoluteLocalPathStringSchema.describe(
|
||||
"Absolute filesystem path to a thin or universal Mach-O image",
|
||||
),
|
||||
architecture: machoSliceArchitectureSchema.optional(),
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(64)
|
||||
.max(MAX_INSPECT_MACHO_FUNCTION_STARTS_FILE_BYTES)
|
||||
.default(67108864)
|
||||
.describe(
|
||||
"Maximum bytes this reader reads from the artifact: headers, load commands and the LINKEDIT ranges they reference (default 64 MiB). The file may be larger; its one hashing pass is not counted",
|
||||
),
|
||||
max_structure_bytes: maxStructureBytesSchema,
|
||||
max_entries: parameterBudgetSchema(
|
||||
MACHO_FUNCTION_STARTS_ENTRY_BUDGET,
|
||||
).describe(
|
||||
"Maximum function starts plus data-in-code entries to decode (default 2097152); a larger pair of tables fails without partial success",
|
||||
),
|
||||
kind: z
|
||||
.enum(["all", "starts", "data"])
|
||||
.default("all")
|
||||
.describe(
|
||||
"Return both tables, only function starts, or only data-in-code entries; counts always cover every entry",
|
||||
),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(0xffffffff)
|
||||
.default(0)
|
||||
.describe("Zero-based index into each selected table"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(MAX_INSPECT_MACHO_FUNCTION_STARTS_PAGE)
|
||||
.default(64)
|
||||
.describe(
|
||||
"Maximum entries to return from each selected table; 0 returns counts only",
|
||||
),
|
||||
});
|
||||
export type InspectMachoFunctionStartsInput = z.infer<
|
||||
typeof inspectMachoFunctionStartsInputSchema
|
||||
>;
|
||||
|
||||
/**
|
||||
* `data_in_code_entry.kind` values named in <mach-o/loader.h>
|
||||
* (`DICE_KIND_DATA` through `DICE_KIND_ABS_JUMP_TABLE32`), the same five that
|
||||
* dyld's `mach_o::DataInCode` accepts. Any other value is reported as its
|
||||
* number. The reader, the schema and the report check share this table.
|
||||
*/
|
||||
export const MACHO_DICE_KIND_NAMES = {
|
||||
1: "DICE_KIND_DATA",
|
||||
2: "JUMP_TABLE8",
|
||||
3: "JUMP_TABLE16",
|
||||
4: "JUMP_TABLE32",
|
||||
5: "ABS_JUMP_TABLE32",
|
||||
} as const;
|
||||
const DICE_KINDS = Object.values(MACHO_DICE_KIND_NAMES) as [
|
||||
(typeof MACHO_DICE_KIND_NAMES)[keyof typeof MACHO_DICE_KIND_NAMES],
|
||||
...(typeof MACHO_DICE_KIND_NAMES)[keyof typeof MACHO_DICE_KIND_NAMES][],
|
||||
];
|
||||
|
||||
/** The reported `kind` of one raw `data_in_code_entry.kind`. */
|
||||
export const machoDataInCodeKind = (raw: number): MachoDataInCode["kind"] =>
|
||||
Object.hasOwn(MACHO_DICE_KIND_NAMES, raw)
|
||||
? MACHO_DICE_KIND_NAMES[raw as keyof typeof MACHO_DICE_KIND_NAMES]
|
||||
: raw;
|
||||
|
||||
const startIssueSchema = z.enum(["wrapped", "out_of_text"]);
|
||||
const dataIssueSchema = z.enum([
|
||||
"crosses_section",
|
||||
"zero_length",
|
||||
"unmapped",
|
||||
"out_of_order",
|
||||
]);
|
||||
|
||||
/** An observed section name, which may be empty (an all-zero `sectname`). */
|
||||
const sectionNameSchema = z.string().nullable();
|
||||
|
||||
export const machoFunctionStartSchema = z.strictObject({
|
||||
index: uint,
|
||||
/** Code address. On 32-bit ARM the Thumb tag in bit 0 is cleared here. */
|
||||
vmaddr: hexAddress,
|
||||
/**
|
||||
* 32-bit ARM only: bit 0 of the encoded start was set, marking Thumb code.
|
||||
* Other architectures omit it, because their starts carry no ISA tag.
|
||||
*/
|
||||
thumb: z.boolean().optional(),
|
||||
section: sectionNameSchema,
|
||||
issues: z.array(startIssueSchema),
|
||||
});
|
||||
export type MachoFunctionStart = z.infer<typeof machoFunctionStartSchema>;
|
||||
|
||||
const ownerSchema = z.strictObject({
|
||||
index: uint,
|
||||
vmaddr: hexAddress,
|
||||
});
|
||||
|
||||
export const machoDataInCodeSchema = z.strictObject({
|
||||
index: uint,
|
||||
/**
|
||||
* `data_in_code_entry.offset`, relative to the mach_header's address: ld64
|
||||
* writes the entry's address minus that address. For MH_OBJECT, whose
|
||||
* header is not mapped, it is the address itself.
|
||||
*/
|
||||
offset: uint,
|
||||
vmaddr: hexAddress.nullable(),
|
||||
length: z.number().int().min(0).max(0xffff),
|
||||
kind: z.union([z.enum(DICE_KINDS), z.number().int().min(0).max(0xffff)]),
|
||||
section: sectionNameSchema,
|
||||
/** Greatest decoded start at or before `vmaddr`, or null when none applies. */
|
||||
owner: ownerSchema.nullable(),
|
||||
issues: z.array(dataIssueSchema),
|
||||
});
|
||||
export type MachoDataInCode = z.infer<typeof machoDataInCodeSchema>;
|
||||
|
||||
const commandSchema = z.strictObject({
|
||||
status: z.enum(["present", "absent"]),
|
||||
dataoff: uint.nullable(),
|
||||
datasize: uint.nullable(),
|
||||
/** Container file offset of `dataoff`, or null when the command is absent. */
|
||||
file_offset: uint.nullable(),
|
||||
in_linkedit: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
export const machoFunctionStartsSchema = z.strictObject({
|
||||
artifact: z.strictObject({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
bytes: uint,
|
||||
}),
|
||||
format: z.literal("macho"),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
bits: z.union([z.literal(32), z.literal(64)]),
|
||||
byte_order: z.enum(["little", "big"]),
|
||||
/** Present only for a universal file. A thin image omits it. */
|
||||
selected_slice: machoTargetSelectionSchema.optional(),
|
||||
function_starts: commandSchema,
|
||||
data_in_code: commandSchema,
|
||||
coverage: z.strictObject({
|
||||
status: knownCoverageStatusSchema,
|
||||
total_starts: uint,
|
||||
total_data_in_code: uint,
|
||||
duplicate_commands: uint,
|
||||
mis_sized_commands: uint,
|
||||
outside_linkedit: uint,
|
||||
truncated_commands: uint,
|
||||
uleb_truncated: uint,
|
||||
uleb_overflow: uint,
|
||||
non_monotonic: uint,
|
||||
out_of_text: uint,
|
||||
missing_text_anchor: uint,
|
||||
/** 1 when __TEXT does not map file offset 0, so the delta base is disputed. */
|
||||
text_not_at_header: uint,
|
||||
/** 1 when the table ends after a delta without its zero terminator. */
|
||||
unterminated_starts: uint,
|
||||
trailing_nonzero: uint,
|
||||
data_trailing_bytes: uint,
|
||||
section_crossings: uint,
|
||||
unsorted_data: uint,
|
||||
unmapped_data: uint,
|
||||
zero_length_data: uint,
|
||||
}),
|
||||
page: z.strictObject({
|
||||
kind: z.enum(["all", "starts", "data"]),
|
||||
offset: uint,
|
||||
limit: uint,
|
||||
returned_starts: uint,
|
||||
total_starts: uint,
|
||||
next_starts_offset: uint.nullable(),
|
||||
returned_data: uint,
|
||||
total_data: uint,
|
||||
next_data_offset: uint.nullable(),
|
||||
}),
|
||||
starts: z.array(machoFunctionStartSchema),
|
||||
data_in_code_entries: z.array(machoDataInCodeSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
});
|
||||
export type MachoFunctionStarts = z.infer<typeof machoFunctionStartsSchema>;
|
||||
|
||||
/** Whether any decoded-table problem made coverage partial. */
|
||||
export const machoFunctionStartsHasIssues = (
|
||||
coverage: MachoFunctionStarts["coverage"],
|
||||
): boolean =>
|
||||
coverage.duplicate_commands +
|
||||
coverage.mis_sized_commands +
|
||||
coverage.outside_linkedit +
|
||||
coverage.truncated_commands +
|
||||
coverage.uleb_truncated +
|
||||
coverage.uleb_overflow +
|
||||
coverage.non_monotonic +
|
||||
coverage.out_of_text +
|
||||
coverage.missing_text_anchor +
|
||||
coverage.text_not_at_header +
|
||||
coverage.unterminated_starts +
|
||||
coverage.trailing_nonzero +
|
||||
coverage.data_trailing_bytes +
|
||||
coverage.section_crossings +
|
||||
coverage.unsorted_data +
|
||||
coverage.unmapped_data +
|
||||
coverage.zero_length_data >
|
||||
0;
|
||||
@@ -550,6 +550,8 @@ it("indexes 25,000 Mach-O load regions and sections without quadratic stalls and
|
||||
const container: BinaryContainer = {
|
||||
format: "macho",
|
||||
macho_cpu_type: 0x0100000c,
|
||||
macho_file_type: 2,
|
||||
macho_segments: [],
|
||||
architecture: "arm64",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
@@ -712,6 +714,8 @@ it.each([
|
||||
const container: BinaryContainer = {
|
||||
format: "macho",
|
||||
macho_cpu_type: 0x0100000c,
|
||||
macho_file_type: 2,
|
||||
macho_segments: [],
|
||||
architecture: "arm64",
|
||||
bits: 64,
|
||||
byte_order: "little",
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
indexCoveredRanges,
|
||||
indexFileOffsets,
|
||||
indexSmallestSections,
|
||||
lookupInterval,
|
||||
type SectionSpan,
|
||||
} from "./MachoAddressIndex.js";
|
||||
|
||||
const span = (name: string, address: bigint, size: bigint): SectionSpan => ({
|
||||
name,
|
||||
address,
|
||||
size,
|
||||
});
|
||||
|
||||
/** The linear scan the index replaces: smallest wins, first declared on ties. */
|
||||
const scanSmallest = (
|
||||
sections: readonly SectionSpan[],
|
||||
address: bigint,
|
||||
): string | null => {
|
||||
let best: SectionSpan | null = null;
|
||||
for (const section of sections) {
|
||||
if (address < section.address || address >= section.address + section.size)
|
||||
continue;
|
||||
if (best === null || section.size < best.size) best = section;
|
||||
}
|
||||
return best?.name ?? null;
|
||||
};
|
||||
|
||||
describe("indexSmallestSections", () => {
|
||||
it("matches a linear scan over nested, overlapping, tied and empty sections", () => {
|
||||
const sections = [
|
||||
span("outer", 0x1000n, 0x1000n),
|
||||
span("inner", 0x1200n, 0x100n),
|
||||
span("overlap", 0x1280n, 0x200n),
|
||||
span("tie-first", 0x3000n, 0x10n),
|
||||
span("tie-second", 0x3000n, 0x10n),
|
||||
span("empty", 0x1250n, 0n),
|
||||
span("later-smaller", 0x1290n, 0x8n),
|
||||
];
|
||||
const index = indexSmallestSections(sections);
|
||||
for (let address = 0xff0n; address < 0x3020n; address += 1n) {
|
||||
expect(
|
||||
lookupInterval(index, address)?.name ?? null,
|
||||
`0x${address.toString(16)}`,
|
||||
).toBe(scanSmallest(sections, address));
|
||||
}
|
||||
});
|
||||
|
||||
it("returns nothing when no section is declared", () => {
|
||||
expect(lookupInterval(indexSmallestSections([]), 0n)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("indexFileOffsets", () => {
|
||||
it("translates offsets and treats conflicting translations as ambiguous", () => {
|
||||
const index = indexFileOffsets([
|
||||
{ address: 0x100000000n, offset: 0, size: 0x4000 },
|
||||
{ address: 0x100008000n, offset: 0x4000, size: 0x1000 },
|
||||
{ address: 0x200000000n, offset: 0x4800, size: 0x1000 },
|
||||
{ address: 0x100004000n, offset: 0x4000, size: 0 },
|
||||
]);
|
||||
const at = (offset: number): bigint | null => {
|
||||
const delta = lookupInterval(index, BigInt(offset));
|
||||
return delta === undefined || delta === null
|
||||
? null
|
||||
: BigInt(offset) + delta;
|
||||
};
|
||||
expect(at(0x10)).toBe(0x100000010n);
|
||||
expect(at(0x4100)).toBe(0x100008100n);
|
||||
expect(at(0x4900)).toBeNull();
|
||||
expect(at(0x5700)).toBe(0x200000f00n);
|
||||
expect(at(0x6000)).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps one translation when identical mappings overlap", () => {
|
||||
const index = indexFileOffsets([
|
||||
{ address: 0x1000n, offset: 0, size: 0x100 },
|
||||
{ address: 0x1080n, offset: 0x80, size: 0x100 },
|
||||
]);
|
||||
expect(lookupInterval(index, 0x90n)).toBe(0x1000n);
|
||||
});
|
||||
});
|
||||
|
||||
describe("indexCoveredRanges", () => {
|
||||
it("matches a linear scan over overlapping, adjacent, empty and disjoint ranges", () => {
|
||||
const ranges = [
|
||||
{ address: 0x1000n, size: 0x100n },
|
||||
{ address: 0x1080n, size: 0x100n },
|
||||
{ address: 0x1180n, size: 0x80n },
|
||||
{ address: 0x2000n, size: 0n },
|
||||
{ address: 0x3000n, size: 0x10n },
|
||||
];
|
||||
const index = indexCoveredRanges(ranges);
|
||||
for (let point = 0xf00n; point < 0x3100n; point += 0x8n) {
|
||||
const scanned = ranges.some(
|
||||
(range) => point >= range.address && point < range.address + range.size,
|
||||
);
|
||||
expect(
|
||||
lookupInterval(index, point) === true,
|
||||
`0x${point.toString(16)}`,
|
||||
).toBe(scanned);
|
||||
}
|
||||
expect(indexCoveredRanges([])).toEqual({ bounds: [], values: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,189 @@
|
||||
import type { FileMapping } from "../../domain/virtualFileMapping.js";
|
||||
import { lastAtOrBelow } from "../../domain/virtualFileMapping.js";
|
||||
|
||||
/** A section's VM span, as the function-starts parser reports it. */
|
||||
export interface SectionSpan {
|
||||
readonly name: string;
|
||||
readonly address: bigint;
|
||||
readonly size: bigint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disjoint intervals keyed by their sorted start points. `values[k]` covers
|
||||
* `[bounds[k], bounds[k + 1])`, so a lookup is one binary search instead of a
|
||||
* scan of every declared span.
|
||||
*/
|
||||
export interface IntervalIndex<Value> {
|
||||
readonly bounds: readonly bigint[];
|
||||
readonly values: readonly Value[];
|
||||
}
|
||||
|
||||
export const lookupInterval = <Value>(
|
||||
index: IntervalIndex<Value>,
|
||||
point: bigint,
|
||||
): Value | undefined => {
|
||||
const at = lastAtOrBelow(index.bounds, point);
|
||||
return at < 0 || at >= index.values.length ? undefined : index.values[at];
|
||||
};
|
||||
|
||||
const uniqueSorted = (points: readonly bigint[]): bigint[] => {
|
||||
const sorted = [...points].sort((left, right) =>
|
||||
left < right ? -1 : left > right ? 1 : 0,
|
||||
);
|
||||
return sorted.filter(
|
||||
(point, index) => index === 0 || point !== sorted[index - 1],
|
||||
);
|
||||
};
|
||||
|
||||
/** Min-heap order: smallest size, then the earliest declared section. */
|
||||
const sectionBefore = (
|
||||
left: { readonly section: SectionSpan; readonly order: number },
|
||||
right: { readonly section: SectionSpan; readonly order: number },
|
||||
): boolean =>
|
||||
left.section.size < right.section.size ||
|
||||
(left.section.size === right.section.size && left.order < right.order);
|
||||
|
||||
/**
|
||||
* Index the smallest section that contains each address. Overlapping
|
||||
* sections resolve the way a scan would: the smallest wins and the first
|
||||
* declared breaks a tie. A sweep with a lazily pruned min-heap builds it in
|
||||
* O(n log n).
|
||||
*/
|
||||
export const indexSmallestSections = (
|
||||
sections: readonly SectionSpan[],
|
||||
): IntervalIndex<SectionSpan | null> => {
|
||||
const spans = sections
|
||||
.map((section, order) => ({ section, order }))
|
||||
.filter((span) => span.section.size > 0n)
|
||||
.sort((left, right) =>
|
||||
left.section.address < right.section.address
|
||||
? -1
|
||||
: left.section.address > right.section.address
|
||||
? 1
|
||||
: left.order - right.order,
|
||||
);
|
||||
const bounds = uniqueSorted(
|
||||
spans.flatMap((span) => [
|
||||
span.section.address,
|
||||
span.section.address + span.section.size,
|
||||
]),
|
||||
);
|
||||
const heap: (typeof spans)[number][] = [];
|
||||
const push = (item: (typeof spans)[number]): void => {
|
||||
heap.push(item);
|
||||
let at = heap.length - 1;
|
||||
while (at > 0) {
|
||||
const parent = (at - 1) >> 1;
|
||||
if (!sectionBefore(heap[at]!, heap[parent]!)) break;
|
||||
[heap[at], heap[parent]] = [heap[parent]!, heap[at]!];
|
||||
at = parent;
|
||||
}
|
||||
};
|
||||
const pop = (): void => {
|
||||
const last = heap.pop();
|
||||
if (last === undefined || heap.length === 0) return;
|
||||
heap[0] = last;
|
||||
let at = 0;
|
||||
for (;;) {
|
||||
const left = at * 2 + 1;
|
||||
const right = left + 1;
|
||||
let best = at;
|
||||
if (left < heap.length && sectionBefore(heap[left]!, heap[best]!))
|
||||
best = left;
|
||||
if (right < heap.length && sectionBefore(heap[right]!, heap[best]!))
|
||||
best = right;
|
||||
if (best === at) return;
|
||||
[heap[at], heap[best]] = [heap[best]!, heap[at]!];
|
||||
at = best;
|
||||
}
|
||||
};
|
||||
const values: (SectionSpan | null)[] = [];
|
||||
let next = 0;
|
||||
for (let index = 0; index + 1 < bounds.length; index += 1) {
|
||||
const point = bounds[index] as bigint;
|
||||
while (next < spans.length && spans[next]!.section.address <= point) {
|
||||
push(spans[next]!);
|
||||
next += 1;
|
||||
}
|
||||
while (
|
||||
heap.length > 0 &&
|
||||
heap[0]!.section.address + heap[0]!.section.size <= point
|
||||
)
|
||||
pop();
|
||||
values.push(heap[0]?.section ?? null);
|
||||
}
|
||||
return { bounds, values };
|
||||
};
|
||||
|
||||
/**
|
||||
* Index each file offset's VM translation (`address - offset`). An interval
|
||||
* that more than one distinct translation covers is ambiguous and stored as
|
||||
* `null`, so the lookup reports it unmapped.
|
||||
*/
|
||||
export const indexFileOffsets = (
|
||||
mappings: readonly FileMapping[],
|
||||
): IntervalIndex<bigint | null> => {
|
||||
const events = mappings
|
||||
.filter((mapping) => mapping.size > 0)
|
||||
.flatMap((mapping) => {
|
||||
const start = BigInt(mapping.offset);
|
||||
const delta = mapping.address - start;
|
||||
return [
|
||||
{ point: start, delta, step: 1 },
|
||||
{ point: start + BigInt(mapping.size), delta, step: -1 },
|
||||
];
|
||||
})
|
||||
.sort((left, right) =>
|
||||
left.point < right.point ? -1 : left.point > right.point ? 1 : 0,
|
||||
);
|
||||
const bounds = uniqueSorted(events.map((event) => event.point));
|
||||
const active = new Map<bigint, number>();
|
||||
const values: (bigint | null)[] = [];
|
||||
let next = 0;
|
||||
for (let index = 0; index + 1 < bounds.length; index += 1) {
|
||||
const point = bounds[index] as bigint;
|
||||
while (next < events.length && events[next]!.point === point) {
|
||||
const event = events[next]!;
|
||||
const count = (active.get(event.delta) ?? 0) + event.step;
|
||||
if (count === 0) active.delete(event.delta);
|
||||
else active.set(event.delta, count);
|
||||
next += 1;
|
||||
}
|
||||
values.push(
|
||||
active.size === 1 ? (active.keys().next().value as bigint) : null,
|
||||
);
|
||||
}
|
||||
return { bounds, values };
|
||||
};
|
||||
|
||||
/**
|
||||
* Index which addresses at least one of `ranges` covers. Overlaps and
|
||||
* adjacent ranges merge, and a lookup is one binary search, so a caller
|
||||
* checking many addresses does not scan every range for each one.
|
||||
*/
|
||||
export const indexCoveredRanges = (
|
||||
ranges: readonly { readonly address: bigint; readonly size: bigint }[],
|
||||
): IntervalIndex<boolean> => {
|
||||
const events = ranges
|
||||
.filter((range) => range.size > 0n)
|
||||
.flatMap((range) => [
|
||||
{ point: range.address, step: 1 },
|
||||
{ point: range.address + range.size, step: -1 },
|
||||
])
|
||||
.sort((left, right) =>
|
||||
left.point < right.point ? -1 : left.point > right.point ? 1 : 0,
|
||||
);
|
||||
const bounds = uniqueSorted(events.map((event) => event.point));
|
||||
const values: boolean[] = [];
|
||||
let depth = 0;
|
||||
let next = 0;
|
||||
for (let index = 0; index + 1 < bounds.length; index += 1) {
|
||||
const point = bounds[index] as bigint;
|
||||
while (next < events.length && events[next]!.point === point) {
|
||||
depth += events[next]!.step;
|
||||
next += 1;
|
||||
}
|
||||
values.push(depth > 0);
|
||||
}
|
||||
return { bounds, values };
|
||||
};
|
||||
@@ -0,0 +1,475 @@
|
||||
/** Synthetic little-endian Mach-O images for function-start tests. No vendor bytes. */
|
||||
|
||||
export const MACHO_TEXT_BASE = 0x100000000n;
|
||||
export const MACHO_FUNCTION_STARTS_FILE_BYTES = 0x5000;
|
||||
const LINKEDIT_OFFSET = 0x4000;
|
||||
const TEXT_VM_SIZE = 0x4000;
|
||||
|
||||
const CPU = {
|
||||
arm64: { type: 0x0100000c, subtype: 0 },
|
||||
x86_64: { type: 0x01000007, subtype: 3 },
|
||||
} as const;
|
||||
|
||||
export type MachoFunctionStartsCpu = keyof typeof CPU;
|
||||
|
||||
export interface MachoLinkeditDuplicateCommand {
|
||||
readonly offset?: number;
|
||||
readonly declaredSize?: number;
|
||||
readonly commandSize?: number;
|
||||
}
|
||||
|
||||
export interface MachoFunctionStartBlob {
|
||||
readonly deltas?: readonly bigint[];
|
||||
readonly blob?: Buffer;
|
||||
/** Include the zero terminator. Default true. Ignored when `blob` is set. */
|
||||
readonly terminator?: boolean;
|
||||
readonly padding?: number;
|
||||
/** One nonzero byte after the terminator and padding. */
|
||||
readonly trailingByte?: number;
|
||||
/** Slice file offset of the payload. Default: start of __LINKEDIT. */
|
||||
readonly offset?: number;
|
||||
/** Declared datasize. Default: the payload length. */
|
||||
readonly declaredSize?: number;
|
||||
/** linkedit_data_command cmdsize. Default 16. */
|
||||
readonly commandSize?: number;
|
||||
readonly duplicate?: boolean | MachoLinkeditDuplicateCommand;
|
||||
}
|
||||
|
||||
export interface MachoDataInCodeBlob {
|
||||
readonly entries?: readonly {
|
||||
readonly offset: number;
|
||||
readonly length: number;
|
||||
readonly kind: number;
|
||||
}[];
|
||||
readonly blob?: Buffer;
|
||||
readonly trailing?: number;
|
||||
readonly offset?: number;
|
||||
readonly declaredSize?: number;
|
||||
readonly commandSize?: number;
|
||||
readonly duplicate?: boolean | MachoLinkeditDuplicateCommand;
|
||||
}
|
||||
|
||||
export interface MachoFunctionStartsImageOptions {
|
||||
readonly cpu?: MachoFunctionStartsCpu;
|
||||
readonly starts?: MachoFunctionStartBlob;
|
||||
readonly data?: MachoDataInCodeBlob;
|
||||
readonly omitText?: boolean;
|
||||
readonly omitLinkedit?: boolean;
|
||||
/** __TEXT filesize. Default equals its vmsize, so the segment covers its file bytes. */
|
||||
readonly textFileSize?: number;
|
||||
/** __TEXT segment `flags`, such as SG_HIGHVM (0x1). Default 0. */
|
||||
readonly textFlags?: number;
|
||||
/** `mach_header.filetype`. Default MH_EXECUTE (2). */
|
||||
readonly fileType?: number;
|
||||
/** `sectname` of the code section. Default `__text`; "" writes all zeros. */
|
||||
readonly textSectionName?: string;
|
||||
/** Segments appended after __LINKEDIT, such as one aliasing __TEXT file bytes. */
|
||||
readonly extraSegments?: readonly {
|
||||
readonly name: string;
|
||||
readonly address: bigint;
|
||||
readonly memorySize: number;
|
||||
readonly fileOffset: number;
|
||||
readonly fileSize: number;
|
||||
readonly protection: number;
|
||||
}[];
|
||||
/** Total file bytes. Default `MACHO_FUNCTION_STARTS_FILE_BYTES`. */
|
||||
readonly fileBytes?: number;
|
||||
}
|
||||
|
||||
/** ULEB128 used by LC_FUNCTION_STARTS. The high bit continues the integer. */
|
||||
export const encodeUleb = (value: bigint): Buffer => {
|
||||
const bytes: number[] = [];
|
||||
let rest = value;
|
||||
do {
|
||||
let byte = Number(rest & 0x7fn);
|
||||
rest >>= 7n;
|
||||
if (rest !== 0n) byte |= 0x80;
|
||||
bytes.push(byte);
|
||||
} while (rest !== 0n);
|
||||
return Buffer.from(bytes);
|
||||
};
|
||||
|
||||
/** Absolute VM addresses of `deltas` added to the __TEXT vmaddr. */
|
||||
export const functionStartAddresses = (
|
||||
deltas: readonly bigint[],
|
||||
base = MACHO_TEXT_BASE,
|
||||
): readonly bigint[] => {
|
||||
const addresses: bigint[] = [];
|
||||
let cursor = base;
|
||||
for (const delta of deltas) {
|
||||
cursor += delta;
|
||||
addresses.push(cursor);
|
||||
}
|
||||
return addresses;
|
||||
};
|
||||
|
||||
const encodeStarts = (starts: MachoFunctionStartBlob): Buffer => {
|
||||
if (starts.blob !== undefined) return starts.blob;
|
||||
const parts = (starts.deltas ?? []).map((delta) => encodeUleb(delta));
|
||||
if (starts.terminator !== false) parts.push(Buffer.from([0]));
|
||||
if ((starts.padding ?? 0) > 0) parts.push(Buffer.alloc(starts.padding ?? 0));
|
||||
if (starts.trailingByte !== undefined)
|
||||
parts.push(Buffer.from([starts.trailingByte]));
|
||||
return Buffer.concat(parts);
|
||||
};
|
||||
|
||||
const encodeData = (data: MachoDataInCodeBlob): Buffer => {
|
||||
if (data.blob !== undefined) return data.blob;
|
||||
const entries = data.entries ?? [];
|
||||
const trailing = data.trailing ?? 0;
|
||||
const bytes = Buffer.alloc(entries.length * 8 + trailing);
|
||||
for (const [index, entry] of entries.entries()) {
|
||||
const at = index * 8;
|
||||
bytes.writeUInt32LE(entry.offset, at);
|
||||
bytes.writeUInt16LE(entry.length, at + 4);
|
||||
bytes.writeUInt16LE(entry.kind, at + 6);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const name16 = (text: string): Buffer => {
|
||||
const bytes = Buffer.alloc(16);
|
||||
bytes.write(text, 0, "utf8");
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const segment64 = (
|
||||
name: string,
|
||||
address: bigint,
|
||||
memorySize: number,
|
||||
fileOffset: number,
|
||||
fileSize: number,
|
||||
protection: number,
|
||||
sections: readonly Buffer[],
|
||||
flags = 0,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(72 + sections.length * 80);
|
||||
bytes.writeUInt32LE(0x19, 0);
|
||||
bytes.writeUInt32LE(bytes.length, 4);
|
||||
name16(name).copy(bytes, 8);
|
||||
bytes.writeBigUInt64LE(address, 24);
|
||||
bytes.writeBigUInt64LE(BigInt(memorySize), 32);
|
||||
bytes.writeBigUInt64LE(BigInt(fileOffset), 40);
|
||||
bytes.writeBigUInt64LE(BigInt(fileSize), 48);
|
||||
bytes.writeUInt32LE(protection, 56);
|
||||
bytes.writeUInt32LE(protection, 60);
|
||||
bytes.writeUInt32LE(sections.length, 64);
|
||||
bytes.writeUInt32LE(flags, 68);
|
||||
for (const [index, section] of sections.entries())
|
||||
section.copy(bytes, 72 + index * 80);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const section64 = (
|
||||
section: string,
|
||||
segment: string,
|
||||
address: bigint,
|
||||
size: number,
|
||||
offset: number,
|
||||
flags: number,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(80);
|
||||
name16(section).copy(bytes, 0);
|
||||
name16(segment).copy(bytes, 16);
|
||||
bytes.writeBigUInt64LE(address, 32);
|
||||
bytes.writeBigUInt64LE(BigInt(size), 40);
|
||||
bytes.writeUInt32LE(offset, 48);
|
||||
bytes.writeUInt32LE(flags, 64);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const linkeditCommand = (
|
||||
command: number,
|
||||
dataoff: number,
|
||||
datasize: number,
|
||||
size: number,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(size);
|
||||
bytes.writeUInt32LE(command, 0);
|
||||
bytes.writeUInt32LE(size, 4);
|
||||
if (size >= 12) bytes.writeUInt32LE(dataoff, 8);
|
||||
if (size >= 16) bytes.writeUInt32LE(datasize, 12);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
const place = (file: Buffer, offset: number, bytes: Buffer): void => {
|
||||
if (offset < 0 || offset + bytes.length > file.length)
|
||||
throw new Error(
|
||||
`fixture payload at ${offset} does not fit in ${file.length} bytes`,
|
||||
);
|
||||
bytes.copy(file, offset);
|
||||
};
|
||||
|
||||
const appendDuplicateCommand = (
|
||||
file: Buffer,
|
||||
commands: Buffer[],
|
||||
options: {
|
||||
readonly command: number;
|
||||
readonly duplicate: boolean | MachoLinkeditDuplicateCommand | undefined;
|
||||
readonly defaultOffset: number;
|
||||
readonly decoy: Buffer;
|
||||
},
|
||||
): void => {
|
||||
if (options.duplicate === undefined || options.duplicate === false) return;
|
||||
const spec = options.duplicate === true ? {} : options.duplicate;
|
||||
if (spec.offset === undefined)
|
||||
place(file, options.defaultOffset, options.decoy);
|
||||
commands.push(
|
||||
linkeditCommand(
|
||||
options.command,
|
||||
spec.offset ?? options.defaultOffset,
|
||||
spec.declaredSize ?? options.decoy.length,
|
||||
spec.commandSize ?? 16,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* One thin arm64 or x86_64 MH_EXECUTE image.
|
||||
*
|
||||
* __TEXT covers file 0..textFileSize at `MACHO_TEXT_BASE` and holds `__text`
|
||||
* then `__literal`. __LINKEDIT covers file 0x4000..0x5000. Payloads default
|
||||
* into __LINKEDIT.
|
||||
*/
|
||||
export const machoFunctionStartsImage = (
|
||||
options: MachoFunctionStartsImageOptions = {},
|
||||
): Buffer => {
|
||||
const file = Buffer.alloc(
|
||||
options.fileBytes ?? MACHO_FUNCTION_STARTS_FILE_BYTES,
|
||||
);
|
||||
const cpu = CPU[options.cpu ?? "arm64"];
|
||||
const textFileSize = options.textFileSize ?? TEXT_VM_SIZE;
|
||||
const commands: Buffer[] = [];
|
||||
if (options.omitText !== true) {
|
||||
commands.push(
|
||||
segment64(
|
||||
"__TEXT",
|
||||
MACHO_TEXT_BASE,
|
||||
TEXT_VM_SIZE,
|
||||
0,
|
||||
textFileSize,
|
||||
5,
|
||||
[
|
||||
section64(
|
||||
options.textSectionName ?? "__text",
|
||||
"__TEXT",
|
||||
MACHO_TEXT_BASE + 0x1000n,
|
||||
0x800,
|
||||
0x1000,
|
||||
0x80000400,
|
||||
),
|
||||
section64(
|
||||
"__literal",
|
||||
"__TEXT",
|
||||
MACHO_TEXT_BASE + 0x1800n,
|
||||
0x800,
|
||||
0x1800,
|
||||
0,
|
||||
),
|
||||
],
|
||||
options.textFlags ?? 0,
|
||||
),
|
||||
);
|
||||
}
|
||||
if (options.omitLinkedit !== true) {
|
||||
commands.push(
|
||||
segment64(
|
||||
"__LINKEDIT",
|
||||
MACHO_TEXT_BASE + BigInt(LINKEDIT_OFFSET),
|
||||
0x1000,
|
||||
LINKEDIT_OFFSET,
|
||||
0x1000,
|
||||
1,
|
||||
[],
|
||||
),
|
||||
);
|
||||
}
|
||||
for (const segment of options.extraSegments ?? [])
|
||||
commands.push(
|
||||
segment64(
|
||||
segment.name,
|
||||
segment.address,
|
||||
segment.memorySize,
|
||||
segment.fileOffset,
|
||||
segment.fileSize,
|
||||
segment.protection,
|
||||
[],
|
||||
),
|
||||
);
|
||||
if (options.starts !== undefined) {
|
||||
const payload = encodeStarts(options.starts);
|
||||
const offset = options.starts.offset ?? LINKEDIT_OFFSET;
|
||||
place(file, offset, payload);
|
||||
commands.push(
|
||||
linkeditCommand(
|
||||
0x26,
|
||||
offset,
|
||||
options.starts.declaredSize ?? payload.length,
|
||||
options.starts.commandSize ?? 16,
|
||||
),
|
||||
);
|
||||
appendDuplicateCommand(file, commands, {
|
||||
command: 0x26,
|
||||
duplicate: options.starts.duplicate,
|
||||
defaultOffset: 0x4400,
|
||||
decoy: Buffer.concat([encodeUleb(1n), Buffer.from([0])]),
|
||||
});
|
||||
}
|
||||
if (options.data !== undefined) {
|
||||
const payload = encodeData(options.data);
|
||||
const offset = options.data.offset ?? 0x4200;
|
||||
place(file, offset, payload);
|
||||
commands.push(
|
||||
linkeditCommand(
|
||||
0x29,
|
||||
offset,
|
||||
options.data.declaredSize ?? payload.length,
|
||||
options.data.commandSize ?? 16,
|
||||
),
|
||||
);
|
||||
appendDuplicateCommand(file, commands, {
|
||||
command: 0x29,
|
||||
duplicate: options.data.duplicate,
|
||||
defaultOffset: 0x4600,
|
||||
decoy: encodeData({
|
||||
entries: [{ offset: 0x10, length: 1, kind: 1 }],
|
||||
}),
|
||||
});
|
||||
}
|
||||
const commandBytes = Buffer.concat(commands);
|
||||
file.writeUInt32LE(0xfeedfacf, 0);
|
||||
file.writeUInt32LE(cpu.type, 4);
|
||||
file.writeUInt32LE(cpu.subtype, 8);
|
||||
file.writeUInt32LE(options.fileType ?? 2, 12);
|
||||
file.writeUInt32LE(commands.length, 16);
|
||||
file.writeUInt32LE(commandBytes.length, 20);
|
||||
commandBytes.copy(file, 32);
|
||||
return file;
|
||||
};
|
||||
|
||||
/** FAT32 file whose arm64 and x86_64 slices are the two thin images. */
|
||||
export const machoFunctionStartsUniversal = (
|
||||
arm64: Buffer,
|
||||
x86_64: Buffer,
|
||||
): Buffer => {
|
||||
const align = 0x1000;
|
||||
const armOffset = align;
|
||||
const x64Offset = align + Math.ceil(arm64.length / align) * align;
|
||||
const file = Buffer.alloc(x64Offset + x86_64.length);
|
||||
file.writeUInt32BE(0xcafebabe, 0);
|
||||
file.writeUInt32BE(2, 4);
|
||||
const arch = (
|
||||
at: number,
|
||||
cpu: number,
|
||||
offset: number,
|
||||
size: number,
|
||||
): void => {
|
||||
file.writeUInt32BE(cpu, at);
|
||||
file.writeUInt32BE(
|
||||
cpu === CPU.x86_64.type ? CPU.x86_64.subtype : 0,
|
||||
at + 4,
|
||||
);
|
||||
file.writeUInt32BE(offset, at + 8);
|
||||
file.writeUInt32BE(size, at + 12);
|
||||
file.writeUInt32BE(12, at + 16);
|
||||
};
|
||||
arch(8, CPU.arm64.type, armOffset, arm64.length);
|
||||
arch(28, CPU.x86_64.type, x64Offset, x86_64.length);
|
||||
arm64.copy(file, armOffset);
|
||||
x86_64.copy(file, x64Offset);
|
||||
return file;
|
||||
};
|
||||
|
||||
/** Three arm64 starts inside `__text`, and three in-section data entries. */
|
||||
export const ARM64_DELTAS = [0x1000n, 0x100n, 0x100n] as const;
|
||||
export const X64_DELTAS = [0x1000n, 0x200n] as const;
|
||||
|
||||
export const arm64FunctionStartsImage = (): Buffer =>
|
||||
machoFunctionStartsImage({
|
||||
cpu: "arm64",
|
||||
starts: { deltas: ARM64_DELTAS, padding: 4 },
|
||||
data: {
|
||||
entries: [
|
||||
{ offset: 0x1080, length: 8, kind: 1 },
|
||||
{ offset: 0x1120, length: 4, kind: 2 },
|
||||
{ offset: 0x1210, length: 4, kind: 0x42 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
export const x64FunctionStartsImage = (): Buffer =>
|
||||
machoFunctionStartsImage({
|
||||
cpu: "x86_64",
|
||||
starts: { deltas: X64_DELTAS },
|
||||
data: {
|
||||
entries: [
|
||||
{ offset: 0x1080, length: 2, kind: 3 },
|
||||
{ offset: 0x1220, length: 4, kind: 5 },
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
/** __TEXT vmaddr of the 32-bit ARM image. */
|
||||
export const MACHO_ARM32_TEXT_BASE = 0x1000;
|
||||
|
||||
const segment32 = (
|
||||
name: string,
|
||||
address: number,
|
||||
memorySize: number,
|
||||
fileOffset: number,
|
||||
fileSize: number,
|
||||
protection: number,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(56);
|
||||
bytes.writeUInt32LE(0x1, 0);
|
||||
bytes.writeUInt32LE(56, 4);
|
||||
name16(name).copy(bytes, 8);
|
||||
bytes.writeUInt32LE(address, 24);
|
||||
bytes.writeUInt32LE(memorySize, 28);
|
||||
bytes.writeUInt32LE(fileOffset, 32);
|
||||
bytes.writeUInt32LE(fileSize, 36);
|
||||
bytes.writeUInt32LE(protection, 40);
|
||||
bytes.writeUInt32LE(protection, 44);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Thin armv7 executable whose LC_FUNCTION_STARTS holds `deltas`. ld64 sets
|
||||
* bit 0 of a Thumb start before taking the next delta, so callers pass the
|
||||
* deltas between those tagged values.
|
||||
*/
|
||||
export const machoArm32FunctionStartsImage = (
|
||||
deltas: readonly bigint[],
|
||||
): Buffer => {
|
||||
const file = Buffer.alloc(MACHO_FUNCTION_STARTS_FILE_BYTES);
|
||||
const payload = encodeStarts({ deltas });
|
||||
place(file, LINKEDIT_OFFSET, payload);
|
||||
const commands = [
|
||||
segment32(
|
||||
"__TEXT",
|
||||
MACHO_ARM32_TEXT_BASE,
|
||||
TEXT_VM_SIZE,
|
||||
0,
|
||||
TEXT_VM_SIZE,
|
||||
5,
|
||||
),
|
||||
segment32(
|
||||
"__LINKEDIT",
|
||||
MACHO_ARM32_TEXT_BASE + LINKEDIT_OFFSET,
|
||||
0x1000,
|
||||
LINKEDIT_OFFSET,
|
||||
0x1000,
|
||||
1,
|
||||
),
|
||||
linkeditCommand(0x26, LINKEDIT_OFFSET, payload.length, 16),
|
||||
];
|
||||
const commandBytes = Buffer.concat(commands);
|
||||
file.writeUInt32LE(0xfeedface, 0);
|
||||
file.writeUInt32LE(12, 4);
|
||||
file.writeUInt32LE(9, 8);
|
||||
file.writeUInt32LE(2, 12);
|
||||
file.writeUInt32LE(commands.length, 16);
|
||||
file.writeUInt32LE(commandBytes.length, 20);
|
||||
commandBytes.copy(file, 28);
|
||||
return file;
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,846 @@
|
||||
import { setImmediate } from "node:timers/promises";
|
||||
|
||||
import { LC } from "../../domain/apple/machoLoadCommandCodes.js";
|
||||
import {
|
||||
readMachoHeaderDeclarations,
|
||||
readMachoLinkeditDataCommand,
|
||||
} from "../../domain/apple/machoLoadCommands.js";
|
||||
import { unrecognizedTarget } from "../../domain/analysisErrorCore.js";
|
||||
import {
|
||||
readMachoImageFromReader,
|
||||
type MachoLoadCommandVisit,
|
||||
} from "../../domain/apple/machoImage.js";
|
||||
import { requireSelectedNativeImageFromReader } from "../../domain/apple/machoSliceSelection.js";
|
||||
import {
|
||||
readByteSourceSlice,
|
||||
type ByteSource,
|
||||
} from "../../domain/byteSource.js";
|
||||
import {
|
||||
BinaryReader,
|
||||
BinaryResourceFailure,
|
||||
} from "../../domain/binaryContainer.js";
|
||||
import { firstKeyed, keyedBy } from "../../domain/keyedCollection.js";
|
||||
import type { MachoSegmentDeclaration } from "../../domain/binaryContainer.js";
|
||||
import { readLeb128, ULEB64 } from "../../domain/leb128.js";
|
||||
import {
|
||||
MACHO_FUNCTION_STARTS_LIMITATIONS as TEXT,
|
||||
machoDataInCodeKind,
|
||||
machoFunctionStartsHasIssues,
|
||||
type InspectMachoFunctionStartsInput,
|
||||
type MachoDataInCode,
|
||||
type MachoFunctionStart,
|
||||
type MachoFunctionStarts,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import {
|
||||
indexCoveredRanges,
|
||||
indexFileOffsets,
|
||||
indexSmallestSections,
|
||||
lookupInterval,
|
||||
type IntervalIndex,
|
||||
type SectionSpan,
|
||||
} from "./MachoAddressIndex.js";
|
||||
import { binaryMetadataArchitecture } from "../../domain/binaryMetadataArchitecture.js";
|
||||
import {
|
||||
assertArtifactReadActive,
|
||||
type StableArtifactHandle,
|
||||
} from "../../resources/index.js";
|
||||
|
||||
const OPERATION = "inspect_macho_function_starts";
|
||||
/** Limit name of the combined entry budget (`max_entries`). */
|
||||
export const MACHO_FUNCTION_STARTS_ENTRY_LIMIT = "entries";
|
||||
const LINKEDIT_COMMAND_BYTES = 16;
|
||||
const DATA_ENTRY_BYTES = 8;
|
||||
const YIELD_EVERY = 4096;
|
||||
/** Largest address a 32- or 64-bit image can name; a larger sum wrapped. */
|
||||
const addressMask = (bits: 32 | 64): bigint => (1n << BigInt(bits)) - 1n;
|
||||
/** CPU_TYPE_ARM (<mach/machine.h>). Its function starts tag Thumb code with bit 0. */
|
||||
const CPU_TYPE_ARM = 12;
|
||||
/** VM_PROT_EXECUTE (<mach/vm_prot.h>). */
|
||||
const VM_PROT_EXECUTE = 4;
|
||||
/** MH_OBJECT (<mach-o/loader.h>): a relocatable object, whose header is not mapped. */
|
||||
const MH_OBJECT = 1;
|
||||
const NO_ISSUES: MachoFunctionStart["issues"] = Object.freeze([]) as never;
|
||||
|
||||
const hex = (value: bigint): string => `0x${value.toString(16)}`;
|
||||
|
||||
/** File range of the __LINKEDIT segment within the selected slice. */
|
||||
interface LinkeditRange {
|
||||
readonly fileOffset: bigint;
|
||||
readonly fileSize: bigint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Facts about every LC_FUNCTION_STARTS or LC_DATA_IN_CODE command, kept
|
||||
* compactly. A malformed image can repeat a command millions of times within
|
||||
* the load-command budget, so each one adds two 32-bit words, not an object.
|
||||
* The first command is the one decoded; later ones only feed issue counters.
|
||||
*/
|
||||
class LinkeditCommandTally {
|
||||
count = 0;
|
||||
misSized = 0;
|
||||
/** Commands too short to hold `dataoff` and `datasize`. */
|
||||
fieldless = 0;
|
||||
first: { readonly dataOffset: number; readonly dataSize: number } | null =
|
||||
null;
|
||||
#ranges = new Uint32Array(16);
|
||||
#rangeCount = 0;
|
||||
|
||||
add(
|
||||
size: number,
|
||||
fields: { readonly dataOffset: number; readonly dataSize: number } | null,
|
||||
): void {
|
||||
this.count += 1;
|
||||
if (size !== LINKEDIT_COMMAND_BYTES) this.misSized += 1;
|
||||
if (fields === null) {
|
||||
this.fieldless += 1;
|
||||
return;
|
||||
}
|
||||
if (this.count === 1) this.first = fields;
|
||||
if (this.#rangeCount * 2 === this.#ranges.length) {
|
||||
const grown = new Uint32Array(this.#ranges.length * 2);
|
||||
grown.set(this.#ranges);
|
||||
this.#ranges = grown;
|
||||
}
|
||||
this.#ranges[this.#rangeCount * 2] = fields.dataOffset;
|
||||
this.#ranges[this.#rangeCount * 2 + 1] = fields.dataSize;
|
||||
this.#rangeCount += 1;
|
||||
}
|
||||
|
||||
/** Each declared `[dataoff, datasize)` pair, in declaration order. */
|
||||
*ranges(): Generator<readonly [number, number]> {
|
||||
for (let index = 0; index < this.#rangeCount; index += 1)
|
||||
yield [this.#ranges[index * 2]!, this.#ranges[index * 2 + 1]!];
|
||||
}
|
||||
}
|
||||
|
||||
/** One decoded start, handed to a walk visitor without being retained. */
|
||||
interface StartVisit {
|
||||
readonly index: number;
|
||||
/** Code address: the accumulated value with any Thumb tag cleared. */
|
||||
readonly address: bigint;
|
||||
readonly thumb: boolean;
|
||||
readonly issues: MachoFunctionStart["issues"];
|
||||
}
|
||||
|
||||
interface WalkResult {
|
||||
readonly count: number;
|
||||
readonly truncated: boolean;
|
||||
readonly overflow: boolean;
|
||||
readonly wrapped: boolean;
|
||||
readonly outOfText: boolean;
|
||||
readonly trailingNonzero: boolean;
|
||||
/** The bytes ended after a complete delta, before any zero terminator. */
|
||||
readonly unterminated: boolean;
|
||||
/** `stopAt` was reached, so `count` is a lower bound. */
|
||||
readonly stopped: boolean;
|
||||
}
|
||||
|
||||
const absentCommand = {
|
||||
status: "absent" as const,
|
||||
dataoff: null,
|
||||
datasize: null,
|
||||
file_offset: null,
|
||||
in_linkedit: null,
|
||||
};
|
||||
|
||||
const smallestSection = (
|
||||
index: IntervalIndex<SectionSpan | null>,
|
||||
address: bigint,
|
||||
): SectionSpan | null => lookupInterval(index, address) ?? null;
|
||||
|
||||
/**
|
||||
* `linkedit_data_command.dataoff` and `datasize` are `uint32_t`
|
||||
* (<mach-o/loader.h>), and so is a FAT32 slice offset, so an end or
|
||||
* container offset above this does not name a byte of a 32-bit file.
|
||||
*/
|
||||
const UINT32_MAX = 0xffffffff;
|
||||
|
||||
/** One command's declared blob, normalized once against the selected slice. */
|
||||
interface DeclaredBlob {
|
||||
readonly dataoff: number;
|
||||
readonly datasize: number;
|
||||
readonly end: number;
|
||||
/** `dataoff + datasize` fits the 32-bit field width. */
|
||||
readonly endFits: boolean;
|
||||
/** Declared bytes that lie inside the slice. */
|
||||
readonly available: number;
|
||||
}
|
||||
|
||||
const declaredBlob = (
|
||||
sliceSize: number,
|
||||
dataoff: number,
|
||||
datasize: number,
|
||||
): DeclaredBlob => {
|
||||
const end = dataoff + datasize;
|
||||
return {
|
||||
dataoff,
|
||||
datasize,
|
||||
end,
|
||||
endFits: end <= UINT32_MAX,
|
||||
available:
|
||||
dataoff >= sliceSize ? 0 : Math.min(datasize, sliceSize - dataoff),
|
||||
};
|
||||
};
|
||||
|
||||
const insideLinkedit = (
|
||||
linkedit: LinkeditRange | undefined,
|
||||
blob: DeclaredBlob,
|
||||
): boolean =>
|
||||
linkedit !== undefined &&
|
||||
blob.endFits &&
|
||||
BigInt(blob.dataoff) >= linkedit.fileOffset &&
|
||||
BigInt(blob.end) <= linkedit.fileOffset + linkedit.fileSize;
|
||||
|
||||
const blobPastSlice = (sliceSize: number, blob: DeclaredBlob): boolean =>
|
||||
!blob.endFits || blob.end > sliceSize;
|
||||
|
||||
const readDeclaredBlob = (
|
||||
source: ByteSource,
|
||||
blob: DeclaredBlob,
|
||||
): Promise<Buffer> =>
|
||||
blob.available === 0
|
||||
? Promise.resolve(Buffer.alloc(0))
|
||||
: readByteSourceSlice(source, blob.dataoff, blob.available);
|
||||
|
||||
interface LoadedTable {
|
||||
readonly record: MachoFunctionStarts["function_starts"];
|
||||
readonly misSized: number;
|
||||
readonly duplicate: number;
|
||||
readonly outside: number;
|
||||
readonly pastFile: number;
|
||||
readonly bytes: Buffer;
|
||||
readonly declared: number;
|
||||
}
|
||||
|
||||
const loadTable = async (
|
||||
source: ByteSource,
|
||||
tally: LinkeditCommandTally,
|
||||
sliceFileOffset: number,
|
||||
linkedit: LinkeditRange | undefined,
|
||||
): Promise<LoadedTable> => {
|
||||
if (tally.count === 0)
|
||||
return {
|
||||
record: absentCommand,
|
||||
misSized: 0,
|
||||
duplicate: 0,
|
||||
outside: 0,
|
||||
pastFile: 0,
|
||||
bytes: Buffer.alloc(0),
|
||||
declared: 0,
|
||||
};
|
||||
const first = tally.first;
|
||||
const duplicate = tally.count - 1;
|
||||
const misSized = tally.misSized;
|
||||
let outside = 0;
|
||||
let pastFile = 0;
|
||||
for (const [dataOffset, dataSize] of tally.ranges()) {
|
||||
const blob = declaredBlob(source.size, dataOffset, dataSize);
|
||||
if (!insideLinkedit(linkedit, blob)) outside += 1;
|
||||
if (blobPastSlice(source.size, blob)) pastFile += 1;
|
||||
}
|
||||
if (first === null)
|
||||
return {
|
||||
record: { ...absentCommand, status: "present" },
|
||||
misSized,
|
||||
duplicate,
|
||||
outside,
|
||||
pastFile,
|
||||
bytes: Buffer.alloc(0),
|
||||
declared: 0,
|
||||
};
|
||||
const blob = declaredBlob(source.size, first.dataOffset, first.dataSize);
|
||||
const bytes = await readDeclaredBlob(source, blob);
|
||||
// A short read of bytes the slice declares is also a truncated table.
|
||||
if (!blobPastSlice(source.size, blob) && bytes.length < blob.available)
|
||||
pastFile += 1;
|
||||
const container = sliceFileOffset + blob.dataoff;
|
||||
return {
|
||||
record: {
|
||||
status: "present",
|
||||
dataoff: blob.dataoff,
|
||||
datasize: blob.datasize,
|
||||
file_offset: container <= UINT32_MAX ? container : null,
|
||||
in_linkedit: insideLinkedit(linkedit, blob),
|
||||
},
|
||||
misSized,
|
||||
duplicate,
|
||||
outside,
|
||||
pastFile,
|
||||
bytes,
|
||||
declared: blob.datasize,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Walk the ULEB128 deltas once. Each delta is added to the previous
|
||||
* accumulated value, the first to the __TEXT vmaddr, as ld64 encodes it and
|
||||
* llvm-objdump decodes it. On 32-bit ARM, ld64 sets bit 0 for a Thumb start
|
||||
* before taking the next delta, so the accumulator keeps that bit and only the
|
||||
* reported address clears it, as LLDB does. `visit` sees every start, and
|
||||
* the walk retains none, so its memory does not grow with the table.
|
||||
*/
|
||||
const walkStarts = async (
|
||||
table: {
|
||||
readonly bytes: Uint8Array;
|
||||
readonly textBase: bigint;
|
||||
readonly executable: IntervalIndex<boolean>;
|
||||
readonly thumbTagged: boolean;
|
||||
readonly addressLimit: bigint;
|
||||
/** Stop after this many starts; the caller refuses a larger table. */
|
||||
readonly stopAt: number;
|
||||
},
|
||||
signal: AbortSignal | undefined,
|
||||
visit: (start: StartVisit) => void,
|
||||
): Promise<WalkResult> => {
|
||||
const { bytes, textBase, executable, thumbTagged, addressLimit, stopAt } =
|
||||
table;
|
||||
let terminated = false;
|
||||
let stopped = false;
|
||||
let offset = 0;
|
||||
let previous: bigint = textBase;
|
||||
let count = 0;
|
||||
let truncated = false;
|
||||
let overflow = false;
|
||||
let wrapped = false;
|
||||
let outOfText = false;
|
||||
let trailingNonzero = false;
|
||||
while (offset < bytes.length) {
|
||||
if (count > 0 && count % YIELD_EVERY === 0) {
|
||||
await setImmediate();
|
||||
assertArtifactReadActive(signal);
|
||||
}
|
||||
const read = readLeb128(bytes, offset, bytes.length, ULEB64);
|
||||
if ("failure" in read) {
|
||||
truncated = read.failure === "truncated";
|
||||
overflow = read.failure === "overflow";
|
||||
break;
|
||||
}
|
||||
offset = read.next;
|
||||
if (read.value === 0n) {
|
||||
terminated = true;
|
||||
for (let index = offset; index < bytes.length; index += 1) {
|
||||
if (bytes[index] !== 0) {
|
||||
trailingNonzero = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
const sum: bigint = previous + read.value;
|
||||
const tagged: bigint = sum & addressLimit;
|
||||
const thumb = thumbTagged && (tagged & 1n) === 1n;
|
||||
const address = thumb ? tagged & ~1n : tagged;
|
||||
const didWrap = sum > addressLimit;
|
||||
const outside = lookupInterval(executable, address) !== true;
|
||||
let issues = NO_ISSUES;
|
||||
if (didWrap || outside) {
|
||||
issues = [];
|
||||
if (didWrap) {
|
||||
wrapped = true;
|
||||
issues.push("wrapped");
|
||||
}
|
||||
if (outside) {
|
||||
outOfText = true;
|
||||
issues.push("out_of_text");
|
||||
}
|
||||
}
|
||||
if (count >= stopAt) {
|
||||
stopped = true;
|
||||
count += 1;
|
||||
break;
|
||||
}
|
||||
visit({ index: count, address, thumb, issues });
|
||||
count += 1;
|
||||
if (didWrap || outside) break;
|
||||
previous = tagged;
|
||||
}
|
||||
return {
|
||||
count,
|
||||
truncated,
|
||||
overflow,
|
||||
wrapped,
|
||||
outOfText,
|
||||
trailingNonzero,
|
||||
unterminated:
|
||||
bytes.length > 0 &&
|
||||
!terminated &&
|
||||
!stopped &&
|
||||
!truncated &&
|
||||
!overflow &&
|
||||
!wrapped &&
|
||||
!outOfText,
|
||||
stopped,
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* The VM address the mach_header is mapped at. ld64 writes each
|
||||
* data-in-code offset as an address minus this one, and dyld documents the
|
||||
* offset as a delta from the mach_header. A relocatable object does not map
|
||||
* its header, so its offsets are addresses (base 0). Otherwise the header is
|
||||
* file offset 0, translated through the shared file mappings; an unmapped or
|
||||
* ambiguously mapped header leaves the base unknown.
|
||||
*/
|
||||
const machHeaderAddress = (
|
||||
fileType: number,
|
||||
mappings: IntervalIndex<bigint | null>,
|
||||
): bigint | null => {
|
||||
if (fileType === MH_OBJECT) return 0n;
|
||||
const delta = lookupInterval(mappings, 0n);
|
||||
return delta === undefined || delta === null ? null : delta;
|
||||
};
|
||||
|
||||
/** A data-in-code entry on the returned page, before its owner is resolved. */
|
||||
type PagedDataInCode = Omit<MachoDataInCode, "owner"> & {
|
||||
readonly address: bigint | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check every data-in-code entry once, counting its issues, and build result
|
||||
* objects only for entries on the requested page.
|
||||
*/
|
||||
const decodeData = async (
|
||||
bytes: Buffer,
|
||||
littleEndian: boolean,
|
||||
headerAddress: bigint | null,
|
||||
segments: IntervalIndex<boolean>,
|
||||
sections: IntervalIndex<SectionSpan | null>,
|
||||
page: { readonly from: number; readonly to: number },
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<{
|
||||
readonly count: number;
|
||||
readonly page: readonly PagedDataInCode[];
|
||||
readonly crossings: number;
|
||||
readonly unsorted: number;
|
||||
readonly unmapped: number;
|
||||
readonly zeroLength: number;
|
||||
}> => {
|
||||
const reader = new BinaryReader(bytes, littleEndian, "macho");
|
||||
const count = Math.floor(bytes.length / DATA_ENTRY_BYTES);
|
||||
const entries: PagedDataInCode[] = [];
|
||||
let crossings = 0;
|
||||
let unsorted = 0;
|
||||
let unmapped = 0;
|
||||
let zeroLength = 0;
|
||||
let previous: number | null = null;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
if (index > 0 && index % YIELD_EVERY === 0) {
|
||||
await setImmediate();
|
||||
assertArtifactReadActive(signal);
|
||||
}
|
||||
const at = index * DATA_ENTRY_BYTES;
|
||||
const offset = reader.u32(at);
|
||||
const length = reader.u16(at + 4);
|
||||
const candidate =
|
||||
headerAddress === null ? null : headerAddress + BigInt(offset);
|
||||
const vmaddr =
|
||||
candidate !== null && lookupInterval(segments, candidate) === true
|
||||
? candidate
|
||||
: null;
|
||||
const outOfOrder = previous !== null && offset <= previous;
|
||||
previous = offset;
|
||||
const span = vmaddr === null ? null : smallestSection(sections, vmaddr);
|
||||
const crosses =
|
||||
vmaddr !== null &&
|
||||
length !== 0 &&
|
||||
(span === null || vmaddr + BigInt(length) > span.address + span.size);
|
||||
if (outOfOrder) unsorted += 1;
|
||||
if (length === 0) zeroLength += 1;
|
||||
if (vmaddr === null) unmapped += 1;
|
||||
if (crosses) crossings += 1;
|
||||
if (index < page.from || index >= page.to) continue;
|
||||
const issues: MachoDataInCode["issues"] = [];
|
||||
if (outOfOrder) issues.push("out_of_order");
|
||||
if (length === 0) issues.push("zero_length");
|
||||
if (vmaddr === null) issues.push("unmapped");
|
||||
if (crosses) issues.push("crosses_section");
|
||||
entries.push({
|
||||
index,
|
||||
offset,
|
||||
vmaddr: vmaddr === null ? null : hex(vmaddr),
|
||||
address: vmaddr,
|
||||
length,
|
||||
kind: machoDataInCodeKind(reader.u16(at + 6)),
|
||||
section: span?.name ?? null,
|
||||
issues,
|
||||
});
|
||||
}
|
||||
return { count, page: entries, crossings, unsorted, unmapped, zeroLength };
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve each paged entry's owner, the greatest decoded start at or before
|
||||
* its address, during the one start walk. Starts increase strictly until a
|
||||
* wrapped start ends the walk, and that start is never an owner. Targets are
|
||||
* sorted once, so the work is linear in starts plus the page.
|
||||
*/
|
||||
class OwnerResolver {
|
||||
readonly #targets: { readonly address: bigint; readonly slot: number }[];
|
||||
readonly #owners: MachoDataInCode["owner"][];
|
||||
#next = 0;
|
||||
#best: MachoDataInCode["owner"] = null;
|
||||
|
||||
constructor(entries: readonly PagedDataInCode[]) {
|
||||
this.#owners = entries.map(() => null);
|
||||
this.#targets = entries
|
||||
.flatMap((entry, slot) =>
|
||||
entry.address === null ? [] : [{ address: entry.address, slot }],
|
||||
)
|
||||
.sort((left, right) =>
|
||||
left.address < right.address
|
||||
? -1
|
||||
: left.address > right.address
|
||||
? 1
|
||||
: 0,
|
||||
);
|
||||
}
|
||||
|
||||
visit(start: StartVisit): void {
|
||||
if (start.issues.includes("wrapped")) return;
|
||||
while (
|
||||
this.#next < this.#targets.length &&
|
||||
this.#targets[this.#next]!.address < start.address
|
||||
) {
|
||||
this.#owners[this.#targets[this.#next]!.slot] = this.#best;
|
||||
this.#next += 1;
|
||||
}
|
||||
this.#best = { index: start.index, vmaddr: hex(start.address) };
|
||||
}
|
||||
|
||||
finish(): readonly MachoDataInCode["owner"][] {
|
||||
for (; this.#next < this.#targets.length; this.#next += 1)
|
||||
this.#owners[this.#targets[this.#next]!.slot] = this.#best;
|
||||
return this.#owners;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A segment the loader maps executable, by its initial protection. The shared
|
||||
* reader never makes __PAGEZERO a load region, and neither does this check.
|
||||
*/
|
||||
const executableSegment = (segment: MachoSegmentDeclaration): boolean =>
|
||||
(segment.protection & VM_PROT_EXECUTE) !== 0 && segment.name !== "__PAGEZERO";
|
||||
|
||||
/** Indexes `[from, to)` of one table that the caller's page selects. */
|
||||
const pageRange = (
|
||||
included: boolean,
|
||||
offset: number,
|
||||
limit: number,
|
||||
): { readonly from: number; readonly to: number } =>
|
||||
included ? { from: offset, to: offset + limit } : { from: 0, to: 0 };
|
||||
|
||||
const nextOffset = (
|
||||
included: boolean,
|
||||
offset: number,
|
||||
returned: number,
|
||||
total: number,
|
||||
): number | null =>
|
||||
included && offset + returned < total ? offset + returned : null;
|
||||
|
||||
/**
|
||||
* Refuse a table pair above `max_entries`. `required` is the measured total
|
||||
* when both tables were counted, and absent when decoding stopped at the
|
||||
* allowance, which only shows the total is larger.
|
||||
*/
|
||||
const entryBudgetFailure = (
|
||||
maximum: number,
|
||||
required: number | undefined,
|
||||
): BinaryResourceFailure =>
|
||||
new BinaryResourceFailure(
|
||||
"structure",
|
||||
maximum,
|
||||
required === undefined
|
||||
? `Mach-O function starts and data-in-code entries exceed max_entries (${String(maximum)})`
|
||||
: `Mach-O function starts and data-in-code entries total ${String(required)}, above max_entries (${String(maximum)})`,
|
||||
MACHO_FUNCTION_STARTS_ENTRY_LIMIT,
|
||||
"entries",
|
||||
required,
|
||||
);
|
||||
|
||||
/** Decode one selected slice's function starts and data-in-code entries. */
|
||||
export const parseMachoFunctionStartsFromHandle = async (
|
||||
handle: StableArtifactHandle,
|
||||
artifact: MachoFunctionStarts["artifact"],
|
||||
input: InspectMachoFunctionStartsInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<MachoFunctionStarts> => {
|
||||
assertArtifactReadActive(signal);
|
||||
const selected = await requireSelectedNativeImageFromReader(
|
||||
OPERATION,
|
||||
artifact.path,
|
||||
handle,
|
||||
input.architecture,
|
||||
);
|
||||
const source = selected.source;
|
||||
// The shared header recognizer returns null for a magic that is not
|
||||
// Mach-O, such as an ELF or PE file passed without `architecture`. That
|
||||
// file is outside this operation, not a malformed Mach-O, so it is reported
|
||||
// as unrecognized before the thin reader would call it malformed. A header
|
||||
// the recognizer rejects for another reason stays a format failure.
|
||||
const header = readMachoHeaderDeclarations(
|
||||
await readByteSourceSlice(source, 0, Math.min(32, source.size)),
|
||||
source.size,
|
||||
);
|
||||
if (header.ok && header.value === null)
|
||||
throw unrecognizedTarget(
|
||||
OPERATION,
|
||||
artifact.path,
|
||||
"macho",
|
||||
"The file is not a thin Mach-O image or a universal Mach-O file.",
|
||||
);
|
||||
// The shared image walk hands back the two LINKEDIT data commands, so the
|
||||
// load-command table is read and framed once.
|
||||
const startsCommands = new LinkeditCommandTally();
|
||||
const dataCommands = new LinkeditCommandTally();
|
||||
const image = await readMachoImageFromReader(
|
||||
source,
|
||||
input.max_structure_bytes,
|
||||
({ command, size, body, littleEndian: little }: MachoLoadCommandVisit) => {
|
||||
const tally =
|
||||
command === LC.FUNCTION_STARTS
|
||||
? startsCommands
|
||||
: command === LC.DATA_IN_CODE
|
||||
? dataCommands
|
||||
: undefined;
|
||||
tally?.add(size, readMachoLinkeditDataCommand(command, body, little));
|
||||
},
|
||||
);
|
||||
const littleEndian = image.byte_order === "little";
|
||||
// Declared segments, file-backed or not: llvm-objdump anchors the deltas on
|
||||
// the first __TEXT segment command's vmaddr, which needs no file bytes.
|
||||
const segments = keyedBy(image.macho_segments, (segment) => segment.name);
|
||||
// Mach-O names one __TEXT and one __LINKEDIT; a repeat keeps the first.
|
||||
const linkeditSegment = firstKeyed(
|
||||
segments,
|
||||
"__LINKEDIT",
|
||||
"The first __LINKEDIT segment contains LC_FUNCTION_STARTS and LC_DATA_IN_CODE.",
|
||||
);
|
||||
const linkedit =
|
||||
linkeditSegment === undefined
|
||||
? undefined
|
||||
: {
|
||||
fileOffset: linkeditSegment.file_offset,
|
||||
fileSize: linkeditSegment.file_size,
|
||||
};
|
||||
const text = firstKeyed(
|
||||
segments,
|
||||
"__TEXT",
|
||||
"The first __TEXT segment anchors LC_FUNCTION_STARTS deltas.",
|
||||
);
|
||||
const executable = indexCoveredRanges(
|
||||
image.macho_segments.filter(executableSegment).map((segment) => ({
|
||||
address: segment.address,
|
||||
size: segment.memory_size,
|
||||
})),
|
||||
);
|
||||
const startsTable = await loadTable(
|
||||
source,
|
||||
startsCommands,
|
||||
selected.fileOffset,
|
||||
linkedit,
|
||||
);
|
||||
const dataTable = await loadTable(
|
||||
source,
|
||||
dataCommands,
|
||||
selected.fileOffset,
|
||||
linkedit,
|
||||
);
|
||||
const sections: SectionSpan[] = [];
|
||||
for (const section of image.sections) {
|
||||
if (section.format !== "macho") continue;
|
||||
sections.push({
|
||||
name: section.section_name,
|
||||
address: section.address,
|
||||
size: section.declared_range.size,
|
||||
});
|
||||
}
|
||||
const missingText =
|
||||
startsTable.record.status === "present" &&
|
||||
startsTable.declared > 0 &&
|
||||
text === undefined
|
||||
? 1
|
||||
: 0;
|
||||
const headerAddress = machHeaderAddress(
|
||||
image.macho_file_type,
|
||||
indexFileOffsets(image.mappings),
|
||||
);
|
||||
// ld64 and llvm-objdump take the deltas from the __TEXT vmaddr, and dyld
|
||||
// from the mach_header address. Where the header is not mapped at that
|
||||
// vmaddr (it lives elsewhere, SG_HIGHVM shifts it, or it is unmapped), the
|
||||
// two disagree and the base is reported as disputed.
|
||||
const textNotAtHeader =
|
||||
missingText === 0 &&
|
||||
text !== undefined &&
|
||||
startsTable.declared > 0 &&
|
||||
headerAddress !== text.address
|
||||
? 1
|
||||
: 0;
|
||||
const includeStarts = input.kind !== "data";
|
||||
const includeData = input.kind !== "starts";
|
||||
const sectionIndex = indexSmallestSections(sections);
|
||||
// The entry allowance bounds decoding work, not only the result: a data
|
||||
// table counted from its bytes is refused before any entry is examined,
|
||||
// and the start walk stops once the combined count would exceed it.
|
||||
const dataCount = Math.floor(dataTable.bytes.length / DATA_ENTRY_BYTES);
|
||||
// With no starts to decode, the data count is the complete need.
|
||||
const noStarts = missingText === 1 || startsTable.bytes.length === 0;
|
||||
if (dataCount > input.max_entries)
|
||||
throw entryBudgetFailure(
|
||||
input.max_entries,
|
||||
noStarts ? dataCount : undefined,
|
||||
);
|
||||
// Every entry is checked and counted, but result objects are built only for
|
||||
// the requested page of each table.
|
||||
const data = await decodeData(
|
||||
dataTable.bytes,
|
||||
littleEndian,
|
||||
headerAddress,
|
||||
indexCoveredRanges(
|
||||
image.macho_segments
|
||||
.filter((segment) => segment.name !== "__PAGEZERO")
|
||||
.map((segment) => ({
|
||||
address: segment.address,
|
||||
size: segment.memory_size,
|
||||
})),
|
||||
),
|
||||
sectionIndex,
|
||||
pageRange(includeData, input.offset, input.limit),
|
||||
signal,
|
||||
);
|
||||
const startRange = pageRange(includeStarts, input.offset, input.limit);
|
||||
const startPage: MachoFunctionStart[] = [];
|
||||
const owners = new OwnerResolver(data.page);
|
||||
const thumbTagged = image.macho_cpu_type === CPU_TYPE_ARM;
|
||||
const decoded =
|
||||
missingText === 1
|
||||
? {
|
||||
count: 0,
|
||||
truncated: false,
|
||||
overflow: false,
|
||||
wrapped: false,
|
||||
outOfText: false,
|
||||
trailingNonzero: false,
|
||||
unterminated: false,
|
||||
stopped: false,
|
||||
}
|
||||
: await walkStarts(
|
||||
{
|
||||
bytes: startsTable.bytes,
|
||||
textBase: text?.address ?? 0n,
|
||||
executable,
|
||||
thumbTagged,
|
||||
addressLimit: addressMask(image.bits),
|
||||
stopAt: input.max_entries - data.count,
|
||||
},
|
||||
signal,
|
||||
(start) => {
|
||||
owners.visit(start);
|
||||
if (start.index < startRange.from || start.index >= startRange.to)
|
||||
return;
|
||||
startPage.push({
|
||||
index: start.index,
|
||||
vmaddr: hex(start.address),
|
||||
...(thumbTagged ? { thumb: start.thumb } : {}),
|
||||
section:
|
||||
smallestSection(sectionIndex, start.address)?.name ?? null,
|
||||
issues: [...start.issues],
|
||||
});
|
||||
},
|
||||
);
|
||||
if (decoded.stopped) throw entryBudgetFailure(input.max_entries, undefined);
|
||||
const resolvedOwners = owners.finish();
|
||||
const dataPage: MachoDataInCode[] = data.page.map(
|
||||
({ address: _address, ...entry }, slot) => ({
|
||||
...entry,
|
||||
owner: resolvedOwners[slot] ?? null,
|
||||
}),
|
||||
);
|
||||
const coverage = {
|
||||
status: "complete" as const,
|
||||
total_starts: decoded.count,
|
||||
total_data_in_code: data.count,
|
||||
duplicate_commands: startsTable.duplicate + dataTable.duplicate,
|
||||
mis_sized_commands: startsTable.misSized + dataTable.misSized,
|
||||
outside_linkedit: startsTable.outside + dataTable.outside,
|
||||
truncated_commands: startsTable.pastFile + dataTable.pastFile,
|
||||
uleb_truncated: decoded.truncated ? 1 : 0,
|
||||
uleb_overflow: decoded.overflow ? 1 : 0,
|
||||
non_monotonic: decoded.wrapped ? 1 : 0,
|
||||
out_of_text: decoded.outOfText ? 1 : 0,
|
||||
missing_text_anchor: missingText,
|
||||
text_not_at_header: textNotAtHeader,
|
||||
unterminated_starts: decoded.unterminated ? 1 : 0,
|
||||
trailing_nonzero: decoded.trailingNonzero ? 1 : 0,
|
||||
data_trailing_bytes: dataTable.bytes.length % DATA_ENTRY_BYTES,
|
||||
section_crossings: data.crossings,
|
||||
unsorted_data: data.unsorted,
|
||||
unmapped_data: data.unmapped,
|
||||
zero_length_data: data.zeroLength,
|
||||
};
|
||||
const partial = machoFunctionStartsHasIssues(coverage);
|
||||
const limitations = [
|
||||
TEXT.missingStarts,
|
||||
TEXT.missingData,
|
||||
TEXT.static,
|
||||
...(startsTable.duplicate > 0 ? [TEXT.duplicateStarts] : []),
|
||||
...(dataTable.duplicate > 0 ? [TEXT.duplicateData] : []),
|
||||
...(startsTable.outside > 0 ? [TEXT.outsideStarts] : []),
|
||||
...(dataTable.outside > 0 ? [TEXT.outsideData] : []),
|
||||
...(startsTable.misSized > 0 ? [TEXT.misSizedStarts] : []),
|
||||
...(dataTable.misSized > 0 ? [TEXT.misSizedData] : []),
|
||||
...(decoded.truncated ? [TEXT.ulebTruncated] : []),
|
||||
...(decoded.overflow ? [TEXT.ulebOverflow] : []),
|
||||
...(decoded.wrapped ? [TEXT.wrapped] : []),
|
||||
...(decoded.outOfText ? [TEXT.outOfText] : []),
|
||||
...(missingText === 1 ? [TEXT.missingText] : []),
|
||||
...(textNotAtHeader === 1 ? [TEXT.textNotAtHeader] : []),
|
||||
...(decoded.unterminated ? [TEXT.unterminated] : []),
|
||||
...(decoded.trailingNonzero ? [TEXT.trailing] : []),
|
||||
...(startsTable.pastFile > 0 ? [TEXT.startsPastFile] : []),
|
||||
...(dataTable.pastFile > 0 ? [TEXT.dataPastFile] : []),
|
||||
...(coverage.data_trailing_bytes > 0 ? [TEXT.dataTrailing] : []),
|
||||
...(data.crossings > 0 ? [TEXT.crosses] : []),
|
||||
...(data.unsorted > 0 ? [TEXT.unsorted] : []),
|
||||
...(data.zeroLength > 0 ? [TEXT.zeroLength] : []),
|
||||
...(data.unmapped > 0 ? [TEXT.unmapped] : []),
|
||||
...selected.limitations,
|
||||
];
|
||||
const architecture = binaryMetadataArchitecture(image.architecture) ?? null;
|
||||
return {
|
||||
artifact,
|
||||
format: "macho",
|
||||
architecture,
|
||||
bits: image.bits,
|
||||
byte_order: image.byte_order,
|
||||
...(selected.selection === null
|
||||
? {}
|
||||
: { selected_slice: selected.selection }),
|
||||
function_starts: startsTable.record,
|
||||
data_in_code: dataTable.record,
|
||||
coverage: { ...coverage, status: partial ? "partial" : "complete" },
|
||||
page: {
|
||||
kind: input.kind,
|
||||
offset: input.offset,
|
||||
limit: input.limit,
|
||||
returned_starts: startPage.length,
|
||||
total_starts: decoded.count,
|
||||
next_starts_offset: nextOffset(
|
||||
includeStarts,
|
||||
input.offset,
|
||||
startPage.length,
|
||||
decoded.count,
|
||||
),
|
||||
returned_data: dataPage.length,
|
||||
total_data: data.count,
|
||||
next_data_offset: nextOffset(
|
||||
includeData,
|
||||
input.offset,
|
||||
dataPage.length,
|
||||
data.count,
|
||||
),
|
||||
},
|
||||
starts: startPage,
|
||||
data_in_code_entries: dataPage,
|
||||
limitations,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,147 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createMachoFunctionStartsService } from "../../composition/binaryDiagnostics/machoFunctionStarts.js";
|
||||
import { AnalysisTargetFailureError } from "../../domain/analysisErrorCore.js";
|
||||
import { inspectMachoFunctionStartsInputSchema } from "../../domain/native/machoFunctionStarts.js";
|
||||
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
arm64FunctionStartsImage,
|
||||
machoFunctionStartsUniversal,
|
||||
x64FunctionStartsImage,
|
||||
} from "./MachoFunctionStarts.fixture.js";
|
||||
import { MachoFunctionStartsProvider } from "./MachoFunctionStartsProvider.js";
|
||||
|
||||
const inspect = async (bytes: Buffer, input: Record<string, unknown> = {}) => {
|
||||
const path = join(
|
||||
await createTestTempDirectory("rea-macho-function-starts-"),
|
||||
"program",
|
||||
);
|
||||
await writeFile(path, bytes);
|
||||
const provider = new MachoFunctionStartsProvider();
|
||||
try {
|
||||
return await provider.inspect(
|
||||
inspectMachoFunctionStartsInputSchema.parse({ path, ...input }),
|
||||
);
|
||||
} finally {
|
||||
await provider.close();
|
||||
}
|
||||
};
|
||||
|
||||
describe("Mach-O function starts provider", () => {
|
||||
it("refuses max_entries at the allowance without claiming a total", async () => {
|
||||
const refused = await inspect(arm64FunctionStartsImage(), {
|
||||
max_entries: 5,
|
||||
});
|
||||
if (refused.ok) throw new Error("Expected a max_entries refusal");
|
||||
expect(refused.error).toMatchObject({
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
limit: {
|
||||
control_kind: "parameter",
|
||||
parameter: "max_entries",
|
||||
effective_value: 5,
|
||||
default_value: 2_097_152,
|
||||
},
|
||||
});
|
||||
// Decoding stopped at the allowance, so the total was not measured.
|
||||
expect(
|
||||
(refused.error as { readonly limit?: object }).limit,
|
||||
).not.toHaveProperty("required_value");
|
||||
});
|
||||
|
||||
it("rejects architecture on a thin image and a universal file without one", async () => {
|
||||
const thin = await inspect(arm64FunctionStartsImage(), {
|
||||
architecture: "arm64",
|
||||
});
|
||||
if (thin.ok) throw new Error("Expected a thin-image architecture refusal");
|
||||
expect(thin.error).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [{ path: ["architecture"] }],
|
||||
});
|
||||
const universal = await inspect(
|
||||
machoFunctionStartsUniversal(
|
||||
arm64FunctionStartsImage(),
|
||||
x64FunctionStartsImage(),
|
||||
),
|
||||
);
|
||||
if (universal.ok)
|
||||
throw new Error("Expected a missing architecture refusal");
|
||||
expect(universal.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
|
||||
it("reports bytes that are not Mach-O as a target failure", async () => {
|
||||
const foreign = await inspect(
|
||||
Buffer.from("not a macho image, just text!!"),
|
||||
);
|
||||
if (foreign.ok) throw new Error("Expected a target failure");
|
||||
expect(foreign.error).toBeInstanceOf(AnalysisTargetFailureError);
|
||||
expect(foreign.error._tag).toBe("AnalysisTargetFailureError");
|
||||
expect(foreign.error).toMatchObject({
|
||||
failure: { kind: "unrecognized", format: "macho" },
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an ELF file as unrecognized, not as a malformed Mach-O", async () => {
|
||||
const elf = Buffer.alloc(64);
|
||||
Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2, 1, 1]).copy(elf);
|
||||
const refused = await inspect(elf);
|
||||
if (refused.ok) throw new Error("Expected a target failure");
|
||||
expect(refused.error).toMatchObject({
|
||||
_tag: "AnalysisTargetFailureError",
|
||||
failure: { kind: "unrecognized", format: "macho" },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a recognized but cut-off Mach-O header a format failure", async () => {
|
||||
// A 64-bit Mach-O magic with the header cut off after 12 bytes.
|
||||
const cut = arm64FunctionStartsImage().subarray(0, 12);
|
||||
const refused = await inspect(Buffer.from(cut));
|
||||
if (refused.ok) throw new Error("Expected a target failure");
|
||||
expect(refused.error._tag).toBe("AnalysisTargetFailureError");
|
||||
expect((refused.error as AnalysisTargetFailureError).failure.kind).not.toBe(
|
||||
"unrecognized",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Mach-O function starts service failures", () => {
|
||||
it("returns typed resource and cancellation failures", async () => {
|
||||
const path = join(
|
||||
await createTestTempDirectory("rea-macho-function-starts-budget-"),
|
||||
"program",
|
||||
);
|
||||
await writeFile(path, arm64FunctionStartsImage());
|
||||
const service = createMachoFunctionStartsService();
|
||||
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");
|
||||
expect(tooSmall.error).toMatchObject({
|
||||
resource: "capacity",
|
||||
limit: { parameter: "max_file_bytes" },
|
||||
});
|
||||
const paddedPath = join(
|
||||
await createTestTempDirectory("rea-macho-function-starts-padded-"),
|
||||
"padded",
|
||||
);
|
||||
await writeFile(
|
||||
paddedPath,
|
||||
Buffer.concat([arm64FunctionStartsImage(), Buffer.alloc(131_072)]),
|
||||
);
|
||||
const fitsReadBudget = await service.inspect({
|
||||
path: paddedPath,
|
||||
max_file_bytes: 80_000,
|
||||
});
|
||||
expect(fitsReadBudget.ok).toBe(true);
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { maxFileBytesReadBudget } from "../../domain/artifactReadBudget.js";
|
||||
import { parseLimitConstraint } from "../../domain/parseFailureAnalysisError.js";
|
||||
import {
|
||||
artifactFileCeilingConstraint,
|
||||
artifactFilePrimaryFacts,
|
||||
artifactReadBudgetConstraint,
|
||||
assertArtifactReadActive,
|
||||
closeArtifactResources,
|
||||
projectStableArtifactFailure,
|
||||
withStableArtifactHandle,
|
||||
ArtifactResourceScope,
|
||||
} from "../../resources/index.js";
|
||||
import type { MachoFunctionStartsPort } from "../../ports/binaryDiagnostics/MachoFunctionStartsPort.js";
|
||||
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
|
||||
import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js";
|
||||
import { offlineArtifactFailureDialect } from "../../providers/offlineArtifactFailure.js";
|
||||
import {
|
||||
BinaryResourceFailure,
|
||||
binaryResourceAllowance,
|
||||
isNativeStructureFailure,
|
||||
} from "../../domain/binaryContainer.js";
|
||||
import { nativeStructureConstraint } from "../../domain/native/nativeStructureBudget.js";
|
||||
import {
|
||||
MACHO_FUNCTION_STARTS_FILE_CEILING_BYTES,
|
||||
MAX_INSPECT_MACHO_FUNCTION_STARTS_FILE_BYTES,
|
||||
machoFunctionStartsEntryLimit,
|
||||
type InspectMachoFunctionStartsInput,
|
||||
type MachoFunctionStarts,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import { err, ok } from "../../domain/result.js";
|
||||
import { MACHO_FUNCTION_STARTS_PROVIDER } from "../../domain/investigationProviders.js";
|
||||
import {
|
||||
MACHO_FUNCTION_STARTS_ENTRY_LIMIT,
|
||||
parseMachoFunctionStartsFromHandle,
|
||||
} from "./MachoFunctionStarts.js";
|
||||
|
||||
const OPERATION = "inspect_macho_function_starts";
|
||||
const HEADER_PREFIX_BYTES = 4096;
|
||||
const FILE_CEILING = {
|
||||
name: "The Mach-O whole-file ceiling (32-bit linkedit dataoff and FAT32 offsets)",
|
||||
bytes: MACHO_FUNCTION_STARTS_FILE_CEILING_BYTES,
|
||||
} as const;
|
||||
|
||||
/** Portable Mach-O function-start reader over one bounded, identity-checked regular file. */
|
||||
export class MachoFunctionStartsProvider implements MachoFunctionStartsPort {
|
||||
readonly identity = MACHO_FUNCTION_STARTS_PROVIDER;
|
||||
readonly #resources = new ArtifactResourceScope();
|
||||
|
||||
close(): Promise<void> {
|
||||
return closeArtifactResources(
|
||||
() => this.#resources.close(),
|
||||
MACHO_FUNCTION_STARTS_PROVIDER,
|
||||
OPERATION,
|
||||
);
|
||||
}
|
||||
|
||||
async inspect(
|
||||
input: InspectMachoFunctionStartsInput,
|
||||
options?: ExecutionOptions,
|
||||
) {
|
||||
const signal = options?.signal;
|
||||
let completed: MachoFunctionStarts | undefined;
|
||||
let snapshot:
|
||||
| { readonly sha256: string; readonly bytes: number }
|
||||
| undefined;
|
||||
try {
|
||||
return await this.#resources.run(async () => {
|
||||
const report = await withStableArtifactHandle<MachoFunctionStarts>(
|
||||
input.path,
|
||||
FILE_CEILING.bytes,
|
||||
{
|
||||
readBudget: maxFileBytesReadBudget(
|
||||
input.max_file_bytes,
|
||||
MAX_INSPECT_MACHO_FUNCTION_STARTS_FILE_BYTES,
|
||||
),
|
||||
retainBytes: (size) => Math.min(size, HEADER_PREFIX_BYTES),
|
||||
signal,
|
||||
resourceScope: this.#resources,
|
||||
onIdentity: (identity) => {
|
||||
snapshot = identity;
|
||||
},
|
||||
onVerifiedResult: (value) => {
|
||||
completed = value;
|
||||
},
|
||||
},
|
||||
async (handle) => {
|
||||
assertArtifactReadActive(signal);
|
||||
const value = await parseMachoFunctionStartsFromHandle(
|
||||
handle,
|
||||
{ path: input.path, sha256: handle.sha256, bytes: handle.size },
|
||||
input,
|
||||
signal,
|
||||
);
|
||||
assertArtifactReadActive(signal);
|
||||
return value;
|
||||
},
|
||||
);
|
||||
return ok(report);
|
||||
});
|
||||
} catch (cause) {
|
||||
return err(machoFunctionStartsFailure(cause, input, snapshot, completed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const machoFunctionStartsFailure = (
|
||||
cause: unknown,
|
||||
input: InspectMachoFunctionStartsInput,
|
||||
snapshot?: { readonly sha256: string; readonly bytes: number },
|
||||
completed?: MachoFunctionStarts,
|
||||
) => {
|
||||
const facts = artifactFilePrimaryFacts(cause);
|
||||
const primary = classifyProviderFailure(
|
||||
facts.cause,
|
||||
offlineArtifactFailureDialect(facts, {
|
||||
providerId: MACHO_FUNCTION_STARTS_PROVIDER.id,
|
||||
operation: OPERATION,
|
||||
path: input.path,
|
||||
description: "Mach-O image",
|
||||
fallbackMessage: "Mach-O function-start inspection failed.",
|
||||
recognise: (failure) => {
|
||||
const readBudget = artifactReadBudgetConstraint(OPERATION, failure, {
|
||||
max_file_bytes: input.max_file_bytes,
|
||||
});
|
||||
if (readBudget !== undefined) return readBudget;
|
||||
if (isNativeStructureFailure(failure))
|
||||
return nativeStructureConstraint(OPERATION, failure, input.path);
|
||||
if (
|
||||
!(failure instanceof BinaryResourceFailure) ||
|
||||
binaryResourceAllowance(failure, [
|
||||
MACHO_FUNCTION_STARTS_ENTRY_LIMIT,
|
||||
]) === null
|
||||
)
|
||||
return undefined;
|
||||
const { required } = failure.failure.limit;
|
||||
return parseLimitConstraint(OPERATION, "capacity", failure, {
|
||||
path: input.path,
|
||||
retryable: false,
|
||||
limit: {
|
||||
...machoFunctionStartsEntryLimit(failure.maximum_bytes),
|
||||
...(typeof required === "number"
|
||||
? { required_value: required }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
},
|
||||
fileSize: (failure) =>
|
||||
artifactFileCeilingConstraint(OPERATION, failure, FILE_CEILING, {
|
||||
max_file_bytes: input.max_file_bytes,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
if (completed !== undefined) primary.retainPartialObservation(completed);
|
||||
return projectStableArtifactFailure(
|
||||
cause,
|
||||
primary,
|
||||
input.path,
|
||||
MACHO_FUNCTION_STARTS_PROVIDER.id,
|
||||
OPERATION,
|
||||
snapshot,
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type {
|
||||
InspectMachoFunctionStartsInput,
|
||||
MachoFunctionStarts,
|
||||
} from "../../domain/native/machoFunctionStarts.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Stable read and Mach-O function-start decoding, independent of a disassembler session. */
|
||||
export interface MachoFunctionStartsPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close?(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectMachoFunctionStartsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<MachoFunctionStarts, AnalysisError>>;
|
||||
}
|
||||
@@ -208,6 +208,7 @@ export const createServer = (
|
||||
kernelBuildConfig,
|
||||
peLoadConfig,
|
||||
peUnwindRanges,
|
||||
machoFunctionStarts,
|
||||
peOverlay,
|
||||
binaryHardening,
|
||||
peCertificates,
|
||||
@@ -408,6 +409,7 @@ export const createServer = (
|
||||
kernelBuildConfig,
|
||||
peLoadConfig,
|
||||
peUnwindRanges,
|
||||
machoFunctionStarts,
|
||||
peOverlay,
|
||||
releaseExposure,
|
||||
binaryHardening,
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { NativeInitializersService } from "../application/binaryDiagnostics
|
||||
import type { PeCertificatesService } from "../application/binaryDiagnostics/PeCertificatesService.js";
|
||||
import type { PeImportsService } from "../application/binaryDiagnostics/PeImportsService.js";
|
||||
import type { PeLoadConfigService } from "../application/binaryDiagnostics/PeLoadConfigService.js";
|
||||
import type { MachoFunctionStartsService } from "../application/binaryDiagnostics/MachoFunctionStartsService.js";
|
||||
import type { PeUnwindRangesService } from "../application/binaryDiagnostics/PeUnwindRangesService.js";
|
||||
import type { PeOverlayService } from "../application/binaryDiagnostics/PeOverlayService.js";
|
||||
import type { PeResourcesService } from "../application/binaryDiagnostics/PeResourcesService.js";
|
||||
@@ -133,6 +134,12 @@ export const OFFLINE_INSPECTION_TOOL_BINDINGS = {
|
||||
run: (input, options) => service.inspect(input, options),
|
||||
},
|
||||
})) satisfies Bind<PeUnwindRangesService>,
|
||||
machoFunctionStarts: ((service) => ({
|
||||
inspect_macho_function_starts: {
|
||||
admission: "sdk",
|
||||
run: (input, options) => service.inspect(input, options),
|
||||
},
|
||||
})) satisfies Bind<MachoFunctionStartsService>,
|
||||
peOverlay: ((service) => ({
|
||||
inspect_pe_overlay: {
|
||||
admission: "application",
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
arm64FunctionStartsImage,
|
||||
functionStartAddresses,
|
||||
ARM64_DELTAS,
|
||||
X64_DELTAS,
|
||||
machoFunctionStartsUniversal,
|
||||
x64FunctionStartsImage,
|
||||
} from "../../src/native/apple/MachoFunctionStarts.fixture.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
expectAdapterErrorParity,
|
||||
parseMcpToolError,
|
||||
} from "../fixtures/mcpToolError.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
const hex = (value: bigint): string => `0x${value.toString(16)}`;
|
||||
|
||||
cliTest(
|
||||
"reads Mach-O function starts identically over CLI and MCP",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-macho-function-starts-cli-",
|
||||
);
|
||||
const path = join(root, "program");
|
||||
const bytes = arm64FunctionStartsImage();
|
||||
await writeFile(path, bytes);
|
||||
const result = await cli.run({
|
||||
arguments: [
|
||||
"inspect-macho-function-starts",
|
||||
path,
|
||||
"--kind",
|
||||
"starts",
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(result.json);
|
||||
expect(evidence.operation).toBe("inspect_macho_function_starts");
|
||||
expect(evidence.normalized_result.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
total_starts: 3,
|
||||
total_data_in_code: 3,
|
||||
});
|
||||
expect(
|
||||
evidence.normalized_result.starts.map((start) => start.vmaddr),
|
||||
).toEqual(functionStartAddresses(ARM64_DELTAS).map(hex));
|
||||
expect(evidence.normalized_result.data_in_code_entries).toEqual([]);
|
||||
|
||||
const call = await cli.sharedMcpCall!();
|
||||
const response = await call("inspect_macho_function_starts", {
|
||||
path,
|
||||
kind: "starts",
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const mcpEvidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
expect(mcpEvidence.normalized_result).toEqual(evidence.normalized_result);
|
||||
expect((await readFile(path)).equals(bytes)).toBe(true);
|
||||
|
||||
const universal = join(root, "universal");
|
||||
const fat = machoFunctionStartsUniversal(bytes, x64FunctionStartsImage());
|
||||
await writeFile(universal, fat);
|
||||
const selected = await cli.run({
|
||||
arguments: [
|
||||
"inspect-macho-function-starts",
|
||||
universal,
|
||||
"--architecture",
|
||||
"x86_64",
|
||||
"--json",
|
||||
],
|
||||
});
|
||||
expect(selected.exitCode, selected.stderr).toBe(0);
|
||||
const slice = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(selected.json);
|
||||
expect(slice.subject.identity).toMatchObject({
|
||||
format: "mach-o-universal",
|
||||
architecture: "x86_64",
|
||||
});
|
||||
expect(slice.normalized_result.starts.map((start) => start.vmaddr)).toEqual(
|
||||
functionStartAddresses(X64_DELTAS).map(hex),
|
||||
);
|
||||
|
||||
const truncated = join(root, "truncated");
|
||||
await writeFile(truncated, bytes.subarray(0, 20));
|
||||
const refused = await cli.run({
|
||||
arguments: ["inspect-macho-function-starts", truncated, "--json"],
|
||||
});
|
||||
expect(refused.exitCode).toBe(1);
|
||||
expect(refused.json).toMatchObject({
|
||||
details: { operation: "inspect_macho_function_starts", path: truncated },
|
||||
});
|
||||
const mcpRefused = await call("inspect_macho_function_starts", {
|
||||
path: truncated,
|
||||
});
|
||||
expect(mcpRefused.isError).toBe(true);
|
||||
expectAdapterErrorParity(
|
||||
parseMcpToolError(mcpRefused).error,
|
||||
refused.json,
|
||||
"inspect_macho_function_starts",
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -264,6 +264,7 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
["inspect_elf_debug_link", { path: "/tmp/prog", candidate_path: nul }],
|
||||
["inspect_native_initializers", { path: nul }],
|
||||
["inspect_elf_unwind_ranges", { path: nul }],
|
||||
["inspect_macho_function_starts", { path: nul }],
|
||||
["inspect_apple_ips", { path: nul }],
|
||||
["inspect_devicetree", { path: nul }],
|
||||
["inspect_kernel_module", { path: nul }],
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { open, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { createMachoFunctionStartsService } from "../../../src/composition/binaryDiagnostics/machoFunctionStarts.js";
|
||||
import {
|
||||
primaryAnalysisError,
|
||||
resolvedAnalysisError,
|
||||
} from "../../../src/domain/analysisErrorBase.js";
|
||||
import { parseEvidence } from "../../../src/domain/evidence.js";
|
||||
import { arm64FunctionStartsImage } from "../../../src/native/apple/MachoFunctionStarts.fixture.js";
|
||||
import {
|
||||
expectRetainedDescriptor,
|
||||
withDescriptorCloseFailure,
|
||||
} from "../../fixtures/descriptorCloseFailure.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
vi.mock(import("node:fs/promises"), { spy: true });
|
||||
|
||||
it("retains the verified function-start report across descriptor close failure and retry", async () => {
|
||||
const path = join(
|
||||
await createTestTempDirectory("rea-macho-function-starts-finalization-"),
|
||||
"program",
|
||||
);
|
||||
const bytes = arm64FunctionStartsImage();
|
||||
await writeFile(path, bytes);
|
||||
const sha256 = createHash("sha256").update(bytes).digest("hex");
|
||||
const service = createMachoFunctionStartsService();
|
||||
const real =
|
||||
await vi.importActual<typeof import("node:fs/promises")>(
|
||||
"node:fs/promises",
|
||||
);
|
||||
const cleanup: Parameters<typeof withDescriptorCloseFailure>[1] = {
|
||||
path,
|
||||
denied: true,
|
||||
handles: [],
|
||||
};
|
||||
const openFile = vi.mocked(open);
|
||||
openFile.mockImplementation(withDescriptorCloseFailure(real, cleanup).open);
|
||||
try {
|
||||
const result = await service.inspect({ path });
|
||||
if (result.ok) throw new Error("Expected retained descriptor cleanup");
|
||||
expectRetainedDescriptor(result, cleanup, "inspect_macho_function_starts");
|
||||
const primary = primaryAnalysisError(result.error);
|
||||
const partial = result.error.partialObservation;
|
||||
expect(parseEvidence(partial)).toMatchObject({
|
||||
operation: "inspect_macho_function_starts",
|
||||
subject: { identity: { format: "mach-o", sha256 }, local_path: path },
|
||||
normalized_result: {
|
||||
artifact: { path, bytes: bytes.length, sha256 },
|
||||
coverage: { total_starts: 3, total_data_in_code: 3 },
|
||||
},
|
||||
});
|
||||
cleanup.denied = false;
|
||||
await service.close();
|
||||
expect(cleanup.handles[0]?.fd).toBe(-1);
|
||||
expect(result.error.cleanupResources).toEqual([]);
|
||||
expect(resolvedAnalysisError(result.error)).toBe(primary);
|
||||
expect(primary.partialObservation).toBe(partial);
|
||||
} finally {
|
||||
cleanup.denied = false;
|
||||
openFile.mockReset();
|
||||
await service.close();
|
||||
}
|
||||
});
|
||||
@@ -41,6 +41,7 @@ const PATH_FIELDS = {
|
||||
inspect_elf_notes: ["path"],
|
||||
inspect_elf_debug_link: ["path", "candidate_path"],
|
||||
inspect_elf_unwind_ranges: ["path"],
|
||||
inspect_macho_function_starts: ["path"],
|
||||
inspect_kernel_module: ["path"],
|
||||
inspect_byte_entropy: ["path"],
|
||||
inspect_api_contract: ["path", "operations_path"],
|
||||
@@ -157,6 +158,7 @@ it("rejects one relative path field at a time on tools/list", async () => {
|
||||
"inspect_elf_debug_link.path",
|
||||
"inspect_elf_debug_link.candidate_path",
|
||||
"inspect_elf_unwind_ranges.path",
|
||||
"inspect_macho_function_starts.path",
|
||||
"inspect_kernel_module.path",
|
||||
"inspect_byte_entropy.path",
|
||||
"inspect_api_contract.path",
|
||||
|
||||
@@ -0,0 +1,204 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { toolContract } from "../../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
ARM64_DELTAS,
|
||||
arm64FunctionStartsImage,
|
||||
functionStartAddresses,
|
||||
machoFunctionStartsUniversal,
|
||||
x64FunctionStartsImage,
|
||||
} from "../../../src/native/apple/MachoFunctionStarts.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { fileInspectionTest } from "../../support/mcp/fileInspection.js";
|
||||
|
||||
const hex = (value: bigint): string => `0x${value.toString(16)}`;
|
||||
|
||||
fileInspectionTest(
|
||||
"advertises inspect_macho_function_starts and decodes one slice",
|
||||
async ({ client }) => {
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_macho_function_starts",
|
||||
);
|
||||
expect(advertised?.annotations).toMatchObject({
|
||||
readOnlyHint: false,
|
||||
idempotentHint: true,
|
||||
});
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-macho-function-starts-mcp-",
|
||||
);
|
||||
const path = join(root, "program");
|
||||
await writeFile(path, arm64FunctionStartsImage());
|
||||
const response = await client.callTool({
|
||||
name: "inspect_macho_function_starts",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const evidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
const report = evidence.normalized_result;
|
||||
expect(report.format).toBe("macho");
|
||||
expect(report.architecture).toBe("arm64");
|
||||
expect(report.starts.map((start) => start.vmaddr)).toEqual(
|
||||
functionStartAddresses(ARM64_DELTAS).map(hex),
|
||||
);
|
||||
expect(report.data_in_code_entries[2]).toMatchObject({
|
||||
kind: 0x42,
|
||||
owner: { index: 2 },
|
||||
});
|
||||
expect(report.coverage.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
|
||||
fileInspectionTest("pages one function start over MCP", async ({ client }) => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-macho-function-starts-mcp-page-",
|
||||
);
|
||||
const path = join(root, "program");
|
||||
await writeFile(path, arm64FunctionStartsImage());
|
||||
const response = await client.callTool({
|
||||
name: "inspect_macho_function_starts",
|
||||
arguments: { path, kind: "starts", offset: 1, limit: 1 },
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const evidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
expect(
|
||||
evidence.normalized_result.starts.map((start) => start.vmaddr),
|
||||
).toEqual([hex(functionStartAddresses(ARM64_DELTAS)[1]!)]);
|
||||
expect(evidence.normalized_result.page).toMatchObject({
|
||||
kind: "starts",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
returned_starts: 1,
|
||||
total_starts: 3,
|
||||
next_starts_offset: 2,
|
||||
returned_data: 0,
|
||||
next_data_offset: null,
|
||||
});
|
||||
});
|
||||
|
||||
fileInspectionTest(
|
||||
"reads the selected universal slice over MCP",
|
||||
async ({ client }) => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-macho-function-starts-mcp-fat-",
|
||||
);
|
||||
const path = join(root, "universal");
|
||||
await writeFile(
|
||||
path,
|
||||
machoFunctionStartsUniversal(
|
||||
arm64FunctionStartsImage(),
|
||||
x64FunctionStartsImage(),
|
||||
),
|
||||
);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_macho_function_starts",
|
||||
arguments: { path, architecture: "arm64", limit: 0 },
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const evidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
expect(evidence.subject.identity).toMatchObject({
|
||||
format: "mach-o-universal",
|
||||
architecture: "arm64",
|
||||
});
|
||||
expect(evidence.normalized_result.coverage).toMatchObject({
|
||||
status: "complete",
|
||||
total_starts: 3,
|
||||
total_data_in_code: 3,
|
||||
});
|
||||
expect(evidence.normalized_result.starts).toEqual([]);
|
||||
expect(evidence.normalized_result.selected_slice).toMatchObject({
|
||||
offset: 0x1000,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
/** Rewrite the arm64 slice's LC_FUNCTION_STARTS `dataoff` and `datasize`. */
|
||||
const redirectStarts = (
|
||||
image: Buffer,
|
||||
dataoff: number,
|
||||
datasize: number,
|
||||
): Buffer => {
|
||||
const copy = Buffer.from(image);
|
||||
const count = copy.readUInt32LE(16);
|
||||
let at = 32;
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const command = copy.readUInt32LE(at);
|
||||
if (command === 0x26) {
|
||||
copy.writeUInt32LE(dataoff, at + 8);
|
||||
copy.writeUInt32LE(datasize, at + 12);
|
||||
return copy;
|
||||
}
|
||||
at += copy.readUInt32LE(at + 4);
|
||||
}
|
||||
throw new Error("fixture has no LC_FUNCTION_STARTS");
|
||||
};
|
||||
|
||||
fileInspectionTest(
|
||||
"keeps Evidence ranges inside the selected universal slice",
|
||||
async ({ client }) => {
|
||||
const root = await createTestTempDirectory(
|
||||
"rea-macho-function-starts-mcp-slice-range-",
|
||||
);
|
||||
const arm = arm64FunctionStartsImage();
|
||||
const ranges = async (image: Buffer, name: string) => {
|
||||
const path = join(root, name);
|
||||
await writeFile(
|
||||
path,
|
||||
machoFunctionStartsUniversal(image, x64FunctionStartsImage()),
|
||||
);
|
||||
const response = await client.callTool({
|
||||
name: "inspect_macho_function_starts",
|
||||
arguments: { path, architecture: "arm64", limit: 0 },
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const evidence = toolContract(
|
||||
"inspect_macho_function_starts",
|
||||
).outputSchema.parse(response.structuredContent);
|
||||
return {
|
||||
report: evidence.normalized_result,
|
||||
ranges: evidence.locations.filter(
|
||||
(location) => location.kind === "file-offset-range",
|
||||
),
|
||||
};
|
||||
};
|
||||
// The arm64 slice spans [0x1000, 0x6000); the x86_64 slice starts at 0x6000.
|
||||
const outside = await ranges(redirectStarts(arm, arm.length, 4), "past");
|
||||
expect(outside.report.function_starts).toMatchObject({
|
||||
dataoff: arm.length,
|
||||
datasize: 4,
|
||||
file_offset: 0x1000 + arm.length,
|
||||
});
|
||||
expect(outside.report.coverage.status).toBe("partial");
|
||||
expect(
|
||||
outside.ranges.every(
|
||||
(range) => "end" in range && range.end <= 0x1000 + arm.length,
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
outside.ranges.some(
|
||||
(range) => "start" in range && range.start === 0x1000 + arm.length,
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const straddling = await ranges(
|
||||
redirectStarts(arm, arm.length - 0x100, 0x400),
|
||||
"straddling",
|
||||
);
|
||||
expect(straddling.report.function_starts).toMatchObject({
|
||||
dataoff: arm.length - 0x100,
|
||||
datasize: 0x400,
|
||||
});
|
||||
expect(straddling.ranges).toContainEqual({
|
||||
kind: "file-offset-range",
|
||||
start: 0x1000 + arm.length - 0x100,
|
||||
end: 0x1000 + arm.length,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -143,6 +143,9 @@ export const PROVIDER_CAPABILITY_CONFORMANCE: Readonly<
|
||||
peImports: { cases: ["tests/acceptance/peImportsCli.test.ts"] },
|
||||
peLoadConfig: { cases: ["tests/acceptance/peLoadConfigCli.test.ts"] },
|
||||
peUnwindRanges: { cases: ["tests/acceptance/peUnwindRangesCli.test.ts"] },
|
||||
machoFunctionStarts: {
|
||||
cases: ["tests/acceptance/machoFunctionStartsCli.test.ts"],
|
||||
},
|
||||
peOverlay: { cases: ["tests/acceptance/peOverlayCli.test.ts"] },
|
||||
peResources: { cases: ["tests/acceptance/applications/peResources.test.ts"] },
|
||||
nugetNupkg: { cases: ["tests/acceptance/nugetNupkgCli.test.ts"] },
|
||||
|
||||
@@ -1567,6 +1567,15 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly<
|
||||
),
|
||||
typedFailures("src/native/pe/PeUnwindRangesProvider.test.ts"),
|
||||
),
|
||||
"rea-macho-function-starts": inProcess(
|
||||
covered(
|
||||
test(
|
||||
"tests/acceptance/machoFunctionStartsCli.test.ts",
|
||||
"reads Mach-O function starts identically over CLI and MCP",
|
||||
),
|
||||
),
|
||||
typedFailures("src/native/apple/MachoFunctionStartsProvider.test.ts"),
|
||||
),
|
||||
"rea-playwright-browser-scenario": {
|
||||
ownership: "process",
|
||||
stages: {
|
||||
|
||||
Reference in new issue
Block a user