perf(hopper): resolve string search records once per query (#1229)

* perf(hopper): resolve string search records once per query

search_strings called _string_inventory(document) once per match, and each
call sorts every string address and rebuilds the record dict, so a query cost
O(matches x strings log strings). Resolve the inventory once per search.
Warm search, 50% matches, fake document, best of 7: 1000 strings 186 -> 0.5 ms,
4000 strings 3161 -> 2.1 ms, 8000 strings 13121 -> 4.9 ms; output byte-identical.

* perf(hopper): skip record resolution for empty string searches

Resolving the full string inventory for a query with no matches added a sort
of every string address that the previous code never performed. Return early
when nothing matches. Zero-match search on a warm document, best of 7:
64000 strings 35.9 ms before this change, 4.0 ms after (main: 3.9 ms).
This commit is contained in:
keemsisi
2026-10-09 18:39:19 +08:00
committed by GitHub
parent 45e3edc17f
commit 9426c3f1bb
3 changed files with 198 additions and 1 deletions
+6 -1
View File
@@ -553,7 +553,12 @@ def _search_results(document, kind, params):
if not matches(item[1]):
continue
selected.append(item)
return [{"address": address, **_string_inventory(document)[address]} for address, _ in selected] if kind == "string" else [
if not selected:
return []
if kind == "string":
records = _string_inventory(document)
return [{"address": address, **records[address]} for address, _ in selected]
return [
{
"address": address,
"value": value,
@@ -0,0 +1,80 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import { z } from "zod";
const execute = promisify(execFile);
const bridge = fileURLToPath(
new URL("../../../../bridge/hopper_bridge.py", import.meta.url),
);
const probe = fileURLToPath(
new URL("../../../fixtures/hopperStringSearchProbe.py", import.meta.url),
);
const resultSchema = z.array(
z.object({
pattern: z.string(),
case_sensitive: z.boolean(),
actual: z.array(z.object({ address: z.string() }).passthrough()),
expected: z.array(z.object({ address: z.string() }).passthrough()),
}),
);
async function runProbe() {
const { stdout } = await execute("python3", [probe, bridge], {
encoding: "utf8",
timeout: 5_000,
maxBuffer: 1_024 * 1_024,
});
return resultSchema.parse(JSON.parse(stdout));
}
describe("Hopper string search", () => {
it("returns the independently expected records for every query, including repeats", async () => {
const results = await runProbe();
expect(results).toHaveLength(14);
for (const result of results) {
expect(result.actual).toEqual(result.expected);
}
});
it("matches case-insensitively and case-sensitively across segments in ascending address order", async () => {
const results = await runProbe();
const byQuery = (pattern: string, caseSensitive: boolean) =>
results
.find(
(item) =>
item.pattern === pattern && item.case_sensitive === caseSensitive,
)
?.actual.map((item) => item.address);
expect(byQuery("needle", false)).toEqual([
"0x1010",
"0x1030",
"0x1050",
"0x2000",
"0x3020",
"0x3040",
]);
expect(byQuery("needle", true)).toEqual(["0x1010", "0x2000", "0x3040"]);
expect(byQuery("zzz-absent", false)).toEqual([]);
});
it("preserves the decoding-unavailable record for an unreadable string", async () => {
const results = await runProbe();
const search = results.find(
(item) => item.pattern === "Broken" && item.case_sensitive,
);
expect(search?.actual).toEqual([
{
address: "0x1030",
value: "Broken Needle",
provider_value: "Broken Needle",
decoding: {
available: false,
reason: "Hopper reported an invalid string object extent at 0x1030",
},
},
]);
});
});
+112
View File
@@ -0,0 +1,112 @@
"""Exercise bridge string search against a Hopper-shaped multi-segment document."""
import json
from pathlib import Path
import sys
class Segment:
TYPE_ASCII = 1
TYPE_UNICODE = 2
def __init__(self, start, length, strings):
self.start, self.length = start, length
self.strings = strings # address -> (display, raw bytes, type, reported length)
def getStringsList(self):
return [(display, address) for address, (display, _, _, _) in self.strings.items()]
def getStartingAddress(self):
return self.start
def getLength(self):
return self.length
def getObjectLength(self, address):
return self.strings[address][3]
def readBytes(self, address, length):
return self.strings[address][1][:length]
def getTypeAtAddress(self, address):
return self.strings[address][2]
class Document:
def __init__(self, segments):
self.segments = segments
def getSegmentsList(self):
return self.segments
def ascii_entry(text):
raw = text.encode() + b"\x00"
return (text, raw, Segment.TYPE_ASCII, len(raw))
def unicode_entry(text):
raw = text.encode("utf-16-le") + b"\x00\x00"
return (text, raw, Segment.TYPE_UNICODE, len(raw))
def main():
path = sys.argv[1]
bridge = {"__file__": path, "__name__": "rea_hopper_bridge"}
exec(compile(Path(path).read_text(encoding="utf-8"), path, "exec"), bridge)
class API:
def require_analysis_complete(self, document, method):
pass
# Later segment listed first so ascending order must come from the bridge.
high = Segment(0x3000, 0x100, {
0x3040: ascii_entry("needle high"),
0x3000: ascii_entry("Other"),
0x3020: unicode_entry("Needle wide"),
})
low = Segment(0x1000, 0x100, {
0x1050: ascii_entry("NEEDLE upper"),
0x1010: ascii_entry("a needle"),
0x1030: ("Broken Needle", b"", Segment.TYPE_ASCII, 0),
0x1080: ascii_entry("nothing here"),
})
mid = Segment(0x2000, 0x100, {0x2000: ascii_entry("needle mid"), 0x2010: ascii_entry("x")})
document = Document([high, low, mid])
bridge["_api"] = lambda: API()
bridge["_document"] = lambda name=None: document
table = {}
for segment in document.getSegmentsList():
for address, (display, raw, kind, _) in segment.strings.items():
if display == "Broken Needle":
table[address] = {
"value": display,
"provider_value": display,
"decoding": {"available": False, "reason": "Hopper reported an invalid string object extent at 0x%x" % address},
}
continue
encoding = "utf-8" if kind == Segment.TYPE_ASCII else "utf-16-le"
table[address] = {
"value": display,
"provider_value": display,
"string": {"encoding": encoding, "encoding_status": "inferred", "termination": "present_or_not_required", "byte_length": len(raw)},
}
def expected(pattern, case_sensitive):
needle = pattern if case_sensitive else pattern.casefold()
hits = [a for a in sorted(table) if needle in (table[a]["value"] if case_sensitive else table[a]["value"].casefold())]
return [{"address": "0x%x" % a, **table[a]} for a in hits]
cases = [("needle", False), ("needle", True), ("Needle", True), ("NEEDLE", False), ("zzz-absent", False), ("Broken", True), ("e", False)]
results = []
# Run the sequence twice: the second pass reuses the document caches.
for _ in range(2):
for pattern, case_sensitive in cases:
actual = bridge["_dispatch"]("search_strings", {"pattern": pattern, "case_sensitive": case_sensitive})
results.append({"pattern": pattern, "case_sensitive": case_sensitive, "actual": actual, "expected": expected(pattern, case_sensitive)})
print(json.dumps(results))
if __name__ == "__main__":
main()