Skip to content

fix(ghidra): bound language definition reads before allocation - #2867

Closed
yasshmittal wants to merge 7 commits into
morluto:mainfrom
yasshmittal:fix/ghidra-ldefs-size-before-read
Closed

yasshmittal wants to merge 7 commits into
morluto:mainfrom
yasshmittal:fix/ghidra-ldefs-size-before-read

Conversation

@yasshmittal

@yasshmittal yasshmittal commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2531.

The Ghidra language catalog read each .ldefs file completely with readFile and only then compared its length with the 4 MiB limit. An oversized file was therefore buffered in full before being skipped, so the limit did not bound the allocation it exists to bound.

Problem and expected behavior

readGhidraLanguageCatalog (src/ghidra/GhidraLanguageCatalog.ts) runs when a configured REA_GHIDRA_LANGUAGE_ID is admitted. An installation or extension file larger than MAX_LDEFS_BYTES should be skipped without allocating more than the limit; a small valid sibling should still load.

Change and scope

Each definition is read through the shared readBoundedFileBytes helper (src/process/BoundedFileBytes.ts, already used by GhidraClient). It reads in bounded chunks, stops after the limit plus one byte, and reports overflow; the catalog keeps its existing rule of skipping oversized files. Because the bound is applied while reading rather than from a prior stat, a file that grows during the read is bounded too. The handle is always closed.

Not included: reporting skipped oversized files as a catalog limitation, which would be a contract change beyond this fix.

This builds on the merged #2772: the bounded bytes are still decoded with TextDecoder, so UTF-8 signed definitions keep loading.

Contribution scope: an ordinary fix within existing boundaries; no maintainer scope decision applies.

Contract and boundary impact

  • Semantic owner and earliest changed stage: .ldefs file read in src/ghidra/GhidraLanguageCatalog.ts.

  • Contribution scope fit and linked maintainer decision: not applicable (bug fix).

  • CLI and MCP/tool-catalog contract: unchanged.

  • Provider, bridge, target-format, or platform compatibility: unchanged results; peak memory for oversized definitions is now bounded.

  • Evidence, artifact, provenance, or reconstruction contract: unchanged.

  • Target selection, authority, upstream behavior, and cleanup details: read-only; no Ghidra launch.

  • Generated metadata, package, or installation impact: none.

  • Read existing files or captured data.

Evidence and regression coverage

  • Tests added or updated: tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts.

    • An 8 MiB definition beside a small sibling: the sibling loads, the oversized file is skipped, and the bytes read from it are at most 4 MiB + 1.
    • A definition of exactly 4 MiB is still accepted.
  • Base reproduction or other evidence: on the base revision the first test fails with expected 8388688 to be less than or equal to 4194305, so the whole 8 MiB file was buffered.

  • User-visible CLI/MCP output: none.

  • Remaining proof gaps: no real Ghidra installation run (not required for this read path).

  • Performance (review request): Windows 11 x64, Node 24.21.0, three fresh processes per revision reading a 256 MiB oversized definition beside a small sibling.

    Revision Peak RSS (MiB) Elapsed (ms) CPU (ms)
    main (readFile) 309–343 195–273 172–328
    this PR 57–89 9–32 0–31

    Both revisions return the same catalog. About 55 MiB of the PR figure is the process and loader baseline. Agent-token cost is unchanged.

  • 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

Host: Windows 11, Node.js 24.21.0.

  • npx vitest run --project boundary tests/boundary/filesystem/ghidraLanguageCatalogBound.test.ts: 2 passed (fails on the base revision as above).
  • npm run test:local -- src/ghidra/GhidraLanguageOverride.test.ts: all catalog tests pass. Four profile tests in this file fail identically on the unmodified base revision on Windows and are unrelated.
  • npm run check, npm run verify:test-discovery, npm run verify:module-boundaries: passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: Windows only.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: tightens a resource bound; no new I/O beyond the existing file read.

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-13T18:50:47.970529Z ac832ff 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 Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[High impact] The test-only changes since the previous review appear safe to merge.

Summary

