diff --git a/src/native/apple/AppleIpsMachOJoin.ts b/src/native/apple/AppleIpsMachOJoin.ts index c9c6f1eeb39..fbbe9db82e8 100644 --- a/src/native/apple/AppleIpsMachOJoin.ts +++ b/src/native/apple/AppleIpsMachOJoin.ts @@ -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 => { - 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, +): Promise => { + 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 => { 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 => { 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 => { 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 => { + 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 & { readonly path: string; - readonly sha256: string; - readonly bytes: Buffer; }, input: { readonly path: string; readonly max_join_bytes: number }, read: FieldReader, ): Promise => { - 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), diff --git a/src/native/apple/AppleIpsProvider.test.ts b/src/native/apple/AppleIpsProvider.test.ts index aafc1b04e61..7d2f7b5cdcc 100644 --- a/src/native/apple/AppleIpsProvider.test.ts +++ b/src/native/apple/AppleIpsProvider.test.ts @@ -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(); + } +}); diff --git a/src/native/apple/AppleIpsProvider.ts b/src/native/apple/AppleIpsProvider.ts index 1c56bc8dd6d..de5830c8e67 100644 --- a/src/native/apple/AppleIpsProvider.ts +++ b/src/native/apple/AppleIpsProvider.ts @@ -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), { diff --git a/src/resources/readStableArtifact.ts b/src/resources/readStableArtifact.ts index f2cb1bca8d9..3bdc9770cb8 100644 --- a/src/resources/readStableArtifact.ts +++ b/src/resources/readStableArtifact.ts @@ -287,7 +287,8 @@ export const withStableArtifactHandle = async ( 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; }, });