fix(artifacts): distinguish Java classes from universal Mach-O

Classify FAT containers using shared architecture, range, and observed slice-header facts rather than the CAFEBABE signature alone. Preserve typed unsupported and malformed reasons, reject malformed sibling slices consistently, and remove repeated range parsing in consumers.

Validation: valid small and large JVM classes in public JAR/ZIP inspection, four FAT width/byte-order controls, and focused executable/Mach-O boundary tests. The class fixtures were checked with JDK javap; no new JVM analysis capability is advertised.

The Apple selection and Hopper readers retain their existing parsing because they also own oversized-count diagnostics, reserved fields, streaming final-size validation, or source freshness that the shared header result does not represent.

Representative public mixed-ZIP inventory probe, four fresh processes with an already warm filesystem cache: first process elapsed 626.8 -> 548.3 ms, CPU 740 -> 740 ms, sampled family peak RSS 375.5 -> 345.4 MiB. Subsequent three-process medians: elapsed 767.2 -> 454.0 ms, CPU 890 -> 640 ms, peak RSS 368.7 -> 346.2 MiB. Estimated output tokens 2310 -> 2292. Concurrent load was uncontrolled, so these observations do not establish a speed improvement. Whole-agent task tokens and schema/call overhead were not measured.

Fixes #2317
This commit is contained in:
morluto
2026-10-13 04:12:04 +08:00
parent c339f9ebe7
commit 921bb95755
8 changed files with 535 additions and 170 deletions
@@ -26,6 +26,7 @@ import {
} from "./MachoLoadCommandReader.js";
import { traceDylibResolution } from "./DylibResolutionReader.js";
import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js";
import { javaClassFile } from "../../../tests/fixtures/javaClassFile.js";
const read = (bytes: Uint8Array) =>
readMachoImage(readerOf(bytes), bytes.length);
@@ -345,10 +346,13 @@ describe("Mach-O load command reader inputs", () => {
expect(i386.status === "parsed" && i386.slices[0]?.architecture).toBe(
"i386",
);
// A Java class file shares the FAT magic; its version is not a slice count.
const javaClass = Uint8Array.from([0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 0x34]);
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
// A Java class file shares the FAT magic; version fields are not a slice count.
const javaClasses = [javaClassFile(), javaClassFile(4000)];
expect(javaClasses.map(({ length }) => length)).toEqual([57, 4060]);
for (const javaClass of javaClasses) {
expect(hasMachoMagic(javaClass)).toBe(true);
expect(await read(javaClass)).toEqual({ status: "not-mach-o" });
}
expect(await read(new TextEncoder().encode("#!/bin/sh\n"))).toEqual({
status: "not-mach-o",
});
@@ -489,6 +493,16 @@ describe("Mach-O load command reader failures", () => {
reason: "FAT architecture 0 slice range extends beyond the file",
});
});
it("preserves unsupported status for an unsupported FAT alignment exponent", async () => {
const fat = fatImage([{ cpu: CPU.arm64, bytes: machoImage({}) }]);
new DataView(fat.buffer).setUint32(24, 53, false);
expect(await read(fat)).toMatchObject({
status: "unsupported",
reason: expect.stringContaining("alignment exponent 53 is unsupported"),
});
});
});
it.each([true, false])(
+36 -78
View File
@@ -4,8 +4,9 @@ import type {
MachoSlice,
} from "../../domain/apple/dylibResolution.js";
import {
readFatSliceDeclarations,
validateFatSlice,
classifyFatContainerIdentity,
readFatContainerHeader,
validateFatSliceIdentity,
type FatSliceDeclaration,
} from "../../domain/apple/machoContainer.js";
@@ -14,13 +15,6 @@ export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
/** Load commands larger than this are refused instead of buffered. */
export const MAX_LOAD_COMMAND_BYTES = 16 * 1024 * 1024;
/** Target opening accepts up to 128 FAT records; Java class files share the FAT magic. */
const MAX_FAT_ARCHITECTURES = 128;
/** CPU types of real Mach-O slices (x86, x86_64, arm, arm64, arm64_32, ppc, ppc64). */
const KNOWN_CPU_TYPES: readonly number[] = [
7, 0x01000007, 12, 0x0100000c, 0x0200000c, 18, 0x01000012,
];
const MH_MAGIC = 0xfeedface;
const MH_MAGIC_64 = 0xfeedfacf;
const MH_CIGAM = 0xcefaedfe;
@@ -146,69 +140,41 @@ export const readMachoImage = async (
: { status: "not-mach-o" };
const view = viewOf(head);
const magic = view.getUint32(0, false);
if ([FAT_MAGIC, FAT_MAGIC_64, FAT_CIGAM, FAT_CIGAM_64].includes(magic)) {
// FAT headers are big-endian; the swapped magics store them little-endian.
const littleEndian = magic === FAT_CIGAM || magic === FAT_CIGAM_64;
const count = view.getUint32(4, littleEndian);
const wide = magic === FAT_MAGIC_64 || magic === FAT_CIGAM_64;
// A Java class file's nonzero major version reads as the count, so an
// empty architecture table can only be a malformed universal header.
if (count === 0)
return {
status: "malformed",
reason: "FAT header declares no architectures",
};
if (count > MAX_FAT_ARCHITECTURES || 8 + count * (wide ? 32 : 20) > size)
return { status: "not-mach-o" };
const tableBytes = await readExact(
readAt,
8,
count * (wide ? 32 : 20),
"FAT table",
);
const declarations = readFatSliceDeclarations(tableBytes, {
count,
wide,
littleEndian,
});
if (declarations.status !== "parsed")
throw new MachoFormatIssue("malformed", declarations.reason);
// A Java class file's version fields read as a FAT count; its "table" names no CPU.
if (
!declarations.slices.some(({ cpuType }) =>
KNOWN_CPU_TYPES.includes(cpuType),
)
) {
let hasMachOSliceHeader = false;
for (const declaration of declarations.slices) {
if (
validateFatSlice(
declaration,
size,
8 + count * (wide ? 32 : 20),
) !== null
)
continue;
const bytes = await readAt(declaration.offset, 4);
if (bytes.byteLength < 4) continue;
const sliceMagic = viewOf(bytes).getUint32(0, false);
if (
[MH_MAGIC, MH_MAGIC_64, MH_CIGAM, MH_CIGAM_64].includes(sliceMagic)
) {
hasMachOSliceHeader = true;
break;
}
}
if (!hasMachOSliceHeader) return { status: "not-mach-o" };
let header = readFatContainerHeader(head, size);
if (header.state !== "not-fat") {
if (header.state === "needs-data") {
header = readFatContainerHeader(
await readAt(0, header.requiredBytes),
size,
);
}
if (header.state === "not-fat") return { status: "not-mach-o" };
if (header.state === "needs-data")
throw new MachoFormatIssue("malformed", "FAT table is truncated");
if (header.state === "malformed")
throw new MachoFormatIssue("malformed", header.reason);
let identity = classifyFatContainerIdentity(header, () => undefined);
if (identity.state === "needs-slice-header") {
const sliceHeaders = new Map<number, number | null>();
for (const offset of identity.offsets) {
const bytes = await readAt(offset, 4);
sliceHeaders.set(
offset,
bytes.byteLength < 4 ? null : viewOf(bytes).getUint32(0, false),
);
}
identity = classifyFatContainerIdentity(header, (offset) =>
sliceHeaders.get(offset),
);
}
if (identity.state === "not-mach-o") return { status: "not-mach-o" };
if (identity.state === "malformed")
throw new MachoFormatIssue(identity.category, identity.reason);
if (identity.state === "needs-slice-header")
return { status: "not-mach-o" };
return {
status: "parsed",
slices: await readFatSlices(
readAt,
size,
8 + count * (wide ? 32 : 20),
declarations.slices,
),
slices: await readFatSlices(readAt, header.slices),
};
}
if (magic === MH_CIGAM || magic === MH_CIGAM_64)
@@ -228,25 +194,17 @@ export const readMachoImage = async (
const readFatSlices = async (
readAt: ReadAt,
size: number,
tableEnd: number,
declarations: readonly FatSliceDeclaration[],
): Promise<MachoSlice[]> => {
const slices: MachoSlice[] = [];
for (const declaration of declarations) {
const { offset, size: length, cpuType, cpuSubtype } = declaration;
const rangeIssue = validateFatSlice(declaration, size, tableEnd);
if (rangeIssue !== null)
throw new MachoFormatIssue(
rangeIssue.includes("unsupported") ? "unsupported" : "malformed",
rangeIssue,
);
const slice = await readSlice(readAt, offset, length, {
fatCpuType: cpuType,
fatCpuSubtype: cpuSubtype,
alignmentExponent: declaration.alignmentExponent,
});
const identityIssue = validateFatSlice(declaration, size, tableEnd, {
const identityIssue = validateFatSliceIdentity(declaration, {
cpuType: slice.cpu_type,
cpuSubtype: slice.cpu_subtype,
});
@@ -22,6 +22,10 @@ import {
observeMzWindowsHeader,
parseDosMzHeader,
} from "../../domain/dosMz.js";
import {
classifyFatContainerIdentity,
readFatContainerHeader,
} from "../../domain/apple/machoContainer.js";
/** Mutable internal occurrence used until root-bound IDs are known. */
export interface MutableOccurrence {
@@ -437,10 +441,10 @@ export const classifyArtifactBytes = (
): ArtifactNode["format"] => {
if (hasZipSignature(prefix)) return "zip";
if (prefix.subarray(0, 8).equals(Buffer.from("bplist00"))) return "plist";
const fatFormat = classifyFatArtifact(prefix, fileSize);
if (fatFormat !== null) return fatFormat;
if (prefix.length >= 4) {
const magic = prefix.readUInt32BE(0);
if ([0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic))
return "mach-o-universal";
if ([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe].includes(magic))
return "mach-o";
if (prefix.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])))
@@ -471,6 +475,22 @@ export const classifyArtifactBytes = (
return "file";
};
const classifyFatArtifact = (
prefix: Buffer,
fileSize: number,
): ArtifactNode["format"] | null => {
const fatHeader = readFatContainerHeader(prefix, fileSize);
if (fatHeader.state === "needs-data" || fatHeader.state === "malformed")
return "unknown";
if (fatHeader.state === "not-fat") return null;
const identity = classifyFatContainerIdentity(fatHeader, (offset) => {
if (offset >= prefix.length) return undefined;
if (offset + 4 > prefix.length) return null;
return prefix.readUInt32BE(offset);
});
return identity.state === "mach-o" ? "mach-o-universal" : "unknown";
};
const relationFor = (path: string): ArtifactEdge["relation"] => {
const lower = path.toLowerCase();
if (lower.endsWith(".map")) return "maps-source";