Skip to content

feat(ghidra): define function-pointer members and typedefs - #14889

Merged
morluto merged 2 commits into
mainfrom
feat/ghidra-function-pointer-members
Nov 27, 2026
Merged

morluto merged 2 commits into
mainfrom
feat/ghidra-function-pointer-members

Conversation

@morluto

@morluto morluto commented Nov 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

Fixes #14887. define_native_data_types refused every parenthesis in a definition, so a struct or union with a function-pointer member (vtables, ops tables, callback structs) and function-pointer typedefs could not be defined. This admits the plain function-pointer forms Ghidra 12.2 stores as written, and reports the stored prototype through inspect_native_data_type.

Problem and expected behavior

Before:

define_native_data_types { declarations: "struct ops { int (*open)(const char *path, int flags); };" }
→ invalid_request: declarations contains a parenthesis (a struct, union, enum or typedef definition admits none ...)

After: the struct is stored with open as a pointer to /rea_caller_defined/ops.open, a function type whose prototype is readable:

{ "kind": "function", "source": "caller-defined",
  "function_definition": { "return_type": "/int",
    "parameters": [ { "name": "path", "type": "/char *" }, { "name": "flags", "type": "/int" } ],
    "varargs": false, "calling_convention": "unknown" } }

Change and scope

  • Admission (one owner, the C tokenizer): in a member or typedef, a parenthesis is admitted only as ret (*name)(parameters), with (**name), (*name[N]) and a calling convention written before the parenthesis (int __stdcall (*name)(int)). The parameters use the existing grammar, so qualifiers in them are reported in dropped_qualifiers and array sizes stay literal-only. Forms Ghidra 12.2 stores differently from the text are refused at their position, each found with a headless CParser probe and C.jj:
    • (): stored as (void); write (void).
    • A calling convention inside the parenthesis, (__stdcall *f): dropped by Ghidra.
    • _Noreturn: not stored on a function-pointer type.
    • A nested function-pointer parameter: Ghidra names its function type after the parameter. Typedef the inner pointer instead.
    • Grouped declarators int (x); and function types typedef int f(int);.
    • A parameter Ghidra leaves as its undefined placeholder (a K&R identifier list or unknown name), refused after parsing.
  • Naming: Ghidra names these function types _func_N by a per-parse counter, which would collide across calls and make repeats non-idempotent. Each is stored in /rea_caller_defined as owner.member, or typedef.target for a typedef; a repeat reports unchanged and a changed prototype is refused with data_type_conflict. Ghidra's ArrayDataType keeps the element name it was built with (and resolving it then threw StringIndexOutOfBoundsException on real Ghidra), so arrays of function pointers are rebuilt around the renamed type.
  • Readback: inspect_native_data_type adds kind: "function" and an optional function_definition (return type, parameters, varargs, calling_convention).
  • Not included: function-pointer parameters inside function pointers, function types, __thiscall (not a C.jj token), and annotate_native_function signatures, which still refuse function-pointer declarators.

