Repository navigation
feat(ghidra): select a pre-imported project with -process - #2358
goncalompontes wants to merge 18 commits into
Conversation
…-importing Every session paid a fresh -import plus auto-analysis into a per-session project that -deleteProject removed, so large targets re-paid the cold-import tax on every open and could not fit the startup deadline (morluto#1048). Add an opt-in existing-project launch path following the first-slice spec from the issue. ghidraHeadlessArguments gains an existing-project branch that selects the project location, project name and program explicitly with -process <program> -noanalysis, keeps -readOnly and drops -import/-deleteProject. Import-only selections (DOS, raw binary, language override, PSP, analysis seeds, analyzer overrides, MIPS soft-float) are rejected with their reasons, and Windows keeps its current P0 launch path unchanged. GhidraHeadlessLauncher copies the caller's project into the owned runtime project root before launching (copy-first), so Ghidra never touches the original project files and a missing project directory fails before any process starts. Wiring the profile/CLI selection surface is left for a follow-up slice.
The headless invocation selects the fixed project name rea-project while copyExistingGhidraProject copied caller entries verbatim, so a directory holding any other project file was copied and spawned successfully only to fail inside Ghidra with an opaque error. Reject that layout before any copy or process start with its actual reason, and state the fixed-name contract on GhidraExistingProject and the copy helper. Also open morluto#2147 to track the product wiring, target-digest binding with stale/mismatch rejection, provenance/mutation documentation, and the real-provider verification lane this fixture-only slice has not run (morluto#1048).
Add REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM so a caller can open a project produced outside REA with '-process -noanalysis' instead of re-importing and re-analyzing the target inside the provider startup deadline. Both settings are required together and validated against import-time options (language, compiler spec, seeds, disabled analyzers) that only apply to a fresh import. The pair is threaded through AppConfig to the launcher, and rejected for the Windows launch path and DOS, raw-binary, and PSP targets. The analysis profile records import_mode: existing-project-copy; the bridge's executable SHA-256 check already rejects a stale or mismatched project. Stacks on morluto#2150, which adds the launcher existingProject branch. Refs morluto#1048, morluto#2147.
97353b7 to
000f379
Compare
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
Review Finding & Architecture VerificationWhile threading 1. Late Failure for Incompatible Targets (
|
|
@greptileai review |
|
This PR is set for a Plus review. TREX isn't supported with Plus or Apex reviews yet, so Greptile reviews this PR at Base while TREX is on. |
[Medium impact] Adds support for opening pre-imported Ghidra analysis projects. The normal restart path is fixed, but restoration can still return stale saved-project answers and should be fixed before merging. Findings
Fix with agent prompt### Issue 1
src/ghidra/GhidraProvider.ts:301-309
`session_id` is created when the profile is resolved, not when the project is copied. When Ghidra exits and `open_binary` reopens the same target without `providerId`, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.
Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.SummaryAdds environment settings for opening a saved Ghidra project through a private copy.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Open saved project] --> B[Resolve selected provider profile]
B --> C[Copy project into private runtime]
C --> D[Open with process and noanalysis]
D --> E[Serve queries and cache answers]
E --> F{Retained client alive?}
F -->|Yes| E
F -->|No| G[Refresh selected profile]
G --> C
Reviews (13) · Last reviewed commit: "fix(session): recommit the profile for a..." · Reviewed by Greptile |
Copy only selected project files through a cancelable sequential stream traversal, reject symlinks, use the regular-file ownership helper, keep import-only derived flags out of existing-project launches and reject caller import overrides during profile resolution. Source inspection and git diff --check; tests/builds/typechecks/CI reruns skipped at explicit user request.
Keep the established missing-project message for ENOENT and preserve other filesystem failures instead of relabeling them as absence. Source inspection and git diff --check only. Tests, builds and typechecks skipped by explicit user request. GitHub review writes paused globally.
|
Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open. Fixed in 676326e. Root cause and structural fix: ENOENT retains the established missing-project diagnostic. Other lstat failures preserve their original reason; an existing nonregular directory or symlink is separately refused. Validation: source inspection and git diff --check only. Tests, builds and typechecks were skipped by the user's explicit request; no runtime or real-provider pass is claimed. No directly related cleanup remains identified. |
|
Review findings addressed at their producing boundaries and consumers. Latest changes were reviewed from source; tests and provider runs were skipped at the maintainer's request. Findings requiring separate decisions or verification remain open. Fixed in bd8633c (snapshot identity commit be9c21f). The executable digest and import mode cannot identify a saved project's program analysis. Until that saved state has a verified content commitment, the Ghidra provider now creates a fresh existing_project.session_id for each profile resolution and commits the selected program name with it. Shared snapshot import/cache matching already compares the complete profile digest, so another session's snapshot fails the existing mismatch gate; repeated queries in one immutable owned copy retain their session cache. The installation guide explicitly documents this lifetime. A regression was authored for repeated resolutions of one project and a second project producing distinct digests, but was not run. Source inspection followed profile composition, route capture, snapshot import validation and cache binding; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. Cross-session reuse intentionally remains unavailable until saved-state hashing is implemented; no downstream cache reinterpretation was added. Fixed in bd8633c. The parser correctly identified the missing setting but generated the constraint from the supplied setting, reversing the remediation. The paired-settings owner now emits one symmetric constraint: REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_EXISTING_PROGRAM must be set together. Both one-sided configuration cases now assert that exact guidance in the existing regression. Source inspection followed ConfigurationError projection and both parser branches; git diff --check passed. Validation: inspected the producing boundary and affected consumers in source; no tests, builds, lint, typechecks, provider workloads or CI reruns were executed, as explicitly requested. No duplicate direction-dependent message remains. |
|
Want your agent to iterate on Greptile's feedback? Try greploops. |
REA_GHIDRA_EXISTING_PROJECT / REA_GHIDRA_EXISTING_PROGRAM were rejected on win32 at profile resolution and again in headless argument construction, so the existing-project `-process -noanalysis -readOnly` path was Linux/macOS only even though the Windows P0 launcher builds the same invocation. Remove both win32 gates. The Windows batch launch already quotes the project location, the fixed `rea-project` name and the `-process <program>` program name, and copyExistingGhidraProject writes the caller's project into the owned private runtime, so no POSIX-only behavior is required. Import-time selections (DOS/raw-binary/PSP/language override/seeds/disabled analyzers) stay rejected, and the no-return repair post-script remains POSIX-only, matching a fresh Windows import's `disabled-windows-p0` profile. Verified on Windows with Ghidra 12.1.4 and a pre-imported engine2.dll (6.8 MB PE x86-64, project produced by analyzeHeadless.bat under the fixed `rea-project` name): `rea analyze` opened the owned copy in ~12 s with import_mode `existing-project-copy` and reported 13,302 procedures, versus a ~237 s cold import. The Windows-rejection regressions now assert the admitted behavior, and the installation guide documents the batch pre-import command.
Reconcile morluto#2358's existing-project wiring and this branch's project cache with 254 commits of main, including main's Ghidra provider/launcher/installation refactors. Conflicts: keep main's parsed-environment structure in parseConfig and re-apply the REA_GHIDRA_EXISTING_PROJECT and REA_GHIDRA_PROJECT_CACHE settings; keep both main's and this branch's suites in config.test.ts and GhidraProvider.behavior.test.ts; adopt main's shared GhidraInstallation fixture in the language-override, snapshot-cache and PowerPC tests and align the raw-binary profile test with main (drop the stale hard-coded digest). Skip main's POSIX-path and Windows native-replay lanes on Windows, as the suite already does elsewhere. Install the merged lockfile (npm ci) for main's new dependency.
|
TL;DR: The two new settings work end to end on Linux. A saved project opens in about 6 seconds, where a fresh import of the same program takes about 53 seconds. A project folder with I tested head 9adad2c as pushed. GitHub says it conflicts with main b7dcf78. Main does not know the settings, so I used it as "before". I ran the real command: Results
The 4 skipped tests are the Windows-only cases. The profile reads Config errors on head came back in under 1 second, with no Java started:
Late failures (head)
Not run
Thanks, Gonçalo Pontes, for the feature. Thanks, morluto, for the copy and cancel rework. Load average (busy tasks over 1 minute, on 24 threads) read 5.0 to 5.6 during the timing runs. A benchmark shared the box, so read the times as rough. Test setup
CommandsEach run sat under 🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊 |
# Conflicts: # src/config.test.ts # src/config/parseConfig.ts # src/ghidra/GhidraProvider.behavior.test.ts # tests/boundary/filesystem/artifactComparison.test.ts
|
Merged latest
I checked that no test title this PR added since the merge base was lost. Validation:
Not verified: a real Windows host or Ghidra project. |
| // Saved project analysis is not committed by the executable digest. | ||
| // Bind snapshots to this resolution's owned copy; cross-session replay | ||
| // stays unavailable until the selected program's saved state is hashed. | ||
| ...(existingProject === undefined | ||
| ? {} | ||
| : { | ||
| existing_project: { | ||
| program_name: existingProject.programName, | ||
| session_id: randomUUID(), |
There was a problem hiding this comment.
session_id is created when the profile is resolved, not when the project is copied. When Ghidra exits and open_binary reopens the same target without providerId, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.
Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.
Knowledge Base Used:
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/ghidra/GhidraProvider.ts
Line: 301-309
Comment:
**Restart returns old answers**
`session_id` is created when the profile is resolved, not when the project is copied. When Ghidra exits and `open_binary` reopens the same target without `providerId`, REA reuses the route and profile but copies the saved project again. If the caller edited that project meanwhile, the cache still matches and returns answers from the old copy. Cached and fresh queries can then describe different saved states.
Bind cache identity to the copy's lifetime, or clear and rebind cached answers whenever a new copy is opened.
**Knowledge Base Used:**
- [Ghidra integration](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/ghidra-integration.md)
- [Reverse-engineering toolchains](https://app.greptile.com/pre/-/custom-context/knowledge-base/morluto/rea/-/docs/reverse-engineering-toolchains.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.There was a problem hiding this comment.
@goncalompontes I traced the potential stale-cache mechanism at head 2a637760d a little further. resolveSessionTarget in BinarySessionOpen.ts reuses current.route for a same-target open_binary without providerId; when a retained provider is dead, BinarySession.#openWithinTransition starts a new client from that route. Its old profile is not re-resolved. AnalysisSnapshotCache.select only clears entries when the target/profile changes. A new copy of an externally edited saved project can therefore retain the previous copy's cache identity.
I reproduced these branch decisions in an isolated Node model, not an authentic REA provider restart or Ghidra run. A useful regression sequence would be: query a saved project, lose the Ghidra process while keeping the REA session, edit the external saved project, reopen the same target with provider_id omitted, and assert that the current answer comes from the newly copied state. An explicit provider re-selection would make a useful control. The fix likely belongs at copy-lifetime identity or snapshot invalidation, while preserving historical Evidence.
This extends the existing review finding, not a competing implementation. Happy to prepare a focused reproducible regression for incorporation.
There was a problem hiding this comment.
Thanks for tracing this through resolveSessionTarget and the retained-provider restart path. This confirms the original finding: session_id is generated only when the profile is first resolved, so it does not identify each subsequent private-project copy. When the route/profile is reused, AnalysisSnapshotCache.select can retain answers even though existingProject has been copied again from a potentially edited external project.
The regression sequence you described is the right one, with explicit provider re-selection as the control. The fix should either generate/cache identity at the copy boundary and use it for snapshot selection, or invalidate/rebind the snapshot whenever a new copy is opened; preserving historical Evidence is important. A focused regression covering the retained-session restart would be useful for incorporation.
There was a problem hiding this comment.
@goncalompontes I turned the restart/cache sequence from my earlier review reply into a regression using REA's actual BinarySession, SessionProviderRouter, and AnalysisSnapshotCache, with a production-composed fixture provider. It is based directly on #2358 head 2a637760da8d4d91c7aca5231645339d573f811a.
Test commit in my fork | GitHub Actions run
The existing nine liveness tests pass. The new test fails as expected: after a dead provider is replaced and the simulated saved project changes from old_saved_project_name to new_saved_project_name, the re-opened session still returns the old name from its retained snapshot. This is a real REA session/cache regression with a fixture child, not a real Ghidra process/project test. It ran on Ubuntu 24.04 with Node 24.18.0 after npm ci and the build.
I have deliberately stopped before changing the cache/profile architecture. Refreshing the copied-project identity on provider restart, or invalidating only the retired copy's cache, needs to preserve warm-query reuse while keeping historical Evidence. If the regression fits your PR, you're welcome to incorporate it; I'm happy to work with your preferred owning boundary. I have not modified your branch or opened a competing PR.
There was a problem hiding this comment.
@goncalompontes, following up on my verified restart regression with a focused correction against PR head 2a637760da8d4d91c7aca5231645339d573f811a.
Isolated fix branch | passing expanded GitHub Actions run | original failing run
Cause/fix: The same-target open_binary path correctly retains the selected provider, but on a dead client it also retained that provider's previous analysis profile. I added SessionProviderRouter.refreshBoundProfile, which recommits the original selected provider's profile only when its client must be replaced, preserving its selection source/authority. BinarySession binds the replacement client and snapshot selection to that refreshed profile, and validates any caller-supplied snapshot against it before retiring the previous client. A still-live client keeps the existing fast path.
The source changes are router and session transition; the branch contains the independently cherry-pickable regression and subsequent assertions, without needing the fork-only workflow.
Verified: The original fixture test failed with the stale saved-project name. The corrected branch passed 59 focused tests (2 skips) across session liveness, snapshot cache, direct snapshot replay and MCP workflow replay; test discovery, docs checks, fresh typecheck/lint (zero cached static tasks) and source cleanliness passed under Node 24.18.0 on Ubuntu 24.04. Controls confirm a changed profile digest, refusal of the prior copy's snapshot, and warm cache reuse within the new copy.
This exercises actual REA routing/snapshot/session code with a fixture provider, not a real Ghidra process restart. Historical Evidence records are not cleared by the change; the snapshot binding is replaced. I haven't modified your branch or opened a competing PR.
If you agree with the approach, please feel free to incorporate the patch into #2358. Happy to adjust the refresh owner to fit your architecture or help with a real-Ghidra restart test.
There was a problem hiding this comment.
@goncalompontes, I completed the follow-up real-Ghidra provider-restart acceptance test for the copy-lifetime correction on my fork.
Successful real-provider GitHub Actions run | isolated verifier branch | previously verified minimal source fix
Using Ghidra 12.1.4 (official archive SHA-256 verified), JDK 21, Node 24.18.0 and a wholly source-owned PE fixture, the verifier:
- Prepared saved
rea-projectwith functionsaved_first_version. - Opened it from REA's copy-first mode, then changed the external saved project using a separate real Ghidra
-processrun tosaved_second_version. - Located the REA-owned JVM using the authenticated
binary_sessionstatus, checked its command line, terminated only that child on the disposable runner, and calledopen_binaryagain in the same MCP connection withoutprovider_id. - Confirmed fresh pseudocode uses
saved_second_version, not the cached first name; the provider remainedghidra, profile digest changed71f28001...->d93bb1e0..., original target digest stayed0c641432..., and owned cleanup finished.
The successful run also passed the focused session/snapshot tests, fresh static checks, and source-cleanliness checks. Earlier failed real-provider attempts were verifier-side response-shape mistakes, fixed by using the canonical MCP lifecycle schema and Evidence digest; they were not failures of the provider's restart behavior.
This closes the real-provider gap I noted in my prior handoff. The actual source correction and unit tests remain on the smaller branch linked above; the second branch adds only test scripts and the fork-only CI workflow. Please incorporate only what fits your PR's design, and let me know if you'd like a further failure/recovery control. No competing upstream PR or edits to your branch.
An existing-project session mints its copy identity when the analysis profile is resolved, but the provider copies the saved project for every client it starts. When a dead client was replaced for the same target, the session reused the retired profile, so the snapshot cache could replay answers recorded from the old copy after the caller edited the selected project. A retained-route restart now asks the bound provider to recommit its analysis profile before the replacement client is created, revalidates the staged snapshot against it, and fails closed when the provider cannot recommit its original identity. A provider whose profile is unchanged keeps replaying its cached answers. The restore-after-a-failed-open path still recreates the previous client with the retired profile. It is left out because it spans only a failed open, but it needs the same treatment when that path is next touched. Refs morluto#2358
|
Thank you for the project-selection work and documentation. #7236 now provides shared CLI/MCP configuration for an existing project, verifies and copies it before read-only launch, records its provenance, and rejects incompatible import settings. I’m closing this stacked PR as superseded. The merged interface selects an expanded |
Summary
Adds the selection surface for the existing-project
-processpath introducedby #2150, so a caller can open a project produced outside REA and pay import +
auto-analysis once, outside the provider startup deadline. This is the
product-wiring slice tracked by #2147 (items 1-3); it addresses #1048's
"documented environment variable" selection entry.
REA_GHIDRA_EXISTING_PROJECT(directory holdingrea-project.grezorrea-project.rep) andREA_GHIDRA_EXISTING_PROGRAM(program name for-process).(
REA_GHIDRA_LANGUAGE_ID,REA_GHIDRA_COMPILER_SPEC_ID,REA_GHIDRA_SEED_FILE,REA_GHIDRA_DISABLED_ANALYZERS), which only apply toa fresh import.
AppConfigtoGhidraHeadlessLauncher.existingProject.path and for DOS, raw-binary, and PSP targets.
import_mode: "existing-project-copy"(provenance); the bridge's existing executable SHA-256 check rejects a stale
or mismatched project.
GhidraExistingProjectmoves tosrc/config/and is imported by the launcher,matching the
GhidraLanguageOverridepattern.analyzeHeadlesscommand plus the read-only/copy-firstprovenance and mutation guarantees.
Stacks on #2150 (the launcher
existingProjectbranch). Until #2150 merges,this PR's diff also contains its two commits; I will rebase on
mainonce itlands. Ready for review once #2150 is in, or together with it.
Refs #1048, #2147.
Validation
npm run check— typecheck, lint (incl. module boundaries), format, knip,metadata, architecture guards: pass.
npm run test:focused -- src/config.test.ts src/ghidra/GhidraProvider.behavior.test.ts— 101 pass, including 12 new cases for the existing-project path (pairing,
absolute-path, whitespace, import-time conflicts, profile mode, launcher
hand-off, raw-binary and Windows rejection).
npx vitest run src/ghidra tests/boundary/providers/ghidra— 444 pass, 1skipped (includes feat(ghidra): open pre-imported projects with -process instead of re-importing #2150's launcher boundary tests).
npm run docs:check— pass.Real-provider coverage
Not run in this slice (fixture/behavior harness only), matching #2150's own
note. Separately, the underlying
-process -noanalysisreuse was exercisedagainst a real Ghidra 12.1.4 on Linux: a cold import + auto-analysis of a
445 KB PE took 27.7 s and the warm
-processopen took 6.3 s with identicalanalysis results. I can post that evidence to #1048/#2150 or add a real-provider
lane here if wanted.
AI disclosure
This change (code, tests, and this description) was developed with AI
assistance, under human direction. Every validation command above was executed
on this branch's tip.