mirror of
https://github.com/morluto/rea.git
synced 2026-12-03 21:46:01 +00:00
perf(apple-ips): stream Mach-O join headers over FileHandle (#13894)
* perf(apple-ips): stream Mach-O join headers over FileHandle * fix(apple-ips): retain only verified Mach-O joins
This commit is contained in:
1 parent
eae4b4cd2e
commit
8e379a31d8
4 files changed
+156
-51
No files matched your search
@@ -1,6 +1,9 @@
|
||||
import { LC } from "../../domain/apple/machoLoadCommandCodes.js";
|
||||
import { readMachoContainer } from "../../domain/apple/machoLoadCommandReader.js";
|
||||
import { readUniversalMachoSlice } from "../../domain/apple/machoImageSelection.js";
|
||||
import {
|
||||
readMachoHeaderPrefixFacts,
|
||||
validateFatSlice,
|
||||
} from "../../domain/apple/machoContainer.js";
|
||||
import {
|
||||
readMachoLoadCommandTableHeader,
|
||||
MachoLoadCommandCursor,
|
||||
@@ -9,6 +12,7 @@ import {
|
||||
readMachoSegmentHeader,
|
||||
admitMachoSegmentCommand,
|
||||
} from "../../domain/apple/machoSegmentHeader.js";
|
||||
import type { StableArtifactHandle } from "../../resources/index.js";
|
||||
import { FieldReader } from "./AppleIpsFieldReader.js";
|
||||
import {
|
||||
machoArchitectureFamily,
|
||||
@@ -50,11 +54,12 @@ type SliceParse =
|
||||
| { readonly kind: "slices"; readonly slices: readonly SliceIdentity[] }
|
||||
| { readonly kind: "unreadable"; readonly reason: string };
|
||||
|
||||
const readSliceIdentities = async (bytes: Buffer): Promise<SliceParse> => {
|
||||
const container = await readMachoContainer(
|
||||
async (offset, length) => bytes.subarray(offset, offset + length),
|
||||
bytes.length,
|
||||
);
|
||||
const MACHO_HEADER_PREFIX_BYTES = 32;
|
||||
|
||||
const readSliceIdentities = async (
|
||||
handle: Pick<StableArtifactHandle, "size" | "readRange">,
|
||||
): Promise<SliceParse> => {
|
||||
const container = await readMachoContainer(handle.readRange, handle.size);
|
||||
if (container.kind === "issue")
|
||||
return { kind: "unreadable", reason: container.reason };
|
||||
if (container.kind === "not-mach-o")
|
||||
@@ -63,7 +68,7 @@ const readSliceIdentities = async (bytes: Buffer): Promise<SliceParse> => {
|
||||
reason: "Selected join is not a Mach-O image",
|
||||
};
|
||||
if (container.kind === "thin") {
|
||||
const slice = sliceAt(bytes, 0n, 0);
|
||||
const slice = await sliceAt(handle.readRange, 0, handle.size, 0);
|
||||
return slice === null
|
||||
? {
|
||||
kind: "unreadable",
|
||||
@@ -86,13 +91,23 @@ const readSliceIdentities = async (bytes: Buffer): Promise<SliceParse> => {
|
||||
return { kind: "unreadable", reason: "Join slice allowance exceeded" };
|
||||
const slices: SliceIdentity[] = [];
|
||||
for (const declaration of declarations) {
|
||||
const selected = readUniversalMachoSlice(bytes, header, declaration);
|
||||
if (!selected.ok)
|
||||
return { kind: "unreadable", reason: selected.error.message };
|
||||
const slice = sliceAt(
|
||||
selected.value,
|
||||
BigInt(declaration.offset),
|
||||
const prefixLength = Math.min(declaration.size, MACHO_HEADER_PREFIX_BYTES);
|
||||
const prefix =
|
||||
prefixLength === 0
|
||||
? Buffer.alloc(0)
|
||||
: await handle.readRange(declaration.offset, prefixLength);
|
||||
const identity = readMachoHeaderPrefixFacts(prefix).identity;
|
||||
const message =
|
||||
identity === null
|
||||
? `FAT architecture ${declaration.index} has a truncated Mach-O identity`
|
||||
: validateFatSlice(declaration, handle.size, header.tableEnd, identity);
|
||||
if (message !== null) return { kind: "unreadable", reason: message };
|
||||
const slice = await sliceAt(
|
||||
handle.readRange,
|
||||
declaration.offset,
|
||||
declaration.size,
|
||||
declaration.index,
|
||||
prefix,
|
||||
);
|
||||
if (slice === null)
|
||||
return {
|
||||
@@ -104,14 +119,28 @@ const readSliceIdentities = async (bytes: Buffer): Promise<SliceParse> => {
|
||||
return { kind: "slices", slices };
|
||||
};
|
||||
|
||||
const sliceAt = (
|
||||
bytes: Buffer,
|
||||
offset: bigint,
|
||||
const sliceAt = async (
|
||||
readRange: StableArtifactHandle["readRange"],
|
||||
sliceOffset: number,
|
||||
sliceSize: number,
|
||||
index: number,
|
||||
): SliceIdentity | null => {
|
||||
const parsed = readMachoLoadCommandTableHeader(bytes, bytes.length);
|
||||
prefetchedHeader?: Buffer,
|
||||
): Promise<SliceIdentity | null> => {
|
||||
const headerPrefix =
|
||||
prefetchedHeader ??
|
||||
(sliceSize === 0
|
||||
? Buffer.alloc(0)
|
||||
: await readRange(
|
||||
sliceOffset,
|
||||
Math.min(sliceSize, MACHO_HEADER_PREFIX_BYTES),
|
||||
));
|
||||
const parsed = readMachoLoadCommandTableHeader(headerPrefix, sliceSize);
|
||||
if (!parsed.ok || parsed.value === null) return null;
|
||||
const header = parsed.value;
|
||||
const tableBytes =
|
||||
header.commandBytes === 0
|
||||
? Buffer.alloc(0)
|
||||
: await readRange(sliceOffset + header.headerSize, header.commandBytes);
|
||||
const cursor = new MachoLoadCommandCursor(header);
|
||||
let uuid: string | null = null;
|
||||
let uuidSeen = false;
|
||||
@@ -119,7 +148,7 @@ const sliceAt = (
|
||||
for (;;) {
|
||||
const next = cursor.nextOffset;
|
||||
if (next === null) break;
|
||||
const command = bytes.subarray(header.headerSize + next);
|
||||
const command = tableBytes.subarray(next);
|
||||
const frame = cursor.read(command);
|
||||
if (!frame.ok) return null;
|
||||
const payload = command.subarray(0, frame.value.size);
|
||||
@@ -145,7 +174,7 @@ const sliceAt = (
|
||||
segment.value,
|
||||
payload.length,
|
||||
wide ? 64 : 32,
|
||||
bytes.length,
|
||||
sliceSize,
|
||||
).ok
|
||||
)
|
||||
return null;
|
||||
@@ -162,7 +191,7 @@ const sliceAt = (
|
||||
const { cpuType, cpuSubtype } = header.identity;
|
||||
return {
|
||||
index,
|
||||
offset,
|
||||
offset: BigInt(sliceOffset),
|
||||
cpuType,
|
||||
cpuSubtype,
|
||||
arch: machoArchitectureName(cpuType, cpuSubtype),
|
||||
@@ -237,24 +266,22 @@ const architectureRelation = (
|
||||
: "mismatch";
|
||||
};
|
||||
|
||||
/** Resolve every report image and frame against the selected artifact. */
|
||||
/** Resolve every report image and frame against the selected artifact handle. */
|
||||
export const resolveAppleIpsJoin = async (
|
||||
report: AppleIps,
|
||||
artifact: {
|
||||
artifact: Pick<StableArtifactHandle, "sha256" | "size" | "readRange"> & {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly bytes: Buffer;
|
||||
},
|
||||
input: { readonly path: string; readonly max_join_bytes: number },
|
||||
read: FieldReader,
|
||||
): Promise<AppleIpsJoin> => {
|
||||
const parsed = await readSliceIdentities(artifact.bytes);
|
||||
const parsed = await readSliceIdentities(artifact);
|
||||
if (parsed.kind === "unreadable")
|
||||
return {
|
||||
status: "unreadable",
|
||||
path: input.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes.length,
|
||||
bytes: artifact.size,
|
||||
reason: parsed.reason,
|
||||
};
|
||||
const matches: AppleIpsJoinDigest[] = [];
|
||||
@@ -346,7 +373,7 @@ export const resolveAppleIpsJoin = async (
|
||||
status: "selected",
|
||||
path: input.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes.length,
|
||||
bytes: artifact.size,
|
||||
slices: parsed.slices.map((slice) => ({
|
||||
index: slice.index,
|
||||
offset: read.decimalText64(slice.offset),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { appendFile, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
@@ -60,3 +61,44 @@ it("retains completed join facts when cancellation arrives during join parsing",
|
||||
await provider.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains the IPS and verified identity without publishing a changed Mach-O join", async () => {
|
||||
const root = await createTestTempDirectory("rea-ips-join-changed-");
|
||||
const path = join(root, "report.ips");
|
||||
const joinPath = join(root, "image.bin");
|
||||
await writeFile(path, appleIpsBytes());
|
||||
const image = Buffer.alloc(32);
|
||||
image.writeUInt32LE(0xfeedfacf, 0);
|
||||
image.writeUInt32LE(0x0100000c, 4);
|
||||
image.writeUInt32LE(2, 12);
|
||||
await writeFile(joinPath, image);
|
||||
const input = inspectAppleIpsInputSchema.parse({ path, join_path: joinPath });
|
||||
const provider = new AppleIpsProvider();
|
||||
const readContainer = machoReader.readMachoContainer;
|
||||
const spy = vi
|
||||
.spyOn(machoReader, "readMachoContainer")
|
||||
.mockImplementationOnce(async (...args) => {
|
||||
const container = await readContainer(...args);
|
||||
await appendFile(joinPath, Buffer.of(1));
|
||||
return container;
|
||||
});
|
||||
try {
|
||||
const changed = await provider.inspect(input);
|
||||
if (changed.ok) throw new Error("Expected changed Mach-O to be rejected");
|
||||
expect(changed.error).toMatchObject({
|
||||
_tag: "AnalysisArtifactChangedError",
|
||||
partialObservation: {
|
||||
artifact: { path },
|
||||
join: null,
|
||||
join_artifact: {
|
||||
path: joinPath,
|
||||
sha256: createHash("sha256").update(image).digest("hex"),
|
||||
bytes: image.length,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
spy.mockRestore();
|
||||
await provider.close();
|
||||
}
|
||||
});
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
projectArtifactCloseFailure,
|
||||
ArtifactReaderFailure,
|
||||
readStableArtifact,
|
||||
withStableArtifactHandle,
|
||||
artifactFileCompletion,
|
||||
artifactFilePrimaryFacts,
|
||||
type ArtifactFilePrimaryFacts,
|
||||
assertArtifactReadActive,
|
||||
@@ -70,9 +72,13 @@ export class AppleIpsProvider implements AppleIpsPort {
|
||||
|
||||
async inspect(input: InspectAppleIpsInput, options?: ExecutionOptions) {
|
||||
let completedReport: AppleIps | undefined;
|
||||
let candidateJoin: AppleIps | undefined;
|
||||
let activePath = input.path;
|
||||
let activeField: "path" | "join_path" = "path";
|
||||
let completedSnapshot: StableArtifactSnapshot | undefined;
|
||||
let completedSnapshot:
|
||||
| StableArtifactSnapshot
|
||||
| { readonly sha256: string; readonly bytes: number }
|
||||
| undefined;
|
||||
const read = new FieldReader(input.max_integer_text_bytes);
|
||||
try {
|
||||
return await this.#resources.run(async () => {
|
||||
@@ -98,34 +104,63 @@ export class AppleIpsProvider implements AppleIpsPort {
|
||||
completedReport = report;
|
||||
assertArtifactReadActive(options?.signal);
|
||||
if (input.join_path === undefined) return ok(report);
|
||||
activePath = input.join_path;
|
||||
const joinPath = input.join_path;
|
||||
activePath = joinPath;
|
||||
activeField = "join_path";
|
||||
completedSnapshot = undefined;
|
||||
const joinArtifact = await readStableArtifact(
|
||||
input.join_path,
|
||||
completedReport = await withStableArtifactHandle(
|
||||
joinPath,
|
||||
input.max_join_bytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
completedSnapshot = joinArtifact;
|
||||
assertArtifactReadActive(options?.signal);
|
||||
completedReport = {
|
||||
...report,
|
||||
join: await resolveAppleIpsJoin(
|
||||
report,
|
||||
{ ...joinArtifact, path: input.join_path },
|
||||
{
|
||||
path: input.join_path,
|
||||
max_join_bytes: input.max_join_bytes,
|
||||
{
|
||||
retainBytes: (size) => Math.min(size, 4096),
|
||||
signal: options?.signal,
|
||||
resourceScope: this.#resources,
|
||||
onIdentity: (identity) => {
|
||||
completedSnapshot = identity;
|
||||
},
|
||||
read,
|
||||
),
|
||||
};
|
||||
},
|
||||
async (joinHandle) => {
|
||||
assertArtifactReadActive(options?.signal);
|
||||
const readJoinRange: typeof joinHandle.readRange = (
|
||||
offset,
|
||||
length,
|
||||
) =>
|
||||
offset >= 0 &&
|
||||
length >= 0 &&
|
||||
offset + length <= joinHandle.prefix.length
|
||||
? Promise.resolve(
|
||||
joinHandle.prefix.subarray(offset, offset + length),
|
||||
)
|
||||
: joinHandle.readRange(offset, length);
|
||||
candidateJoin = {
|
||||
...report,
|
||||
join: await resolveAppleIpsJoin(
|
||||
report,
|
||||
{
|
||||
path: joinPath,
|
||||
sha256: joinHandle.sha256,
|
||||
size: joinHandle.size,
|
||||
readRange: readJoinRange,
|
||||
},
|
||||
{
|
||||
path: joinPath,
|
||||
max_join_bytes: input.max_join_bytes,
|
||||
},
|
||||
read,
|
||||
),
|
||||
};
|
||||
return candidateJoin;
|
||||
},
|
||||
);
|
||||
assertArtifactReadActive(options?.signal);
|
||||
return ok(completedReport);
|
||||
});
|
||||
} catch (cause) {
|
||||
if (
|
||||
candidateJoin !== undefined &&
|
||||
artifactFileCompletion(cause)?.value === candidateJoin
|
||||
)
|
||||
completedReport = candidateJoin;
|
||||
const primary = appleIpsFailurePrimary(
|
||||
artifactFilePrimaryFacts(cause),
|
||||
{
|
||||
|
||||
@@ -287,7 +287,8 @@ export const withStableArtifactHandle = async <Value>(
|
||||
throw cause;
|
||||
});
|
||||
await verifyState();
|
||||
assertArtifactReadActive(options.signal);
|
||||
// The descriptor owner records this verified completion before checking
|
||||
// finalization cancellation, so cleanup errors can retain the value.
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user