perf(ida/hopper): push required regex literal candidates to provider bridges (#13438)

* perf(ida/hopper): push required regex literal candidates to provider bridges

* fix(domain): split capped repeat runs and scan groups iteratively

* test(hopper): verify regex candidate requests after CLI exit
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 15:38:01 +00:00
1 parent 1e6880cef7
commit acb714aaf5
10 files changed
+792 -61

No files matched your search

+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, it } from "vitest";
import { literalSubstringPredicate } from "./analysisSearch.js";
import { extractRequiredRegexLiteral } from "./regexLiteralCandidate.js";
const approxPythonCasefold = (value: string): string =>
value
.replace(/\u017f/gu, "s")
.replace(/\u212a/gu, "k")
.replace(/\u00df/gu, "ss")
.replace(/\u0130/gu, "i\u0307")
.toLowerCase();
it("extracts longest contiguous literal segments across valid regex constructs", () => {
expect(extractRequiredRegexLiteral("hello_world", false)).toBe("hello_world");
expect(extractRequiredRegexLiteral("^prefix\\d+suffix$", true)).toBe(
"prefix",
);
expect(extractRequiredRegexLiteral("^a+foobaz\\dbaz$", true)).toBe("afoobaz");
expect(extractRequiredRegexLiteral("(?:foo)bar", true)).toBe("foobar");
expect(extractRequiredRegexLiteral("(?<name>foo)bar", true)).toBe("foobar");
expect(extractRequiredRegexLiteral("pre(a|b)longer_post", true)).toBe(
"longer_post",
);
expect(extractRequiredRegexLiteral("pre(optional)?mid", true)).toBe("pre");
expect(extractRequiredRegexLiteral("pre(abc)+post", true)).toBe("post");
expect(extractRequiredRegexLiteral("x(abc)+y", true)).toBe("abc");
expect(extractRequiredRegexLiteral("xa{2,}y", true)).toBe("xaa");
expect(extractRequiredRegexLiteral("ba{3}c", true)).toBe("baaac");
expect(extractRequiredRegexLiteral(`^ab{64}c$`, true)).toBe(
`a${"b".repeat(64)}c`,
);
expect(extractRequiredRegexLiteral("^ab{65}c$", true)).toBe(
`a${"b".repeat(64)}`,
);
expect(
`a${"b".repeat(65)}c`.includes(
extractRequiredRegexLiteral("^ab{65}c$", true)!,
),
).toBe(true);
expect(extractRequiredRegexLiteral("^xa{65}longer_suffix$", true)).toBe(
`${"a".repeat(64)}longer_suffix`,
);
expect(
extractRequiredRegexLiteral(
`${"(?:".repeat(6000)}foo_deep${")".repeat(6000)}`,
true,
),
).toBe("foo_deep");
expect(extractRequiredRegexLiteral("fooa?", true)).toBe("foo");
expect(extractRequiredRegexLiteral("pre\\(x\\)\\/path", true)).toBe(
"pre(x)/path",
);
expect(
extractRequiredRegexLiteral("\\t\\n\\r\\x41\\u0042\\u{43}", true),
).toBe("\t\n\rABC");
expect(extractRequiredRegexLiteral("pre\\p{Letter}+post_text", false)).toBe(
"post_text",
);
expect(extractRequiredRegexLiteral("(tag)\\1longer", true)).toBe("longer");
expect(extractRequiredRegexLiteral("(?<k>tag)\\k<k>tail", true)).toBe("tail");
});
it("handles anchors, lookarounds, ES2025 inline modifiers, NUL, and astral characters safely", () => {
expect(extractRequiredRegexLiteral("foo(?=bar)baz", true)).toBe("foo");
expect(extractRequiredRegexLiteral("foo(?=bar)bazqux", true)).toBe("bazqux");
expect(extractRequiredRegexLiteral("foo(?<=bar)longer", true)).toBe("longer");
expect(extractRequiredRegexLiteral("foo(?!bar)bazqux", true)).toBe("bazqux");
expect(extractRequiredRegexLiteral("(?i:Foo)BarBaz", true)).toBe("BarBaz");
expect(extractRequiredRegexLiteral("pre(?-i:FOO)longer", false)).toBe(
"longer",
);
expect(extractRequiredRegexLiteral("ab\\0cdef", true)).toBe("cdef");
expect(extractRequiredRegexLiteral("ab\\x00cd", true)).toBe("ab");
expect(extractRequiredRegexLiteral("ab\\u0000cd", true)).toBe("ab");
expect(extractRequiredRegexLiteral("ab\\u{0}cd", true)).toBe("ab");
expect(extractRequiredRegexLiteral("中文🧪ok", true)).toBe("中文🧪ok");
expect(extractRequiredRegexLiteral("pre\\uD83E\\uDDEApost", true)).toBe(
"pre🧪post",
);
expect(extractRequiredRegexLiteral("prefix\\u{1F9EA}?suffix", true)).toBe(
"prefix",
);
expect(extractRequiredRegexLiteral("aβcdef", false)).toBe("cdef");
expect(extractRequiredRegexLiteral("İstorage", false)).toBe("storage");
});
it("returns undefined for alternations, wildcard-only, empty, or invalid regexes", () => {
for (const pattern of [
"",
"[",
"foo|bar",
"a(?:b)|c",
"^[a-z0-9_]+$",
".*",
"(?i:foo)",
"ß",
"(?:foo)?",
"\\d+\\s+\\w+",
]) {
expect(extractRequiredRegexLiteral(pattern, false)).toBeUndefined();
}
expect(extractRequiredRegexLiteral("(?i:foo)", true)).toBeUndefined();
});
it("has zero false negatives against ECMAScript /u and /iu plus downstream fold semantics", () => {
const patterns = [
"^warfare/.+/read-write$",
"a+b(c|d)ef+",
"pre[\\]\\[x]+suf",
"foo(?:bar(baz))+end",
"xa{2,4}y",
"ba{3}?c",
"pre(?i:foo)post",
"pre(?=xy)mid(?<=ab)end",
"\\uD83E\\uDDEA-item",
"a\\0b+cdef",
"kelvin",
"storage",
"pre(a|b|c)mid(x)?post",
];
const corpus = [
"Warfare/Storage/Read-Write",
"warfare/\u017ftoragE/read-write",
"\u212aelvin",
"KELVIN",
"ß",
"İstorage",
"aaabcdEF",
"pre[]xSUF",
"fooBarBazBazEnd",
"prefooPOST",
"ab🧪-item",
"xaAAy",
"baaaac",
"a\0bbbCDEF",
"preamidxpost",
"prexymidabend",
];
for (const pattern of patterns) {
for (const caseSensitive of [false, true]) {
const regex = new RegExp(pattern, caseSensitive ? "u" : "iu");
const literal = extractRequiredRegexLiteral(pattern, caseSensitive);
const matchesLiteral =
literal === undefined
? undefined
: literalSubstringPredicate(literal, caseSensitive);
for (const value of corpus) {
if (!regex.test(value) || literal === undefined) continue;
if (caseSensitive) {
expect(value.includes(literal)).toBe(true);
expect(matchesLiteral?.(value)).toBe(true);
} else {
expect(matchesLiteral?.(value)).toBe(true);
expect(
approxPythonCasefold(value).includes(approxPythonCasefold(literal)),
).toBe(true);
}
}
}
}
});
+404
View File
@@ -0,0 +1,404 @@
const MAX_QUANTIFIED_REPEAT = 64;
const SYNTAX_ESCAPES = new Set([
"^",
"$",
"\\",
".",
"*",
"+",
"?",
"(",
")",
"[",
"]",
"{",
"}",
"|",
"/",
]);
const CONTROL_ESCAPES: Readonly<Record<string, number>> = {
t: 0x09,
n: 0x0a,
v: 0x0b,
f: 0x0c,
r: 0x0d,
};
interface Quantifier {
readonly min: number;
readonly max: number;
readonly nextIndex: number;
}
interface GroupIndex {
readonly groupEnd: Int32Array;
readonly groupHasAlt: Uint8Array;
readonly topLevelHasAlt: boolean;
}
interface GroupFrame {
readonly bodyEnd: number;
readonly afterGroupIndex: number;
readonly inline: boolean;
}
const isHexDigit = (code: number): boolean =>
(code >= 0x30 && code <= 0x39) ||
(code >= 0x41 && code <= 0x46) ||
(code >= 0x61 && code <= 0x66);
const isEligibleCodePoint = (
codePoint: number,
caseSensitive: boolean,
): boolean => {
// Never emit NUL across C/Python/Java string boundaries.
if (codePoint <= 0) return false;
// For case-insensitive pushdown, only ASCII characters are safe across both
// IDA's ASCII+U+017F/U+212A regex folding and Python's str.casefold().
if (!caseSensitive) return codePoint <= 0x7f;
return codePoint < 0xd800 || codePoint > 0xdfff;
};
const skipCharClass = (pattern: string, start: number, end: number): number => {
let index = start;
while (index < end) {
const ch = pattern[index];
if (ch === "\\") {
index += 2;
continue;
}
if (ch === "]") return index + 1;
index += 1;
}
return end;
};
const analyzeRegexGroups = (pattern: string): GroupIndex => {
const length = pattern.length;
const groupEnd = new Int32Array(length).fill(-1);
const groupHasAlt = new Uint8Array(length);
const stack: number[] = [];
let index = 0;
while (index < length) {
const ch = pattern[index];
if (ch === "\\") {
index += 2;
continue;
}
if (ch === "[") {
index = skipCharClass(pattern, index + 1, length);
continue;
}
if (ch === "(") {
stack.push(index);
index += 1;
continue;
}
if (ch === "|") {
const top = stack.at(-1);
if (top === undefined) {
return { groupEnd, groupHasAlt, topLevelHasAlt: true };
}
groupHasAlt[top] = 1;
index += 1;
continue;
}
if (ch === ")") {
const open = stack.pop();
if (open !== undefined) groupEnd[open] = index;
index += 1;
continue;
}
index += 1;
}
return { groupEnd, groupHasAlt, topLevelHasAlt: false };
};
const consumeLazyModifier = (
pattern: string,
index: number,
end: number,
): number => (index < end && pattern[index] === "?" ? index + 1 : index);
const parseQuantifier = (
pattern: string,
start: number,
end: number,
): Quantifier => {
if (start >= end) return { min: 1, max: 1, nextIndex: start };
const ch = pattern[start];
if (ch === "?") {
return {
min: 0,
max: 1,
nextIndex: consumeLazyModifier(pattern, start + 1, end),
};
}
if (ch === "*") {
return {
min: 0,
max: Infinity,
nextIndex: consumeLazyModifier(pattern, start + 1, end),
};
}
if (ch === "+") {
return {
min: 1,
max: Infinity,
nextIndex: consumeLazyModifier(pattern, start + 1, end),
};
}
if (ch === "{") {
const match = /^\{(\d+)(?:,(\d*))?\}/u.exec(pattern.slice(start, end));
if (match !== null) {
const min = Number(match[1]);
const max =
match[2] === undefined
? min
: match[2] === ""
? Infinity
: Number(match[2]);
return {
min,
max,
nextIndex: consumeLazyModifier(pattern, start + match[0].length, end),
};
}
}
return { min: 1, max: 1, nextIndex: start };
};
const parseHex4 = (
pattern: string,
start: number,
end: number,
): number | undefined => {
if (start + 4 > end) return undefined;
for (let offset = 0; offset < 4; offset += 1) {
if (!isHexDigit(pattern.charCodeAt(start + offset))) return undefined;
}
return Number.parseInt(pattern.slice(start, start + 4), 16);
};
const parseEscape = (
pattern: string,
start: number,
end: number,
): { readonly codePoint: number | undefined; readonly nextIndex: number } => {
const next = pattern[start + 1];
if (next === undefined) return { codePoint: undefined, nextIndex: end };
if (SYNTAX_ESCAPES.has(next))
return { codePoint: next.codePointAt(0), nextIndex: start + 2 };
const control = CONTROL_ESCAPES[next];
if (control !== undefined)
return { codePoint: control, nextIndex: start + 2 };
if (next === "x" && start + 4 <= end) {
const hi = pattern.charCodeAt(start + 2);
const lo = pattern.charCodeAt(start + 3);
if (isHexDigit(hi) && isHexDigit(lo)) {
return {
codePoint: Number.parseInt(pattern.slice(start + 2, start + 4), 16),
nextIndex: start + 4,
};
}
}
if (next === "u") {
if (pattern[start + 2] === "{") {
const close = pattern.indexOf("}", start + 3);
if (close !== -1 && close < end) {
return {
codePoint: Number.parseInt(pattern.slice(start + 3, close), 16),
nextIndex: close + 1,
};
}
}
const first = parseHex4(pattern, start + 2, end);
if (first !== undefined) {
if (
first >= 0xd800 &&
first <= 0xdbff &&
pattern[start + 6] === "\\" &&
pattern[start + 7] === "u"
) {
const second = parseHex4(pattern, start + 8, end);
if (second !== undefined && second >= 0xdc00 && second <= 0xdfff) {
return {
codePoint: ((first - 0xd800) << 10) + (second - 0xdc00) + 0x10000,
nextIndex: start + 12,
};
}
}
return { codePoint: first, nextIndex: start + 6 };
}
}
if ((next === "p" || next === "P") && pattern[start + 2] === "{") {
const close = pattern.indexOf("}", start + 3);
if (close !== -1 && close < end)
return { codePoint: undefined, nextIndex: close + 1 };
}
if (next === "k" && pattern[start + 2] === "<") {
const close = pattern.indexOf(">", start + 3);
if (close !== -1 && close < end)
return { codePoint: undefined, nextIndex: close + 1 };
}
if (next >= "1" && next <= "9") {
let cursor = start + 2;
while (cursor < end && pattern[cursor]! >= "0" && pattern[cursor]! <= "9")
cursor += 1;
return { codePoint: undefined, nextIndex: cursor };
}
if (next === "c" && start + 3 <= end)
return { codePoint: undefined, nextIndex: start + 3 };
return { codePoint: undefined, nextIndex: start + 2 };
};
const parseGroupHeader = (
pattern: string,
openIndex: number,
end: number,
): { readonly bodyStart: number; readonly extractable: boolean } => {
const afterOpen = openIndex + 1;
if (pattern[afterOpen] !== "?")
return { bodyStart: afterOpen, extractable: true };
if (pattern[afterOpen + 1] === ":")
return { bodyStart: afterOpen + 2, extractable: true };
if (pattern[afterOpen + 1] === "<") {
const kind = pattern[afterOpen + 2];
if (kind === "=" || kind === "!")
return { bodyStart: afterOpen + 3, extractable: false };
const close = pattern.indexOf(">", afterOpen + 2);
if (close !== -1 && close < end)
return { bodyStart: close + 1, extractable: true };
}
// Lookaheads (?=...), (?!...) and ES2025 inline modifiers (?i:...).
return { bodyStart: afterOpen + 1, extractable: false };
};
const collectRequiredRuns = (
pattern: string,
groups: GroupIndex,
caseSensitive: boolean,
): readonly string[] => {
const runs: string[] = [];
const frames: GroupFrame[] = [];
let current = "";
const flush = (): void => {
if (current.length > 0) {
runs.push(current);
current = "";
}
};
let index = 0;
while (true) {
const top = frames.at(-1);
const limit = top === undefined ? pattern.length : top.bodyEnd;
if (index >= limit) {
if (top === undefined) break;
frames.pop();
if (!top.inline) flush();
index = top.afterGroupIndex;
continue;
}
const ch = pattern[index]!;
if (ch === "^" || ch === "$" || ch === ".") {
flush();
index = parseQuantifier(pattern, index + 1, limit).nextIndex;
continue;
}
if (ch === "[") {
flush();
const classEnd = skipCharClass(pattern, index + 1, limit);
index = parseQuantifier(pattern, classEnd, limit).nextIndex;
continue;
}
if (ch === "(") {
const bodyEnd = groups.groupEnd[index]!;
const { bodyStart, extractable } = parseGroupHeader(
pattern,
index,
bodyEnd,
);
const quantifier = parseQuantifier(pattern, bodyEnd + 1, limit);
if (
!extractable ||
groups.groupHasAlt[index] === 1 ||
quantifier.min === 0
) {
flush();
index = quantifier.nextIndex;
continue;
}
const inline = quantifier.min === 1 && quantifier.max === 1;
if (!inline) flush();
frames.push({ bodyEnd, afterGroupIndex: quantifier.nextIndex, inline });
index = bodyStart;
continue;
}
let codePoint: number | undefined;
let atomEnd: number;
if (ch === "\\") {
const escaped = parseEscape(pattern, index, limit);
codePoint = escaped.codePoint;
atomEnd = escaped.nextIndex;
} else {
codePoint = pattern.codePointAt(index)!;
atomEnd = index + (codePoint > 0xffff ? 2 : 1);
}
const quantifier = parseQuantifier(pattern, atomEnd, limit);
index = quantifier.nextIndex;
if (
codePoint === undefined ||
!isEligibleCodePoint(codePoint, caseSensitive) ||
quantifier.min === 0
) {
flush();
continue;
}
const literal = String.fromCodePoint(codePoint);
if (quantifier.min === 1 && quantifier.max === 1) {
current += literal;
} else if (
quantifier.min === quantifier.max &&
quantifier.min <= MAX_QUANTIFIED_REPEAT
) {
current += literal.repeat(quantifier.min);
} else {
// Break the run whenever characters may vary or repeats exceed the cap so
// prefix and suffix are never joined across omitted characters.
const capped = literal.repeat(
Math.min(quantifier.min, MAX_QUANTIFIED_REPEAT),
);
runs.push(current + capped);
current = capped;
}
}
flush();
return runs;
};
/**
* Extract the longest contiguous literal substring that every match of a valid
* ECMAScript `/u` (or `/iu`) regular expression is guaranteed to contain, or
* `undefined` when no safe provider-side literal pre-filter can be derived.
*/
export const extractRequiredRegexLiteral = (
pattern: string,
caseSensitive: boolean,
): string | undefined => {
if (pattern.length === 0) return undefined;
try {
new RegExp(pattern, caseSensitive ? "u" : "iu");
} catch {
return undefined;
}
const groups = analyzeRegexGroups(pattern);
if (groups.topLevelHasAlt) return undefined;
let longest = "";
for (const run of collectRequiredRuns(pattern, groups, caseSensitive)) {
if (run.length > longest.length) longest = run;
}
return longest.length > 0 ? longest : undefined;
};
+68 -21
View File
@@ -39,9 +39,34 @@ vi.mock("../process/RegexMatcher.js", async (importOriginal) => {
};
});
it.each(["search_strings", "search_procedures"] as const)(
"preserves selected source metadata through the provider's %s regex boundary",
async (operation) => {
it.each([
{
operation: "search_strings" as const,
pattern: "^matched$",
expectedMethod: "search_strings" as const,
expectedArgs: { pattern: "matched", mode: "literal", case_sensitive: true },
},
{
operation: "search_strings" as const,
pattern: "^(?:matched|absent)$",
expectedMethod: "list_strings" as const,
expectedArgs: {},
},
{
operation: "search_procedures" as const,
pattern: "^matched$",
expectedMethod: "search_procedures" as const,
expectedArgs: { pattern: "matched", mode: "literal", case_sensitive: true },
},
{
operation: "search_procedures" as const,
pattern: "^(?:matched|absent)$",
expectedMethod: "list_procedures" as const,
expectedArgs: {},
},
])(
"preserves selected source metadata through the $operation ($expectedMethod) regex boundary",
async ({ operation, pattern, expectedMethod, expectedArgs }) => {
const config = parseConfig({});
if (!config.ok) throw config.error;
const metadata =
@@ -88,16 +113,15 @@ it.each(["search_strings", "search_procedures"] as const)(
});
try {
const result = await client.execute(operation, {
pattern: "^matched$",
pattern,
mode: "regex",
case_sensitive: true,
});
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result).toEqual([originalSource[1]]);
expect(callTool).toHaveBeenCalledOnce();
expect(callTool.mock.calls[0]?.[0]).toBe(
operation === "search_strings" ? "list_strings" : "list_procedures",
);
expect(callTool.mock.calls[0]?.[0]).toBe(expectedMethod);
expect(callTool.mock.calls[0]?.[1]).toEqual(expectedArgs);
expect(source).toEqual(originalSource);
} finally {
await client.close();
@@ -106,9 +130,14 @@ it.each(["search_strings", "search_procedures"] as const)(
},
);
it.each(["search_strings", "search_procedures"] as const)(
"rejects malformed canonical metadata in the %s inventory",
async (operation) => {
it.each([
{ operation: "search_strings" as const, pattern: "matched" },
{ operation: "search_strings" as const, pattern: "^[a-z]+$" },
{ operation: "search_procedures" as const, pattern: "matched" },
{ operation: "search_procedures" as const, pattern: "^[a-z]+$" },
])(
"rejects malformed canonical metadata in the $operation ($pattern) inventory",
async ({ operation, pattern }) => {
// The client validates each reply against its method contract.
const search = new HopperRegexSearch({
callTool: async (method, _arguments, options) =>
@@ -130,7 +159,7 @@ it.each(["search_strings", "search_procedures"] as const)(
try {
expect(
await search.execute(operation, {
pattern: "matched",
pattern,
mode: "regex",
case_sensitive: true,
}),
@@ -146,16 +175,25 @@ it.each(["search_strings", "search_procedures"] as const)(
it.each(
(["search_strings", "search_procedures"] as const).flatMap((operation) =>
(["remote", "capability", "timeout", "process"] as const).map((family) => ({
operation,
family,
})),
(["remote", "capability", "timeout", "process"] as const).flatMap(
(family) =>
(["pushdown", "fallback"] as const).map((route) => ({
operation,
family,
route,
})),
),
),
)(
"attributes $family inventory failure to accepted $operation with live cleanup",
async ({ operation, family }) => {
"attributes $family $route inventory failure to accepted $operation with live cleanup",
async ({ operation, family, route }) => {
const inventory =
operation === "search_strings" ? "list_strings" : "list_procedures";
route === "pushdown"
? operation
: operation === "search_strings"
? "list_strings"
: "list_procedures";
const pattern = route === "pushdown" ? "fixture" : "fixture|other";
const diagnostics = {
provider_request: { operation: inventory, request_id: 17 },
};
@@ -213,7 +251,7 @@ it.each(
});
try {
const result = await search.execute(operation, {
pattern: "fixture",
pattern,
mode: "regex",
case_sensitive: false,
});
@@ -402,8 +440,12 @@ it("selects sparse matched inventory rows by direct index without altering row i
: "unrelated_entry",
provider_value: `display_${index}`,
}));
const calls: { method: string; args: Record<string, unknown> }[] = [];
const search = new HopperRegexSearch({
callTool: async () => ok(rows),
callTool: async (method, args) => {
calls.push({ method, args });
return ok(rows);
},
});
try {
const matched = await search.execute("search_strings", {
@@ -419,12 +461,17 @@ it("selects sparse matched inventory rows by direct index without altering row i
expect(selected[1]).toBe(rows[127]);
expect(selected[2]).toBe(rows[250]);
}
expect(calls[0]).toEqual({
method: "search_strings",
args: { pattern: "target_hit_", mode: "literal", case_sensitive: true },
});
const empty = await search.execute("search_strings", {
pattern: "^never_matches_anything$",
pattern: "^[0-9]+$",
mode: "regex",
case_sensitive: true,
});
expect(empty).toEqual(ok([]));
expect(calls[1]).toEqual({ method: "list_strings", args: {} });
} finally {
await search.close();
}
+32 -5
View File
@@ -6,6 +6,7 @@ import { cancelledBy, OwnerCancellation } from "../domain/analysisErrorCore.js";
import { HopperRemoteError } from "./HopperErrors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { extractRequiredRegexLiteral } from "../domain/regexLiteralCandidate.js";
import { nativeSearchInput } from "../domain/native/nativeSearch.js";
import type { HopperClient } from "./HopperClient.js";
import {
@@ -28,15 +29,22 @@ const inputSchema = z.strictObject({
mode: z.literal("regex"),
});
/** Match collected native facts off Hopper's API thread, with cancellable lifetime. */
/** The client capability regex search needs: one validated inventory read. */
/** The client capability regex search needs: one validated inventory or literal candidate read. */
export interface HopperInventoryReader {
callTool(
method: "list_strings" | "list_procedures",
method:
| "list_strings"
| "list_procedures"
| "search_strings"
| "search_procedures",
arguments_: Readonly<Record<string, JsonValue>>,
options: Parameters<HopperClient["callTool"]>[2],
): Promise<
Result<
HopperReply<"list_strings"> | HopperReply<"list_procedures">,
| HopperReply<"list_strings">
| HopperReply<"list_procedures">
| HopperReply<"search_strings">
| HopperReply<"search_procedures">,
AnalysisError
>
>;
@@ -119,9 +127,28 @@ export class HopperRegexSearch {
input.data.document === undefined
? {}
: { document: input.data.document };
const candidateLiteral = extractRequiredRegexLiteral(
input.data.pattern,
input.data.case_sensitive,
);
const inventoryMethod =
candidateLiteral !== undefined
? operation
: operation === "search_strings"
? "list_strings"
: "list_procedures";
const inventoryArgs =
candidateLiteral !== undefined
? {
...inventoryArguments,
pattern: candidateLiteral,
mode: "literal",
case_sensitive: input.data.case_sensitive,
}
: inventoryArguments;
const inventory = await this.client.callTool(
operation === "search_strings" ? "list_strings" : "list_procedures",
inventoryArguments,
inventoryMethod,
inventoryArgs,
{ ...inventoryOptions, operation },
);
if (!inventory.ok)
+10 -3
View File
@@ -12,6 +12,7 @@ import {
analysisSearchQuerySchema,
type AnalysisSearchQuery,
} from "../domain/analysisSearch.js";
import { extractRequiredRegexLiteral } from "../domain/regexLiteralCandidate.js";
import {
matchRegexValues,
launchRegexMatchingLimitation,
@@ -596,10 +597,16 @@ export class IdaOperationRunner {
query === undefined && parameters.address !== undefined
? idaAddressSchema.parse(parameters.address)
: undefined;
const candidateLiteral =
query === undefined
? undefined
: query.mode === "literal"
? query.pattern
: extractRequiredRegexLiteral(query.pattern, query.case_sensitive);
const candidatePattern =
query?.mode === "literal"
? idaLiteralSearchPattern(query.pattern, query.case_sensitive)
: undefined;
candidateLiteral === undefined || query === undefined
? undefined
: idaLiteralSearchPattern(candidateLiteral, query.case_sensitive);
const items = await this.strings(candidatePattern);
return query !== undefined
? this.searchItems(operation, items, query)
+26 -1
View File
@@ -2225,8 +2225,33 @@ describe("headless IDA literal string predicate pushdown", () => {
await client.execute("list_strings", {});
expect(lastFindRegexPattern()).toBe("(?s).*");
const regexMatch = await client.execute("search_strings", {
pattern: "^warfare/storage/.+$",
mode: "regex",
});
if (!regexMatch.ok) throw regexMatch.error;
expect(regexMatch.value.result).toEqual([
{ address: "0x5002", value: "Warfare/Storage/Read-Write" },
{ address: "0x5003", value: "warfare/\u017ftoragE/read-write" },
]);
const pushedRegexPattern = lastFindRegexPattern();
expect(pushedRegexPattern).not.toBe("(?s).*");
expect(pushedRegexPattern).toContain("(?:[sS]|\u017f)");
await client.execute("search_strings", {
pattern: "Storage",
pattern: "Storage|Other",
mode: "regex",
});
expect(lastFindRegexPattern()).toBe("(?s).*");
await client.execute("search_strings", {
pattern: "[0-9]+",
mode: "regex",
});
expect(lastFindRegexPattern()).toBe("(?s).*");
await client.execute("search_strings", {
pattern: "İ.*",
mode: "regex",
});
expect(lastFindRegexPattern()).toBe("(?s).*");
@@ -10,13 +10,18 @@ import {
it.each(
(["search_strings", "search_procedures"] as const).flatMap((operation) =>
(["capability_unavailable", "bridge_exception"] as const).map(
(failure) => ({ operation, failure }),
(["capability_unavailable", "bridge_exception"] as const).flatMap(
(failure) =>
(["pushdown", "fallback"] as const).map((route) => ({
operation,
failure,
route,
})),
),
),
)(
"attributes real bridge $failure inventory response to $operation and preserves wire identity",
async ({ operation, failure }) => {
"attributes real bridge $failure $route response to $operation and preserves wire identity",
async ({ operation, failure, route }) => {
const launcher = new HopperFixtureLauncher(
undefined,
"quiet",
@@ -31,18 +36,32 @@ it.each(
const started = await client.start();
if (!started.ok) throw started.error;
const search = new HopperRegexSearch(client);
const pattern = route === "pushdown" ? "fixture" : "fixture|other";
const expectedMethod =
route === "pushdown"
? operation
: operation === "search_strings"
? "list_strings"
: "list_procedures";
const expectedParams =
route === "pushdown"
? {
document: "selected-document",
pattern: "fixture",
mode: "literal",
case_sensitive: false,
}
: { document: "selected-document" };
try {
const result = await search.execute(operation, {
mode: "regex",
pattern: "fixture",
pattern,
case_sensitive: false,
document: "selected-document",
});
if (result.ok) throw new Error("Expected fixture failure");
const inventory =
operation === "search_strings" ? "list_strings" : "list_procedures";
const request = await launcher.waitForRequest(inventory);
expect(request.params).toEqual({ document: "selected-document" });
const request = await launcher.waitForRequest(expectedMethod);
expect(request.params).toEqual(expectedParams);
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe(
failure === "capability_unavailable"
@@ -52,7 +71,7 @@ it.each(
expect(projected.details?.operation).toBe(operation);
expect(result.error.diagnostics).toMatchObject({
provider_request: {
operation: inventory,
operation: expectedMethod,
request_id: request.id,
provider_code: -32000,
diagnostic_type: failure,
@@ -62,7 +81,7 @@ it.each(
expect(projected.message).toContain(operation);
expect(result.error.cause).toBeInstanceOf(HopperRemoteError);
expect(result.error.cause).toMatchObject({
operation: inventory,
operation: expectedMethod,
requestId: request.id,
});
}
@@ -73,9 +92,13 @@ it.each(
},
);
it.each(["search_strings", "search_procedures"] as const)(
"preserves successful %s search and caller-selected document",
async (operation) => {
it.each(
(["search_strings", "search_procedures"] as const).flatMap((operation) =>
(["pushdown", "fallback"] as const).map((route) => ({ operation, route })),
),
)(
"preserves successful $operation ($route) search and caller-selected document",
async ({ operation, route }) => {
const launcher = new HopperFixtureLauncher();
// Production reply contracts: the inventory reply is validated by the client.
const client = trackHopperClient(
@@ -84,11 +107,27 @@ it.each(["search_strings", "search_procedures"] as const)(
const started = await client.start();
if (!started.ok) throw started.error;
const search = new HopperRegexSearch(client);
const pattern = route === "pushdown" ? "fixture" : "fixture|other";
const expectedMethod =
route === "pushdown"
? operation
: operation === "search_strings"
? "list_strings"
: "list_procedures";
const expectedParams =
route === "pushdown"
? {
document: "selected-document",
pattern: "fixture",
mode: "literal",
case_sensitive: false,
}
: { document: "selected-document" };
try {
expect(
await search.execute(operation, {
mode: "regex",
pattern: "fixture",
pattern,
case_sensitive: false,
document: "selected-document",
}),
@@ -96,10 +135,8 @@ it.each(["search_strings", "search_procedures"] as const)(
ok: true,
value: [{ address: "0x1000", value: "fixture" }],
});
const request = await launcher.waitForRequest(
operation === "search_strings" ? "list_strings" : "list_procedures",
);
expect(request.params).toEqual({ document: "selected-document" });
const request = await launcher.waitForRequest(expectedMethod);
expect(request.params).toEqual(expectedParams);
} finally {
await search.close();
expect((await client.close()).ok).toBe(true);
+3 -1
View File
@@ -262,7 +262,9 @@ const server = createServer((socket) => {
} else if (
inventoryFailure !== "none" &&
(request.method === "list_strings" ||
request.method === "list_procedures")
request.method === "list_procedures" ||
request.method === "search_strings" ||
request.method === "search_procedures")
) {
send({
id: request.id,
+14 -2
View File
@@ -90,8 +90,20 @@ export const FAKE_HOPPER_REPLIES = Object.freeze({
native_value_flow: null,
limitations: [],
}),
search_strings: () => [],
search_procedures: () => [],
search_strings: (params = {}) =>
typeof params.pattern === "string" &&
(params.case_sensitive === true
? "fixture".includes(params.pattern)
: "fixture".includes(params.pattern.toLowerCase()))
? [{ address: "0x1000", value: "fixture" }]
: [],
search_procedures: (params = {}) =>
typeof params.pattern === "string" &&
(params.case_sensitive === true
? "fixture".includes(params.pattern)
: "fixture".includes(params.pattern.toLowerCase()))
? [{ address: "0x1000", value: "fixture" }]
: [],
xrefs: () => ["0x1000"],
resolve_containing_procedure: (params = {}) => ({
query_address:
@@ -87,25 +87,39 @@ it
REA_LOG_LEVEL: "silent",
},
);
const operation = `search_${kind}`;
expect(launcher.requests.map(({ method }) => method)).toEqual([
"health",
operation,
"shutdown",
]);
const request = launcher.requests[1];
if (request === undefined)
throw new Error("Missing fixture search request");
expect(request.params).toEqual({
pattern: "fixture",
mode: "literal",
case_sensitive: false,
});
const output: unknown = JSON.parse(run.stdout);
if (mode === "valid") {
expect(process.exitCode ?? run.exitCode, run.stdout).toBe(0);
const evidence = parseEvidence(output);
expect(evidence.operation).toBe(`search_${kind}`);
expect(evidence.operation).toBe(operation);
expect(evidence.normalized_result).toEqual([
{ address: "0x1000", value: "fixture" },
]);
} else {
expect(process.exitCode ?? run.exitCode, run.stdout).toBe(1);
const error = analysisCliErrorEnvelopeSchema.parse(output);
const request = await launcher.waitForRequest(`list_${kind}`);
expect(error.code, run.stdout).toBe(
mode === "capability_unavailable"
? "capability_unavailable"
: "execution_failure",
);
expect(error.details).toMatchObject({
operation: `search_${kind}`,
operation,
diagnostics: {
provider_request: {
operation: request.method,
@@ -116,13 +130,8 @@ it
},
});
if (mode === "bridge_exception")
expect(error.message).toContain(`search_${kind}`);
expect(error.message).toContain(operation);
}
expect(launcher.requests.map(({ method }) => method)).toEqual([
"health",
`list_${kind}`,
"shutdown",
]);
expect(launcher.processes).toHaveLength(1);
const child = launcher.processes[0];
if (child === undefined) throw new Error("Missing fixture process");