From dff9b479ed3228a27bc49037c03ea970123f5a43 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:38:16 -0500 Subject: [PATCH] perf(ida): push literal patterns down to find_regex on all protocols and drop catch-all non-ASCII wildcard (#13291) --- bridge/ida/test_hexrays_queries.py | 35 +++++++++++++ src/ida/IdaNativeProtocol.test.ts | 58 +++++++++++++++++++++ src/ida/IdaNativeProtocol.ts | 26 ---------- src/ida/IdaOperationRunner.ts | 17 +++---- src/ida/IdaProtocolValues.ts | 35 +++++++++++++ src/ida/IdaSessionClient.test.ts | 82 ++++++++++++++++++++++++++++++ 6 files changed, 218 insertions(+), 35 deletions(-) diff --git a/bridge/ida/test_hexrays_queries.py b/bridge/ida/test_hexrays_queries.py index 46478b0044..0e415ed32b 100644 --- a/bridge/ida/test_hexrays_queries.py +++ b/bridge/ida/test_hexrays_queries.py @@ -284,6 +284,41 @@ class BridgeTest(unittest.TestCase): self.assertEqual(survey["segments"], [{"start": "0x1000", "end": "0x3000", "size": "0x2000"}]) self.assertEqual(survey["statistics"], {"total_segments": 1}) + def test_find_regex_matches_pushed_down_unicode_fold_literals(self): + extra = STRINGS + [ + (0x7000, "中文菜单"), + (0x7001, "Warfare/Storage/Read-Write"), + (0x7002, "warfare/\u017ftoragE/read-write"), + (0x7003, "\u212aelvin"), + ] + sys.modules["idautils"].Strings = lambda: [StringItem(ea, text) for ea, text in extra] + storage = self.query( + "find_regex", + { + "pattern": "[wW][aA][rR][fF][aA][rR][eE]/(?:[sS]|\u017f)[tT][oO][rR][aA][gG][eE]/[rR][eE][aA][dD]-[wW][rR][iI][tT][eE]", + "offset": 0, + "limit": 100, + }, + ) + self.assertEqual( + storage, + { + "matches": [ + {"addr": "0x7001", "string": "Warfare/Storage/Read-Write"}, + {"addr": "0x7002", "string": "warfare/\u017ftoragE/read-write"}, + ], + "cursor": {"done": True}, + }, + ) + kelvin = self.query( + "find_regex", + {"pattern": "(?:[kK]|\u212a)[eE][lL][vV][iI][nN]", "offset": 0, "limit": 100}, + ) + self.assertEqual( + kelvin, + {"matches": [{"addr": "0x7003", "string": "\u212aelvin"}], "cursor": {"done": True}}, + ) + if __name__ == "__main__": unittest.main() diff --git a/src/ida/IdaNativeProtocol.test.ts b/src/ida/IdaNativeProtocol.test.ts index c85ae025a6..bf8f72d03a 100644 --- a/src/ida/IdaNativeProtocol.test.ts +++ b/src/ida/IdaNativeProtocol.test.ts @@ -959,3 +959,61 @@ describe("native IDA attached operation admission", () => { await client.close(); }); }); + +describe("native IDA literal candidate precision", () => { + it("excludes unrelated non-ASCII strings while preserving U+017F and U+212A simple folds", async () => { + const { client, producer } = await fixture(); + const values = [ + "中文菜单", + "Настройки", + "İstanbul", + "σ", + "🧪", + "Warfare/Storage/Read-Write", + "warfare/\u017ftoragE/read-write", + "\u212aelvin", + ]; + producer.overrideCall = (name, args) => { + if (name !== "find_regex") return undefined; + const regex = new RegExp( + Buffer.from(String(args.pattern)).toString("latin1"), + "i", + ); + return { + matches: values.flatMap((value, index) => + regex.test(Buffer.from(value).toString("latin1")) + ? [{ addr: `0x${(0x4000 + index).toString(16)}`, string: value }] + : [], + ), + cursor: { done: true }, + }; + }; + try { + const storage = await client.execute("search_strings", { + pattern: "warfare/storage/read-write", + }); + if (!storage.ok) throw storage.error; + expect(storage.value.result).toEqual([ + { address: "0x4005", value: "Warfare/Storage/Read-Write" }, + { address: "0x4006", value: "warfare/\u017ftoragE/read-write" }, + ]); + const storageCall = producer.calls.find( + ({ name }) => name === "find_regex", + ); + expect(storageCall?.args.pattern).not.toContain("\\x80-\\xff"); + const rawMatches = JSON.stringify(storage.value.rawResult); + expect(rawMatches).not.toContain("中文菜单"); + expect(rawMatches).not.toContain("İstanbul"); + + const kelvin = await client.execute("search_strings", { + pattern: "kelvin", + }); + if (!kelvin.ok) throw kelvin.error; + expect(kelvin.value.result).toEqual([ + { address: "0x4007", value: "\u212aelvin" }, + ]); + } finally { + await client.close(); + } + }); +}); diff --git a/src/ida/IdaNativeProtocol.ts b/src/ida/IdaNativeProtocol.ts index 1c0f91c4a0..4ae37b2bfb 100644 --- a/src/ida/IdaNativeProtocol.ts +++ b/src/ida/IdaNativeProtocol.ts @@ -82,32 +82,6 @@ export const nativeXrefsSchema = z .array(modernXrefsSchema.element.extend({ error: nativeErrorSchema })) .length(1); -/** - * Native regexes fold bytes, while REA's insensitive literal search uses - * ECMAScript Unicode simple case folding. Non-ASCII patterns can match ASCII - * values (for example long s matches S), so leave those queries unfiltered. - * For ASCII patterns include every non-ASCII value, then apply REA's predicate. - * Ill-formed UTF-16 cannot cross upstream JSON/UTF-8. - */ -export const nativeLiteralSearchPattern = ( - pattern: string, - caseSensitive: boolean, -): string | undefined => { - if (/[\uD800-\uDFFF]/u.test(pattern)) return undefined; - if (!caseSensitive && /[\u0080-\u{10ffff}]/u.test(pattern)) return undefined; - let literal = (caseSensitive ? pattern : pattern.toLowerCase()).replace( - /[.*+?^${}()|[\]\\]/gu, - "\\$&", - ); - // Spell ASCII variants explicitly rather than depending on an upstream locale. - if (!caseSensitive) - literal = literal.replace( - /[a-z]/gu, - (char) => `[${char}${char.toUpperCase()}]`, - ); - return caseSensitive ? literal : `(?:${literal})|[\\x80-\\xff]`; -}; - /** Read-only tools required from the native bridge; GUI lifecycle tools are excluded. */ export const nativeTools = [ "list_funcs", diff --git a/src/ida/IdaOperationRunner.ts b/src/ida/IdaOperationRunner.ts index 786e940f74..05ab7a05dc 100644 --- a/src/ida/IdaOperationRunner.ts +++ b/src/ida/IdaOperationRunner.ts @@ -6,7 +6,6 @@ import { nativeDisassemblySchema, nativeCalleesSchema, nativeXrefsSchema, - nativeLiteralSearchPattern, } from "./IdaNativeProtocol.js"; import { analysisSearchPredicate, @@ -44,6 +43,7 @@ import type { EvidenceLocation } from "../domain/evidence.js"; import { idaAddressSchema, idaFunctionSchema, + idaLiteralSearchPattern, idaStringsPageSchema, modernCalleesSchema, modernDecompileSchema, @@ -311,7 +311,7 @@ export class IdaOperationRunner { } async strings( - nativePattern?: string, + candidatePattern?: string, ): Promise<{ address: string; value: string }[]> { if (this.protocol === "native") this.limitations.push(IDA_NATIVE_STRING_LIMITATION); @@ -322,9 +322,8 @@ export class IdaOperationRunner { const page = idaStringsPageSchema.parse( await this.call("find_regex", { pattern: - this.protocol === "native" - ? (nativePattern ?? "[\\s\\S]*") - : "(?s).*", + candidatePattern ?? + (this.protocol === "native" ? "[\\s\\S]*" : "(?s).*"), offset, limit: 100, }), @@ -590,11 +589,11 @@ export class IdaOperationRunner { query === undefined && parameters.address !== undefined ? idaAddressSchema.parse(parameters.address) : undefined; - const nativePattern = - this.protocol === "native" && query?.mode === "literal" - ? nativeLiteralSearchPattern(query.pattern, query.case_sensitive) + const candidatePattern = + query?.mode === "literal" + ? idaLiteralSearchPattern(query.pattern, query.case_sensitive) : undefined; - const items = await this.strings(nativePattern); + const items = await this.strings(candidatePattern); return query !== undefined ? this.searchItems(operation, items, query) : selectedAddress === undefined diff --git a/src/ida/IdaProtocolValues.ts b/src/ida/IdaProtocolValues.ts index 92d5c95584..7e3a538891 100644 --- a/src/ida/IdaProtocolValues.ts +++ b/src/ida/IdaProtocolValues.ts @@ -298,3 +298,38 @@ export const surveySegmentsSchema = z }); } }); + +/** + * Translate a `search_strings` literal query into a candidate regex for upstream + * `find_regex` across all IDA protocols (`modern`, `hexrays`, and `native`) + * while keeping REA's ECMAScript Unicode simple case folding as the final filter. + * + * Across all 1,114,112 Unicode code points, only U+017F (`ſ` ↔ `s`/`S`) and + * U+212A (`K` ↔ `k`/`K`) fold to ASCII under `/iu`. Spelling them inline as + * `(?:[sS]|\u017f)` and `(?:[kK]|\u212a)` matches both Unicode regex engines + * (Python `re`) and UTF-8-as-bytes matchers (`ida-free-mcp`) without a catch-all + * wildcard that forces every non-ASCII string across paginated RPCs. + * + * Returns `undefined` when ill-formed UTF-16 surrogates or non-ASCII + * case-insensitive characters require unfiltered enumeration. + */ +export const idaLiteralSearchPattern = ( + pattern: string, + caseSensitive: boolean, +): string | undefined => { + if (/[\uD800-\uDFFF]/u.test(pattern)) return undefined; + if (!caseSensitive && /[\u0080-\u{10ffff}]/u.test(pattern)) return undefined; + let literal = (caseSensitive ? pattern : pattern.toLowerCase()).replace( + /[.*+?^${}()|[\]\\]/gu, + "\\$&", + ); + // Spell ASCII variants (plus U+017F/U+212A simple folds) explicitly rather + // than depending on upstream regex case flags or locale rules. + if (!caseSensitive) + literal = literal.replace(/[a-z]/gu, (char) => { + if (char === "s") return "(?:[sS]|\u017f)"; + if (char === "k") return "(?:[kK]|\u212a)"; + return `[${char}${char.toUpperCase()}]`; + }); + return literal; +}; diff --git a/src/ida/IdaSessionClient.test.ts b/src/ida/IdaSessionClient.test.ts index 7a48e9bf31..083cb14574 100644 --- a/src/ida/IdaSessionClient.test.ts +++ b/src/ida/IdaSessionClient.test.ts @@ -2159,3 +2159,85 @@ it("keeps the session cleanup owner until an ignored-abort HTTP acquisition and vi.unstubAllGlobals(); } }); + +describe("headless IDA literal string predicate pushdown", () => { + it("pushes ASCII literal patterns with U+017F/U+212A folds to modern find_regex while keeping regex and non-ASCII fallback intact", async () => { + const { producer, client } = await fixture("headless"); + const values = [ + "中文菜单", + "other", + "Warfare/Storage/Read-Write", + "warfare/\u017ftoragE/read-write", + "\u212aelvin", + "İstanbul", + "🧪", + ]; + producer.overrideCall = (name, args) => { + if (name !== "find_regex") return undefined; + const pattern = String(args.pattern); + const regex = pattern.startsWith("(?s)") + ? new RegExp(pattern.slice(4), "su") + : new RegExp(pattern, "u"); + return { + matches: values.flatMap((value, index) => + regex.test(value) + ? [{ addr: `0x${(0x5000 + index).toString(16)}`, string: value }] + : [], + ), + cursor: { done: true }, + }; + }; + try { + const lastFindRegexPattern = () => + String( + producer.calls.filter(({ name }) => name === "find_regex").at(-1) + ?.args.pattern ?? "", + ); + + const storage = await client.execute("search_strings", { + pattern: "warfare/storage/read-write", + }); + if (!storage.ok) throw storage.error; + expect(storage.value.result).toEqual([ + { address: "0x5002", value: "Warfare/Storage/Read-Write" }, + { address: "0x5003", value: "warfare/\u017ftoragE/read-write" }, + ]); + const storagePattern = lastFindRegexPattern(); + expect(storagePattern).not.toBe("(?s).*"); + expect(storagePattern).toContain("(?:[sS]|\u017f)"); + + const emoji = await client.execute("search_strings", { + pattern: "🧪", + case_sensitive: true, + }); + if (!emoji.ok) throw emoji.error; + expect(emoji.value.result).toEqual([{ address: "0x5006", value: "🧪" }]); + expect(lastFindRegexPattern()).toBe("🧪"); + + const kelvin = await client.execute("search_strings", { + pattern: "kelvin", + }); + if (!kelvin.ok) throw kelvin.error; + expect(kelvin.value.result).toEqual([ + { address: "0x5004", value: "\u212aelvin" }, + ]); + + await client.execute("list_strings", {}); + expect(lastFindRegexPattern()).toBe("(?s).*"); + + await client.execute("search_strings", { + pattern: "Storage", + mode: "regex", + }); + expect(lastFindRegexPattern()).toBe("(?s).*"); + + const sigma = await client.execute("search_strings", { + pattern: "İ", + }); + if (!sigma.ok) throw sigma.error; + expect(lastFindRegexPattern()).toBe("(?s).*"); + } finally { + await client.close(); + } + }); +});