The PR bounds .ldefs reads before buffering oversized files and carries file-close failures through provider selection.

  • Ghidra skips oversized language files without reading them in full.
  • Automatic provider selection stops when Ghidra cleanup is unconfirmed.

Reviews (9) · Last reviewed commit: "test(registry): keep unconfirmed-cleanup..." · Reviewed by Greptile

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14906ae4fb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/ghidra/GhidraLanguageCatalog.ts Resolved
{ id: "x86:LE:32:default", compilerSpecIds: [] },
]);
expect(readBytes.value).toBeGreaterThan(0);
expect(readBytes.value).toBeLessThanOrEqual(LIMIT + 1);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Measure peak memory for the bounded-read regression

In this oversized-file scenario, readBytes measures only bytes delivered by the filesystem, not allocations or peak process-family memory; readBoundedFileBytes retains copied chunks plus a scratch buffer independently of this counter, so this assertion can pass without demonstrating the claimed allocation improvement or detecting a later allocation regression. Record representative before/after elapsed, CPU, and peak-memory results with cold/warm conditions instead of using I/O byte count as the performance proof.

AGENTS.md reference: AGENTS.md:L52-L56

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Measured as requested. Windows 11 x64, Node 24.21.0. Each run is a fresh process reading an installation with a 256 MiB oversized .ldefs beside a small valid sibling; cold and warm are the first and second catalog reads in that process. Peak RSS is process.resourceUsage().maxRSS.

Revision Read Peak RSS (MiB) Elapsed (ms) CPU (ms)
main (readFile) cold 309–342 195–258 172–297
main (readFile) warm 309–343 215–273 234–328
this PR cold 57–89 16–32 0–31
this PR warm 58–89 9–21 16

Ranges cover three runs per revision. Both revisions return the same catalog (oversized file skipped, sibling kept). About 55 MiB of the PR figure is the process and loader baseline, so the oversized definition no longer contributes a full-file allocation. Agent-token cost is unchanged (no output change).

On the test: it keeps the I/O byte bound as a deterministic regression signal (<= 4 MiB + 1 versus the full 8 MiB on main), because process peak-memory assertions are GC-timing dependent and would be flaky in CI. The measurements above are the performance evidence. I'll add the table to the PR description.

Comment thread src/ghidra/GhidraLanguageCatalog.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b034cabe94

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/ghidra/GhidraLanguageCatalog.ts Outdated

