fix(artifacts): keep universal Mach-O coverage unknown when bytes lie outside every slice

The universal Mach-O reader reported complete coverage whenever lipo and
the FAT table agreed, without comparing the slice ranges with the file.
Bytes appended after the last slice, or placed before a slice beyond the
padding its alignment needs, were never exposed and nothing said so.

readMachoImage now reports where the FAT table ends, including Apple's
hidden ARM64 row. fatUnaccountedBytes measures the bytes outside the
table, every slice and each slice's alignment padding, following lipo's
placement of every slice at the first offset its alignment allows. Any
such bytes keep coverage unknown with a limitation that counts them and
names the first offset. Without a FAT parse only the fixed header is
known, which measures leading bytes conservatively.

The FAT fixture no longer pads its last slice, matching lipo output; the
two tests that needed bytes past the last slice now add them explicitly.

Fixes #15534
This commit is contained in:
Anurag Singh authored and Ysopwnable committed 2026-12-02 13:41:41 +08:00
1 parent 104c1c189e
commit d4cefde290
9 files changed
+252 -11

No files matched your search

+4
View File
@@ -2184,6 +2184,10 @@ row's retained field evidence stays on its slice. A slice lipo did not match is
named from its own CPU identity, qualified by its FAT offset when that name
repeats. When REA cannot parse the FAT table, lipo's rows are inventoried and a
count disagreement makes coverage `unknown`. A malformed FAT table still fails.
lipo places each slice at the first offset its declared alignment allows, so
only that gap is padding. Bytes after the last slice, or before a slice beyond
its padding, keep coverage `unknown`, and a limitation states how many there
are and where the first one starts.
If native DMG child traversal is unavailable after carrier identification,
the typed failure retains a revalidated root-only inventory under
+53
View File
@@ -28,6 +28,7 @@ import {
readMachoImage,
type ReadAt,
} from "../domain/apple/machoLoadCommandReader.js";
import { fatUnaccountedBytes } from "../domain/apple/machoContainer.js";
import type { StableRegularFileDescriptor } from "../filesystem/RegularFile.js";
import { readFileHandleRange } from "../filesystem/readFileHandleRange.js";
import type { ArtifactIntegrityPolicyName } from "../domain/artifactIntegrityPolicy.js";
@@ -38,6 +39,18 @@ import {
type LipoArchitecture,
} from "../domain/apple/lipo.js";
/** fat.h: the magic and architecture count that precede every FAT table. */
const FAT_HEADER_BYTES = 8;
type FatPlacedSlice = Parameters<typeof fatUnaccountedBytes>[2][number];
/** lipo reports alignment in bytes; a FAT row declares its power of two. */
const alignmentExponent = (alignment: number | null): number | null => {
if (alignment === null || alignment <= 0) return null;
const exponent = Math.log2(alignment);
return Number.isInteger(exponent) ? exponent : null;
};
/** Read-only universal Mach-O slice reader backed by native lipo metadata. */
export class MachOSliceArtifactReader implements ArtifactReader {
readonly format = "file" as const;
@@ -219,6 +232,11 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"Apple hidden ARM64 slice could not be verified against the FAT table",
);
const slices = structural.status === "parsed" ? structural.slices : null;
// Without a FAT parse only the fixed FAT header is known to precede the
// slices, which measures any bytes before the first slice conservatively.
const tableEnd =
(structural.status === "parsed" ? structural.fatTableEnd : undefined) ??
FAT_HEADER_BYTES;
const hiddenSlices =
structural.status === "parsed" ? (structural.hiddenSlices ?? []) : [];
const matchingSlices = new Map<LipoArchitecture, MachoSlice>();
@@ -292,6 +310,15 @@ export class MachOSliceArtifactReader implements ArtifactReader {
reported === undefined ? [] : lipoRowEvidence(reported),
);
}
this.#recordUnaccountedBytes(
tableEnd,
fileSize,
[...slices, ...hiddenSlices].map((slice) => ({
offset: slice.slice_offset,
size: slice.slice_size,
alignmentExponent: slice.fat_alignment_exponent,
})),
);
return;
}
// Without a FAT parse, lipo's rows are the only slice list; a count
@@ -303,6 +330,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
`Integrity limitation: lipo's architecture counts disagree with its own records (${disagreements.join("; ")}). No structural FAT parse was available, so slice ranges are based on lipo's records and the slice list may be incomplete.`,
],
};
const placed: FatPlacedSlice[] = [];
for (const architecture of architectures) {
this.#assertOpen(signal);
const structuralSlice = matchingSlices.get(architecture);
@@ -314,6 +342,13 @@ export class MachOSliceArtifactReader implements ArtifactReader {
"lipo omitted a universal slice byte range",
{ integrityCheck: "layout-consistency" },
);
placed.push({
offset,
size: sliceSize,
alignmentExponent:
structuralSlice?.fat_alignment_exponent ??
alignmentExponent(architecture.alignment),
});
yield this.#sliceEntry(architecture.name, offset, sliceSize, fileSize, [
...architecture.limitations,
...(structural.status === "not-mach-o"
@@ -336,6 +371,24 @@ export class MachOSliceArtifactReader implements ArtifactReader {
...lipoCpuSourceLimitations(architecture),
]);
}
this.#recordUnaccountedBytes(tableEnd, fileSize, placed);
}
/** Keep coverage unknown when bytes lie outside the FAT table and every slice. */
#recordUnaccountedBytes(
tableEnd: number,
fileSize: number,
slices: readonly FatPlacedSlice[],
): void {
const unaccounted = fatUnaccountedBytes(tableEnd, fileSize, slices);
if (unaccounted.firstOffset === null) return;
this.#coverage = {
status: "unknown",
limitations: [
...this.#coverage.limitations,
`${String(unaccounted.bytes)} byte(s) in ${String(unaccounted.ranges)} range(s), the first at offset ${String(unaccounted.firstOffset)}, lie outside the FAT table, every slice and its alignment padding and were not exposed as entries.`,
],
};
}
/** Inventory one slice range after checking it lies within the artifact. */
+8 -5
View File
@@ -258,8 +258,9 @@ export const machoImageWithUnknownCommand = (
};
/**
* A FAT container whose slices start on 4 KiB boundaries. Headers are
* big-endian unless `littleEndian` selects the swapped FAT_CIGAM magics.
* A FAT container whose slices start on 4 KiB boundaries and that ends with
* its last slice, as lipo writes it. Headers are big-endian unless
* `littleEndian` selects the swapped FAT_CIGAM magics.
*/
export const fatImage = (
slices: readonly {
@@ -271,10 +272,12 @@ export const fatImage = (
): Uint8Array => {
const entrySize = wide ? 32 : 20;
const offsets: number[] = [];
let end = 4096;
let next = 4096;
let end = next;
for (const slice of slices) {
offsets.push(end);
end += Math.ceil(slice.bytes.length / 4096) * 4096;
offsets.push(next);
end = next + slice.bytes.length;
next += Math.ceil(slice.bytes.length / 4096) * 4096;
}
const bytes = new Uint8Array(end);
const view = new DataView(bytes.buffer);
@@ -1769,7 +1769,9 @@ describe("Mach-O load command reader: reads and validates universal binary slice
}),
});
}
const unaligned = original.slice();
// One spare byte keeps the shifted slice inside the file.
const unaligned = new Uint8Array(original.length + 1);
unaligned.set(original);
new DataView(unaligned.buffer).setUint32(16, 4097, false);
expect(await read(unaligned)).toMatchObject({
status: "failed",
@@ -2220,12 +2222,14 @@ it("reads the common header at exactly its supported physical boundaries", async
it("does not borrow Mach-O header bytes beyond a short FAT declaration", async () => {
const short = machoImage({ cpu: CPU.arm64 });
const bytes = fatImage([
const fat = fatImage([
{ cpu: CPU.x86_64, bytes: machoImage({ cpu: CPU.x86_64 }) },
{ cpu: CPU.arm64, bytes: short.subarray(0, 12) },
]);
const { offset, size } = fatSliceRange(bytes, 1);
const { offset, size } = fatSliceRange(fat, 1);
// Keep a complete header physically readable after the declared slice ends.
const bytes = new Uint8Array(offset + short.length);
bytes.set(fat);
bytes.set(short, offset);
const readAt = vi.fn(readerOf(bytes));
const result = await readMachoImage(readAt, bytes.length);
@@ -16,6 +16,7 @@ import { isJvmClassFile } from "../../domain/apple/jvmClassFile.js";
import {
classifyFatContainerIdentity,
classifyFatContainerEvidence,
fatUnaccountedBytes,
findOverlappingFatSlices,
readFatContainerHeader,
readFatSliceDeclarations,
@@ -488,3 +489,55 @@ describe("FAT slice header identity and bounds", () => {
).toEqual(expected);
});
});
describe("FAT unaccounted bytes", () => {
it("admits only the padding each slice's alignment needs, in physical order", () => {
const slice = (offset: number, size: number, exponent: number | null) => ({
offset,
size,
alignmentExponent: exponent,
});
// Table ends at 48; slices listed out of byte order.
expect(
fatUnaccountedBytes(48, 0x81c8, [
slice(0x4000, 0x41c8, 14),
slice(0x1000, 0x10b0, 12),
]),
).toEqual({ bytes: 0, ranges: 0, firstOffset: null });
// A slice a page past its aligned start, and bytes after the last slice.
expect(
fatUnaccountedBytes(48, 0x3010, [
slice(0x1000, 0x10, 12),
slice(0x3000, 0x8, 12),
]),
).toEqual({ bytes: 0x1000 + 8, ranges: 2, firstOffset: 0x2000 });
// Without a declared alignment no gap is padding.
expect(
fatUnaccountedBytes(48, 0x1010, [slice(0x1000, 0x10, null)]),
).toEqual({ bytes: 0x1000 - 48, ranges: 1, firstOffset: 48 });
});
it("ends the FAT table after Apple's hidden ARM64 row", async () => {
const fat = fatImage([
{
cpu: { type: 12, subtype: 9 },
bytes: machoImage({ cpu: { type: 12, subtype: 9 }, wide: false }),
},
{ cpu: CPU.arm64, bytes: machoImage({ cpu: CPU.arm64 }) },
]);
expect(await readMachoImage(readerOf(fat), fat.length)).toMatchObject({
status: "parsed",
fatTableEnd: 48,
});
// One declared row; the second row becomes Apple's hidden ARM64 row.
const hidden = fat.slice();
new DataView(hidden.buffer).setUint32(4, 1, false);
expect(await readMachoImage(readerOf(hidden), hidden.length)).toMatchObject(
{
status: "parsed",
hiddenSlices: [expect.objectContaining({ hidden: true })],
fatTableEnd: 48,
},
);
});
});
+5
View File
@@ -123,6 +123,11 @@ export type MachoImageFacts =
readonly slices: readonly MachoSlice[];
/** Apple lipo's ARM64 compatibility row, stored beyond raw nfat_arch. */
readonly hiddenSlices?: readonly MachoSlice[];
/**
* End of a universal container's FAT table, including Apple's hidden
* ARM64 row when one is declared. Absent for a thin image.
*/
readonly fatTableEnd?: number;
}
| { readonly status: "failed"; readonly failure: MachoReadFailure }
| { readonly status: "not-mach-o" };
+43
View File
@@ -569,6 +569,49 @@ export const fatSliceOverlapReason = (
): string =>
`Mach-O slices ${overlap[0].index} and ${overlap[1].index} overlap.`;
/** Bytes of a universal container that neither its FAT table nor any slice explains. */
export interface FatUnaccountedBytes {
readonly bytes: number;
readonly ranges: number;
/** Start of the first unaccounted range; null when every byte is accounted. */
readonly firstOffset: number | null;
}
/**
* Measure the bytes of a universal container outside its FAT table and every
* slice. lipo places each slice at the first offset its declared alignment
* admits after the bytes before it, so only that gap is padding. A slice
* placed further out, or bytes after the last slice, leave bytes no structure
* describes. A slice whose alignment is unknown admits no padding.
*/
export const fatUnaccountedBytes = (
tableEnd: number,
fileSize: number,
slices: readonly {
readonly offset: number;
readonly size: number;
readonly alignmentExponent: number | null;
}[],
): FatUnaccountedBytes => {
let reach = tableEnd;
let bytes = 0;
let ranges = 0;
let firstOffset: number | null = null;
const gapUntil = (start: number, end: number): void => {
if (end <= start) return;
bytes += end - start;
ranges += 1;
firstOffset ??= start;
};
for (const slice of [...slices].sort((a, b) => a.offset - b.offset)) {
const alignment = 2 ** (slice.alignmentExponent ?? 0);
gapUntil(Math.ceil(reach / alignment) * alignment, slice.offset);
reach = Math.max(reach, slice.offset + slice.size);
}
gapUntil(reach, fileSize);
return { bytes, ranges, firstOffset };
};
/** Validate byte-range and table/header identity facts shared by Mach-O readers. */
export const validateFatSlice = (
declaration: FatSliceDeclaration,
+9 -3
View File
@@ -52,6 +52,10 @@ import { decodeStrictUtf8 } from "../strictUtf8.js";
export type ReadAt = (offset: number, length: number) => Promise<Uint8Array>;
export { MAX_LOAD_COMMAND_BYTES };
/** A 32-bit FAT architecture row, including Apple's hidden ARM64 row. */
const FAT_ARCH_ROW_BYTES = 20;
/**
* Identical `LC_LAZY_LOAD_DYLIB_INFO` commands are 16 bytes, so the load-command
* byte cap alone would retain about a million dependency results. Stop before
@@ -284,6 +288,8 @@ export const readMachoImage = async (
status: "parsed",
slices: await readFatSlices(readAt, header.slices),
...(hiddenSlice === null ? {} : { hiddenSlices: [hiddenSlice] }),
fatTableEnd:
header.tableEnd + (hiddenSlice === null ? 0 : FAT_ARCH_ROW_BYTES),
};
} catch (cause: unknown) {
if (cause instanceof MachoReadError)
@@ -309,11 +315,11 @@ const readAppleHiddenArm64Row = async (
): Promise<HiddenFatRow | null> => {
if (header.wide) return null;
const firstOffset = Math.min(...header.slices.map(({ offset }) => offset));
const end = header.tableEnd + 20;
const end = header.tableEnd + FAT_ARCH_ROW_BYTES;
if (end > fileSize || end > firstOffset) return null;
const bytes = await readAt(header.tableEnd, 20);
const bytes = await readAt(header.tableEnd, FAT_ARCH_ROW_BYTES);
// `end` lies inside the measured file, so a short read means it changed.
if (bytes.byteLength < 20)
if (bytes.byteLength < FAT_ARCH_ROW_BYTES)
return {
status: "failed",
failure: machoFailure.changed(
@@ -127,6 +127,76 @@ describe("artifact Mach-O slices", () => {
});
});
describe("artifact Mach-O slice coverage", () => {
const x86 = machoImage({ cpu: CPU.x86_64 });
const arm = machoImage({ cpu: CPU.arm64 });
const coverageOf = async (bytes: Uint8Array, armOffset = 8192) => {
const root = await createTestTempDirectory("rea-slices-coverage-");
const binary = join(root, "fat");
await writeFile(binary, bytes);
const runner: NativeCommandRunner = {
run: () =>
Promise.resolve(
ok({
tool: "lipo",
executable: "/usr/bin/lipo",
executableSha256: "1".repeat(64),
toolVersion: null,
versionReason: "fixture",
arguments: ["-detailed_info", binary],
stdout: `architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 4096\n size ${String(x86.length)}\n align 2^12 (4096)\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset ${String(armOffset)}\n size ${String(arm.length)}\n align 2^12 (4096)\n`,
stderr: "",
stdoutBytes: 1,
stderrBytes: 0,
exitCode: 0,
signal: null,
}),
),
};
const reader = new MachOSliceArtifactReader(binary, {}, runner);
onTestFinished(() => reader.close());
const coverage: { status: string; limitations: readonly string[] }[] = [];
const paths: string[] = [];
for await (const entry of reader.entries(undefined, {
onCoverage: (observed) => coverage.push(observed),
}))
paths.push(entry.path);
expect(paths).toEqual(["slices/x86_64", "slices/arm64"]);
return coverage;
};
const unaccounted = (bytes: number, first: number): string =>
`${String(bytes)} byte(s) in 1 range(s), the first at offset ${String(first)}, lie outside the FAT table, every slice and its alignment padding and were not exposed as entries.`;
const image = fatImage([
{ cpu: CPU.x86_64, bytes: x86 },
{ cpu: CPU.arm64, bytes: arm },
]);
it("is complete when only alignment padding separates the table and slices", async () => {
expect(await coverageOf(image)).toEqual([
{ status: "complete", limitations: [] },
]);
});
it("stays unknown when bytes follow the last slice", async () => {
expect(
await coverageOf(Buffer.concat([image, Buffer.from("appended")])),
).toEqual([
{ status: "unknown", limitations: [unaccounted(8, image.length)] },
]);
});
it("stays unknown when a slice starts past the padding its alignment needs", async () => {
// The arm64 slice could start at 8192; a page of unexplained bytes precedes it.
const moved = Buffer.alloc(12288 + arm.length);
moved.set(image.subarray(0, 8192));
moved.set(arm, 12288);
moved.writeUInt32BE(12288, 8 + 20 + 8);
expect(await coverageOf(moved, 12288)).toEqual([
{ status: "unknown", limitations: [unaccounted(4096, 8192)] },
]);
});
});
describe("artifact Mach-O slice integrity", () => {
it.each([
["CPU type", "cputype 16777223"],