fix(macho): require bounded slice evidence when JVM identity is unresolved (#12482)

This commit is contained in:
morluto authored and GitHub committed 2026-11-19 19:33:07 +00:00
1 parent 93f4c3749f
commit adafb97eb1
4 files changed
+131 -46

No files matched your search

+16 -15
View File
@@ -118,6 +118,7 @@ import {
import {
classifyFatContainerIdentity,
readFatContainerHeader,
readFatJvmIdentityLimitIssue,
readMachoHeaderPrefixFacts,
type FatSliceHeaderEvidence,
type MachoHeaderPrefixFacts,
@@ -126,7 +127,6 @@ import {
hasJvmClassHeader,
isJvmClassFile,
MAX_JVM_CLASS_IDENTITY_BYTES,
JVM_CLASS_IDENTITY_LIMIT_REASON,
} from "../domain/apple/jvmClassFile.js";
import {
MachoLoadCommandCursor,
@@ -1062,13 +1062,20 @@ const readExecutableMetadata = async (
if (
mayBeJvmClass &&
fileSize > MAX_JVM_CLASS_IDENTITY_BYTES &&
fatEvidence !== undefined &&
classifyFatContainerIdentity(
fatEvidence.header,
(offset) => fatEvidence.sliceHeadersByOffset.get(offset)?.magic,
).state === "malformed"
)
return err(JVM_CLASS_IDENTITY_LIMIT_REASON);
fatEvidence !== undefined
) {
const { header, sliceHeadersByOffset } = fatEvidence;
const identity = classifyFatContainerIdentity(
header,
(offset) => sliceHeadersByOffset.get(offset)?.magic,
);
const limitIssue = await readFatJvmIdentityLimitIssue(
header,
identity,
(offset, length) => readHandleRange(handle, offset, length, signal),
);
if (limitIssue !== null) return err(limitIssue);
}
const parsed = parseExecutableHeader(
bytes,
hostArchitecture,
@@ -1338,13 +1345,7 @@ const readFatSliceHeaderEvidence = async (
for (let index = 0; index < header.slices.length; index += 1) {
const slice = header.slices[index];
if (slice === undefined) continue;
if (header.rangeIssues[index] !== null) {
sliceHeadersByOffset.set(
slice.offset,
readMachoHeaderPrefixFacts(Buffer.alloc(0)),
);
continue;
}
if (header.rangeIssues[index] !== null) continue;
const observedLength = Math.min(12, slice.size);
const thinHeader = await readHandleRange(
handle,
+34 -1
View File
@@ -1,4 +1,7 @@
import { isJvmClassFile } from "./jvmClassFile.js";
import {
isJvmClassFile,
JVM_CLASS_IDENTITY_LIMIT_REASON,
} from "./jvmClassFile.js";
/** loader.h: load commands are 8-byte aligned in 64-bit images, 4 in 32-bit. */
export const machoLoadCommandAlignment = (wide: boolean): 4 | 8 =>
@@ -329,6 +332,36 @@ export const classifyFatContainerEvidence = (
).magic;
});
/**
* A malformed table is conclusive after a capped JVM scan only if one
* range-valid slice owns a complete, matching thin header. A sibling's range
* failure still belongs to that sibling.
*/
export const readFatJvmIdentityLimitIssue = async (
header: Extract<FatContainerHeader, { readonly state: "parsed" }>,
identity: FatContainerIdentity,
readAt: (offset: number, length: number) => Promise<Uint8Array>,
): Promise<string | null> => {
if (identity.state !== "malformed") return null;
for (const [index, slice] of header.slices.entries()) {
// A 28-byte header is the smallest complete thin header. Never read
// outside the slice, even when the enclosing file has more bytes.
if (header.rangeIssues[index] !== null || slice.size < 28) continue;
const requested = Math.min(32, slice.size);
const observed = await readAt(slice.offset, requested);
const { format, identity: embedded } = readMachoHeaderPrefixFacts(observed);
if (
format !== null &&
embedded !== null &&
format.headerSize <= requested &&
format.headerSize <= observed.byteLength &&
validateFatSliceIdentity(slice, embedded) === null
)
return null;
}
return JVM_CLASS_IDENTITY_LIMIT_REASON;
};
/** Decode FAT table entries once so artifact and native readers share identity facts. */
export const readFatSliceDeclarations = (
tableBytes: Uint8Array,
+10 -30
View File
@@ -20,7 +20,6 @@ import {
import {
hasJvmClassHeader,
MAX_JVM_CLASS_IDENTITY_BYTES,
JVM_CLASS_IDENTITY_LIMIT_REASON,
} from "./jvmClassFile.js";
import type {
MachoDependency,
@@ -38,6 +37,7 @@ import {
findOverlappingFatSlices,
hasMachoMagic,
readFatContainerHeader,
readFatJvmIdentityLimitIssue,
readFatSliceDeclarations,
readMachoHeaderPrefixFacts,
validateFatSlice,
@@ -191,22 +191,15 @@ export const readMachoContainer = async (
identity.state === "needs-slice-header"
)
return { kind: "not-mach-o" };
// A large CAFEBABE input whose bounded prefix resembles an invalid
// known-CPU FAT table remains unknown until its JVM identity can be
// checked; do not turn the resource limit into a malformed claim. A slice
// with a valid range that starts with a Mach-O header settles identity,
// and its siblings' range faults then stay their own.
if (
identity.state === "malformed" &&
mayBeJvmClass &&
size > MAX_JVM_CLASS_IDENTITY_BYTES &&
!(await observesMachoSlice(readAt, header))
)
return {
kind: "issue",
status: "unsupported",
reason: JVM_CLASS_IDENTITY_LIMIT_REASON,
};
if (mayBeJvmClass && size > MAX_JVM_CLASS_IDENTITY_BYTES) {
const limitIssue = await readFatJvmIdentityLimitIssue(
header,
identity,
readAt,
);
if (limitIssue !== null)
return { kind: "issue", status: "unsupported", reason: limitIssue };
}
// Aliased declarations are rejected at the declaration owner before any
// slice payload is parsed. A declaration whose own range is already
// defective keeps that fault; it does not turn its neighbours into aliases.
@@ -245,19 +238,6 @@ const readSliceMagic = async (
return bytes.byteLength < 4 ? null : viewOf(bytes).getUint32(0, false);
};
const observesMachoSlice = async (
readAt: ReadAt,
header: ParsedFatContainerHeader,
): Promise<boolean> => {
for (const [index, slice] of header.slices.entries())
if (
header.rangeIssues[index] === null &&
readMachoHeaderPrefixFacts(await readAt(slice.offset, 4)).format !== null
)
return true;
return false;
};
/** Decode every slice's dylib-loading load commands without reading code. */
export const readMachoImage = async (
readAt: ReadAt,
@@ -17,6 +17,7 @@ import { describe, expect, it, vi } from "vitest";
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
import { espFlashSelectionError } from "../../../src/domain/firmware/espFlashSelection.js";
import { readMachoContainer } from "../../../src/domain/apple/machoLoadCommandReader.js";
import { resolveAppleBundleExecutable } from "../../../src/application/AppBundleExecutable.js";
import {
dosMz,
@@ -122,6 +123,76 @@ it.each([MAX_JVM_CLASS_IDENTITY_BYTES, MAX_JVM_CLASS_IDENTITY_BYTES + 1])(
},
);
it.each([
{ length: 32, subtype: CPU.arm64.subtype, established: true },
{ length: 32, subtype: CPU.arm64e.subtype, established: false },
{ length: 28, subtype: CPU.arm64.subtype, established: false },
{ length: 1, subtype: CPU.arm64.subtype, established: false },
{
length: 32,
subtype: CPU.arm64e.subtype,
matchingSibling: true,
established: true,
},
])(
"shares FAT identity evidence after the JVM scan cap (length=$length, subtype=$subtype, matching sibling=$matchingSibling)",
async ({ length, subtype, matchingSibling, established }) => {
const directory = await createTestTempDirectory("rea-fat-class-boundary-");
const path = join(directory, "image");
const sliceOffset = 4096;
const slices = Array.from({ length: 65 }, (_, index) => ({
cpu: CPU.arm64,
bytes:
index === 0
? machoImage({ cpu: { ...CPU.arm64, subtype } })
: index === 1 && matchingSibling
? machoImage({ cpu: CPU.arm64 })
: new Uint8Array(0),
}));
const bytes = Buffer.from(fatImage(slices));
const invalidRow = matchingSibling ? 2 : 1;
const rangeReason = `FAT architecture ${invalidRow} has an invalid slice range`;
bytes.writeUInt32BE(length, 20);
const size = MAX_JVM_CLASS_IDENTITY_BYTES + 1;
const handle = await open(path, "w+");
try {
await handle.write(bytes);
await handle.truncate(size);
const container = await readMachoContainer(async (offset, requested) => {
if (offset === sliceOffset)
expect(requested).toBeLessThanOrEqual(length);
const buffer = Buffer.alloc(requested);
const { bytesRead } = await handle.read(buffer, 0, requested, offset);
return buffer.subarray(0, bytesRead);
}, size);
expect(container).toMatchObject(
established
? {
kind: "fat",
header: {
rangeIssues: expect.arrayContaining([
expect.objectContaining({
reason: rangeReason,
}),
]),
},
}
: { kind: "issue", reason: JVM_CLASS_IDENTITY_LIMIT_REASON },
);
} finally {
await handle.close();
}
expect(
await parseBinaryTarget(path, { hostArchitecture: "arm64" }),
).toMatchObject({
ok: false,
error: {
reason: established ? rangeReason : JVM_CLASS_IDENTITY_LIMIT_REASON,
},
});
},
);
it.each([0x01c0, 0x01c2, 0x01c4, 0xaa64])(
"retains original PE COFF machine %i through file-backed target resolution",
async (peMachine) => {