diff --git a/src/erlang/BeamParser.test.ts b/src/erlang/BeamParser.test.ts index 81d7dc0a6f..3f713cdd73 100644 --- a/src/erlang/BeamParser.test.ts +++ b/src/erlang/BeamParser.test.ts @@ -13,7 +13,7 @@ import { erlangBeamLegacyAtomsFixture, erlangBeamOtp29Fixture, } from "./Beam.fixture.js"; -import { parseErlangBeam } from "./BeamParser.js"; +import { parseErlangBeam, parseErlangBeamFromHandle } from "./BeamParser.js"; import { BeamProvider } from "./BeamProvider.js"; import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; @@ -32,6 +32,56 @@ const parse = (bytes: Buffer, input = defaults) => input, ); +const streamBeam = (bytes: Buffer, reads: number[] = []) => { + const sha256 = createHash("sha256").update(bytes).digest("hex"); + return parseErlangBeamFromHandle( + { + sha256, + size: bytes.length, + prefix: bytes.subarray(0, 12), + readRange: async (offset, length) => { + reads.push(length); + return bytes.subarray(offset, offset + length); + }, + }, + { path: defaults.path, sha256, bytes: bytes.length }, + defaults, + ); +}; + +it("streams bulk BEAM chunks and selects the last Code header", async () => { + const code = Buffer.alloc(1024 * 1024 + 123, 0x62); + [16, 0, 169, 4, 2].forEach((field, index) => + code.writeUInt32BE(field, 4 * index), + ); + const decoy = Buffer.from(code.subarray(0, 20)); + decoy.writeUInt32BE(99, 16); + const bytes = erlangBeamChunksFixture([ + ["Code", decoy], + ["Code", code], + ]); + const reads: number[] = []; + const streamed = await streamBeam(bytes, reads); + expect(streamed).toEqual(parse(bytes)); + expect(streamed.code?.functions).toBe(2); + expect(streamed.chunks.map(({ payload }) => payload.sha256)).toEqual( + [decoy, code].map((payload) => + createHash("sha256").update(payload).digest("hex"), + ), + ); + expect(reads).toEqual([8, 20, 8, 1024 * 1024, 123]); +}); + +it("preserves the buffered failure for an invalid chunk extent", async () => { + const bytes = erlangBeamChunksFixture([["Code", Buffer.alloc(20)]]); + bytes.writeUInt32BE(100, 16); + expect(() => parse(bytes)).toThrow("BEAM chunk payload exceeds the form."); + await expect(streamBeam(bytes)).rejects.toMatchObject({ + reason: "format", + message: "BEAM chunk payload exceeds the form.", + }); +}); + it("selects the last table and Code payload for every repeated chunk name", () => { const original = erlangBeamFixture("selected"); const decoy = erlangBeamFixture("decoy"); diff --git a/src/erlang/BeamParser.ts b/src/erlang/BeamParser.ts index 1441ecdca7..2b37cc90b5 100644 --- a/src/erlang/BeamParser.ts +++ b/src/erlang/BeamParser.ts @@ -1,5 +1,9 @@ import { isUtf8 } from "node:buffer"; -import { ArtifactReaderFailure } from "../resources/index.js"; +import { createHash } from "node:crypto"; +import { + ArtifactReaderFailure, + type StableArtifactHandle, +} from "../resources/index.js"; import { BinaryReader } from "../domain/binaryContainer.js"; import { decodeLimit } from "../domain/parseFailure.js"; import { @@ -18,13 +22,21 @@ const LIMITATIONS = [ "Atom names are structural table entries; they do not authenticate the originating compiler or module checksum.", ] as const; -const requireRange = (bytes: Buffer, offset: number, length: number): void => { +const STREAM_CHUNK_BYTES = 1024 * 1024; +const RETAINED_TABLE_CHUNKS = new Set(["AtU8", "Atom", "ExpT", "ImpT", "FunT"]); +const CODE_HEADER_BYTES = 20; + +const requireRange = ( + fileSize: number, + offset: number, + length: number, +): void => { if ( !Number.isSafeInteger(offset) || !Number.isSafeInteger(length) || offset < 0 || length < 0 || - offset > bytes.length - length + offset > fileSize - length ) fail( `BEAM range ${String(offset)} + ${String(length)} leaves the artifact.`, @@ -174,13 +186,15 @@ const mapRows = ( }; const parseCode = ( - payload: Buffer, + header: Buffer, + payloadLength: number, chunkOffset: number, ): NonNullable => { - if (payload.length < 20) fail("BEAM Code chunk is truncated."); - const reader = new BinaryReader(payload, false, "beam"); + if (payloadLength < CODE_HEADER_BYTES || header.length < CODE_HEADER_BYTES) + fail("BEAM Code chunk is truncated."); + const reader = new BinaryReader(header, false, "beam"); const infoSize = reader.u32(0); - if (infoSize < 16 || infoSize > payload.length - 4) + if (infoSize < 16 || infoSize > payloadLength - 4) fail("BEAM Code header size is invalid."); const instructionsOffset = 4 + infoSize; return { @@ -191,66 +205,26 @@ const parseCode = ( extra_header_bytes: infoSize - 16, instructions: { offset: chunkOffset + 8 + instructionsOffset, - bytes: payload.length - instructionsOffset, + bytes: payloadLength - instructionsOffset, }, }; }; -/** Decode one FOR1/BEAM IFF container into bounded chunk and table facts. */ -export const parseErlangBeam = ( - bytes: Buffer, +interface RetainedBeamChunk { + readonly payload: Buffer; + readonly payloadLength: number; + readonly offset: number; +} + +const buildErlangBeamReport = ( + fileSize: number, + formSize: number, + formEnd: number, + chunks: ErlangBeam["chunks"], + payloads: ReadonlyMap, artifact: ErlangBeam["artifact"], input: InspectErlangBeamInput, ): ErlangBeam => { - requireRange(bytes, 0, 12); - if (bytes.subarray(0, 4).toString("latin1") !== "FOR1") - fail("Expected a FOR1 IFF container."); - const carrier = new BinaryReader(bytes, false, "beam"); - const formSize = carrier.u32(4); - if (formSize < 4) fail("BEAM form size is shorter than the BEAM tag."); - requireRange(bytes, 8, formSize); - if (bytes.subarray(8, 12).toString("latin1") !== "BEAM") - fail("Expected a BEAM form type."); - const formEnd = 8 + formSize; - const form = new BinaryReader( - carrier.range(0, formEnd, "BEAM form"), - false, - "beam", - ); - const chunks: ErlangBeam["chunks"] = []; - const payloads = new Map(); - let at = 12; - while (at < formEnd) { - if (formEnd - at < 8) fail("BEAM chunk header is truncated."); - const size = form.u32(at + 4); - const payloadOffset = at + 8; - if (size > formEnd - payloadOffset) - fail("BEAM chunk payload exceeds the form."); - const padded = payloadOffset + size + ((4 - (size % 4)) % 4); - if (padded > formEnd) fail("BEAM chunk padding exceeds the form."); - if (chunks.length >= input.max_chunks) - throw decodeLimit( - "beam", - `BEAM form exceeds the ${String(input.max_chunks)}-chunk budget.`, - { name: "max_chunks", maximum: input.max_chunks }, - ); - const name = form.range(at, 4, "BEAM chunk name").toString("latin1"); - const payload = form.range(payloadOffset, size, "BEAM chunk payload"); - chunks.push({ - index: chunks.length, - name, - location: { offset: at, bytes: padded - at }, - payload: { - location: { offset: payloadOffset, bytes: size }, - bytes: size, - sha256: sha256Hex(payload), - }, - }); - // OTP's loader replaces the selected payload on each matching chunk. - // Keep every occurrence above; decode the last occurrence of each name. - payloads.set(name, { payload, offset: at }); - at = padded; - } const utf8AtomChunk = payloads.get("AtU8"); const legacyAtomChunk = payloads.get("Atom"); // Historical OTP selects Atom when AtU8 has no payload. Without a legacy @@ -344,10 +318,10 @@ export const parseErlangBeam = ( const code = codeChunk === undefined ? null - : parseCode(codeChunk.payload, codeChunk.offset); + : parseCode(codeChunk.payload, codeChunk.payloadLength, codeChunk.offset); // A conformant FOR1 form sizes itself to the file; any surplus bytes trail an // unexamined region. Disclose them instead of reporting complete coverage. - const trailingBytes = bytes.length - formEnd; + const trailingBytes = fileSize - formEnd; const unexamined: string[] = []; if (trailingBytes > 0) unexamined.push( @@ -385,3 +359,188 @@ export const parseErlangBeam = ( limitations: [...LIMITATIONS, ...unexamined], }; }; + +/** Decode one FOR1/BEAM IFF container into bounded chunk and table facts. */ +export const parseErlangBeam = ( + bytes: Buffer, + artifact: ErlangBeam["artifact"], + input: InspectErlangBeamInput, +): ErlangBeam => { + requireRange(bytes.length, 0, 12); + if (bytes.subarray(0, 4).toString("latin1") !== "FOR1") + fail("Expected a FOR1 IFF container."); + const carrier = new BinaryReader(bytes, false, "beam"); + const formSize = carrier.u32(4); + if (formSize < 4) fail("BEAM form size is shorter than the BEAM tag."); + requireRange(bytes.length, 8, formSize); + if (bytes.subarray(8, 12).toString("latin1") !== "BEAM") + fail("Expected a BEAM form type."); + const formEnd = 8 + formSize; + const form = new BinaryReader( + carrier.range(0, formEnd, "BEAM form"), + false, + "beam", + ); + const chunks: ErlangBeam["chunks"] = []; + const payloads = new Map(); + let at = 12; + while (at < formEnd) { + if (formEnd - at < 8) fail("BEAM chunk header is truncated."); + const size = form.u32(at + 4); + const payloadOffset = at + 8; + if (size > formEnd - payloadOffset) + fail("BEAM chunk payload exceeds the form."); + const padded = payloadOffset + size + ((4 - (size % 4)) % 4); + if (padded > formEnd) fail("BEAM chunk padding exceeds the form."); + if (chunks.length >= input.max_chunks) + throw decodeLimit( + "beam", + `BEAM form exceeds the ${String(input.max_chunks)}-chunk budget.`, + { name: "max_chunks", maximum: input.max_chunks }, + ); + const name = form.range(at, 4, "BEAM chunk name").toString("latin1"); + const payload = form.range(payloadOffset, size, "BEAM chunk payload"); + chunks.push({ + index: chunks.length, + name, + location: { offset: at, bytes: padded - at }, + payload: { + location: { offset: payloadOffset, bytes: size }, + bytes: size, + sha256: sha256Hex(payload), + }, + }); + // OTP's loader replaces the selected payload on each matching chunk. + // Keep every occurrence above; decode the last occurrence of each name. + payloads.set(name, { payload, payloadLength: size, offset: at }); + at = padded; + } + return buildErlangBeamReport( + bytes.length, + formSize, + formEnd, + chunks, + payloads, + artifact, + input, + ); +}; + +const streamChunkDigest = async ( + handle: StableArtifactHandle, + payloadOffset: number, + size: number, + retainPrefixBytes: number, +): Promise<{ readonly sha256: string; readonly prefix: Buffer }> => { + const hash = createHash("sha256"); + const prefix = Buffer.alloc(Math.min(size, retainPrefixBytes)); + for (let offset = 0; offset < size; offset += STREAM_CHUNK_BYTES) { + const length = Math.min(STREAM_CHUNK_BYTES, size - offset); + const part = await handle.readRange(payloadOffset + offset, length); + if (part.length !== length) + throw new ArtifactReaderFailure( + "integrity", + "BEAM payload ended before its admitted extent.", + { integrityCheck: "read-coverage" }, + ); + hash.update(part); + if (offset < prefix.length) + part.copy( + prefix, + offset, + 0, + Math.min(part.length, prefix.length - offset), + ); + } + return { sha256: hash.digest("hex"), prefix }; +}; + +/** + * Decode one FOR1/BEAM IFF container from a verified random-access handle, + * retaining only decoded table chunks and the 20-byte Code header while + * streaming SHA-256 digests over bulk chunks such as Code, Dbgi, and LitT. + */ +export const parseErlangBeamFromHandle = async ( + handle: StableArtifactHandle, + artifact: ErlangBeam["artifact"], + input: InspectErlangBeamInput, +): Promise => { + requireRange(handle.size, 0, 12); + const header = + handle.prefix.length >= 12 + ? handle.prefix.subarray(0, 12) + : await handle.readRange(0, 12); + if (header.subarray(0, 4).toString("latin1") !== "FOR1") + fail("Expected a FOR1 IFF container."); + const formSize = new BinaryReader(header, false, "beam").u32(4); + if (formSize < 4) fail("BEAM form size is shorter than the BEAM tag."); + requireRange(handle.size, 8, formSize); + if (header.subarray(8, 12).toString("latin1") !== "BEAM") + fail("Expected a BEAM form type."); + const formEnd = 8 + formSize; + const chunks: ErlangBeam["chunks"] = []; + const payloads = new Map(); + let at = 12; + while (at < formEnd) { + if (formEnd - at < 8) fail("BEAM chunk header is truncated."); + const chunkHeader = await handle.readRange(at, 8); + const size = new BinaryReader(chunkHeader, false, "beam").u32(4); + const payloadOffset = at + 8; + if (size > formEnd - payloadOffset) + fail("BEAM chunk payload exceeds the form."); + const padded = payloadOffset + size + ((4 - (size % 4)) % 4); + if (padded > formEnd) fail("BEAM chunk padding exceeds the form."); + if (chunks.length >= input.max_chunks) + throw decodeLimit( + "beam", + `BEAM form exceeds the ${String(input.max_chunks)}-chunk budget.`, + { name: "max_chunks", maximum: input.max_chunks }, + ); + const name = chunkHeader.subarray(0, 4).toString("latin1"); + let sha256: string; + if (RETAINED_TABLE_CHUNKS.has(name)) { + const payload = + size === 0 + ? Buffer.alloc(0) + : await handle.readRange(payloadOffset, size); + sha256 = sha256Hex(payload); + payloads.set(name, { payload, payloadLength: size, offset: at }); + } else if (name === "Code") { + const streamed = await streamChunkDigest( + handle, + payloadOffset, + size, + CODE_HEADER_BYTES, + ); + sha256 = streamed.sha256; + payloads.set(name, { + payload: streamed.prefix, + payloadLength: size, + offset: at, + }); + } else { + const streamed = await streamChunkDigest(handle, payloadOffset, size, 0); + sha256 = streamed.sha256; + } + chunks.push({ + index: chunks.length, + name, + location: { offset: at, bytes: padded - at }, + payload: { + location: { offset: payloadOffset, bytes: size }, + bytes: size, + sha256, + }, + }); + at = padded; + } + return buildErlangBeamReport( + handle.size, + formSize, + formEnd, + chunks, + payloads, + artifact, + input, + ); +}; diff --git a/src/erlang/BeamProvider.ts b/src/erlang/BeamProvider.ts index 3f674421bd..7d2f53e9be 100644 --- a/src/erlang/BeamProvider.ts +++ b/src/erlang/BeamProvider.ts @@ -5,8 +5,7 @@ import { stableArtifactInputFailure, projectArtifactCloseFailure, ArtifactReaderFailure, - type StableArtifactSnapshot, - readStableArtifact, + withStableArtifactHandle, artifactFilePrimaryFacts, type ArtifactFilePrimaryFacts, artifactSelectedPathErrno, @@ -34,7 +33,7 @@ import { isParseLimit, parseLimitConstraint, } from "../domain/parseFailureAnalysisError.js"; -import { parseErlangBeam } from "./BeamParser.js"; +import { parseErlangBeamFromHandle } from "./BeamParser.js"; const OPERATION = "inspect_erlang_beam"; @@ -56,30 +55,38 @@ export class BeamProvider implements BeamPort { } async inspect(input: InspectErlangBeamInput, options?: ExecutionOptions) { - let snapshot: StableArtifactSnapshot | undefined; + let observed: + | { readonly sha256: string; readonly bytes: number } + | undefined; try { - return await this.#resources.run(async () => { - snapshot = await readStableArtifact( + return await this.#resources.run(async () => + withStableArtifactHandle( input.path, input.max_file_bytes, - options?.signal, - undefined, - this.#resources, - ); - return ok( - parseErlangBeam( - snapshot.bytes, - { - path: input.path, - sha256: snapshot.sha256, - bytes: snapshot.bytes.length, + { + retainBytes: (size) => Math.min(size, 12), + signal: options?.signal, + resourceScope: this.#resources, + onIdentity: (identity) => { + observed = identity; }, - input, - ), - ); - }); + }, + async (handle) => + ok( + await parseErlangBeamFromHandle( + handle, + { + path: input.path, + sha256: handle.sha256, + bytes: handle.size, + }, + input, + ), + ), + ), + ); } catch (cause) { - return err(beamFailure(cause, input, snapshot)); + return err(beamFailure(cause, input, observed)); } } } @@ -191,7 +198,7 @@ const beamFailurePrimary = ( const beamFailure = ( cause: unknown, input: InspectErlangBeamInput, - snapshot?: StableArtifactSnapshot, + observed?: { readonly sha256: string; readonly bytes: number }, ) => { const primary = beamFailurePrimary(artifactFilePrimaryFacts(cause), input); return projectStableArtifactFailure( @@ -200,6 +207,6 @@ const beamFailure = ( input.path, ERLANG_BEAM_PROVIDER_IDENTITY.id, OPERATION, - snapshot, + observed, ); };