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
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 16:14:17 -05:00
1 parent 36997555d2
commit c9c8e1e088
7 files changed
+198 -48

No files matched your search

+38 -11
View File
@@ -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<Uint8Array> => {
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();
+31 -15
View File
@@ -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,
+22 -2
View File
@@ -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<Buffer> => {
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
+10 -10
View File
@@ -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<ExecutableMetadata, string> => {
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;
}
+5 -2
View File
@@ -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<FileHandle, "read">,
position: number,
length: number,
assertActive: (bytesRead: number) => void = () => {},
destination?: Buffer,
): Promise<Buffer> => {
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);
+46
View File
@@ -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);
},
);
+46 -8
View File
@@ -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<Buffer> => {
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<boolean> {
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);
}