From c9c8e1e08884fc14792ad73b2ce098fd6a73238f Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 16:14:17 -0500 Subject: [PATCH] perf(artifacts): eliminate format-dispatch read amplification and prefix/suffix copies (#13600) * perf(artifacts): eliminate format-dispatch read amplification and prefix/suffix copies * fix(uefi): fill the final firmware probe buffer directly --- src/application/BinaryTargetResolver.ts | 49 ++++++++++++++---- src/artifacts/ArtifactClassificationProbe.ts | 46 +++++++++++------ src/artifacts/inventory/classify.ts | 24 ++++++++- src/domain/binaryTarget.ts | 20 ++++---- src/filesystem/readFileHandleRange.ts | 7 ++- src/uefi/FirmwareVolume.test.ts | 46 +++++++++++++++++ src/uefi/UefiFormatProbe.ts | 54 +++++++++++++++++--- 7 files changed, 198 insertions(+), 48 deletions(-) diff --git a/src/application/BinaryTargetResolver.ts b/src/application/BinaryTargetResolver.ts index 2a4d13c768..dd6fc37cc4 100644 --- a/src/application/BinaryTargetResolver.ts +++ b/src/application/BinaryTargetResolver.ts @@ -767,13 +767,36 @@ const detectArtifactFormat = async ( throwIfTargetResolutionCancelled(signal); if ( magic.length >= 8 && - magic.subarray(0, 8).equals(Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])) + magic[0] === 0 && + magic[1] === 0x61 && + magic[2] === 0x73 && + magic[3] === 0x6d && + magic[4] === 1 && + magic[5] === 0 && + magic[6] === 0 && + magic[7] === 0 ) throw new BinaryTargetError( path, "WebAssembly v1 artifacts are not supported by the native opening route", { constraint: "wasm_requires_static_inspection" }, ); + const readCachedRange = async ( + position: number, + length: number, + ): Promise => { + throwIfTargetResolutionCancelled(signal); + if (position >= 0 && length >= 0) { + if (position + length <= magic.length) + return magic.subarray(position, position + length); + if (magic.length >= initial.size) + return magic.subarray( + Math.min(position, initial.size), + Math.min(position + length, initial.size), + ); + } + return readHandleRange(handle, position, length, signal); + }; // The shared recognizer table decides; this route reads the trailer or // locates an ESP flash layout only when a recognizer asks for it, and // refuses a file whose header names a format it cannot open. @@ -800,18 +823,15 @@ const detectArtifactFormat = async ( suffix = initial.size < DFUSE_SUFFIX_BYTES ? new Uint8Array(0) - : await readHandleRange( - handle, + : await readCachedRange( initial.size - DFUSE_SUFFIX_BYTES, DFUSE_SUFFIX_BYTES, - signal, ); else espFlashLayout = ( await locateEspFlashLayout( initial.size, - (position, length) => - readHandleRange(handle, position, length, signal), + readCachedRange, {}, { explicit: false, ...(signal === undefined ? {} : { signal }) }, ) @@ -827,17 +847,24 @@ const detectArtifactFormat = async ( if ( lower.endsWith(".pkg") && magic.length >= 4 && - magic.subarray(0, 4).equals(Buffer.from("xar!")) + magic[0] === 0x78 && + magic[1] === 0x61 && + magic[2] === 0x72 && + magic[3] === 0x21 ) return "pkg"; if ( lower.endsWith(".dmg") && - (await hasDiskImageSignature(initial.size, (position, length) => - readHandleRange(handle, position, length, signal), - )) + (await hasDiskImageSignature(initial.size, readCachedRange)) ) return "dmg"; - if (await probeUefiFlashImage(handle, signal)) return "uefi"; + if ( + await probeUefiFlashImage(handle, signal, { + fileSize: initial.size, + prefix: magic, + }) + ) + return "uefi"; // XML property lists can use archive-specific suffixes such as .archive. // The named-format check above keeps .js, .map, and .asar classifications. const xmlProbe = createXmlPlistSignatureProbe(); diff --git a/src/artifacts/ArtifactClassificationProbe.ts b/src/artifacts/ArtifactClassificationProbe.ts index 71a31a09c2..66a360b8ea 100644 --- a/src/artifacts/ArtifactClassificationProbe.ts +++ b/src/artifacts/ArtifactClassificationProbe.ts @@ -148,17 +148,27 @@ export const createArtifactClassificationProbe = ( let mzWindowsHeaderRecord: MzWindowsHeaderRecordEvidence | undefined; let mzWindowsHeaderOffset: number | undefined; let mzHeaderChecked = false; - let suffix = Buffer.alloc(0); + const suffixBuffer = Buffer.allocUnsafe(ARTIFACT_CLASSIFICATION_SUFFIX_BYTES); + let suffixLength = 0; const observeSuffix = (bytes: Uint8Array): void => { - const joined = - bytes.length >= ARTIFACT_CLASSIFICATION_SUFFIX_BYTES - ? bytes - : Buffer.concat([suffix, bytes]); - suffix = Buffer.from( - joined.subarray( - Math.max(0, joined.length - ARTIFACT_CLASSIFICATION_SUFFIX_BYTES), - ), - ); + if (bytes.length === 0) return; + if (bytes.length >= ARTIFACT_CLASSIFICATION_SUFFIX_BYTES) { + suffixBuffer.set( + bytes.subarray(bytes.length - ARTIFACT_CLASSIFICATION_SUFFIX_BYTES), + 0, + ); + suffixLength = ARTIFACT_CLASSIFICATION_SUFFIX_BYTES; + return; + } + if (suffixLength + bytes.length <= ARTIFACT_CLASSIFICATION_SUFFIX_BYTES) { + suffixBuffer.set(bytes, suffixLength); + suffixLength += bytes.length; + return; + } + const keep = ARTIFACT_CLASSIFICATION_SUFFIX_BYTES - bytes.length; + suffixBuffer.copyWithin(0, suffixLength - keep, suffixLength); + suffixBuffer.set(bytes, keep); + suffixLength = ARTIFACT_CLASSIFICATION_SUFFIX_BYTES; }; const observeSignatureWindow = ( offset: number, @@ -177,9 +187,10 @@ export const createArtifactClassificationProbe = ( previous?.copy(window); let observedLength = previous?.length ?? 0; if (start < end && start <= offset + observedLength) { - Buffer.from( + window.set( sourceBytes.subarray(start - sourceOffset, end - sourceOffset), - ).copy(window, start - offset); + start - offset, + ); observedLength = Math.max(observedLength, end - offset); } if (observedLength === 0) return; @@ -206,9 +217,10 @@ export const createArtifactClassificationProbe = ( previous?.copy(window); let observedLength = previous?.length ?? 0; if (start <= offset + observedLength) { - Buffer.from( + window.set( sourceBytes.subarray(start - sourceOffset, end - sourceOffset), - ).copy(window, start - offset); + start - offset, + ); observedLength = Math.max(observedLength, end - offset); } if (observedLength === 0) return; @@ -236,6 +248,8 @@ export const createArtifactClassificationProbe = ( } }; const retainedPrefix = (): Buffer => { + if (blocks.length === 0) return Buffer.alloc(0); + if (blocks.length === 1) return blocks[0]!.subarray(0, retainedBytes); const prefix = Buffer.allocUnsafe(retainedBytes); let copied = 0; for (const block of blocks) { @@ -328,7 +342,9 @@ export const createArtifactClassificationProbe = ( return finishClassificationEvidence( retainedPrefix(), // Bytes the probe did not observe could still follow its last write. - observedBytes === archiveBytes ? suffix : undefined, + observedBytes === archiveBytes + ? suffixBuffer.subarray(0, suffixLength) + : undefined, archiveBytes, (bytes) => asar.finish(bytes), fatSliceHeadersByOffset, diff --git a/src/artifacts/inventory/classify.ts b/src/artifacts/inventory/classify.ts index 8f2fcba755..15be266250 100644 --- a/src/artifacts/inventory/classify.ts +++ b/src/artifacts/inventory/classify.ts @@ -339,6 +339,16 @@ const classifyRootFormat = async ( } // Fill each range: a short result is end of file, not a partial host read. const read = async (position: number, length: number): Promise => { + abortIfNeeded(signal); + if (position >= 0 && length >= 0) { + if (position + length <= evidence.prefix.length) + return evidence.prefix.subarray(position, position + length); + if (evidence.prefix.length >= archiveBytes) + return evidence.prefix.subarray( + Math.min(position, archiveBytes), + Math.min(position + length, archiveBytes), + ); + } const bytes = Buffer.alloc(length); let filled = 0; while (filled < length) { @@ -386,7 +396,11 @@ const classifyRootFormat = async ( if (hasZipSignature(evidence.prefix)) return zipRootPackageFormat(lower); if ( lower.endsWith(".pkg") && - evidence.prefix.subarray(0, 4).equals(Buffer.from("xar!")) + evidence.prefix.length >= 4 && + evidence.prefix[0] === 0x78 && + evidence.prefix[1] === 0x61 && + evidence.prefix[2] === 0x72 && + evidence.prefix[3] === 0x21 ) return "pkg"; if ( @@ -394,7 +408,13 @@ const classifyRootFormat = async ( (await hasDiskImageSignature(archiveBytes, read)) ) return "dmg"; - if (await probeUefiFlashImage(handle, signal)) return "uefi"; + if ( + await probeUefiFlashImage(handle, signal, { + fileSize: archiveBytes, + prefix: evidence.prefix, + }) + ) + return "uefi"; const pck = await embeddedProbes.godotPck(evidence.prefix); if (pck !== undefined) return { kind: "godot-pck", source, location: pck }; // A C3 or S3 dump begins with its bootloader, so the layout is located diff --git a/src/domain/binaryTarget.ts b/src/domain/binaryTarget.ts index fff5e7a0b5..834d94d8ff 100644 --- a/src/domain/binaryTarget.ts +++ b/src/domain/binaryTarget.ts @@ -118,6 +118,13 @@ export const PE_RECORD_HEADER_BYTES = 24; /** Bound the optional-header read used by structural PE admission. */ export const MAX_PE_OPTIONAL_HEADER_BYTES = 4096; +const hasElfMagic = (bytes: Buffer): boolean => + bytes.length >= 4 && + bytes[0] === 0x7f && + bytes[1] === 0x45 && + bytes[2] === 0x4c && + bytes[3] === 0x46; + /** * Whether leading bytes begin an executable header family that * `parseExecutableHeader` interprets, whether or not that header is valid. @@ -127,7 +134,7 @@ export const claimsExecutableHeader = ( fileSize = bytes.length, ): boolean => (bytes.length >= 4 && - (bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) || + (hasElfMagic(bytes) || readMachoHeaderPrefixFacts(bytes).format !== null)) || (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) || readFatContainerHeader(bytes, fileSize).state !== "not-fat"; @@ -144,11 +151,7 @@ export const parseExecutableHeader = ( mzWindowsHeaderSignature?: MzWindowsHeaderSignatureEvidence, fatEvidence?: FatSliceHeaderEvidence, ): Result => { - if ( - bytes.length >= 4 && - bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) - ) - return parseElf(bytes, fileSize); + if (hasElfMagic(bytes)) return parseElf(bytes, fileSize); if (bytes.length >= 2 && bytes[0] === 0x4d && bytes[1] === 0x5a) return parseMzExecutableMetadata( bytes, @@ -176,10 +179,7 @@ export const readNativeHeaderFormat = ( bytes: Buffer, fileSize = bytes.length, ): Result<"elf" | "mach-o" | null, string> => { - if ( - bytes.length >= 4 && - bytes.subarray(0, 4).equals(Buffer.from([0x7f, 0x45, 0x4c, 0x46])) - ) { + if (hasElfMagic(bytes)) { const header = readElfFixedHeader(bytes, fileSize); return header.ok ? ok("elf") : header; } diff --git a/src/filesystem/readFileHandleRange.ts b/src/filesystem/readFileHandleRange.ts index ba07803a18..7a8091306e 100644 --- a/src/filesystem/readFileHandleRange.ts +++ b/src/filesystem/readFileHandleRange.ts @@ -4,23 +4,26 @@ import type { FileHandle } from "node:fs/promises"; * Fill a positional window until its end or explicit EOF, without owning the descriptor. * Checkpoints receive cumulative acquired bytes so an owner can defer cancellation * of a completed range to its finalization without losing the completed observation. + * A destination view lets the caller fill part of an existing allocation. */ export const readFileHandleRange = async ( handle: Pick, position: number, length: number, assertActive: (bytesRead: number) => void = () => {}, + destination?: Buffer, ): Promise => { if ( !Number.isSafeInteger(position) || position < 0 || !Number.isSafeInteger(length) || length < 0 || - !Number.isSafeInteger(position + length) + !Number.isSafeInteger(position + length) || + (destination !== undefined && destination.length !== length) ) throw new RangeError("Invalid file read range"); assertActive(0); - const bytes = Buffer.alloc(length); + const bytes = destination ?? Buffer.alloc(length); let filled = 0; while (filled < length) { assertActive(filled); diff --git a/src/uefi/FirmwareVolume.test.ts b/src/uefi/FirmwareVolume.test.ts index 01f7998142..1d9fc14117 100644 --- a/src/uefi/FirmwareVolume.test.ts +++ b/src/uefi/FirmwareVolume.test.ts @@ -173,3 +173,49 @@ it.each([ ); }, ); + +it.each([false, true])( + "reuses the caller prefix and fills a firmware image directly (short file: %s)", + async (shortFile) => { + const { probeUefiFlashImage } = await import("./UefiFormatProbe.js"); + const probeBytes = 1024 * 1024; + const volume = buildFv({ files: [] }).buffer; + const volumeAt = probeBytes - 128; + const physicalLength = shortFile ? probeBytes + 128 : probeBytes + 8192; + const image = Buffer.alloc(physicalLength); + volume.copy(image, volumeAt); + + const reads: { position: number; storage: ArrayBufferLike }[] = []; + const handle = { + async read( + buffer: Buffer, + offset: number, + length: number, + position: number, + ) { + reads.push({ position, storage: buffer.buffer }); + const end = Math.min( + position + length, + position + 512 * 1024, + image.length, + ); + return { bytesRead: image.copy(buffer, offset, position, end), buffer }; + }, + } as import("node:fs/promises").FileHandle; + const retained = image.subarray(0, 64); + await expect( + probeUefiFlashImage(handle, undefined, { + fileSize: probeBytes + 8192, + prefix: retained, + }), + ).resolves.toBe(!shortFile); + + expect(reads.map(({ position }) => position)).toEqual( + shortFile + ? [64, 64 + 512 * 1024, probeBytes, physicalLength] + : [64, 64 + 512 * 1024, probeBytes], + ); + expect(reads[0]?.storage).toBe(reads[1]?.storage); + expect(reads[2]?.storage.byteLength).toBe(probeBytes + 8192); + }, +); diff --git a/src/uefi/UefiFormatProbe.ts b/src/uefi/UefiFormatProbe.ts index b7656ba0d7..6e16720752 100644 --- a/src/uefi/UefiFormatProbe.ts +++ b/src/uefi/UefiFormatProbe.ts @@ -34,6 +34,31 @@ export function admitUefiFlashImage( ); } +/** Known file facts a caller already read before probing for a PI flash image. */ +export interface UefiFlashProbeKnownInput { + readonly fileSize?: number; + readonly prefix?: Buffer; +} + +/** Extend previously observed bytes without allocating a second tail buffer. */ +const extendPrefix = async ( + handle: FileHandle, + prefix: Buffer, + length: number, + assertActive: () => void, +): Promise => { + const bytes = Buffer.alloc(length); + prefix.copy(bytes); + const tail = await readFileHandleRange( + handle, + prefix.length, + length - prefix.length, + assertActive, + bytes.subarray(prefix.length), + ); + return bytes.subarray(0, prefix.length + tail.length); +}; + /** * Detect a PI flash image through an aligned `_FVH` plausibility probe over * the declared admission prefix (1 MiB). The prefix decides most misses @@ -44,19 +69,32 @@ export function admitUefiFlashImage( export async function probeUefiFlashImage( handle: FileHandle, signal?: AbortSignal, + known?: UefiFlashProbeKnownInput, ): Promise { const throwIfCancelled = (): void => { if (signal?.aborted === true) throw cancelledBy("resolve_binary_target", signal); }; throwIfCancelled(); - const { size } = await handle.stat(); - const prefix = await readFileHandleRange( - handle, - 0, - Math.min(UEFI_FIRMWARE_LIMITS.scanProbeBytes, size), - throwIfCancelled, - ); + const size = known?.fileSize ?? (await handle.stat()).size; + throwIfCancelled(); + if (known?.prefix !== undefined && claimsExecutableHeader(known.prefix, size)) + return false; + + const probeBytes = Math.min(UEFI_FIRMWARE_LIMITS.scanProbeBytes, size); + let prefix: Buffer; + if (known?.prefix !== undefined && known.prefix.length >= probeBytes) { + prefix = known.prefix.subarray(0, probeBytes); + } else if (known?.prefix !== undefined && known.prefix.length > 0) { + prefix = await extendPrefix( + handle, + known.prefix, + probeBytes, + throwIfCancelled, + ); + } else { + prefix = await readFileHandleRange(handle, 0, probeBytes, throwIfCancelled); + } throwIfCancelled(); if (claimsExecutableHeader(prefix, size) || !prefix.includes("_FVH", "ascii")) return false; @@ -65,7 +103,7 @@ export async function probeUefiFlashImage( const observed = readLimit <= prefix.length ? prefix - : await readFileHandleRange(handle, 0, readLimit, throwIfCancelled); + : await extendPrefix(handle, prefix, readLimit, throwIfCancelled); throwIfCancelled(); return admitUefiFlashImage(observed, prefix.length); }