feat(ghidra): set function signatures and define the types they use (#14859)

* feat(ghidra): set function signatures and define the types they use

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

* feat(ghidra): bound caller C text with launch controls and refuse unapplied 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

* fix(ghidra): apply the signature bound to the caller's text

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

* chore(mcp): refresh advertised schema summaries for Ghidra type edits

Refs #14831

* fix(ghidra): bound caller C text per call and report dropped qualifiers

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.

* fix(ghidra): read caller C through one tokenizer and bound nesting per 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.

* fix(ghidra): parse caller C inside the edit's rollback and refuse parser 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.

* fix(ghidra): admit caller C from one audited table of tokens Ghidra drops

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.

* fix(ghidra): bound caller type depth, admit only constant expressions 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.

* fix(ghidra): admit constant expressions only as one literal, skip absent 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.

* refactor(ghidra): refuse parentheses in definitions and keep parenthesis_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.

* fix(ghidra): refuse distinct types that share one parser name

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 <morluto@users.noreply.github.com>

* fix(ghidra): roll back a composite the parser fills in place

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 <morluto@users.noreply.github.com>

* fix(ghidra): close line comments at EOF and refuse overflowing pack values

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 <morluto@users.noreply.github.com>

* test(ghidra): assert the empty-composite refusal by code and readback

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 <morluto@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: morluto <morluto@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-27 06:11:53 -05:00
1 parent 06fa8d0634
commit 3a8a717b02
40 files changed
+4123 -39

No files matched your search

+3 -1
View File
@@ -1714,7 +1714,9 @@ distinguish restored database state from fresh analysis.
Run `npm run verify:ghidra:checkpoints` with your existing Ghidra/JDK installation
to verify fresh CLI/MCP processes, name/comment/type preservation, competing
sessions, corruption refusal and explicit recovery. Lifecycle fixtures cover
sessions, corruption refusal and explicit recovery. `npm run verify:ghidra:type-edits`
verifies caller-defined types and function signatures, their refusals and
their restoration from a checkpoint in a new process. Lifecycle fixtures cover
save failure/retry and cancellation during checkpoint finalization separately.
### Reuse an existing Ghidra project
+116
View File
@@ -1503,6 +1503,122 @@ unpaired Unicode surrogate; a rejection identifies the field and UTF-16 index
and leaves every annotation unchanged. CRLF, supplementary Unicode characters,
and combining characters are preserved. Windows P0 remains read-only. Ghidra has no
GUI authority, and REA never falls back automatically to Hopper.
For a target without debug information, set a function's prototype and the
types it needs so later pseudocode uses field and parameter names instead of
offsets. Define the types, then pass `signature` to
`annotate_native_function`:
```javascript
await call("define_native_data_types", {
declarations:
"struct session { int id; char name[32]; unsigned flags; double score; struct session *next; };",
});
await call("annotate_native_function", {
procedure: "0x1001800",
name: "session_total",
signature: "double total(const struct session *s, unsigned mask)",
});
```
`signature` is one C prototype over types the database already holds. Its
function name is a placeholder; `name` renames the function. The prototype is
applied in the same transaction as the name and comments with Ghidra's
`USER_DEFINED` source and Ghidra-assigned parameter storage.
`annotations.signature` is the applied prototype, which `signature` accepts
back when its function and type names are C identifiers,
`annotations.signature_source` is `user_defined` for a caller-authored
prototype rather than `default`, `analysis` or `imported`, and
`annotations.calling_convention` is the convention that storage follows. When
the function has no calling convention and the prototype names none, REA
records the compiler specification's default convention, which is the one
Ghidra already uses to assign the storage; without it the decompiler prefixes
the pseudocode with `Unknown calling convention -- yet parameter storage is
locked`. Name a convention in the prototype (for example `__stdcall`) to
assert another one.
`define_native_data_types` accepts C struct, union, enum and typedef
definitions and stores all of them or none in the category
`/rea_caller_defined`. `inspect_native_data_type` reports those types with
`source: "caller-defined"`; they are the caller's assertions about layout, not
observations of the target. A name the database already holds in any category
is refused and never replaced; repeating an equivalent caller definition
reports `unchanged`. Ghidra fills an existing empty composite in place while
parsing, and that replacement is rolled back with the rest of a refused call. Ghidra keeps a struct, union or enum tag in a different
map from a typedef and stores one type per name. When the declarations give
that name to definitions that are not equivalent, such as
`struct item { int x; }; typedef int item;`, the call is refused with
`details.diagnostics.remote_code` `conflicting_type_definitions` and stores
nothing. `typedef struct s { ... } s;` is one struct and is stored.
Ghidra's C parser accepts several constructs and records nothing for them. REA
refuses those before parsing, names the construct and its line and column, and
changes nothing:
| Construct | `signature` | `declarations` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `__attribute__`, `__declspec`, `__readableTo`, `_Alignas`, `packed`, `[[...]]`, asm labels, `__extension__` | refused | refused; use `#pragma pack` to pack |
| `__ptr32`, `__ptr64` (Ghidra stores a native-width pointer), `__near`, `__far` | refused | refused |
| `__pragma`, `_Pragma`, `_Static_assert`, Objective-C `@` blocks, backslashes, `#` apart from its name | refused | refused |
| `static`, `extern`, `inline`, `__forceinline`, `register`, `auto`, `_Thread_local` | refused | refused |
| Variable declarations and other non-type statements | refused | refused |
| Preprocessor directives | refused | refused except `#pragma pack` in a form Ghidra applies: decimal values from 0 through 2147483647, a `push` with a value or label, a `pop` that matches an admitted push |
| String and character literals | refused | refused |
| Function body, default argument, second declaration | refused | not applicable |
| Function pointers | refused | refused |
| Any parenthesis in a definition (Ghidra stores no parenthesized form there as written) | not applicable | refused |
| Unnamed enum; unnamed struct or union other than `typedef struct { } name` | refused | refused |
| Repeated parameter or member name; struct, union or enum without members (Ghidra invents one for an undefined tag) | refused | refused |
| Array parameter (Ghidra stores a pointer) | refused | not applicable |
| A type name the database holds as different types | refused | refused |
| Anything Ghidra's parser reports a diagnostic for, such as a repeated enumerator name | refused | refused |
| An enum value, array size or bit-field width other than one decimal or hex integer literal, optionally negated, without suffixes; a value or implicit enumerator outside `int` | not applicable | refused |
| `#pragma pack`, bit-fields, flexible and zero-length arrays, enum values, several typedef declarators | not applicable | applied; the stored layout shows them |
| `_Noreturn`, a calling convention the compiler specification defines | applied | not applicable |
| `const`, `volatile`, `restrict`, `__unaligned`, `__w64` | accepted, reported | accepted, reported |
These qualifiers have no representation in Ghidra's type system and no
effect on layout or storage, so the stored type and the readback omit them.
The bridge recognizes every spelling Ghidra 12.2's C grammar accepts, such as
`__const` or `_restrict`, and reports the qualifier by its plain name.
The result's `dropped_qualifiers` lists each one with its line and column, and
for a signature its zero-based `parameter_index` (`null` for the return type),
so the omission is visible without comparing the text with the readback.
Ghidra evaluates enum values, array sizes and bit-field widths with its own
rules, which differ from C: it does not evaluate names such as an earlier
enumerator (`MASK = FIRST << 4` would be stored as the next implicit value),
it truncates values outside `int`, and comparisons and unsigned arithmetic
give other results (`~0U >> 1` is -1). REA therefore admits each one only as a
single decimal or hex integer literal within `int`, optionally negated,
without suffixes, and refuses anything else at its position: write the
computed value. Ghidra's parser can report a diagnostic, such as a repeated enumerator it
drops, and still succeed; REA refuses such text with Ghidra's message, which
names the nearest type but has no line or column. Parsing runs inside the
edit's own transaction, because Ghidra's parser fills an existing empty
composite of the same name in place, so a refusal leaves even such a type
unchanged. A
type name that exists in several categories is accepted only when every type
of that name is equivalent; otherwise the refusal lists their category paths,
because C text cannot select one.
Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. Each
bound has a per-call parameter, and a refusal names it with its effective
value, range and the measured need:
| Parameter | Default | Range | Bounds |
| ----------------------------------------------------- | ------: | -------- | ----------------------------------- |
| `signature_max_utf16` (`annotate_native_function`) | 2048 | 16..4096 | UTF-16 code units of `signature` |
| `declarations_max_utf16` (`define_native_data_types`) | 4096 | 16..8192 | UTF-16 code units of `declarations` |
| `parenthesis_max_depth` (`annotate_native_function`) | 8 | 1..12 | Parenthesis nesting in `signature` |
The maxima follow measured parse times on Ghidra 12.2: the slowest admitted
text at the maxima took about 7 seconds (a single chain of 8192 pointer
declarators); twice the length took 100 seconds. Each level of parentheses
doubles the time (12 levels took 2.2 seconds). Split a larger set
of definitions across calls. Both edits invalidate immutable analysis
snapshots and persist exactly as names and comments do: saved on normal close
in checkpoint mode, discarded otherwise. Cancelling an active edit stops the
Ghidra process without saving it.
For a before-and-after `compare_functions` in MCP, call `analyze_function`
before and after the edit while the session remains open; the annotation Evidence
itself is not an `analyze_function` input. If comparing after close, export the
+39
View File
@@ -136,6 +136,45 @@ effective payload allowance; payload recovery applies only when that diagnostic
identifies payload exhaustion. Raising these controls does not raise the MCP
client's deadline or receive buffer.
## C text for signatures and type definitions
`annotate_native_function` `signature` and `define_native_data_types`
`declarations` are parsed by Ghidra's C parser, which cannot be cancelled, so
REA bounds that text before parsing it. Each bound has a per-call parameter;
`parenthesis_max_depth` applies to `signature`; a `declarations` text admits no parentheses at all.
| Bound | Default | Floor | Maximum | Slowest measured parse at the maximum |
| --------------------------------------------- | ------: | ----: | ------: | ------------------------------------------ |
| `signature_max_utf16` (UTF-16 code units) | 2048 | 16 | 4096 | 0.8 s (one chain of pointer declarators) |
| `declarations_max_utf16` (UTF-16 code units) | 4096 | 16 | 8192 | 6.8 s (one chain of pointer declarators) |
| `parenthesis_max_depth` (`signature`, levels) | 8 | 1 | 12 | 2.2 s (8192 units of 12-level expressions) |
Measured with Ghidra 12.2 on arm64 macOS; other hosts differ. Parse time is
cubic in the length of a declarator chain (16384 units took 100 s) and doubles
with each level of nested parentheses (12 levels took 2.2 s), so the maxima
are fixed. A text over a bound is refused before parsing with
`code: "resource_constraint"`; `details.limit` carries
`control_kind: "parameter"`, the parameter, its effective value, range,
default and `required_value`: the text's length, or its deepest nesting over
the whole text. The recovery names the larger value to pass, or asks for
shorter or flatter text, or several calls, when the need is above the maximum.
A type chained more than 256 levels deep through pointers, arrays, typedefs
or members, counting existing database types, is refused with
`details.refusal.kind: "fixed_ceiling"` and the measured depth of the whole
chain. Because the depth counts through typedefs and existing types, naming
intermediate types or splitting definitions across calls does not reduce it;
only fewer nested levels do. Ghidra 12.2 stores, names and
compares types recursively: 1024 levels resolved and 2048 exhausted the stack
inside `addDataType` while its database lock was held, leaving the Program
unable to save. No caller value raises that stack, so the bound is fixed. If
Ghidra exhausts its stack anyway, the bridge reports it and ends the session
rather than serve a Program whose lock may be held.
The bridge also refuses, with the construct's line and column (CR, LF and
CRLF each end a line, as in Ghidra's parser),
what its parser would accept without applying; see the
[native guide](../guides/native/native-investigation.md).
## PE debug-symbol coverage
The post-analysis handshake reports Ghidra's PDB Program Information attributes:
+3
View File
@@ -227,6 +227,9 @@ These parameters report that limit:
| Operation | Parameter | Default | Floor | Maximum | Owner |
| --------------------------------------------- | --------------------------------- | ---------- | ----: | -----------------------------------: | ----------------------------------------- |
| `annotate_native_function` | `signature_max_utf16` | 2048 | 16 | 4096 | `src/domain/analysisResourceLimits.ts` |
| `define_native_data_types` | `declarations_max_utf16` | 4096 | 16 | 8192 | `src/domain/analysisResourceLimits.ts` |
| `annotate_native_function` | `parenthesis_max_depth` | 8 | 1 | 12 | `src/domain/analysisResourceLimits.ts` |
| `inspect_il2cpp_metadata` | `max_native_index_bytes` | 1073741824 | 1 | `Number.MAX_SAFE_INTEGER` | `src/domain/il2cpp/il2cppMetadata.ts` |
| `inspect_elf_notes`, `inspect_elf_debug_link` | `max_file_bytes` | 67108864 | 64 | 536870912 | `src/domain/native/elfReadBudgets.ts` |
| `inspect_elf_notes`, `inspect_elf_debug_link` | `max_entries` | 128 | 1 | 256 | `src/domain/native/elfReadBudgets.ts` |