mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 01:46:39 +00:00
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:
40 files changed
+4123
-39
No files matched your search
@@ -947,7 +947,7 @@ numbering gaps leave coverage unknown; a DfuSe suffix CRC mismatch follows
|
||||
### Function annotations in Ghidra
|
||||
|
||||
Fresh-import sessions admit annotations; existing-project reuse is read-only.
|
||||
Use `annotate_native_function` for one function name and/or entry comments, with at least one explicit change. Review its annotation readback and refreshed dossier inline. Changes are atomic; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits. Normal close saves them when owned Program checkpoint mode is enabled; ephemeral mode discards them. CLI `annotate-native-function` follows the same setting when closing after its updated result. Select the [checkpoint workflow](#continue-editable-ghidra-analysis-across-processes) before edits that must survive a later process. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier. Ghidra rejects batch addresses that request the same name or a name another selected address holds; `raw_result.failures` gives each failure's reason.
|
||||
Use `annotate_native_function` for one function name, C prototype (`signature`) and/or entry comments, with at least one explicit change. When pseudocode for a target without debug information reads fixed offsets from one pointer, assert the layout with `define_native_data_types` and set the prototype; treat the resulting field names as your hypothesis (`signature_source: user_defined`, type `source: caller-defined`), not as recovered facts, and confirm each offset against the instructions. Review its annotation readback and refreshed dossier inline. Changes are atomic; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits. Normal close saves them when owned Program checkpoint mode is enabled; ephemeral mode discards them. CLI `annotate-native-function` follows the same setting when closing after its updated result. Select the [checkpoint workflow](#continue-editable-ghidra-analysis-across-processes) before edits that must survive a later process. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier. Ghidra rejects batch addresses that request the same name or a name another selected address holds; `raw_result.failures` gives each failure's reason.
|
||||
|
||||
A provider switch or different target can retire the active Ghidra database and discard
|
||||
its edits, even if the new provider fails on a later call. Same-target,
|
||||
|
||||
@@ -947,7 +947,7 @@ numbering gaps leave coverage unknown; a DfuSe suffix CRC mismatch follows
|
||||
### Function annotations in Ghidra
|
||||
|
||||
Fresh-import sessions admit annotations; existing-project reuse is read-only.
|
||||
Use `annotate_native_function` for one function name and/or entry comments, with at least one explicit change. Review its annotation readback and refreshed dossier inline. Changes are atomic; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits. Normal close saves them when owned Program checkpoint mode is enabled; ephemeral mode discards them. CLI `annotate-native-function` follows the same setting when closing after its updated result. Select the [checkpoint workflow](#continue-editable-ghidra-analysis-across-processes) before edits that must survive a later process. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier. Ghidra rejects batch addresses that request the same name or a name another selected address holds; `raw_result.failures` gives each failure's reason.
|
||||
Use `annotate_native_function` for one function name, C prototype (`signature`) and/or entry comments, with at least one explicit change. When pseudocode for a target without debug information reads fixed offsets from one pointer, assert the layout with `define_native_data_types` and set the prototype; treat the resulting field names as your hypothesis (`signature_source: user_defined`, type `source: caller-defined`), not as recovered facts, and confirm each offset against the instructions. Review its annotation readback and refreshed dossier inline. Changes are atomic; empty comments clear them, omitted fields preserve them. Later MCP calls observe edits. Normal close saves them when owned Program checkpoint mode is enabled; ephemeral mode discards them. CLI `annotate-native-function` follows the same setting when closing after its updated result. Select the [checkpoint workflow](#continue-editable-ghidra-analysis-across-processes) before edits that must survive a later process. Original executable bytes are unchanged; edits invalidate immutable snapshots. Windows P0 does not admit database mutations. For naming only, `set_address_name` / `set_addresses_names` also work with Ghidra: they name function entries or data addresses (primary labels) and return compact per-address success booleans instead of a dossier. Ghidra rejects batch addresses that request the same name or a name another selected address holds; `raw_result.failures` gives each failure's reason.
|
||||
|
||||
A provider switch or different target can retire the active Ghidra database and discard
|
||||
its edits, even if the new provider fails on a later call. Same-target,
|
||||
|
||||
+1058
-20
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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` |
|
||||
|
||||
@@ -222,6 +222,7 @@
|
||||
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
|
||||
"verify:ghidra:project-coverage": "npm run build:cached && node scripts/verify-real-ghidra-project-coverage.mjs",
|
||||
"verify:ghidra:checkpoints": "npm run build:cached && node scripts/verify-real-ghidra-checkpoints.mjs",
|
||||
"verify:ghidra:type-edits": "npm run build:cached && node scripts/verify-real-ghidra-type-edits.mjs",
|
||||
"verify:ghidra:seeds": "npm run build:cached && node scripts/verify/ghidra/seeds.mjs",
|
||||
"verify:ghidra:mips": "npm run build:cached && node scripts/verify-real-ghidra-mips.mjs",
|
||||
"verify:ghidra:ppc": "npm run build:cached && node scripts/verify-real-ghidra-ppc.mjs",
|
||||
|
||||
@@ -27,6 +27,24 @@ import { verifyGhidraInstructionFlow } from "./real-ghidra-instruction-flow.mjs"
|
||||
import { verifyGhidraSearchFacts } from "./real-ghidra-search-facts.mjs";
|
||||
|
||||
/** Probe real Ghidra location, annotation and error contracts through public adapters. */
|
||||
/**
|
||||
* Readback of an edit that changed the name and comments only: those fields
|
||||
* match the request, and the untouched prototype is not caller-authored.
|
||||
*/
|
||||
export function assertNameAndCommentReadback(annotations, address, changes) {
|
||||
const { signature, signature_source, calling_convention, ...edited } =
|
||||
annotations;
|
||||
assert.deepEqual(edited, {
|
||||
address,
|
||||
name: changes.name,
|
||||
comment: changes.comment,
|
||||
inline_comment: changes.inline_comment,
|
||||
});
|
||||
assert.ok(signature.includes(`${changes.name}(`));
|
||||
assert.notEqual(signature_source, "user_defined");
|
||||
assert.equal(typeof calling_convention, "string");
|
||||
}
|
||||
|
||||
export async function verifyGhidraBoundaries(
|
||||
client,
|
||||
{ target, procedure, entrypoint, env },
|
||||
@@ -564,12 +582,7 @@ export async function verifyGhidraBoundaries(
|
||||
inline_comment: "Inline\n註記",
|
||||
};
|
||||
const updated = await call("annotate_native_function", changes);
|
||||
assert.deepEqual(updated.annotations, {
|
||||
address,
|
||||
name: changes.name,
|
||||
comment: changes.comment,
|
||||
inline_comment: changes.inline_comment,
|
||||
});
|
||||
assertNameAndCommentReadback(updated.annotations, address, changes);
|
||||
const traceAfter = await evidence("trace_native_values", traceInput);
|
||||
const sourceAfter = traceAfter.normalized_result.procedures[0].evidence_id;
|
||||
assert.notEqual(sourceBefore, sourceAfter);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "70c17ea61092a8c3",
|
||||
"input compact": "35e71f4fbd7e748e",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "5cbbfe8ba3778c39",
|
||||
"output compact": "fc6c5d5a78a47254"
|
||||
},
|
||||
"patterns": {}
|
||||
}
|
||||
@@ -199,6 +199,12 @@
|
||||
"reason": "Bounds Ghidra's own Ghidra/application.properties, a short key=value installation descriptor of the bring-your-own provider (about 1 KiB); no analysis input passes through it, and a larger file is not a Ghidra installation REA can drive."
|
||||
}
|
||||
},
|
||||
"src/ghidra/GhidraSessionErrorProjection.ts": {
|
||||
"\"The Ghidra C type depth allowance\"": {
|
||||
"class": "representation",
|
||||
"reason": "Ghidra 12.2 stores, names and compares a data type recursively through its pointer, array, typedef and member chain; measured on Ghidra 12.2, 1024 levels resolve and 2048 exhaust the JVM stack inside addDataType while its database lock is held, leaving that lock held and the Program unusable. No caller value can raise the stack, so the bound is a quarter of the last measured safe depth."
|
||||
}
|
||||
},
|
||||
"src/gpu/GpuCodeObjectsProvider.ts": {
|
||||
"\"The GPU object allowance\"": {
|
||||
"class": "pending",
|
||||
|
||||
@@ -50,6 +50,27 @@ export const registerCoreNativeCommands = (
|
||||
name: "inline-comment",
|
||||
description: "Inline entry comment; empty text clears it",
|
||||
},
|
||||
signature: {
|
||||
description:
|
||||
"C prototype using existing database types; its function name is a placeholder",
|
||||
},
|
||||
},
|
||||
},
|
||||
run,
|
||||
);
|
||||
registerContractCommand(
|
||||
cli,
|
||||
logger,
|
||||
contractNamed(OFFICIAL_TOOL_CONTRACTS, "define_native_data_types"),
|
||||
{
|
||||
description:
|
||||
"Add C struct, union, enum and typedef definitions to the analysis database. In Ghidra ephemeral mode they are discarded when this command exits; REA_GHIDRA_CHECKPOINT_DIR keeps them under the same conditions as function annotations",
|
||||
sessionTarget: executable,
|
||||
positionals: ["declarations"],
|
||||
fields: {
|
||||
declarations: {
|
||||
description: "C type definitions; existing type names are refused",
|
||||
},
|
||||
},
|
||||
},
|
||||
run,
|
||||
|
||||
@@ -21,7 +21,10 @@ import {
|
||||
providerUiNetworkEvidenceEffects,
|
||||
toolEffects,
|
||||
} from "./toolEffects.js";
|
||||
import { nativeDataTypeInputSchema } from "../domain/native/nativeDataType.js";
|
||||
import {
|
||||
nativeDataTypeDefinitionsInputSchema,
|
||||
nativeDataTypeInputSchema,
|
||||
} from "../domain/native/nativeDataType.js";
|
||||
import { nativeInstructionInputSchema } from "../domain/native/nativeInstruction.js";
|
||||
import { functionInstructionInputSchema } from "./functionInstructionContract.js";
|
||||
import { HOPPER_MEMORY_TOOL_DEFINITIONS } from "./hopperMemoryContracts.js";
|
||||
@@ -37,6 +40,7 @@ export const decompileAnalysisSelection = decompileAnalysisSchema
|
||||
/** The contracts below that the CLI exposes as commands. */
|
||||
const OFFICIAL_CLI_CONTRACTS: ReadonlySet<string> = new Set([
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"inspect_native_load_image",
|
||||
"inspect_native_data_type",
|
||||
"inspect_native_instruction",
|
||||
@@ -85,9 +89,21 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
writesFilesystem: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
"Atomically rename one function and/or change entry comments, verify readback, and return its refreshed complete dossier. Ghidra resolves interior addresses to function entries; use procedure_address to select the entry explicitly. Edits change analysis metadata, never executable bytes; empty comment text clears it. Invalid edits roll back together. Ghidra checkpoint mode saves on normal close; ephemeral mode discards edits, including in CLI cleanup. Check binary_session for the mode. Windows P0 and providers without this capability are unsupported.",
|
||||
"Atomically rename one function, set its prototype and/or change entry comments, verify readback, and return its refreshed complete dossier. signature is a C prototype over types the database holds, e.g. `double f(struct session *s, unsigned mask)`; it makes pseudocode use those parameter and field names. Its function name is a placeholder (rename with name); add missing types with define_native_data_types first. Ghidra resolves interior addresses to function entries; use procedure_address to select the entry explicitly. Edits change analysis metadata, never executable bytes; empty comment text clears it. Invalid edits roll back together. Ghidra checkpoint mode saves on normal close; ephemeral mode discards edits, including in CLI cleanup. Check binary_session for the mode. Windows P0 and providers without this capability are unsupported.",
|
||||
nativeFunctionAnnotationsInputSchema,
|
||||
),
|
||||
official(
|
||||
"define_native_data_types",
|
||||
// Additive: an existing type is never replaced, so no data is discarded.
|
||||
toolEffects({
|
||||
mutatesTarget: true,
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
"Add caller-authored C struct, union, enum and typedef definitions to the analysis database, e.g. declarations `struct session { int id; struct session *next; };`, so annotate_native_function signatures can use them. All are stored or none; a name the database already holds is refused, never replaced. Returns each type's id for inspect_native_data_type, which reports source caller-defined. Changes analysis metadata, never executable bytes; persistence follows annotate_native_function. Windows P0 and providers without this capability are unsupported.",
|
||||
nativeDataTypeDefinitionsInputSchema,
|
||||
),
|
||||
official(
|
||||
"inspect_native_load_image",
|
||||
evidenceEffects,
|
||||
@@ -98,7 +114,7 @@ export const OFFICIAL_TOOL_CONTRACTS = [
|
||||
official(
|
||||
"inspect_native_data_type",
|
||||
evidenceEffects,
|
||||
"Inspect one recovered type by exact database category path or defined typed data address. Returns observed size, alignment, packing, fields, bitfields, enum values, and child type identities; source-level authority and flexible-tail semantics remain unknown unless substantiated.",
|
||||
"Inspect one recovered or caller-defined type by exact database category path or defined typed data address. Returns observed size, alignment, packing, fields, bitfields, enum values, and child type identities; source-level authority and flexible-tail semantics remain unknown unless substantiated.",
|
||||
nativeDataTypeInputSchema,
|
||||
),
|
||||
official(
|
||||
|
||||
@@ -23,6 +23,9 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
procedure_info: { procedure: "main" },
|
||||
trace_native_values: { procedure: "0x1000" },
|
||||
inspect_native_data_type: { type: "/MyStruct" },
|
||||
define_native_data_types: {
|
||||
declarations: "struct session { int id; struct session *next; };",
|
||||
},
|
||||
inspect_native_instruction: { address: "0x1000" },
|
||||
resolve_native_call_targets: { address: "0x1000" },
|
||||
read_function_instructions: { procedure: "main" },
|
||||
|
||||
@@ -54,7 +54,10 @@ import { nativeLoadImageSchema } from "../domain/native/nativeLoadImage.js";
|
||||
import { nativeUiResultSchema } from "../domain/native/nativeUiObservation.js";
|
||||
import { nativeValueTraceSchema } from "../domain/native/nativeValueTrace.js";
|
||||
import { bundleResourceRootSchema } from "../domain/apple/bundleResourceRoot.js";
|
||||
import { nativeDataTypeSchema } from "../domain/native/nativeDataType.js";
|
||||
import {
|
||||
nativeDataTypeDefinitionsSchema,
|
||||
nativeDataTypeSchema,
|
||||
} from "../domain/native/nativeDataType.js";
|
||||
import { nativeCallObservationResultSchema } from "../domain/native/nativeCallObservation.js";
|
||||
import {
|
||||
nativeInstructionSchema,
|
||||
@@ -156,6 +159,7 @@ export const officialOutputSchemas = {
|
||||
nativeLoadImageSchema,
|
||||
nativeLoadImageSummaryViewResultSchema,
|
||||
),
|
||||
define_native_data_types: evidenceResultOf(nativeDataTypeDefinitionsSchema),
|
||||
inspect_native_data_type: evidenceResultOf(nativeDataTypeSchema),
|
||||
inspect_native_instruction: evidenceResultOf(nativeInstructionSchema),
|
||||
resolve_native_call_targets: evidenceResultOf(nativeCallTargetsSchema),
|
||||
|
||||
@@ -58,6 +58,39 @@ export const MAXIMUM_NATIVE_MATCHING_REPRESENTATION_BYTES = 1024 * 1024 * 1024;
|
||||
/** Default absolute deadline for Ghidra import, analysis, bridge, and readiness. */
|
||||
export const DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS = 330_000;
|
||||
|
||||
/**
|
||||
* Per-call bounds on the C text REA hands to Ghidra's parser, which cannot be
|
||||
* cancelled. Measured on Ghidra 12.2: the slowest shape per character is one
|
||||
* chain of pointer declarators, cubic in its length (0.3 s at 2048 UTF-16 code
|
||||
* units, 0.8 s at 4096, 6.8 s at 8192, 100 s at 16384). The maxima keep the
|
||||
* slowest admitted text under about 7 s; the Java bridge enforces the same
|
||||
* defaults and ranges.
|
||||
*/
|
||||
export const DEFAULT_GHIDRA_SIGNATURE_MAX_UTF16 = 2048;
|
||||
export const MAXIMUM_GHIDRA_SIGNATURE_MAX_UTF16 = 4096;
|
||||
export const DEFAULT_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16 = 4096;
|
||||
export const MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16 = 8192;
|
||||
/** Shorter text cannot hold a prototype or a definition worth refusing by length. */
|
||||
export const MINIMUM_GHIDRA_C_TEXT_UTF16 = 16;
|
||||
/**
|
||||
* Per-call bound on parenthesis nesting in caller C text. Each level doubles
|
||||
* Ghidra's recursive-descent parse time and the cost repeats per occurrence
|
||||
* (8192 units filled at depth 8: 0.2 s; at depth 12: 2.2 s), so the maximum
|
||||
* keeps the slowest admitted text near the length bounds' own. A prototype's
|
||||
* own parameter list is one level.
|
||||
*/
|
||||
export const MINIMUM_GHIDRA_C_PARENTHESIS_DEPTH = 1;
|
||||
export const DEFAULT_GHIDRA_C_PARENTHESIS_DEPTH = 8;
|
||||
export const MAXIMUM_GHIDRA_C_PARENTHESIS_DEPTH = 12;
|
||||
/**
|
||||
* Fixed ceiling on how deep a parsed C type chains through pointers, arrays,
|
||||
* typedefs and members. Ghidra 12.2 stores, names and compares a type
|
||||
* recursively: 1024 levels resolve, 2048 exhaust the stack inside
|
||||
* addDataType with its database lock held, leaving the Program unusable. The
|
||||
* Java bridge enforces the same value.
|
||||
*/
|
||||
export const GHIDRA_C_MAX_TYPE_DEPTH = 256;
|
||||
|
||||
/** Default absolute deadline for Hopper launch, analysis, bridge, and readiness. */
|
||||
export const DEFAULT_HOPPER_STARTUP_TIMEOUT_MS = 120_000;
|
||||
|
||||
|
||||
@@ -180,6 +180,7 @@ const hopperAndGhidraBridgeOperations = [
|
||||
"inspect_native_load_image",
|
||||
"search_bytes",
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"inspect_native_data_type",
|
||||
"inspect_native_instruction",
|
||||
"resolve_native_call_targets",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { nativeMetadataRecoverySchema } from "./nativeMetadataRecovery.js";
|
||||
import {
|
||||
DEFAULT_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
MINIMUM_GHIDRA_C_TEXT_UTF16,
|
||||
} from "../analysisResourceLimits.js";
|
||||
|
||||
/** Select a database type by exact category path or a defined typed data address. */
|
||||
export const nativeDataTypeInputSchema = z
|
||||
@@ -12,6 +17,66 @@ export const nativeDataTypeInputSchema = z
|
||||
(value) => (value.type === undefined) !== (value.address === undefined),
|
||||
"Supply exactly one of type or address",
|
||||
);
|
||||
/** C definitions of the types a caller adds to the analysis database. */
|
||||
export const nativeDataTypeDefinitionsInputSchema = z.strictObject({
|
||||
declarations: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"C struct, union, enum and typedef definitions, e.g. `struct session { int id; char name[32]; struct session *next; };`. Members may use earlier definitions and existing database types.",
|
||||
),
|
||||
declarations_max_utf16: z
|
||||
.int()
|
||||
.min(MINIMUM_GHIDRA_C_TEXT_UTF16)
|
||||
.max(MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16)
|
||||
.optional()
|
||||
.describe(
|
||||
`Longest declarations text to parse, in UTF-16 code units (default ${String(DEFAULT_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16)}); the C parser cannot be cancelled`,
|
||||
),
|
||||
});
|
||||
|
||||
/** A pure qualifier in caller C text, which Ghidra's types cannot record. */
|
||||
export const droppedCQualifierSchema = z.strictObject({
|
||||
qualifier: z.enum(["const", "volatile", "restrict", "__unaligned", "__w64"]),
|
||||
line: z.int().positive(),
|
||||
column: z.int().positive().describe("UTF-16 column in the caller's text"),
|
||||
});
|
||||
|
||||
/** Present only when the caller's text held qualifiers that were not recorded. */
|
||||
export const droppedCQualifiersDescription =
|
||||
"Qualifiers in the caller's text (const, volatile, restrict, __unaligned, __w64) that Ghidra has no representation for and did not record; absent when there were none";
|
||||
|
||||
/** Readback of each type one atomic definition call stored or found unchanged. */
|
||||
export const nativeDataTypeDefinitionsSchema = z.strictObject({
|
||||
types: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
id: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe("Category path for inspect_native_data_type"),
|
||||
name: z.string().min(1),
|
||||
kind: z.enum(["struct", "union", "enum", "typedef"]),
|
||||
size_bytes: z.int().nonnegative().nullable(),
|
||||
status: z
|
||||
.enum(["defined", "unchanged"])
|
||||
.describe(
|
||||
"unchanged: an equivalent caller-defined type already existed",
|
||||
),
|
||||
}),
|
||||
)
|
||||
.min(1),
|
||||
dropped_qualifiers: z
|
||||
.array(droppedCQualifierSchema)
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(droppedCQualifiersDescription),
|
||||
effects: z.strictObject({
|
||||
scope: z.literal("session-analysis-database"),
|
||||
source_bytes_modified: z.literal(false),
|
||||
}),
|
||||
});
|
||||
|
||||
/** Types and component identities remain analysis database observations. */
|
||||
export const nativeDataTypeSchema = z.strictObject({
|
||||
status: z.enum(["available", "unavailable"]),
|
||||
@@ -29,7 +94,11 @@ export const nativeDataTypeSchema = z.strictObject({
|
||||
"unsupported",
|
||||
"unavailable",
|
||||
]),
|
||||
source: z.literal("analysis-database"),
|
||||
source: z
|
||||
.enum(["analysis-database", "caller-defined"])
|
||||
.describe(
|
||||
"caller-defined: stored by define_native_data_types under /rea_caller_defined, not recovered by analysis. analysis-database: every other origin.",
|
||||
),
|
||||
source_archive: z.string().nullable(),
|
||||
address: z.string().nullable(),
|
||||
size_bytes: z.int().nonnegative().nullable(),
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
import { z } from "zod";
|
||||
import { functionDossierSchema } from "../native/functionDossier.js";
|
||||
import {
|
||||
DEFAULT_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
MAXIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
MINIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
DEFAULT_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
MAXIMUM_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
MINIMUM_GHIDRA_C_TEXT_UTF16,
|
||||
} from "../analysisResourceLimits.js";
|
||||
import {
|
||||
droppedCQualifierSchema,
|
||||
droppedCQualifiersDescription,
|
||||
} from "./nativeDataType.js";
|
||||
|
||||
/** One explicit function's analyst-authored metadata changes. */
|
||||
export const nativeFunctionAnnotationsInputSchema = z
|
||||
@@ -19,13 +31,56 @@ export const nativeFunctionAnnotationsInputSchema = z
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Inline entry comment; empty text clears it"),
|
||||
signature: z
|
||||
.string()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(
|
||||
"C prototype using types the database already holds, e.g. `double f(struct session *s, unsigned mask)`. Its function name is a placeholder; rename with name. Add missing types with define_native_data_types first.",
|
||||
),
|
||||
signature_max_utf16: z
|
||||
.int()
|
||||
.min(MINIMUM_GHIDRA_C_TEXT_UTF16)
|
||||
.max(MAXIMUM_GHIDRA_SIGNATURE_MAX_UTF16)
|
||||
.optional()
|
||||
.describe(
|
||||
`Longest signature to parse, in UTF-16 code units (default ${String(DEFAULT_GHIDRA_SIGNATURE_MAX_UTF16)}); the C parser cannot be cancelled`,
|
||||
),
|
||||
parenthesis_max_depth: z
|
||||
.int()
|
||||
.min(MINIMUM_GHIDRA_C_PARENTHESIS_DEPTH)
|
||||
.max(MAXIMUM_GHIDRA_C_PARENTHESIS_DEPTH)
|
||||
.optional()
|
||||
.describe(
|
||||
`Deepest parenthesis nesting to parse (default ${String(DEFAULT_GHIDRA_C_PARENTHESIS_DEPTH)})`,
|
||||
),
|
||||
})
|
||||
.refine(
|
||||
(value) =>
|
||||
value.name !== undefined ||
|
||||
value.comment !== undefined ||
|
||||
value.inline_comment !== undefined,
|
||||
value.inline_comment !== undefined ||
|
||||
value.signature !== undefined,
|
||||
"Supply at least one annotation change",
|
||||
)
|
||||
.refine(
|
||||
(value) =>
|
||||
value.signature_max_utf16 === undefined || value.signature !== undefined,
|
||||
{
|
||||
path: ["signature_max_utf16"],
|
||||
message:
|
||||
"signature_max_utf16 bounds a signature; supply signature with it",
|
||||
},
|
||||
)
|
||||
.refine(
|
||||
(value) =>
|
||||
value.parenthesis_max_depth === undefined ||
|
||||
value.signature !== undefined,
|
||||
{
|
||||
path: ["parenthesis_max_depth"],
|
||||
message:
|
||||
"parenthesis_max_depth bounds a signature; supply signature with it",
|
||||
},
|
||||
);
|
||||
|
||||
/** Readback and refreshed analysis after one atomic metadata edit. */
|
||||
@@ -36,8 +91,39 @@ export const nativeFunctionAnnotationsSchema = z
|
||||
name: z.string().min(1),
|
||||
comment: z.string().nullable(),
|
||||
inline_comment: z.string().nullable(),
|
||||
signature: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Formal prototype after the edit. The signature field accepts it back when its function and type names are C identifiers",
|
||||
),
|
||||
signature_source: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Ghidra source of the prototype: user_defined is caller-authored; default, analysis and imported are not",
|
||||
),
|
||||
calling_convention: z
|
||||
.string()
|
||||
.min(1)
|
||||
.describe(
|
||||
"Convention Ghidra assigns parameter storage with; unknown when the function has none recorded",
|
||||
),
|
||||
}),
|
||||
dossier: functionDossierSchema,
|
||||
dropped_qualifiers: z
|
||||
.array(
|
||||
droppedCQualifierSchema.safeExtend({
|
||||
parameter_index: z
|
||||
.int()
|
||||
.nonnegative()
|
||||
.nullable()
|
||||
.describe("Zero-based parameter; null for the return type"),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe(droppedCQualifiersDescription),
|
||||
effects: z.strictObject({
|
||||
scope: z.literal("session-analysis-database"),
|
||||
source_bytes_modified: z.literal(false),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Function analysis and annotation operations admitted by the Ghidra adapter. */
|
||||
export const GHIDRA_FUNCTION_OPERATIONS = [
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"inspect_native_data_type",
|
||||
"inspect_native_instruction",
|
||||
"resolve_native_call_targets",
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
nativeFunctionAnnotationsInputSchema,
|
||||
nativeFunctionAnnotationsSchema,
|
||||
} from "../domain/native/nativeFunctionAnnotations.js";
|
||||
import { nativeDataTypeSchema } from "../domain/native/nativeDataType.js";
|
||||
import {
|
||||
nativeDataTypeDefinitionsInputSchema,
|
||||
nativeDataTypeDefinitionsSchema,
|
||||
nativeDataTypeSchema,
|
||||
} from "../domain/native/nativeDataType.js";
|
||||
import {
|
||||
nativeInstructionSchema,
|
||||
nativeCallTargetsSchema,
|
||||
@@ -74,6 +78,7 @@ const directProcedure = { document, procedure };
|
||||
|
||||
const inputSchemas = {
|
||||
annotate_native_function: nativeFunctionAnnotationsInputSchema,
|
||||
define_native_data_types: nativeDataTypeDefinitionsInputSchema,
|
||||
inspect_native_data_type: z
|
||||
.object({
|
||||
document,
|
||||
@@ -352,6 +357,7 @@ const resultSchemas = {
|
||||
procedure_pseudo_code: z.string().nullable(),
|
||||
read_function_instructions: ghidraFunctionInstructionWindow,
|
||||
inspect_native_instruction: ghidraInstruction,
|
||||
define_native_data_types: nativeDataTypeDefinitionsSchema,
|
||||
inspect_native_data_type: nativeDataTypeSchema,
|
||||
resolve_native_call_targets: nativeCallTargetsSchema,
|
||||
procedure_references: procedureReferences,
|
||||
|
||||
@@ -4230,6 +4230,9 @@ describe("Ghidra empty annotation reference facets", () => {
|
||||
name: "fixture_main",
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
signature: "undefined fixture_main()",
|
||||
signature_source: "default",
|
||||
calling_convention: "unknown",
|
||||
},
|
||||
dossier: { ...dossier, incoming_references: [], outgoing_references: [] },
|
||||
effects: {
|
||||
@@ -4263,6 +4266,9 @@ describe("Ghidra empty annotation reference facets", () => {
|
||||
name: "fixture_main",
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
signature: "undefined fixture_main()",
|
||||
signature_source: "default",
|
||||
calling_convention: "unknown",
|
||||
},
|
||||
dossier: {
|
||||
...dossier,
|
||||
|
||||
@@ -189,11 +189,21 @@ export const ghidraOperationLimitations = (
|
||||
case "annotate_native_function":
|
||||
return [
|
||||
"Names use Ghidra USER_DEFINED source. Name writes accept a leaf name or a fully qualified name within the existing namespace; readback uses the fully qualified name and can be reused without adding namespace prefixes. Edits retain the current namespace; other namespace-like text remains literal leaf-name text. Regular comments map to PRE and inline comments to EOL at the exact function entry. Changes commit together after readback and refreshed analysis; failure rolls them all back.",
|
||||
"A signature is one C prototype, parsed by Ghidra's C parser against the database's types and applied with USER_DEFINED source and Ghidra-assigned parameter storage; annotations.signature_source reports that source. The prototype's function name is not applied. When the function has no calling convention and the prototype names none, the compiler specification's default convention, which Ghidra uses to assign that storage, is recorded; annotations.calling_convention reports the result. const, volatile, restrict, __unaligned and __w64 have no Ghidra representation and are not recorded; dropped_qualifiers lists each one with its line, column and parameter. _Noreturn is applied.",
|
||||
"Refused with nothing applied: a thunk; an undefined type; a type name the database holds as different types; attributes, __declspec, _Alignas and asm labels; __ptr32, __ptr64, __near and __far; storage-class and inline specifiers; preprocessor directives; string and character literals; a function body, default argument or second declaration; function-pointer parameters; a repeated parameter name; a prototype Ghidra would apply differently (an array parameter, a parameter name another symbol holds, a calling convention the compiler specification lacks); and a prototype Ghidra's parser reports a diagnostic for. An undefined type name without struct, union or enum is reported as a syntax error at the next token. Ghidra's C parser cannot be cancelled: signature_max_utf16 (default 2048, range 16..4096) bounds the prototype's length and parenthesis_max_depth (default 8, range 1..12) its nesting.",
|
||||
"Annotation text rejects NUL and unpaired Unicode surrogates before mutation, with the field and UTF-16 index in the error. Supported Unicode and line endings are preserved.",
|
||||
source === "owned-checkpoint"
|
||||
? "Metadata edits invalidate immutable analysis snapshots. Normal close saves edits to the owned checkpoint; cancellation or process failure can lose edits after the last successful save. CLI returns the updated dossier before cleanup."
|
||||
: "Metadata edits invalidate immutable analysis snapshots and are discarded on close. CLI returns the updated dossier before session cleanup; this is not a saved Ghidra project.",
|
||||
];
|
||||
case "define_native_data_types":
|
||||
return [
|
||||
"Definitions are parsed by Ghidra's C parser and stored in category /rea_caller_defined; inspect_native_data_type reports them with source caller-defined. They are the caller's assertions about layout, not observations of the target. Layout follows the program's data organization. Applied as written: #pragma pack (including push and pop), bit-fields, flexible and zero-length array members (stored with size 0), enum values and several typedef declarators. const, volatile, restrict, __unaligned and __w64 have no Ghidra representation and are not recorded; dropped_qualifiers lists each one with its line and column.",
|
||||
"Refused with nothing stored: a type name the database already holds in any category, unless it is an equivalent caller-defined type, which reports unchanged; a member type name the database holds as different types; attributes (including packed, aligned and [[...]]), __declspec, __readableTo, _Alignas and asm labels; __ptr32, __ptr64, __near and __far; __pragma, _Static_assert and Objective-C @ blocks; storage-class specifiers; variable declarations and any statement that is not a struct, union, enum or typedef definition; preprocessor directives other than #pragma pack in a form Ghidra applies; string and character literals; function declarations and function-pointer members; structs, unions or enums without members, including the empty enum Ghidra invents for an undefined tag; repeated member names; unnamed struct, union or enum definitions other than a typedef of an unnamed struct or union; an enum value, array size or bit-field width other than one decimal or hex integer literal within int, optionally negated (Ghidra evaluates expressions differently from C; write the computed value); a type chained more than 256 levels deep; and text Ghidra's parser reports a diagnostic for, such as a repeated enumerator name. Ghidra's C parser cannot be cancelled: declarations_max_utf16 (default 4096, range 16..8192) bounds the text's length, and a parenthesis is refused, since Ghidra stores no parenthesized form in a definition as written; split larger sets across calls.",
|
||||
source === "owned-checkpoint"
|
||||
? "Metadata edits invalidate immutable analysis snapshots. Normal close saves edits to the owned checkpoint; cancellation or process failure can lose edits after the last successful save."
|
||||
: "Metadata edits invalidate immutable analysis snapshots and are discarded on close; this is not a saved Ghidra project.",
|
||||
];
|
||||
case "set_address_name":
|
||||
case "set_addresses_names":
|
||||
return [
|
||||
|
||||
@@ -145,6 +145,7 @@ const FLOW_INDEPENDENT_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"set_address_name",
|
||||
"set_addresses_names",
|
||||
"inspect_native_data_type",
|
||||
"define_native_data_types",
|
||||
]);
|
||||
|
||||
/** The observed facts a defect record's declared scope is checked against. */
|
||||
|
||||
@@ -209,6 +209,45 @@ const createGhidraSessionError = (failure: {
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* Refusals of a prototype or type definition. The bridge rolled the call back
|
||||
* and the session is unaffected, so their diagnostics are request-scoped.
|
||||
*/
|
||||
export type GhidraTypeEditRefusalCode =
|
||||
| "invalid_function_signature"
|
||||
| "unknown_data_type"
|
||||
| "ambiguous_data_type"
|
||||
| "invalid_type_declarations"
|
||||
| "data_type_conflict"
|
||||
| "conflicting_type_definitions";
|
||||
|
||||
/** Bridge refusals of caller C text over a bound on Ghidra's uncancellable parser. */
|
||||
export const GHIDRA_C_PARSER_LIMIT_CODES = [
|
||||
"signature_length_limit",
|
||||
"declarations_length_limit",
|
||||
"parenthesis_depth_limit",
|
||||
"type_depth_limit",
|
||||
] as const;
|
||||
export type GhidraCParserLimitCode =
|
||||
(typeof GHIDRA_C_PARSER_LIMIT_CODES)[number];
|
||||
|
||||
export const isGhidraCParserLimitCode = (
|
||||
code: string | undefined,
|
||||
): code is GhidraCParserLimitCode =>
|
||||
(GHIDRA_C_PARSER_LIMIT_CODES as readonly (string | undefined)[]).includes(
|
||||
code,
|
||||
);
|
||||
|
||||
export const isGhidraTypeEditRefusalCode = (
|
||||
code: string | undefined,
|
||||
): code is GhidraTypeEditRefusalCode =>
|
||||
code === "invalid_function_signature" ||
|
||||
code === "unknown_data_type" ||
|
||||
code === "ambiguous_data_type" ||
|
||||
code === "invalid_type_declarations" ||
|
||||
code === "data_type_conflict" ||
|
||||
code === "conflicting_type_definitions";
|
||||
|
||||
/** Bridge input failures share classification with their domain error projection. */
|
||||
export const isGhidraInputFailureCode = (code: string | undefined): boolean =>
|
||||
code === "invalid_request" ||
|
||||
@@ -245,6 +284,8 @@ export const bindGhidraSessionFailure =
|
||||
kind === "remote" &&
|
||||
(isGhidraInputFailureCode(options.remoteCode) ||
|
||||
options.remoteCode === "invalid_function_name" ||
|
||||
isGhidraTypeEditRefusalCode(options.remoteCode) ||
|
||||
isGhidraCParserLimitCode(options.remoteCode) ||
|
||||
ghidraFileOffsetOutcome(options.remoteCode) !== undefined ||
|
||||
isGhidraByteSearchCursorMismatch(options.remoteCode))
|
||||
? "request"
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
import { analysisSettingLimit } from "../domain/analysisSettingDefinitions.js";
|
||||
import { MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS } from "../domain/analysisResourceLimits.js";
|
||||
import {
|
||||
MAX_GHIDRA_DECOMPILE_TIMEOUT_SECONDS,
|
||||
DEFAULT_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
DEFAULT_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
DEFAULT_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
GHIDRA_C_MAX_TYPE_DEPTH,
|
||||
MAXIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
MINIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
MAXIMUM_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
MINIMUM_GHIDRA_C_TEXT_UTF16,
|
||||
} from "../domain/analysisResourceLimits.js";
|
||||
import { z } from "zod";
|
||||
import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
|
||||
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
|
||||
@@ -38,12 +49,19 @@ import {
|
||||
GhidraCheckpointSupersededError,
|
||||
} from "./GhidraCheckpoint.js";
|
||||
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
|
||||
import type { AnalysisErrorOptions } from "../domain/analysisErrorBase.js";
|
||||
import { parseLimitConstraint } from "../domain/parseFailureAnalysisError.js";
|
||||
import { decodeLimit } from "../domain/parseFailure.js";
|
||||
import { fixedAllowanceOptions } from "../domain/fixedAllowanceRemediation.js";
|
||||
import { GhidraLaunchError } from "./GhidraLauncher.js";
|
||||
import type { GhidraSessionSource } from "./GhidraProviderCapabilities.js";
|
||||
import {
|
||||
GHIDRA_STARTUP_DEADLINE_ELAPSED,
|
||||
isGhidraInputFailureCode,
|
||||
isGhidraTypeEditRefusalCode,
|
||||
isGhidraCParserLimitCode,
|
||||
isGhidraRemoteCancellation,
|
||||
type GhidraTypeEditRefusalCode,
|
||||
type GhidraSessionError,
|
||||
} from "./GhidraSessionError.js";
|
||||
import {
|
||||
@@ -264,6 +282,38 @@ const projectPrimarySessionError = (
|
||||
return new AnalysisInputError(operation, context, [
|
||||
{ path: ["name"], reason: "invalid_value", message: failure.message },
|
||||
]);
|
||||
const overLimit = ghidraCParserLimitRefusal(
|
||||
operation,
|
||||
failure,
|
||||
request,
|
||||
context,
|
||||
);
|
||||
if (overLimit !== undefined) return overLimit;
|
||||
const typeEdit =
|
||||
failure.kind === "remote"
|
||||
? ghidraTypeEditRefusal(operation, failure.remoteCode)
|
||||
: undefined;
|
||||
if (typeEdit !== undefined)
|
||||
return new AnalysisInputError(
|
||||
operation,
|
||||
{
|
||||
...context,
|
||||
...(typeEdit.recovery === undefined
|
||||
? {}
|
||||
: {
|
||||
remediationAction: typeEdit.recovery.action,
|
||||
conformsToInputContract: true,
|
||||
related: { operations: typeEdit.recovery.operations },
|
||||
}),
|
||||
},
|
||||
[
|
||||
{
|
||||
path: [typeEdit.field],
|
||||
reason: "invalid_value",
|
||||
message: failure.message,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (
|
||||
failure.kind === "remote" &&
|
||||
(failure.remoteCode === "procedure_not_found" ||
|
||||
@@ -697,6 +747,201 @@ const projectObservedJvmMemoryFailure = (
|
||||
/** Outcome addition that only a caller keeping the Ghidra session receives. */
|
||||
const GHIDRA_SESSION_RETAINED = "The Ghidra session remains usable.";
|
||||
|
||||
type GhidraTypeEditOperation =
|
||||
| "annotate_native_function"
|
||||
| "define_native_data_types";
|
||||
|
||||
interface GhidraTypeEditRefusal {
|
||||
/** The argument the refusal is attributed to, per operation that can raise it. */
|
||||
readonly fields: Partial<
|
||||
Record<GhidraTypeEditOperation, "signature" | "declarations">
|
||||
>;
|
||||
/** Present when the text is well formed and the database state refuses it. */
|
||||
readonly recovery?: {
|
||||
readonly action: string;
|
||||
readonly operations: readonly string[];
|
||||
};
|
||||
}
|
||||
|
||||
/** The operation and argument each refused prototype or type definition is attributed to. */
|
||||
const GHIDRA_TYPE_EDIT_REFUSALS: Readonly<
|
||||
Record<GhidraTypeEditRefusalCode, GhidraTypeEditRefusal>
|
||||
> = {
|
||||
invalid_function_signature: {
|
||||
fields: { annotate_native_function: "signature" },
|
||||
},
|
||||
unknown_data_type: {
|
||||
fields: { annotate_native_function: "signature" },
|
||||
recovery: {
|
||||
action:
|
||||
"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.",
|
||||
operations: ["define_native_data_types"],
|
||||
},
|
||||
},
|
||||
ambiguous_data_type: {
|
||||
fields: {
|
||||
annotate_native_function: "signature",
|
||||
define_native_data_types: "declarations",
|
||||
},
|
||||
recovery: {
|
||||
action:
|
||||
"Use a type whose name is unique in the database: inspect the listed types (MCP inspect_native_data_type; CLI rea inspect-native-data-type) and define the intended layout under a new name. This release cannot select a type by category path in C text; nothing in this call was applied.",
|
||||
operations: ["inspect_native_data_type", "define_native_data_types"],
|
||||
},
|
||||
},
|
||||
invalid_type_declarations: {
|
||||
fields: { define_native_data_types: "declarations" },
|
||||
},
|
||||
data_type_conflict: {
|
||||
fields: { define_native_data_types: "declarations" },
|
||||
recovery: {
|
||||
action:
|
||||
"Use another type name, or inspect the existing type (MCP inspect_native_data_type; CLI rea inspect-native-data-type) and use it unchanged. REA does not replace an existing type; nothing in this call was stored.",
|
||||
operations: ["inspect_native_data_type"],
|
||||
},
|
||||
},
|
||||
conflicting_type_definitions: {
|
||||
fields: { define_native_data_types: "declarations" },
|
||||
recovery: {
|
||||
action:
|
||||
"Give each distinct type its own name. C keeps a struct, union or enum tag and a typedef in separate namespaces, and Ghidra stores both under one name. Repeat this call (MCP define_native_data_types; CLI rea define-native-data-types) with the renamed text. Nothing in this call was stored.",
|
||||
operations: ["define_native_data_types"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const ghidraTypeEditRefusal = (
|
||||
operation: string,
|
||||
remoteCode: string | undefined,
|
||||
):
|
||||
| (Pick<GhidraTypeEditRefusal, "recovery"> & {
|
||||
readonly field: "signature" | "declarations";
|
||||
})
|
||||
| undefined => {
|
||||
if (
|
||||
!isGhidraTypeEditRefusalCode(remoteCode) ||
|
||||
(operation !== "annotate_native_function" &&
|
||||
operation !== "define_native_data_types")
|
||||
)
|
||||
return undefined;
|
||||
const refusal = GHIDRA_TYPE_EDIT_REFUSALS[remoteCode];
|
||||
const field = refusal.fields[operation];
|
||||
return field === undefined
|
||||
? undefined
|
||||
: {
|
||||
field,
|
||||
...(refusal.recovery === undefined
|
||||
? {}
|
||||
: { recovery: refusal.recovery }),
|
||||
};
|
||||
};
|
||||
|
||||
/** The per-call control that bounds each Ghidra C parser refusal. */
|
||||
const GHIDRA_C_PARSER_CONTROLS = {
|
||||
signature_length_limit: {
|
||||
parameter: "signature_max_utf16",
|
||||
unit: "UTF-16 code units",
|
||||
minimum: MINIMUM_GHIDRA_C_TEXT_UTF16,
|
||||
defaultValue: DEFAULT_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
maximum: MAXIMUM_GHIDRA_SIGNATURE_MAX_UTF16,
|
||||
},
|
||||
declarations_length_limit: {
|
||||
parameter: "declarations_max_utf16",
|
||||
unit: "UTF-16 code units",
|
||||
minimum: MINIMUM_GHIDRA_C_TEXT_UTF16,
|
||||
defaultValue: DEFAULT_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
maximum: MAXIMUM_GHIDRA_TYPE_DECLARATIONS_MAX_UTF16,
|
||||
},
|
||||
parenthesis_depth_limit: {
|
||||
parameter: "parenthesis_max_depth",
|
||||
unit: "levels",
|
||||
minimum: MINIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
defaultValue: DEFAULT_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
maximum: MAXIMUM_GHIDRA_C_PARENTHESIS_DEPTH,
|
||||
},
|
||||
} as const;
|
||||
|
||||
const GHIDRA_C_PARSER_LIMIT_REASON =
|
||||
"Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. Nothing in this call was applied";
|
||||
|
||||
/**
|
||||
* Caller C text over a per-call bound on Ghidra's parser. The bridge refused
|
||||
* it before parsing, so the session is unaffected. The effective bound comes
|
||||
* from the request; the bridge measured the text's whole length or deepest
|
||||
* nesting and sends it as the required value.
|
||||
*/
|
||||
const ghidraCParserLimitRefusal = (
|
||||
operation: string,
|
||||
failure: GhidraSessionError,
|
||||
request: Readonly<Record<string, JsonValue>> | undefined,
|
||||
context: AnalysisErrorOptions,
|
||||
): AnalysisResourceConstraintError | undefined => {
|
||||
if (
|
||||
failure.kind !== "remote" ||
|
||||
!isGhidraCParserLimitCode(failure.remoteCode)
|
||||
)
|
||||
return undefined;
|
||||
const { cause: _cause, ...options } = context;
|
||||
// A stack-safety bound on Ghidra's recursive type code: no value raises it safely.
|
||||
if (failure.remoteCode === "type_depth_limit")
|
||||
return parseLimitConstraint(
|
||||
operation,
|
||||
"memory",
|
||||
decodeLimit(
|
||||
"c-declarations",
|
||||
`${failure.message}, above the ${String(GHIDRA_C_MAX_TYPE_DEPTH)}-level limit. Nothing in this call was applied`,
|
||||
{
|
||||
name: "Ghidra C type depth",
|
||||
maximum: GHIDRA_C_MAX_TYPE_DEPTH,
|
||||
},
|
||||
{ cause: failure },
|
||||
),
|
||||
{
|
||||
...options,
|
||||
requestSent: true,
|
||||
...fixedAllowanceOptions("The Ghidra C type depth allowance", "count", {
|
||||
limit: GHIDRA_C_MAX_TYPE_DEPTH,
|
||||
unit: "levels",
|
||||
narrowing: `Ghidra stores and compares types recursively and exhausts its stack on deeper chains, so the limit is fixed. The depth counts through typedefs, members and existing database types, so naming intermediate types or splitting the definitions across calls does not reduce it; only fewer nested pointer, array, typedef or member levels does.`,
|
||||
}),
|
||||
},
|
||||
);
|
||||
const control = GHIDRA_C_PARSER_CONTROLS[failure.remoteCode];
|
||||
const requested = request?.[control.parameter];
|
||||
const effective =
|
||||
typeof requested === "number" ? requested : control.defaultValue;
|
||||
const required =
|
||||
failure.cause instanceof GhidraRemoteError
|
||||
? failure.cause.requiredValue
|
||||
: undefined;
|
||||
return parseLimitConstraint(
|
||||
operation,
|
||||
"cpu",
|
||||
decodeLimit(
|
||||
"c-declarations",
|
||||
`${failure.message}; ${control.parameter} admits at most ${String(effective)} ${control.unit}. ${GHIDRA_C_PARSER_LIMIT_REASON}`,
|
||||
{ name: control.parameter, maximum: effective },
|
||||
{ cause: failure },
|
||||
),
|
||||
{
|
||||
...options,
|
||||
retryable: false,
|
||||
requestSent: true,
|
||||
limit: {
|
||||
control_kind: "parameter",
|
||||
parameter: control.parameter,
|
||||
effective_value: effective,
|
||||
unit: "count",
|
||||
minimum: control.minimum,
|
||||
maximum: control.maximum,
|
||||
default_value: control.defaultValue,
|
||||
applies_at: "next_call",
|
||||
...(required === undefined ? {} : { required_value: required }),
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/** The same addition when a failed search leaves session annotations intact. */
|
||||
const GHIDRA_ANNOTATIONS_RETAINED =
|
||||
"The active analysis session and annotations remain available.";
|
||||
|
||||
@@ -308,6 +308,7 @@ describe("Ghidra disabled analyzer report", () => {
|
||||
|
||||
const databaseEdits = [
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"set_address_name",
|
||||
"set_addresses_names",
|
||||
] as const;
|
||||
|
||||
@@ -28,6 +28,7 @@ export const GHIDRA_SESSION_CAPABILITIES = [
|
||||
/** Methods that edit the session database; read-only bridges omit them. */
|
||||
export const GHIDRA_MUTATING_OPERATIONS: ReadonlySet<string> = new Set([
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
...GHIDRA_NAMING_OPERATIONS,
|
||||
]);
|
||||
|
||||
|
||||
@@ -96,6 +96,28 @@ const fixture = (version = "12.2", coverage?: RelationshipCoverage) => {
|
||||
name = "original";
|
||||
return err(new GhidraSessionError("cancelled", "Cancelled"));
|
||||
}
|
||||
// The bridge rolls a refused prototype or type definition back.
|
||||
if (operation === "define_native_data_types")
|
||||
return err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"The database already holds types with these names: session",
|
||||
{},
|
||||
{ remoteCode: "data_type_conflict" },
|
||||
),
|
||||
);
|
||||
if (
|
||||
operation === "annotate_native_function" &&
|
||||
parameters.signature !== undefined
|
||||
)
|
||||
return err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
"signature repeats parameter name a",
|
||||
{},
|
||||
{ remoteCode: "invalid_function_signature" },
|
||||
),
|
||||
);
|
||||
if (operation === "annotate_native_function") {
|
||||
if (typeof parameters.name !== "string")
|
||||
throw new Error("Expected an annotation name");
|
||||
@@ -128,6 +150,9 @@ const fixture = (version = "12.2", coverage?: RelationshipCoverage) => {
|
||||
name,
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
signature: `undefined ${name}()`,
|
||||
signature_source: "default",
|
||||
calling_convention: "unknown",
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
@@ -457,6 +482,47 @@ describe("Ghidra snapshot cache", () => {
|
||||
await changed.session.close();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
operation: "define_native_data_types",
|
||||
edit: { declarations: "struct session { long other; };" },
|
||||
field: "declarations",
|
||||
},
|
||||
{
|
||||
operation: "annotate_native_function",
|
||||
edit: { procedure: "0x1000", signature: "int f(int a, int a)" },
|
||||
field: "signature",
|
||||
},
|
||||
] as const)(
|
||||
"stops replaying the snapshot once $operation is dispatched, even when the bridge refuses it",
|
||||
async ({ operation, edit, field }) => {
|
||||
const { session, calls } = fixture();
|
||||
await open(session);
|
||||
const parameters = { procedure: "0x1000", document: "fixture" };
|
||||
const reads = () =>
|
||||
calls.filter((call) => call === "procedure_pseudo_code").length;
|
||||
for (let index = 0; index < 2; index += 1)
|
||||
expect(
|
||||
(await session.execute("procedure_pseudo_code", parameters)).ok,
|
||||
).toBe(true);
|
||||
// The second read replayed the immutable snapshot.
|
||||
expect(reads()).toBe(1);
|
||||
expect(session.exportAnalysisSnapshot().ok).toBe(true);
|
||||
expect(await session.execute(operation, edit)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError", issues: [{ path: [field] }] },
|
||||
});
|
||||
// A failed reply cannot prove the write rolled back, so reads stay live.
|
||||
expect(session.exportAnalysisSnapshot().ok).toBe(false);
|
||||
for (let index = 0; index < 2; index += 1)
|
||||
expect(
|
||||
(await session.execute("procedure_pseudo_code", parameters)).ok,
|
||||
).toBe(true);
|
||||
expect(reads()).toBe(3);
|
||||
await session.close();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps annotation-dependent reads live after cancellation reimports the original artifact", async () => {
|
||||
const { session, calls, cancellationReady } = fixture();
|
||||
await open(session);
|
||||
|
||||
@@ -41,3 +41,29 @@ it("refuses a candidate list that cannot describe an ambiguity", () => {
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the measured value a bounded refusal requires", () => {
|
||||
expect(
|
||||
failure({
|
||||
code: "parenthesis_depth_limit",
|
||||
message: "signature nests parentheses 10 levels deep",
|
||||
required_value: 10,
|
||||
}),
|
||||
).toMatchObject({ code: "parenthesis_depth_limit", requiredValue: 10 });
|
||||
expect(
|
||||
failure({ code: "procedure_not_found", message: "Unknown" })?.requiredValue,
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
ghidraReplyEnvelope.parse(
|
||||
JSON.stringify({
|
||||
id: 3,
|
||||
ok: false,
|
||||
error: {
|
||||
code: "signature_length_limit",
|
||||
message: "x",
|
||||
required_value: 0,
|
||||
},
|
||||
}),
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
+10
-1
@@ -22,6 +22,8 @@ const responseSchema = z.discriminatedUnion("ok", [
|
||||
message: z.string().min(1),
|
||||
/** Every matching candidate address, sent for an ambiguous selector only. */
|
||||
candidates: z.array(z.string().min(1)).min(2).exactOptional(),
|
||||
/** The measured value a per-call control must admit, for a bounded refusal only. */
|
||||
required_value: z.int().positive().exactOptional(),
|
||||
})
|
||||
.strict(),
|
||||
}),
|
||||
@@ -37,6 +39,8 @@ export class GhidraRemoteError extends Error {
|
||||
message: string,
|
||||
/** Every matching candidate address of an ambiguous selector. */
|
||||
readonly candidates?: readonly string[],
|
||||
/** The measured value a per-call control must admit. */
|
||||
readonly requiredValue?: number,
|
||||
) {
|
||||
super(message);
|
||||
this.name = "GhidraRemoteError";
|
||||
@@ -47,7 +51,12 @@ export class GhidraRemoteError extends Error {
|
||||
export const ghidraRemoteError = (
|
||||
error: Extract<GhidraBridgeResponse, { ok: false }>["error"],
|
||||
): GhidraRemoteError =>
|
||||
new GhidraRemoteError(error.code, error.message, error.candidates);
|
||||
new GhidraRemoteError(
|
||||
error.code,
|
||||
error.message,
|
||||
error.candidates,
|
||||
error.required_value,
|
||||
);
|
||||
|
||||
/** Parse one complete Java-bridge response without accepting extra fields. */
|
||||
const parseGhidraResponseLine = (
|
||||
|
||||
@@ -287,6 +287,9 @@ it("rejects contradictory annotation readback across the provider and MCP bounda
|
||||
name: dossier.procedure.name,
|
||||
comment: null,
|
||||
inline_comment: "Finding",
|
||||
signature: "undefined fixture_main()",
|
||||
signature_source: "default",
|
||||
calling_convention: "unknown",
|
||||
};
|
||||
const effects = {
|
||||
scope: "session-analysis-database",
|
||||
|
||||
@@ -0,0 +1,779 @@
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { functionDossierSchema } from "../../../src/domain/native/functionDossier.js";
|
||||
import { ghidraFunctionDossier } from "../../../src/domain/ghidraValues.fixture.js";
|
||||
import {
|
||||
jsonValueSchema,
|
||||
type JsonValue,
|
||||
} from "../../../src/domain/jsonValue.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import {
|
||||
bindGhidraSessionFailure,
|
||||
GhidraSessionError,
|
||||
} from "../../../src/ghidra/GhidraSessionError.js";
|
||||
import { GhidraRemoteError } from "../../../src/ghidra/protocol.js";
|
||||
import { connectGhidraMcp, ghidraFixtureResult } from "./ghidraMcpHarness.js";
|
||||
|
||||
/** A bridge refusal as the client receives it, with the value the bridge measured. */
|
||||
const bridgeRefusal = (
|
||||
remoteCode: string,
|
||||
message: string,
|
||||
requiredValue: number,
|
||||
): GhidraSessionError =>
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
message,
|
||||
{},
|
||||
{
|
||||
remoteCode,
|
||||
cause: new GhidraRemoteError(
|
||||
remoteCode,
|
||||
message,
|
||||
undefined,
|
||||
requiredValue,
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
const SESSION_TYPE = {
|
||||
id: "/rea_caller_defined/session",
|
||||
name: "session",
|
||||
kind: "struct",
|
||||
size_bytes: 56,
|
||||
status: "defined",
|
||||
};
|
||||
const DEFINITION_EFFECTS = {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
};
|
||||
const DECLARATIONS = "struct session { int id; struct session *next; };";
|
||||
const SIGNATURE = "double total(struct session *s, unsigned mask)";
|
||||
|
||||
const annotationReply = (signature: string, source: string) => {
|
||||
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
|
||||
return jsonValueSchema.parse({
|
||||
annotations: {
|
||||
address: dossier.procedure.address,
|
||||
name: dossier.procedure.name,
|
||||
comment: null,
|
||||
inline_comment: null,
|
||||
signature,
|
||||
signature_source: source,
|
||||
calling_convention: "__stdcall",
|
||||
},
|
||||
dossier,
|
||||
effects: {
|
||||
scope: "session-analysis-database",
|
||||
source_bytes_modified: false,
|
||||
persists_after_close: false,
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
it("returns caller-defined type readback and refuses a reply outside the contract", async () => {
|
||||
let output: JsonValue = {
|
||||
types: [SESSION_TYPE],
|
||||
effects: DEFINITION_EFFECTS,
|
||||
};
|
||||
const requests: Readonly<Record<string, JsonValue>>[] = [];
|
||||
const harness = await connectGhidraMcp(
|
||||
"ghidra-type-definitions",
|
||||
(_, input) => {
|
||||
requests.push(input);
|
||||
return Promise.resolve(ok(output));
|
||||
},
|
||||
);
|
||||
try {
|
||||
const defined = await harness.mcp.callTool({
|
||||
name: "define_native_data_types",
|
||||
arguments: { declarations: DECLARATIONS },
|
||||
});
|
||||
expect(defined.isError).not.toBe(true);
|
||||
expect(defined.structuredContent).toMatchObject({
|
||||
operation: "define_native_data_types",
|
||||
normalized_result: { types: [SESSION_TYPE], effects: DEFINITION_EFFECTS },
|
||||
});
|
||||
// The caller's text reaches the bridge unchanged.
|
||||
expect(requests).toEqual([{ declarations: DECLARATIONS }]);
|
||||
for (const value of [
|
||||
{ types: [], effects: DEFINITION_EFFECTS },
|
||||
{
|
||||
types: [{ ...SESSION_TYPE, status: "replaced" }],
|
||||
effects: DEFINITION_EFFECTS,
|
||||
},
|
||||
{
|
||||
types: [{ ...SESSION_TYPE, kind: "pointer" }],
|
||||
effects: DEFINITION_EFFECTS,
|
||||
},
|
||||
{
|
||||
types: [SESSION_TYPE],
|
||||
effects: { ...DEFINITION_EFFECTS, source_bytes_modified: true },
|
||||
},
|
||||
]) {
|
||||
output = jsonValueSchema.parse(value);
|
||||
const reply = await harness.mcp.callTool({
|
||||
name: "define_native_data_types",
|
||||
arguments: { declarations: DECLARATIONS },
|
||||
});
|
||||
expect(parseMcpToolError(reply)).toMatchObject({
|
||||
error: { code: "unreadable_output" },
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports the applied prototype and its source with the annotation readback", async () => {
|
||||
const requests: Readonly<Record<string, JsonValue>>[] = [];
|
||||
let output = annotationReply(
|
||||
"double fixture_main(session * s, uint mask)",
|
||||
"user_defined",
|
||||
);
|
||||
const harness = await connectGhidraMcp("ghidra-signature", (_, input) => {
|
||||
requests.push(input);
|
||||
return Promise.resolve(ok(output));
|
||||
});
|
||||
try {
|
||||
const procedure = "0x401000";
|
||||
const applied = await harness.mcp.callTool({
|
||||
name: "annotate_native_function",
|
||||
arguments: { procedure, signature: SIGNATURE },
|
||||
});
|
||||
expect(applied.isError).not.toBe(true);
|
||||
expect(applied.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
annotations: {
|
||||
signature: "double fixture_main(session * s, uint mask)",
|
||||
signature_source: "user_defined",
|
||||
calling_convention: "__stdcall",
|
||||
},
|
||||
},
|
||||
});
|
||||
// A signature is a complete edit on its own and is forwarded verbatim.
|
||||
expect(requests).toEqual([{ procedure, signature: SIGNATURE }]);
|
||||
// A reply without prototype readback cannot prove what was applied.
|
||||
const { annotations, ...rest } = annotationReply(
|
||||
"int f(void)",
|
||||
"analysis",
|
||||
) as {
|
||||
annotations: Record<string, JsonValue>;
|
||||
};
|
||||
const { signature_source: _source, ...unsourced } = annotations;
|
||||
output = jsonValueSchema.parse({ ...rest, annotations: unsourced });
|
||||
const reply = await harness.mcp.callTool({
|
||||
name: "annotate_native_function",
|
||||
arguments: { procedure, signature: SIGNATURE },
|
||||
});
|
||||
expect(parseMcpToolError(reply)).toMatchObject({
|
||||
error: { code: "unreadable_output" },
|
||||
});
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
operation: "annotate_native_function",
|
||||
remoteCode: "invalid_function_signature",
|
||||
field: "signature",
|
||||
message:
|
||||
'Ghidra\'s C parser rejected signature: Encountered " ";" "; "" at line 1, column 27.',
|
||||
recovery: undefined,
|
||||
},
|
||||
{
|
||||
operation: "annotate_native_function",
|
||||
remoteCode: "unknown_data_type",
|
||||
field: "signature",
|
||||
message: "signature uses types the database does not define: session",
|
||||
recovery: {
|
||||
action: /define_native_data_types.*Nothing in this call was applied/u,
|
||||
operations: ["define_native_data_types"],
|
||||
},
|
||||
},
|
||||
{
|
||||
operation: "define_native_data_types",
|
||||
remoteCode: "invalid_type_declarations",
|
||||
field: "declarations",
|
||||
message:
|
||||
"declarations contains the directive #define at line 2, column 1; Ghidra's C parser would not apply it as written, so nothing was changed",
|
||||
recovery: undefined,
|
||||
},
|
||||
{
|
||||
operation: "define_native_data_types",
|
||||
remoteCode: "data_type_conflict",
|
||||
field: "declarations",
|
||||
message:
|
||||
"The database already holds types with these names: session (existing /session)",
|
||||
recovery: {
|
||||
action:
|
||||
/does not replace an existing type; nothing in this call was stored/u,
|
||||
operations: ["inspect_native_data_type"],
|
||||
},
|
||||
},
|
||||
] as const)(
|
||||
"attributes the $remoteCode refusal to $field and keeps the bridge's reason",
|
||||
async ({ operation, remoteCode, field, message, recovery }) => {
|
||||
const harness = await connectGhidraMcp(
|
||||
`ghidra-${remoteCode}`,
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === operation
|
||||
? err(new GhidraSessionError("remote", message, {}, { remoteCode }))
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const reply = await harness.mcp.callTool({
|
||||
name: operation,
|
||||
arguments:
|
||||
operation === "annotate_native_function"
|
||||
? { procedure: "0x401000", name: "renamed", signature: SIGNATURE }
|
||||
: { declarations: DECLARATIONS },
|
||||
});
|
||||
const { error } = parseMcpToolError(reply);
|
||||
expect(error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation,
|
||||
issues: [{ path: [field], reason: "invalid_value", message }],
|
||||
},
|
||||
});
|
||||
if (recovery === undefined) {
|
||||
expect(error.recovery).toMatchObject({
|
||||
kind: "inspect_input_contract",
|
||||
});
|
||||
} else {
|
||||
expect(error.remediation.action).toMatch(recovery.action);
|
||||
expect(error.details).toMatchObject({
|
||||
related_operations: recovery.operations,
|
||||
});
|
||||
// The text satisfies the schema, so rereading it cannot correct the call.
|
||||
expect(error.recovery).toBeUndefined();
|
||||
}
|
||||
// The refusal leaves the session usable.
|
||||
const next = await harness.mcp.callTool({
|
||||
name: "procedure_info",
|
||||
arguments: { procedure: "0x401000" },
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
operation: "annotate_native_function",
|
||||
field: "signature",
|
||||
parameter: "signature_max_utf16",
|
||||
rangeMaximum: 4096,
|
||||
},
|
||||
{
|
||||
operation: "define_native_data_types",
|
||||
field: "declarations",
|
||||
parameter: "declarations_max_utf16",
|
||||
rangeMaximum: 8192,
|
||||
},
|
||||
] as const)(
|
||||
"refuses $parameter outside its range before the bridge and forwards text of any length",
|
||||
async ({ operation, field, parameter, rangeMaximum }) => {
|
||||
const requests: Readonly<Record<string, JsonValue>>[] = [];
|
||||
const harness = await connectGhidraMcp(
|
||||
`ghidra-${field}-range`,
|
||||
(requested, input) => {
|
||||
requests.push(input);
|
||||
return Promise.resolve(
|
||||
ok(
|
||||
requested === "define_native_data_types"
|
||||
? { types: [SESSION_TYPE], effects: DEFINITION_EFFECTS }
|
||||
: annotationReply("int fixture_main(void)", "user_defined"),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
try {
|
||||
const call = (values: Record<string, JsonValue>) =>
|
||||
harness.mcp.callTool({
|
||||
name: operation,
|
||||
arguments: {
|
||||
...(operation === "annotate_native_function"
|
||||
? { procedure: "0x401000" }
|
||||
: {}),
|
||||
...values,
|
||||
},
|
||||
});
|
||||
const before = harness.calls.length;
|
||||
for (const bound of [15, rangeMaximum + 1]) {
|
||||
const { error } = parseMcpToolError(
|
||||
await call({ [field]: SIGNATURE, [parameter]: bound }),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ path: [parameter] }] },
|
||||
});
|
||||
}
|
||||
if (operation === "annotate_native_function") {
|
||||
// A bound without the text it bounds is an ignored option.
|
||||
const { error } = parseMcpToolError(
|
||||
await call({ name: "renamed", [parameter]: 64 }),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { issues: [{ path: [parameter] }] },
|
||||
});
|
||||
}
|
||||
expect(harness.calls.length).toBe(before);
|
||||
// The bridge measures the text, so a long one is the producer's to refuse.
|
||||
const long = "x".repeat(rangeMaximum + 1);
|
||||
expect((await call({ [field]: long })).isError).not.toBe(true);
|
||||
expect(
|
||||
(await call({ [field]: SIGNATURE, [parameter]: rangeMaximum })).isError,
|
||||
).not.toBe(true);
|
||||
expect(requests.slice(-2).map((request) => request[parameter])).toEqual([
|
||||
undefined,
|
||||
rangeMaximum,
|
||||
]);
|
||||
expect(requests.at(-2)?.[field]).toBe(long);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "a default bound",
|
||||
operation: "annotate_native_function",
|
||||
remoteCode: "signature_length_limit",
|
||||
text: "x".repeat(2049),
|
||||
bound: undefined,
|
||||
limit: {
|
||||
parameter: "signature_max_utf16",
|
||||
effective_value: 2048,
|
||||
minimum: 16,
|
||||
maximum: 4096,
|
||||
default_value: 2048,
|
||||
required_value: 2049,
|
||||
},
|
||||
recovery:
|
||||
/Pass a larger signature_max_utf16 on .*annotate_native_function.*\(at least 2049; range 16\.\.4096\), then retry/u,
|
||||
},
|
||||
{
|
||||
name: "the caller's bound",
|
||||
operation: "define_native_data_types",
|
||||
remoteCode: "declarations_length_limit",
|
||||
text: "x".repeat(300),
|
||||
bound: 256,
|
||||
limit: {
|
||||
parameter: "declarations_max_utf16",
|
||||
effective_value: 256,
|
||||
minimum: 16,
|
||||
maximum: 8192,
|
||||
default_value: 4096,
|
||||
required_value: 300,
|
||||
},
|
||||
recovery:
|
||||
/Pass a larger declarations_max_utf16 .*at least 300; range 16\.\.8192/u,
|
||||
},
|
||||
{
|
||||
name: "text above the maximum",
|
||||
operation: "define_native_data_types",
|
||||
remoteCode: "declarations_length_limit",
|
||||
text: "x".repeat(8193),
|
||||
bound: undefined,
|
||||
limit: {
|
||||
parameter: "declarations_max_utf16",
|
||||
effective_value: 4096,
|
||||
minimum: 16,
|
||||
maximum: 8192,
|
||||
default_value: 4096,
|
||||
required_value: 8193,
|
||||
},
|
||||
recovery:
|
||||
/requires 8193, above the declarations_max_utf16 maximum \(16\.\.8192\); narrow the request/u,
|
||||
},
|
||||
] as const)(
|
||||
"binds a length refusal under $name to its per-call control",
|
||||
async ({ operation, remoteCode, text, bound, limit, recovery }) => {
|
||||
const field =
|
||||
operation === "annotate_native_function" ? "signature" : "declarations";
|
||||
const message = `${field} has ${String(text.length)} UTF-16 code units`;
|
||||
const harness = await connectGhidraMcp(
|
||||
`ghidra-${remoteCode}`,
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === operation
|
||||
? err(bridgeRefusal(remoteCode, message, text.length))
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const { error } = parseMcpToolError(
|
||||
await harness.mcp.callTool({
|
||||
name: operation,
|
||||
arguments: {
|
||||
...(operation === "annotate_native_function"
|
||||
? { procedure: "0x401000" }
|
||||
: {}),
|
||||
[field]: text,
|
||||
...(bound === undefined ? {} : { [limit.parameter]: bound }),
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
category: "resource_constraint",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation,
|
||||
limit: {
|
||||
control_kind: "parameter",
|
||||
unit: "count",
|
||||
applies_at: "next_call",
|
||||
...limit,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(error.message).toContain(message);
|
||||
expect(error.message).toContain(
|
||||
`${limit.parameter} admits at most ${String(limit.effective_value)}`,
|
||||
);
|
||||
expect(error.message).toContain("Nothing in this call was applied");
|
||||
expect(error.remediation.action).toMatch(recovery);
|
||||
const next = await harness.mcp.callTool({
|
||||
name: "procedure_info",
|
||||
arguments: { procedure: "0x401000" },
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{
|
||||
name: "the default bound",
|
||||
operation: "annotate_native_function",
|
||||
bound: undefined,
|
||||
required: 9,
|
||||
effective: 8,
|
||||
recovery:
|
||||
/Pass a larger parenthesis_max_depth .*annotate_native_function.*\(at least 9; range 1\.\.12\), then retry/u,
|
||||
},
|
||||
{
|
||||
name: "the caller's bound",
|
||||
operation: "annotate_native_function",
|
||||
bound: 3,
|
||||
required: 5,
|
||||
effective: 3,
|
||||
recovery:
|
||||
/Pass a larger parenthesis_max_depth .*at least 5; range 1\.\.12/u,
|
||||
},
|
||||
{
|
||||
name: "nesting above the maximum",
|
||||
operation: "annotate_native_function",
|
||||
bound: undefined,
|
||||
required: 13,
|
||||
effective: 8,
|
||||
recovery:
|
||||
/requires 13, above the parenthesis_max_depth maximum \(1\.\.12\); narrow the request/u,
|
||||
},
|
||||
] as const)(
|
||||
"binds a nesting refusal under $name to its per-call control",
|
||||
async ({ operation, bound, required, effective, recovery }) => {
|
||||
const field =
|
||||
operation === "annotate_native_function" ? "signature" : "declarations";
|
||||
const message = `${field} nests parentheses ${String(required)} levels deep, first beyond ${String(effective)} at line 1, column 30`;
|
||||
const harness = await connectGhidraMcp(
|
||||
`ghidra-parenthesis-depth-${String(required)}`,
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === operation
|
||||
? err(bridgeRefusal("parenthesis_depth_limit", message, required))
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const { error } = parseMcpToolError(
|
||||
await harness.mcp.callTool({
|
||||
name: operation,
|
||||
arguments: {
|
||||
...(operation === "annotate_native_function"
|
||||
? { procedure: "0x401000", signature: SIGNATURE }
|
||||
: { declarations: DECLARATIONS }),
|
||||
...(bound === undefined ? {} : { parenthesis_max_depth: bound }),
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation,
|
||||
limit: {
|
||||
control_kind: "parameter",
|
||||
parameter: "parenthesis_max_depth",
|
||||
effective_value: effective,
|
||||
unit: "count",
|
||||
minimum: 1,
|
||||
maximum: 12,
|
||||
default_value: 8,
|
||||
applies_at: "next_call",
|
||||
required_value: required,
|
||||
},
|
||||
},
|
||||
});
|
||||
// An adjustable budget, not a fixed ceiling.
|
||||
expect(error.details).toMatchObject({
|
||||
refusal: {
|
||||
kind: "adjustable_budget",
|
||||
control: "parenthesis_max_depth",
|
||||
},
|
||||
});
|
||||
expect(error.message).toContain(message);
|
||||
expect(error.message).toContain(
|
||||
`parenthesis_max_depth admits at most ${String(effective)} levels`,
|
||||
);
|
||||
expect(error.remediation.action).toMatch(recovery);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("reports a type chained deeper than Ghidra's stack admits as a fixed ceiling", async () => {
|
||||
const message =
|
||||
"declarations defines rea_chain, chained 300 levels deep through pointers, arrays, typedefs, members or existing database types";
|
||||
const harness = await connectGhidraMcp(
|
||||
"ghidra-type-depth",
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === "define_native_data_types"
|
||||
? err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
message,
|
||||
{},
|
||||
{ remoteCode: "type_depth_limit" },
|
||||
),
|
||||
)
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const { error } = parseMcpToolError(
|
||||
await harness.mcp.callTool({
|
||||
name: "define_native_data_types",
|
||||
arguments: { declarations: DECLARATIONS },
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation: "define_native_data_types",
|
||||
refusal: {
|
||||
kind: "fixed_ceiling",
|
||||
allowance: "The Ghidra C type depth allowance",
|
||||
limit: 256,
|
||||
unit: "levels",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(error.details).not.toHaveProperty("limit");
|
||||
expect(error.message).toContain(`${message}, above the 256-level limit`);
|
||||
expect(error.remediation.action).toMatch(
|
||||
/only fewer nested pointer, array, typedef or member levels does/u,
|
||||
);
|
||||
expect(error.remediation.action).not.toMatch(/Split the chain/u);
|
||||
// The refusal leaves the session usable.
|
||||
const next = await harness.mcp.callTool({
|
||||
name: "procedure_info",
|
||||
arguments: { procedure: "0x401000" },
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("returns the qualifiers each edit could not record", async () => {
|
||||
const qualifier = { qualifier: "const", line: 1, column: 14 };
|
||||
// Every other pure qualifier the bridge reports.
|
||||
const PURE_QUALIFIERS = ["restrict", "__unaligned", "__w64"].map(
|
||||
(name, index) => ({ qualifier: name, line: 2, column: 1 + index }),
|
||||
);
|
||||
const harness = await connectGhidraMcp(
|
||||
"ghidra-dropped-qualifiers",
|
||||
(requested) =>
|
||||
Promise.resolve(
|
||||
ok(
|
||||
requested === "define_native_data_types"
|
||||
? {
|
||||
types: [SESSION_TYPE],
|
||||
dropped_qualifiers: [qualifier, ...PURE_QUALIFIERS],
|
||||
effects: DEFINITION_EFFECTS,
|
||||
}
|
||||
: {
|
||||
...(annotationReply(SIGNATURE, "user_defined") as Record<
|
||||
string,
|
||||
JsonValue
|
||||
>),
|
||||
dropped_qualifiers: [
|
||||
{ ...qualifier, parameter_index: 0 },
|
||||
{
|
||||
qualifier: "volatile",
|
||||
line: 1,
|
||||
column: 1,
|
||||
parameter_index: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const defined = await harness.mcp.callTool({
|
||||
name: "define_native_data_types",
|
||||
arguments: { declarations: DECLARATIONS },
|
||||
});
|
||||
expect(defined.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
dropped_qualifiers: [qualifier, ...PURE_QUALIFIERS],
|
||||
},
|
||||
});
|
||||
const annotated = await harness.mcp.callTool({
|
||||
name: "annotate_native_function",
|
||||
arguments: { procedure: "0x401000", signature: SIGNATURE },
|
||||
});
|
||||
expect(annotated.structuredContent).toMatchObject({
|
||||
normalized_result: {
|
||||
dropped_qualifiers: [
|
||||
{ ...qualifier, parameter_index: 0 },
|
||||
{ qualifier: "volatile", parameter_index: null },
|
||||
],
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["annotate_native_function", "define_native_data_types"] as const)(
|
||||
"attributes an ambiguous type name in %s to its text and lists the recovery",
|
||||
async (operation) => {
|
||||
const message =
|
||||
"The type name size_t names different types in the database: /DWARF/size_t, /stddef.h/size_t";
|
||||
const harness = await connectGhidraMcp(
|
||||
`ghidra-ambiguous-${operation}`,
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === operation
|
||||
? err(
|
||||
new GhidraSessionError(
|
||||
"remote",
|
||||
message,
|
||||
{},
|
||||
{ remoteCode: "ambiguous_data_type" },
|
||||
),
|
||||
)
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const { error } = parseMcpToolError(
|
||||
await harness.mcp.callTool({
|
||||
name: operation,
|
||||
arguments:
|
||||
operation === "annotate_native_function"
|
||||
? { procedure: "0x401000", signature: SIGNATURE }
|
||||
: { declarations: DECLARATIONS },
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: {
|
||||
issues: [
|
||||
{
|
||||
path: [
|
||||
operation === "annotate_native_function"
|
||||
? "signature"
|
||||
: "declarations",
|
||||
],
|
||||
message,
|
||||
},
|
||||
],
|
||||
related_operations: [
|
||||
"inspect_native_data_type",
|
||||
"define_native_data_types",
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(error.remediation.action).toMatch(/unique in the database/u);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("refuses non-equivalent types that share one Ghidra name and stores nothing", async () => {
|
||||
const remoteCode = "conflicting_type_definitions";
|
||||
const failure = bindGhidraSessionFailure((scope) => ({
|
||||
diagnostic_scope: scope,
|
||||
}))(
|
||||
"remote",
|
||||
"declarations define different types under one name: item; nothing was changed",
|
||||
new GhidraRemoteError(
|
||||
remoteCode,
|
||||
"declarations define different types under one name: item; nothing was changed",
|
||||
),
|
||||
{ remoteCode },
|
||||
);
|
||||
const harness = await connectGhidraMcp(
|
||||
"ghidra-conflicting-type-definitions",
|
||||
(requested, input) =>
|
||||
Promise.resolve(
|
||||
requested === "define_native_data_types"
|
||||
? err(failure)
|
||||
: ok(ghidraFixtureResult(requested, input)),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const { error } = parseMcpToolError(
|
||||
await harness.mcp.callTool({
|
||||
name: "define_native_data_types",
|
||||
arguments: {
|
||||
declarations: "struct item { int x; }; typedef int item;",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
retryable: false,
|
||||
details: {
|
||||
operation: "define_native_data_types",
|
||||
issues: [{ path: ["declarations"], reason: "invalid_value" }],
|
||||
diagnostics: {
|
||||
diagnostic_scope: "request",
|
||||
remote_code: remoteCode,
|
||||
},
|
||||
related_operations: ["define_native_data_types"],
|
||||
},
|
||||
});
|
||||
expect(error.recovery).toBeUndefined();
|
||||
const next = await harness.mcp.callTool({
|
||||
name: "procedure_info",
|
||||
arguments: { procedure: "0x401000" },
|
||||
});
|
||||
expect(next.isError).not.toBe(true);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
@@ -197,6 +197,9 @@ describe("official operation arguments", () => {
|
||||
name: dossier.procedure.name,
|
||||
comment: "existing finding",
|
||||
inline_comment: "existing inline finding",
|
||||
signature: "undefined fixture_main()",
|
||||
signature_source: "default",
|
||||
calling_convention: "unknown",
|
||||
};
|
||||
const parameters: Readonly<Record<string, JsonValue>>[] = [];
|
||||
const client = await connect({
|
||||
|
||||
@@ -351,3 +351,70 @@ it.skipIf(process.platform === "win32")(
|
||||
await once(child, "exit");
|
||||
},
|
||||
);
|
||||
|
||||
const typeEdits = [
|
||||
[
|
||||
"annotate_native_function",
|
||||
{ procedure: "0x1000", signature: "int f(struct session *s)" },
|
||||
],
|
||||
["define_native_data_types", { declarations: "struct session { int id; };" }],
|
||||
] as const;
|
||||
|
||||
it.skipIf(process.platform === "win32").each(typeEdits)(
|
||||
"reports a %s edit as not saved when the closing checkpoint fails, keeps it editable and saves it on retry",
|
||||
async (operation, parameters) => {
|
||||
const f = await fixture("checkpoint_fail_close");
|
||||
expect((await f.client.start()).ok).toBe(true);
|
||||
const path = join(f.selection.directory, "current.json"),
|
||||
before = await readFile(path, "utf8");
|
||||
expect((await f.client.callTool(operation, parameters)).ok).toBe(true);
|
||||
// The save fails: close reports it and the previous checkpoint is intact.
|
||||
expect((await f.client.close()).ok).toBe(false);
|
||||
expect(await readFile(path, "utf8")).toEqual(before);
|
||||
expect(
|
||||
(await readdir(f.launcher.runtimeRoots[0]!)).filter((name) =>
|
||||
name.startsWith("checkpoint-"),
|
||||
),
|
||||
).toEqual([]);
|
||||
// The live Program still holds the edit and accepts further requests.
|
||||
expect(f.client.isReady()).toBe(true);
|
||||
expect((await f.client.callTool("list_documents", {})).ok).toBe(true);
|
||||
expect(f.launcher.processes).toHaveLength(1);
|
||||
expect((await f.client.close()).ok).toBe(true);
|
||||
expect(await readFile(path, "utf8")).not.toEqual(before);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each(typeEdits)(
|
||||
"cancelling an active %s edit stops the Program without saving and the next start restores the last checkpoint",
|
||||
async (operation, parameters) => {
|
||||
const f = await fixture("checkpoint_hang_edit");
|
||||
expect((await f.client.start()).ok).toBe(true);
|
||||
const path = join(f.selection.directory, "current.json"),
|
||||
before = await readFile(path, "utf8");
|
||||
const controller = new AbortController();
|
||||
const active = f.client.callTool(operation, parameters, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
// The edit has crossed the socket and is in progress.
|
||||
await waitFor(() => expect(f.launcher.requests).toContain(operation));
|
||||
controller.abort(new Error("caller stopped waiting"));
|
||||
expect(await active).toMatchObject({
|
||||
ok: false,
|
||||
error: { kind: "cancelled" },
|
||||
});
|
||||
const child = f.launcher.processes[0]!;
|
||||
if (child.exitCode === null && child.signalCode === null)
|
||||
await once(child, "exit");
|
||||
// All or nothing: the interrupted Program was discarded, not checkpointed.
|
||||
expect(f.client.isReady()).toBe(false);
|
||||
expect(await readFile(path, "utf8")).toEqual(before);
|
||||
expect(f.launcher.requests).not.toContain("shutdown");
|
||||
// The next start is a new Program restored from the unchanged checkpoint.
|
||||
expect((await f.client.start()).ok).toBe(true);
|
||||
expect(f.launcher.processes).toHaveLength(2);
|
||||
expect(f.client.checkpointRestore()).not.toBeNull();
|
||||
expect((await f.client.close()).ok).toBe(true);
|
||||
expect(await readFile(path, "utf8")).toEqual(before);
|
||||
},
|
||||
);
|
||||
@@ -18,6 +18,7 @@ export const ghidraFixturePath = fileURLToPath(
|
||||
type FixtureMode =
|
||||
| "checkpoint"
|
||||
| "checkpoint_fail_close"
|
||||
| "checkpoint_hang_edit"
|
||||
| "checkpoint_hold_startup"
|
||||
| "checkpoint_hold_close"
|
||||
| "checkpoint_hold_close_hang_tool"
|
||||
|
||||
Vendored
+17
@@ -199,6 +199,23 @@ const handleRequest = (socket, server, request, state) => {
|
||||
);
|
||||
return;
|
||||
}
|
||||
// A prototype or type edit changes the Program like a rename does. The
|
||||
// hang mode never answers one and never applies it.
|
||||
if (
|
||||
request.method === "annotate_native_function" ||
|
||||
request.method === "define_native_data_types"
|
||||
) {
|
||||
if (state.mode === "checkpoint_hang_edit") return;
|
||||
state.checkpointDirty = true;
|
||||
socket.write(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
ok: true,
|
||||
result: { edited: request.method },
|
||||
}) + "\n",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (request.method === "checkpoint_program") {
|
||||
void handleCheckpoint(socket, request, state);
|
||||
return;
|
||||
|
||||
Vendored
+2
@@ -29,6 +29,7 @@ const hex = (value) => `0x${value.toString(16)}`;
|
||||
/** Methods the bridge drops from a read-only (loopback TCP) handshake. */
|
||||
const MUTATING_METHODS = [
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"set_address_name",
|
||||
"set_addresses_names",
|
||||
];
|
||||
@@ -55,6 +56,7 @@ export const FAKE_GHIDRA_CAPABILITIES = Object.freeze([
|
||||
"set_address_name",
|
||||
"set_addresses_names",
|
||||
"annotate_native_function",
|
||||
"define_native_data_types",
|
||||
"inspect_native_data_type",
|
||||
"inspect_native_instruction",
|
||||
"resolve_native_call_targets",
|
||||
|
||||
Reference in new issue
Block a user