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

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

annotate_native_function accepts an optional C prototype, applied with
USER_DEFINED source in the same transaction as the name and comments,
verified by readback and rolled back with them on refusal.
define_native_data_types stores caller-authored struct, union, enum and
typedef definitions atomically under /rea_caller_defined and refuses
existing names. inspect_native_data_type reports those types with source
caller-defined, and annotation readback reports the applied prototype
and its source.

Refs #14831

* feat(ghidra): bound caller C text with launch controls and refuse unapplied constructs

The lengths of a signature and of type declarations and the nesting depth
of parentheses are launch-only REA_ controls with measured defaults, floors
and maxima, written into the bridge's session descriptor. A refusal names
the control, its effective value, source and range.

The bridge tokenizes caller C before Ghidra's parser sees it and refuses
what that parser accepts without applying: attributes, storage-class
specifiers, variable declarations, directives other than #pragma pack,
literals, function bodies, default arguments, unnamed enums and repeated
member names. A type name that names different types is refused.

When a function has no calling convention and the prototype names none,
the compiler specification's default convention, which Ghidra already uses
to assign the locked storage, is recorded, and annotation readback reports
the convention.

Refs #14831

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

The bridge appended the semicolon its parser needs before checking the
length, so a prototype of exactly the admitted length was refused. The
readback prototype is documented as reusable only when its function and
type names are C identifiers.

Refs #14831

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

Refs #14831

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

Ghidra's C parser cannot be cancelled, so REA bounds the text it parses.
The three launch-only environment controls left an agent that hit them
with a restart as its only recovery. The two length bounds are now
per-call parameters, signature_max_utf16 on annotate_native_function and
declarations_max_utf16 on define_native_data_types, with the same defaults
and measured maxima. A refusal reports details.limit with
control_kind "parameter" and required_value, the text's length, so the
generated recovery names the value to pass or asks for shorter text. The
text fields no longer carry a schema maximum, so every over-length
refusal is typed. Parenthesis nesting is a fixed ceiling of 8 levels,
registered as a representation bound, because each level doubles parse
time. The session descriptor no longer carries C parser limits, and the
config module, environment entries and restart-only registry rows are
removed.

const and volatile are still applied without effect, because Ghidra's
types have no representation for them. Both edits now return
dropped_qualifiers with each qualifier's line and column, and for a
signature its parameter index, null for the return type, instead of
dropping them silently.

* fix(ghidra): read caller C through one tokenizer and bound nesting per call

The C admission scan tracked lines only at LF and read directives as raw
lines matched by a regular expression, so a CR-only line break shifted
dropped-qualifier positions and a trailing comment on #pragma pack was
refused. One tokenizer now owns caller C positions, comments and literals:
CR, LF and CRLF each end a line as in Ghidra's parser, and directives are
admitted from its tokens, so comments read as whitespace there too. A block
comment that would carry a directive onto another line is refused.

Parenthesis nesting was a fixed ceiling justified by parse time, a resource
limit. It is now the per-call parenthesis_max_depth (default 8, range
1..12) on both type-edit tools. The bridge measures the deepest nesting
over the whole text and sends it, with a text's length, as the wire
failure's required_value, so details.limit reports the bridge's own
measurement instead of the adapter re-reading the request.

The tokenizer also decides whether a prototype is terminated, so the parser
sees the caller's text unchanged: no leading whitespace is stripped, and a
trailing line comment no longer swallows the appended terminator.

* fix(ghidra): parse caller C inside the edit's rollback and refuse parser diagnostics

Ghidra's C parser writes the type database even with storeDataType false:
a definition whose name matches an existing empty composite fills that
type in place, in the parser's own nested transaction. Both type edits
parsed before opening their transaction, so a refused definition, such as
one conflicting with a DWARF placeholder, left that placeholder filled.
Parsing, validation and storage now share the edit's one transaction, and
parseCallerC refuses to run outside one.

The parser also records diagnostics it cannot apply, such as a repeated
enumerator it drops, and still reports success. Both edits now refuse any
diagnostic with Ghidra's message, before anything is stored.

The real-Ghidra verifier gains a phase with an ELF object whose DWARF
declares an opaque struct, proving a refused definition leaves that empty
composite unchanged, and refuses a repeated enumerator.

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

Review kept finding one more construct Ghidra's C parser consumes without
applying, because admission listed spellings piecemeal. The tokenizer now
owns one table, audited against every token and production of Ghidra
12.2's C.jj and checked on Ghidra 12.2, in that grammar's own spellings:

- Refused, because meaning is lost: __ptr32 and __ptr64 (stored as a
  native-width pointer), __near and __far, every attribute, declspec,
  __readableTo, alignas, packed and asm spelling, [[...]] attributes,
  storage and inline specifiers including __forceinline, __pragma and
  _Pragma, _Static_assert, Objective-C @ blocks (Ghidra skips their whole
  text), and backslashes.
- Reported in dropped_qualifiers as pure qualifiers: every const and
  volatile spelling, restrict, __unaligned and __w64.

