#7041

feat(binary-ninja-headless): add owned headless Binary Ninja provider

Openihabontopwants to merge intofrom

Summary

Adds binary-ninja-headless, a deep-analysis provider that starts an owned headless Binary Ninja Python interpreter, loads the admitted file read-only after verifying its Raw-view digest, waits for default auto-analysis, and serves REA's native analysis operations from that BinaryView. Refs #1551. Draft for the maintainer scope decision CONTRIBUTING requires for a new provider; it does not ask for integration yet.

It complements the attached GUI MCP adapter proposed in #5794: that adapter reads a file the analyst already opened in the GUI; this provider needs no GUI and reproduces analysis from the file alone, but requires a Binary Ninja license edition that permits headless use.

Problem and expected behavior

Binary Ninja users with a headless-capable license cannot point REA at Binary Ninja without keeping a GUI open. With this change, --provider binary-ninja-headless (or REA_ANALYSIS_PROVIDER / open_binary.provider_id) serves decompile, function, analyze, search, trace and the underlying native operations from an owned, digest-bound headless analysis, with the same Evidence and limitation reporting as the other providers.

Change and scope

  • src/binaryNinjaHeadless/: capabilities (identity, operations, limitations, effects), filesystem-only installation discovery, protocol values with zod schemas and projections to the shared REA shapes, an owned bridge process (NDJSON over stdio on spawnOwnedProviderProcess + ProviderProcessSupervisor, reply-size budget, startup deadline, cancellation stops the interpreter), an operation runner, a serial session client, and the AnalysisProviderCandidate.
  • bridge/binaryninja/rea_binaryninja_bridge.py: the Python side; one BinaryView per process, Binary Ninja log on stderr, requests validated and answered with stable error codes.
  • Configuration: BINARY_NINJA_INSTALL_DIR, REA_BINARY_NINJA_PYTHON, REA_BINARY_NINJA_STARTUP_TIMEOUT_MS (additive, optional).
  • Composition: registered in src/composition/binary.ts; catalog, module-boundary and test-project wiring.
  • Intentionally not included: list_segments (segment contract provenance is Hopper/Ghidra only), list_names, procedure_references, read_bytes, doctor integration, a real-provider verifier lane, engine-version commitment in the profile. These are listed in the guide as next steps.
  • Existing providers are unchanged.

Contribution scope: new provider; maintainer scope decision requested in #1551 (pending). No target execution, injection, mutation or protection recovery.

Contract and boundary impact

  • Semantic owner and earliest changed stage: new provider adapter src/binaryNinjaHeadless/ and bridge; application and contract layers unchanged.
  • Contribution scope fit and linked maintainer decision: pending in #1551.
  • CLI and MCP/tool-catalog contract: no new tools or schemas; the provider catalog gains one provider entry.
  • Provider, bridge, target-format, or platform compatibility: Binary Ninja 6.0 headless API; PE, ELF and thin Mach-O executables on x86, x86_64, arm, arm64, mips, powerpc, riscv; Windows bundled interpreter by default, explicit interpreter elsewhere.
  • Evidence, artifact, provenance, or reconstruction contract: observations carry cachePolicy: live, Binary Ninja provenance strings in body/classification/locals, reference kinds reported as unavailable with the observed category, and relationship coverage unknown (callers) / partial-or-complete (callees).
  • Target selection, authority, upstream behavior, and cleanup details: REA owns the interpreter process; Binary Ninja writes only its own user directory; close releases the view and stops the process; failed startups are not cached.
  • Generated metadata, package, or installation impact: package.json#files ships the bridge script; test:python runs its unit test; no installer changes.

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: src/binaryNinjaHeadless/BinaryNinjaHeadlessProvider.test.ts (availability, target support, profile binding), src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.test.ts (launch contract, projections against functionDossierSchema and instruction windows, caller mistakes, startup failure attribution, deadline, cancellation, protocol faults, reply bounds, close) with tests/fixtures/fakeBinaryNinjaBridge.mjs; bridge/binaryninja/test_rea_binaryninja_bridge.py with a fake binaryninja module.

  • Base reproduction or other evidence: real-engine run recorded in docs/testing.md#binary-ninja-headless-lane (Windows 11 x64, Binary Ninja 6.0.10905, where.exe).

  • User-visible CLI/MCP output: rea decompile 'C:\Windows\System32\where.exe' --procedure __wmainCRTStartup --provider binary-ninja-headless --json returns Pseudo C Evidence with provider binary-ninja-headless, profile mode owned-headless, and raw engine facts (core_version 6.0.10905).

  • Remaining proof gaps: MCP parity, Linux and macOS hosts, ELF and Mach-O targets, other Binary Ninja releases and license editions, cancellation against the real engine, token/CPU/memory measurements.

  • 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 and lint, 2 tasks successful).
  • npm run test:local -- src/binaryNinjaHeadless/BinaryNinjaHeadlessProvider.test.ts src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.test.ts src/config.test.ts — 111 tests passed.
  • python -m unittest bridge/binaryninja/test_rea_binaryninja_bridge.py (CPython 3.14) — 10 tests passed.
  • Production CLI against real Binary Ninja 6.0.10905 on Windows 11 x64 with where.exe: decompile, function --detail complete, analyze, search --pattern 'cannot be run', trace --query 'cannot be run' — all exit 0; every output parsed against the built Evidence schema and its output contract; dossier parsed against functionDossierSchema.

