perf(search/kuna): optimize regex worker dispatch and Kuna inventory validation (#13320)

perf(search,kuna): optimize RegexMatcher worker dispatch and Kuna inventory validators
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 03:46:02 -05:00
1 parent e0d8cc942f
commit 2f171faa9f
15 files changed
+899 -160

No files matched your search

+54
View File
@@ -3,6 +3,7 @@ import { expect, it } from "vitest";
import {
analysisSearchPredicate,
literalSubstringPredicate,
matchedProcedureAliases,
matchProcedureNames,
} from "./analysisSearch.js";
@@ -101,3 +102,56 @@ it("preserves single-alias matches, primary fallback and duplicate ordering", ()
matched_aliases: ["name", "name2"],
});
});
it("handles empty patterns and Unicode simple case folding boundaries", () => {
expect(literalSubstringPredicate("", false)("")).toBe(true);
expect(literalSubstringPredicate("", false)("Δelta")).toBe(true);
expect(
analysisSearchPredicate({
pattern: "",
mode: "regex",
case_sensitive: false,
document: undefined,
})(""),
).toBe(true);
expect(literalSubstringPredicate("::123", false)("ns::123_fn")).toBe(true);
expect(literalSubstringPredicate("::123", false)("ns:123_fn")).toBe(false);
// Kelvin sign (U+212A) and long s (U+017F) fold to k/s under ECMAScript iu,
// while İ (U+0130) must NOT match ASCII 'i'.
expect(literalSubstringPredicate("sk", false)("\u017f\u212a")).toBe(true);
expect(literalSubstringPredicate("i", false)("\u0130")).toBe(false);
});
it("deduplicates and orders matched aliases across zero, small, and large alias lists", () => {
const matches = (value: string) => value.startsWith("hit_");
expect(matchedProcedureAliases("hit_primary", [], matches)).toBeUndefined();
expect(
matchedProcedureAliases("hit_primary", ["hit_primary"], matches),
).toBeUndefined();
expect(
matchedProcedureAliases(
"primary",
["miss", "hit_1", "miss", "hit_2", "hit_1", "primary"],
matches,
),
).toEqual(["hit_1", "hit_2"]);
const manyAliases = [
"m0",
"m1",
"hit_a",
"m2",
"m3",
"hit_b",
"hit_a",
"m4",
"m5",
"primary",
"hit_c",
];
expect(
matchProcedureNames({ value: "primary" }, manyAliases, matches),
).toEqual({
value: "primary",
matched_aliases: ["hit_a", "hit_b", "hit_c"],
});
});
+51 -10
View File
@@ -18,6 +18,7 @@ export const literalSubstringPredicate = (
pattern: string,
caseSensitive: boolean,
): ((value: string) => boolean) => {
if (pattern.length === 0) return () => true;
if (caseSensitive) return (value) => value.includes(pattern);
const escaped = pattern.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
const regex = new RegExp(escaped, "iu");
@@ -33,6 +34,7 @@ export const analysisSearchPredicate = (
query: AnalysisSearchQuery,
): ((value: string) => boolean) => {
if (query.mode === "regex") {
if (query.pattern.length === 0) return () => true;
let regex: RegExp;
try {
regex = new RegExp(query.pattern, query.case_sensitive ? "u" : "iu");
@@ -44,6 +46,53 @@ export const analysisSearchPredicate = (
return literalSubstringPredicate(query.pattern, query.case_sensitive);
};
/**
* Distinct matching secondary names in provider order, or undefined when none
* match. Avoids Set and array allocations on the common miss path.
*/
export const matchedProcedureAliases = (
primaryName: string,
aliases: readonly string[],
matches: (value: string) => boolean,
): string[] | undefined => {
if (aliases.length === 0) return undefined;
if (aliases.length === 1) {
const alias = aliases[0]!;
return alias !== primaryName && matches(alias) ? [alias] : undefined;
}
let matched: string[] | undefined;
if (aliases.length <= 8) {
for (let i = 0; i < aliases.length; i += 1) {
const alias = aliases[i]!;
if (alias === primaryName) continue;
let duplicate = false;
for (let j = 0; j < i; j += 1) {
if (aliases[j] === alias) {
duplicate = true;
break;
}
}
if (!duplicate && matches(alias)) {
if (matched === undefined) matched = [alias];
else matched.push(alias);
}
}
return matched;
}
const seen = new Set<string>([primaryName]);
for (let i = 0; i < aliases.length; i += 1) {
const alias = aliases[i]!;
if (!seen.has(alias)) {
seen.add(alias);
if (matches(alias)) {
if (matched === undefined) matched = [alias];
else matched.push(alias);
}
}
}
return matched;
};
/**
* Match one procedure by its primary name and the secondary names its provider
* accepts for exact selection. A procedure remains one row whose value is its
@@ -55,15 +104,7 @@ export const matchProcedureNames = <Row extends { readonly value: string }>(
aliases: readonly string[],
matches: (value: string) => boolean,
): (Row & { readonly matched_aliases?: string[] }) | undefined => {
if (aliases.length === 1) {
const alias = aliases[0]!;
if (alias !== row.value && matches(alias))
return { ...row, matched_aliases: [alias] };
} else if (aliases.length > 1) {
const matched = [...new Set(aliases)].filter(
(alias) => alias !== row.value && matches(alias),
);
if (matched.length > 0) return { ...row, matched_aliases: matched };
}
const matched = matchedProcedureAliases(row.value, aliases, matches);
if (matched !== undefined) return { ...row, matched_aliases: matched };
return matches(row.value) ? row : undefined;
};
+19
View File
@@ -1,5 +1,24 @@
const isLowerHexCode = (code: number): boolean =>
(code >= 48 && code <= 57) || (code >= 97 && code <= 102);
/** Whether `value` is a canonical lowercase u64 hex address (`0x0` or `0x[1-9a-f][0-9a-f]{0,15}`). */
export const isCanonicalKunaHexAddress = (value: unknown): value is string => {
if (typeof value !== "string") return false;
const { length } = value;
if (length < 3 || length > 18) return false;
if (value.charCodeAt(0) !== 48 || value.charCodeAt(1) !== 120) return false;
const first = value.charCodeAt(2);
if (length === 3) return isLowerHexCode(first);
if (first === 48 || !isLowerHexCode(first)) return false;
for (let i = 3; i < length; i += 1) {
if (!isLowerHexCode(value.charCodeAt(i))) return false;
}
return true;
};
/** Normalize a u64 selector without allocating a BigInt for unbounded digits. */
export const normalizeKunaAddress = (value: unknown): string | undefined => {
if (isCanonicalKunaHexAddress(value)) return value;
if (typeof value !== "string") return undefined;
const match = /^0x0*([0-9a-f]{1,16})$/iu.exec(value);
return match?.[1] === undefined
+47
View File
@@ -2,6 +2,7 @@ import { z } from "zod";
import { err, ok, type Result } from "../domain/result.js";
import { decodeStrictUtf8 } from "../domain/strictUtf8.js";
import { isRecord } from "../kernel/isRecord.js";
import { KunaDocumentError } from "./KunaDocumentError.js";
/**
@@ -255,6 +256,25 @@ export interface KunaInventoryFunction {
readonly size: number;
}
const isLowerHexPrefixed = (value: unknown): value is string => {
if (typeof value !== "string" || value.length < 3) return false;
if (value.charCodeAt(0) !== 48 || value.charCodeAt(1) !== 120) return false;
for (let i = 2; i < value.length; i += 1) {
const code = value.charCodeAt(i);
if (!((code >= 48 && code <= 57) || (code >= 97 && code <= 102)))
return false;
}
return true;
};
const isStringArray = (value: unknown): value is readonly string[] => {
if (!Array.isArray(value)) return false;
for (let i = 0; i < value.length; i += 1) {
if (typeof value[i] !== "string") return false;
}
return true;
};
/** Parse the callable-symbol inventory `kuna functions --json` writes. */
export const parseKunaInventory = (
text: string,
@@ -265,6 +285,33 @@ export const parseKunaInventory = (
} catch {
return err("the function inventory is not JSON");
}
if (isRecord(value) && Array.isArray(value.functions)) {
const rawFunctions: unknown[] = value.functions;
const functions: KunaInventoryFunction[] = new Array(rawFunctions.length);
let valid = true;
for (let i = 0; i < rawFunctions.length; i += 1) {
const entry = rawFunctions[i];
if (
!isRecord(entry) ||
typeof entry.name !== "string" ||
!isLowerHexPrefixed(entry.address_hex) ||
!isStringArray(entry.aliases) ||
typeof entry.size !== "number" ||
!Number.isSafeInteger(entry.size) ||
entry.size < 0
) {
valid = false;
break;
}
functions[i] = {
name: entry.name,
address: entry.address_hex,
aliases: entry.aliases,
size: entry.size,
};
}
if (valid) return ok(functions);
}
const parsed = inventorySchema.safeParse(value);
if (!parsed.success)
return err(
+222 -54
View File
@@ -2,11 +2,16 @@ import { z } from "zod";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareKunaAddresses, normalizeKunaAddress } from "./KunaAddress.js";
import {
compareKunaAddresses,
isCanonicalKunaHexAddress,
normalizeKunaAddress,
} from "./KunaAddress.js";
import { KunaDocumentError } from "./KunaDocumentError.js";
import { parseKunaJson } from "./KunaJson.js";
import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js";
import { errorMessage } from "../kernel/errorMessage.js";
import { isRecord } from "../kernel/isRecord.js";
import { sha256Hex } from "../kernel/sha256Hex.js";
/** The raw xref budget also bounds its materialized rows. */
@@ -90,16 +95,84 @@ const GRAPH_DOCUMENT = {
]),
};
interface CallerEdgeState {
readonly targets: Set<string>;
/** Next expected sequential calleeOrder while orders arrive as 0, 1, 2, ... */
sequentialCount: number;
maxOrder: number;
/** Allocated only when calleeOrder arrives out of sequential 0..n-1 order. */
orders: Set<number> | undefined;
}
const isEdgeKind = (value: unknown): value is z.infer<typeof kind> =>
value === "call" ||
value === "jump" ||
value === "data" ||
value === "read" ||
value === "write";
const parseGraphNodeFast = (
fields: Readonly<Record<string, unknown>>,
): KunaGraphNode => {
const {
address: nodeAddress,
name,
kind: nodeKind,
hasIndirectCalls,
forwardsTo,
codeC,
assembly,
error,
} = fields;
if (
isCanonicalKunaHexAddress(nodeAddress) &&
typeof name === "string" &&
name.length >= 1 &&
typeof nodeKind === "string" &&
nodeKind.length >= 1 &&
typeof hasIndirectCalls === "boolean" &&
(forwardsTo === null || isCanonicalKunaHexAddress(forwardsTo)) &&
codeC === null &&
assembly === null &&
error === null
)
return {
address: nodeAddress,
name,
kind: nodeKind,
hasIndirectCalls,
forwardsTo,
codeC: null,
assembly: null,
error: null,
};
return parseKunaRow(graphNode, "graph function", fields);
};
const parseGraphEdgeFast = (
fields: Readonly<Record<string, unknown>>,
): z.infer<typeof graphEdge> => {
const { callerAddress, calleeAddress, kind: edgeKind, calleeOrder } = fields;
if (
isCanonicalKunaHexAddress(callerAddress) &&
isCanonicalKunaHexAddress(calleeAddress) &&
isEdgeKind(edgeKind) &&
typeof calleeOrder === "number" &&
Number.isSafeInteger(calleeOrder) &&
calleeOrder >= 0
)
return fields as unknown as z.infer<typeof graphEdge>;
return parseKunaRow(graphEdge, "graph edge", fields);
};
/**
* Validates `kuna decompile-graph --functions ''` as Kuna writes it and
* retains only the facts call queries use.
*/
export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
readonly #nodes = new Map<string, KunaGraphNode>();
/** Callees of every edge by caller, which also detects repeated edges. */
readonly #targets = new Map<string, Set<string>>();
/** Callee orders by caller; each caller's must be 0..n-1. */
readonly #orders = new Map<string, Set<number>>();
/** Per-caller edge targets and callee orders, cleared once validated. */
readonly #callerEdges = new Map<string, CallerEdgeState>();
readonly #callers = new Map<string, string[]>();
readonly #callees = new Map<string, string[]>();
#edgeCount = 0;
@@ -123,9 +196,8 @@ export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
)
return err(this.unusable("graph counts disagree with examined rows"));
const invalid = this.#invalidEdges();
// These indexes only validate edges; queries never read them.
this.#targets.clear();
this.#orders.clear();
// This index only validates edges; queries never read it.
this.#callerEdges.clear();
if (invalid !== undefined) return err(this.unusable(invalid));
for (const index of [this.#callers, this.#callees])
for (const list of index.values()) list.sort(compareKunaAddresses);
@@ -145,10 +217,10 @@ export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
fields: Readonly<Record<string, unknown>>,
): void {
if (member === "edges") {
this.#index(parseKunaRow(graphEdge, "graph edge", fields));
this.#index(parseGraphEdgeFast(fields));
return;
}
const node = parseKunaRow(graphNode, "graph function", fields);
const node = parseGraphNodeFast(fields);
if (this.#nodes.has(node.address))
throw new KunaDocumentError("repeated_function");
this.#nodes.set(node.address, node);
@@ -158,8 +230,7 @@ export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
protected override discardRows(): void {
for (const index of [
this.#nodes,
this.#targets,
this.#orders,
this.#callerEdges,
this.#callers,
this.#callees,
])
@@ -172,38 +243,73 @@ export class KunaCallGraphReader extends KunaJsonDocumentReader<KunaCallGraph> {
* known.
*/
#index(edge: z.infer<typeof graphEdge>): void {
const { callerAddress: caller, calleeAddress: callee } = edge;
const { callerAddress: caller, calleeAddress: callee, calleeOrder } = edge;
this.#edgeCount += 1;
const targets = this.#targets.get(caller) ?? new Set<string>();
if (targets.has(callee)) throw new KunaDocumentError("repeated_edge");
targets.add(callee);
this.#targets.set(caller, targets);
const order = this.#orders.get(caller) ?? new Set<number>();
if (order.has(edge.calleeOrder))
throw new KunaDocumentError("repeated_callee_order");
order.add(edge.calleeOrder);
this.#orders.set(caller, order);
let state = this.#callerEdges.get(caller);
if (state === undefined) {
state = {
targets: new Set<string>(),
sequentialCount: 0,
maxOrder: -1,
orders: undefined,
};
this.#callerEdges.set(caller, state);
}
if (state.targets.has(callee)) throw new KunaDocumentError("repeated_edge");
state.targets.add(callee);
this.#recordOrder(state, calleeOrder);
if (edge.kind !== "call") return;
const incoming = this.#callers.get(callee) ?? [];
let incoming = this.#callers.get(callee);
if (incoming === undefined) {
incoming = [];
this.#callers.set(callee, incoming);
}
incoming.push(caller);
this.#callers.set(callee, incoming);
const outgoing = this.#callees.get(caller) ?? [];
let outgoing = this.#callees.get(caller);
if (outgoing === undefined) {
outgoing = [];
this.#callees.set(caller, outgoing);
}
outgoing.push(callee);
this.#callees.set(caller, outgoing);
}
#recordOrder(state: CallerEdgeState, calleeOrder: number): void {
if (state.orders === undefined) {
if (calleeOrder === state.sequentialCount) {
state.sequentialCount += 1;
return;
}
if (calleeOrder < state.sequentialCount)
throw new KunaDocumentError("repeated_callee_order");
const orders = new Set<number>();
for (let i = 0; i < state.sequentialCount; i += 1) orders.add(i);
orders.add(calleeOrder);
state.orders = orders;
state.maxOrder = calleeOrder;
return;
}
if (state.orders.has(calleeOrder))
throw new KunaDocumentError("repeated_callee_order");
state.orders.add(calleeOrder);
if (calleeOrder > state.maxOrder) state.maxOrder = calleeOrder;
}
/** Why the edges contradict the nodes, if they do. */
#invalidEdges(): string | undefined {
for (const [caller, targets] of this.#targets) {
let missingOrder = false;
for (const [caller, state] of this.#callerEdges) {
if (!this.#nodes.has(caller)) return "graph edge has an unknown endpoint";
for (const callee of targets)
for (const callee of state.targets)
if (!this.#nodes.has(callee))
return "graph edge has an unknown endpoint";
// Distinct non-negative orders cover 0..n-1 iff maxOrder === size - 1.
if (
state.orders !== undefined &&
state.maxOrder !== state.orders.size - 1
)
missingOrder = true;
}
for (const order of this.#orders.values())
for (let index = 0; index < order.size; index += 1)
if (!order.has(index)) return "graph callee orders are incomplete";
return undefined;
return missingOrder ? "graph callee orders are incomplete" : undefined;
}
}
@@ -298,6 +404,50 @@ export interface KunaIncomingReferenceError {
readonly field?: string;
}
const isValidXrefFunction = (
fn: unknown,
): fn is z.infer<typeof xrefFunction> | null =>
fn === null ||
(isRecord(fn) &&
typeof fn.name === "string" &&
fn.name.length >= 1 &&
isCanonicalKunaHexAddress(fn.address) &&
(fn.address_hex === fn.address ||
isCanonicalKunaHexAddress(fn.address_hex)));
const parseXrefRowFast = (raw: unknown): z.infer<typeof xrefRow> => {
if (isRecord(raw)) {
const {
address: rowAddress,
address_hex: rowAddressHex,
kind: rowKind,
from_address: fromAddress,
from_address_hex: fromAddressHex,
to_address: toAddress,
to_address_hex: toAddressHex,
from_function: fromFunction,
to_function: toFunction,
instruction,
} = raw;
if (
isCanonicalKunaHexAddress(rowAddress) &&
(rowAddressHex === rowAddress ||
isCanonicalKunaHexAddress(rowAddressHex)) &&
(fromAddress === rowAddress || isCanonicalKunaHexAddress(fromAddress)) &&
(fromAddressHex === rowAddress ||
isCanonicalKunaHexAddress(fromAddressHex)) &&
isCanonicalKunaHexAddress(toAddress) &&
(toAddressHex === toAddress || isCanonicalKunaHexAddress(toAddressHex)) &&
isEdgeKind(rowKind) &&
isValidXrefFunction(fromFunction) &&
isValidXrefFunction(toFunction) &&
typeof instruction === "string"
)
return raw as unknown as z.infer<typeof xrefRow>;
}
return xrefRow.parse(raw);
};
/** Native --to unifies forwarding aliases; REA xrefs asks for the exact address. */
export const parseKunaIncomingReferences = (
text: string,
@@ -335,24 +485,35 @@ export const parseKunaIncomingReferences = (
for (const item of document.coverage?.unwalked ?? [])
if (item.address !== item.address_hex)
throw new KunaDocumentError("xref_endpoints");
for (const pointer of document.data_refs ?? []) {
if (
pointer.from_address !== pointer.from_address_hex ||
pointer.to_address !== pointer.to_address_hex
)
throw new KunaDocumentError("xref_endpoints");
if (!aliases.has(pointer.to_address))
throw new KunaDocumentError("xref_target");
}
const addresses = new Set<string>();
let excludedAliasRows = 0;
const arm64DirectCalls: KunaArm64DirectCall[] = [];
for (const pointer of document.data_refs ?? []) {
if (pointer.to_address === target) addresses.add(pointer.from_address);
else excludedAliasRows += 1;
let pointers: Array<
Omit<z.infer<typeof xrefPointer>, "from_address_hex" | "to_address_hex">
> | null = null;
if (document.data_refs !== undefined) {
pointers = new Array(document.data_refs.length);
for (let i = 0; i < document.data_refs.length; i += 1) {
const pointer = document.data_refs[i]!;
if (
pointer.from_address !== pointer.from_address_hex ||
pointer.to_address !== pointer.to_address_hex
)
throw new KunaDocumentError("xref_endpoints");
if (!aliases.has(pointer.to_address))
throw new KunaDocumentError("xref_target");
if (pointer.to_address === target) addresses.add(pointer.from_address);
else excludedAliasRows += 1;
const {
from_address_hex: _from,
to_address_hex: _to,
...kept
} = pointer;
pointers[i] = kept;
}
}
for (const raw of document.xrefs) {
const row = xrefRow.parse(raw);
const row = parseXrefRowFast(raw);
if (
row.address !== row.address_hex ||
row.address !== row.from_address ||
@@ -360,9 +521,13 @@ export const parseKunaIncomingReferences = (
row.to_address !== row.to_address_hex
)
throw new KunaDocumentError("xref_endpoints");
for (const fn of [row.from_function, row.to_function])
if (fn !== null && fn.address !== fn.address_hex)
throw new KunaDocumentError("xref_function_hex");
if (
(row.from_function !== null &&
row.from_function.address !== row.from_function.address_hex) ||
(row.to_function !== null &&
row.to_function.address !== row.to_function.address_hex)
)
throw new KunaDocumentError("xref_function_hex");
if (!aliases.has(row.to_address))
throw new KunaDocumentError("xref_target");
if (row.to_address !== target) {
@@ -375,13 +540,20 @@ export const parseKunaIncomingReferences = (
if (
row.kind !== "call" ||
row.from_function === null ||
row.instruction.length < 4 ||
row.instruction.length > "bl 0x0000000000000000".length
)
continue;
const c0 = row.instruction.charCodeAt(0);
const c1 = row.instruction.charCodeAt(1);
if ((c0 !== 98 && c0 !== 66) || (c1 !== 108 && c1 !== 76)) continue;
const operand = /^bl[ \t]+(0x[0-9a-f]{1,16})$/iu.exec(
row.instruction,
)?.[1];
if (normalizeKunaAddress(operand) === target)
if (
operand !== undefined &&
(operand === target || normalizeKunaAddress(operand) === target)
)
arm64DirectCalls.push({
from_address: row.from_address,
caller_address: row.from_function.address,
@@ -400,11 +572,7 @@ export const parseKunaIncomingReferences = (
})),
walkCoverage: document.coverage ?? null,
pointerCoverage: document.data_refs_coverage ?? null,
pointers:
document.data_refs?.map(
({ from_address_hex: _from, to_address_hex: _to, ...pointer }) =>
pointer,
) ?? null,
pointers,
bytes: Buffer.byteLength(text),
sha256: sha256Hex(text),
});
+79 -21
View File
@@ -40,7 +40,7 @@ import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import {
analysisSearchPredicate,
analysisSearchQuerySchema,
matchProcedureNames,
matchedProcedureAliases,
type AnalysisSearchQuery,
} from "../domain/analysisSearch.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
@@ -167,6 +167,53 @@ interface InventoryIndex {
readonly byName: ReadonlyMap<string, readonly KunaInventoryFunction[]>;
}
const addIndexedName = (
byName: Map<string, KunaInventoryFunction[]>,
name: string,
entry: KunaInventoryFunction,
): void => {
const named = byName.get(name);
if (named === undefined) byName.set(name, [entry]);
else named.push(entry);
};
const indexInventoryEntryNames = (
byName: Map<string, KunaInventoryFunction[]>,
entry: KunaInventoryFunction,
): void => {
addIndexedName(byName, entry.name, entry);
const { aliases } = entry;
if (aliases.length === 0) return;
if (aliases.length === 1) {
const alias = aliases[0]!;
if (alias !== entry.name) addIndexedName(byName, alias, entry);
return;
}
if (aliases.length <= 8) {
for (let i = 0; i < aliases.length; i += 1) {
const alias = aliases[i]!;
if (alias === entry.name) continue;
let duplicate = false;
for (let j = 0; j < i; j += 1) {
if (aliases[j] === alias) {
duplicate = true;
break;
}
}
if (!duplicate) addIndexedName(byName, alias, entry);
}
return;
}
const seen = new Set<string>([entry.name]);
for (let i = 0; i < aliases.length; i += 1) {
const alias = aliases[i]!;
if (!seen.has(alias)) {
seen.add(alias);
addIndexedName(byName, alias, entry);
}
}
};
/**
* One inventory entry a procedure request selected, with its placement and
* the classification caveats every answer about it carries.
@@ -1200,24 +1247,20 @@ export class KunaSessionClient implements AnalysisClient {
if (query !== undefined) {
if (query.mode === "regex") {
// Each distinct spelling is matched once, however many entries share it.
// byName already holds every unique primary name and alias in inventory order.
let names: readonly string[] = [];
const matched = await this.#queryWork.match({
operation,
pattern: query.pattern,
caseSensitive: query.case_sensitive,
values: () =>
(names = [
...new Set(
inventory.flatMap(({ name, aliases }) => [name, ...aliases]),
),
]),
values: () => (names = [...index.value.byName.keys()]),
signal: options.signal,
...regex,
});
if (!matched.ok) return matched;
const accepted = new Set(
matched.value.map((position) => names[position]!),
);
const accepted = new Set<string>();
for (let i = 0; i < matched.value.length; i += 1)
accepted.add(names[matched.value[i]!]!);
matches = (name) => accepted.has(name);
} else matches = analysisSearchPredicate(query);
}
@@ -1231,12 +1274,31 @@ export class KunaSessionClient implements AnalysisClient {
const omitted: KunaDataPlacement[] = [];
let unclassified = 0;
for (const entry of inventory) {
const row = { address: entry.address, value: entry.name };
const selected =
matches === undefined
? row
: matchProcedureNames(row, entry.aliases, matches);
if (selected === undefined) continue;
let selected: {
readonly address: string;
readonly value: string;
readonly matched_aliases?: string[];
};
if (matches === undefined) {
selected = { address: entry.address, value: entry.name };
} else {
const matchedAliases = matchedProcedureAliases(
entry.name,
entry.aliases,
matches,
);
if (matchedAliases !== undefined) {
selected = {
address: entry.address,
value: entry.name,
matched_aliases: matchedAliases,
};
} else if (matches(entry.name)) {
selected = { address: entry.address, value: entry.name };
} else {
continue;
}
}
const placement = data.get(entry);
if (placement !== undefined) {
omitted.push(placement);
@@ -2081,11 +2143,7 @@ export class KunaSessionClient implements AnalysisClient {
const byName = new Map<string, KunaInventoryFunction[]>();
for (const entry of inventory) {
byAddress.set(entry.address, entry);
for (const name of new Set([entry.name, ...entry.aliases])) {
const named = byName.get(name);
if (named === undefined) byName.set(name, [entry]);
else named.push(entry);
}
indexInventoryEntryNames(byName, entry);
}
this.#inventoryIndex = {
inventory,
+94 -34
View File
@@ -3,7 +3,10 @@ import { z } from "zod";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { analysisStringSchema } from "../domain/native/nativeString.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareKunaAddresses } from "./KunaAddress.js";
import {
compareKunaAddresses,
isCanonicalKunaHexAddress,
} from "./KunaAddress.js";
import { KunaDocumentError } from "./KunaDocumentError.js";
import { KunaJsonDocumentReader, parseKunaRow } from "./KunaJsonStream.js";
import { KUNA_STRING_MIN_LENGTH } from "./KunaLimits.js";
@@ -56,31 +59,82 @@ const DOCUMENT = {
]),
} as const;
type StringRow = z.infer<typeof row>;
const parseStringRow = (
fields: Readonly<Record<string, unknown>>,
): StringRow => {
const {
address: rawAddress,
address_hex: rawAddressHex,
text,
length,
byte_length: byteLength,
nul_terminated: nulTerminated,
encoding,
section,
xrefs_count: xrefsCount,
functions,
} = fields;
if (
isCanonicalKunaHexAddress(rawAddress) &&
(rawAddressHex === rawAddress ||
isCanonicalKunaHexAddress(rawAddressHex)) &&
typeof text === "string" &&
typeof length === "number" &&
Number.isSafeInteger(length) &&
length >= 0 &&
typeof byteLength === "number" &&
Number.isSafeInteger(byteLength) &&
byteLength >= 0 &&
typeof nulTerminated === "boolean" &&
(encoding === "ascii" || encoding === "utf8" || encoding === "utf16") &&
(section === null || typeof section === "string") &&
xrefsCount === 0 &&
Array.isArray(functions) &&
functions.length === 0
)
return fields as unknown as StringRow;
return parseKunaRow(row, "string", fields);
};
/** JSON text omits terminators; native lengths describe the encoded source. */
const validateStringFacts = (entry: z.infer<typeof row>): void => {
const validateStringFacts = (entry: StringRow): void => {
const { text, encoding } = entry;
const isAscii = encoding === "ascii";
const isUtf16 = encoding === "utf16";
let characters = 0;
for (const character of entry.text) {
const point = character.codePointAt(0)!;
if (
point === 0 ||
(point >= 0xd800 && point <= 0xdfff) ||
(entry.encoding === "ascii" && point > 0x7f) ||
(entry.encoding === "utf16" && point > 0xff)
)
let utf8Bytes = 0;
for (let i = 0; i < text.length; i += 1) {
const unit = text.charCodeAt(i);
if (unit === 0) throw new KunaDocumentError("encoding_contradicts_text");
if (unit >= 0xd800 && unit <= 0xdfff) {
if (
unit <= 0xdbff &&
i + 1 < text.length &&
text.charCodeAt(i + 1) >= 0xdc00 &&
text.charCodeAt(i + 1) <= 0xdfff
) {
if (isAscii || isUtf16)
throw new KunaDocumentError("encoding_contradicts_text");
i += 1;
characters += 1;
utf8Bytes += 4;
continue;
}
throw new KunaDocumentError("encoding_contradicts_text");
}
if ((isAscii && unit > 0x7f) || (isUtf16 && unit > 0xff))
throw new KunaDocumentError("encoding_contradicts_text");
characters += 1;
utf8Bytes += unit <= 0x7f ? 1 : unit <= 0x7ff ? 2 : 3;
}
const textBytes =
entry.encoding === "utf16"
? entry.text.length * 2
: entry.encoding === "ascii"
? entry.text.length
: Buffer.byteLength(entry.text);
const terminatorBytes = entry.nul_terminated
? entry.encoding === "utf16"
? 2
: 1
: 0;
const textBytes = isUtf16
? text.length * 2
: isAscii
? text.length
: utf8Bytes;
const terminatorBytes = entry.nul_terminated ? (isUtf16 ? 2 : 1) : 0;
if (
characters < KUNA_STRING_MIN_LENGTH ||
entry.length !== characters ||
@@ -121,7 +175,7 @@ export const kunaStringsAtAddress = (
/** Validates `kuna strings --json` row by row as Kuna writes it. */
export class KunaStringInventoryReader extends KunaJsonDocumentReader<KunaStringInventory> {
readonly #items: KunaStringItem[] = [];
readonly #identities = new Set<string>();
readonly #identities = new Map<string, number>();
constructor() {
super("kuna:strings", "Kuna's string inventory", DOCUMENT);
@@ -141,14 +195,18 @@ export class KunaStringInventoryReader extends KunaJsonDocumentReader<KunaString
return err(
this.unusable("string inventory count disagrees with examined rows"),
);
this.#items.sort(
(left, right) =>
compareKunaAddresses(left.address, right.address) ||
(left.string?.encoding ?? "").localeCompare(
right.string?.encoding ?? "",
"en",
),
);
this.#identities.clear();
this.#items.sort((left, right) => {
const addressOrder = compareKunaAddresses(left.address, right.address);
if (addressOrder !== 0) return addressOrder;
const leftEncoding = left.string?.encoding ?? "";
const rightEncoding = right.string?.encoding ?? "";
return leftEncoding < rightEncoding
? -1
: leftEncoding > rightEncoding
? 1
: 0;
});
return ok({
items: this.#items,
sha256: completed.value.sha256,
@@ -161,14 +219,16 @@ export class KunaStringInventoryReader extends KunaJsonDocumentReader<KunaString
_member: string,
fields: Readonly<Record<string, unknown>>,
): void {
const entry = parseKunaRow(row, "string", fields);
const entry = parseStringRow(fields);
validateStringFacts(entry);
if (entry.address !== entry.address_hex)
throw new KunaDocumentError("address_hex_disagrees");
const identity = `${entry.address}:${entry.encoding}`;
if (this.#identities.has(identity))
const encodingMask =
entry.encoding === "ascii" ? 1 : entry.encoding === "utf8" ? 2 : 4;
const seen = this.#identities.get(entry.address) ?? 0;
if ((seen & encodingMask) !== 0)
throw new KunaDocumentError("repeated_identity");
this.#identities.add(identity);
this.#identities.set(entry.address, seen | encodingMask);
this.#items.push({
address: entry.address,
value: entry.text,
+20
View File
@@ -546,3 +546,23 @@ it.each([
});
},
);
it("validates patterns even when the worker has no candidate values", async () => {
const invalid = await matchRegexValues({
operation: "search_procedures",
pattern: "[",
caseSensitive: false,
values: [],
});
expect(invalid).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError", operation: "search_procedures" },
});
const empty = await matchRegexValues({
operation: "search_procedures",
pattern: "^main$",
caseSensitive: false,
values: [],
});
expect(empty).toEqual({ ok: true, value: [] });
});
+68 -41
View File
@@ -5,7 +5,7 @@ import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js";
import { readFileSync } from "node:fs";
import { Worker } from "node:worker_threads";
import { z } from "zod";
import { isRecord } from "../kernel/isRecord.js";
import type {
AnalysisError,
@@ -564,18 +564,48 @@ export const invalidRegexPatternError = (
[{ path: ["pattern"], reason: "invalid_format", message: reason }],
);
const replySchema = z.discriminatedUnion("status", [
z.strictObject({
status: z.literal("matched"),
indices: z.array(z.int().nonnegative()),
}),
z.strictObject({ status: z.literal("invalid_pattern"), reason: z.string() }),
]);
type WorkerReply =
| { readonly kind: "matched"; readonly indices: readonly number[] }
| { readonly kind: "invalid_pattern"; readonly reason: string }
| { readonly kind: "malformed" }
| { readonly kind: "invalid_indices" };
const parseWorkerReply = (
message: unknown,
valueCount: number,
): WorkerReply => {
if (!isRecord(message) || Object.keys(message).length !== 2)
return { kind: "malformed" };
if (message.status === "invalid_pattern") {
if (!Object.hasOwn(message, "reason") || typeof message.reason !== "string")
return { kind: "malformed" };
return { kind: "invalid_pattern", reason: message.reason };
}
if (
message.status !== "matched" ||
!Object.hasOwn(message, "indices") ||
!Array.isArray(message.indices)
)
return { kind: "malformed" };
const indices: unknown[] = message.indices;
let previous = -1;
let outOfOrderOrRange = false;
for (let position = 0; position < indices.length; position += 1) {
const index = indices[position];
if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0)
return { kind: "malformed" };
if (index >= valueCount || index <= previous) outOfOrderOrRange = true;
previous = index;
}
if (outOfOrderOrRange) return { kind: "invalid_indices" };
return { kind: "matched", indices: indices as number[] };
};
// Code is constant; caller patterns and target strings cross only workerData.
// process.getBuiltinModule loads synchronously in both CJS and ESM workers
// without async import overhead or ESM customization hook startup.
const WORKER_SOURCE = String.raw`
(async () => {
const { parentPort, workerData } = await import("node:worker_threads");
const { parentPort, workerData } = process.getBuiltinModule("node:worker_threads");
let expression;
try {
expression = new RegExp(workerData.pattern, workerData.caseSensitive ? "u" : "iu");
@@ -583,12 +613,12 @@ try {
parentPort.postMessage({ status: "invalid_pattern", reason: cause instanceof Error ? cause.message : String(cause) });
}
if (expression !== undefined) {
const { values } = workerData;
const indices = [];
for (const [index, value] of workerData.values.entries())
if (expression.test(value)) indices.push(index);
for (let index = 0, length = values.length; index < length; index += 1)
if (expression.test(values[index])) indices.push(index);
parentPort.postMessage({ status: "matched", indices });
}
})();
`;
export interface RegexConfigurationSnapshot {
@@ -674,36 +704,33 @@ export const matchRegexValues = async (input: {
input.signal?.addEventListener("abort", onAbort, { once: true });
if (input.signal?.aborted) onAbort();
worker.once("message", (message: unknown) => {
const reply = replySchema.safeParse(message);
if (!reply.success)
return finish(
err(
new AnalysisOutputError(
input.operation,
"Regex worker reply is malformed",
const reply = parseWorkerReply(message, input.values.length);
switch (reply.kind) {
case "malformed":
return finish(
err(
new AnalysisOutputError(
input.operation,
"Regex worker reply is malformed",
),
),
),
);
if (reply.data.status === "invalid_pattern")
return finish(
err(invalidRegexPatternError(input.operation, reply.data.reason)),
);
if (
reply.data.indices.some(
(index, position, indices) =>
index >= input.values.length ||
(position > 0 && index <= (indices[position - 1] ?? -1)),
)
)
return finish(
err(
new AnalysisOutputError(
input.operation,
"Regex worker returned invalid inventory indices",
);
case "invalid_pattern":
return finish(
err(invalidRegexPatternError(input.operation, reply.reason)),
);
case "invalid_indices":
return finish(
err(
new AnalysisOutputError(
input.operation,
"Regex worker returned invalid inventory indices",
),
),
),
);
finish(ok(reply.data.indices));
);
case "matched":
return finish(ok(reply.indices));
}
});
worker.once("error", (cause: Error & { code?: string }) =>
finish(
+54
View File
@@ -0,0 +1,54 @@
import { EventEmitter } from "node:events";
import { expect, it, vi } from "vitest";
import { matchRegexValues } from "./RegexMatcher.js";
const { reply } = vi.hoisted(() => ({
reply: { value: undefined as unknown },
}));
vi.mock("node:worker_threads", () => ({
Worker: class extends EventEmitter {
constructor() {
super();
queueMicrotask(() => this.emit("message", reply.value));
}
terminate(): Promise<number> {
return Promise.resolve(0);
}
},
}));
it.each([
[{ status: "invalid_pattern", reason: 42 }, "reply is malformed"],
[
{ status: "invalid_pattern", reason: "invalid", extra: true },
"reply is malformed",
],
[{ status: "matched", wrong: [] }, "reply is malformed"],
[{ status: "matched", indices: [0], extra: true }, "reply is malformed"],
[{ status: "matched", indices: [-1] }, "reply is malformed"],
[{ status: "matched", indices: [0.5] }, "reply is malformed"],
[{ status: "matched", indices: [2, "0"] }, "reply is malformed"],
[{ status: "matched", indices: [2] }, "invalid inventory indices"],
[{ status: "matched", indices: [0, 0] }, "invalid inventory indices"],
[{ status: "matched", indices: [1, 0] }, "invalid inventory indices"],
] as const)(
"rejects a worker reply %j at the matching boundary",
async (message, reason) => {
reply.value = message;
await expect(
matchRegexValues({
operation: "search_procedures",
pattern: "main",
caseSensitive: true,
values: ["main", "domain"],
}),
).resolves.toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
message: expect.stringContaining(reason),
},
});
},
);
@@ -626,3 +626,21 @@ it("keeps Hopper's result projection and invalid-pattern contract with the share
});
await search.close();
});
it("returns ordered matching indices across large batches in the supervised worker", async () => {
const values = Array.from({ length: 2500 }, (_, i) =>
i % 2 === 0 ? `sym_hit_${String(i)}` : `sym_miss_${String(i)}`,
);
const matched = await matchRegexValues({
operation: "search_procedures",
pattern: "^sym_hit_\\d+$",
caseSensitive: true,
values,
});
expect(matched.ok).toBe(true);
if (!matched.ok) return;
expect(matched.value.length).toBe(1250);
expect(matched.value[0]).toBe(0);
expect(matched.value[1]).toBe(2);
expect(matched.value.at(-1)).toBe(2498);
});
@@ -293,3 +293,47 @@ test("reports lookup failures with recovery for the selected target, not the inp
expect(missingAddress.message).toContain("no inventory entry named");
expect(missingAddress.remediation.action).toContain("address");
});
test("indexes and searches procedures with more than eight aliases and repeated spellings", async ({
mcp,
}) => {
const { search } = await aliasSession(mcp, "rea-kuna-many-aliases-", {
functions: [
{
name: "many_primary",
addr: "0x1000",
aliases: [
"alias_0",
"alias_1",
"many_primary",
"alias_2",
"alias_3",
"alias_1",
"alias_4",
"alias_5",
"alias_6",
"alias_7",
"alias_hit",
"alias_hit",
],
},
{ name: "other_fn", addr: "0x1040", aliases: ["only_other"] },
],
});
expect(
await search({
pattern: "^alias_hit$",
mode: "regex",
case_sensitive: true,
}),
).toEqual([
{
address: "0x1000",
value: "many_primary",
matched_aliases: ["alias_hit"],
},
]);
expect(await search({ pattern: "other_fn", mode: "regex" })).toEqual([
{ address: "0x1040", value: "other_fn" },
]);
});
@@ -247,6 +247,47 @@ it.each([
},
);
it("preserves parseKunaInventory fast-path acceptance and Zod error fallback", () => {
expect(
parseKunaInventory(
JSON.stringify({
functions: [
{
name: "zero_padded",
address_hex: "0x0010",
aliases: ["a0", "a1"],
size: 0,
extra: true,
},
],
}),
),
).toEqual({
ok: true,
value: [
{
name: "zero_padded",
address: "0x0010",
aliases: ["a0", "a1"],
size: 0,
},
],
});
for (const invalid of [
{ functions: [{ name: "x", address_hex: "0xABC", aliases: [], size: 0 }] },
{ functions: [{ name: "x", address_hex: "0x10", aliases: [7], size: 0 }] },
{ functions: [{ name: "x", address_hex: "0x10", aliases: [], size: -1 }] },
{ functions: "not-an-array" },
]) {
expect(parseKunaInventory(JSON.stringify(invalid))).toMatchObject({
ok: false,
error: expect.stringContaining(
"the function inventory does not match Kuna's document:",
),
});
}
});
describe("Kuna streaming line-scanner chunk boundary parity", () => {
it("handles empty lines, overlong skipped lines, cross-chunk kept lines, and unterminated EOF lines across chunk sizes", async () => {
const padding = "x".repeat(70_000);
@@ -563,3 +563,60 @@ it("bounds u64 input parsing before BigInt allocation", () => {
expect(normalizeKunaAddress("0x10000000000000000")).toBeUndefined();
expect(normalizeKunaAddress("caller")).toBeUndefined();
});
it("accepts out-of-order calleeOrder sequences and rejects gaps or fast-path row fallback errors", async () => {
const reordered = graph();
reordered.edges[0]!.calleeOrder = 1;
reordered.edges[1]!.calleeOrder = 0;
expect(await parseKunaCallGraph(wire(reordered), input)).toMatchObject({
ok: true,
value: { edgeCount: 2 },
});
const gapped = graph();
gapped.edges[0]!.calleeOrder = 2;
gapped.edges[1]!.calleeOrder = 0;
expect(await parseKunaCallGraph(wire(gapped), input)).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
reason: "graph callee orders are incomplete",
},
});
const badEdge = graph();
badEdge.edges[0]!.kind = "invalid";
expect(await parseKunaCallGraph(wire(badEdge), input)).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
diagnostics: { code: "row_field", member: "graph edge", field: "kind" },
},
});
});
it("keeps arm64 direct BL normalization while skipping non-BL instructions and rejecting malformed xref rows", () => {
const doc = xrefs();
doc.xrefs[0]!.instruction = "bl\t0X002000";
doc.xrefs[1]!.instruction = "blx 0x2000";
const parsed = parseKunaIncomingReferences(wire(doc), input, "0x2000");
expect(parsed).toMatchObject({
ok: true,
value: {
arm64DirectCalls: [
{
from_address: "0x1004",
caller_address: "0x1000",
to_address: "0x2000",
instruction: "bl\t0X002000",
},
],
},
});
const malformed = xrefs();
malformed.xrefs[0]!.address_hex = "0x01";
expect(parseKunaIncomingReferences(wire(malformed), input, "0x2000")).toEqual(
{
ok: false,
error: { code: expect.any(String) },
},
);
});
@@ -333,7 +333,38 @@ it.each([
{ encoding: "utf8", text: "hello\u0000", length: 6, byte_length: 7 },
{ encoding: "utf8", text: "hello\ud800", length: 6, byte_length: 9 },
{ encoding: "utf16", text: "Δelta", length: 5, byte_length: 12 },
{ encoding: "utf8", text: "\udc00\ud800", length: 2, byte_length: 7 },
{ encoding: "utf8", text: "😀", length: 1, byte_length: 5 },
])("rejects conflicting encoded string facts: %j", async (facts) => {
const value = { ...document(), strings: [{ ...row, ...facts }] };
expect((await read(wire(value))).result.ok).toBe(false);
});
it("preserves encoding_contradicts_text precedence and row_field fallback diagnostics", async () => {
const nulShort = {
...document(),
strings: [{ ...row, text: "\u0000", length: 1, byte_length: 2 }],
};
expect((await read(wire(nulShort))).result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
diagnostics: { code: "encoding_contradicts_text" },
},
});
const badHex = {
...document(),
strings: [{ ...row, address_hex: "0x01" }],
};
expect((await read(wire(badHex))).result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
diagnostics: {
code: "row_field",
member: "string",
field: "address_hex",
},
},
});
});