mirror of
https://github.com/morluto/rea.git
synced 2026-11-30 02:17:09 +00:00
perf(model/uefi/rizin): cache GGUF/UEFI BinaryReaders and share O(1) FifoQueue (#13745)
* perf(model/uefi/rizin): cache GGUF/UEFI BinaryReaders and share O(1) FifoQueue * perf(uefi): reuse GUID reader across firmware file headers
This commit is contained in:
1 parent
6fa4f337b3
commit
91b45c0aee
8 files changed
+260
-152
No files matched your search
@@ -61,6 +61,7 @@ import {
|
||||
} from "../domain/fridaCapturePolicy.js";
|
||||
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
import { FifoQueue } from "../kernel/FifoQueue.js";
|
||||
import { sha256Hex } from "../kernel/sha256Hex.js";
|
||||
|
||||
const DEVICE_LOOKUP_TIMEOUT_MS = 1_000;
|
||||
@@ -77,7 +78,7 @@ const isFridaDeviceLookupTimeout = (cause: unknown): boolean =>
|
||||
cause.message === FRIDA_DEVICE_LOOKUP_TIMEOUT_MESSAGE;
|
||||
|
||||
interface ScriptMessageCapture {
|
||||
readonly messages: MessageFifo<JsonValue>;
|
||||
readonly messages: FifoQueue<JsonValue>;
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
@@ -113,7 +114,7 @@ interface ManagedSession extends ManagedRemoteConnection {
|
||||
readonly pid: number;
|
||||
readonly mode: "attach" | "spawn";
|
||||
readonly scripts: Map<string, ManagedScript>;
|
||||
readonly messages: MessageFifo<CapturedMessage>;
|
||||
readonly messages: FifoQueue<CapturedMessage>;
|
||||
readonly scriptCaptures: Map<string, ScriptMessageCapture>;
|
||||
/** Once close begins, this session is retained only for cleanup. */
|
||||
cleanupStarted: boolean;
|
||||
@@ -373,7 +374,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
|
||||
pid,
|
||||
mode: input.mode,
|
||||
scripts: new Map(),
|
||||
messages: new MessageFifo(),
|
||||
messages: new FifoQueue(),
|
||||
scriptCaptures: new Map(),
|
||||
cleanupStarted: false,
|
||||
detached: false,
|
||||
@@ -499,7 +500,7 @@ export class FridaInstrumentationManager implements FridaInstrumentationPort {
|
||||
return err(cancelledOperation("load_frida_script", signal));
|
||||
const scriptId = randomUUID();
|
||||
const capture: ScriptMessageCapture = {
|
||||
messages: new MessageFifo(),
|
||||
messages: new FifoQueue(),
|
||||
truncated: false,
|
||||
};
|
||||
managed.scriptCaptures.set(scriptId, capture);
|
||||
@@ -1970,42 +1971,3 @@ const markMessageTruncated = (
|
||||
const capture = managed.scriptCaptures.get(scriptId);
|
||||
if (capture !== undefined) capture.truncated = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Arrival-ordered queue whose eviction advances a head offset. A full capture
|
||||
* budget evicts on every message, and `Array#shift` would copy every retained
|
||||
* message each time.
|
||||
*/
|
||||
class MessageFifo<T> {
|
||||
#items: (T | undefined)[] = [];
|
||||
#head = 0;
|
||||
|
||||
get size(): number {
|
||||
return this.#items.length - this.#head;
|
||||
}
|
||||
|
||||
push(item: T): void {
|
||||
this.#items.push(item);
|
||||
}
|
||||
|
||||
peek(): T | undefined {
|
||||
return this.#items[this.#head];
|
||||
}
|
||||
|
||||
shift(): T | undefined {
|
||||
if (this.#head >= this.#items.length) return undefined;
|
||||
const item = this.#items[this.#head];
|
||||
this.#items[this.#head] = undefined;
|
||||
this.#head += 1;
|
||||
// Compacting once half the slots are evicted keeps eviction amortized O(1).
|
||||
if (this.#head * 2 >= this.#items.length) {
|
||||
this.#items = this.#items.slice(this.#head);
|
||||
this.#head = 0;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
toArray(): T[] {
|
||||
return this.#items.slice(this.#head) as T[];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { FifoQueue } from "./FifoQueue.js";
|
||||
|
||||
describe("FifoQueue", () => {
|
||||
it("preserves FIFO order across compaction and clear", () => {
|
||||
const queue = new FifoQueue<number>();
|
||||
expect(queue.size).toBe(0);
|
||||
expect(queue.peek()).toBeUndefined();
|
||||
expect(queue.shift()).toBeUndefined();
|
||||
|
||||
for (let i = 0; i < 10; i++) queue.push(i);
|
||||
expect(queue.size).toBe(10);
|
||||
expect(queue.peek()).toBe(0);
|
||||
|
||||
const drained: number[] = [];
|
||||
for (let i = 0; i < 6; i++) drained.push(queue.shift()!);
|
||||
expect(drained).toEqual([0, 1, 2, 3, 4, 5]);
|
||||
expect(queue.size).toBe(4);
|
||||
expect(queue.toArray()).toEqual([6, 7, 8, 9]);
|
||||
|
||||
queue.clear();
|
||||
expect(queue.size).toBe(0);
|
||||
expect(queue.shift()).toBeUndefined();
|
||||
expect(queue.toArray()).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Arrival-ordered FIFO queue whose dequeue advances a head offset.
|
||||
* Compacting once half the backing slots are evicted keeps push/shift
|
||||
* amortized O(1) without shifting remaining elements on every dequeue.
|
||||
*/
|
||||
export class FifoQueue<T> {
|
||||
#items: (T | undefined)[] = [];
|
||||
#head = 0;
|
||||
|
||||
get size(): number {
|
||||
return this.#items.length - this.#head;
|
||||
}
|
||||
|
||||
push(item: T): void {
|
||||
this.#items.push(item);
|
||||
}
|
||||
|
||||
peek(): T | undefined {
|
||||
return this.#items[this.#head];
|
||||
}
|
||||
|
||||
shift(): T | undefined {
|
||||
if (this.#head >= this.#items.length) return undefined;
|
||||
const item = this.#items[this.#head];
|
||||
this.#items[this.#head] = undefined;
|
||||
this.#head += 1;
|
||||
if (this.#head * 2 >= this.#items.length) {
|
||||
this.#items = this.#items.slice(this.#head);
|
||||
this.#head = 0;
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.#items = [];
|
||||
this.#head = 0;
|
||||
}
|
||||
|
||||
toArray(): T[] {
|
||||
return this.#items.slice(this.#head) as T[];
|
||||
}
|
||||
}
|
||||
+61
-41
@@ -63,40 +63,22 @@ export class GgufHeader {
|
||||
readonly #budget = new ModelReportBudget();
|
||||
constructor(readonly reader: ModelHeaderReader) {}
|
||||
|
||||
// take() returns exactly `width` bytes, so field reads at 0 stay in range.
|
||||
async #field(width: number): Promise<BinaryReader> {
|
||||
return new BinaryReader(
|
||||
await this.reader.take(width),
|
||||
this.#little,
|
||||
"gguf",
|
||||
);
|
||||
}
|
||||
|
||||
async #unsigned(width: 4 | 8): Promise<bigint> {
|
||||
const fields = new BinaryReader(
|
||||
await this.reader.take(width),
|
||||
this.#little,
|
||||
"gguf",
|
||||
);
|
||||
return fields.word(0, width === 4 ? 32 : 64);
|
||||
const offset =
|
||||
this.reader.takeOffsetSync(width) ??
|
||||
(await this.reader.takeOffset(width));
|
||||
return this.reader
|
||||
.binaryReader(this.#little)
|
||||
.word(offset, width === 4 ? 32 : 64);
|
||||
}
|
||||
|
||||
async #text(
|
||||
retain: boolean,
|
||||
requiredAfter: number,
|
||||
maximum?: number,
|
||||
): Promise<string> {
|
||||
const rawLength = await this.#unsigned(STRING_LENGTH_BYTES);
|
||||
if (maximum !== undefined && rawLength > BigInt(maximum))
|
||||
rejectModel("GGUF name exceeds its format byte limit");
|
||||
this.reader.guarantee(rawLength + BigInt(requiredAfter));
|
||||
const length = Number(rawLength);
|
||||
if (retain) this.#budget.charge(6 * length + 2);
|
||||
async #decodeTextBytes(length: number, retain: boolean): Promise<string> {
|
||||
// Omitted preview entries still need validation, but not decoded strings.
|
||||
// Keep the streaming decoder for values spanning multiple read chunks.
|
||||
if (!retain && length <= 65536) {
|
||||
if (!isUtf8(await this.reader.take(length)))
|
||||
rejectModel("GGUF string is not valid UTF-8");
|
||||
const slice =
|
||||
this.reader.takeSync(length) ?? (await this.reader.take(length));
|
||||
if (!isUtf8(slice)) rejectModel("GGUF string is not valid UTF-8");
|
||||
return "";
|
||||
}
|
||||
const decoder = strictUtf8Decoder("preserve");
|
||||
@@ -104,7 +86,8 @@ export class GgufHeader {
|
||||
try {
|
||||
for (let left = length; left > 0;) {
|
||||
const n = Math.min(left, 65536);
|
||||
const text = decoder.decode(await this.reader.take(n), {
|
||||
const slice = this.reader.takeSync(n) ?? (await this.reader.take(n));
|
||||
const text = decoder.decode(slice, {
|
||||
stream: true,
|
||||
});
|
||||
if (retain) result += text;
|
||||
@@ -120,6 +103,20 @@ export class GgufHeader {
|
||||
return result;
|
||||
}
|
||||
|
||||
async #text(
|
||||
retain: boolean,
|
||||
requiredAfter: number,
|
||||
maximum?: number,
|
||||
): Promise<string> {
|
||||
const rawLength = await this.#unsigned(STRING_LENGTH_BYTES);
|
||||
if (maximum !== undefined && rawLength > BigInt(maximum))
|
||||
rejectModel("GGUF name exceeds its format byte limit");
|
||||
this.reader.guarantee(rawLength + BigInt(requiredAfter));
|
||||
const length = Number(rawLength);
|
||||
if (retain) this.#budget.charge(6 * length + 2);
|
||||
return this.#decodeTextBytes(length, retain);
|
||||
}
|
||||
|
||||
async #value(
|
||||
type: number,
|
||||
retain: boolean,
|
||||
@@ -183,6 +180,26 @@ export class GgufHeader {
|
||||
const remaining = (count - index - 1) * minimum + requiredAfter;
|
||||
if (element === 8) {
|
||||
this.reader.guarantee(minimum + remaining);
|
||||
if (!keep) {
|
||||
const lenOffset = this.reader.takeOffsetSync(STRING_LENGTH_BYTES);
|
||||
if (lenOffset !== undefined) {
|
||||
const rawLength = this.reader
|
||||
.binaryReader(this.#little)
|
||||
.word(lenOffset, 64);
|
||||
this.reader.guarantee(rawLength + BigInt(remaining));
|
||||
const length = Number(rawLength);
|
||||
if (length <= 65536) {
|
||||
const slice =
|
||||
this.reader.takeSync(length) ??
|
||||
(await this.reader.take(length));
|
||||
if (!isUtf8(slice))
|
||||
rejectModel("GGUF string is not valid UTF-8");
|
||||
continue;
|
||||
}
|
||||
await this.#decodeTextBytes(length, false);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const text = await this.#text(keep, remaining);
|
||||
if (keep) preview.push(text);
|
||||
continue;
|
||||
@@ -209,45 +226,48 @@ export class GgufHeader {
|
||||
complete,
|
||||
};
|
||||
}
|
||||
const b = await this.#field(width);
|
||||
const offset =
|
||||
this.reader.takeOffsetSync(width) ??
|
||||
(await this.reader.takeOffset(width));
|
||||
const b = this.reader.binaryReader(this.#little);
|
||||
let value: JsonValue;
|
||||
switch (type) {
|
||||
case 0:
|
||||
value = b.u8(0);
|
||||
value = b.u8(offset);
|
||||
break;
|
||||
case 1:
|
||||
value = b.i8(0);
|
||||
value = b.i8(offset);
|
||||
break;
|
||||
case 2:
|
||||
value = b.u16(0);
|
||||
value = b.u16(offset);
|
||||
break;
|
||||
case 3:
|
||||
value = b.i16(0);
|
||||
value = b.i16(offset);
|
||||
break;
|
||||
case 4:
|
||||
value = b.u32(0);
|
||||
value = b.u32(offset);
|
||||
break;
|
||||
case 5:
|
||||
value = b.i32(0);
|
||||
value = b.i32(offset);
|
||||
break;
|
||||
case 6:
|
||||
value = b.f32(0);
|
||||
value = b.f32(offset);
|
||||
break;
|
||||
case 7: {
|
||||
const byte = b.u8(0);
|
||||
const byte = b.u8(offset);
|
||||
if (byte !== 0 && byte !== 1)
|
||||
rejectModel("GGUF boolean must be 0 or 1");
|
||||
value = byte === 1;
|
||||
break;
|
||||
}
|
||||
case 10:
|
||||
value = b.word(0, 64).toString();
|
||||
value = b.word(offset, 64).toString();
|
||||
break;
|
||||
case 11:
|
||||
value = b.i64(0).toString();
|
||||
value = b.i64(offset).toString();
|
||||
break;
|
||||
case 12:
|
||||
value = b.f64(0);
|
||||
value = b.f64(offset);
|
||||
break;
|
||||
default:
|
||||
return rejectModel("Unsupported GGUF scalar");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import { BinaryReader } from "../domain/binaryContainer.js";
|
||||
import {
|
||||
assertArtifactReadActive,
|
||||
ArtifactReaderFailure,
|
||||
@@ -17,6 +18,8 @@ export class ModelHeaderReader {
|
||||
#end = 0;
|
||||
#guaranteedEnd = 0;
|
||||
#buffer = Buffer.alloc(0);
|
||||
#littleReader: BinaryReader | undefined;
|
||||
#bigReader: BinaryReader | undefined;
|
||||
#start = 0;
|
||||
#headerPrefixBytes = 0;
|
||||
readonly #hash = createHash("sha256");
|
||||
@@ -67,48 +70,85 @@ export class ModelHeaderReader {
|
||||
);
|
||||
}
|
||||
|
||||
async take(length: number): Promise<Buffer> {
|
||||
/** Cached BinaryReader over the current read-ahead buffer (reset on refill). */
|
||||
binaryReader(little: boolean): BinaryReader {
|
||||
if (little) {
|
||||
this.#littleReader ??= new BinaryReader(this.#buffer, true, "model");
|
||||
return this.#littleReader;
|
||||
}
|
||||
this.#bigReader ??= new BinaryReader(this.#buffer, false, "model");
|
||||
return this.#bigReader;
|
||||
}
|
||||
|
||||
async #fill(end: number): Promise<void> {
|
||||
const readEnd = Math.max(
|
||||
end,
|
||||
Math.min(this.position + 65536, this.#guaranteedEnd),
|
||||
);
|
||||
const retained = this.#buffer.subarray(this.position - this.#start);
|
||||
const next = Buffer.allocUnsafe(readEnd - this.position);
|
||||
retained.copy(next);
|
||||
let offset = retained.length;
|
||||
while (offset < next.length) {
|
||||
assertArtifactReadActive(this.signal);
|
||||
const result = await this.file.read(
|
||||
next,
|
||||
offset,
|
||||
next.length - offset,
|
||||
this.position + offset,
|
||||
);
|
||||
if (result.bytesRead === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Model header ended before its admitted file extent",
|
||||
{ integrityCheck: "read-coverage" },
|
||||
);
|
||||
this.#hash.update(next.subarray(offset, offset + result.bytesRead));
|
||||
offset += result.bytesRead;
|
||||
}
|
||||
this.#start = this.position;
|
||||
this.#end = readEnd;
|
||||
this.#buffer = next;
|
||||
this.#littleReader = undefined;
|
||||
this.#bigReader = undefined;
|
||||
}
|
||||
|
||||
/** Fast synchronous advance when `length` bytes are already in `#buffer`. */
|
||||
takeOffsetSync(length: number): number | undefined {
|
||||
assertArtifactReadActive(this.signal);
|
||||
const end = this.position + length;
|
||||
this.#validateEnd(end);
|
||||
if (!Number.isSafeInteger(length) || length < 0)
|
||||
rejectModel("Invalid header field length");
|
||||
if (end > this.#end) {
|
||||
const readEnd = Math.max(
|
||||
end,
|
||||
Math.min(this.position + 65536, this.#guaranteedEnd),
|
||||
);
|
||||
const retained = this.#buffer.subarray(this.position - this.#start);
|
||||
const next = Buffer.allocUnsafe(readEnd - this.position);
|
||||
retained.copy(next);
|
||||
let offset = retained.length;
|
||||
while (offset < next.length) {
|
||||
assertArtifactReadActive(this.signal);
|
||||
const result = await this.file.read(
|
||||
next,
|
||||
offset,
|
||||
next.length - offset,
|
||||
this.position + offset,
|
||||
);
|
||||
if (result.bytesRead === 0)
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
"Model header ended before its admitted file extent",
|
||||
{ integrityCheck: "read-coverage" },
|
||||
);
|
||||
this.#hash.update(next.subarray(offset, offset + result.bytesRead));
|
||||
offset += result.bytesRead;
|
||||
}
|
||||
this.#start = this.position;
|
||||
this.#end = readEnd;
|
||||
this.#buffer = next;
|
||||
}
|
||||
const result = this.#buffer.subarray(
|
||||
this.position - this.#start,
|
||||
end - this.#start,
|
||||
);
|
||||
if (end > this.#end) return undefined;
|
||||
const offset = this.position - this.#start;
|
||||
this.position = end;
|
||||
return result;
|
||||
return offset;
|
||||
}
|
||||
|
||||
/** Advance `length` bytes and return their offset within the current `#buffer`. */
|
||||
async takeOffset(length: number): Promise<number> {
|
||||
assertArtifactReadActive(this.signal);
|
||||
const end = this.position + length;
|
||||
this.#validateEnd(end);
|
||||
if (!Number.isSafeInteger(length) || length < 0)
|
||||
rejectModel("Invalid header field length");
|
||||
if (end > this.#end) await this.#fill(end);
|
||||
const offset = this.position - this.#start;
|
||||
this.position = end;
|
||||
return offset;
|
||||
}
|
||||
|
||||
/** Fast synchronous slice when `length` bytes are already in `#buffer`. */
|
||||
takeSync(length: number): Buffer | undefined {
|
||||
const offset = this.takeOffsetSync(length);
|
||||
if (offset === undefined) return undefined;
|
||||
return this.#buffer.subarray(offset, offset + length);
|
||||
}
|
||||
|
||||
async take(length: number): Promise<Buffer> {
|
||||
const offset = await this.takeOffset(length);
|
||||
return this.#buffer.subarray(offset, offset + length);
|
||||
}
|
||||
|
||||
async consume(length: number): Promise<void> {
|
||||
|
||||
@@ -82,6 +82,7 @@ import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js";
|
||||
import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js";
|
||||
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
import { FifoQueue } from "../kernel/FifoQueue.js";
|
||||
|
||||
const CLEANUP_COMMAND_TIMEOUT_MS = 1_000;
|
||||
const STARTUP_TIMEOUT_MS = 30_000;
|
||||
@@ -241,7 +242,7 @@ interface RizinDebugSession {
|
||||
readonly id: string;
|
||||
readonly launched: SpawnedOwnedProviderProcess;
|
||||
readonly supervisor: ProviderProcessSupervisor;
|
||||
readonly frames: Array<{
|
||||
readonly frames: FifoQueue<{
|
||||
readonly frame: RizinFrame;
|
||||
readonly queueChargeBytes: number;
|
||||
}>;
|
||||
@@ -677,7 +678,7 @@ export class RizinDebugSessionManager {
|
||||
maxDiagnosticBytes: MAX_DIAGNOSTIC_BYTES,
|
||||
},
|
||||
),
|
||||
frames: [],
|
||||
frames: new FifoQueue(),
|
||||
frameWaiters: [],
|
||||
history: [],
|
||||
queuedFrameBytes: 0,
|
||||
@@ -1354,7 +1355,9 @@ export class RizinDebugSessionManager {
|
||||
continue;
|
||||
}
|
||||
if (piece.length > 0) {
|
||||
session.frameChunks.push(Buffer.from(piece));
|
||||
session.frameChunks.push(
|
||||
piece.length === chunk.length ? chunk : Buffer.from(piece),
|
||||
);
|
||||
session.bufferedFrameBytes += piece.length;
|
||||
}
|
||||
if (boundary < 0) return;
|
||||
@@ -1429,7 +1432,7 @@ export class RizinDebugSessionManager {
|
||||
MIN_QUEUED_FRAME_CHARGE_BYTES,
|
||||
);
|
||||
if (
|
||||
session.frames.length >= MAX_QUEUED_FRAMES ||
|
||||
session.frames.size >= MAX_QUEUED_FRAMES ||
|
||||
session.queuedFrameBytes + queueChargeBytes > MAX_QUEUED_FRAME_BYTES
|
||||
) {
|
||||
session.commandOutputDropped ||= session.commandCaptureActive;
|
||||
@@ -1620,7 +1623,7 @@ export class RizinDebugSessionManager {
|
||||
// Admission remains closed. Only cleanup can recover correlation, and then
|
||||
// it still obtains a fresh ptrace inventory and validates identity/output.
|
||||
session.ready = false;
|
||||
session.frames.length = 0;
|
||||
session.frames.clear();
|
||||
session.queuedFrameBytes = 0;
|
||||
const marker = `__REA_CLEANUP_SYNC_${randomUUID().replaceAll("-", "")}__`;
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
@@ -1868,7 +1871,7 @@ export const assertRizinProcessStartTimeStable = (
|
||||
};
|
||||
|
||||
const hasUnclaimedRizinFrames = (session: RizinDebugSession): boolean =>
|
||||
session.frames.length > 0 ||
|
||||
session.frames.size > 0 ||
|
||||
session.bufferedFrameBytes > 0 ||
|
||||
session.discardingOversizedFrame;
|
||||
|
||||
@@ -1975,10 +1978,8 @@ const waitForCommandFrames = async (
|
||||
// following it, and apply the same decoded UTF-8 budget as normal frames.
|
||||
const interrupted = () => {
|
||||
let markerSeen = false;
|
||||
let consumed = 0;
|
||||
while (consumed < session.frames.length) {
|
||||
const queued = session.frames[consumed]!;
|
||||
consumed += 1;
|
||||
while (session.frames.size > 0) {
|
||||
const queued = session.frames.shift()!;
|
||||
session.queuedFrameBytes -= queued.queueChargeBytes;
|
||||
frameCount += 1;
|
||||
if (frameCount > MAX_COMMAND_FRAMES) {
|
||||
@@ -1988,7 +1989,6 @@ const waitForCommandFrames = async (
|
||||
markerSeen = append(queued.frame);
|
||||
if (markerSeen || outputTruncated) break;
|
||||
}
|
||||
if (consumed > 0) session.frames.splice(0, consumed);
|
||||
if (!markerSeen && !outputTruncated && session.bufferedFrameBytes > 0)
|
||||
append(
|
||||
bufferedRizinFrame(session, session.discardingOversizedFrame).frame,
|
||||
|
||||
+15
-6
@@ -65,6 +65,18 @@ interface UnconfirmedFfsState {
|
||||
* Checksum findings are observations on the header,
|
||||
* not rejections — invalid files stay in the inventory with their notes.
|
||||
*/
|
||||
const MAX_SAFE_INTEGER_BIGINT = BigInt(Number.MAX_SAFE_INTEGER);
|
||||
const ffsFileReaders = new WeakMap<Buffer, BinaryReader>();
|
||||
|
||||
function ffsFileReader(buffer: Buffer): BinaryReader {
|
||||
let reader = ffsFileReaders.get(buffer);
|
||||
if (reader === undefined) {
|
||||
reader = new BinaryReader(buffer, true, "FFS file");
|
||||
ffsFileReaders.set(buffer, reader);
|
||||
}
|
||||
return reader;
|
||||
}
|
||||
|
||||
export function parseFfsFileHeader(
|
||||
region: ScanRegion,
|
||||
localBase: number,
|
||||
@@ -115,14 +127,14 @@ function observeFfsFileHeader(
|
||||
let headerLength: number = FFS_HEADER_LAYOUT.length;
|
||||
let declaredLength = declaredCompact;
|
||||
if (largeFile) {
|
||||
const reader = new BinaryReader(region.buffer, true, "FFS file");
|
||||
if (!extended) return null;
|
||||
const reader = ffsFileReader(region.buffer);
|
||||
headerLength = FFS_HEADER_LAYOUT.extendedLength;
|
||||
const size = reader.word(
|
||||
localBase + FFS_HEADER_LAYOUT.extendedSizeOffset,
|
||||
64,
|
||||
);
|
||||
if (size > BigInt(Number.MAX_SAFE_INTEGER))
|
||||
if (size > MAX_SAFE_INTEGER_BIGINT)
|
||||
return { kind: "unrepresentable", size, unusableState };
|
||||
declaredLength = Number(size);
|
||||
if (declaredCompact !== 0)
|
||||
@@ -166,10 +178,7 @@ function observeFfsFileHeader(
|
||||
: null,
|
||||
bodyIssue: state === "header-valid" ? "data-not-valid" : null,
|
||||
extentIssue,
|
||||
nameGuid: formatGuidLittleEndian(
|
||||
region.buffer.subarray(localBase, localBase + 16),
|
||||
0,
|
||||
),
|
||||
nameGuid: formatGuidLittleEndian(region.buffer, localBase),
|
||||
typeCode: region.buffer[localBase + FFS_HEADER_LAYOUT.typeOffset] ?? 0,
|
||||
attributes,
|
||||
dataAlignment:
|
||||
|
||||
+24
-15
@@ -4,6 +4,17 @@ import { Buffer } from "node:buffer";
|
||||
/** UEFI GUIDs are 16 raw bytes rendered as 8-4-4-4-12 hex digits. */
|
||||
export const GUID_LENGTH = 16;
|
||||
|
||||
const guidReaders = new WeakMap<Buffer, BinaryReader>();
|
||||
|
||||
function guidReader(buffer: Buffer): BinaryReader {
|
||||
let reader = guidReaders.get(buffer);
|
||||
if (reader === undefined) {
|
||||
reader = new BinaryReader(buffer, true, "UEFI GUID");
|
||||
guidReaders.set(buffer, reader);
|
||||
}
|
||||
return reader;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a raw GUID with UEFI mixed-endian decoding: the first data word and
|
||||
* the two following words read little-endian, the remaining eight bytes keep
|
||||
@@ -17,21 +28,19 @@ export function formatGuidLittleEndian(
|
||||
if (offset < 0 || offset + GUID_LENGTH > buffer.length) {
|
||||
return null;
|
||||
}
|
||||
const reader = new BinaryReader(buffer, true, "UEFI GUID");
|
||||
const data1 = reader.u32(offset);
|
||||
const data2 = reader.u16(offset + 4);
|
||||
const data3 = reader.u16(offset + 6);
|
||||
const tail = buffer.subarray(offset + 8, offset + GUID_LENGTH);
|
||||
const word = (value: number, digits: number): string =>
|
||||
value.toString(16).padStart(digits, "0");
|
||||
const node = Array.from(tail, (byte) => word(byte, 2)).join("");
|
||||
return [
|
||||
word(data1, 8),
|
||||
word(data2, 4),
|
||||
word(data3, 4),
|
||||
node.slice(0, 4),
|
||||
node.slice(4),
|
||||
].join("-");
|
||||
const reader = guidReader(buffer);
|
||||
const data1 = reader.u32(offset).toString(16).padStart(8, "0");
|
||||
const data2 = reader
|
||||
.u16(offset + 4)
|
||||
.toString(16)
|
||||
.padStart(4, "0");
|
||||
const data3 = reader
|
||||
.u16(offset + 6)
|
||||
.toString(16)
|
||||
.padStart(4, "0");
|
||||
const clockSeq = buffer.toString("hex", offset + 8, offset + 10);
|
||||
const node = buffer.toString("hex", offset + 10, offset + GUID_LENGTH);
|
||||
return `${data1}-${data2}-${data3}-${clockSeq}-${node}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in new issue
Block a user