Skip to content

perf(ghidra): eliminate non-ASCII search flood, compact bridge inventories, and stream JSON responses - #13305

Merged
morluto merged 3 commits into
mainfrom
perf/ghidra-bridge-scale-and-indexes
Nov 22, 2026
Merged

morluto merged 3 commits into
mainfrom
perf/ghidra-bridge-scale-and-indexes

Conversation

@morluto

@morluto morluto commented Nov 22, 2026

Copy link
Copy Markdown
Owner

Summary

Eliminates the primary CPU, memory, GC, and lookup bottlenecks inside ReaGhidraBridge.java using Data-Intensive Applications (DDIA) designs — exact predicate pre-filtering, typed compact representations before wire serialization, secondary lookup indexes, and single-pass streaming response serialization:

  1. Exact Unicode-sound zero-allocation literalCandidateMatcher + foldAsciiCandidateChar: Eliminates value.chars() IntStream and value.toLowerCase(Locale.ROOT) allocations per row and stops forwarding all non-ASCII symbols/strings when the search pattern is case-insensitive ASCII (matching ECMAScript /iu simple case folding: 'A'..'Z' -> +32, '\u017F' -> 's', '\u212A' -> 'k').
  2. Compact typed inventory records & lazy tie-breaking comparator: Replaces eager Gson JsonObject/.deepCopy() retention in InventoryItem/FunctionEntry with typed NameEntry, ProcedureEntry, StringEntry, and *Facts records, materializing JsonObject only for returned hits and deferring GSON.toJson(...) tie-breaking in compareInventory to exact (address, value) ties. binaryInventorySummary uses lightweight counters (countProcedures(), countStrings()) preserving deduplication without retaining full inventories.
  3. Indexed procedure alias lookup & O(1) single-address slices: Pre-indexes leafName + sorted List<ProcedureAlias> on ProcedureEntry so search_procedures executes zero SymbolTable.getSymbols(entryPoint) queries per search. resolveProcedureByName uses lazy procedureNameIndex when cached or direct SymbolTable.getSymbols(name) / SymbolUtilities.parseDynamicName / getFunctionThunkAddresses(true) lookup when uncached. listNames / listStrings binary-search (sliceAtAddress) when cached or query single addresses directly when uncached.
  4. Streaming surrogate-escaping JSON writer (SurrogateEscapingWriter): Streams GSON.toJson(response, writer) directly into BufferedWriter without allocating a full-response intermediate String.
  5. Additional hot-path fixes: "0x" + Long.toHexString(...) replacing BigInteger formatting in canonicalAddress, ConcurrentHashMap + precompiled regex caches for symbol/source/FS normalization, recoveredJumpTables.length > 0 guard for ClangNode traversal, per-call reference-edge maps, batched batch-naming cache invalidation keeping stringInventory, cancellation checks in referencedStrings/referencedNames/selectedValue/swiftStringLiterals, and originalFileBytesSha256 memoization per unmodified FileBytes.

Problem and expected behavior

  • Large binaries caused search_strings and search_procedures in ReaGhidraBridge to allocate IntStreams and lowercased strings per candidate, forward every non-ASCII row across the pipe on ASCII queries, retain tens of megabytes of eager Gson LinkedTreeMap trees for cached inventories, re-query Ghidra's symbol table inside every search and name resolution, and buffer giant JSON reply strings on the JVM heap.
  • Expected behavior: identical canonical addresses, inventory ordering, ambiguity/not-found errors, Unicode case folding parity (/iu), surrogate escaping, cancellation responsiveness, and wire schemas with dramatically lower latency and heap footprint.

Change and scope

  • Modified ReaGhidraBridge.java (+828/-191).
  • No TS contract, MCP/CLI schema, or public tool changes in this PR.

Follow the contribution scope.
Not applicable (internal Ghidra bridge optimization within existing read-only ephemeral database and wire boundaries; no persistent/cross-run ad-hoc caches added).

