Skip to content

fix(ghidra): warn when Borland SEH handlers fall outside the function body - #2981

Closed
sx4im wants to merge 7 commits into
morluto:mainfrom
sx4im:fix/2926-seh-handler-limitations
Closed

sx4im wants to merge 7 commits into
morluto:mainfrom
sx4im:fix/2926-seh-handler-limitations

Conversation

@sx4im

@sx4im sx4im commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #2926. Delphi and C++Builder register exception handlers through the SEH chain with a push imm32; push fs:[reg]; mov fs:[reg], esp prologue. Ghidra's flow model never follows that chain, so the handler block lands outside the analyzed function body, and REA reported the function's callees, strings, and references as complete with no hint that a handler region was missing.

Problem and expected behavior

Smallest trigger: any Delphi function containing a try block. The compiler emits the SEH registration prologue at the function head; Ghidra keeps the pushed handler address out of the function body because nothing in its flow graph reaches it. REA's function views then silently presented incomplete results as complete. Expected: a reader of procedure_info, procedure_callees, or analyze_function is told when a known handler region is excluded, the same way #2326/#2360 handled truncated bodies from terminal calls.

Change and scope

bridge/ghidra/ReaGhidraBridge.java gains sehHandlerLimitations, which scans a function's instructions for the consecutive prologue triple (push with a 32-bit scalar operand, push with an fs: segment memory operand, mov to an fs: segment operand from esp). When the pushed handler address falls outside function.getBody(), the six function views that already carry terminal-call qualifications (procedure_pseudo_code, procedure_assembly, read_function_instructions, procedure_callees, procedure_callers, procedure_info, plus the analyze_function dossier) include an Evidence limitation naming the registration site and the excluded handler address.

I took the issue's report branch rather than the seed-as-code branch: the bridge only observes and reports, it does not rewrite Ghidra function bodies. Detection is strict by design. A partial match emits nothing, so a missed variant keeps the old behavior instead of producing noise.

src/ghidra/GhidraAnalysisProfile.ts versions the boundary-observation contract to ghidra-terminal-call-limitations-v3 so older snapshots cannot replay unqualified results. docs/ghidra-provider.md documents the new observation.

Follow the contribution scope. Unresolved scope, authority, side effects, or required verification block integration: not applicable, this is an ordinary fix within existing boundaries (read-only observation, no target execution, injection, mutation, or protection recovery).

Contract and boundary impact

  • Semantic owner and earliest changed stage: Ghidra provider bridge (ReaGhidraBridge.java), function-view result shaping.
  • Contribution scope fit and linked maintainer decision: ordinary bug fix within existing boundaries; no maintainer scope decision required.
  • CLI and MCP/tool-catalog contract: unchanged tool shapes; results may carry additional limitation strings.
  • Provider, bridge, target-format, or platform compatibility: bridge-only; the pattern is x86-32 specific and inert elsewhere (a 32-bit push imm32 scalar never matches in 16-bit code, and the fs: triple does not occur in 64-bit code).
  • Evidence, artifact, provenance, or reconstruction contract: function_boundary_observations v2 to v3; snapshots recorded under v2 fail profile match on replay, which is the intended invalidation.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata, 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: tests/boundary/mcp/ghidraEvidenceMcp.test.ts now expects the v3 contract string.
  • Base reproduction or other evidence: the updated test failed against the v2 profile (red) and passes after the bump (green). The Java detection itself could not be executed here; every Ghidra API call it uses (getMnemonicString, getNumOperands, getOpObjects, Scalar/Register checks, getDefaultOperandRepresentation, function.getBody().contains) already appears in the same file, and the file parses clean under tree-sitter's Java grammar.
  • User-visible CLI/MCP output (if applicable): a new limitation string, e.g. "Ghidra Listing shows a Borland/Delphi SEH frame registration at 0x5353ac (push 0x5355c3 followed by fs-segment stack chaining); the handler 0x5355c3 lies outside this procedure's body, so callees, strings, and cross-references may omit the handler region."
  • Remaining proof gaps: no execution against a real Ghidra instance with a Delphi binary; the real-Ghidra CI lane is the first place this runs against live analysis.

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 test:focused -- tests/boundary/mcp/ghidraEvidenceMcp.test.ts — 4/4 passed (1 failed before the profile change, confirming the red step)
  • npm run test:focused -- src/ghidra/GhidraFunctionValues.test.ts — 50/50 passed
  • npm run test:focused -- src/ghidra/GhidraProvider.behavior.test.ts src/ghidra/GhidraSnapshotCache.test.ts — 60/60 passed
  • npm run check:fast — typecheck and lint green
  • npm run docs:check — green
  • npm run verify:test-discovery — 1112 test files, green

