From 1e5956a5878a0e9a0a29c6cc2df9ab9a79cb341c Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Thu, 19 Nov 2026 06:51:55 -0500 Subject: [PATCH] fix(artifacts): verify FAT identities before Bun and Node SEA claims (#12288) * fix(artifacts): verify FAT identities before Bun and Node SEA claims * fix(node-sea): bound thin Mach-O header reads to their slice * fix(bun): exclude rejected FAT slices from trailer fallback --- src/artifacts/NodeSeaArtifactReader.test.ts | 130 +++++++++++++++++++ src/artifacts/bun/BunModuleGraph.test.ts | 137 ++++++++++++++++++++ src/artifacts/bun/BunModuleGraphLayout.ts | 118 ++++++++++++----- src/artifacts/nodeSea/NodeSeaLocation.ts | 58 ++++++--- tests/fixtures/universalMacho.ts | 5 +- 5 files changed, 395 insertions(+), 53 deletions(-) diff --git a/src/artifacts/NodeSeaArtifactReader.test.ts b/src/artifacts/NodeSeaArtifactReader.test.ts index 23a71e144b..b1371d25e2 100644 --- a/src/artifacts/NodeSeaArtifactReader.test.ts +++ b/src/artifacts/NodeSeaArtifactReader.test.ts @@ -44,6 +44,11 @@ import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { createDeferred } from "../../tests/fixtures/binarySession.js"; import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js"; import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js"; +import { + CPU_ARM64, + CPU_X86_64, + universalMacho, +} from "../../tests/fixtures/universalMacho.js"; import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js"; import { classifyAndHashRootForInventory } from "./inventory/classify.js"; import { DEFAULT_NODE_SEA_READER_LIMITS } from "../domain/artifactReaderLimits.js"; @@ -292,6 +297,131 @@ it("accepts the __NODE_SEA segment spelling and a universal Mach-O slice", async ).toMatchObject({ carrier: "mach-o", fuse_state: "set" }); }); +it.each(["cpu-type", "cpu-subtype"] as const)( + "requires a matching FAT %s for a Node SEA section claim", + async (field) => { + const candidate = { + bytes: nodeSeaMachO(populated), + cpuType: CPU_ARM64, + cpuSubtype: 0, + }; + const conflicting = { + ...candidate, + ...(field === "cpu-type" + ? { tableCpuType: CPU_X86_64 } + : { tableCpuSubtype: 1 }), + }; + const locate = async ( + bytes: Buffer, + limits = DEFAULT_NODE_SEA_READER_LIMITS, + ) => { + const handle = await open( + await writeCarrier("fat-sea-identity", bytes), + "r", + ); + try { + return await locateNodeSea(handle, bytes.length, undefined, limits); + } finally { + await handle.close(); + } + }; + const matching = universalMacho([candidate]); + expect(await locate(matching.bytes)).toMatchObject({ + carrier: "mach-o", + blobOffset: + matching.slices[0]!.offset + candidate.bytes.readUInt32LE(32 + 72 + 48), + }); + const wrong = universalMacho([conflicting]); + await expect(locate(wrong.bytes)).rejects.toMatchObject({ + reason: "format", + message: expect.stringContaining("CPU type/subtype disagrees"), + }); + const unrelated = { + ...conflicting, + bytes: nodeSeaMachO({ segmentName: "__DATA", sectionName: "__notes" }), + }; + expect(await locate(universalMacho([unrelated]).bytes)).toBeUndefined(); + const sibling = { + ...candidate, + bytes: nodeSeaMachO({ + ...populated, + main: "console.log('independent');", + }), + }; + const mixed = universalMacho([conflicting, sibling]); + expect(await locate(mixed.bytes)).toMatchObject({ + carrier: "mach-o", + blobOffset: + mixed.slices[1]!.offset + sibling.bytes.readUInt32LE(32 + 72 + 48), + }); + const oversizedCommands = nodeSeaMachO({ + ...populated, + extraBlobs: [buildNodeSeaBlob({ main: "console.log(2);" })], + }); + const limited = universalMacho([ + { ...conflicting, bytes: oversizedCommands }, + sibling, + ]); + expect( + await locate(limited.bytes, { + ...DEFAULT_NODE_SEA_READER_LIMITS, + recognition_load_command_bytes: sibling.bytes.readUInt32LE(20), + }), + ).toMatchObject({ + carrier: "mach-o", + blobOffset: + limited.slices[1]!.offset + sibling.bytes.readUInt32LE(32 + 72 + 48), + }); + }, +); + +it("reads a 28-byte FAT header without borrowing the following padding", async () => { + const thin = Buffer.alloc(28); + thin.writeUInt32LE(0xfeedface, 0); + thin.writeUInt32LE(2, 12); + const good = nodeSeaMachO(populated); + const fixture = universalMacho([ + { bytes: thin, cpuType: 7, cpuSubtype: 3 }, + { bytes: good, cpuType: CPU_ARM64, cpuSubtype: 0 }, + ]); + const short = fixture.slices[0]!; + const sibling = fixture.slices[1]!; + fixture.bytes.fill(0xa5, short.offset + short.size, sibling.offset); + + const handle = await open( + await writeCarrier("short-fat-header", fixture.bytes), + "r", + ); + const read = vi.spyOn(handle, "read"); + try { + expect(await locateNodeSea(handle, fixture.bytes.length)).toMatchObject({ + carrier: "mach-o", + blobOffset: sibling.offset + good.readUInt32LE(32 + 72 + 48), + }); + const beforeSibling = read.mock.calls.flatMap((args) => { + const [, , length, offset]: readonly unknown[] = args; + return typeof offset === "number" && + typeof length === "number" && + offset >= short.offset && + offset < sibling.offset + ? [{ offset, length }] + : []; + }); + expect(beforeSibling).toContainEqual({ + offset: short.offset, + length: thin.length, + }); + expect( + beforeSibling.every( + ({ offset, length }) => offset + length <= short.offset + short.size, + ), + ).toBe(true); + } finally { + read.mockRestore(); + await handle.close(); + } +}); + it("reads a 32-bit and a big-endian Mach-O section", async () => { for (const bytes of [ nodeSeaMachO({ ...populated, bits: 32 }), diff --git a/src/artifacts/bun/BunModuleGraph.test.ts b/src/artifacts/bun/BunModuleGraph.test.ts index 199e59b091..f49900825b 100644 --- a/src/artifacts/bun/BunModuleGraph.test.ts +++ b/src/artifacts/bun/BunModuleGraph.test.ts @@ -8,6 +8,7 @@ import { expect, it, vi } from "vitest"; import { createTestTempDirectory } from "../../../tests/fixtures/temporaryDirectory.js"; import { CPU_ARM64, + CPU_X86_64, universalMacho, } from "../../../tests/fixtures/universalMacho.js"; import { probeBunStandaloneGraph } from "./BunModuleGraphLayout.js"; @@ -330,6 +331,142 @@ it.each(["thin", "universal"] as const)( }, ); +it.each(["cpu-type", "cpu-subtype"] as const)( + "requires a matching FAT %s for a Bun section claim", + async (field) => { + const thin = (name: string) => + machoBunSection( + bunPrefixedPayload(bunModuleGraphPayload({ modules: [{ name }] })), + ); + const candidate = { + bytes: thin("candidate.js"), + cpuType: CPU_ARM64, + cpuSubtype: 0, + }; + const conflicting = { + ...candidate, + ...(field === "cpu-type" + ? { tableCpuType: CPU_X86_64 } + : { tableCpuSubtype: 1 }), + }; + const matching = universalMacho([candidate]); + expect((await probe(matching.bytes)).result).toMatchObject({ + status: "present", + claim: { carrier: "mach-o-section" }, + }); + const wrong = universalMacho([conflicting]); + const unpadded = wrong.bytes.subarray( + 0, + wrong.slices[0]!.offset + wrong.slices[0]!.size, + ); + expect((await probe(unpadded)).result).toMatchObject({ + status: "present", + failure: { + reason: "format", + message: expect.stringContaining("CPU type/subtype disagrees"), + }, + }); + const unnamed = Buffer.from(conflicting.bytes); + unnamed.write("__note", 32 + 72); + expect( + (await probe(universalMacho([{ ...conflicting, bytes: unnamed }]).bytes)) + .result, + ).toEqual({ status: "absent" }); + const validSibling = { ...candidate, bytes: thin("independent.js") }; + const mixed = universalMacho([conflicting, validSibling]); + const result = await locate(mixed.bytes); + if (result.status !== "present" || !result.graph) + throw new Error("Expected the independent Bun graph"); + expect( + (await decodeBunModuleGraph(result.graph)).modules[0]?.nameText.text, + ).toBe("independent.js"); + const oversizedCommands = machoBunSections([ + bunPrefixedPayload( + bunModuleGraphPayload({ modules: [{ name: "first.js" }] }), + ), + bunPrefixedPayload( + bunModuleGraphPayload({ modules: [{ name: "second.js" }] }), + ), + ]); + const limited = universalMacho([ + { ...conflicting, bytes: oversizedCommands }, + validSibling, + ]); + const { result: underBudget } = await probe(limited.bytes, { + ...DEFAULT_BUN_READER_LIMITS, + recognition_load_command_bytes: validSibling.bytes.readUInt32LE(20), + }); + expect(underBudget).toMatchObject({ + status: "present", + claim: { + carrier: "mach-o-section", + payloadOffset: limited.slices[1]!.offset + 32 + 72 + 80 + 8, + }, + }); + }, +); + +it("keeps refused FAT bytes outside the appended graph fallback", async () => { + const graph = (name: string) => + bunModuleGraphPayload({ modules: [{ name }] }); + const thin = machoBunSection(bunPrefixedPayload(graph("refused.js"))); + const fixture = universalMacho([ + { + bytes: thin, + cpuType: CPU_ARM64, + cpuSubtype: 0, + tableCpuType: CPU_X86_64, + }, + ]); + const slice = fixture.slices[0]!; + const unpadded = fixture.bytes.subarray(0, slice.offset + slice.size); + const limits = { + ...DEFAULT_BUN_READER_LIMITS, + recognition_load_command_bytes: thin.readUInt32LE(20) - 1, + }; + expect((await probe(unpadded, limits)).result).toEqual({ status: "absent" }); + + const outside = graph("outside.js"); + const outer = Buffer.concat([unpadded, outside]); + for (const selected of [limits, DEFAULT_BUN_READER_LIMITS]) { + expect((await probe(outer, selected)).result).toMatchObject({ + status: "present", + claim: { + carrier: "appended-trailer", + payloadOffset: unpadded.length, + payloadLength: outside.length, + }, + }); + } + + const legacySize = Buffer.alloc(8); + legacySize.writeBigUInt64LE(BigInt(outer.length + legacySize.length)); + expect( + (await probe(Buffer.concat([outer, legacySize]), limits)).result, + ).toMatchObject({ + status: "present", + claim: { + carrier: "appended-trailer", + payloadOffset: unpadded.length, + payloadLength: outside.length, + }, + }); + + // The footer is outside, but its reported data begins one byte in the + // refused slice. Both the footer and the full graph span must be eligible. + const overlapping = Buffer.from(outside); + const offsets = overlapping.length - BUN_FIXTURE_GRAPH_SUFFIX_BYTES; + overlapping.writeBigUInt64LE( + overlapping.readBigUInt64LE(offsets) + 1n, + offsets, + ); + expect( + (await probe(Buffer.concat([unpadded, overlapping]), limits)).result, + ).toEqual({ + status: "absent", + }); +}); + it("probes a section graph without reading its payload data", async () => { const contents = Buffer.alloc(1024 * 1024, 0x61); const bytes = machoBunSection( diff --git a/src/artifacts/bun/BunModuleGraphLayout.ts b/src/artifacts/bun/BunModuleGraphLayout.ts index c738970ec1..bc9b2cd225 100644 --- a/src/artifacts/bun/BunModuleGraphLayout.ts +++ b/src/artifacts/bun/BunModuleGraphLayout.ts @@ -18,6 +18,8 @@ import { observeElfStringTableEntry } from "../../domain/elfStringTable.js"; import { readFatContainerHeader, readMachoHeaderPrefixFacts, + validateFatSliceIdentity, + type FatSliceDeclaration, } from "../../domain/apple/machoContainer.js"; import { readMachoLoadCommandTableHeader, @@ -146,6 +148,15 @@ interface SectionWindow { type SectionClaim = SectionWindow | { readonly failure: ArtifactReaderFailure }; +/** A rejected slice has no authority over any embedded graph at its offsets. */ +interface RejectedFatSlice { + readonly rejectedSlice: FatSliceDeclaration; + /** Only set when the bounded command metadata actually names a Bun slot. */ + readonly namedFailure?: ArtifactReaderFailure; +} + +type SectionObservation = SectionClaim | RejectedFatSlice; + /** * Locate at most one graph claim with bounded reads of headers, length * prefixes, and suffixes. Payload data is not read. Multiple real claims are @@ -159,7 +170,7 @@ export const probeBunStandaloneGraph = async ( ): Promise => { abortIfNeeded(signal); const source = { handle, fileSize, signal, limits }; - let claims: readonly SectionClaim[]; + let claims: readonly SectionObservation[]; try { claims = [ ...(await machOClaims(source, 0, fileSize)), @@ -172,8 +183,15 @@ export const probeBunStandaloneGraph = async ( return { status: "limited", failure: cause }; } const real: BunStandaloneProbe[] = []; + const rejectedSlices: FatSliceDeclaration[] = []; + let fatIdentityFailure: ArtifactReaderFailure | undefined; for (const claim of claims) { abortIfNeeded(signal); + if ("rejectedSlice" in claim) { + rejectedSlices.push(claim.rejectedSlice); + fatIdentityFailure ??= claim.namedFailure; + continue; + } const evaluated = "failure" in claim ? presentFailure(claim.failure) @@ -191,7 +209,10 @@ export const probeBunStandaloneGraph = async ( } const only = real[0]; if (only !== undefined) return only; - return evaluateAppendedTrailer(source); + const appended = await evaluateAppendedTrailer(source, rejectedSlices); + return appended.status === "absent" && fatIdentityFailure !== undefined + ? presentFailure(fatIdentityFailure) + : appended; }; /** Read a probed payload once and validate its suffix against the claim. */ @@ -423,26 +444,25 @@ const evaluateSection = async ( */ const evaluateAppendedTrailer = async ( source: BunProbeSource, + rejectedSlices: readonly FatSliceDeclaration[], ): Promise => { const { handle, fileSize, signal, limits } = source; + const outsideRejectedSlices = (start: number, end: number): boolean => + !rejectedSlices.some( + (slice) => start < slice.offset + slice.size && slice.offset < end, + ); + const readTrailer = async (end: number): Promise => + outsideRejectedSlices(end - BUN_GRAPH_SUFFIX_BYTES, fileSize) + ? readExact(handle, end - BUN_TRAILER_BYTES, BUN_TRAILER_BYTES, signal) + : null; if (fileSize < BUN_GRAPH_SUFFIX_BYTES) return { status: "absent" }; let graphEnd = fileSize; - let trailer = await readExact( - handle, - graphEnd - BUN_TRAILER_BYTES, - BUN_TRAILER_BYTES, - signal, - ); - if (!trailer.equals(BUN_TRAILER)) { + let trailer = await readTrailer(graphEnd); + if (!trailer?.equals(BUN_TRAILER)) { if (fileSize < BUN_GRAPH_SUFFIX_BYTES + 8) return { status: "absent" }; graphEnd -= 8; - trailer = await readExact( - handle, - graphEnd - BUN_TRAILER_BYTES, - BUN_TRAILER_BYTES, - signal, - ); - if (!trailer.equals(BUN_TRAILER)) return { status: "absent" }; + trailer = await readTrailer(graphEnd); + if (!trailer?.equals(BUN_TRAILER)) return { status: "absent" }; const length = await readExact(handle, graphEnd, 8, signal); if (length.readBigUInt64LE() !== BigInt(fileSize)) return presentFailure( @@ -455,21 +475,26 @@ const evaluateAppendedTrailer = async ( BUN_OFFSETS_BYTES, signal, ); - const byteCount = offsets.readBigUInt64LE(0); - if (byteCount + BigInt(BUN_GRAPH_SUFFIX_BYTES) > BigInt(limits.payload_bytes)) - return presentFailure( - bunPayloadBytesLimit(byteCount + BigInt(BUN_GRAPH_SUFFIX_BYTES), limits), - ); - const payloadLength = byteCount + BigInt(BUN_GRAPH_SUFFIX_BYTES); - if (payloadLength > BigInt(graphEnd)) + const payloadLength = + offsets.readBigUInt64LE(0) + BigInt(BUN_GRAPH_SUFFIX_BYTES); + const payloadStart = BigInt(graphEnd) - payloadLength; + if ( + !outsideRejectedSlices( + payloadStart < 0n ? 0 : Number(payloadStart), + graphEnd, + ) + ) + return { status: "absent" }; + if (payloadLength > BigInt(limits.payload_bytes)) + return presentFailure(bunPayloadBytesLimit(payloadLength, limits)); + if (payloadStart < 0n) return presentFailure(bunFormatFailure("trailer is truncated")); - const length = Number(payloadLength); return { status: "present", claim: { carrier: "appended-trailer", - payloadOffset: graphEnd - length, - payloadLength: length, + payloadOffset: Number(payloadStart), + payloadLength: Number(payloadLength), }, }; }; @@ -504,7 +529,8 @@ const machOClaims = async ( source: BunProbeSource, imageOffset: number, imageLimit: number, -): Promise => { + fat?: FatSliceDeclaration, +): Promise => { const { handle, fileSize, signal, limits } = source; if (imageOffset < 0 || imageOffset >= fileSize) return []; const imageSize = Math.min(fileSize - imageOffset, imageLimit); @@ -514,6 +540,10 @@ const machOClaims = async ( const facts = readMachoHeaderPrefixFacts(header); if (facts.identity === null) return imageOffset === 0 ? fatClaims(source, header) : []; + const identityIssue = + fat === undefined ? null : validateFatSliceIdentity(fat, facts.identity); + const rejected: readonly RejectedFatSlice[] = + fat !== undefined && identityIssue !== null ? [{ rejectedSlice: fat }] : []; const full = await tryRead( handle, imageOffset, @@ -521,22 +551,24 @@ const machOClaims = async ( imageEnd, signal, ); - if (full === null) return []; + if (full === null) return rejected; const parsed = readMachoLoadCommandTableHeader(full, imageSize); - if (!parsed.ok || parsed.value === null) return []; + if (!parsed.ok || parsed.value === null) return rejected; const table = parsed.value; const { littleEndian, headerSize: headerBytes, commandBytes: sizeofcmds, } = table; - if (sizeofcmds > limits.recognition_load_command_bytes) + if (sizeofcmds > limits.recognition_load_command_bytes) { + if (identityIssue !== null) return rejected; throw artifactReaderLimitFailure( "artifact_limits.bun.recognition_load_command_bytes", limits.recognition_load_command_bytes, "bytes", sizeofcmds, ); + } const commands = await tryRead( handle, imageOffset + headerBytes, @@ -544,7 +576,7 @@ const machOClaims = async ( imageEnd, signal, ); - if (commands === null || commands.length !== sizeofcmds) return []; + if (commands === null || commands.length !== sizeofcmds) return rejected; const claims: SectionClaim[] = []; const cursor = new MachoLoadCommandCursor(table); let framingFailure: string | undefined; @@ -563,9 +595,20 @@ const machOClaims = async ( cmd === LC.SEGMENT_64, imageOffset, imageSize, - )) + )) { + // A mismatched slice can identify a named declaration from bounded + // metadata, but cannot contribute graph bytes or veto another slice. + if (fat !== undefined && identityIssue !== null) + return [ + { + rejectedSlice: fat, + namedFailure: bunFormatFailure(identityIssue), + }, + ]; claims.push(claim); + } } + if (rejected.length !== 0) return rejected; const complete = cursor.finish(); if (!complete.ok) framingFailure ??= complete.error; return framingFailure === undefined @@ -636,7 +679,7 @@ const segmentClaims = ( const fatClaims = async ( source: BunProbeSource, prefix: Buffer, -): Promise => { +): Promise => { const { handle, fileSize, signal } = source; let parsed = readFatContainerHeader(prefix, fileSize); if (parsed.state === "needs-data") { @@ -651,11 +694,16 @@ const fatClaims = async ( parsed = readFatContainerHeader(table, fileSize); } if (parsed.state !== "parsed") return []; - const claims: SectionClaim[] = []; + const claims: SectionObservation[] = []; for (const slice of parsed.slices) { abortIfNeeded(signal); if (parsed.rangeIssues[slice.index] !== null) continue; - for (const claim of await machOClaims(source, slice.offset, slice.size)) + for (const claim of await machOClaims( + source, + slice.offset, + slice.size, + slice, + )) claims.push(claim); } return claims; diff --git a/src/artifacts/nodeSea/NodeSeaLocation.ts b/src/artifacts/nodeSea/NodeSeaLocation.ts index ae7d8ea4fc..8a30e1898e 100644 --- a/src/artifacts/nodeSea/NodeSeaLocation.ts +++ b/src/artifacts/nodeSea/NodeSeaLocation.ts @@ -47,6 +47,8 @@ import { readFatContainerHeader, readFatHeaderPrefix, readMachoHeaderPrefixFacts, + validateFatSliceIdentity, + type FatSliceDeclaration, } from "../../domain/apple/machoContainer.js"; import { readElfFixedHeader } from "../../domain/elfFixedHeader.js"; import { @@ -92,6 +94,13 @@ interface BlobRange { readonly length: number; } +interface MachoSliceScan { + readonly ranges: readonly BlobRange[]; + readonly identityIssue?: string; +} + +const EMPTY_MACHO_SLICE: MachoSliceScan = { ranges: [] }; + interface Carrier { readonly handle: FileHandle; readonly fileSize: number; @@ -144,7 +153,7 @@ export const locateNodeSea = async ( if (thin !== null || fat.state === "incomplete" || fat.state === "parsed") { const ranges = thin !== null - ? await locateThinMachO(carrier, 0, fileSize) + ? (await locateThinMachO(carrier, 0, fileSize)).ranges : await locateFatMachO(carrier, prefix); return collapseRanges(carrier, "mach-o", ranges); } @@ -257,7 +266,7 @@ const collapseRanges = async ( const locateFatMachO = async ( carrier: Carrier, prefix: Buffer, -): Promise => { +): Promise => { let bytes = prefix; let header = readFatContainerHeader(bytes, carrier.fileSize); if (header.state === "needs-data") { @@ -273,19 +282,24 @@ const locateFatMachO = async ( } if (header.state !== "parsed") { if (readMachoHeaderPrefixFacts(bytes).format !== null) - return locateThinMachO(carrier, 0, carrier.fileSize); + return (await locateThinMachO(carrier, 0, carrier.fileSize)).ranges; return []; } const found: BlobRange[] = []; + let identityIssue: string | undefined; for (const [index, slice] of header.slices.entries()) { if (slice === undefined || header.rangeIssues[index] != null) continue; - for (const range of await locateThinMachO( + const scan = await locateThinMachO( carrier, slice.offset, slice.size, - )) - found.push(range); + slice, + ); + for (const range of scan.ranges) found.push(range); + identityIssue ??= scan.identityIssue; } + if (found.length === 0 && identityIssue !== undefined) + throw formatFailure(identityIssue); return found; }; @@ -293,27 +307,33 @@ const locateThinMachO = async ( carrier: Carrier, base: number, sliceSize: number, -): Promise => { + fat?: FatSliceDeclaration, +): Promise => { if ( !Number.isSafeInteger(base) || !Number.isSafeInteger(sliceSize) || base < 0 || - sliceSize < 32 || + sliceSize < 4 || base > carrier.fileSize || sliceSize > carrier.fileSize - base ) - return []; - const header = await readExact(carrier, base, 32); - if (header === undefined) return []; + return EMPTY_MACHO_SLICE; + const header = await readExact(carrier, base, Math.min(32, sliceSize)); + if (header === undefined) return EMPTY_MACHO_SLICE; const framing = readMachoLoadCommandTableHeader(header, sliceSize); - if (!framing.ok || framing.value === null) return []; + if (!framing.ok || framing.value === null) return EMPTY_MACHO_SLICE; + const identityIssue = + fat === undefined + ? null + : validateFatSliceIdentity(fat, framing.value.identity); const { headerSize, littleEndian: little, commandBytes: sizeofcmds, } = framing.value; const limits = carrier.limits ?? DEFAULT_NODE_SEA_READER_LIMITS; - if (sizeofcmds > limits.recognition_load_command_bytes) + if (sizeofcmds > limits.recognition_load_command_bytes) { + if (identityIssue !== null) return EMPTY_MACHO_SLICE; throw artifactReaderLimitFailure( "artifact_limits.node_sea.recognition_load_command_bytes", limits.recognition_load_command_bytes, @@ -321,8 +341,9 @@ const locateThinMachO = async ( sizeofcmds, "memory", ); + } const commands = await readExact(carrier, base + headerSize, sizeofcmds); - if (commands === undefined) return []; + if (commands === undefined) return EMPTY_MACHO_SLICE; const found: BlobRange[] = []; const cursor = new MachoLoadCommandCursor(framing.value); while (cursor.nextOffset !== null) { @@ -350,8 +371,10 @@ const locateThinMachO = async ( const segmentHeader = segment.headerSize; const nsects = segment.sectionCount; const table = offset + segmentHeader; - if (nsects > Math.floor((size - segmentHeader) / sectionSize)) + if (nsects > Math.floor((size - segmentHeader) / sectionSize)) { + if (identityIssue !== null) continue; throw formatFailure(NODE_SEA_MACHO_SEGMENT_TRUNCATED); + } const admission = admitMachoSegmentCommand( segment, size, @@ -369,6 +392,9 @@ const locateThinMachO = async ( throw formatFailure(NODE_SEA_MACHO_SEGMENT_TRUNCATED); const record = parsedSection.value; if (cString(record.nameBytes, 0, 16) !== SEA_SECTION) continue; + // Only a named declaration is attributed to SEA. A mismatch + // cannot supply bytes or block an independently admitted sibling. + if (identityIssue !== null) return { ranges: [], identityIssue }; if (!admission.ok) throw formatFailure(`Node SEA ${admission.error.message}`); const { issue } = machoSectionBacking(record, segment); @@ -387,7 +413,7 @@ const locateThinMachO = async ( } if (found.length > 0 && !cursor.finish().ok) throw formatFailure(NODE_SEA_MACHO_COMMANDS_TRUNCATED); - return found; + return { ranges: found }; }; const locateElfNotes = async ( diff --git a/tests/fixtures/universalMacho.ts b/tests/fixtures/universalMacho.ts index ef4289e28a..0a5df20b76 100644 --- a/tests/fixtures/universalMacho.ts +++ b/tests/fixtures/universalMacho.ts @@ -3,8 +3,9 @@ interface UniversalSlice { readonly bytes: Buffer; readonly cpuType: number; readonly cpuSubtype: number; - /** Declare a different CPU in the FAT table than in the slice header. */ + /** Override the FAT CPU identity independently of the thin header. */ readonly tableCpuType?: number; + readonly tableCpuSubtype?: number; } /** The FAT32 container and where each slice landed. */ @@ -38,7 +39,7 @@ export const universalMacho = ( const { offset: sliceOffset, size } = placed[index]!; const entry = 8 + index * 20; bytes.writeUInt32BE(slice.tableCpuType ?? slice.cpuType, entry); - bytes.writeUInt32BE(slice.cpuSubtype, entry + 4); + bytes.writeUInt32BE(slice.tableCpuSubtype ?? slice.cpuSubtype, entry + 4); bytes.writeUInt32BE(sliceOffset, entry + 8); bytes.writeUInt32BE(size, entry + 12); bytes.writeUInt32BE(ALIGNMENT_EXPONENT, entry + 16);