Contract and boundary impact

  • Semantic owner and earliest changed stage: ReaGhidraBridge.java (JVM bridge inventory construction, search pre-filtering, procedure/address resolution, and response serialization).
  • Contribution scope fit and linked maintainer decision: not applicable.
  • CLI and MCP/tool-catalog contract: none.
  • Provider, bridge, target-format, or platform compatibility: preserves all existing wire DTO fields, ReaSwitchEvidenceProbe (typedJumpTableCases), ContextEvaluatorAdapter / ReaSwiftDecoderRegressions (selectedValue), surrogate escaping, and ECMAScript /iu case-folding semantics.
  • Evidence, artifact, provenance, or reconstruction contract: preserved (identical canonical addresses, provenance fields, limitations, and error codes).
  • Target selection, authority, upstream behavior, and cleanup details: preserved (ephemeral read-only bridge; cancellation checks added inside reference/constant loops).
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact: none.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: bridge-internal changes compiled against minimal Ghidra/Gson stubs (BridgeEditedMethodsCheck.java) and verified via an extracted Unicode/helper parity harness (GhidraParityTest.java across 10,027,008 code-point/surrogate checks vs Node v24.22.1) outside Git.
  • Base reproduction or other evidence (Apple M5 arm64, OpenJDK 21.0.12.1, Node v24.22.1, extracted harness):
    • literalCandidateMatcher (100k mixed ASCII/non-ASCII strings): candidate hits 50,200 -> 200, cold 28.56 ms -> 16.00 ms, warm 4.13 ms -> 2.23 ms.
    • StringEntry vs eager InventoryItem+stub JsonObject build+sort (200k entries): 75.33 ms -> 25.91 ms, retained heap 82.95 MiB -> 25.54 MiB.
    • canonicalAddress (100k): 9.73 ms -> 1.23 ms.
    • normalizedSymbolType (500k): 124.54 ms -> 8.98 ms.
    • writeResponse streaming vs intermediate String (50k objects): 23.71 ms -> 13.15 ms (eliminates full-response String).
  • User-visible CLI/MCP output (if applicable): unchanged schemas/outputs; lower latency and JVM memory pressure on large programs.
  • Remaining proof gaps: GHIDRA_INSTALL_DIR (>= 12.2) is not installed locally, so full headless Ghidra SDK compilation (npm run verify:ghidra:bridge-sources) and live Ghidra E2E runs rely on CI (ghidra-bridge-sources.yml).

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run check:fast — passed (typecheck + lint cached 106ms, architecture guards passed across 2944 source files)
  • npm run test:local -- src/ghidra/*.test.ts — 35/37 files (1158 tests) passed inside sandbox; the 2 sandbox-restricted tests (GhidraCheckpoint.test.ts, GhidraJavaProbe.test.ts) + GhidraLiteralSearch.test.ts passed 3/3 files (62/62 tests) when run outside sandbox (37/37 files, 1220/1220 tests total)
  • python3 tests/fixtures/ghidraHandshakeProbe.py /opt/homebrew/opt/openjdk@21/bin/java — passed (outside sandbox)
  • javac -Xlint:all -Werror parity & extracted method check (10,027,008 Unicode/surrogate parity checks vs Node v24.22.1) — passed (0 discrepancies)

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: OpenJDK 21.0.12.1 handshake probe + extracted compilation/parity checks + mocked TS unit tests; live Ghidra SDK compile awaited in CI.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only analysis preserved; no ambient caches or temp files created; stringInventory preserved across symbol/comment edits while mutation-sensitive symbol/decompiler caches still invalidate per batch.

Author readiness

Human owner:

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-22T04:23:54.430945Z a921dbf New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking findings remain.

Summary

The PR reduces Ghidra bridge allocations and repeated lookups, streams JSON replies, and adds checked-in Java helper tests.

  • Ghidra inventory requests reuse compact rows and saved procedure names.
  • Case-insensitive Ghidra searches check candidates without making temporary copies.
  • Ghidra responses stream as JSON while escaping surrogate characters.
  • Other Ghidra bridge paths reuse cached values and check cancellation sooner.

Reviews (4) · Last reviewed commit: "fix(ghidra): handle CRLF line endings in..." · Reviewed by Greptile

Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: bridge Hopper bridge (Python) related changes performance Performance regressions, scaling limits, and bounded-resource work provider: ghidra Analysis provider / engine: ghidra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant