Repository navigation
feat(ghidra): set function signatures and define the types they use - #14859
Conversation
annotate_native_function accepts an optional C prototype, applied with USER_DEFINED source in the same transaction as the name and comments, verified by readback and rolled back with them on refusal. define_native_data_types stores caller-authored struct, union, enum and typedef definitions atomically under /rea_caller_defined and refuses existing names. inspect_native_data_type reports those types with source caller-defined, and annotation readback reports the applied prototype and its source. Refs #14831
|
Maintainer scope decision recorded for #14831: approved. Setting a function signature through |
[Medium impact] The reviewed update appears safe to merge; no new actionable issue was found. SummaryThe PR adds caller-defined C types and function signatures to Ghidra. This update fixes the verifier’s outdated expectation for a refused replacement of an empty DWARF type.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Caller submits signature or type definitions] --> B[Begin database transaction]
B --> C[Check text and parse C]
C --> D{Edit kind}
D -->|Signature| E[Apply prototype]
D -->|Types| F[Check conflicts and store types]
E --> G[Check readback]
F --> G
G --> H[Commit]
C -->|Refusal| I[Roll back]
E -->|Mismatch| I
F -->|Conflict| I
G -->|Mismatch| I
Reviews (13) · Last reviewed commit: "test(ghidra): assert the empty-composite..." · Reviewed by Greptile |
…pplied constructs The lengths of a signature and of type declarations and the nesting depth of parentheses are launch-only REA_ controls with measured defaults, floors and maxima, written into the bridge's session descriptor. A refusal names the control, its effective value, source and range. The bridge tokenizes caller C before Ghidra's parser sees it and refuses what that parser accepts without applying: attributes, storage-class specifiers, variable declarations, directives other than #pragma pack, literals, function bodies, default arguments, unnamed enums and repeated member names. A type name that names different types is refused. When a function has no calling convention and the prototype names none, the compiler specification's default convention, which Ghidra already uses to assign the locked storage, is recorded, and annotation readback reports the convention. Refs #14831
The bridge appended the semicolon its parser needs before checking the length, so a prototype of exactly the admitted length was refused. The readback prototype is documented as reusable only when its function and type names are C identifiers. Refs #14831
|
Follow-up to the scope approval, in commits What changed, and why1. Description. The three "pending" statements now say the scope is approved for signature edits and caller-defined data types, with local-variable retyping as a follow-up. 2. The three hardcoded limits are launch-only
3. Silently dropped input is refused before parsing. The bridge tokenizes the text once, skipping comments, and names the construct with its line and column.
4. "Unknown calling convention -- yet parameter storage is locked".
5. The edited assertion in 6. Lifecycle. Four new cases in
Cancellation inside the Java transaction on real Ghidra was not exercised. 7. Contract changes. Automated review findings
Commands and results
Still open
|
Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. The three launch-only environment controls left an agent that hit them with a restart as its only recovery. The two length bounds are now per-call parameters, signature_max_utf16 on annotate_native_function and declarations_max_utf16 on define_native_data_types, with the same defaults and measured maxima. A refusal reports details.limit with control_kind "parameter" and required_value, the text's length, so the generated recovery names the value to pass or asks for shorter text. The text fields no longer carry a schema maximum, so every over-length refusal is typed. Parenthesis nesting is a fixed ceiling of 8 levels, registered as a representation bound, because each level doubles parse time. The session descriptor no longer carries C parser limits, and the config module, environment entries and restart-only registry rows are removed. const and volatile are still applied without effect, because Ghidra's types have no representation for them. Both edits now return dropped_qualifiers with each qualifier's line and column, and for a signature its parameter index, null for the return type, instead of dropping them silently.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 71ac4c9f6b
ℹ️ 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".
…r call The C admission scan tracked lines only at LF and read directives as raw lines matched by a regular expression, so a CR-only line break shifted dropped-qualifier positions and a trailing comment on #pragma pack was refused. One tokenizer now owns caller C positions, comments and literals: CR, LF and CRLF each end a line as in Ghidra's parser, and directives are admitted from its tokens, so comments read as whitespace there too. A block comment that would carry a directive onto another line is refused. Parenthesis nesting was a fixed ceiling justified by parse time, a resource limit. It is now the per-call parenthesis_max_depth (default 8, range 1..12) on both type-edit tools. The bridge measures the deepest nesting over the whole text and sends it, with a text's length, as the wire failure's required_value, so details.limit reports the bridge's own measurement instead of the adapter re-reading the request. The tokenizer also decides whether a prototype is terminated, so the parser sees the caller's text unchanged: no leading whitespace is stripped, and a trailing line comment no longer swallows the appended terminator.
…ser diagnostics Ghidra's C parser writes the type database even with storeDataType false: a definition whose name matches an existing empty composite fills that type in place, in the parser's own nested transaction. Both type edits parsed before opening their transaction, so a refused definition, such as one conflicting with a DWARF placeholder, left that placeholder filled. Parsing, validation and storage now share the edit's one transaction, and parseCallerC refuses to run outside one. The parser also records diagnostics it cannot apply, such as a repeated enumerator it drops, and still reports success. Both edits now refuse any diagnostic with Ghidra's message, before anything is stored. The real-Ghidra verifier gains a phase with an ELF object whose DWARF declares an opaque struct, proving a refused definition leaves that empty composite unchanged, and refuses a repeated enumerator.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7fa87573a6
ℹ️ 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".
…rops Review kept finding one more construct Ghidra's C parser consumes without applying, because admission listed spellings piecemeal. The tokenizer now owns one table, audited against every token and production of Ghidra 12.2's C.jj and checked on Ghidra 12.2, in that grammar's own spellings: - Refused, because meaning is lost: __ptr32 and __ptr64 (stored as a native-width pointer), __near and __far, every attribute, declspec, __readableTo, alignas, packed and asm spelling, [[...]] attributes, storage and inline specifiers including __forceinline, __pragma and _Pragma, _Static_assert, Objective-C @ blocks (Ghidra skips their whole text), and backslashes. - Reported in dropped_qualifiers as pure qualifiers: every const and volatile spelling, restrict, __unaligned and __w64. #pragma pack is admitted only in the operand forms Ghidra applies as written with a decimal value; (0x1), (010), (show) and (pop, n) were ignored or read differently, and "# pragma" is a line marker Ghidra skips. An enum tag that neither the text nor the database defines made Ghidra invent an empty enum without a diagnostic; declarations now refuse it as they do an invented struct or union. Identifiers admit $, as C.jj's do, and the tokenizer reads numbers and [[ as single tokens.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e0fda78841
ℹ️ 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".
… Ghidra evaluates, refuse unmatched pack pops Recursion: the tokenizer's [[ lookahead re-entered next() for each "[", and the dependency walk recursed per pointer, array and member level. Both are iterative now. Ghidra 12.2's own data-type code recurses too: 1024 pointer or array levels resolve, 2048 exhaust the stack inside addDataType while its database lock is held, leaving the Program unable to save. Every parsed type's chain through pointers, arrays, typedefs and members, including existing database types, is now measured iteratively and refused beyond a fixed 256-level ceiling before Ghidra walks it. An unexpected StackOverflowError ends the session with a reason instead of being caught by the parser call, since Ghidra's lock may then be held. Constant expressions: Ghidra leaves names, casts, sizeof, floating and binary literals unevaluated and substitutes a default, so "MASK = FIRST << 4" was stored as 2, and it truncates values outside int. Enum values, array sizes and bit-field widths are admitted only as integer literals with arithmetic, shift, comparison, bitwise and logical operators, checked iteratively with C's rules to stay in int, including implicit enumerator values; anything else is refused at its position. Pragma pack: Ghidra ignores a bare (push), a pop with nothing pushed keeps the current packing, and a plain pop pops past labelled entries. The tokenizer tracks admitted pushes and admits a pop only when Ghidra's result matches C's.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c8f0d304ad
ℹ️ 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".
…ent pointer targets, state the type-depth recovery truthfully Constant expressions: emulating C against Ghidra's own evaluator is an open-ended class of mismatches (comparisons, unsigned arithmetic such as ~0U >> 1 giving -1, names, casts, truncation). The evaluator is removed. Enum values, array sizes and bit-field widths are admitted only as one decimal or hex integer literal within int, optionally negated, without suffixes; anything else is refused at the first token that leaves that form, and the refusal says to write the computed value. Implicit enumerator values are still checked against int. Dependency walk: Ghidra's generic pointer has a null pointed-to type, and pushing it onto the ArrayDeque threw. Both the dependency and depth walks now take children from one cTypeChildren and skip an absent child. Type depth: the depth is measured over the whole chain before comparing it with the limit, so the refusal reports the depth it used, and it names the type from the parser's table rather than walking the type for a name. The recovery no longer suggests splitting into named types, which cannot help because depth counts through typedefs and existing types; it says only fewer nested levels do.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 12685eb33b
ℹ️ 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".
…-and-type-edits # Conflicts: # src/ghidra/GhidraSessionErrorProjection.ts
…sis_max_depth on signatures only Under the literal-only rule for constant expressions, every parenthesis in a define_native_data_types text already ended in a refusal (function declarators, attributes, casts, sizeof, or a Ghidra diagnostic for a grouped declarator), so parenthesis_max_depth changed only which refusal a caller saw. A definition now refuses its first parenthesis at its position, and the parameter is removed from that tool's schema; it stays on annotate_native_function, whose prototype has a parameter list.
Ghidra keeps struct tags, enum tags and typedefs in separate maps.
Combining those maps dropped a typedef such as typedef int item when
struct item was also defined, and the call still succeeded. Overlapping
names are stored only when the definitions are equivalent, which keeps
typedef struct s { ... } s as one struct. Any other overlap is refused
with conflicting_type_definitions before the transaction stores anything.
Co-authored-by: morluto <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 70aa45f780
ℹ️ 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".
Ghidra's parser replaces an empty composite during parsing and returns that same object. A later same-path check would store the fill as unchanged. Record those empty composites before parsing and refuse if parsing fills one, so the open transaction restores them. A different layout of a non-empty caller type still conflicts and leaves the stored type in place. Co-authored-by: morluto <[email protected]>
…-and-type-edits Co-authored-by: morluto <[email protected]> # Conflicts: # bridge/ghidra/ReaGhidraBridge.java
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8df5ba7e0b
ℹ️ 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".
…alues Ghidra's // skip token requires a line break, so a comment at the end of declarations or of an already-terminated signature was rejected. A newline is appended whenever the text ends in a line comment, before any semicolon added for an unterminated prototype. Integer.parseInt drops a pack operand outside a Java int and leaves the previous packing, so #pragma pack(2147483648) stored a natural layout. Decimal pack operands are admitted only when that parse succeeds. Co-authored-by: morluto <[email protected]>
Defining a struct over the DWARF placeholder fills that empty composite during parsing, so the refusal is data_type_conflict before the old name-conflict message. The verifier checks that code and that the placeholder still has no fields. Co-authored-by: morluto <[email protected]>
Summary
Refs #14831 (design discussion; the maintainer approved the scope there and in a comment on this PR: signature edits and caller-defined data types, with local-variable retyping left as a follow-up).
On a target without debug information, Ghidra pseudocode reads fixed offsets from an untyped pointer. Nothing in REA could assert a type, so an agent re-derived the layout in every function. This PR lets a caller set one function's prototype and define the structure types it needs:
annotate_native_functiongains an optionalsignature.define_native_data_types, adds caller-authored C types to the analysis database.inspect_native_data_typereports those types assource: "caller-defined".Retyping or renaming individual local variables (
HighFunctionDBUtil) is not included.Problem and expected behavior
Use case, on a stripped x86-64 ELF where
0x1001800isdouble session_total(const struct session *s, unsigned mask):Observed
procedure_pseudo_codebefore:and after:
Change and scope
Follow the contribution scope.
Unresolved scope, authority, side effects, or required verification block
integration. Link the required maintainer scope decision for new providers or
capabilities involving target execution, injection, mutation, or protection
recovery; ordinary fixes within existing boundaries may state "not applicable".
Draft PRs may leave the scope decision pending and the Author readiness and
Author checklist unchecked. Maintainers can help resolve open questions.
Scope decision: approved in #14831 for signature edits through
annotate_native_functionand caller-defined data types throughdefine_native_data_types. Local-variable retyping is a follow-up and not in this PR. This adds a mutation capability (analysis metadata in the session database, never executable bytes).What the existing path does (read before designing):
annotate_native_function(src/contracts/officialToolContracts.ts) → Ghidra input/result schemas (src/ghidra/GhidraFunctionValues.ts) → bridgeannotateNativeFunction. The bridge ends theGhidraScriptouter transaction before serving, so each edit owns a real outer transaction; it validates text, applies comments then name withSourceType.USER_DEFINED, reads back, rebuilds the dossier inside the transaction, and rolls back on any failure. Both outcomes flush the name inventories and the decompiler cache.BinarySessioninvalidates the immutable snapshot before dispatching any capability whoseeffects.mutatesArtifactis true, whichGHIDRA_MUTATING_OPERATIONSdrives. Checkpoint mode saves on normal close when the Program modification number changed.capabilities, andparseGhidraSessionInforequires exactly that set.symbol.source: "user_defined". Prototypes hadsignature_sourceonly ininspect_native_api; data types have noSourceTypeat all.What this PR adds:
signatureonannotate_native_function(same intent, result contract and authority as the existing tool). Parsed with Ghidra'sCParseragainst the Program's data type manager withstoreDataType=false, before the transaction, so a refused prototype writes nothing. Applied inside the existing transaction withApplyFunctionSignatureCmd,SourceType.USER_DEFINED, Ghidra-assigned storage andFunctionRenameOption.NO_CHANGE. The prototype's own function name is a placeholder;nameremains the only rename. Readback compares return type, parameter count, types, names, varargs,_Noreturnand any named calling convention against what Ghidra applied; a difference rolls the call back.annotationsgainssignature(the formal prototype, accepted back as input when its function and type names are C identifiers),signature_sourceandcalling_convention. When the function has no calling convention and the prototype names none, the compiler specification's default convention is recorded; see "Unknown calling convention" below.define_native_data_types(a different object, so a separate tool paired withinspect_native_data_type). Accepts C struct, union, enum and typedef definitions; all are stored in one transaction or none. Types go to the category/rea_caller_defined, which is the persisted mark of caller authorship. A name the database already holds in any category is refused; an equivalent caller definition reportsunchanged. Declared additive (mayDiscardData: false), so it is not in the destructive baseline.signatureordeclarationswith the bridge's reason. Refused: thunks (Ghidra redirects the prototype to the thunked function), undefined types, function-pointer parameters and members, repeated parameter and member names, structs without members, unnamed nested struct/union/enum members, and any prototype Ghidra would apply differently (array parameters, a parameter name another symbol holds, a calling convention the compiler specification lacks).CParsersees it. It owns positions (CR, LF and CRLF each end a line, as in Ghidra's parser), comments (read as whitespace, including on#pragma packlines) and directives (admitted from its tokens). Its decisions come from one table,UNAPPLIED_C_TOKENS, audited against every token and production of Ghidra 12.2's C.jj and checked on Ghidra 12.2: it refuses tokens whose meaning would be lost (__ptr32/__ptr64, which Ghidra stores as a native-width pointer;__near/__far; every attribute and declspec spelling including[[...]]and a trailingpacked;__pragma;_Static_assert; Objective-C@blocks, whose whole text Ghidra skips; backslashes) and reports pure qualifiers (const,volatile,restrict,__unaligned,__w64in every C.jj spelling) indropped_qualifiers.#pragma packis admitted only in the operand forms Ghidra applies as written, with a decimal value, and apoponly when it matches an admitted push (Ghidra ignores a barepush). Enum values, array sizes and bit-field widths are admitted only as one decimal or hex integer literal withinint, optionally negated, without suffixes: Ghidra evaluates C constant expressions with its own rules (names, casts andsizeofdefault, values outsideinttruncate, comparisons and unsigned arithmetic differ), so the caller writes the computed value. Every parsed type is refused beyond a fixed 256-level chain through pointers, arrays, typedefs and members, because Ghidra 12.2's recursive type code exhausts the stack near 2048 levels while holding its database lock; the tokenizer and dependency walks are iterative. An enum tag nothing defines makes Ghidra invent an empty enum, which is refused like an invented struct or union. It refuses, with line and column, every construct that parser accepts without applying:__attribute__in every spelling,__declspec,_Alignas,__packed, asm labels,__extension__;static/extern/inline/register/auto/_Thread_local; variable declarations and any statement that is not a struct, union, enum or typedef definition; directives other than#pragma pack(#linesilently changed the type's category); string and character literals (char a['b']was stored aschar[0]); a function body, default argument or second declaration in a signature; unnamed enums (stored under a generated name). Applied as written and proven by stored layout in the verifier:#pragma packincluding push/pop, bit-fields, flexible and zero-length array members, enum values, several typedef declarators,_Noreturn, named calling conventions. Any diagnostic Ghidra's parser records while still reporting success, such as a repeated enumerator it drops, is refused with Ghidra's message. Parsing runs inside each edit's own transaction, because the parser fills an existing empty composite of the same name in place (for example a DWARF placeholder), so a refused edit leaves the program unchanged.constandvolatileare accepted and not recorded, because Ghidra's type system has no representation for them and they affect neither layout nor storage. Both edits returndropped_qualifiers, listing each one with its line and column and, for a signature, its zero-basedparameter_index(nullfor the return type), so the omission is reported rather than silent.ambiguous_data_type), because C text cannot select a category.USER_DEFINEDprototype locks parameter storage while the function's convention staysunknown, and the decompiler then prefixes pseudocode withUnknown calling convention -- yet parameter storage is locked. The applied storage was already what the caller's prototype implies under the default convention (observedRDI:8,ESI:4, returnXMM0_Qa:8, identical withunknownand with__stdcall). The bridge now records the compiler specification's default convention in that case only; the warning is gone andannotations.calling_conventionreports the result.Decisions that need the maintainer's view:
Bounds on the uncancellable parser.
CParsercannot be cancelled and Ghidra requests have no deadline, so REA bounds the text before parsing it. Following choose the limit's control, a one-off structural limit is per-call. Each length, and nesting, whose cost doubles per level, is therefore an optional per-call parameter. The earlier launch-onlyREA_controls are removed: an agent that hit one could only recover by restarting REA.signature_max_utf16(annotate_native_function)declarations_max_utf16(define_native_data_types)parenthesis_max_depth(both tools)Measured on Ghidra 12.2, macOS arm64. The slowest shape per character is one chain of pointer declarators, cubic in length: 0.3 s at 2048 units, 0.8 s at 4096, 6.3–6.8 s at 8192, 24 s at 12288, 100 s at 16384. Nesting doubles the time per level and repeats per occurrence: 8192 units at depth 8 took 0.2 s, depth 10 0.7 s, depth 12 2.2 s.
A length refusal is
resource_constraintwithdetails.limitcarryingcontrol_kind: "parameter", the parameter, its effective value, range, default andrequired_value, which the bridge measures and sends on the wire failure: the text's length, or its deepest nesting over the whole text. The generated recovery names the value to pass, or asks for shorter text when the length is above the maximum. The text fields have no schema maximum, so every over-length text gets this typed refusal rather than a schema error. A nesting refusal has the same shape withparenthesis_max_depth. The bridge validates each per-call value against the same range./rea_caller_definedas provenance. Data types have no source field, so the category path carries it and survives a checkpoint.inspect_native_data_type.sourcewidens from the literalanalysis-databaseto an enum withcaller-defined.Required readback fields.
annotations.signature,annotations.signature_sourceandannotations.calling_conventionare required in the output contract, not optional. Only the Ghidra adapter producesannotate_native_function; no Hopper, IDA or other provider implements it. They therefore stay required, and would become nullable if a second provider is added.Not included: local-variable retyping or renaming; replacing or deleting a type; function-pointer types; any change to
effects.persists_after_close, which is still the literalfalsein checkpoint mode as before.Other open PRs edit
bridge/ghidra/ReaGhidraBridge.java(#14843, #14847). This branch is based onorigin/mainonly; expect a merge conflict in that file with whichever lands second.Contract and boundary impact
GhidraSessionErrorProjectionowns attributing the four new remote codes to an argument, and shares their classification withGhidraSessionError(request-scoped diagnostics). Consumers: MCP and CLI through the existing official-tool path.define_native_data_types, CLIdefine-native-data-types); new optional inputssignatureandsignature_max_utf16, three new required output fields and an optionaldropped_qualifiersonannotate_native_function(CLI--signature);define_native_data_typestakes an optionaldeclarations_max_utf16and returns an optionaldropped_qualifiers;inspect_native_data_type.sourcegains a value. The tool catalog grows by one entry. No environment controls and no runtime analysis settings.signature_source: "user_defined"; caller-authored types readsource: "caller-defined"and live under/rea_caller_defined. Both edits invalidate immutable analysis snapshots through the existingmutatesArtifactrule. Limitation text states that the types are the caller's assertions, not observations.CParserwithstoreDataType=falsestores nothing (observed: type count unchanged after parses); it invents an empty composite for an undefinedstructtag (detected and refused); it accepts and drops attributes, storage classes, variable declarations and other constructs (now refused before parsing, see above). No new process, file or cleanup path.docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs andskills/; edit authored instructions in.agents/skills/reverse-engineer-anything/and never commit build outputs): authored skill reference edited and the tracked.cursor-plugincopy regenerated withnpm run cursor-plugin:generate. New npm scriptverify:ghidra:type-edits.Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.
The checked change effect is limited to analysis metadata: function prototypes and data types in Ghidra's temporary working database, saved to the caller's
REA_GHIDRA_CHECKPOINT_DIRon normal close when checkpoint mode is on. Executable bytes, process memory, registers and REA configuration are not changed; the verifier asserts the target's SHA-256 is unchanged. The Ghidra process is the one the session already launched.Evidence and regression coverage
Tests added or updated:
tests/boundary/mcp/ghidraTypeEditsMcp.test.ts(simulated bridge, real MCP boundary): type readback contract and rejection of out-of-contract replies; prototype readback with source and calling convention; each refusal code attributed to its field with the bridge's reason, recovery and a still-usable session; the ambiguous-name refusal for both tools; each length refusal binds its per-call parameter with effective value, range, default andrequired_value, covering the default bound, the caller's bound, and text above the maximum; a per-call value out of range, orsignature_max_utf16withoutsignature, is refused before the bridge, and long text reaches the bridge; each nesting refusal bindsparenthesis_max_depthwith the measuredrequired_value(default bound, caller's bound, need above the maximum);dropped_qualifierspasses through both results.src/ghidra/GhidraSnapshotCache.test.ts: a dispatcheddefine_native_data_typesor signature edit stops snapshot replay and blocks snapshot export even when the bridge refuses it.tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts(fake Ghidra process over a real socket): after a signature edit or a type definition, a failed closing checkpoint is reported, leaves the previous checkpoint intact and the Program editable, and saves on retry; cancelling an active edit stops the Program without saving, and the next start is a new Program restored from the unchanged checkpoint.scripts/verify-real-ghidra-type-edits.mjs(npm run verify:ghidra:type-edits), real Ghidra over MCP on a self-built fixture without debug information: nine phases, including maximum-length bracket, parenthesis, array, pointer and typedef floods that are refused while the session survives and still saves on close, a refused definition against a DWARF placeholder leaving it unchanged, a refused parser diagnostic, refusals for every audited C.jj token class and unapplied#pragma packform, pure qualifiers reported with exact columns, every refused construct with its position, the stored layout of every applied construct, parameter storage and calling convention after a signature edit, a nesting bypass through comments, the deepest nesting reported under a lower bound, a raised bound admitting 10 levels,#pragma packwith trailing comments, CR and CRLF positions,dropped_qualifierspositions forconstandvolatilein both edits, and per-call bounds reaching the bridge.src/ghidra/GhidraSessionValues.test.ts(databaseEdits) andtests/fixtures/fakeGhidraReplies.mjs(capability and mutating-method lists) list the new operation, because the handshake requires the exact capability set and the read-only (Windows P0, existing-project) set must omit it. Annotation reply fixtures inGhidraProvider.behavior.test.ts,GhidraSnapshotCache.test.ts,ghidraEvidenceMcp.test.tsandofficialArguments.test.tsgained the three required readback fields.scripts/lib/real-ghidra-boundaries.mjscompared the wholeannotationsobject to four fields; that comparison is now the exportedassertNameAndCommentReadback, which compares those four and asserts the untouched prototype is notuser_defined.tests/fixtures/fakeGhidra.mjsgained acheckpoint_hang_editmode and marks the checkpoint dirty after either edit. No assertion was removed or loosened otherwise.Base reproduction or other evidence: executed by hand over MCP (
node scripts/rea.mjs mcp) on a stripped x86-64 ELF with Ghidra 12.2. The before/after pseudocode above is that output. In the same session: a signature naming an undefined struct, and one with a syntax error, each sent withnameandcomment, leftprocedure_infoatundefined FUN_01001800()withsymbol.source: "default"andaddress_nameatFUN_01001800; a conflicting redefinition sent together with a new struct stored neither; the applied prototype's readback, passed back assignature, returned identical annotations. With a fresh mode-0700REA_GHIDRA_CHECKPOINT_DIR, afterclose_binarya new MCP process showeds->flags,s->score,s->next,inspect_native_data_typesource: "caller-defined", and the same definition reportedunchanged.User-visible CLI/MCP output (if applicable):
{"types":[{"id":"/rea_caller_defined/session","name":"session","kind":"struct","size_bytes":56,"status":"defined"}],"effects":{"scope":"session-analysis-database","source_bytes_modified":false}}{"address":"0x1001800","name":"session_total","comment":"sums scores","inline_comment":null,"signature":"double session_total(session * s, uint mask)","signature_source":"user_defined","calling_convention":"__stdcall"}Over-length refusal, with the fields the boundary test asserts; this was composed from the code, not captured:
{"code":"resource_constraint","message":"signature has 2063 UTF-16 code units; signature_max_utf16 admits at most 2048 UTF-16 code units. Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. Nothing in this call was applied","limit":{"control_kind":"parameter","parameter":"signature_max_utf16","effective_value":2048,"unit":"count","minimum":16,"maximum":4096,"default_value":2048,"applies_at":"next_call","required_value":2063}}{"issues":[{"path":["declarations"],"reason":"invalid_value","message":"declarations contains the attribute or extension __attribute__ (use #pragma pack for packing) at line 1, column 30; Ghidra's C parser would not apply it as written, so nothing was changed"}]}{"issues":[{"path":["signature"],"reason":"invalid_value","message":"The type name FILE names different types in the database: /DWARF/FILE.h/FILE, /stdio.h/FILE"}]}{"code":"invalid_request","issues":[{"path":["signature"],"reason":"invalid_value","message":"signature uses types the database does not define: session"}],"remediation":"Define the named types first (MCP define_native_data_types; CLI rea define-native-data-types), then repeat this call. Nothing in this call was applied."}{"issues":[{"path":["signature"],"reason":"invalid_value","message":"Ghidra applied a different prototype at 0x1001800 than requested: double FUN_01001800(int * a); requested double f(int[4] a)"}]}Remaining proof gaps:
npm run verify:ghidrafails on this host atscripts/lib/native-value-e2e.mjs:313before the annotation section; the same failure occurs on the base commit ofmainon this machine, so it is pre-existing and not addressed here. The edited assertion was executed separately: a driver sent the section's own request to real Ghidra and passed the reply to the exportedassertNameAndCommentReadback, which passed, and failed as intended on a caller-authored prototype. The rest of that section remains unexecuted with this change.FILErefused in a signature and as a member with nothing stored;size_t, whose two definitions are equivalent, accepted). The verifier fixture has no duplicate names, so the automated coverage of this rule is the simulated-bridge projection test only.constandvolatileare accepted and not recorded, because Ghidra cannot store them; the real verifier asserts the reporteddropped_qualifierspositions instead.sizeof); another superlinear shape under 8192 units is not excluded.x0:8,w1:4, returnd0:8). Other architectures were not run.For boundary fixes, identify the applicable boundary regressions
and lifecycle regressions
covered by the evidence above, and explain relevant gaps.
Covered: malformed input (syntax error, undefined type, over-length, over-nested, dropped constructs), conflict with existing state, atomicity across fields and across definitions, readback mismatch, snapshot invalidation on refused dispatch, read-only authority, persistence across processes, cancellation of an active edit, and a failed closing checkpoint with retry (the last two against the fake Ghidra process). Not covered: cancellation inside the bridge transaction on real Ghidra.
For evidence-bearing changes:
Validation performed
Node v24.22.1, Ghidra 12.2, macOS arm64. On the current head (
71ac4c9f6b), targeted runs only:npm run check:fast— typecheck and lint succeeded (includingfixed-ceilings.mjs); architecture guards passed across 3239 source files.npm run docs:check—readmeConsistency8 passed.npm run verify:advertised-schemas -- --update-summary—annotate_native_functionanddefine_native_data_typesinput summaries refreshed.npx oxfmt --check .— all matched files use the correct format.javacagainst the Ghidra 12.2 jars, with no errors.npm run test:local -- src/ghidra/GhidraLaunchFailure.test.ts src/ghidra/GhidraClientWire.test.ts src/ghidra/GhidraSessionError.test.ts src/ghidra/GhidraProvider.behavior.test.ts src/ghidra/GhidraSnapshotCache.test.ts src/ghidra/GhidraSessionValues.test.ts src/domain/analysisRefusal.test.ts— 7 files, 418 passed.npm run test:local -- src/config.test.ts src/contracts/toolEffects.test.ts tests/evaluation/numericLimitCheck.test.ts src/doctorRuntime.test.ts— 4 files, 174 passed, 1 skipped.npm run test:focused -- tests/boundary/mcp/ghidraTypeEditsMcp.test.ts tests/boundary/mcp/ghidraEvidenceMcp.test.ts tests/boundary/mcp/officialArguments.test.ts tests/boundary/mcp/ghidraFailureDiagnostics.test.ts tests/boundary/providers/ghidra/ghidraJavaLaunch.test.ts tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts— 6 files, 98 passed.npm run test:focused -- tests/boundary/mcp/toolSchemaValidity.test.ts tests/boundary/providers/ghidra/ghidraClient.test.ts tests/boundary/providers/ghidra/fakeGhidraReplyContracts.test.ts tests/boundary/providers/ghidra/ghidraLauncher.test.ts tests/boundary/cli/cliContractSchemaParity.test.ts tests/boundary/cli/cliContractCommandParity.test.ts tests/boundary/cli/cliInputSchemaRequired.test.ts— 7 files, 1252 passed, 3 skipped.node scripts/verify-real-ghidra-type-edits.mjs—verified; all nine phases verified; process lineage cleanup verified.On the first commit only, not repeated: the broad source run (406 files, 7614 passed), 80 boundary files (2458 passed) and 4 acceptance files (108 passed).
Compatibility, safety, and release
annotate_native_functionresults gain three required fields (annotations.signature,signature_source,calling_convention) andinspect_native_data_type.sourcegains the valuecaller-defined. Under the convention indocs/development/releasing.md, a change is marked breaking when a previously valid call or configuration fails or changes meaning. No previously valid call or configuration does: the new input is optional, the new tool is additive, and existing calls return the same facts plus new ones. The title and commits are therefore not marked!. A consumer that validates these results against a closed copy of the old schema must accept the new fields and value. In-repo holders of the old shape were checked by searching for the result fields: the annotation fixtures listed above were updated, no tracked catalog or recorded fixture holds a copy,docs/error-contract.schema.jsonanddocs/user-visible-errors.csvare unchanged by their generator, and the ignored catalogs are regenerated by the build.sources_sha256and therefore the analysis profile digest change, as with any bridge edit. Existing owned checkpoints key on that profile.#pragma packis refused before parsing);StackOverflowErrorand lexer errors are caught so they cannot end the bridge; the per-call length and nesting bounds above bound its uncancellable work. No network, no new process, no executable-byte writes.Author readiness
Human owner: @morluto
Author checklist (completed by the PR author before requesting review)
type(scope): outcome.REA_runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.