const retryLanguageFileCleanup = async (): Promise<void> => {
for (const owner of pendingLanguageFileCleanup) {
await owner.close();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry every retained handle before returning failure

When concurrent catalog resolutions each encounter a close failure while their handles remain open, this set can contain multiple owners. If the earliest owner's retry continues to reject, this await exits the loop before reaching later owners; because insertion order remains unchanged, every future catalog read retries the same first owner and the later handles never receive another cleanup attempt. Attempt every retained owner and aggregate failures after the loop instead of short-circuiting.

AGENTS.md reference: AGENTS.md:L49-L50

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a9da52. retryLanguageFileCleanup now attempts every retained owner, then throws one GhidraLanguageCatalogCleanupError listing the paths still unconfirmed, so a persistently failing first owner no longer starves later ones. Regression: two concurrent resolutions each retain an owner; on the next read the second owner's close is retried and succeeds, and the error names only the first path.

Comment thread src/ghidra/GhidraLanguageCatalog.ts Outdated
const owner = new OwnedFileHandle(await open(path, "r"));
try {
return await readBoundedFileBytes(owner.handle, MAX_LDEFS_BYTES);
} finally {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve read errors when descriptor cleanup also fails

When readBoundedFileBytes rejects (for example, with an I/O error from a damaged or network-backed installation) and owner.close() also rejects, this finally replaces the read failure with the cleanup cause, so GhidraProvider.resolveAnalysisProfile loses the reason the catalog read failed. The newly added owner-retention catch preserves the handle but not that primary failure; capture the read outcome and report both failures, such as with an aggregate cleanup error.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a9da52. The read outcome is captured before cleanup. If the close also fails, GhidraLanguageCatalogCleanupError keeps the read failure as readFailure (and as cause), and the provider reports it as read_failure in diagnostics. Regression: "keeps the read failure when the close also fails" asserts the original read error is retained.

Comment thread src/ghidra/GhidraLanguageCatalog.ts Outdated
pendingLanguageFileCleanup.delete(owner);
} catch (cause: unknown) {
pendingLanguageFileCleanup.add(owner);
throw cause;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark retained close failures as incomplete cleanup

Whenever owner.close() rejects, this branch has established that cleanup remains unconfirmed by retaining the owner, yet it throws only the raw cause. The sole production caller, GhidraProvider.resolveAnalysisProfile, wraps that cause in a ProviderAdapterError without a cleanup observation, so projectAnalysisError emits execution_failure with cleanupIncomplete === false while the handle is still retained; propagate a cleanup-aware failure including the path instead.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1a9da52. Unconfirmed cleanup is thrown as GhidraLanguageCatalogCleanupError with the retained paths. GhidraProvider.resolveAnalysisProfile maps it, through a small languageCatalogFailure helper (keeping the method's complexity unchanged), to ProviderCleanupError (cleanupIncomplete: true, cleanupResources = paths, operation: resolve_analysis_profile). Other read failures keep the existing ProviderAdapterError.

@yasshmittal

Copy link
Copy Markdown
Contributor Author

Thanks for adding cleanup ownership (b034cab). The four follow-up review findings on it are addressed in 1a9da52, on top of your commit:

  • An invalidated descriptor is no longer retained, so it cannot block later catalog reads.
  • Every retained owner is retried, and the remaining failures are reported together.
  • A read failure survives a failing close.
  • Unconfirmed cleanup reaches callers as ProviderCleanupError (cleanupIncomplete).

Validation (Windows 11 x64, Node 24.21.0):

  • New tests/boundary/filesystem/ghidraLanguageCatalogCleanup.test.ts: 4 cases, stable across three runs. All four fail on b034cab.
  • ghidraLanguageCatalogBound.test.ts: passes.
  • src/ghidra: 381 passed. Nine tests fail identically on b034cab on Windows (language-override, generic-pin and symlink profile tests) and are unrelated.
  • tsc --noEmit, oxfmt --check, test discovery, module boundaries and the pre-push check:fast: pass. Lint for the touched files drops from two warnings to the one pre-existing max-params.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1a9da523fa

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

},
}),
);
return err(languageCatalogFailure(cause));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Abort automatic selection on cleanup failures

When provider selection is auto and another provider (for example Hopper) resolves successfully, this becomes a profileError, but AnalysisProviderRegistry.#selectAutomatically filters for evaluations with profiles and selects the lone usable alternate without checking any profileError. A failed catalog close can therefore leave pendingLanguageFileCleanup holding a live descriptor while the target still opens under the other provider, despite ProviderCleanupError requiring cleanup review before another target; propagate cleanup-incomplete profile errors before binding an alternate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Valid, but it reaches into AnalysisProviderRegistry auto-selection, beyond the catalog read. Today #selectAutomatically ignores every profileError when another provider has a profile, so any Ghidra profile failure is skipped, including this cleanup-incomplete one. Changing that means treating cleanupIncomplete profile errors as selection-blocking across all providers, which deserves its own decision and tests. I'd suggest a follow-up issue unless you want it in this PR.

Comment thread src/ghidra/GhidraLanguageCatalog.ts Outdated
// An invalidated descriptor rejects every retry, so retaining it would
// block later reads without ever confirming cleanup.
if (file.owner.handle.fd >= 0) pendingLanguageFileCleanup.add(file);
else pendingLanguageFileCleanup.delete(file);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep ownership after an invalidated close failure

When FileHandle.close() rejects after setting fd negative, OwnedFileHandle deliberately records a sticky, unconfirmed failure, but this line discards the only owner and lets the next catalog read proceed. Fresh evidence after the earlier retention thread is the new else ...delete(file) branch that explicitly abandons this failed owner; keep it in an owning lifecycle scope and continue surfacing cleanup-incomplete rather than treating descriptor invalidation as cleanup confirmation.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This conflicts with the earlier Greptile finding (thread 4261657179). Retaining an invalidated owner in the module-level retry set blocked every later catalog read permanently, because OwnedFileHandle rejects each retry. 1a9da52 therefore reports that close as cleanup-incomplete for the read that hit it, then drops it from the set.

