mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 21:46:01 +00:00
* 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>
190 lines
6.1 KiB
TypeScript
190 lines
6.1 KiB
TypeScript
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 };
|
|
};
|