Repository navigation
perf(hopper): resolve string search records once per query #1229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
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
commit c1afce8f6657c390c655908e4155345b8e53fe8a
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
80 changes: 80 additions & 0 deletions
80
tests/boundary/providers/hopper/hopperStringSearch.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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", | ||
| }, | ||
| }, | ||
| ]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.