Satisfying both findings needs an owner with a lifecycle: a provider-scoped ArtifactResourceScope (or equivalent) that keeps the unconfirmed owner, reports cleanup-incomplete through provider health or close, and does not gate unrelated reads. That is the structural option I described in thread 4260427590. @morluto, which do you prefer: keep the current non-blocking behavior here, or move retention into a provider scope (in this PR or a follow-up)?

"ghidra",
cause.paths,
{
reason: cause.message,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include close causes in cleanup diagnostics

When an immediate or retried close() rejects with an actionable filesystem error, this diagnostic contains only the wrapper text and paths; the real errors remain in GhidraLanguageCatalogCleanupError.causes. projectAnalysisError projects error.diagnostics but does not traverse nested Error causes, so CLI/MCP users cannot see whether cleanup failed with EIO, EBADF, or another condition that determines remediation; include sanitized per-handle close messages here.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4d31dd5. The ProviderCleanupError diagnostics now include close_failures: [{ path, error }] for every unconfirmed handle (the close error message, for example the EIO or EBADF text), alongside read_failure. Validation is tsc and lint only: the provider profile tests that would exercise this mapping fail on Windows on main as well, so CI is the first execution.

// Concurrent resolutions can each retain an owner.
const roots = [await installation("first"), await installation("second")];
const results = await Promise.allSettled(
roots.map((root) => readGhidraLanguageCatalog(root)),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Synchronize both closes in the concurrency test

If the first installation's directory read and file read finish before the second call reaches readLanguageDefinitionFile, its failed close populates the global pending set and the second call is rejected by retryLanguageFileCleanup without ever opening second.ldefs; second.closeCalls then remains 0 and the later >= 2 assertion flakes. Promise.allSettled waits for completion but provides no barrier, so coordinate the mock to ensure both handles reach close() before either rejection is released.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 4d31dd5. The mock now holds each synchronized close() at a barrier until both handles have reached it, so both reads have already opened their files before either close rejects. The assertions are now exact (closeCalls is 2 for each). The suite passed five consecutive runs.

@morluto

morluto commented Oct 13, 2026

Copy link
Copy Markdown
Owner

Source fixes and publication evidence for the review findings below. Tests and executable checks were skipped at the maintainer's request. Findings that still require a decision or execution evidence remain open.

review thread

A failed close now retains its OwnedFileHandle and retries cleanup before a subsequent catalog read can open another file. The source is live at b034cab; pinned formatting and git diff --check passed. Tests were not run.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4d31dd57b6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (!entry.endsWith(".ldefs")) continue;
const bytes = await readFile(join(directory, entry));
if (bytes.length > MAX_LDEFS_BYTES) continue;
const bytes = await readLanguageDefinitionFile(join(directory, entry));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry cleanup before catalog discovery

When a previously retained handle exists and the next catalog has no readable .ldefs entries—for example, its language directories were removed or became unreadable—this call is never reached because the retry is nested inside readLanguageDefinitionFile. readGhidraLanguageCatalog then returns an empty catalog, so the provider reports a configuration error instead of the pending cleanup-incomplete failure while the descriptor remains owned; run the retry at catalog entry as well as before each file for concurrency.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in bbd21d7. readGhidraLanguageCatalog now retries retained owners at entry, before language directory discovery; the per-file retry still covers concurrent reads. Regression: "reports retained cleanup for a catalog without definitions" retains a failed close, then reads an installation with no .ldefs and expects GhidraLanguageCatalogCleanupError naming the retained path. On 4d31dd5 that read returned an empty catalog. Cleanup suite: 5 passed, three consecutive runs.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bbd21d7b81

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

const failed: { readonly path: string; readonly cause: unknown }[] = [];
for (const file of pendingLanguageFileCleanup) {
const cause = await closeLanguageFile(file);
if (cause !== undefined) failed.push({ path: file.path, cause });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve undefined close rejections

If FileHandle.close() rejects with undefined, which is a legal JavaScript rejection value, closeLanguageFile retains the owner but also returns undefined; this condition consequently records no failure, and the equivalent immediate-close check treats it as success too. Every later catalog read can therefore continue while the retained descriptor repeatedly fails cleanup, so return a tagged close outcome rather than using the rejection value as the success sentinel.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

@morluto
morluto force-pushed the fix/ghidra-ldefs-size-before-read branch from 72a8d54 to 91f0fc0 Compare October 13, 2026 18:10

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 91f0fc0df6

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +309 to +312
const cleanupFailure = evaluations.find(
({ profileError }) => profileError?.cleanupIncomplete === true,
)?.profileError;
if (cleanupFailure !== undefined) return err(cleanupFailure);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve cleanup failures when another probe is cancelled

When Ghidra has already produced a cleanup-incomplete profile error but a slower parallel candidate returns AnalysisCancelledError after the shared signal is aborted, #selectAutomatically returns the cancelled result at lines 302-303 before reaching this scan. The unchanged cancellation return is fresh evidence after the earlier auto-selection fix: the caller still sees only cancellation while pendingLanguageFileCleanup owns an unconfirmed descriptor, so prioritize/aggregate the cleanup error and retain cancellation as its primary diagnostic.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

Comment on lines +72 to +75
throw new GhidraLanguageCatalogCleanupError(
failed.map(({ path }) => path),
failed.map(({ cause }) => cause),
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain original read failures across cleanup retries

When the initial bounded read rejects and owner.close() also rejects, the immediate error records readFailure, but if the retained owner's next close attempt still fails, this retry path constructs a replacement error with only paths and close causes. Because RetainedLanguageFile stores no read outcome, the second caller gets read_failure: null and loses the original EIO or damaged-installation reason while cleanup remains unresolved. Fresh evidence beyond the earlier read-error thread is this retry construction, which bypasses the immediate path that was fixed; retain the per-owner read failure when re-reporting cleanup.

AGENTS.md reference: AGENTS.md:L29-L29

Useful? React with 👍 / 👎.

@morluto
morluto force-pushed the fix/ghidra-ldefs-size-before-read branch from 91f0fc0 to c9fcd89 Compare October 13, 2026 18:28

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c9fcd89f3d

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

const readLanguageDefinitionFile = async (
path: string,
): Promise<Buffer | undefined> => {
await retryLanguageFileCleanup();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize concurrent catalog cleanup decisions

When two profile resolutions overlap, both can pass this check while the cleanup set is empty; if the first handle's close() rejects and retains its owner before the second handle's close resolves successfully, the second path never rechecks the shared set and returns a usable catalog. That resolution can then open a target while the first descriptor's cleanup is still unconfirmed, so serialize the check/read/close lifecycle or gate successful completion atomically on the shared cleanup state.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

Comment on lines +309 to +310
const cleanupFailure = evaluations.find(
({ profileError }) => profileError?.cleanupIncomplete === true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Consult retained cleanup before skipping a candidate

After an earlier Ghidra catalog close has left an owner pending, a later automatic selection for which Ghidra is unsupported (for example, a Hopper database target) takes the eligibility branch at lines 287-298 without resolving a Ghidra profile, so this scan sees no profileError and can select Hopper while cleanup remains unresolved. Fresh evidence after the earlier auto-selection fix is that the new check only inspects evaluated profile errors; consult retained provider cleanup state before filtering candidates.

AGENTS.md reference: AGENTS.md:L19-L19

Useful? React with 👍 / 👎.

yasshmittal and others added 6 commits October 14, 2026 02:43
The language catalog read each .ldefs file in full with readFile and only
then compared its length with the 4 MiB limit, so an oversized file was
buffered completely before being skipped. Read through the shared
readBoundedFileBytes helper, which stops after the limit plus one byte and
reports overflow; oversized definitions are still skipped.

Fixes morluto#2531

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the review findings on retained language-file cleanup:

- Retain an owner only while its descriptor is still valid; a close that
  invalidated the handle can never be retried and no longer blocks every
  later catalog read.
- Retry every retained owner and report the remaining failures together
  instead of stopping at the first.
- Keep a read failure as the primary cause when the close also fails.
- Report unconfirmed cleanup as GhidraLanguageCatalogCleanupError, which
  the provider maps to ProviderCleanupError (cleanupIncomplete) with the
  retained paths.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Include every unconfirmed handle's close error in the cleanup diagnostics
(close_failures), so callers see the filesystem condition behind
cleanupIncomplete instead of only the wrapper message.

Hold both synchronized closes in the concurrency regression until each has
been reached, so the test no longer depends on read scheduling and asserts
exact close attempts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The retry ran only before each definition read, so a catalog with no
readable .ldefs entries returned an empty catalog while a retained handle
stayed unconfirmed, and the provider reported a configuration error
instead of incomplete cleanup. Retry retained owners when the catalog read
starts as well; the per-file retry still covers concurrent reads.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@morluto
morluto force-pushed the fix/ghidra-ldefs-size-before-read branch from c9fcd89 to ac832ff Compare October 13, 2026 18:43
@morluto morluto added area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior bug Something isn't working labels Oct 14, 2026
morluto added a commit that referenced this pull request Oct 14, 2026
Share tagged readiness observations, retain partial provider facts, authenticate bridge identity, bound diagnostics, and preserve cancellation and lost-session reasons. Fail closed for unparsed MIPS ABI attributes and macOS saved Hopper databases without a script-capable bridge route.

Reviewed fixes: #2010, #2108, #2513, #2695, #2731, #2771, #2828, #2867, #2868, #2870, #2880, #2919, #2945, #2961, #2981, #2998, #3000, #3002.

Validation: 285 focused source/boundary tests passed. Real Ghidra, IDA, Linux Hopper, and Windows provider runs were not repeated.

BREAKING CHANGE: MIPS targets with unresolved GNU ABI attributes and saved Hopper databases on macOS are refused rather than advertised as supported.
@kaoru0822-kitauji kaoru0822-kitauji added the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
@kaoru0822-kitauji

Copy link
Copy Markdown
Collaborator

CI-fix track: this change is already on main. After merging current main into this branch, every file has no remaining diff, tests included: the bounded language-definition read in GhidraLanguageCatalog.ts, the registry change, both boundary tests, and the cleanup-error mapping, which main has in GhidraProvider.ts via d4bd65c (it lists #2867 among its reviewed fixes). The failing Static checks job was the lint error main had at the time (see #2993), not this PR. I didn't push a merge, since it would be empty. This PR looks safe to close as superseded.

@kaoru0822-kitauji kaoru0822-kitauji removed the ci-fix-wip Claimed by the CI-fix track label Oct 14, 2026
The unconfirmed-cleanup auto-selection case took the binding-failures
describe block past the 150-line max-lines-per-function lint limit. Move
it, unchanged, into its own describe block.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@CassieFox23

Copy link
Copy Markdown
Contributor

Heads up: main already has this change in d4bd65c. The code is in src/ghidra/GhidraLanguageCatalog.ts, and skips an oversized definition without buffering it beyond the catalog limit covers it. It is listed on tracker #3582. If this PR still adds something main doesn't have, please say so here and I'll take it off the list. Thanks for the fix!

🤖 Generated with Claude Code (Sonnet 5.5, verified by Opus 5.5) 🦊

@morluto

morluto commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Superseded by the Ghidra language-catalog boundary and cleanup ownership changes delivered in d4bd65c53. Main bounds reads before allocation, retains unresolved descriptor cleanup ownership for retry, and aborts provider fallback when cleanup is unconfirmed; boundary/registry regressions cover the failure paths. Closing this earlier proposal; #2531 is already resolved.

@morluto morluto closed this Oct 15, 2026
@morluto

morluto commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Thank you @yasshmittal for examining oversized Ghidra language definitions and cleanup ownership. Main bounds the definition read and retains failed-cleanup ownership.

@morluto morluto added the provider: ghidra Analysis provider / engine: ghidra label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: native Native analysis and decompilation, including Ghidra, IDA, and Hopper analysis behavior bug Something isn't working provider: ghidra Analysis provider / engine: ghidra

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(ghidra): oversized language files allocate beyond the catalog limit

4 participants