Files
reverse-engineering-anything/src/go/GoStringLiterals.test.ts
T
61fb6cf68a 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>
2026-11-27 20:29:07 +00:00

875 lines
26 KiB
TypeScript

import { readGoFixture } from "../../tests/fixtures/go/image.js";
import type { FileMapping } from "../domain/virtualFileMapping.js";
import { expect, it } from "vitest";
import { GO_ANALYSIS_BUDGET_DEFAULTS } from "../domain/go/goBinary.js";
import type {
BinaryContainer,
ImageSection,
LoadRegion,
} from "../domain/binaryContainer.js";
import { createGoRodataStringFixture } from "../../tests/fixtures/go/rodataStringImage.js";
import { readBinaryContainerFromReader } from "../domain/native/readBinaryContainer.js";
import { recoverGoStringLiteralsFromReader } from "./GoStringLiterals.js";
import { bufferByteSource } from "../domain/byteSource.js";
const recoverStringFixture = (
bytes: Buffer,
container: BinaryContainer,
budgets?: Parameters<typeof recoverGoStringLiteralsFromReader>[2],
checkActive?: () => void,
) =>
recoverGoStringLiteralsFromReader(
bufferByteSource(bytes, 4096),
container,
budgets,
checkActive,
);
const DEFAULT_AGGREGATE_BYTES = 512 * 1024;
const DEFAULT_LITERAL_BYTES = 4096;
const LITERALS = [
"ListResourceProviders",
"genai",
"https://example.invalid/v1",
] as const;
const PACKED_RODATA = Buffer.concat(
LITERALS.map((value) => Buffer.from(value, "utf8")),
);
it.each([
{ format: "elf", bits: 64, byteOrder: "little" },
{ format: "elf", bits: 32, byteOrder: "little" },
{ format: "elf", bits: 64, byteOrder: "big" },
{ format: "pe", bits: 64, byteOrder: "little" },
{ format: "pe", bits: 32, byteOrder: "little" },
{ format: "macho", bits: 64, byteOrder: "little" },
{ format: "macho", bits: 32, byteOrder: "little" },
] as const)(
"recovers exact non-NUL-terminated slices in $format ($bits-bit $byteOrder)",
async ({ format, bits, byteOrder }) => {
const width = bits / 8;
const firstLen = Buffer.byteLength(LITERALS[0]);
const secondLen = Buffer.byteLength(LITERALS[1]);
const thirdLen = Buffer.byteLength(LITERALS[2]);
const baseRo = 0x102000n;
const fixture = createGoRodataStringFixture({
format,
bits,
byteOrder,
rodata: PACKED_RODATA,
headers: [
{
section: "data",
offsetInSection: width,
ptr: baseRo + BigInt(firstLen + secondLen),
len: BigInt(thirdLen),
},
{
section: "data",
offsetInSection: width * 4,
ptr: baseRo,
len: BigInt(firstLen),
},
{
section: "data",
offsetInSection: width * 7,
ptr: baseRo + BigInt(firstLen),
len: BigInt(secondLen),
},
{
section: "data",
offsetInSection: width * 10,
ptr: baseRo + BigInt(firstLen),
len: BigInt(secondLen),
},
],
});
expect(
(await readGoFixture(fixture.bytes)).string_literals,
).toBeUndefined();
const recovered = (
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
})
).string_literals;
expect(recovered).toEqual({
evidence_kind: "inferred",
discovered_count: 3,
aggregate_bytes: PACKED_RODATA.length,
max_items: 2000,
truncated: false,
items: [
{
value: "ListResourceProviders",
location: { offset: fixture.rodataOffset, bytes: firstLen },
first_header_offset: fixture.dataOffset + width * 4,
reference_count: 1,
},
{
value: "genai",
location: {
offset: fixture.rodataOffset + firstLen,
bytes: secondLen,
},
first_header_offset: fixture.dataOffset + width * 7,
reference_count: 2,
},
{
value: "https://example.invalid/v1",
location: {
offset: fixture.rodataOffset + firstLen + secondLen,
bytes: thirdLen,
},
first_header_offset: fixture.dataOffset + width,
reference_count: 1,
},
],
});
},
);
it.each([
{ label: "sectionless ELF", sectionless: true, corruptElfShstrtab: false },
{
label: "ELF with unreadable .shstrtab",
sectionless: false,
corruptElfShstrtab: true,
},
])("recovers literals from $label via load regions", async (mode) => {
const baseRo = 0x102000n;
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: PACKED_RODATA,
sectionless: mode.sectionless,
corruptElfShstrtab: mode.corruptElfShstrtab,
headers: [
{
section: "data",
offsetInSection: 0,
ptr: baseRo,
len: BigInt(LITERALS[0].length),
},
{
section: "data",
offsetInSection: 16,
ptr: baseRo + BigInt(LITERALS[0].length),
len: BigInt(LITERALS[1].length),
},
],
});
const recovered = (
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
})
).string_literals;
expect(recovered?.items.map((item) => item.value)).toEqual([
"ListResourceProviders",
"genai",
]);
});
it("recovers only admitted printable ranges at the default literal length", async () => {
const parts = [
Buffer.from("café\t日本語\n"),
Buffer.from([0xff, 0xfe, 0x41]), // Malformed UTF-8.
Buffer.from("bad\0str"),
Buffer.from([0xc2, 0x85]), // C1 control.
Buffer.from([0xef, 0xbf, 0xbf]), // Noncharacter.
Buffer.alloc(DEFAULT_LITERAL_BYTES, 0x61),
Buffer.alloc(DEFAULT_LITERAL_BYTES + 1, 0x62),
];
const base = 0x102000n;
let next = base;
const headers = parts.map((part, index) => {
const len = BigInt(part.length);
const ptr = next;
next += len;
return { section: "data" as const, offsetInSection: index * 16, ptr, len };
});
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: Buffer.concat([...parts, Buffer.from("tail")]),
secondRodata: Buffer.from("across-boundary"),
headers: [
...headers,
{ section: "data", offsetInSection: 112, ptr: base, len: 0n },
{ section: "data", offsetInSection: 128, ptr: next, len: 10n },
{ section: "data", offsetInSection: 144, ptr: next + 4n, len: 23n },
{ section: "data", offsetInSection: 164, ptr: next, len: 4n },
{ section: "text", offsetInSection: 0, ptr: next, len: 4n },
{ section: "data", offsetInSection: 192, ptr: 0x101000n, len: 4n },
],
});
fixture.bytes.write("CODE", 0x1000);
const recovered = (
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
})
).string_literals;
expect(recovered?.items.map((item) => item.value)).toEqual([
"café\t日本語\n",
"a".repeat(DEFAULT_LITERAL_BYTES),
]);
expect(recovered).toMatchObject({
discovered_count: 2,
truncated: true,
limits_reached: ["max_string_literal_bytes"],
});
});
it.each(["length", "candidate count"] as const)(
"reports a %s limit only when it excludes a literal candidate",
async (limit) => {
const rodata = Buffer.alloc(64);
rodata.write("kept", 32);
rodata.write("sixteen letters!", 48);
const base = 0x102000n;
const fixture = createGoRodataStringFixture({
format: "elf",
rodata,
headers: [
{ section: "data", offsetInSection: 0, ptr: base + 32n, len: 4n },
limit === "length"
? { section: "rodata", offsetInSection: 0, ptr: base, len: 16n }
: { section: "data", offsetInSection: 16, ptr: base + 40n, len: 4n },
],
});
const parameter =
limit === "length" ? "max_string_literal_bytes" : "max_string_candidates";
const inspect = async () =>
(
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
budgets: { [parameter]: limit === "length" ? 8 : 1 },
})
).string_literals;
expect(await inspect()).toEqual({
evidence_kind: "inferred",
discovered_count: 1,
aggregate_bytes: 4,
max_items: 2000,
truncated: false,
items: [
{
value: "kept",
location: { offset: fixture.rodataOffset + 32, bytes: 4 },
first_header_offset: fixture.dataOffset,
reference_count: 1,
},
],
});
if (limit === "length")
fixture.bytes.writeBigUInt64LE(base + 48n, fixture.rodataOffset);
else fixture.bytes.write("next", fixture.rodataOffset + 40);
expect(await inspect()).toMatchObject({
discovered_count: 1,
truncated: true,
limits_reached: [parameter],
});
},
);
it("reports a complete candidate count at the 512 KiB output cap", async () => {
const chunks = Array.from({ length: 130 }, (_, index) =>
Buffer.from(
`${String(index).padStart(4, "0")}:${"x".repeat(DEFAULT_LITERAL_BYTES - 5)}`,
"utf8",
),
);
const rodata = Buffer.concat(chunks);
const baseRo = 0x102000n;
const fixture = createGoRodataStringFixture({
format: "macho",
rodata,
headers: chunks.map((chunk, index) => ({
section: "data" as const,
offsetInSection: index * 16,
ptr: baseRo + BigInt(index * chunk.length),
len: BigInt(chunk.length),
})),
});
const cappedByBytes = await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
budgets: { max_string_literals: 500 },
});
expect(cappedByBytes.string_literals).toMatchObject({
discovered_count: 130,
max_items: 500,
aggregate_bytes: DEFAULT_AGGREGATE_BYTES,
truncated: true,
limits_reached: ["max_string_bytes"],
});
expect(cappedByBytes.string_literals?.items).toHaveLength(
DEFAULT_AGGREGATE_BYTES / DEFAULT_LITERAL_BYTES,
);
});
it.each([false, true])(
"counts physical headers once in file order across reversed sections and overlapping PT_LOAD (corruptShstrtab=%s)",
async (corruptElfShstrtab) => {
const baseRo = 0x102000n;
const firstLen = Buffer.byteLength(LITERALS[0]);
const secondLen = Buffer.byteLength(LITERALS[1]);
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: PACKED_RODATA,
corruptElfShstrtab,
elfSplitReversedDataSections: true,
headers: [
{
section: "data",
offsetInSection: 0x200,
ptr: baseRo,
len: BigInt(firstLen),
},
{
section: "data",
offsetInSection: 0x40,
ptr: baseRo,
len: BigInt(firstLen),
},
{
section: "data",
offsetInSection: 0x60,
ptr: baseRo + BigInt(firstLen),
len: BigInt(secondLen),
},
],
});
const recovered = (
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
})
).string_literals;
expect(recovered?.items).toEqual([
{
value: "ListResourceProviders",
location: { offset: fixture.rodataOffset, bytes: firstLen },
first_header_offset: fixture.dataOffset + 0x40,
reference_count: 2,
},
{
value: "genai",
location: {
offset: fixture.rodataOffset + firstLen,
bytes: secondLen,
},
first_header_offset: fixture.dataOffset + 0x60,
reference_count: 1,
},
]);
},
);
it("rejects invisible/bidi Cf format controls while keeping U+200C ZWNJ, U+200D ZWJ and visible Unicode", async () => {
const zeroWidthSpace = Buffer.from("zero\u200Bwidth", "utf8");
const rtlOverride = Buffer.from("rtl\u202Eoverride", "utf8");
const byteOrderMark = Buffer.from("\uFEFFbom", "utf8");
const softHyphen = Buffer.from("soft\u00ADhyphen", "utf8");
const persianZwnj = Buffer.from("می\u200cخواهم", "utf8");
const zwjEmoji = Buffer.from("👩\u200d💻", "utf8");
const visibleUnicode = Buffer.from("visible-café", "utf8");
const slices = [
zeroWidthSpace,
persianZwnj,
rtlOverride,
zwjEmoji,
byteOrderMark,
softHyphen,
visibleUnicode,
];
let cursor = 0;
const headers = slices.map((slice, index) => {
const header = {
section: "data" as const,
offsetInSection: index * 16,
ptr: 0x102000n + BigInt(cursor),
len: BigInt(slice.length),
};
cursor += slice.length;
return header;
});
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: Buffer.concat(slices),
headers,
});
const recovered = (
await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
})
).string_literals;
expect(recovered?.items.map((item) => item.value)).toEqual([
"می\u200cخواهم",
"👩\u200d💻",
"visible-café",
]);
expect(recovered?.truncated).toBe(false);
});
it("bounds rejected-slice caching across thousands of distinct NUL slices without dropping later literals", async () => {
const rejectedCount = 6000;
const pageBytes = 4096;
const nulBlob = Buffer.alloc(2 * pageBytes);
const survivor = Buffer.from("recovered-after-nul-flood", "utf8");
const rodata = Buffer.concat([nulBlob, survivor]);
const baseRo = 0x102000n;
const headers = Array.from({ length: rejectedCount }, (_, index) => ({
section: "data" as const,
offsetInSection: index * 8,
ptr: baseRo + BigInt(Math.floor(index / 2) + (index % 2) * pageBytes),
len: 1n,
}));
headers.push(
{
section: "data",
offsetInSection: rejectedCount * 8,
ptr: baseRo,
len: 1n,
},
{
section: "data",
offsetInSection: (rejectedCount + 1) * 8,
ptr: baseRo + BigInt(nulBlob.length),
len: BigInt(survivor.length),
},
);
const fixture = createGoRodataStringFixture({
format: "elf",
bits: 32,
rodata,
dataSize: (rejectedCount + 8) * 8,
headers,
});
const source = bufferByteSource(fixture.bytes, 4096);
const container = await readBinaryContainerFromReader(
source,
"inspect_go_binary",
async () => {},
);
let firstTargetReads = 0;
const recovered = await recoverGoStringLiteralsFromReader(
{
...source,
readRange: (offset, length) => {
if (offset === fixture.rodataOffset && length === 1)
firstTargetReads += 1;
return source.readRange(offset, length);
},
},
container,
);
// Alternating pages bypass read-ahead. The oldest rejected candidate is
// read again after the bounded rejection cache forgets it.
expect(firstTargetReads).toBe(2);
expect(recovered).toEqual({
evidence_kind: "inferred",
discovered_count: 1,
aggregate_bytes: survivor.length,
max_items: 2000,
truncated: false,
items: [
{
value: "recovered-after-nul-flood",
location: {
offset: fixture.rodataOffset + nulBlob.length,
bytes: survivor.length,
},
first_header_offset: fixture.dataOffset + (rejectedCount + 1) * 8,
reference_count: 1,
},
],
});
});
it("indexes 25,000 Mach-O load regions and sections without quadratic stalls and honors region and section cancellation", async () => {
const count = 25_000;
const slotBytes = 16;
const bytes = Buffer.alloc((count + 1) * slotBytes);
const literal = "macho-indexed";
const literalBytes = Buffer.from(literal, "utf8");
literalBytes.copy(bytes, 0);
const mappings: FileMapping[] = [];
const loadRegions: LoadRegion[] = [];
const sections: ImageSection[] = [];
for (let index = 0; index < count; index += 1) {
const offset = index * slotBytes;
const address = 0x100000n + BigInt(index) * 0x2000n;
const mapping: FileMapping = { address, offset, size: slotBytes };
const readable = index !== count - 2;
mappings.push(mapping);
loadRegions.push({
mapping,
memory_size: BigInt(slotBytes),
read: readable,
write: index > 0,
execute: false,
});
sections.push({
format: "macho",
name: index === 0 ? "__TEXT,__rodata" : "__DATA,__data",
section_name: index === 0 ? "__rodata" : "__data",
type: 0,
flags: 0,
address,
declared_range: { offset: BigInt(offset), size: BigInt(slotBytes) },
segment_mapping: mapping,
segment_unmapped: false,
on_disk: true,
relocations: { offset: 0, count: 0 },
offset,
size: slotBytes,
file_backed: true,
read_only: index === 0,
compressed: false,
});
}
const roAddr = 0x100000n;
const unreadableHeaderOffset = (count - 2) * slotBytes;
bytes.writeBigUInt64LE(roAddr, unreadableHeaderOffset);
bytes.writeBigUInt64LE(
BigInt(literalBytes.length),
unreadableHeaderOffset + 8,
);
const validHeaderOffset = (count - 1) * slotBytes;
bytes.writeBigUInt64LE(roAddr, validHeaderOffset);
bytes.writeBigUInt64LE(BigInt(literalBytes.length), validHeaderOffset + 8);
const container: BinaryContainer = {
format: "macho",
macho_cpu_type: 0x0100000c,
macho_file_type: 2,
macho_segments: [],
architecture: "arm64",
bits: 64,
byte_order: "little",
mappings,
load_regions: loadRegions,
zero_fills: [],
sections,
};
// Indexing reads each mapping, load region and section once or twice
// (100,000 reads here); a per-lookup scan reads 25,000 regions per lookup.
let tableReads = 0;
const budget = 8 * count;
const counted = <T extends object>(table: readonly T[]): readonly T[] =>
new Proxy(table, {
get(target, property, receiver) {
if (
typeof property === "string" &&
/^\d+$/u.test(property) &&
++tableReads > budget
)
throw new Error("Container table read budget exceeded");
return Reflect.get(target, property, receiver) as unknown;
},
});
const recovered = await recoverStringFixture(bytes, {
...container,
mappings: counted(mappings),
load_regions: counted(loadRegions),
sections: counted(sections),
} as BinaryContainer);
expect(tableReads).toBeLessThanOrEqual(budget);
expect(recovered.items).toEqual([
{
value: literal,
location: { offset: 0, bytes: literalBytes.length },
first_header_offset: validHeaderOffset,
reference_count: 1,
},
]);
let inRegionLoop = false;
let observedRegions = 0;
let regionCancelChecks = 0;
let inSectionLoop = false;
let observedSections = 0;
const trackedLoadRegions = new Proxy(loadRegions, {
get(target, property, receiver) {
if (typeof property === "string" && /^\d+$/u.test(property)) {
inRegionLoop = true;
observedRegions += 1;
}
return Reflect.get(target, property, receiver);
},
});
const trackedSections = new Proxy(sections, {
get(target, property, receiver) {
if (typeof property === "string" && /^\d+$/u.test(property)) {
inSectionLoop = true;
observedSections += 1;
}
return Reflect.get(target, property, receiver);
},
});
await expect(
recoverStringFixture(
bytes,
{
...container,
load_regions: trackedLoadRegions,
sections: trackedSections,
},
GO_ANALYSIS_BUDGET_DEFAULTS,
() => {
if (inRegionLoop && !inSectionLoop) {
regionCancelChecks += 1;
if (regionCancelChecks >= 10)
throw new Error("cancelled during region indexing");
}
},
),
).rejects.toThrow("cancelled during region indexing");
expect(observedRegions).toBeGreaterThan(0);
expect(observedRegions).toBeLessThan(count);
expect(observedSections).toBe(0);
inSectionLoop = false;
observedSections = 0;
await expect(
recoverStringFixture(
bytes,
{ ...container, sections: trackedSections },
GO_ANALYSIS_BUDGET_DEFAULTS,
() => {
if (inSectionLoop) throw new Error("cancelled during section indexing");
},
),
).rejects.toThrow("cancelled during section indexing");
expect(observedSections).toBeLessThan(count);
});
it.each([
{ target: "data", mode: "single", expected: ["macho-span-check"] },
{ target: "data", mode: "touching", expected: ["macho-span-check"] },
{ target: "data", mode: "overlapping", expected: ["macho-span-check"] },
{ target: "data", mode: "gap", expected: [] },
{ target: "data", mode: "unreadable-tail", expected: [] },
{ target: "rodata", mode: "single", expected: ["macho-span-check"] },
{ target: "rodata", mode: "touching", expected: ["macho-span-check"] },
{ target: "rodata", mode: "overlapping", expected: ["macho-span-check"] },
{ target: "rodata", mode: "gap", expected: [] },
{ target: "rodata", mode: "unreadable-tail", expected: [] },
] as const)(
"requires contiguous readable Mach-O load_regions for $target ($mode)",
async ({ target, mode, expected }) => {
const literal = "macho-span-check";
const bytes = Buffer.alloc(32);
bytes.write(literal, 0, "utf8");
const roAddr = 0x100000n;
const dataAddr = 0x200000n;
bytes.writeBigUInt64LE(roAddr, 16);
bytes.writeBigUInt64LE(16n, 24);
const buildRegions = (
address: bigint,
offset: number,
write: boolean,
kind: "single" | "touching" | "overlapping" | "gap" | "unreadable-tail",
): LoadRegion[] => {
const region = (
delta: number,
size: number,
read: boolean,
): LoadRegion => ({
mapping: {
address: address + BigInt(delta),
offset: offset + delta,
size,
},
memory_size: BigInt(size),
read,
write,
execute: false,
});
if (kind === "single") return [region(0, 16, true)];
if (kind === "touching") return [region(0, 8, true), region(8, 8, true)];
if (kind === "overlapping")
return [region(0, 12, true), region(4, 12, true)];
if (kind === "gap") return [region(0, 6, true), region(10, 6, true)];
return [region(0, 8, true), region(8, 8, false)];
};
const roMapping: FileMapping = { address: roAddr, offset: 0, size: 16 };
const dataMapping: FileMapping = {
address: dataAddr,
offset: 16,
size: 16,
};
const container: BinaryContainer = {
format: "macho",
macho_cpu_type: 0x0100000c,
macho_file_type: 2,
macho_segments: [],
architecture: "arm64",
bits: 64,
byte_order: "little",
mappings: [roMapping, dataMapping],
load_regions: [
...buildRegions(
roAddr,
0,
false,
target === "rodata" ? mode : "single",
),
...buildRegions(
dataAddr,
16,
true,
target === "data" ? mode : "single",
),
],
zero_fills: [],
sections: [
{
format: "macho",
name: "__TEXT,__rodata",
section_name: "__rodata",
type: 0,
flags: 0,
address: roAddr,
declared_range: { offset: 0n, size: 16n },
segment_mapping: roMapping,
segment_unmapped: false,
on_disk: true,
relocations: { offset: 0, count: 0 },
offset: 0,
size: 16,
file_backed: true,
read_only: true,
compressed: false,
},
{
format: "macho",
name: "__DATA,__data",
section_name: "__data",
type: 0,
flags: 0,
address: dataAddr,
declared_range: { offset: 16n, size: 16n },
segment_mapping: dataMapping,
segment_unmapped: false,
on_disk: true,
relocations: { offset: 0, count: 0 },
offset: 16,
size: 16,
file_backed: true,
read_only: false,
compressed: false,
},
],
};
const recovered = await recoverStringFixture(bytes, container);
expect(recovered.items.map((item) => item.value)).toEqual(expected);
},
);
it("recovers longer literals with a selected budget without conflating offset/length identities", async () => {
const fixture = createGoRodataStringFixture({
format: "elf",
rodata: Buffer.alloc(9000, 0x61),
headers: [
{ section: "data", offsetInSection: 0, ptr: 0x102000n, len: 9000n },
{ section: "data", offsetInSection: 16, ptr: 0x102000n, len: 808n },
{ section: "data", offsetInSection: 32, ptr: 0x102001n, len: 808n },
],
});
const limited = await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
});
expect(limited.string_literals).toMatchObject({
truncated: true,
limits_reached: ["max_string_literal_bytes"],
});
const recovered = await readGoFixture(fixture.bytes, {
includeStringLiterals: true,
budgets: { max_string_literal_bytes: 9000 },
});
expect(recovered.string_literals).toMatchObject({
truncated: false,
discovered_count: 3,
});
expect(
recovered.string_literals?.items.map((item) => [
item.location.offset,
item.location.bytes,
item.reference_count,
]),
).toEqual([
[fixture.rodataOffset, 808, 1],
[fixture.rodataOffset, 9000, 1],
[fixture.rodataOffset + 1, 808, 1],
]);
});
it("charges and reads only the admitted bytes of distant short string candidates", async () => {
const rodata = Buffer.alloc(256 * 1024);
const firstHeader = 64 * 1024 - 8;
const placements = [127, 128 * 1024 + 127, 128, 128 * 1024 + 128];
for (const [index, offset] of placements.entries())
rodata[offset] = 0x41 + index;
const fixture = createGoRodataStringFixture({
format: "elf",
rodata,
dataSize: firstHeader + placements.length * 16,
headers: placements.map((offset, index) => ({
section: "data",
offsetInSection: firstHeader + index * 16,
ptr: 0x102000n + BigInt(offset),
len: 1n,
})),
});
const { bytes, rodataOffset, dataOffset } = fixture;
let payloadBytes = 0;
const readRange = async (offset: number, length: number) => {
const start = Math.max(offset, rodataOffset);
const end = Math.min(offset + length, rodataOffset + rodata.length);
if (start < end) payloadBytes += end - start;
return bytes.subarray(offset, offset + length);
};
const container = await readBinaryContainerFromReader(
bufferByteSource(bytes, 4096),
"inspect_go_binary",
async () => {},
);
const result = await recoverGoStringLiteralsFromReader(
{ size: bytes.length, readRange },
container,
);
expect(result).toMatchObject({
discovered_count: 4,
aggregate_bytes: 4,
truncated: false,
});
expect(result.items).toEqual(
[0, 2, 1, 3].map((index) => ({
value: String.fromCharCode(0x41 + index),
location: { offset: rodataOffset + placements[index]!, bytes: 1 },
first_header_offset: dataOffset + firstHeader + index * 16,
reference_count: 1,
})),
);
// Read-only data is also scanned for headers. Charge every intersecting read,
// including any page prefetch whose start precedes the actual target.
expect(payloadBytes).toBeGreaterThanOrEqual(rodata.length);
expect(payloadBytes).toBeLessThanOrEqual(
rodata.length + placements.length * 2,
);
});