Compatibility, safety, and release

  • Breaking changes or migration steps: none. The v2 to v3 contract bump intentionally invalidates old analysis snapshots on replay; they re-run instead of replaying unqualified results.
  • Real Hopper/Ghidra, browser, or OS coverage: real Ghidra lane unavailable in this sandbox (no Ghidra installed). Stated plainly rather than assumed; the detection runs first in CI's real-Ghidra lane.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only observation of the analyzed program; no new process, network, or mutation surface.

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.

… body

Delphi/C++Builder register exception handlers through the SEH chain
(push imm32; push fs:[reg]; mov fs:[reg], esp). Ghidra's flow model does
not follow the chain, so the handler region lands outside the analyzed
function body while procedure_info, procedure_callees, and
analyze_function silently report callees, strings, and references as
complete (fixes morluto#2926).

Detect the prologue triple in the bridge and report excluded handler
registrations as Evidence limitations on the same six function views that
already carry terminal-call qualifications, following the morluto#2326/morluto#2360
precedent. Version the boundary-observation contract to
ghidra-terminal-call-limitations-v3 so older snapshots cannot replay
unqualified results.

Validation: red->green boundary contract test for the version bump; MCP
boundary evidence test, function-values tests, provider behavior and
snapshot-cache tests, check:fast, docs:check, verify:test-discovery green.
Real Ghidra host lane unavailable here (no Ghidra installed); the Java
change mirrors the existing noReturnCallLimitations call pattern and every
Ghidra API call used already appears in the same file.
@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-13T21:42:18.978683Z 961672c 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.

@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: b8b88f83ce

ℹ️ 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 bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3379 to +3380
|| !isFsSegmentPush(pushSegment)
|| !isFsSegmentMove(moveSegment)) {

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 Require both FS operands to address the same slot

When x86 input uses different FS locations in the last two instructions (for example, push fs:[0x18] followed by mov fs:[0], esp), these independent predicates still accept it because they only check for fs:; an outside immediate is then reported as a definite Borland/Delphi SEH registration even though the previous SEH head was not chained. Compare the normalized FS effective-address operands, or qualify the result as a heuristic, before producing this Evidence.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3332 to +3335
List<Instruction> materialized = new ArrayList<>();
for (Instruction instruction : instructions) {
monitor.checkCancelled();
materialized.add(instruction);

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 Stream the boundary scan instead of retaining every instruction

When procedure_info, procedure_callees, or procedure_callers supplies its lazy instruction iterator here, this new loop retains every instruction in a request-unbounded ArrayList, whereas the previous terminal-call scan operated in constant space. A very large or malformed function body can therefore exhaust the headless Ghidra heap before returning one of these otherwise lightweight views; run the no-return check and a three-instruction rolling SEH window in a single pass instead.

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

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with two non-blocking concerns remaining from earlier reviews.

Findings

  1. P2 Handler detection is untested ▶
  2. P2 Skipped XOR causes false warnings ▶
Fix with agent prompt
### Issue 1
bridge/ghidra/ReaGhidraBridge.java:3348-3355
The changed test supplies a fixed terminal-call warning and only updates the expected profile version. It would still pass if `sehHandlerLimitations` always returned an empty list, so missing or false handler warnings would go unnoticed.

Add tests using decoded instructions for an excluded handler, a handler inside the body, and partial or unrelated triples.

### Issue 2
bridge/ghidra/ReaGhidraBridge.java:3550-3554
`isZeroedByXor` treats address order as execution order. When a branch reaches the registration triple without running a nearby `xor eax,eax`, the backward scan still accepts that XOR as proof that `eax` is zero. A write to another FS slot can then produce a false warning about an excluded SEH handler.

Only accept the XOR when the path to the triple cannot bypass it; otherwise leave the slot unproven.

---

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

Summary

The PR warns when a recognized Win32 SEH handler falls outside Ghidra's analyzed function body.

  • Ghidra function results now flag handlers outside the function body.

Supersession could not be checked because GitHub access was unavailable.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Scan function instructions] --> B[Keep terminal-call warnings]
  B --> C{Recognized Win32 SEH registration?}
  C -->|No| F[Return function observation]
  C -->|Yes| D{Handler inside function body?}
  D -->|Yes| F
  D -->|No| E[Add excluded-handler warning]
  E --> F
Loading

Reviews (7) · Last reviewed commit: "fix(ghidra): qualify SEH attribution, ho..." · Reviewed by Greptile

Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3348 to +3355
private List<String> sehHandlerLimitations(
List<Instruction> instructions, Function function) throws Exception {
List<String> limitations = new ArrayList<>();
for (int index = 0; index + 2 < instructions.size(); index++) {
monitor.checkCancelled();
Address handler = sehHandlerAddress(
instructions.get(index), instructions.get(index + 1), instructions.get(index + 2));
if (handler == null || function.getBody().contains(handler)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Handler detection is untested

The changed test supplies a fixed terminal-call warning and only updates the expected profile version. It would still pass if sehHandlerLimitations always returned an empty list, so missing or false handler warnings would go unnoticed.

Add tests using decoded instructions for an excluded handler, a handler inside the body, and partial or unrelated triples.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bridge/ghidra/ReaGhidraBridge.java
Line: 3348-3355

Comment:
**Handler detection is untested**

The changed test supplies a fixed terminal-call warning and only updates the expected profile version. It would still pass if `sehHandlerLimitations` always returned an empty list, so missing or false handler warnings would go unnoticed.

Add tests using decoded instructions for an excluded handler, a handler inside the body, and partial or unrelated triples.

---

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

Require the push imm32 / push fs: / mov fs:,esp triple to be
address-consecutive and to chain the same FS slot, and require the mov
source to be exactly ESP, so unrelated instruction sequences cannot
produce a misleading handler warning. Scan function boundaries in a
single pass with a three-instruction rolling window instead of
materializing the instruction stream, keeping the lazy procedure_pseudo_code
iterator path constant-space. The noReturnCallLimitations(Iterable)
signature is unchanged for the conformance probe.

@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: 8611926cfa

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

Object[] operands = pushImmediate.getOpObjects(0);
if (operands.length != 1
|| !(operands[0] instanceof Scalar scalar)
|| scalar.bitLength() != 32) {

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 Check x86-32 mode before matching SEH

For supported 16-bit x86 inputs, an operand-size-prefixed PUSH imm32 still produces a 32-bit Scalar (and the instruction is also legal in long mode), so this condition does not establish the x86-32 mode for which the Borland pattern is defined. If such code contains the following FS push/move triple, every view using functionBoundaryLimitations reports a definite Delphi handler and can truncate or reject the immediate when converting it through a differently sized address space; gate the inference on the actual x86-32 language/context before emitting Evidence.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3406 to +3407
return currentProgram.getAddressFactory().getDefaultAddressSpace()
.getAddress(scalar.getUnsignedValue());

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 the handler's Ghidra address space

When the matched function is in an overlay or another non-default Ghidra address space, reconstructing the immediate unconditionally in the default space discards its identity: function.getBody().contains(handler) then reports false even when the same-offset handler is in the function's overlay, and the limitation cites an unrelated default-space address. Resolve the address from Ghidra's operand/reference facts, or leave it unknown when the address space is ambiguous, before testing body membership.

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

Useful? React with 👍 / 👎.

…ress space

The Borland/Delphi SEH prologue pattern is defined for 32-bit x86
protected mode, but the matcher fired for any program: on 16-bit x86 an
operand-size-prefixed PUSH imm32 still yields a 32-bit Scalar, and the
instruction is also legal in long mode, so a matching FS push/move triple
produced a definite-Delphi warning for the wrong architecture. Gate the
inference on the program language being 32-bit x86 (address size read
from the Ghidra language ID) and report no registration otherwise.

Also resolve the handler immediate in the matched code's own address
space instead of the default space: for a function analyzed in an
overlay space the old reconstruction failed body membership against the
wrong space and cited an unrelated default-space address.

@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: b40ba8d50e

ℹ️ 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 bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3355 to +3356
* handler through the SEH chain, so callees, strings, and references below
* silently omit the handler region unless the reader is warned.

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 Propagate the warning to procedure_references

When the matched function is queried through procedure_references, procedureReferences still returns a raw result at lines 1052–1090 and functionBoundaryObservationOperations at src/ghidra/GhidraFunctionValues.ts:408-417 omits this operation, so its Evidence cannot carry the new warning even though its returned edges omit exactly the handler region described here. Wrap this operation with the same boundary scan and parser envelope; otherwise the direct reference view remains silently incomplete.

AGENTS.md reference: AGENTS.md:L25-L25

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3400 to +3401
String pushSlot = fsSegmentSlot(pushSegment, 0);
if (pushSlot == null || !pushSlot.equals(fsSegmentSlot(moveSegment, 0))) {

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 Require the SEH head rather than any equal FS slot

When a 32-bit PE contains push addr; push fs:[0x18]; mov fs:[0x18], esp with addr outside the body, this equality check accepts it even though FS:[0x18] is the TEB self pointer rather than the FS:[0] exception-list head; the same problem applies to a register operand whose value is not proven zero. The newly added equality check is fresh evidence after the prior slot-mismatch comment: it proves only that the two expressions match, not that they address the SEH chain, so require a literal/proven zero offset or qualify the result as an inference.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Comment on lines +3413 to +3414
return pushImmediate.getAddress().getAddressSpace()
.getAddress(scalar.getUnsignedValue());

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 Use operand references to resolve the handler address space

When an overlay instruction's handler operand has a Ghidra reference into the default space, these lines manufacture an overlay-space address solely because the instruction resides there; that can suppress the warning if the same offset belongs to the overlay function body or report the wrong handler otherwise. The final remap is fresh evidence after the earlier address-space comment because it replaces the unconditional default-space assumption with an equally unconditional instruction-space assumption; prefer the operand/reference target and preserve ambiguity when no unique target exists.

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

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
*/
private boolean isX86_32BitMode() {
String[] fields = currentProgram.getLanguageID().getIdAsString().split(":");
return fields.length > 2 && fields[0].equals("x86") && fields[2].equals("32");

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 Restrict the SEH claim to Win32 targets

For a caller-selected 32-bit x86 ELF, raw image, or x86:LE:32:System Management Mode program, this predicate succeeds even though FS:[0] is not established as a Win32 TIB exception-list head, so a matching sequence is reported as definite Borland/Delphi Evidence. The final LanguageID-only predicate is fresh evidence after the earlier architecture comment: it proves processor width but not the executable/ABI context, so gate the claim on Win32/PE context or present it as a heuristic.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

…ete reference coverage

The Borland/Delphi SEH prologue matcher fired for any 32-bit x86 program:
on 32-bit ELF or raw images FS:[0] is not the Win32 thread-information
block, so a matching push-triple produced a definite-Delphi warning for
the wrong ABI. Gate the claim on the program's executable format naming
the PE loader, not just the language ID.

Also require the chained slot to be FS:[0] itself (the exception-list
head): the prior equality check accepted any matching slot, but FS:[0x18]
is the TEB self-pointer, not an SEH registration.

Resolve the pushed handler through the immediate operand's Ghidra
references when they exist — the reference target carries the true
address space — instead of unconditionally remapping into the
instruction's space; an ambiguous target reports no registration rather
than manufacturing an address.

Finally, wrap procedure_references in the function-observation envelope
so its Evidence carries the SEH limitation like the other function views.
Comment thread bridge/ghidra/ReaGhidraBridge.java 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: eb46d6958a

ℹ️ 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 bridge/ghidra/ReaGhidraBridge.java Outdated
return null;
}
String pushSlot = fsSegmentSlot(pushSegment, 0);
if (!"fs:[0]".equals(pushSlot) || !pushSlot.equals(fsSegmentSlot(moveSegment, 0))) {

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 Recognize zero-valued register slots

When a Delphi prologue uses the documented fs:[reg] form after proving the register zero (for example xor eax,eax; ...; push fs:[eax]; mov fs:[eax],esp), fsSegmentSlot yields fs:[eax], so this exact fs:[0] test discards a real SEH frame; it likewise misses Ghidra's fs:[0x0] spelling for a literal zero. These ordinary Borland procedures therefore still return silently incomplete handler callees, strings, and references. Determine the effective zero offset from Ghidra's operand/p-code facts, including a register proven zero, instead of comparing one display spelling.

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

Useful? React with 👍 / 👎.

The literal "fs:[0]" slot check rejected the register-based SEH
prologue form from morluto#2926 (push imm32; push fs:[eax]; mov fs:[eax],
esp) even when the register is proven zero, and missed Ghidra's
"fs:[0x0]" spelling, so those handlers stayed unwarned. Accept a
slot proven to be FS:[0]: a literal zero in any rendered spelling,
or fs:[reg] whose latest writer in the scanned prologue history is
xor reg,reg with no intervening writer. Scanning stops at calls,
whose volatile-register clobbers Ghidra does not model. Non-zero
slots (for example the FS:[0x18] TEB self-pointer) stay rejected.
Comment on lines +3536 to +3539
for (int index = history.size() - 4; index >= 0; index -= 1) {
Instruction candidate = history.get(index);
if (mnemonic(candidate).equals("CALL")) {
return false;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Skipped XOR causes false warnings

isZeroedByXor treats address order as execution order. When a branch reaches the registration triple without running a nearby xor eax,eax, the backward scan still accepts that XOR as proof that eax is zero. A write to another FS slot can then produce a false warning about an excluded SEH handler.

Only accept the XOR when the path to the triple cannot bypass it; otherwise leave the slot unproven.

Prompt To Fix With AI
This is a comment left during a code review.
Path: bridge/ghidra/ReaGhidraBridge.java
Line: 3536-3539

Comment:
**Skipped XOR causes false warnings**

`isZeroedByXor` treats address order as execution order. When a branch reaches the registration triple without running a nearby `xor eax,eax`, the backward scan still accepts that XOR as proof that `eax` is zero. A write to another FS slot can then produce a false warning about an excluded SEH handler.

Only accept the XOR when the path to the triple cannot bypass it; otherwise leave the slot unproven.

---

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

@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: b90ff8b739

ℹ️ 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 on lines +3536 to +3537
for (int index = history.size() - 4; index >= 0; index -= 1) {
Instruction candidate = history.get(index);

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 Require the zeroing XOR to reach the matched triple

The newly added flat-history scan is fresh evidence after the earlier zero-slot comment: in a 32-bit PE whose function body places an unrelated xor eax,eax basic block immediately before, in address order, a separately reached block containing the triple, this backward scan treats the XOR as the reaching definition without checking any CFG edge or dominance. isFsZeroSlot can therefore emit definite SEH Evidence while the FS offset on the triple's actual path is unknown; require a reaching/dominating definition (or keep the claim explicitly heuristic).

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
return;
}
limitations.add(
"Ghidra Listing shows a Borland/Delphi SEH frame registration at "

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 the Borland attribution as an inference

The final PE/FS:[0] gates are fresh evidence after the earlier matcher comments: they establish standard Win32 SEH chaining, but neither this path nor isWin32SehTarget establishes Borland compiler identity. A hand-written or non-Borland routine using the same valid three instructions therefore records “shows a Borland/Delphi” as an observation, which can mislead compiler attribution; call it a Win32 SEH registration or explicitly qualify the Borland association as inferred.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

Comment thread bridge/ghidra/ReaGhidraBridge.java Outdated
Instruction pushSegment,
Instruction moveSegment,
List<Instruction> history) {
if (!isWin32SehTarget()

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 Hoist target eligibility out of the instruction loop

When any affected procedure view scans a large ELF, 64-bit, or otherwise non-Win32 function, the matcher reaches this target predicate for every three-instruction window before any mnemonic check; isWin32SehTarget() consequently performs getIdAsString().split(":") and related target work once per instruction even though target eligibility is invariant. This adds avoidable per-instruction allocations to all boundary scans where SEH cannot apply; compute eligibility once per function scan or reject instruction shape before invoking it.

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

Useful? React with 👍 / 👎.

sx4im added 2 commits October 14, 2026 02:13
isZeroedByXor treated address order as execution order: a branch
between xor reg,reg and the SEH registration triple could bypass the
xor, but the backward scan still accepted it as proof of zero,
producing false warnings. Stop the scan at any control-flow
instruction (call, jump, terminal), not just calls.
…gle-entry xor

Codex P2 4264022570: the Win32 SEH gates establish chaining, not Borland
compiler identity, so the Evidence now reports a Win32 SEH frame
registration with the Borland/Delphi codegen called out as inferred.

Codex P2 4264022579: compute isWin32SehTarget() once per function scan
and pass it down instead of re-evaluating it per three-instruction
window.

Codex P2 4264022547: the xor reaching-definition scan now also requires
the triple to be singly entered. Any incoming flow reference to the
triple's first address (a branch into it, a loop back-edge) means the
zeroing xor may have been bypassed, so the register is not proven
zero. Plain fall-through leaves no reference, so the straight-line
Borland prologue is unaffected.

@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: 961672cd5f

ℹ️ 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 on lines +3582 to +3584
Address tripleStart = history.get(history.size() - 3).getAddress();
for (Reference reference :
currentProgram.getReferenceManager().getReferencesTo(tripleStart)) {

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 Check every entry into the XOR-to-triple path

In a 32-bit PE with an out-of-body immediate, if another basic block branches to an intermediate instruction between xor eax,eax and push handler (for example the saved-EBP push), that path reaches the triple without zeroing EAX. This helper queries incoming references only for tripleStart, so the matcher accepts the XOR and can emit an SEH limitation for an unproven FS:[eax] slot. The newly added single-entry helper is fresh evidence after the earlier reaching-definition comment; verify fallthrough and incoming edges for every instruction from the XOR through the triple.

AGENTS.md reference: AGENTS.md:L5-L5

Useful? React with 👍 / 👎.

"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",

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 Wrap reference results in the MCP harness

When a boundary test calls procedure_references through the default connectGhidraMcp fixture, tests/boundary/mcp/ghidraMcpHarness.ts:271-279 still omits that operation from its envelope set and therefore returns the bare reference object. Adding the operation here makes parseGhidraFunctionResult reject that fixture response as unreadable_output, so the shared harness no longer models an operation it advertises. This changed parser membership is fresh evidence beyond the earlier propagation comment; add the operation to the harness envelope set (ideally from the same owner).

AGENTS.md reference: AGENTS.md:L27-L27

Useful? React with 👍 / 👎.

@CassieFox23

Copy link
Copy Markdown
Contributor

TL;DR: The new Java compiles and runs in real Ghidra 12.1.4 on Linux. On a hand-made 32-bit PE, head 961672c warns when the handler sits outside the body. It does so for both SEH forms, and stays quiet in the other four cases I built.

The head moved while I tested. I ran a61cccd first and then 961672c, so the table shows both.

Results

"Warns" means the SEH limitation line shows up in rea function output. "Before" is the merge base 2895a18. "Earlier head" is a61cccd. "Head" is 961672c. Ghidra reports the format as "Portable Executable (PE)", so the new check opens.

Case Before Earlier head Head
A: fs:[0], handler outside the body quiet warns warns
B: the issue's xor eax,eax and fs:[eax], handler outside quiet warns warns
C: fs:[0], handler inside the body quiet quiet quiet
D: fs:[0x18] decoy quiet quiet quiet
E: a jump sits between the xor and the registration quiet quiet quiet
F: a jump lands on the registration and skips the xor quiet warns quiet

Case F is what the newest commit targets. Case E is quiet by design. Ghidra shows the operands as PUSH dword ptr FS:[0x0] and PUSH dword ptr FS:[EAX], and the code matches both. Apart from ids, digests, the profile version and timing, the rest of each output matches before.

Unit file Node 22.23.1 Node 24.18.0 Node 26.11.1 Before, Node 24.18.0
GhidraFunctionValues.test.ts 52 pass 52 pass 52 pass 3 of 52 fail
ghidraEvidenceMcp.test.ts 4 pass 4 pass 4 pass 1 of 4 fails

Both a61cccd and 961672c passed these files on all three Node versions. These unit files check the result envelope and the profile string. None of them runs the detection. The Ghidra run is the only proof for it.

Not run

  • A real Delphi or C++Builder program. The PE is hand-made.
  • procedure_references through the CLI. I found no command for it.
  • A jump that lands between the xor and the registration, as in the open Codex note.
  • 16-bit, 64-bit, ELF and raw-binary inputs.
  • The full test suite and the CI lanes.

Thanks, sx4im, for the fix and for the quick follow-up commits.

Test setup
  • Box: Nobara 44 (Fedora 44 base), Linux 7.2.9
  • CPU: AMD Ryzen 9 5900X, 12 cores / 24 threads
  • RAM: 32 GB DDR4-3600
  • Node: 22.23.1, 24.18.0, 26.11.1
  • Head: 961672c
  • Base: 2895a18
  • Other: Ghidra 12.1.4 (Apache-2.0)
  • Other: Temurin JDK 21.0.12.1+1 (GPL-2.0-only WITH Classpath-exception-2.0)
Commands

The before tree is the head tree with three files put back to 2895a18. They are bridge/ghidra/ReaGhidraBridge.java, src/ghidra/GhidraAnalysisProfile.ts and src/ghidra/GhidraFunctionValues.ts. Its tests are the head's.

GHIDRA_INSTALL_DIR=~/.local/opt/ghidra_12.1.4_PUBLIC JAVA_HOME=~/.local/opt/jdk-21.0.12.1+1
rea inspect-native-load-image rea-seh-test.exe --provider ghidra --format json --full-output   # exit 0
rea function rea-seh-test.exe 0x401040 --provider ghidra --format json --full-output           # exit 0
# the same for 0x401080 (B), 0x4010c0 (C), 0x401100 (D), 0x401140 (E), 0x401180 (F): all exit 0
node scripts/run-development-tests.mjs focused src/ghidra/GhidraFunctionValues.test.ts          # head: exit 0 on Node 22, 24, 26; before: exit 1
node scripts/run-development-tests.mjs focused tests/boundary/mcp/ghidraEvidenceMcp.test.ts     # head: exit 0 on Node 22, 24, 26; before: exit 1
Test PE bytes (image base 0x400000)
0x401000 entry  e83b000000e876000000e8b1000000e8ec000000e827010000e86201000031c0c3
0x401040 A      558bec680012400064ff35000000006489250000000090648f050000000083c4045dc3
0x401080 B      558bec31c055682012400064ff306489209031c05a59596489105dc3
0x4010c0 C      558bec68e710400064ff35000000006489250000000085c0750d90648f050000000083c4045dc3e8d4000000648f050000000083c4045dc3
0x401100 D      558bec684012400064ff351800000064892518000000905dc3
0x401140 E      558bec31c085db74019055686012400064ff306489209031c05a59596489105dc3
0x401180 F      558bec85db740231c0688012400064ff306489209031c05a59596489105dc3
0x4011c0 helper b82a000000c3
handlers (call helper, ret): 0x401200 A, 0x401220 B, 0x401240 D, 0x401260 E, 0x401280 F
C pushes 0x4010e7, a spot inside its own body that a jnz reaches
sha256 a0961af62c8fde414ce002385fb250fe6633b0fa14ba3069f4eecded8f5b8817

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

@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.
@sx4im

sx4im commented Oct 14, 2026

Copy link
Copy Markdown
Contributor Author

Closing this one out. morluto's d4bd65c landed the SEH handler fix on main with a simpler take that covers #2926, and it lists this PR among the reviewed fixes, so there's nothing left for this branch to do. Thanks to everyone who reviewed along the way.

@sx4im sx4im closed this Oct 14, 2026
@tarasovtt29-ui

Copy link
Copy Markdown

Summary

Fixes #2926. Delphi and C++Builder register exception handlers through the SEH chain with a push imm32; push fs:[reg]; mov fs:[reg], esp prologue. Ghidra's flow model never follows that chain, so the handler block lands outside the analyzed function body, and REA reported the function's callees, strings, and references as complete with no hint that a handler region was missing.

Problem and expected behavior

Smallest trigger: any Delphi function containing a try block. The compiler emits the SEH registration prologue at the function head; Ghidra keeps the pushed handler address out of the function body because nothing in its flow graph reaches it. REA's function views then silently presented incomplete results as complete. Expected: a reader of procedure_info, procedure_callees, or analyze_function is told when a known handler region is excluded, the same way #2326/#2360 handled truncated bodies from terminal calls.

Change and scope

bridge/ghidra/ReaGhidraBridge.java gains sehHandlerLimitations, which scans a function's instructions for the consecutive prologue triple (push with a 32-bit scalar operand, push with an fs: segment memory operand, mov to an fs: segment operand from esp). When the pushed handler address falls outside function.getBody(), the six function views that already carry terminal-call qualifications (procedure_pseudo_code, procedure_assembly, read_function_instructions, procedure_callees, procedure_callers, procedure_info, plus the analyze_function dossier) include an Evidence limitation naming the registration site and the excluded handler address.

I took the issue's report branch rather than the seed-as-code branch: the bridge only observes and reports, it does not rewrite Ghidra function bodies. Detection is strict by design. A partial match emits nothing, so a missed variant keeps the old behavior instead of producing noise.

src/ghidra/GhidraAnalysisProfile.ts versions the boundary-observation contract to ghidra-terminal-call-limitations-v3 so older snapshots cannot replay unqualified results. docs/ghidra-provider.md documents the new observation.

Follow the contribution scope. Unresolved scope, authority, side effects, or required verification block integration: not applicable, this is an ordinary fix within existing boundaries (read-only observation, no target execution, injection, mutation, or protection recovery).

Contract and boundary impact

  • Semantic owner and earliest changed stage: Ghidra provider bridge (ReaGhidraBridge.java), function-view result shaping.
  • Contribution scope fit and linked maintainer decision: ordinary bug fix within existing boundaries; no maintainer scope decision required.
  • CLI and MCP/tool-catalog contract: unchanged tool shapes; results may carry additional limitation strings.
  • Provider, bridge, target-format, or platform compatibility: bridge-only; the pattern is x86-32 specific and inert elsewhere (a 32-bit push imm32 scalar never matches in 16-bit code, and the fs: triple does not occur in 64-bit code).
  • Evidence, artifact, provenance, or reconstruction contract: function_boundary_observations v2 to v3; snapshots recorded under v2 fail profile match on replay, which is the intended invalidation.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata, 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: tests/boundary/mcp/ghidraEvidenceMcp.test.ts now expects the v3 contract string.
  • Base reproduction or other evidence: the updated test failed against the v2 profile (red) and passes after the bump (green). The Java detection itself could not be executed here; every Ghidra API call it uses (getMnemonicString, getNumOperands, getOpObjects, Scalar/Register checks, getDefaultOperandRepresentation, function.getBody().contains) already appears in the same file, and the file parses clean under tree-sitter's Java grammar.
  • User-visible CLI/MCP output (if applicable): a new limitation string, e.g. "Ghidra Listing shows a Borland/Delphi SEH frame registration at 0x5353ac (push 0x5355c3 followed by fs-segment stack chaining); the handler 0x5355c3 lies outside this procedure's body, so callees, strings, and cross-references may omit the handler region."
  • Remaining proof gaps: no execution against a real Ghidra instance with a Delphi binary; the real-Ghidra CI lane is the first place this runs against live analysis.

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 test:focused -- tests/boundary/mcp/ghidraEvidenceMcp.test.ts — 4/4 passed (1 failed before the profile change, confirming the red step)
  • npm run test:focused -- src/ghidra/GhidraFunctionValues.test.ts — 50/50 passed
  • npm run test:focused -- src/ghidra/GhidraProvider.behavior.test.ts src/ghidra/GhidraSnapshotCache.test.ts — 60/60 passed
  • npm run check:fast — typecheck and lint green
  • npm run docs:check — green
  • npm run verify:test-discovery — 1112 test files, green

Compatibility, safety, and release

  • Breaking changes or migration steps: none. The v2 to v3 contract bump intentionally invalidates old analysis snapshots on replay; they re-run instead of replaying unqualified results.
  • Real Hopper/Ghidra, browser, or OS coverage: real Ghidra lane unavailable in this sandbox (no Ghidra installed). Stated plainly rather than assumed; the detection runs first in CI's real-Ghidra lane.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: read-only observation of the analyzed program; no new process, network, or mutation surface.

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.

@morluto

morluto commented Oct 15, 2026

Copy link
Copy Markdown
Owner

Thanks @sx4im for isolating the missing Borland SEH handler coverage and demonstrating the out-of-function handler case against Ghidra. Main now reports this limitation through the Ghidra provider bridge in d4bd65c53 (main).

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

[Bug] Delphi/Borland SEH handler blocks are cut from Ghidra function bodies without notice

4 participants