Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
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.
  • Loading branch information
keemsisi committed Oct 9, 2026
commit c1afce8f6657c390c655908e4155345b8e53fe8a
5 changes: 4 additions & 1 deletion bridge/hopper_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -553,7 +553,10 @@ 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 kind == "string":
records = _string_inventory(document)
Comment thread
morluto marked this conversation as resolved.
Resolved
return [{"address": address, **records[address]} for address, _ in selected]
return [
{
"address": address,
"value": value,
Expand Down
80 changes: 80 additions & 0 deletions tests/boundary/providers/hopper/hopperStringSearch.test.ts
Original file line number Diff line number Diff line change
@@ -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 changes: 112 additions & 0 deletions tests/fixtures/hopperStringSearchProbe.py
Original file line number Diff line number Diff line change
@@ -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()