Contract and boundary impact

  • Semantic owner and earliest changed stage: admitCallerC in the bridge owns which forms reach Ghidra's parser; callerFunctionTypes owns naming and the untyped-parameter check after parsing. The previous blanket refusal of ( and of parser.getFunctions() is removed.
  • Contribution scope fit and linked maintainer decision: extends the existing define_native_data_types edit within the same authority (session analysis database, no target bytes); not applicable.
  • CLI and MCP/tool-catalog contract: additive. inspect_native_data_type output gains the function kind and optional function_definition; the declarations description names the admitted form. No input schema change.
  • Provider, bridge, target-format, or platform compatibility: Ghidra only; probed on Ghidra 12.2. A calling convention before the parenthesis is stored by name as written, whether or not the program's compiler specification defines it (documented).
  • Evidence, artifact, provenance, or reconstruction contract: unchanged; function types are marked caller-defined by category like the other definitions.
  • Target selection, authority, upstream behavior, and cleanup details: unchanged; one transaction, a refusal changes nothing.
  • Generated metadata, package, or installation impact: none.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • 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:
    • scripts/verify-real-ghidra-type-edits.mjs: new phase "function-pointer members and typedefs are stored with their prototypes". It defines a typedef and an 11-member struct (plain, (void), pointer return, varargs, __cdecl, (*table[4]), (**indirect), typedef member, typedef parameter, self-referential parameter) and checks every offset, size and member type, each function type's prototype, unchanged on repeat, and refusal of a changed prototype without change. The refusal list now covers (), a convention inside the parenthesis, a nested function-pointer parameter, an identifier list, _Noreturn and a function type, each at its column.
    • tests/boundary/mcp/ghidraTypeEditsMcp.test.ts: a function type's prototype passes the MCP output contract, and a malformed one is refused as unreadable_output.
  • Base reproduction or other evidence: on the base, any ( in declarations is refused, including struct rea_callbacks { int (*fn)(int); };, which the verifier previously expected. During development, an array of function pointers followed by another member failed on real Ghidra with StringIndexOutOfBoundsException until the array was rebuilt.
  • User-visible CLI/MCP output: see above.
  • Remaining proof gaps: real-Ghidra coverage is arm64 macOS (a 64-bit Mach-O fixture); x86-64 Linux runs only in CI if the verifier runs there. Whether the decompiler uses a non-native calling-convention name stored on a function type was not checked.

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

  • node scripts/verify-real-ghidra-type-edits.mjs (Ghidra 12.2, arm64 macOS) — verified, all 10 phases including the new one; process cleanup verified.
  • javac of bridge/ghidra/*.java against the Ghidra 12.2 jars (JDK 25) — success.
  • npm run test:focused -- tests/boundary/mcp/ghidraTypeEditsMcp.test.ts tests/boundary/cli/analysisSelectorCli.test.ts tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts tests/boundary/mcp/ghidraEvidenceMcp.test.ts — 4 files, 81 tests passed.
  • npm run test:local -- src/ghidra/GhidraProvider.behavior.test.ts src/ghidra/GhidraSessionValues.test.ts src/ghidra/GhidraSnapshotCache.test.ts — 382 passed.
  • npm run check:fast — passed. oxfmt --check . — passed. npm run docs:check — passed.
  • npm run verify:advertised-schemas -- --update-summary — no summary changes (Rust validators not installed locally).

Review follow-up (9667f18)

  • Comma-separated function-pointer declarators (int (*open)(int), (*close)(int);, and the typedef form) are admitted; Ghidra 12.2 stores each with the shared return type and calling convention.
  • One parameter-list check, requireCallerParameters, serves signatures and function pointers: repeated names and bare K&R names (stored by Ghidra as undefined) are refused in both. Behavior change: a K&R signature such as double total(s, mask) was previously applied with undefined parameters and is now refused.
  • function_definition parameters share the 20000-entry readback bound with fields and members, check cancellation, and report total_parameters and parameters_truncated.
  • Real-Ghidra verifier: 10/10 phases verified after these changes. One earlier run timed out in its last phase under host load and passed unchanged on rerun.

Compatibility, safety, and release

  • Breaking changes or migration steps: none; previously refused text is now admitted, and the new output fields are additive.
  • Real Hopper/Ghidra, browser, or OS coverage: real Ghidra 12.2 on arm64 macOS.
  • Package or release metadata impact: none.
  • Security, privacy, process, or containment review: no new process, file or network effect; parser input stays bounded by declarations_max_utf16 and the 256-level type-depth ceiling.

Author readiness

Human owner:

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

Author checklist (completed by the PR author before requesting review)

  • 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.
  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.
  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.
  • Documentation is concise and factual, without punchy slogans or promotional language.
  • This change fixes the root cause and follows the engineering rules in AGENTS.md.
  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.
  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.
  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.

define_native_data_types refused every parenthesis in a definition, so
vtables, ops tables and callback structs could not be defined.

Admit ret (*name)(parameters) as a struct or union member or a typedef,
with (**name), (*name[N]) and a calling convention written before the
parenthesis. Ghidra 12.2 stores these as written. The tokenizer still
refuses, at its position, every form Ghidra stores differently: an empty
parameter list (stored as (void)), a calling convention inside the
parenthesis, _Noreturn, a nested function-pointer parameter, grouped
declarators and function types. A parameter Ghidra leaves untyped, such
as a K&R identifier list, is refused after parsing.

Ghidra names these function types by a per-parse counter, which would
collide across calls. Each is stored in /rea_caller_defined as
owner.member, or typedef.target, so a repeat is idempotent and a changed
prototype is refused. Arrays keep the element name they were built with,
so arrays of function pointers are rebuilt around the renamed type.

inspect_native_data_type reports a function type with kind function and
its function_definition: return type, parameters, varargs and calling
convention.

Refs #14887
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-27T12:31:19.900880Z 9667f18 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: a3d0cbc042

ℹ️ 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 bridge/ghidra/ReaGhidraBridge.java Resolved
@greptile-apps

greptile-apps Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed changes appear safe to merge; no new actionable defect was established.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed changes appear safe to merge; no new actionable defect was established.

Summary

Adds function-pointer members and typedefs to define_native_data_types, with stable names and prototype readback through inspect_native_data_type.

  • Ghidra definitions can now include named function-pointer members and typedefs.
  • Function types now show their prototype when callers inspect them.
  • Native signatures now reject bare parameter names without a type.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A["Caller C declarations"] --> B["Tokenizer admits supported forms"]
  B --> C["Ghidra parses inside a transaction"]
  C --> D["Check parameters and name function types"]
  D --> E["Store equivalent types or roll back"]
  E --> F["Inspect stored prototype"]
  F --> G["Bounded parameters and omission counts"]
Loading

Reviews (2) · Last reviewed commit: "fix(ghidra): share caller parameter chec..." · Reviewed by Greptile

Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
Comment thread bridge/ghidra/ReaGhidraBridge.java Resolved
@morluto

morluto commented Nov 27, 2026

Copy link
Copy Markdown
Owner Author

Upstream fix for the array-name crash this PR works around: NationalSecurityAgency/ghidra#10317. ArrayDataType caches its name at construction, so renaming the element leaves a stale name, and DataTypeManagerDB.findDataTypesSameLocation then throws StringIndexOutOfBoundsException when the new element name is longer. The bug is described in full in that PR rather than in a separate issue, as Ghidra's contributing guide asks. Once the minimum supported Ghidra includes the fix, withCurrentArrayNames in the bridge can be removed.

Review of #14889:

- A function pointer after a comma, as in int (*open)(int), (*close)(int);
  or typedef int (*a)(int), (*b)(int);, was refused because its
  parenthesis followed ",". Ghidra 12.2 stores each declarator with the
  shared return type and calling convention, so the declarator check now
  admits "," before the parenthesis.
- A signature and a function-pointer member or typedef checked their
  parameter lists separately, so a function pointer accepted a repeated
  parameter name. requireCallerParameters is now the one check for both:
  repeated names, and a parameter written as a bare name that is not a
  type (a K&R identifier list), which Ghidra stores as undefined. The
  tokenizer records which identifiers fill a whole parameter slot, so an
  explicit undefined parameter type is not mistaken for one. This also
  refuses a K&R signature, which was previously applied with undefined
  parameters.
- inspect_native_data_type serialized every parameter of a function type
  without a bound or cancellation check. It now uses the same 20000-entry
  bound as fields and enum members, checks cancellation per parameter,
  and reports total_parameters and parameters_truncated.

Refs #14887
@morluto
morluto merged commit 8ff311b into main Nov 27, 2026
47 checks passed
@morluto
morluto deleted the feat/ghidra-function-pointer-members branch November 27, 2026 15:50
vincentkoc added a commit that referenced this pull request Nov 27, 2026
…pgp-633-20261127

* commit '3097263763611eb0c32c502d5a222060cf02f468':
  fix(cli): describe universal Mach-O slice selection without a single-dash flag (#14912)
  fix(iso9660): read Joliet trees whose .. records name their own directory (#14817)
  feat(gpu)!: add per-call object, work, report, metadata, structure, and parser budgets to inspect_gpu_code_objects (#14882)
  fix(macho)!: select arm64e.x1 slices of universal Mach-O files by exact subtype (#14881)
  refactor(views): share bounded parent and report limitations (#14902)
  refactor(desktop): share XML parent pointers in task drafts (#14905)
  feat(ghidra): define function-pointer members and typedefs (#14889)
  refactor(setup): share publication destination checks (#14904)
  perf(ci): skip unused test runtime uploads (#14903)
  fix(nuget): preserve explicitly spaced publisher metadata (#14906)
  fix(artifacts): keep uImage coverage unknown when bytes follow the declared payload (#14896)
  fix(artifacts): report incomplete Android sparse coverage (#14883)
  fix(tar): require both end-of-archive blocks for complete coverage (#14884)
  refactor(views): centralize indexed row paging (#14878)
  refactor(views): reuse optional filters in report projections (#14877)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Define function-pointer members and typedefs with define_native_data_types

1 participant