Compatibility, safety, and release

  • Breaking changes or migration steps: none; all settings are new and optional.
  • Real Hopper/Ghidra, browser, or OS coverage: existing providers untouched; real Binary Ninja coverage limited to one Windows host.
  • Package or release metadata impact: one new packaged bridge script; one provider catalog entry.
  • Security, privacy, process, or containment review: the interpreter runs with the current user's permissions under REA's owned-process supervision, user plugins and settings disabled, no network use by REA; Binary Ninja's own license and user directory behavior is unchanged.

Author readiness

Human owner: @ihabontop

  • 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.

🤖 Generated with Claude Code

Activity

3
chatgpt-codex-connector[bot]1mo ago

Codex Review Summary

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

ReviewStatusCommitReview trigger
📝 Code Review⚠️ Failed 2026-10-24T21:10:32.911491Z
We couldn’t complete this review. Comment @codex review to try again.
d4deddfDraft marked ready
ℹ️ 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[bot]1mo ago

Confidence Score: 4/5

[Medium impact] The changes add a new, opt-in analysis path for people using Binary Ninja.

Do not merge until cleanup ownership and retry work correctly and the cited repository requirements are satisfied.

Findings

  1.  Failed cleanup cannot recover ▶
  2.  Queued cancellation keeps waiting ▶
  3.  Recursive call sites disappear ▶
  4.  Replies grow before size checks ▶
  5.  Oversized replies invite useless retries ▶
  6.  Missing replies look complete ▶
  7.  Python writes unwanted cache files ▶
  8.  Setup loses the startup deadline ▶
Fix with agent prompt
### Issue 1
src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.ts:258-262
After cancellation or a protocol fault, `#start` drops the old bridge and starts another without waiting for its stop result. Startup also discards incomplete cleanup. On close, `#closePromise` and the bridge's `#stopping` cache the failure forever, so cleanup retries cannot reach the supervisor again.

This violates the repository requirement to retain ownership of resources whose cleanup failed. Keep the bridge until cleanup succeeds, block replacement while cleanup remains unresolved, and allow failed stop attempts to retry.

### Issue 2
src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.ts:125-132
`execute` puts the entire call behind `#tail`, but checks the caller's signal only inside `#execute`. Cancelling a second MCP request therefore leaves it waiting through the first request's full load or analysis.

Make the queue wait cancellable without stopping another caller's active work, and skip the cancelled entry when its turn arrives.

### Issue 3
bridge/binaryninja/rea_binaryninja_bridge.py:623-625
`_references` drops recursive calls because their target lies inside the current function. A call from `main` back to `main` survives in `callees` but disappears from `outgoing_references`.

Filter internal branches separately from calls. The repository requires available source observations to survive these conversions; this requirement must be satisfied before merging.

### Issue 4
bridge/binaryninja/rea_binaryninja_bridge.py:105-108
`json.dumps` allocates the complete reply before REA receives any bytes. Reference replies also repeat full function identities and body ranges for each edge. Large inventories or reference-heavy functions can consume far more memory than the 64 MiB receiving limit suggests.

Carry the budget into the producer and enforce it while collecting and encoding the reply. The repository requires accounting for representation growth before allocation; this must be addressed before merging.

### Issue 5
src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.ts:429-435
Reporting the reply-size limit as `capacity` makes the public error retryable and tells callers to wait for another analysis to finish. Waiting cannot raise this fixed limit, and another attempt also reloads the interpreter.

Mark the refusal non-retryable and use the existing fixed-allowance recovery fields to name the byte limit and explain recovery. The limits guide requires this distinction before merging.

### Issue 6
src/binaryNinjaHeadless/BinaryNinjaHeadlessProtocolValues.ts:154-160
`bridgeCalleeTargetSchema` accepts `{kind: "function"}` without a procedure, and the projection turns it into a target at `0x0`. Missing requested facets also become empty lists marked available. The current Python producer supplies these fields, but a broken reply would silently become valid-looking Evidence.

Require fields by target kind and validate each operation's requested facets. The repository requires missing facts to remain distinct from observed absence; satisfy that requirement before merging.

### Issue 7
src/binaryNinjaHeadless/BinaryNinjaHeadlessSessionClient.ts:71-74
`-I` makes Python ignore `PYTHONDONTWRITEBYTECODE`, so this launch does not disable bytecode writes. If the Binary Ninja installation is writable, importing its API can create `__pycache__` files there despite the provider's stated write scope.

Pass `-B` as an interpreter argument and test the resulting Python flag rather than only the launcher's environment.

### Issue 8
src/config/environment.ts:68-70
`REA_BINARY_NINJA_STARTUP_TIMEOUT_MS` is missing from `SELECTED_REGISTRATION_SETTINGS`. A user can raise the deadline for a large target and run `rea setup`, yet the registered MCP server still uses the default.

The limits guide requires new headroom settings to be copied into client registrations. Add this setting to the shared allowlist and test its preservation before merging.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds an owned headless Binary Ninja provider with installation discovery, a Python bridge, digest-bound loading, shared result projections and provider registration.

  • Analysts can run Binary Ninja analysis without keeping its GUI open.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[CLI or MCP request] --> B[Provider selection and profile]
  B --> C[Owned Python interpreter]
  C --> D[Load BinaryView]
  D --> E{Raw digest and view type match?}
  E -- No --> F[Close view and return error]
  E -- Yes --> G[Wait for analysis]
  G --> H[Serial bridge requests]
  H --> I[Validate and project results]
  I --> J[Evidence with limits]
  H --> K[Close or cancellation]
  K --> L[Stop owned process]

Reviews (1) · Last reviewed commit: "feat(binary-ninja-headless): add owned h..." · Reviewed by Greptile