fix(native): preserve universal Mach-O container identity

Keep FAT container format distinct from selected slice architecture through target admission, Evidence, snapshots, and CLI/MCP lifecycle results. Preserve native, Hopper, Ghidra, extraction, and dylib routing for the Mach-O family.

Reject selected FAT ranges overlapping their table or too short for a Mach-O header. Replace empty-slice fixtures with in-bounds executable headers and cover thin, universal, single-slice, FAT64, and swapped containers.

Validation: static and architecture checks, generated docs, targeted producer and public MCP tests. Provider routing uses controlled fixtures; no live Hopper, IDA, JADX, or Ghidra analysis was performed for this change.
This commit is contained in:
morluto
2026-10-12 09:29:07 +08:00
parent 87b9793c53
commit b38429cb6a
28 changed files with 608 additions and 143 deletions
+57 -44
View File
@@ -70,7 +70,7 @@ const snapshotWithHistoricalEvidence = () => {
};
};
describe("analysis snapshot contract", () => {
describe("analysis snapshot target identity", () => {
it("partitions raw snapshots and query identities by the canonical entry", () => {
const target: BinaryTarget = {
path: "/fixture/image.bin",
@@ -118,51 +118,64 @@ describe("analysis snapshot contract", () => {
"entry_point",
);
});
});
it("preserves DOS MZ target and subject formats with the x86 family", () => {
const target = {
path: ANALYSIS_SNAPSHOT_TARGET.path,
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable" as const,
format: "dos-mz" as const,
architecture: "x86" as const,
availableArchitectures: ["x86" as const],
};
const evidence = createEvidence(target, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "analyze_function",
parameters: {},
result: null,
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
});
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const parsed = analysisSnapshotSchema.parse({
target: snapshotTarget(target),
binding,
entries: [
{
query_id: `query_${"0".repeat(64)}`,
operation: "analyze_function",
parameters: {},
execution: {
result: null,
raw_result: null,
provider: binding.provider,
limitations: [],
locations: [],
subject: target,
describe("analysis snapshot contract", () => {
it.each([
["dos-mz", "x86"],
["mach-o-universal", "arm64"],
] as const)(
"preserves %s target and subject formats",
(format, architecture) => {
const target = {
path: ANALYSIS_SNAPSHOT_TARGET.path,
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
kind: "executable" as const,
format,
architecture,
availableArchitectures: [architecture],
};
const evidence = createEvidence(target, ANALYSIS_SNAPSHOT_PROVIDER, {
operation: "analyze_function",
parameters: {},
result: null,
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
});
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
const parsed = parseAnalysisSnapshot({
target: snapshotTarget(target),
binding,
entries: [
{
query_id: analysisQueryId(
snapshotTarget(target),
binding,
"analyze_function",
{},
),
operation: "analyze_function",
parameters: {},
execution: {
result: null,
raw_result: null,
provider: binding.provider,
limitations: [],
locations: [],
subject: target,
},
},
},
],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
});
expect(parsed.target).toMatchObject({
format: "dos-mz",
architecture: "x86",
});
expect(parsed.entries[0]?.execution.subject?.format).toBe("dos-mz");
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe("dos-mz");
});
],
workflow_entries: [],
evidence_bundle: createEvidenceBundle([evidence]),
});
expect(parsed.target).toMatchObject({
format,
architecture,
});
expect(parsed.entries[0]?.execution.subject?.format).toBe(format);
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe(format);
},
);
it("rejects a snapshot subject path containing NUL", () => {
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
+1 -1
View File
@@ -51,6 +51,7 @@ const architectureSchema = z.enum(BINARY_ARCHITECTURES);
const formatSchema = z.enum([
"analysis-database",
"mach-o",
"mach-o-universal",
"elf",
"pe",
"dos-mz",
@@ -81,7 +82,6 @@ const subjectSchema = z.object({
"directory",
"file",
"unknown",
"mach-o-universal",
"javascript-bundle",
"entitlements",
]),
+20 -3
View File
@@ -22,15 +22,32 @@ export const thinMach = (magic: number, cpu: number): Buffer => {
return bytes;
};
/** Build a minimal FAT Mach-O table for binary-target parser tests. */
/** Build a FAT Mach-O with in-bounds thin slices, or an explicitly truncated table. */
export const fat = (
cpus: readonly number[],
declared = cpus.length,
): Buffer => {
const bytes = Buffer.alloc(8 + cpus.length * 20);
const tableSize = 8 + cpus.length * 20;
const slices = cpus.map((cpu) => {
const bytes = thinMach(0xfeedfacf, cpu);
bytes.writeUInt32BE(2, 12);
return bytes;
});
const sliceStart = Math.ceil(tableSize / 16) * 16;
const bytes = Buffer.alloc(
declared === cpus.length ? sliceStart + cpus.length * 32 : tableSize,
);
bytes.writeUInt32BE(0xcafebabe, 0);
bytes.writeUInt32BE(declared, 4);
cpus.forEach((cpu, index) => bytes.writeUInt32BE(cpu, 8 + index * 20));
cpus.forEach((cpu, index) => {
const entry = 8 + index * 20;
const offset = sliceStart + index * 32;
bytes.writeUInt32BE(cpu, entry);
bytes.writeUInt32BE(offset, entry + 8);
bytes.writeUInt32BE(32, entry + 12);
bytes.writeUInt32BE(4, entry + 16);
if (declared === cpus.length) slices[index]?.copy(bytes, offset);
});
return bytes;
};
+122
View File
@@ -90,15 +90,30 @@ describe("executable header parsing", () => {
const arm = parseExecutableHeader(bytes, "arm64");
const intel = parseExecutableHeader(bytes, "x64");
expect(arm.ok && arm.value).toMatchObject({
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["x86_64", "arm64"],
});
expect(intel.ok && intel.value).toMatchObject({
format: "mach-o-universal",
architecture: "x86_64",
availableArchitectures: ["x86_64", "arm64"],
});
});
it("classifies even a one-slice FAT table as a universal container", () => {
const result = parseExecutableHeader(fat([0x0100000c]), "arm64");
expect(result).toMatchObject({
ok: true,
value: {
format: "mach-o-universal",
architecture: "arm64",
availableArchitectures: ["arm64"],
},
});
});
it("rejects FAT files without a host-compatible slice", () => {
expect(parseExecutableHeader(fat([0x01000007]), "arm64")).toMatchObject({
ok: false,
@@ -173,4 +188,111 @@ describe("executable header completeness", () => {
// Only the slice REA would analyze must be present.
expect(parseExecutableHeader(bytes, "x64", 4100).ok).toBe(true);
});
it.each([
{
label: "empty range",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(bytes, wide, little, "size", 0n),
error: "FAT slice for arm64 is shorter than its Mach-O header",
},
{
label: "table overlap",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(
bytes,
wide,
little,
"offset",
BigInt(8 + 2 * (wide ? 32 : 20) - 1),
),
error: "FAT slice for arm64 overlaps the architecture table",
},
{
label: "undersized 64-bit header",
corruptRange: (bytes: Buffer, wide: boolean, little: boolean) =>
setFatSliceRange(bytes, wide, little, "size", 31n),
error: "FAT slice for arm64 is shorter than its Mach-O header",
},
])("rejects a selected FAT slice with $label", ({ corruptRange, error }) => {
for (const [wide, little] of [
[false, false],
[true, false],
[true, true],
] as const) {
const bytes = wide
? fat64([0x01000007, 0x0100000c], little)
: fat([0x01000007, 0x0100000c]);
expect(parseExecutableHeader(bytes, "arm64").ok).toBe(true);
corruptRange(bytes, wide, little);
expect(parseExecutableHeader(bytes, "arm64")).toMatchObject({
ok: false,
error,
});
}
});
it("uses a 28-byte minimum for a selected 32-bit Mach-O header", () => {
const exactHeader = fat([7]);
setFatSliceRange(exactHeader, false, false, "size", 28n, 0);
expect(parseExecutableHeader(exactHeader, "ia32").ok).toBe(true);
const undersizedHeader = Buffer.from(exactHeader);
setFatSliceRange(undersizedHeader, false, false, "size", 27n, 0);
expect(parseExecutableHeader(undersizedHeader, "ia32")).toMatchObject({
ok: false,
error: "FAT slice for x86 is shorter than its Mach-O header",
});
});
});
const setFatSliceRange = (
bytes: Buffer,
wide: boolean,
littleEndian: boolean,
field: "offset" | "size",
value: bigint,
index = 1,
): void => {
const entry = 8 + index * (wide ? 32 : 20);
const fieldOffset = entry + (field === "offset" ? 8 : wide ? 16 : 12);
if (wide) {
if (littleEndian) bytes.writeBigUInt64LE(value, fieldOffset);
else bytes.writeBigUInt64BE(value, fieldOffset);
} else {
const numeric = Number(value);
if (littleEndian) bytes.writeUInt32LE(numeric, fieldOffset);
else bytes.writeUInt32BE(numeric, fieldOffset);
}
};
const fat64 = (cpus: readonly number[], littleEndian: boolean): Buffer => {
const tableEnd = 8 + cpus.length * 32;
const sliceStart = Math.ceil(tableEnd / 16) * 16;
const bytes = Buffer.alloc(sliceStart + cpus.length * 32);
if (littleEndian) {
bytes.writeUInt32LE(0xcafebabf, 0);
bytes.writeUInt32LE(cpus.length, 4);
} else {
bytes.writeUInt32BE(0xcafebabf, 0);
bytes.writeUInt32BE(cpus.length, 4);
}
cpus.forEach((cpu, index) => {
const entry = 8 + index * 32;
const sliceOffset = BigInt(sliceStart + index * 32);
if (littleEndian) {
bytes.writeUInt32LE(cpu, entry);
bytes.writeBigUInt64LE(sliceOffset, entry + 8);
bytes.writeBigUInt64LE(32n, entry + 16);
bytes.writeUInt32LE(4, entry + 24);
} else {
bytes.writeUInt32BE(cpu, entry);
bytes.writeBigUInt64BE(sliceOffset, entry + 8);
bytes.writeBigUInt64BE(32n, entry + 16);
bytes.writeUInt32BE(4, entry + 24);
}
thinMach(0xfeedfacf, cpu).copy(bytes, Number(sliceOffset));
});
return bytes;
};
+22 -6
View File
@@ -15,7 +15,12 @@ export type ExecutableMetadata =
readonly mips: MipsElfMetadata;
}
| {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly format:
| "mach-o"
| "mach-o-universal"
| "elf"
| "dos-mz"
| "dos-com";
readonly architecture: Exclude<BinaryArchitecture, "mips">;
readonly availableArchitectures: readonly Exclude<
BinaryArchitecture,
@@ -105,7 +110,10 @@ const parseFatMachO = (
if (count === 0 || count > 128 || bytes.length < 8 + count * entrySize)
return err("truncated or invalid FAT architecture table");
const architectures: Exclude<BinaryArchitecture, "mips">[] = [];
const sliceEnds = new Map<BinaryArchitecture, bigint>();
const slices = new Map<
Exclude<BinaryArchitecture, "mips">,
{ readonly offset: bigint; readonly size: bigint }
>();
for (let index = 0; index < count; index += 1) {
const entry = 8 + index * entrySize;
const architecture = machArchitecture(read(entry));
@@ -122,7 +130,7 @@ const parseFatMachO = (
? bytes.readBigUInt64LE(entry + 16)
: bytes.readBigUInt64BE(entry + 16)
: BigInt(read(entry + 12));
sliceEnds.set(architecture, offset + size);
slices.set(architecture, { offset, size });
}
const preferred =
host === "arm64"
@@ -134,15 +142,23 @@ const parseFatMachO = (
: host === "arm"
? "arm"
: undefined;
if (preferred === undefined || !architectures.includes(preferred))
const slice = preferred === undefined ? undefined : slices.get(preferred);
if (preferred === undefined || slice === undefined)
return err(`FAT binary has no host-compatible ${host} architecture`);
const sliceEnd = sliceEnds.get(preferred) ?? 0n;
const tableEnd = BigInt(8 + count * entrySize);
if (slice.offset < tableEnd)
return err(`FAT slice for ${preferred} overlaps the architecture table`);
const minimumHeaderSize =
preferred === "arm64" || preferred === "x86_64" ? 32n : 28n;
if (slice.size < minimumHeaderSize)
return err(`FAT slice for ${preferred} is shorter than its Mach-O header`);
const sliceEnd = slice.offset + slice.size;
if (sliceEnd > BigInt(fileSize))
return err(
`truncated FAT slice: the ${preferred} slice ends at byte ${sliceEnd}; the file has ${fileSize}`,
);
return ok({
format: "mach-o",
format: "mach-o-universal",
architecture: preferred,
availableArchitectures: architectures,
});
+12 -1
View File
@@ -83,7 +83,12 @@ export type BinaryTarget =
readonly managed?: never;
})
| (ExecutableTarget & {
readonly format: "mach-o" | "elf" | "dos-mz" | "dos-com";
readonly format:
| "mach-o"
| "mach-o-universal"
| "elf"
| "dos-mz"
| "dos-com";
readonly executableRole?: never;
readonly managed?: never;
})
@@ -130,3 +135,9 @@ export type BinaryTarget =
readonly kind: "artifact";
readonly format: "plist" | "javascript" | "source-map";
});
/** Whether an executable target contains a thin or universal Mach-O image. */
export const isMachOFormat = (
format: unknown,
): format is "mach-o" | "mach-o-universal" =>
format === "mach-o" || format === "mach-o-universal";