Files
reverse-engineering-anything/tests/boundary/providers/native/objcClassMetadataFallback.test.ts
T
morluto 557bf41c2c refactor(macho): select slices through one owner with typed refusals (#10874)
* refactor(macho): name load-command codes through the shared LC table

* refactor(macho): name version-min and string commands through the shared tables

* refactor(parsers): report XML, web artifact and Mach-O failures through ParseFailure (#10760)

* refactor(parsers): report XML, web artifact and Mach-O failures through ParseFailure

* refactor(xml): type XML parse failures as malformed or unsupported only

* refactor(parsers): catch per-format document and source failure classes (#10794)

* refactor(parsers): report apktool strings and XML plist source failures through ParseFailure

* refactor(apktool): drop the unused ParseFailureError import

* refactor(native): select ELF sections through the keyed owner

* test(native): pin returned exports and versions for repeated version sections

* refactor(nativeaot): read neither of repeated frozen object regions (#10790)

* refactor(nativeaot): read neither of repeated frozen object regions through the keyed owner

* refactor(parsers): retire every first-match section lookup (#10793)

* fix(nativeaot): report an ambiguous frozen object region as partial (#10812)

* refactor(native): select program headers and load commands through the keyed owner (#10827)

* refactor(native): select the GOT base and dependency segments through the keyed owner (#10847)

* refactor(native): select the GOT base and dependency segments through the keyed owner

resolveGotBase selects the SHT_DYNAMIC section and the allocated .got.plt/.got sections with uniqueKeyed, so a repeat leaves the GOT base unknown instead of taking the first match; elfDependencies reads PT_LOAD segments through the same keyed program table as PT_DYNAMIC. A new keyed-first-match guard recognizes a find/findLast or filter-then-[0] whose predicate compares a key field, whatever the table is called; existing matches are baselined. The unwind fixture can declare PT_DYNAMIC headers and repeated .dynamic/.got.plt sections.

* test(native): pin the PT_DYNAMIC path and destructured keyed lookups

The keyed-first-match guard moves to scripts/verify/keyed-first-match.mjs with focused tests, and now recognizes a destructured key in any position and a destructured filter predicate. The single PT_DYNAMIC unwind test declares .dynamic as SHT_PROGBITS so only the program header supplies DT_PLTGOT, and asserts the resolved ranges.

* fix(macho): refuse repeated chained-fixup and dyld-info tables (#10850)

parseMachoLayout kept the last LC_DYLD_CHAINED_FIXUPS range and merged the rebase/bind streams of every LC_DYLD_INFO(_ONLY) command. A repeat now refuses the slice as malformed. NativeMachoInspection's chained import-name reader already declined repeated LC_DYLD_CHAINED_FIXUPS; that rule is now covered by a test.

* refactor(parsers): retire the Mach-O, source-map, NDJSON and managed-graph failure classes (#10818)

* refactor(parsers): retire the Mach-O, source-map, NDJSON and managed-graph failure classes

* refactor(plist): report property-list and keyed-archive failures through ParseFailure (#10822)

* refactor(plist): report property-list and keyed-archive failures through ParseFailure

* refactor(kuna): report Kuna document failures through ParseFailure (#10824)

* refactor(kuna): report Kuna document failures through ParseFailure

* test(kuna): pin the limit and malformed facts of Kuna document failures

* refactor(plist): report plist decode budgets through ParseFailure (#10842)

* refactor(plist): report plist decode budgets through ParseFailure

The plist preflight owner throws a ParseFailure limit (plist-decode-bytes) for its byte budget, the shared PlistNestingLimitError for nesting depth, and a malformed failure for a reference cycle, instead of a per-format PropertyListDecodeBudgetFailure whose meaning each caller re-mapped through a fail callback. The fail option, PropertyListDecodeBudgetFailure and interfaceBuilderDecodeBudgetFailure are removed; the parser-format-failure-class baseline reaches zero.

* refactor(plist): report keyed-archive allowances as typed limit failures (#10844)

keyedArchive.ts and decodeKeyedArchiveBytes throw decodeLimit parse failures (keyed-archive-bytes, -object-table-entries, -values-per-object, -reference-edges) and malformed parse failures instead of plain RangeError/TypeError. KeyedArchiveReader no longer classifies every RangeError as a limit: only a limit parse failure or a host stack/capacity limit is one. The unreachable 128-level scan nesting check is removed; projectPlistValue already refuses the archive first.

* test(plist): expect the nesting limit as its ParseFailure carrier

* fix(verify): count a filter index only on the filter's own result

* refactor(macho): select slices through one owner with typed refusals

* refactor(keyed): select FIT properties and certificate extensions through uniqueKeyed

* refactor(keyed): key each FIT node once, pin repeated FIT properties and subjectKeyIdentifiers, and type the unknown Mach-O header as unsupported

* refactor(plist): report plist and NIBArchive input faults through ParseFailure and defects through invariantViolation (#10895)

* refactor(plist): report plist and NIBArchive input faults through ParseFailure and defects through invariantViolation

* fix(plist): report a cut-short NIB header or plist length record as truncated

* fix(native): project the selected Mach-O's parse failures through the shared owner

nativeMachoSourcePrimary mapped every non-limit ParseFailureError to
AnalysisOutputError, so a malformed or truncated selected Mach-O was
reported as unreadable tool output and an unsupported one lost its
category. It now uses parseFailureAnalysisError like the ELF, Go and
other byte-format providers: malformed and truncated bytes are an
invalid path, unsupported bytes an unsupported target, and a limit
still falls through to its producer's budget.
2026-11-15 18:36:30 +08:00

185 lines
6.2 KiB
TypeScript

import { createHash } from "node:crypto";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import type {
AnalysisOperation,
AnalysisOperationPort,
} from "../../../../src/application/AnalysisProvider.js";
import { createAnalysisExecution } from "../../../../src/application/AnalysisProvider.js";
import { EnhancedTools } from "../../../../src/application/EnhancedTools.js";
import { layoutFor } from "../../../../src/native/AppleMachoSelection.fixture.js";
import { NativeMacOSProvider } from "../../../../src/native/NativeMacOSProvider.js";
import { BinaryFormatFailure } from "../../../../src/native/metadata/BinaryContainer.js";
import { NativeFixtureRunner } from "../../../fixtures/nativeCommands.js";
import { ok } from "../../../../src/domain/result.js";
const thin32MachOHeader = (cpuType: number): Buffer => {
const bytes = Buffer.alloc(84);
bytes.writeUInt32LE(0xfeedface, 0);
bytes.writeUInt32LE(cpuType, 4);
bytes.writeUInt32LE(cpuType === 7 ? 3 : 0, 8);
bytes.writeUInt32LE(2, 12);
bytes.writeUInt32LE(1, 16);
bytes.writeUInt32LE(56, 20);
bytes.writeUInt32LE(1, 28); // LC_SEGMENT
bytes.writeUInt32LE(56, 32);
bytes.write("__TEXT", 36);
bytes.writeUInt32LE(0x1000, 52); // vmaddr
bytes.writeUInt32LE(0x1000, 56); // vmsize
bytes.writeUInt32LE(0, 60); // fileoff
bytes.writeUInt32LE(bytes.length, 64); // filesize
bytes.writeUInt32LE(7, 68); // maxprot
bytes.writeUInt32LE(5, 72); // initprot
return bytes;
};
const inspect = async (
bytes: Buffer,
architecture: "x86" | "arm" | "x86_64",
) => {
const directory = await mkdtemp(join(tmpdir(), "rea-objc-macho-fallback-"));
const path = join(directory, "fixture");
await writeFile(path, bytes);
const sha256 = createHash("sha256").update(bytes).digest("hex");
const target = {
path,
sha256,
kind: "executable" as const,
format: "mach-o" as const,
architecture,
availableArchitectures: [architecture],
};
const nativeClient = new NativeMacOSProvider(
{},
new NativeFixtureRunner(),
"darwin",
).createClient(target);
try {
const hopper = { id: "hopper", name: "Hopper", version: "1" };
const analysis: AnalysisOperationPort = {
execute: async (operation: AnalysisOperation, parameters, options) => {
if (operation === "list_names")
return ok(
createAnalysisExecution(
[{ address: "0x1000", value: "OBJC_CLASS_$_Known" }],
hopper,
{ subject: target },
),
);
return nativeClient.execute(operation, parameters, options);
},
};
return await new EnhancedTools(analysis).execute("get_objc_classes", {});
} finally {
let closeResult: Awaited<ReturnType<typeof nativeClient.close>> | undefined;
let closeError: unknown;
try {
closeResult = await nativeClient.close();
} catch (cause: unknown) {
closeError = cause;
}
await rm(directory, { recursive: true, force: true });
if (closeError !== undefined) throw closeError;
expect(closeResult).toMatchObject({ ok: true });
}
};
describe("native Objective-C class metadata capability fallback", () => {
it.each([
{ architecture: "x86" as const, cpuType: 7 },
{ architecture: "arm" as const, cpuType: 12 },
])(
"keeps $architecture names when a valid 32-bit executable is unsupported",
async ({ architecture, cpuType }) => {
const result = await inspect(thin32MachOHeader(cpuType), architecture);
expect(result).toMatchObject({
ok: true,
value: {
count: 1,
classes: [{ address: "0x1000", name: "OBJC_CLASS_$_Known" }],
identity_coverage: { status: "unknown" },
},
});
},
);
it("classifies exactly the complete 28-byte 32-bit header as unsupported", () => {
const bytes = Buffer.alloc(28);
bytes.writeUInt32LE(0xfeedface, 0);
bytes.writeUInt32LE(7, 4);
bytes.writeUInt32LE(3, 8);
bytes.writeUInt32LE(2, 12);
let failure: unknown;
try {
layoutFor(bytes, "x86");
} catch (cause: unknown) {
failure = cause;
}
expect(failure).toBeInstanceOf(BinaryFormatFailure);
expect(failure).toMatchObject({
kind: "unsupported",
undecodedContent: true,
});
});
it("keeps truncated 32-bit and 64-bit headers as errors", async () => {
const truncated32 = Buffer.alloc(27);
truncated32.writeUInt32LE(0xfeedface, 0);
const truncated32Result = await inspect(truncated32, "x86");
expect(truncated32Result).toMatchObject({
ok: false,
error: { _tag: "ProviderAdapterError" },
});
const truncated64 = Buffer.alloc(31);
truncated64.writeUInt32LE(0xfeedfacf, 0);
truncated64.writeUInt32LE(0x01000007, 4);
const truncated64Result = await inspect(truncated64, "x86_64");
expect(truncated64Result).toMatchObject({
ok: false,
error: { _tag: "ProviderAdapterError" },
});
});
it("does not treat an unknown header as a supported-format capability limit", async () => {
const result = await inspect(Buffer.alloc(32), "x86_64");
expect(result).toMatchObject({
ok: false,
error: { _tag: "ProviderAdapterError" },
});
});
it("classifies a complete big-endian PowerPC64 Mach-O header as unsupported", () => {
const bytes = Buffer.alloc(32);
bytes.writeUInt32BE(0xfeedfacf, 0);
bytes.writeUInt32BE(0x01000012, 4); // CPU_TYPE_POWERPC64
bytes.writeUInt32BE(0, 8);
bytes.writeUInt32BE(2, 12);
let failure: unknown;
try {
layoutFor(bytes, "powerpc");
} catch (cause: unknown) {
failure = cause;
}
expect(failure).toBeInstanceOf(BinaryFormatFailure);
expect(failure).toMatchObject({
kind: "unsupported",
undecodedContent: true,
});
bytes.writeUInt32BE(0x01000007, 4);
let mismatchedCpuFailure: unknown;
try {
layoutFor(bytes, "powerpc");
} catch (cause: unknown) {
mismatchedCpuFailure = cause;
}
expect(mismatchedCpuFailure).toBeInstanceOf(BinaryFormatFailure);
expect(mismatchedCpuFailure).toMatchObject({ kind: "unsupported" });
expect(mismatchedCpuFailure).toMatchObject({ undecodedContent: false });
});
});