perf(ghidra): push longest ASCII-foldable substring into bridge for non-ASCII case-insensitive literal searches (#13485)

* perf(ghidra): push longest ASCII-foldable substring into bridge for non-ASCII case-insensitive literal searches (#13292)

* test(ghidra): exercise mixed literal filtering in the bridge
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 18:17:40 +00:00
1 parent eb1d540075
commit bdfd0a16f5
6 files changed
+175 -70

No files matched your search

+58 -36
View File
@@ -2686,6 +2686,7 @@ public final class ReaGhidraBridge extends HeadlessScript {
private StreamingResult search(JsonObject params, boolean procedureSearch) throws Exception {
Set<String> keys = new HashSet<>(Set.of("pattern", "mode", "case_sensitive", "document"));
if (params.has("literal_ascii_candidate")) keys.add("literal_ascii_candidate");
if (params.has("literal_ascii_substring")) keys.add("literal_ascii_substring");
requireKeys(params, keys);
requireDocument(params);
String expression = requireString(params, "pattern");
@@ -2698,9 +2699,12 @@ public final class ReaGhidraBridge extends HeadlessScript {
if (mode.equals("literal") && !caseSensitive) {
if (!params.has("literal_ascii_candidate"))
throw new RequestFailure("invalid_request", "Insensitive literal search requires an ASCII candidate");
matcher = literalCandidateMatcher(optionalString(params, "literal_ascii_candidate"));
matcher = literalCandidateMatcher(
optionalString(params, "literal_ascii_candidate"),
optionalString(params, "literal_ascii_substring")
);
} else {
if (params.has("literal_ascii_candidate"))
if (params.has("literal_ascii_candidate") || params.has("literal_ascii_substring"))
throw new RequestFailure("invalid_request", "ASCII candidate applies only to insensitive literals");
matcher = mode.equals("literal")
? literalMatcher(expression)
@@ -6083,50 +6087,68 @@ public final class ReaGhidraBridge extends HeadlessScript {
return nonLeafMatcher(value -> value.contains(pattern));
}
// REA's host owns ECMAScript /iu simple case folding. Across all 1,114,112
// Unicode code points, only U+017F (ſ -> s) and U+212A (K -> k) fold to
// ASCII. When asciiPattern is null, the pattern has a non-ASCII char without
// an ASCII fold, so only source strings containing non-ASCII stay eligible.
private static ValueMatcher literalCandidateMatcher(String asciiPattern) {
if (asciiPattern == null) {
return nonLeafMatcher(value -> {
for (int index = 0; index < value.length(); index++) {
if (value.charAt(index) > 127) return true;
}
return false;
});
private static boolean containsNonAscii(String value) {
for (int index = 0; index < value.length(); index++) {
if (value.charAt(index) > 127) return true;
}
int patternLength = asciiPattern.length();
for (int index = 0; index < patternLength; index++) {
return false;
}
private static void requireAsciiCandidate(String asciiPattern) {
for (int index = 0; index < asciiPattern.length(); index++) {
if (asciiPattern.charAt(index) > 127) {
throw new RequestFailure("invalid_request", "ASCII candidate contains a non-ASCII character");
}
}
}
private static boolean containsFoldedAscii(String value, String asciiPattern) {
int patternLength = asciiPattern.length();
if (patternLength == 0) {
return nonLeafMatcher(value -> true);
return true;
}
int valueLength = value.length();
if (valueLength < patternLength) {
return false;
}
char firstTarget = asciiPattern.charAt(0);
return nonLeafMatcher(value -> {
int valueLength = value.length();
if (valueLength < patternLength) {
return false;
int limit = valueLength - patternLength;
for (int index = 0; index <= limit; index++) {
if (foldAsciiCandidateChar(value.charAt(index)) != firstTarget) {
continue;
}
int limit = valueLength - patternLength;
for (int index = 0; index <= limit; index++) {
if (foldAsciiCandidateChar(value.charAt(index)) != firstTarget) {
continue;
}
int matched = 1;
while (matched < patternLength &&
foldAsciiCandidateChar(value.charAt(index + matched)) == asciiPattern.charAt(matched)) {
matched++;
}
if (matched == patternLength) {
return true;
}
int matched = 1;
while (matched < patternLength &&
foldAsciiCandidateChar(value.charAt(index + matched)) == asciiPattern.charAt(matched)) {
matched++;
}
return false;
});
if (matched == patternLength) {
return true;
}
}
return false;
}
// REA's host owns ECMAScript /iu simple case folding. Across all 1,114,112
// Unicode code points, only U+017F (ſ -> s) and U+212A (K -> k) fold to
// ASCII. When asciiPattern is null, the pattern has a non-ASCII char without
// an ASCII fold, so only source strings containing non-ASCII (and any
// required ASCII-foldable substring) stay eligible.
private static ValueMatcher literalCandidateMatcher(String asciiPattern, String asciiSubstring) {
if (asciiPattern == null) {
if (asciiSubstring == null || asciiSubstring.isEmpty()) {
return nonLeafMatcher(value -> containsNonAscii(value));
}
requireAsciiCandidate(asciiSubstring);
return nonLeafMatcher(value ->
containsFoldedAscii(value, asciiSubstring) && containsNonAscii(value)
);
}
requireAsciiCandidate(asciiPattern);
if (asciiPattern.isEmpty()) {
return nonLeafMatcher(value -> true);
}
return nonLeafMatcher(value -> containsFoldedAscii(value, asciiPattern));
}
private interface StringCheck {
+14 -2
View File
@@ -1,4 +1,7 @@
import { ghidraAsciiLiteralCandidate } from "./GhidraLiteralSearch.js";
import {
ghidraAsciiLiteralCandidate,
ghidraAsciiLiteralSubstring,
} from "./GhidraLiteralSearch.js";
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
import {
fileSnapshotPartialObservationSchema,
@@ -511,12 +514,21 @@ export class GhidraClient {
typeof parameters.pattern === "string"
? parameters.pattern
: undefined;
const asciiCandidate =
pattern === undefined ? undefined : ghidraAsciiLiteralCandidate(pattern);
const asciiSubstring =
pattern !== undefined && asciiCandidate === null
? ghidraAsciiLiteralSubstring(pattern)
: null;
const pending = this.#enqueue(
operation,
pattern !== undefined
? {
...parameters,
literal_ascii_candidate: ghidraAsciiLiteralCandidate(pattern),
literal_ascii_candidate: asciiCandidate ?? null,
...(asciiSubstring === null
? {}
: { literal_ascii_substring: asciiSubstring }),
}
: parameters,
{
+17 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { literalSubstringPredicate } from "../domain/analysisSearch.js";
import { ghidraAsciiLiteralCandidate } from "./GhidraLiteralSearch.js";
import {
ghidraAsciiLiteralCandidate,
ghidraAsciiLiteralSubstring,
} from "./GhidraLiteralSearch.js";
describe("Ghidra ASCII literal candidates", () => {
it.each([
@@ -58,4 +61,17 @@ describe("Ghidra ASCII literal candidates", () => {
}
}
});
it.each([
["https://example.com/café", "https://example.com/caf"],
["αfooβbarbazγ", "barbaz"],
["warfare/storage/ſK™", "warfare/storage/sk"],
["日本語", null],
["", null],
])(
"derives longest ASCII-foldable substring for %j as %j",
(pattern, expected) => {
expect(ghidraAsciiLiteralSubstring(pattern!)).toBe(expected);
},
);
});
+44 -17
View File
@@ -8,6 +8,27 @@ import {
export const GHIDRA_LITERAL_CANDIDATES_LIMITATION =
"For this case-insensitive literal search, raw_result contains Ghidra's candidate rows before REA's Unicode-aware filtering; normalized_result contains the matches.";
const asciiFoldEquivalent = (
character: string,
equivalents: Map<string, string | null>,
): string | null => {
if (character.charCodeAt(0) < 128) return character.toLowerCase();
let equivalent = equivalents.get(character);
if (equivalent === undefined) {
const matches = literalSubstringPredicate(character, false);
equivalent = null;
for (let ascii = 0; ascii < 128; ascii++) {
const value = String.fromCharCode(ascii);
if (matches(value)) {
equivalent = value.toLowerCase();
break;
}
}
equivalents.set(character, equivalent);
}
return equivalent;
};
/** ASCII-only candidates are exact; every non-ASCII source value stays eligible.
* Node owns Unicode folding, so the Java runtime's Unicode version cannot omit
* a match. Null means no ASCII-only value can match this query.
@@ -16,29 +37,35 @@ export const ghidraAsciiLiteralCandidate = (pattern: string): string | null => {
const equivalents = new Map<string, string | null>();
let candidate = "";
for (const character of pattern) {
if (character.charCodeAt(0) < 128) {
candidate += character.toLowerCase();
continue;
}
let equivalent = equivalents.get(character);
if (equivalent === undefined) {
const matches = literalSubstringPredicate(character, false);
equivalent = null;
for (let ascii = 0; ascii < 128; ascii++) {
const value = String.fromCharCode(ascii);
if (matches(value)) {
equivalent = value.toLowerCase();
break;
}
}
equivalents.set(character, equivalent);
}
const equivalent = asciiFoldEquivalent(character, equivalents);
if (equivalent === null) return null;
candidate += equivalent;
}
return candidate;
};
/**
* Longest ASCII-foldable substring inside a non-ASCII case-insensitive literal
* query. Every matching source string must contain both a non-ASCII character
* and this folded ASCII run, preventing bridge IPC floods on localized binaries.
*/
export const ghidraAsciiLiteralSubstring = (pattern: string): string | null => {
const equivalents = new Map<string, string | null>();
let best = "";
let current = "";
for (const character of pattern) {
const equivalent = asciiFoldEquivalent(character, equivalents);
if (equivalent === null) {
if (current.length > best.length) best = current;
current = "";
} else {
current += equivalent;
}
}
if (current.length > best.length) best = current;
return best.length > 0 ? best : null;
};
/**
* Apply Node's folding to the bridge's candidate rows, including the secondary
* names a procedure row matched. The bridge matches leaf and qualified
@@ -596,8 +596,9 @@ const JAVA_PROBE_DRIVER = String.raw`
String[] fields = line.split("\\|", -1);
String pattern = "0".equals(fields[0]) ? null : decodeHex(fields[1]);
String value = decodeHex(fields[2]);
String substring = fields[3].isEmpty() ? null : decodeHex(fields[3]);
try {
ValueMatcher matcher = literalCandidateMatcher(pattern);
ValueMatcher matcher = literalCandidateMatcher(pattern, substring);
System.out.println(matcher.matches(value) ? "1" : "0");
}
catch (RequestFailure failure) {
@@ -882,8 +883,8 @@ const JAVA_PROBE_DRIVER = String.raw`
String aliasLeaf = decodeHex(fields[5]);
ValueMatcher delegate = switch (factory) {
case "literal" -> literalMatcher(expr);
case "candidate-ascii" -> literalCandidateMatcher(expr);
case "candidate-null" -> literalCandidateMatcher(null);
case "candidate-ascii" -> literalCandidateMatcher(expr, null);
case "candidate-null" -> literalCandidateMatcher(null, null);
case "regex-cs" -> regexMatcher(expr, true);
case "regex-ci" -> regexMatcher(expr, false);
default -> throw new IllegalArgumentException("Unknown matcher factory: " + factory);
@@ -1,7 +1,10 @@
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { literalSubstringPredicate } from "../../../../src/domain/analysisSearch.js";
import { decodeStrictUtf8 } from "../../../../src/domain/strictUtf8.js";
import { ghidraAsciiLiteralCandidate } from "../../../../src/ghidra/GhidraLiteralSearch.js";
import {
ghidraAsciiLiteralCandidate,
ghidraAsciiLiteralSubstring,
} from "../../../../src/ghidra/GhidraLiteralSearch.js";
import {
createTestWorkspace,
removeTestWorkspace,
@@ -94,6 +97,7 @@ describe.skipIf(jdk === undefined)(
"\ud800",
"\udfff",
"pre\ud800mid",
"éSk",
];
const values = [
"",
@@ -123,24 +127,31 @@ describe.skipIf(jdk === undefined)(
"pre\ud800mid",
"\udfff",
"ascii_only_string",
"xÉſKy",
];
const pairs: {
readonly pattern: string;
readonly candidate: string | null;
readonly substring: string | null;
readonly value: string;
}[] = [];
for (const pattern of patterns) {
const candidate = ghidraAsciiLiteralCandidate(pattern);
const substring =
candidate === null ? ghidraAsciiLiteralSubstring(pattern) : null;
for (const value of values) {
pairs.push({ pattern, candidate, value });
pairs.push({ pattern, candidate, substring, value });
}
}
const stdin = pairs
.map(({ candidate, value }) =>
candidate === null
? `0||${encodeUtf16Hex(value)}`
: `1|${encodeUtf16Hex(candidate)}|${encodeUtf16Hex(value)}`,
.map(({ candidate, substring, value }) =>
[
candidate === null ? "0" : "1",
encodeUtf16Hex(candidate ?? ""),
encodeUtf16Hex(value),
encodeUtf16Hex(substring ?? ""),
].join("|"),
)
.join("\n");
const stdout = await runBridgeProbe(
@@ -152,7 +163,7 @@ describe.skipIf(jdk === undefined)(
expect(observed).toHaveLength(pairs.length);
for (let index = 0; index < pairs.length; index += 1) {
const { pattern, candidate, value } = pairs[index]!;
const { pattern, candidate, substring, value } = pairs[index]!;
const matched = observed[index] === "1";
const jsMatches = literalSubstringPredicate(pattern, false)(value);
if (jsMatches) {
@@ -162,20 +173,36 @@ describe.skipIf(jdk === undefined)(
if (valueIsAscii) {
expect(matched).toBe(jsMatches);
}
if (candidate === null) {
if (candidate === null && substring === null) {
expect(matched).toBe(!valueIsAscii);
}
}
});
},
);
describe.skipIf(jdk === undefined)(
"ReaGhidraBridge literalCandidateMatcher edge cases",
() => {
it("requires both the folded ASCII run and a non-ASCII value for mixed literal candidates", async () => {
const stdout = await runBridgeProbe(
requireProbe(),
"literal-batch",
["xÉſKy", "xÉunrelated", "ASCII_SK_only"]
.map((value) => `0||${encodeUtf16Hex(value)}|${encodeUtf16Hex("sk")}`)
.join("\n"),
);
expect(splitProbeLines(stdout)).toEqual(["1", "0", "0"]);
});
it("handles empty, invalid non-ASCII, and case-sensitive literal matchers", async () => {
const invalidAndEdge = await runBridgeProbe(
requireProbe(),
"literal-batch",
[
`1||${encodeUtf16Hex("anything")}`,
`1|${encodeUtf16Hex("é")}|${encodeUtf16Hex("é")}`,
`1|${encodeUtf16Hex("abc")}|${encodeUtf16Hex("ab")}`,
`1||${encodeUtf16Hex("anything")}|`,
`1|${encodeUtf16Hex("é")}|${encodeUtf16Hex("é")}|`,
`1|${encodeUtf16Hex("abc")}|${encodeUtf16Hex("ab")}|`,
].join("\n"),
);
expect(splitProbeLines(invalidAndEdge)).toEqual([