fix(macho): preserve retained magic from valid FAT ranges (#13910)

This commit is contained in:
morluto authored and GitHub committed 2026-11-23 03:28:30 +00:00
1 parent 389d984b4f
commit 9dba67368d
3 files changed
+76 -82

No files matched your search

+55 -46
View File
@@ -25,14 +25,7 @@ import {
const classify = (bytes: Uint8Array) => {
const header = readFatContainerHeader(bytes, bytes.byteLength);
if (header.state !== "parsed") return header;
return classifyFatContainerIdentity(header, (offset) => {
if (offset + 4 > bytes.byteLength) return undefined;
return new DataView(
bytes.buffer,
bytes.byteOffset,
bytes.byteLength,
).getUint32(offset, false);
});
return classifyFatContainerEvidence(header, bytes);
};
describe("FAT declaration facts", () => {
@@ -216,32 +209,17 @@ it("preserves explicit unknown slice evidence instead of falling back to retaine
});
describe("FAT Mach-O identity", () => {
it("does not treat known CPU declarations as proof when slices are ar archives", async () => {
const archive = arArchive();
it.each([
{ layout: "all archives", first: arArchive() },
{
layout: "mixed Mach-O and archive",
first: machoImage({ cpu: CPU.x86_64 }),
},
])("keeps $layout outside Mach-O identity", async ({ first }) => {
const bytes = fatImage([
{ cpu: CPU.x86_64, bytes: archive },
{ cpu: CPU.arm64, bytes: archive },
]);
expect(classify(bytes)).toEqual({ state: "not-mach-o" });
expect(await readMachoImage(readerOf(bytes), bytes.byteLength)).toEqual({
status: "not-mach-o",
});
expect(parseExecutableHeader(Buffer.from(bytes), "arm64")).toEqual({
ok: false,
error: "unsupported binary format",
});
});
it("rejects a mixed FAT container instead of selecting an ar slice as Mach-O", async () => {
const bytes = fatImage([
{
cpu: CPU.x86_64,
bytes: machoImage({ cpu: CPU.x86_64 }),
},
{ cpu: CPU.x86_64, bytes: first },
{ cpu: CPU.arm64, bytes: arArchive() },
]);
expect(classify(bytes)).toEqual({ state: "not-mach-o" });
expect(await readMachoImage(readerOf(bytes), bytes.byteLength)).toEqual({
status: "not-mach-o",
@@ -426,7 +404,7 @@ describe("FAT slice header identity and bounds", () => {
});
});
it("keeps unresolved headers unknown and preserves declared-range failures", () => {
it("keeps unresolved headers unknown and reports physical range failures before probing them", () => {
const bytes = Buffer.alloc(28);
bytes.writeUInt32BE(0xcafebabe, 0);
bytes.writeUInt32BE(1, 4);
@@ -436,38 +414,69 @@ describe("FAT slice header identity and bounds", () => {
bytes.writeUInt32BE(12, 24);
const header = readFatContainerHeader(bytes, 4128);
if (header.state !== "parsed") throw new Error("expected parsed FAT table");
expect(classifyFatContainerIdentity(header, () => undefined)).toEqual({
expect(classifyFatContainerEvidence(header, bytes)).toEqual({
state: "needs-slice-header",
offsets: [4096],
});
const badRange = {
...header,
rangeIssues: [
{ category: "malformed" as const, reason: "bad test range" },
],
};
expect(classifyFatContainerIdentity(badRange, () => null)).toEqual({
bytes.writeUInt32BE(0, 20);
const badRange = readFatContainerHeader(bytes, 4128);
if (badRange.state !== "parsed")
throw new Error("expected FAT range issue");
expect(
classifyFatContainerIdentity(badRange, () => {
throw new Error("an invalid range must not be probed");
}),
).toEqual({
state: "malformed",
category: "malformed",
reason: "bad test range",
reason: "FAT architecture 0 has an invalid slice range",
});
});
it("classifies a valid but too-short slice without inventing header bytes", () => {
const bytes = Buffer.alloc(31);
it("uses the retained magic of a valid slice when an earlier invalid range shares its offset", () => {
const cpu = { type: 0x12345678, subtype: 0 };
const thin = { cpu, bytes: machoImage({ cpu }) };
const bytes = Buffer.concat([
Buffer.alloc(3),
fatImage([thin, thin]),
]).subarray(3);
const offset = bytes.readUInt32BE(8 + 20 + 8);
bytes.writeUInt32BE(offset, 8 + 8);
bytes.writeUInt32BE(0, 8 + 12);
const header = readFatContainerHeader(bytes, bytes.length);
if (header.state !== "parsed") throw new Error("expected parsed FAT table");
expect(
classifyFatContainerEvidence(header, bytes.subarray(0, offset + 3)),
).toEqual({ state: "needs-slice-header", offsets: [offset] });
const prefix = bytes.subarray(0, offset + 4);
expect(classifyFatContainerEvidence(header, prefix)).toEqual({
state: "malformed",
category: "malformed",
reason: "FAT architecture 0 has an invalid slice range",
});
expect(parseExecutableHeader(prefix, "arm64", bytes.length)).toEqual({
ok: false,
error: "FAT architecture 0 has an invalid slice range",
});
});
it("keeps a three-byte slice outside Mach-O identity with the fourth magic byte in the file", () => {
const bytes = Buffer.alloc(32);
bytes.writeUInt32BE(0xcafebabe, 0);
bytes.writeUInt32BE(1, 4);
bytes.writeUInt32BE(CPU.arm64.type, 8);
bytes.writeUInt32BE(28, 16);
bytes.writeUInt32BE(3, 20);
bytes.set([0xcf, 0xfa, 0xed], 28);
bytes.writeUInt32BE(0xcffaedfe, 28);
const header = readFatContainerHeader(bytes, bytes.length);
if (header.state !== "parsed") throw new Error("expected parsed FAT table");
const expected = { state: "not-mach-o" };
expect(classifyFatContainerEvidence(header, bytes)).toEqual(expected);
expect(
classifyFatContainerIdentity(header, () => {
throw new Error("a three-byte slice cannot provide a four-byte magic");
throw new Error("three declared bytes cannot supply a four-byte read");
}),
).toEqual({ state: "not-mach-o" });
).toEqual(expected);
});
});
+13 -21
View File
@@ -313,23 +313,21 @@ export const classifyFatContainerIdentity = (
header: Extract<FatContainerHeader, { readonly state: "parsed" }>,
sliceHeaderAt: (offset: number) => number | null | undefined,
): FatContainerIdentity => {
const hasKnownCpu = header.slices.some(({ cpuType }) =>
KNOWN_MACHO_CPU_TYPES.includes(cpuType),
);
const invalidRange = header.rangeIssues.find(
(issue): issue is FatSliceRangeIssue => issue !== null,
);
// Preserve the existing malformed-range result for recognized CPU tables;
// a valid CPU declaration by itself does not establish a Mach-O image.
if (hasKnownCpu && invalidRange !== undefined)
if (
invalidRange !== undefined &&
header.slices.some(({ cpuType }) => KNOWN_MACHO_CPU_TYPES.includes(cpuType))
)
return { state: "malformed", ...invalidRange };
const validRanges = header.slices.filter(
(_slice, index) => header.rangeIssues[index] === null,
);
const missingHeaders: number[] = [];
let observedMachO = false;
let observedNonMachO = false;
for (const slice of validRanges) {
for (const [index, slice] of header.slices.entries()) {
if (header.rangeIssues[index] !== null) continue;
if (slice.size < 4) {
observedNonMachO = true;
continue;
@@ -355,22 +353,16 @@ export const classifyFatContainerEvidence = (
header: Extract<FatContainerHeader, { readonly state: "parsed" }>,
prefix: Uint8Array,
sliceHeadersByOffset?: ReadonlyMap<number, MachoHeaderPrefixFacts>,
): FatContainerIdentity =>
classifyFatContainerIdentity(header, (offset) => {
): FatContainerIdentity => {
const reader = machoReader(prefix, false);
// The classifier requests magic only from a valid range of at least four
// bytes. An alias declaration at this offset cannot narrow that range.
return classifyFatContainerIdentity(header, (offset) => {
if (sliceHeadersByOffset?.has(offset))
return sliceHeadersByOffset.get(offset)?.magic;
const slice = header.slices.find(
(candidate) => candidate.offset === offset,
);
if (slice === undefined || offset >= prefix.byteLength) return undefined;
const available = Math.max(
0,
Math.min(slice.size, prefix.byteLength - offset, 12),
);
return readMachoHeaderPrefixFacts(
prefix.subarray(offset, offset + available),
).magic;
return offset <= prefix.byteLength - 4 ? reader.u32(offset) : undefined;
});
};
/**
* A malformed table is conclusive after a capped JVM scan only if one
+8 -15
View File
@@ -12,21 +12,7 @@ const formats = [
] as const;
it.each(formats)(
"preserves incomplete FAT format evidence ($magic)",
(format) => {
const bytes = Buffer.alloc(8);
bytes.writeUInt32BE(format.magic);
for (let observed = 0; observed < 8; observed++)
expect(readFatHeaderPrefix(bytes.subarray(0, observed))).toEqual(
observed < 4
? { state: "unknown", requiredBytes: 4 }
: { state: "incomplete", ...format, requiredBytes: 8 },
);
},
);
it.each(formats)(
"retains raw zero and maximum counts without policy or table allocation ($magic)",
"preserves partial format and raw count evidence from the same FAT view ($magic)",
(format) => {
const backing = Buffer.alloc(27, 0xa5);
const window = backing.subarray(7, 15);
@@ -36,6 +22,13 @@ it.each(formats)(
window.byteLength,
);
view.setUint32(0, format.magic, false);
for (let observed = 0; observed < window.length; observed++)
expect(readFatHeaderPrefix(window.subarray(0, observed))).toEqual(
observed < 4
? { state: "unknown", requiredBytes: 4 }
: { state: "incomplete", ...format, requiredBytes: 8 },
);
for (const count of [0, 0xffffffff]) {
view.setUint32(4, count, format.littleEndian);
const before = Buffer.from(backing);