#pragma pack is admitted only in the operand forms Ghidra applies as
written with a decimal value; (0x1), (010), (show) and (pop, n) were
ignored or read differently, and "# pragma" is a line marker Ghidra
skips. An enum tag that neither the text nor the database defines made
Ghidra invent an empty enum without a diagnostic; declarations now refuse
it as they do an invented struct or union. Identifiers admit $, as C.jj's
do, and the tokenizer reads numbers and [[ as single tokens.

* fix(ghidra): bound caller type depth, admit only constant expressions Ghidra evaluates, refuse unmatched pack pops

Recursion: the tokenizer's [[ lookahead re-entered next() for each "[",
and the dependency walk recursed per pointer, array and member level.
Both are iterative now. Ghidra 12.2's own data-type code recurses too:
1024 pointer or array levels resolve, 2048 exhaust the stack inside
addDataType while its database lock is held, leaving the Program unable
to save. Every parsed type's chain through pointers, arrays, typedefs and
members, including existing database types, is now measured iteratively
and refused beyond a fixed 256-level ceiling before Ghidra walks it. An
unexpected StackOverflowError ends the session with a reason instead of
being caught by the parser call, since Ghidra's lock may then be held.

Constant expressions: Ghidra leaves names, casts, sizeof, floating and
binary literals unevaluated and substitutes a default, so
"MASK = FIRST << 4" was stored as 2, and it truncates values outside int.
Enum values, array sizes and bit-field widths are admitted only as integer
literals with arithmetic, shift, comparison, bitwise and logical
operators, checked iteratively with C's rules to stay in int, including
implicit enumerator values; anything else is refused at its position.

Pragma pack: Ghidra ignores a bare (push), a pop with nothing pushed keeps
the current packing, and a plain pop pops past labelled entries. The
tokenizer tracks admitted pushes and admits a pop only when Ghidra's
result matches C's.

* fix(ghidra): admit constant expressions only as one literal, skip absent pointer targets, state the type-depth recovery truthfully

Constant expressions: emulating C against Ghidra's own evaluator is an
open-ended class of mismatches (comparisons, unsigned arithmetic such as
~0U >> 1 giving -1, names, casts, truncation). The evaluator is removed.
Enum values, array sizes and bit-field widths are admitted only as one
decimal or hex integer literal within int, optionally negated, without
suffixes; anything else is refused at the first token that leaves that
form, and the refusal says to write the computed value. Implicit
enumerator values are still checked against int.

Dependency walk: Ghidra's generic pointer has a null pointed-to type, and
pushing it onto the ArrayDeque threw. Both the dependency and depth walks
now take children from one cTypeChildren and skip an absent child.

Type depth: the depth is measured over the whole chain before comparing it
with the limit, so the refusal reports the depth it used, and it names
the type from the parser's table rather than walking the type for a name.
The recovery no longer suggests splitting into named types, which cannot
help because depth counts through typedefs and existing types; it says
only fewer nested levels do.

* refactor(ghidra): refuse parentheses in definitions and keep parenthesis_max_depth on signatures only

Under the literal-only rule for constant expressions, every parenthesis in
a define_native_data_types text already ended in a refusal (function
declarators, attributes, casts, sizeof, or a Ghidra diagnostic for a
grouped declarator), so parenthesis_max_depth changed only which refusal
a caller saw. A definition now refuses its first parenthesis at its
position, and the parameter is removed from that tool's schema; it stays
on annotate_native_function, whose prototype has a parameter list.

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

Ghidra keeps struct tags, enum tags and typedefs in separate maps.
Combining those maps dropped a typedef such as typedef int item when
struct item was also defined, and the call still succeeded. Overlapping
names are stored only when the definitions are equivalent, which keeps
typedef struct s { ... } s as one struct. Any other overlap is refused
with conflicting_type_definitions before the transaction stores anything.

Co-authored-by: morluto <morluto@users.noreply.github.com>

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

Ghidra's parser replaces an empty composite during parsing and returns
that same object. A later same-path check would store the fill as
unchanged. Record those empty composites before parsing and refuse if
parsing fills one, so the open transaction restores them. A different
layout of a non-empty caller type still conflicts and leaves the stored
type in place.

Co-authored-by: morluto <morluto@users.noreply.github.com>

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

Ghidra's // skip token requires a line break, so a comment at the end of
declarations or of an already-terminated signature was rejected. A newline
is appended whenever the text ends in a line comment, before any semicolon
added for an unterminated prototype.

Integer.parseInt drops a pack operand outside a Java int and leaves the
previous packing, so #pragma pack(2147483648) stored a natural layout.
Decimal pack operands are admitted only when that parse succeeds.

Co-authored-by: morluto <morluto@users.noreply.github.com>

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

Defining a struct over the DWARF placeholder fills that empty composite
during parsing, so the refusal is data_type_conflict before the old
name-conflict message. The verifier checks that code and that the
placeholder still has no fields.

Co-authored-by: morluto <morluto@users.noreply.github.com>

---------

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

No files matched your search

@@ -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"
+17
View File
@@ -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;
+2
View File
@@ -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",