From 841d41df31549e1d8fc424bfb1f47c61818de048 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 22 Nov 2026 17:12:34 -0500 Subject: [PATCH] perf(parsers): remove hot-loop allocs in UEFI, USN, PE, Go, Rust, Maven (#13647) perf(parsers): eliminate hot-loop allocs in UEFI, NTFS USN, PE, Go, Rust, and Maven --- src/domain/windows/ntfsUsnJournal.ts | 65 +++++++++++++-------------- src/go/GoStringLiterals.ts | 6 ++- src/java/MavenGradleMetadataParser.ts | 50 ++++++++++++++++----- src/native/pe/PeImportParser.ts | 8 ++-- src/rust/RustAuditableReader.ts | 13 +++--- src/uefi/FfsFile.ts | 5 ++- 6 files changed, 87 insertions(+), 60 deletions(-) diff --git a/src/domain/windows/ntfsUsnJournal.ts b/src/domain/windows/ntfsUsnJournal.ts index b3a942c2ccc..cfa9a7eda3b 100644 --- a/src/domain/windows/ntfsUsnJournal.ts +++ b/src/domain/windows/ntfsUsnJournal.ts @@ -100,14 +100,9 @@ export function* readUsnJournal( if ((major !== 2 && major !== 3 && major !== 4) || minor !== 0) { yield err({ kind: "unsupported", fileOffset, major, minor }); } else { - const record = new BinaryReader( - journal.range(fileOffset, length, "USN record"), - journal.little, - journal.format, - ); yield major === 4 - ? readExtentRecord(record, fileOffset) - : readNamedRecord(record, fileOffset, major); + ? readExtentRecord(journal, fileOffset, length) + : readNamedRecord(journal, fileOffset, length, major); } fileOffset += length; } @@ -123,17 +118,17 @@ const readReference = ( (width === 16 ? record.word(offset + 8, 64) << 64n : 0n); const readNamedRecord = ( - record: BinaryReader, + journal: BinaryReader, fileOffset: number, + recordBytes: number, majorVersion: 2 | 3, ): Result => { const referenceBytes = majorVersion === 2 ? 8 : 16; const body = COMMON_HEADER_BYTES + referenceBytes * 2; const headerBytes = body + 36; - const recordBytes = record.bytes.length; if (recordBytes < headerBytes) return err({ kind: "malformed", fileOffset }); - const nameBytes = record.u16(body + 32); - const nameOffset = record.u16(body + 34); + const nameBytes = journal.u16(fileOffset + body + 32); + const nameOffset = journal.u16(fileOffset + body + 34); if ( nameOffset < headerBytes || nameOffset % 2 !== 0 || @@ -147,28 +142,32 @@ const readNamedRecord = ( referenceBytes, fileOffset, recordBytes, - fileReference: readReference(record, 8, referenceBytes), - parentReference: readReference(record, 8 + referenceBytes, referenceBytes), - usn: BigInt.asIntN(64, record.word(body, 64)), - timestampFileTime: record.word(body + 8, 64), - reasonFlags: record.u32(body + 16), - sourceFlags: record.u32(body + 20), - securityId: record.u32(body + 24), - fileAttributes: record.u32(body + 28), - name: record - .range(nameOffset, nameBytes, "USN filename") + fileReference: readReference(journal, fileOffset + 8, referenceBytes), + parentReference: readReference( + journal, + fileOffset + 8 + referenceBytes, + referenceBytes, + ), + usn: BigInt.asIntN(64, journal.word(fileOffset + body, 64)), + timestampFileTime: journal.word(fileOffset + body + 8, 64), + reasonFlags: journal.u32(fileOffset + body + 16), + sourceFlags: journal.u32(fileOffset + body + 20), + securityId: journal.u32(fileOffset + body + 24), + fileAttributes: journal.u32(fileOffset + body + 28), + name: journal + .range(fileOffset + nameOffset, nameBytes, "USN filename") .toString("utf16le"), }); }; const readExtentRecord = ( - record: BinaryReader, + journal: BinaryReader, fileOffset: number, + recordBytes: number, ): Result => { - const recordBytes = record.bytes.length; if (recordBytes < 64) return err({ kind: "malformed", fileOffset }); - const extentCount = record.u16(60), - extentSize = record.u16(62); + const extentCount = journal.u16(fileOffset + 60), + extentSize = journal.u16(fileOffset + 62); // Validate the complete declared array before allocating the fixed-size sample. if ( extentSize < 16 || @@ -186,8 +185,8 @@ const readExtentRecord = ( const cursor = 64 + index * extentSize; extentSample.push({ fileOffset: fileOffset + cursor, - offset: BigInt.asIntN(64, record.word(cursor, 64)), - length: BigInt.asIntN(64, record.word(cursor + 8, 64)), + offset: BigInt.asIntN(64, journal.word(fileOffset + cursor, 64)), + length: BigInt.asIntN(64, journal.word(fileOffset + cursor + 8, 64)), }); } return ok({ @@ -195,16 +194,16 @@ const readExtentRecord = ( referenceBytes: 16, fileOffset, recordBytes, - fileReference: readReference(record, 8, 16), - parentReference: readReference(record, 24, 16), - usn: BigInt.asIntN(64, record.word(40, 64)), - reasonFlags: record.u32(48), - sourceFlags: record.u32(52), + fileReference: readReference(journal, fileOffset + 8, 16), + parentReference: readReference(journal, fileOffset + 24, 16), + usn: BigInt.asIntN(64, journal.word(fileOffset + 40, 64)), + reasonFlags: journal.u32(fileOffset + 48), + sourceFlags: journal.u32(fileOffset + 52), timestampFileTime: null, securityId: null, fileAttributes: null, name: null, - remainingExtents: record.u32(56), + remainingExtents: journal.u32(fileOffset + 56), extentCount, extentSize, omittedExtents: extentCount - extentSample.length, diff --git a/src/go/GoStringLiterals.ts b/src/go/GoStringLiterals.ts index d725c89fd62..7bc018fb667 100644 --- a/src/go/GoStringLiterals.ts +++ b/src/go/GoStringLiterals.ts @@ -97,6 +97,7 @@ export const recoverGoStringLiterals = ( const lastTarget = targets[targets.length - 1] as FileMapping; const minTargetAddr = firstTarget.address; const maxTargetEnd = lastTarget.address + BigInt(lastTarget.size); + const targetEnds = targets.map((t) => t.address + BigInt(t.size)); const accepted = new Map(); const rejected = new Set(); @@ -136,7 +137,7 @@ export const recoverGoStringLiterals = ( const targetIndex = lastSpanAtOrBelow(targets, ptr); if (targetIndex < 0) continue; const target = targets[targetIndex] as FileMapping; - if (ptr + rawLen > target.address + BigInt(target.size)) continue; + if (ptr + rawLen > targetEnds[targetIndex]!) continue; const byteLen = Number(rawLen); const sliceOffset = target.offset + Number(ptr - target.address); @@ -234,7 +235,8 @@ export const recoverGoStringLiterals = ( const isPrintableGoUtf8 = (slice: Buffer): boolean => { let hasNonAscii = false; - for (const byte of slice) { + for (let i = 0; i < slice.length; i += 1) { + const byte = slice[i]!; if (byte >= 0x80) { hasNonAscii = true; continue; diff --git a/src/java/MavenGradleMetadataParser.ts b/src/java/MavenGradleMetadataParser.ts index 2a8ae9fe63e..b5c6d58ed90 100644 --- a/src/java/MavenGradleMetadataParser.ts +++ b/src/java/MavenGradleMetadataParser.ts @@ -48,21 +48,47 @@ const childElements = (element: Element): Element[] => { return children; }; -const childrenNamed = (element: Element, ...names: string[]): Element[] => - childElements(element).filter( - (child) => - (child.namespaceURI ?? "") === (element.namespaceURI ?? "") && +const childrenNamed = (element: Element, ...names: string[]): Element[] => { + const ns = element.namespaceURI ?? ""; + const matches: Element[] = []; + for ( + let child = element.firstChild; + child !== null; + child = child.nextSibling + ) { + if ( + isElement(child) && + (child.namespaceURI ?? "") === ns && child.localName !== null && - names.includes(child.localName), - ); + names.includes(child.localName) + ) + matches.push(child); + } + return matches; +}; const soleNamed = (element: Element, local: string): Element | undefined => { - const matches = childrenNamed(element, local); - if (matches.length <= 1) return matches[0]; - throw malformedInput( - MAVEN_GRADLE_METADATA_FORMAT, - `Maven POM declares <${local}> more than once in one <${element.localName}>.`, - ); + const ns = element.namespaceURI ?? ""; + let found: Element | undefined; + for ( + let child = element.firstChild; + child !== null; + child = child.nextSibling + ) { + if ( + isElement(child) && + (child.namespaceURI ?? "") === ns && + child.localName === local + ) { + if (found !== undefined) + throw malformedInput( + MAVEN_GRADLE_METADATA_FORMAT, + `Maven POM declares <${local}> more than once in one <${element.localName}>.`, + ); + found = child; + } + } + return found; }; const MAVEN_POM_NAMESPACE = "http://maven.apache.org/POM/4.0.0"; diff --git a/src/native/pe/PeImportParser.ts b/src/native/pe/PeImportParser.ts index 9fc4923ac2f..7124aea1dd6 100644 --- a/src/native/pe/PeImportParser.ts +++ b/src/native/pe/PeImportParser.ts @@ -196,8 +196,6 @@ export const parsePeImports = async ( let examinedFunctions = 0; let entries = 0; const checkpoint = async (): Promise => { - entries += 1; - if (entries % ENTRIES_PER_YIELD !== 0) return; await setImmediate(); assertArtifactReadActive(signal); }; @@ -252,7 +250,7 @@ export const parsePeImports = async ( const ordinalFlag = bits === 64 ? ORDINAL_FLAG64 : ORDINAL_FLAG32; const functions: PeImportFunction[] = []; for (let index = 0; ; index++) { - await checkpoint(); + if (++entries % ENTRIES_PER_YIELD === 0) await checkpoint(); const nameRva = nameTableRva + index * thunkWidth; const iatRva = addressTableRva + index * thunkWidth; if (!admitRva(nameRva, thunkWidth, "Import lookup table")) break; @@ -383,7 +381,7 @@ export const parsePeImports = async ( if (importDirectory !== undefined && importDirectory.address !== 0) { const spans: { offset: number; bytes: number }[] = []; for (let index = 0; ; index++) { - await checkpoint(); + if (++entries % ENTRIES_PER_YIELD === 0) await checkpoint(); const descriptorRva = importDirectory.address + index * IMPORT_DESCRIPTOR_BYTES; if ( @@ -469,7 +467,7 @@ export const parsePeImports = async ( if (delayDirectory !== undefined && delayDirectory.address !== 0) { const spans: { offset: number; bytes: number }[] = []; for (let index = 0; ; index++) { - await checkpoint(); + if (++entries % ENTRIES_PER_YIELD === 0) await checkpoint(); const descriptorRva = delayDirectory.address + index * DELAY_DESCRIPTOR_BYTES; if ( diff --git a/src/rust/RustAuditableReader.ts b/src/rust/RustAuditableReader.ts index 29e6176f650..6c9967debdf 100644 --- a/src/rust/RustAuditableReader.ts +++ b/src/rust/RustAuditableReader.ts @@ -391,25 +391,26 @@ const assertDepth = (text: string): void => { let depth = 0; let quoted = false; let escaped = false; - for (const char of text) { + for (let i = 0; i < text.length; i += 1) { + const code = text.charCodeAt(i); if (quoted) { if (escaped) escaped = false; - else if (char === "\\") escaped = true; - else if (char === '"') quoted = false; + else if (code === 0x5c) escaped = true; + else if (code === 0x22) quoted = false; continue; } - if (char === '"') { + if (code === 0x22) { quoted = true; continue; } - if (char === "{" || char === "[") { + if (code === 0x7b || code === 0x5b) { depth += 1; if (depth > JSON_DEPTH) throw malformedInput( RUST_AUDITABLE_FORMAT, "Dependency JSON nesting exceeds 32 levels", ); - } else if ((char === "}" || char === "]") && depth > 0) depth -= 1; + } else if ((code === 0x7d || code === 0x5d) && depth > 0) depth -= 1; } }; diff --git a/src/uefi/FfsFile.ts b/src/uefi/FfsFile.ts index 7fc09496064..cafa4d0421d 100644 --- a/src/uefi/FfsFile.ts +++ b/src/uefi/FfsFile.ts @@ -239,8 +239,9 @@ export function checkFfsFileIntegrity( const length = end - start; if (length === 0) return { verdict: "unchecked" } as const; let total = header.fileChecksumField; - for (const byte of region.buffer.subarray(start, end)) { - total = (total + byte) & 0xff; + const buffer = region.buffer; + for (let i = start; i < end; i += 1) { + total = (total + buffer[i]!) & 0xff; } return total === 0 ? ({ verdict: "valid" } as const)