diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index 0507267792..63be839c67 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -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, diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md index 0507267792..63be839c67 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -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, diff --git a/bridge/ghidra/ReaGhidraBridge.java b/bridge/ghidra/ReaGhidraBridge.java index d64b4017bf..b48ae64149 100644 --- a/bridge/ghidra/ReaGhidraBridge.java +++ b/bridge/ghidra/ReaGhidraBridge.java @@ -70,7 +70,9 @@ import generic.concurrent.ConcurrentQ; import generic.concurrent.ConcurrentQBuilder; import generic.concurrent.GThreadPool; import generic.concurrent.QResult; - +import ghidra.app.cmd.function.ApplyFunctionSignatureCmd; +import ghidra.app.cmd.function.FunctionRenameOption; +import ghidra.app.util.cparser.C.CParser; import ghidra.app.util.headless.HeadlessScript; import ghidra.app.decompiler.DecompInterface; import ghidra.app.decompiler.DecompileOptions; @@ -97,7 +99,12 @@ import ghidra.program.model.block.CodeBlockIterator; import ghidra.program.model.block.CodeBlockReference; import ghidra.program.model.block.CodeBlockReferenceIterator; import ghidra.program.model.data.StringDataInstance; +import ghidra.program.model.data.CategoryPath; import ghidra.program.model.data.DataType; +import ghidra.program.model.data.DataTypeConflictHandler; +import ghidra.program.model.data.DataTypeManager; +import ghidra.program.model.data.FunctionDefinitionDataType; +import ghidra.program.model.data.ParameterDefinition; import ghidra.program.model.data.MutabilitySettingsDefinition; import ghidra.program.model.data.Undefined; import ghidra.program.model.lang.OperandType; @@ -111,6 +118,7 @@ import ghidra.program.model.listing.DataIterator; import ghidra.program.model.listing.Function; import ghidra.program.model.listing.FunctionIterator; import ghidra.program.model.listing.FunctionManager; +import ghidra.program.model.listing.FunctionSignature; import ghidra.program.model.listing.Instruction; import ghidra.program.model.listing.InstructionIterator; import ghidra.program.model.listing.Listing; @@ -188,6 +196,7 @@ public final class ReaGhidraBridge extends HeadlessScript { private static final String[] CAPABILITIES = { "read_binary_inventory_summary", "annotate_native_function", + "define_native_data_types", "set_address_name", "set_addresses_names", "inspect_native_load_image", @@ -634,7 +643,17 @@ public final class ReaGhidraBridge extends HeadlessScript { dispatchAndWrite(writer, request, descriptor); } catch (RequestFailure failure) { - writeFailure(writer, request.id, failure.code, failure.getMessage(), failure.candidates); + writeFailure(writer, request.id, failure); + } + catch (StackOverflowError exhausted) { + // Ghidra's data-type code can overflow while holding its database + // lock, which then stays held: the Program can no longer be saved + // or trusted. Admission bounds caller types (MAX_C_TYPE_DEPTH) so + // this is not reachable from caller text; if it happens anyway, + // say why and end the session rather than keep serving it. + writeFailure(writer, request.id, "bridge_exception", + "StackOverflowError: Ghidra exhausted its stack and may hold its database lock; this Ghidra session cannot continue"); + throw exhausted; } catch (CancelledException exception) { writeFailure(writer, request.id, "request_cancelled", "Ghidra request was cancelled"); @@ -732,6 +751,11 @@ public final class ReaGhidraBridge extends HeadlessScript { throw new RequestFailure("method_unavailable", "Windows P0 does not admit database mutation"); yield annotateNativeFunction(request.params); } + case "define_native_data_types" -> { + if (!descriptor.transport.equals("unix-socket")) + throw new RequestFailure("method_unavailable", "Windows P0 does not admit database mutation"); + yield defineNativeDataTypes(request.params); + } default -> throw new RequestFailure( "method_unavailable", "Bridge method is unavailable" @@ -740,7 +764,8 @@ public final class ReaGhidraBridge extends HeadlessScript { } private static boolean isMutatingOperation(String method) { - return method.equals("annotate_native_function") || method.equals("set_address_name") || method.equals("set_addresses_names"); + return method.equals("annotate_native_function") || method.equals("define_native_data_types") || + method.equals("set_address_name") || method.equals("set_addresses_names"); } /** Internal lifecycle request: the destination is inside this owned runtime. */ @@ -1485,10 +1510,9 @@ public final class ReaGhidraBridge extends HeadlessScript { if (!selection.has("mapped_address")) throw failure; // Preserve completed resolution facts without changing the backend's // failure code or suggesting that the successful mapping was invalid. - throw new RequestFailure(failure.code, "Selector " + selector + + throw failure.prefixed("Selector " + selector + " mapped to analysis address " + selection.get("mapped_address").getAsString() + - " and procedure " + canonicalAddress(function.getEntryPoint()) + - "; " + failure.getMessage(), failure.candidates); + " and procedure " + canonicalAddress(function.getEntryPoint()) + "; "); } } @@ -1781,8 +1805,8 @@ public final class ReaGhidraBridge extends HeadlessScript { if (type.getSourceArchive() != null) result.addProperty("source_archive", type.getSourceArchive().getName()); if (type.getLength() >= 0) result.addProperty("size_bytes", type.getLength()); if (type.getAlignment() > 0) result.addProperty("alignment_bytes", type.getAlignment()); - String kind = type instanceof ghidra.program.model.data.Structure ? "struct" : type instanceof ghidra.program.model.data.Union ? "union" : type instanceof ghidra.program.model.data.Enum ? "enum" : type instanceof ghidra.program.model.data.Pointer ? "pointer" : type instanceof ghidra.program.model.data.Array ? "array" : type instanceof ghidra.program.model.data.TypeDef ? "typedef" : type instanceof ghidra.program.model.data.BuiltInDataType ? "scalar" : "unsupported"; - result.addProperty("kind", kind); + result.addProperty("kind", dataTypeKind(type)); + if (isCallerDefinedType(type)) result.addProperty("source", "caller-defined"); if (type instanceof ghidra.program.model.data.Composite composite) { result.addProperty("packing_enabled", composite.isPackingEnabled()); ghidra.program.model.data.DataTypeComponent[] components = composite.getComponents(); @@ -1845,6 +1869,10 @@ public final class ReaGhidraBridge extends HeadlessScript { return result; } + private static String dataTypeKind(DataType type) { + return type instanceof ghidra.program.model.data.Structure ? "struct" : type instanceof ghidra.program.model.data.Union ? "union" : type instanceof ghidra.program.model.data.Enum ? "enum" : type instanceof ghidra.program.model.data.Pointer ? "pointer" : type instanceof ghidra.program.model.data.Array ? "array" : type instanceof ghidra.program.model.data.TypeDef ? "typedef" : type instanceof ghidra.program.model.data.BuiltInDataType ? "scalar" : "unsupported"; + } + private String typeLookupResult(DataType type) { DataType resolved = currentProgram.getDataTypeManager().getDataType(type.getPathName()); return resolved == null ? "not-found" : resolved.isEquivalent(type) ? "equivalent" : "different"; @@ -2064,13 +2092,20 @@ public final class ReaGhidraBridge extends HeadlessScript { value.addProperty("name", procedureName(function)); value.addProperty("comment", currentProgram.getListing().getComment(CommentType.PRE, entry)); value.addProperty("inline_comment", currentProgram.getListing().getComment(CommentType.EOL, entry)); + // The formal prototype omits storage-derived parameters. It reparses as a + // signature edit when its function and type names are C identifiers. + value.addProperty("signature", function.getSignature(true).getPrototypeString(false)); + value.addProperty("signature_source", normalizedSource(function.getSignatureSource())); + value.addProperty("calling_convention", function.getCallingConventionName()); return value; } private JsonObject annotateNativeFunction(JsonObject params) throws Exception { - if (!Set.of("procedure", "name", "comment", "inline_comment").containsAll(params.keySet())) + if (!Set.of("procedure", "name", "comment", "inline_comment", "signature", "signature_max_utf16", + "parenthesis_max_depth") + .containsAll(params.keySet())) throw new RequestFailure("invalid_request", "Unknown function annotation field"); - if (!params.has("name") && !params.has("comment") && !params.has("inline_comment")) + if (!params.has("name") && !params.has("comment") && !params.has("inline_comment") && !params.has("signature")) throw new RequestFailure("invalid_request", "Supply at least one annotation change"); Function function = resolveProcedure(requireString(params, "procedure")); Address entry = function.getEntryPoint(); @@ -2079,9 +2114,17 @@ public final class ReaGhidraBridge extends HeadlessScript { for (String field : List.of("name", "comment", "inline_comment")) { if (params.has(field)) validateAnnotationText(requireText(params, field), field); } + int signatureBound = callerCTextBound( + params, "signature_max_utf16", DEFAULT_FUNCTION_SIGNATURE_UTF16, MAX_FUNCTION_SIGNATURE_UTF16); + int parenthesisBound = callerParenthesisBound(params); int transaction = currentProgram.startTransaction("REA function annotations"); boolean commit = false; try { + // Ghidra's parser writes the database (see parseCallerC), so it runs inside this rollback. + SignatureEdit signature = params.has("signature") + ? parseFunctionSignature(function, requireText(params, "signature"), signatureBound, parenthesisBound) + : null; + FunctionDefinitionDataType prototype = signature == null ? null : signature.prototype(); String leafName = params.has("name") ? symbolLeafName(function.getSymbol(), requireString(params, "name")) : null; // Validate edits through Ghidra's own setters, including name rules. @@ -2095,6 +2138,7 @@ public final class ReaGhidraBridge extends HeadlessScript { } if (params.has("name")) function.setName(leafName, SourceType.USER_DEFINED); + if (prototype != null) applyFunctionSignature(function, prototype); monitor.checkCancelled(); invalidateSymbolAndDecompilerCaches(); JsonObject readback = annotationReadback(function); @@ -2113,6 +2157,8 @@ public final class ReaGhidraBridge extends HeadlessScript { JsonObject result = new JsonObject(); result.add("annotations", readback); result.add("dossier", analyzeFunction(query)); + if (signature != null && !signature.droppedQualifiers().isEmpty()) + result.add("dropped_qualifiers", signature.droppedQualifiers()); JsonObject effects = new JsonObject(); effects.addProperty("scope", "session-analysis-database"); effects.addProperty("source_bytes_modified", false); @@ -2132,6 +2178,989 @@ public final class ReaGhidraBridge extends HeadlessScript { } } + // Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. + // Measured on Ghidra 12.2 (arm64 macOS): the slowest shape per character is one + // chain of pointer declarators, cubic in its length: 0.3 s at 2048 UTF-16 units, + // 0.8 s at 4096, 6.8 s at 8192 and 100 s at 16384. The per-call length controls + // (signature_max_utf16, declarations_max_utf16) stop at those maxima, keeping + // the slowest admitted text under about 7 s; the TypeScript contract owns the + // same defaults and ranges. Each level of nested parentheses in an expression + // doubles parse time and the cost repeats per occurrence (8192 units filled at + // depth 8 take 0.2 s, at depth 12 2.2 s), so parenthesis_max_depth stops at 12. + private static final int MIN_C_TEXT_UTF16 = 16; + private static final int DEFAULT_FUNCTION_SIGNATURE_UTF16 = 2048; + private static final int MAX_FUNCTION_SIGNATURE_UTF16 = 4096; + private static final int DEFAULT_TYPE_DECLARATIONS_UTF16 = 4096; + private static final int MAX_TYPE_DECLARATIONS_UTF16 = 8192; + private static final int MIN_C_PARENTHESIS_DEPTH = 1; + private static final int DEFAULT_C_PARENTHESIS_DEPTH = 8; + private static final int MAX_C_PARENTHESIS_DEPTH = 12; + /** Accepted caller C and the qualifiers Ghidra's types cannot record. */ + private record ParsedCallerC(CParser parser, JsonArray droppedQualifiers) {} + // Data types carry no SourceType; this category is the persisted mark of caller authorship. + private static final CategoryPath CALLER_DEFINED_TYPES = new CategoryPath("/rea_caller_defined"); + /** A token Ghidra's C parser consumes without applying, and what REA does with it. */ + private record UnappliedCToken(Pattern spelling, String construct, String droppedQualifier) { + boolean refused() { return droppedQualifier == null; } + } + + private static UnappliedCToken refusedC(String spelling, String construct) { + return new UnappliedCToken(Pattern.compile(spelling), construct, null); + } + + private static UnappliedCToken droppedC(String spelling, String qualifier) { + return new UnappliedCToken(Pattern.compile(spelling), null, qualifier); + } + + /** + * Every token Ghidra 12.2's C.jj grammar accepts and then ignores, in that + * grammar's own spellings (its token regular expressions). REA refuses a + * token whose meaning would be lost, such as a pointer width, an attribute + * or a storage class, and reports a pure qualifier that changes neither + * layout nor storage as dropped. Every other C.jj keyword is applied: base + * types (including __int8..__int64, _Bool and _*signed), struct, union, + * enum and typedef, calling conventions, _Noreturn, _Alignof and sizeof. + * Types the parser invents for an undefined name are a parse result, not a + * token; requireNoInventedTypes refuses those. + */ + private static final List UNAPPLIED_C_TOKENS = List.of( + // TypeQualifier: consumed without a Ghidra representation. + droppedC("_*const", "const"), + droppedC("_*volatile_*", "volatile"), + droppedC("_+restrict", "restrict"), + droppedC("__unaligned", "__unaligned"), + droppedC("__w64", "__w64"), + refusedC("__ptr32|__ptr64", "the pointer-width qualifier %s (Ghidra stores a native-width pointer)"), + refusedC("__near|__far", "the pointer qualifier %s (Ghidra ignores it)"), + // AttributeSpec, DeclSpec and AlignmentSpecifier: parsed and discarded. + refusedC("__attribute_*|__declspec|__readableTo|_Alignas|alignas|__packed|__packed__|packed|_*asm_*|_+extension_*", + "the attribute or extension %s"), + refusedC("\\[\\[", "a [[...]] attribute"), + // StorageClassSpecifier and function specifiers: no storage or linkage in a type. + refusedC("static|extern|register|auto|_Thread_local|thread_local|_*(?:inline|forceinline)_*", "the specifier %s"), + // Pragma operators, assertions and lexer states whose text is skipped. + // Ghidra applies a pack through the operator but skips any other pragma; REA admits one spelling. + refusedC("__pragma|_Pragma", "the pragma operator %s (write #pragma pack instead)"), + refusedC("_Static_assert|static_assert", "the static assertion %s (Ghidra does not store it)"), + refusedC("@", "an Objective-C @ directive (Ghidra skips its text)"), + refusedC("\\\\", "a backslash (Ghidra's parser skips it)")); + + private static UnappliedCToken unappliedC(String token) { + for (UnappliedCToken rule : UNAPPLIED_C_TOKENS) + if (rule.spelling().matcher(token).matches()) return rule; + return null; + } + + private static boolean isCallerDefinedType(DataType type) { + CategoryPath category = type.getCategoryPath(); + return category != null && category.isAncestorOrSelf(CALLER_DEFINED_TYPES); + } + + private static RequestFailure refusedConstruct(String code, String field, String construct, int line, int column) { + return new RequestFailure(code, field + " contains " + construct + " at line " + line + ", column " + column + + "; Ghidra's C parser would not apply it as written, so nothing was changed"); + } + + /** One token of caller C text and where it starts in the caller's own lines. */ + private record CToken(String text, int line, int column) { + boolean is(String expected) { return text.equals(expected); } + boolean isIdentifier() { return isCIdentifierStart(text.charAt(0)); } + } + + // C.jj's LETTER: identifiers may hold $, as in its IDENTIFIER token. + private static boolean isCIdentifierStart(char character) { + return Character.isLetter(character) || character == '_' || character == '$'; + } + + /** + * The one reader of caller C text. Tokens are identifiers, numbers or + * single characters; comments, and the byte-order mark C.jj skips, read as + * whitespace. CR, LF and CRLF each + * end one line, as in Ghidra's own C parser, so positions name the + * caller's text. A string or character literal is refused here, so no + * later check can mistake its contents for code. + */ + private static final class CTokenizer { + private final String text; + private final String field; + private final String code; + private int index; + private int line = 1; + private int lineStart; + /** The text ends inside a line comment, which would swallow anything appended on its line. */ + private boolean endsInLineComment; + + CTokenizer(String text, String field, String code) { + this.text = text; + this.field = field; + this.code = code; + } + + private static boolean isLineBreak(char character) { + return character == '\n' || character == '\r'; + } + + /** Step over one UTF-16 unit, or one CRLF pair, counting line breaks. */ + private void advance() { + char character = text.charAt(index++); + if (character == '\r' && index < text.length() && text.charAt(index) == '\n') index++; + if (isLineBreak(character)) { + line++; + lineStart = index; + } + } + + /** + * Skip whitespace and comments up to the next token. Returns false at + * the end of the text or, within a directive (lineEnds), at a line + * break; a block comment that crosses one there is refused, since it + * would carry the directive onto another line. + */ + private boolean skipToToken(boolean lineEnds) { + while (index < text.length()) { + char character = text.charAt(index); + int startLine = line, column = index - lineStart + 1; + if (lineEnds && isLineBreak(character)) return false; + if (Character.isWhitespace(character) || character == '\ufeff') { + advance(); + continue; + } + if (text.startsWith("//", index)) { + while (index < text.length() && !isLineBreak(text.charAt(index))) index++; + endsInLineComment = index == text.length(); + continue; + } + if (text.startsWith("/*", index)) { + int close = text.indexOf("*/", index + 2); + int stop = close < 0 ? text.length() : close + 2; + while (index < stop) advance(); + if (lineEnds && line != startLine) + throw refusedConstruct(code, field, + "a block comment that continues a directive onto another line", startLine, column); + continue; + } + return true; + } + return false; + } + + /** + * The next token, or null at the end of the text or a directive's line. + * Iterative throughout: caller text cannot deepen the stack. + */ + CToken next(boolean lineEnds) { + if (!skipToToken(lineEnds)) return null; + char character = text.charAt(index); + int tokenLine = line, column = index - lineStart + 1; + if (character == '"' || character == '\'') + throw refusedConstruct(code, field, "a string or character literal", tokenLine, column); + int stop = index + 1; + if (isCIdentifierStart(character) || Character.isDigit(character)) + while (stop < text.length() && + (isCIdentifierStart(text.charAt(stop)) || Character.isDigit(text.charAt(stop)))) stop++; + String token = text.substring(index, stop); + index = stop; + // C.jj reads "[" "[" as an attribute, with anything skippable between. + if (token.equals("[")) { + int savedIndex = index, savedLine = line, savedLineStart = lineStart; + boolean savedEnds = endsInLineComment; + if (skipToToken(lineEnds) && text.charAt(index) == '[') { + index++; + return new CToken("[[", tokenLine, column); + } + index = savedIndex; + line = savedLine; + lineStart = savedLineStart; + endsInLineComment = savedEnds; + } + return new CToken(token, tokenLine, column); + } + } + + /** What the tokenizer observed in admitted caller C. */ + private record AdmittedCallerC(JsonArray droppedQualifiers, boolean terminated, boolean endsInLineComment) {} + + // Ghidra reads a pack value with Integer.parseInt and, on overflow, keeps the + // packing already in effect. A decimal literal is admitted only when that parse accepts it. + private static final Pattern PACK_VALUE = Pattern.compile("0|[1-9][0-9]*"); + + private static boolean ghidraPackDecimal(String text) { + if (!PACK_VALUE.matcher(text).matches()) return false; + try { + Integer.parseInt(text); + return true; + } catch (NumberFormatException overflow) { + return false; + } + } + + /** + * Whether Ghidra 12.2's PragmaSpecifier applies these #pragma pack operands + * as C does, tracking the labels pushed so far. It ignores a bare (push), + * so its pop would restore nothing; a pop with nothing pushed keeps the + * current packing; and a plain pop keeps popping past labelled entries + * until it finds an unlabelled one. Admitted: (), (n), (push, n), + * (push, id), (push, id, n), (pop) over an unlabelled push and + * (pop, id) over a push of id. + */ + private static boolean appliedPackOperands(List operands, ArrayDeque labels) { + List texts = operands.stream().map(CToken::text).toList(); + java.util.function.Predicate value = ReaGhidraBridge::ghidraPackDecimal; + java.util.function.Predicate label = text -> isCIdentifierStart(text.charAt(0)) && + !text.equals("push") && !text.equals("pop"); + boolean push = !texts.isEmpty() && texts.get(0).equals("push"); + boolean pop = !texts.isEmpty() && texts.get(0).equals("pop"); + switch (texts.size()) { + case 0: + return true; + case 1: + if (value.test(texts.get(0))) return true; + if (!pop || !"".equals(labels.peek())) return false; + labels.pop(); + return true; + case 3: + if (!texts.get(1).equals(",")) return false; + if (push && (value.test(texts.get(2)) || label.test(texts.get(2)))) { + labels.push(value.test(texts.get(2)) ? "" : texts.get(2)); + return true; + } + if (!pop || !label.test(texts.get(2)) || !labels.contains(texts.get(2))) return false; + while (!labels.pop().equals(texts.get(2))) { } + return true; + case 5: + if (!push || !texts.get(1).equals(",") || !label.test(texts.get(2)) || + !texts.get(3).equals(",") || !value.test(texts.get(4))) return false; + labels.push(texts.get(2)); + return true; + default: + return false; + } + } + + /** + * Admit one directive from the tokens after its #. Only a declarations + * text's #pragma pack in a form Ghidra applies is admitted. C.jj reads + * "#pragma" as one token and "#" followed by a space as a line marker + * whose text it skips, so the name must follow # directly. + */ + private static void admitCallerCDirective( + CTokenizer tokens, CToken hash, String field, boolean declarations, String code, ArrayDeque packLabels) { + CToken first = tokens.next(true); + String name = first == null ? "" : first.text(); + boolean adjacent = first != null && first.line() == hash.line() && first.column() == hash.column() + 1; + // Any other directive is refused by its name, before its operands are read. + List directive = new ArrayList<>(); + if (declarations && adjacent && name.equals("pragma")) + for (CToken token = tokens.next(true); token != null; token = tokens.next(true)) directive.add(token); + boolean pack = directive.size() >= 3 && directive.get(0).is("pack") && directive.get(1).is("(") && + directive.get(directive.size() - 1).is(")") && + appliedPackOperands(directive.subList(2, directive.size() - 1), packLabels); + if (!adjacent && first != null) + throw refusedConstruct(code, field, "# separated from its directive name (Ghidra reads it as a line marker)", + hash.line(), hash.column()); + if (!pack && !directive.isEmpty() && directive.get(0).is("pack")) + throw refusedConstruct(code, field, "#pragma pack with operands Ghidra ignores or reads differently " + + "(it applies (), (n), (push, n), (push, id), (push, id, n) with a decimal n from 0 through 2147483647, (pop) over an unlabelled push and (pop, id) over a push of id)", + hash.line(), hash.column()); + if (!pack) + throw refusedConstruct(code, field, "the directive #" + name + + (name.equals("pragma") ? " (only #pragma pack is applied)" : ""), hash.line(), hash.column()); + } + + // One decimal or hex integer literal with no suffix, read the same way by C and by Ghidra. + private static final Pattern C_PLAIN_INTEGER = Pattern.compile("0|[1-9][0-9]*|0[xX][0-9a-fA-F]+"); + + /** + * The value of one constant expression (an enum value, array size or + * bit-field width), admitted only as a single decimal or hex integer + * literal within int, optionally negated. Ghidra 12.2 evaluates C constant + * expressions with its own rules: names, casts and sizeof stay unevaluated + * and default, values outside int are truncated, and comparisons and + * unsigned arithmetic differ from C (~0U >> 1 is -1). Emulating C against + * that evaluator is an open-ended set of mismatches, so anything but one + * literal is refused at its position and the caller writes the value. + */ + /** Admit the next token of a constant expression as it is read, so a refusal names the first token that leaves the form. */ + private static void admitConstantToken(List expression, CToken token, String field, String code) { + boolean admitted = expression.isEmpty() + ? token.is("-") || C_PLAIN_INTEGER.matcher(token.text()).matches() + : expression.size() == 1 && expression.get(0).is("-") && C_PLAIN_INTEGER.matcher(token.text()).matches(); + if (!admitted) + throw refusedConstruct(code, field, "the constant expression token " + token.text() + + " (Ghidra evaluates C constant expressions differently from C; write the computed value as one " + + "decimal or hex integer literal, optionally negated, without suffixes)", token.line(), token.column()); + } + + /** The value of an admitted constant expression; a value outside int, which Ghidra would truncate, is refused. */ + private static long admitConstantExpression(List tokens, String field, String code) { + CToken literal = tokens.get(tokens.size() - 1); + if (literal.is("-")) + throw refusedConstruct(code, field, "a lone - as a constant expression", literal.line(), literal.column()); + boolean negative = tokens.size() == 2; + String digits = literal.text(); + java.math.BigInteger value = digits.startsWith("0x") || digits.startsWith("0X") + ? new java.math.BigInteger(digits.substring(2), 16) : new java.math.BigInteger(digits); + if (negative) value = value.negate(); + if (value.compareTo(java.math.BigInteger.valueOf(Integer.MIN_VALUE)) < 0 || + value.compareTo(java.math.BigInteger.valueOf(Integer.MAX_VALUE)) > 0) + throw refusedConstruct(code, field, "the literal " + (negative ? "-" : "") + digits + + ", outside int (Ghidra truncates it; write a value within int)", literal.line(), literal.column()); + return value.longValue(); + } + + /** + * Tokenize caller C once, before the parser sees it: bound parenthesis + * nesting and refuse every construct Ghidra's parser accepts and drops. + * A declarations text may hold only struct, union, enum and typedef + * definitions and #pragma pack; a signature holds one prototype. + */ + private static AdmittedCallerC admitCallerC( + String text, String field, boolean declarations, String code, int maxParenthesisDepth) { + final int start = 0, tag = 1, named = 2, body = 3, afterBody = 4, typedef = 5; + int state = start; + int parentheses = 0, braces = 0; + // The deepest nesting in the whole text, so a refusal reports the depth to admit. + int deepest = 0, beyondLine = 0, beyondColumn = 0; + // A signature's parameter index: -1 before its parameter list opens, the return type. + int parameter = -1; + boolean parametersClosed = false; + JsonArray dropped = new JsonArray(); + String previous = ""; + String definition = ""; + boolean ended = false; + CTokenizer tokens = new CTokenizer(text, field, code); + // Labels of the #pragma pack pushes admitted so far, innermost first. + ArrayDeque packLabels = new ArrayDeque<>(); + // Declarations: whether each open brace is an enum body, the constant + // expression being read, and the next implicit enumerator value. + ArrayDeque enumBodies = new ArrayDeque<>(); + boolean enumPending = false; + List expression = null; + Set expressionEnds = Set.of(); + boolean enumExpression = false; + Long explicitEnumValue = null; + CToken enumerator = null; + long nextEnumValue = 0; + for (CToken next = tokens.next(false); next != null; next = tokens.next(false)) { + String token = next.text(); + int line = next.line(), column = next.column(); + if (next.is("#")) { + admitCallerCDirective(tokens, next, field, declarations, code, packLabels); + continue; + } + if (!declarations && token.equals("typedef")) + throw refusedConstruct(code, field, "the specifier typedef", line, column); + UnappliedCToken unapplied = unappliedC(token); + if (unapplied != null && unapplied.refused()) + throw refusedConstruct(code, field, String.format(unapplied.construct(), token) + + (declarations && unapplied.construct().startsWith("the attribute") ? " (use #pragma pack for packing)" : ""), + line, column); + if (unapplied != null) { + JsonObject qualifier = new JsonObject(); + qualifier.addProperty("qualifier", unapplied.droppedQualifier()); + qualifier.addProperty("line", line); + qualifier.addProperty("column", column); + if (!declarations) + qualifier.add("parameter_index", parameter < 0 || parametersClosed + ? JsonNull.INSTANCE : GSON.toJsonTree(parameter)); + dropped.add(qualifier); + } + if (ended && !token.equals(";")) + throw refusedConstruct(code, field, "a second declaration", line, column); + if (next.is("(") && ++parentheses > deepest) { + deepest = parentheses; + if (deepest == maxParenthesisDepth + 1) { + beyondLine = line; + beyondColumn = column; + } + } + if (!declarations && parentheses == 1 && !parametersClosed) { + if (token.equals("(") && parameter < 0) parameter = 0; + else if (token.equals(",")) parameter++; + } + if (token.equals(")")) { + if (!declarations && parentheses == 1 && parameter >= 0) parametersClosed = true; + parentheses = Math.max(0, parentheses - 1); + } + if (previous.equals("enum") && token.equals("{")) + throw refusedConstruct(code, field, "an unnamed enum, which Ghidra would store under a generated name", line, column); + if (!declarations) { + if (token.equals("{")) + throw refusedConstruct(code, field, "a function body", line, column); + if (token.equals("=")) + throw refusedConstruct(code, field, "a default argument or initializer", line, column); + if (previous.equals("(") && token.equals("*")) + throw refusedConstruct(code, field, "a function-pointer declarator", line, column); + if (token.equals(";")) ended = true; + previous = token; + continue; + } + boolean top = braces == 0 && parentheses == 0; + // Enum values, array sizes and bit-field widths are constant expressions + // Ghidra evaluates itself; admitConstantExpression owns which ones it gets right. + if (expression != null) { + if (!expressionEnds.contains(token)) { + admitConstantToken(expression, next, field, code); + expression.add(next); + } else { + Long value = expression.isEmpty() ? null : admitConstantExpression(expression, field, code); + if (enumExpression) explicitEnumValue = value; + expression = null; + } + } else if (token.equals("(")) { + // Ghidra applies no parenthesis in a definition as written: function + // declarators, attributes, casts, sizeof and grouped declarators are + // each refused or reported by its parser, so refuse the first one here. + throw refusedConstruct(code, field, "a parenthesis (a struct, union, enum or typedef definition " + + "admits none: Ghidra does not store function declarators, attributes or grouped declarators as written)", + line, column); + } else if (token.equals("[") || (token.equals("=") && Boolean.TRUE.equals(enumBodies.peek())) || + (token.equals(":") && Boolean.FALSE.equals(enumBodies.peek()) && !enumPending)) { + expression = new ArrayList<>(); + enumExpression = token.equals("="); + expressionEnds = token.equals("[") ? Set.of("]") : enumExpression ? Set.of(",", "}") : Set.of(";", ","); + } + boolean inEnum = Boolean.TRUE.equals(enumBodies.peek()); + if (inEnum && expression == null && next.isIdentifier() && (previous.equals("{") || previous.equals(","))) + enumerator = next; + // Ghidra numbers an enumerator without a value one past the previous, in int. + if (inEnum && expression == null && enumerator != null && (token.equals(",") || token.equals("}"))) { + long value = explicitEnumValue != null ? explicitEnumValue : nextEnumValue; + if (value > Integer.MAX_VALUE) + throw refusedConstruct(code, field, "the enumerator " + enumerator.text() + + ", whose implicit value leaves int (Ghidra truncates it)", enumerator.line(), enumerator.column()); + nextEnumValue = value + 1; + explicitEnumValue = null; + enumerator = null; + } + if (token.equals("enum")) enumPending = true; + if (token.equals(";")) enumPending = false; + if (token.equals("{")) { + enumBodies.push(enumPending); + if (enumPending) nextEnumValue = 0; + enumPending = false; + } + if (token.equals("}") && !enumBodies.isEmpty()) enumBodies.pop(); + if (token.equals("{")) braces++; + if (token.equals("}")) braces = Math.max(0, braces - 1); + switch (state) { + case start -> { + if (token.equals("typedef")) state = typedef; + else if (token.equals("struct") || token.equals("union") || token.equals("enum")) state = tag; + else if (!token.equals(";")) + throw refusedConstruct(code, field, + "a declaration that is not a struct, union, enum or typedef definition (" + token + ")", line, column); + } + case tag -> { + if (!next.isIdentifier()) + throw refusedConstruct(code, field, "an unnamed struct or union definition", line, column); + definition = token; + state = named; + } + case named -> { + if (token.equals("{")) state = body; + else if (token.equals(";")) state = start; + else throw refusedConstruct(code, field, "a variable declaration (" + token + ")", line, column); + } + case body -> { + if (braces == 0) state = afterBody; + } + case afterBody -> { + if (!token.equals(";")) + throw refusedConstruct(code, field, + "a variable or declarator (" + token + ") after the definition of " + definition, line, column); + state = start; + } + default -> { + if (top && token.equals(";")) state = start; + if (top && token.equals("=")) + throw refusedConstruct(code, field, "an initializer", line, column); + } + } + previous = token; + } + // Measured over the whole text, so the refusal names the depth that admits it. + if (deepest > maxParenthesisDepth) + throw new RequestFailure("parenthesis_depth_limit", field + " nests parentheses " + deepest + + " levels deep, first beyond " + maxParenthesisDepth + " at line " + beyondLine + ", column " + beyondColumn, + null, deepest); + return new AdmittedCallerC(dropped, ended, tokens.endsInLineComment); + } + + /** + * Ghidra 12.2 stores, names and compares a data type recursively through + * its pointer, array, typedef and member chain. Measured on Ghidra 12.2 + * (macOS arm64): 1024 levels resolve, 2048 exhaust the stack inside + * addDataType while its database lock is held, which leaves that lock held + * and the Program unusable. REA refuses a type deeper than this, a + * quarter of the last measured safe depth, before Ghidra walks it. + */ + private static final int MAX_C_TYPE_DEPTH = 256; + + /** + * Refuse a parsed type whose longest pointer, array, typedef, bit-field + * or member chain, including chains through existing database types, + * exceeds MAX_C_TYPE_DEPTH. Iterative with memoized depths; a chain back + * into a type still being walked (a self-referential pointer) adds no + * depth, because Ghidra resolves that reference without recursing. + */ + private static void requireBoundedTypeDepth(DataType root, String name, String field) { + Map depths = new IdentityHashMap<>(); + Set open = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + ArrayDeque stack = new ArrayDeque<>(); + stack.push(root); + while (!stack.isEmpty()) { + DataType type = stack.peek(); + if (depths.containsKey(type)) { + stack.pop(); + continue; + } + List children = cTypeChildren(type); + boolean ready = true; + if (open.add(type)) { + for (DataType child : children) + if (child != null && !depths.containsKey(child) && !open.contains(child)) { + stack.push(child); + ready = false; + } + if (!ready) continue; + } + int depth = 1; + for (DataType child : children) + if (child != null && depths.containsKey(child)) depth = Math.max(depth, depths.get(child) + 1); + depths.put(type, depth); + open.remove(type); + stack.pop(); + } + // The whole chain is measured, so the reported depth is the one compared with the limit. + int depth = depths.get(root); + if (depth > MAX_C_TYPE_DEPTH) + throw new RequestFailure("type_depth_limit", field + " defines " + name + ", chained " + depth + + " levels deep through pointers, arrays, typedefs, members or existing database types"); + } + + private static List cTypeChildren(DataType type) { + if (type instanceof ghidra.program.model.data.Pointer pointer) return java.util.Collections.singletonList(pointer.getDataType()); + if (type instanceof ghidra.program.model.data.Array array) return List.of(array.getDataType()); + if (type instanceof ghidra.program.model.data.BitFieldDataType bitField) return List.of(bitField.getBaseDataType()); + if (type instanceof ghidra.program.model.data.TypeDef alias) return List.of(alias.getDataType()); + if (type instanceof ghidra.program.model.data.FunctionDefinition function) { + List children = new ArrayList<>(); + children.add(function.getReturnType()); + for (ghidra.program.model.data.ParameterDefinition argument : function.getArguments()) + children.add(argument.getDataType()); + return children; + } + if (type instanceof ghidra.program.model.data.Composite composite) { + List children = new ArrayList<>(); + for (ghidra.program.model.data.DataTypeComponent component : composite.getComponents()) + children.add(component.getDataType()); + return children; + } + return List.of(); + } + + /** The caller's per-call bound, or its default; the contract owns the range. */ + private static int callerBound(JsonObject params, String name, int minimum, int defaultValue, int maximum) { + if (!params.has(name)) return defaultValue; + int bound = requireInteger(params, name); + if (bound < minimum || bound > maximum) + throw new RequestFailure("invalid_request", name + " must be from " + minimum + " to " + maximum); + return bound; + } + + private static int callerCTextBound(JsonObject params, String name, int defaultValue, int maximum) { + return callerBound(params, name, MIN_C_TEXT_UTF16, defaultValue, maximum); + } + + private static int callerParenthesisBound(JsonObject params) { + return callerBound(params, "parenthesis_max_depth", + MIN_C_PARENTHESIS_DEPTH, DEFAULT_C_PARENTHESIS_DEPTH, MAX_C_PARENTHESIS_DEPTH); + } + + /** + * Parse caller C text against the type database. Even with storeDataType + * false, Ghidra's parser writes the database: a definition whose name + * matches an existing empty composite fills that type in place, in the + * parser's own nested transaction. The caller's open transaction is + * therefore the only rollback for a refused or failed edit. + */ + private ParsedCallerC parseCallerC( + String text, String field, boolean declarations, String code, int maximum, int maxParenthesisDepth) { + if (currentProgram.getCurrentTransactionInfo() == null) + throw new IllegalStateException("Caller C must be parsed inside the edit's transaction"); + validateAnnotationText(text, field); + if (text.length() > maximum) + throw new RequestFailure(declarations ? "declarations_length_limit" : "signature_length_limit", + field + " has " + text.length() + " UTF-16 code units", null, text.length()); + AdmittedCallerC admitted = admitCallerC(text, field, declarations, code, maxParenthesisDepth); + DataTypeManager types = currentProgram.getDataTypeManager(); + CParser parser = new CParser(types, false, new DataTypeManager[] { types }); + try { + // The parser needs a terminated prototype, and its // skip token + // requires a line break. Nothing precedes the caller's text, so the + // parser's positions name the caller's own lines. A line comment at + // the end gets a newline first, so a semicolon added for an + // unterminated prototype is not swallowed. + String source = admitted.endsInLineComment() ? text + "\n" : text; + parser.parse(declarations || admitted.terminated() ? source : source + ";"); + } + catch (ghidra.app.util.cparser.C.ParseException | ghidra.app.util.cparser.C.TokenMgrError rejected) { + throw new RequestFailure(code, "Ghidra's C parser rejected " + field + ": " + cParserReason(rejected.getMessage())); + } + if (!parser.didParseSucceed()) + throw new RequestFailure(code, "Ghidra's C parser rejected " + field + ": " + cParserReason(parser.getParseMessages())); + // The parser records what it could not apply, such as a repeated + // enumerator it drops, and still reports success. + String diagnostics = cParserDiagnostics(parser.getParseMessages()); + if (!diagnostics.isEmpty()) + throw new RequestFailure(code, "Ghidra's C parser reported " + field + ": " + diagnostics + + "; it would not apply the text as written, so nothing was changed"); + // Before anything walks the parsed types recursively (naming, comparing, storing). + for (Map parsedTypes : List.of( + parser.getComposites(), parser.getEnums(), parser.getTypes(), parser.getFunctions())) + for (Map.Entry parsedType : parsedTypes.entrySet()) + requireBoundedTypeDepth(parsedType.getValue(), parsedType.getKey(), field); + return new ParsedCallerC(parser, admitted.droppedQualifiers()); + } + + /** + * The parser picks one type for a name. When the database holds another, + * different type under the same name, the caller cannot select between them. + */ + private void requireUnambiguousType(DataType type) { + DataType named = type; + while (named instanceof ghidra.program.model.data.Pointer || named instanceof ghidra.program.model.data.Array) + named = named instanceof ghidra.program.model.data.Pointer pointer + ? pointer.getDataType() : ((ghidra.program.model.data.Array) named).getDataType(); + if (named == null || named instanceof ghidra.program.model.data.BuiltInDataType) return; + List sameName = new ArrayList<>(); + currentProgram.getDataTypeManager().findDataTypes(named.getName(), sameName); + Set candidates = new TreeSet<>(); + for (DataType other : sameName) + if (!other.getPathName().equals(named.getPathName()) && !other.isEquivalent(named)) + candidates.add(other.getPathName()); + if (candidates.isEmpty()) return; + candidates.add(named.getPathName()); + throw new RequestFailure("ambiguous_data_type", "The type name " + named.getName() + + " names different types in the database: " + String.join(", ", candidates)); + } + + + /** Keep the location and offending token; drop the generated expected-token list. */ + /** + * Ghidra's own diagnostic lines. Without a header file the parser has no + * position to give; it names the nearest type when it has one. + */ + private static String cParserDiagnostics(String messages) { + if (messages == null) return ""; + List lines = new ArrayList<>(); + for (String line : messages.split("\\R")) { + String stripped = line.strip(); + if (stripped.isEmpty() || stripped.startsWith("In file ") || + stripped.equals("Near datatype: undefined") || stripped.equals("Near datatype: - none -")) continue; + lines.add(stripped); + } + return lines.isEmpty() ? "" : cParserReason(String.join("; ", lines)); + } + + private static String cParserReason(String message) { + if (message == null || message.isBlank()) return "no reason reported"; + int expected = message.indexOf("Was expecting"); + String reason = WHITESPACE_RUN.matcher(expected < 0 ? message : message.substring(0, expected)).replaceAll(" ").strip(); + return reason.length() > 240 ? reason.substring(0, 240) : reason; + } + + /** A parsed prototype and the qualifiers in its text that Ghidra does not record. */ + private record SignatureEdit(FunctionDefinitionDataType prototype, JsonArray droppedQualifiers) {} + + private SignatureEdit parseFunctionSignature(Function function, String text, int maximum, int maxParenthesisDepth) { + String code = "invalid_function_signature"; + String entry = canonicalAddress(function.getEntryPoint()); + // Ghidra redirects a thunk's prototype to the thunked function, which may be external. + if (function.isThunk()) + throw new RequestFailure(code, "Function at " + entry + " is a thunk; its prototype belongs to the function it forwards to"); + ParsedCallerC parsed = parseCallerC(text, "signature", false, code, maximum, maxParenthesisDepth); + CParser parser = parsed.parser(); + // The parser invents an empty composite or enum for an undefined tag, and a + // prototype defines no types, so every type it reports was invented. + Set undefined = new TreeSet<>(parser.getComposites().keySet()); + undefined.addAll(parser.getEnums().keySet()); + undefined.addAll(parser.getTypes().keySet()); + if (!undefined.isEmpty()) + throw new RequestFailure("unknown_data_type", "signature uses types the database does not define: " + + String.join(", ", undefined)); + Map functions = parser.getFunctions(); + if (functions.size() != 1 || + !(functions.values().iterator().next() instanceof FunctionDefinitionDataType prototype)) + throw new RequestFailure(code, "signature must be one C function prototype without function-pointer parameters; found " + + functions.size() + " function declarators"); + Set names = new HashSet<>(); + for (ParameterDefinition parameter : prototype.getArguments()) { + String name = parameter.getName(); + if (name != null && !name.isEmpty() && !names.add(name)) + throw new RequestFailure(code, "signature repeats parameter name " + name); + requireUnambiguousType(parameter.getDataType()); + } + requireUnambiguousType(prototype.getReturnType()); + return new SignatureEdit(prototype, parsed.droppedQualifiers()); + } + + private void applyFunctionSignature(Function function, FunctionDefinitionDataType prototype) throws Exception { + String code = "invalid_function_signature"; + String entry = canonicalAddress(function.getEntryPoint()); + // Ghidra assigns the locked parameter storage with the compiler specification's + // default convention when the function has none. Recording that convention keeps + // the decompiler from reporting locked storage under an unknown convention. + if (function.getCallingConvention() == null && prototype.hasUnknownCallingConventionName()) + prototype.setCallingConvention(currentProgram.getCompilerSpec().getDefaultCallingConvention().getName()); + // The prototype's own name is never applied; the name field owns renames. + ApplyFunctionSignatureCmd command = new ApplyFunctionSignatureCmd( + function.getEntryPoint(), prototype, SourceType.USER_DEFINED, false, false, + DataTypeConflictHandler.DEFAULT_HANDLER, FunctionRenameOption.NO_CHANGE); + if (!command.applyTo(currentProgram, monitor)) + throw new RequestFailure(code, "Ghidra refused the signature at " + entry + ": " + + (command.getStatusMsg() == null ? "no reason reported" : command.getStatusMsg())); + FunctionSignature applied = function.getSignature(true); + ParameterDefinition[] requested = prototype.getArguments(); + ParameterDefinition[] observed = applied.getArguments(); + boolean matches = function.getSignatureSource() == SourceType.USER_DEFINED && + applied.getReturnType().isEquivalent(prototype.getReturnType()) && + applied.hasVarArgs() == prototype.hasVarArgs() && + (!prototype.hasNoReturn() || function.hasNoReturn()) && + observed.length == requested.length && + (prototype.hasUnknownCallingConventionName() || + prototype.getCallingConventionName().equals(function.getCallingConventionName())); + for (int index = 0; matches && index < requested.length; index++) { + String name = requested[index].getName(); + matches = observed[index].getDataType().isEquivalent(requested[index].getDataType()) && + (name == null || name.isEmpty() || name.equals(observed[index].getName())); + } + // Ghidra settles array parameters, renames parameters that collide with + // other symbols and ignores conventions the compiler specification lacks. + if (!matches) + throw new RequestFailure(code, "Ghidra applied a different prototype at " + entry + " than requested: " + + applied.getPrototypeString(false) + "; requested " + prototype.getPrototypeString(false)); + } + + /** + * Ghidra keeps typedefs, enum tags and struct or union tags in separate + * maps and stores one type per name. A typedef of its own struct or enum + * (`typedef struct s { ... } s`) is that tag, recorded once. Overlapping + * names stay one stored type only when the definitions are equivalent; + * any other overlap is refused so the call stores every definition or none. + */ + private static Map mergeCallerTypeMaps( + Map typedefs, + Map enumerations, + Map composites) { + Map defined = new TreeMap<>(); + Set collisions = new TreeSet<>(); + absorbCallerTypes(defined, collisions, typedefs); + absorbCallerTypes(defined, collisions, enumerations); + absorbCallerTypes(defined, collisions, composites); + if (!collisions.isEmpty()) + throw new RequestFailure("conflicting_type_definitions", + "declarations define different types under one name: " + String.join(", ", collisions) + + "; nothing was changed"); + return defined; + } + + private static void absorbCallerTypes( + Map defined, Set collisions, Map incoming) { + for (Map.Entry entry : incoming.entrySet()) { + String name = entry.getKey(); + DataType type = entry.getValue(); + DataType existing = defined.get(name); + if (existing == null) { + defined.put(name, type); + continue; + } + if (!sameCallerType(existing, type)) { + collisions.add(name); + continue; + } + // The tag is the type a matching typedef names. + if (callerTag(type) && !callerTag(existing)) defined.put(name, type); + } + } + + private static boolean sameCallerType(DataType left, DataType right) { + return left == right || left.isEquivalent(right) || right.isEquivalent(left); + } + + private static boolean callerTag(DataType type) { + return type instanceof ghidra.program.model.data.Composite || + type instanceof ghidra.program.model.data.Enum; + } + + /** + * Composites with no defined components, keyed by identity to the length + * they had before parsing. Ghidra's parser fills such a composite in place + * when storeDataType is false, and that object is the definition it returns. + */ + private Map emptyCompositeLengths() { + Map lengths = new IdentityHashMap<>(); + Iterator all = currentProgram.getDataTypeManager().getAllDataTypes(); + while (all.hasNext()) { + DataType type = all.next(); + if (type instanceof ghidra.program.model.data.Composite composite && + composite.getNumDefinedComponents() == 0) + lengths.put(type, composite.getLength()); + } + return lengths; + } + + /** A filled empty composite is a replacement of a database type, so the call stores nothing. */ + private void requireUnfilledComposites(Map before) { + DataTypeManager types = currentProgram.getDataTypeManager(); + Set replaced = new TreeSet<>(); + for (Map.Entry entry : before.entrySet()) { + DataType type = entry.getKey(); + if (!(type instanceof ghidra.program.model.data.Composite composite) || !types.contains(type)) { + replaced.add(type.getPathName()); + continue; + } + if (composite.getNumDefinedComponents() != 0 || composite.getLength() != entry.getValue()) + replaced.add(composite.getPathName()); + } + if (replaced.isEmpty()) return; + throw new RequestFailure("data_type_conflict", + "Parsing would replace an empty type already in the database: " + String.join(", ", replaced) + + "; nothing was changed"); + } + + private JsonObject defineNativeDataTypes(JsonObject params) throws Exception { + if (!Set.of("declarations", "declarations_max_utf16").containsAll(params.keySet()) || !params.has("declarations")) + throw new RequestFailure("invalid_request", "Bridge request fields are invalid"); + String code = "invalid_type_declarations"; + String declarations = requireText(params, "declarations"); + int lengthBound = callerCTextBound( + params, "declarations_max_utf16", DEFAULT_TYPE_DECLARATIONS_UTF16, MAX_TYPE_DECLARATIONS_UTF16); + // Ghidra's parser writes the database (see parseCallerC), so parsing, + // validation and storage share one rollback: a refusal changes nothing. + int transaction = currentProgram.startTransaction("REA data type definitions"); + boolean commit = false; + try { + // An empty composite is filled in place by the parser. Remember those + // shapes so a fill is not later mistaken for an unchanged definition. + Map emptyComposites = emptyCompositeLengths(); + ParsedCallerC parsedDeclarations = + // Declarations admit no parentheses (see admitCallerC), so no nesting bound applies. + parseCallerC(declarations, "declarations", true, code, lengthBound, MAX_C_PARENTHESIS_DEPTH); + requireUnfilledComposites(emptyComposites); + CParser parser = parsedDeclarations.parser(); + if (!parser.getFunctions().isEmpty()) + throw new RequestFailure(code, "declarations must not declare functions or function-pointer members: " + + String.join(", ", new TreeSet<>(parser.getFunctions().keySet()))); + Map defined = mergeCallerTypeMaps( + parser.getTypes(), parser.getEnums(), parser.getComposites()); + if (defined.isEmpty()) + throw new RequestFailure(code, "declarations define no struct, union, enum or typedef"); + DataTypeManager types = currentProgram.getDataTypeManager(); + Set parsed = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); + parsed.addAll(defined.values()); + List conflicts = new ArrayList<>(); + Set existing = new HashSet<>(); + for (Map.Entry entry : defined.entrySet()) { + monitor.checkCancelled(); + String name = entry.getKey(); + DataType type = entry.getValue(); + // Ghidra's parser invents an empty type for a struct, union or enum + // tag that neither the text nor the database defines, and reports nothing. + if (type instanceof ghidra.program.model.data.Enum enumeration && enumeration.getCount() == 0) + throw new RequestFailure(code, "declarations leave enum " + name + " without members; define every enum they use"); + if (type instanceof ghidra.program.model.data.Composite composite) { + if (composite.getNumComponents() == 0) + throw new RequestFailure(code, "declarations leave " + name + " without members; define every struct or union they use"); + Set members = new HashSet<>(); + for (ghidra.program.model.data.DataTypeComponent component : composite.getComponents()) + if (component.getFieldName() != null && !members.add(component.getFieldName())) + throw new RequestFailure(code, name + " repeats member name " + component.getFieldName()); + } + requireStoredDependencies(name, type, parsed, types, + java.util.Collections.newSetFromMap(new IdentityHashMap<>())); + String path = CALLER_DEFINED_TYPES.getPath() + "/" + name; + List sameName = new ArrayList<>(); + types.findDataTypes(name, sameName); + for (DataType other : sameName) { + if (other.getPathName().equals(path)) existing.add(name); + else conflicts.add(name + " (existing " + other.getPathName() + ")"); + } + } + if (!conflicts.isEmpty()) + throw new RequestFailure("data_type_conflict", "The database already holds types with these names: " + String.join(", ", conflicts)); + for (DataType type : defined.values()) type.setCategoryPath(CALLER_DEFINED_TYPES); + JsonArray rows = new JsonArray(); + for (Map.Entry entry : defined.entrySet()) { + monitor.checkCancelled(); + String name = entry.getKey(); + String path = CALLER_DEFINED_TYPES.getPath() + "/" + name; + DataType stored = types.addDataType(entry.getValue(), DataTypeConflictHandler.DEFAULT_HANDLER); + // The default handler keeps a differing existing type and stores the new one under a conflict name. + if (!stored.getPathName().equals(path)) + throw new RequestFailure("data_type_conflict", name + " is already defined differently as " + path); + DataType readback = types.getDataType(path); + if (readback == null || !readback.isEquivalent(entry.getValue())) + throw new RequestFailure("data_type_readback_mismatch", "Data type readback differs for " + path); + JsonObject row = new JsonObject(); + row.addProperty("id", path); + row.addProperty("name", name); + row.addProperty("kind", dataTypeKind(readback)); + row.add("size_bytes", readback.getLength() < 0 ? JsonNull.INSTANCE : GSON.toJsonTree(readback.getLength())); + row.addProperty("status", existing.contains(name) ? "unchanged" : "defined"); + rows.add(row); + } + JsonObject result = new JsonObject(); + result.add("types", rows); + if (!parsedDeclarations.droppedQualifiers().isEmpty()) + result.add("dropped_qualifiers", parsedDeclarations.droppedQualifiers()); + JsonObject effects = new JsonObject(); + effects.addProperty("scope", "session-analysis-database"); + effects.addProperty("source_bytes_modified", false); + result.add("effects", effects); + monitor.checkCancelled(); + commit = true; + return result; + } + catch (ghidra.util.exception.DuplicateNameException | IllegalArgumentException exception) { + throw new RequestFailure(code, "Ghidra refused the declarations: " + safeMessage(exception)); + } + finally { + currentProgram.endTransaction(transaction, commit); + } + } + + /** Every named type a definition reaches must be defined here or already stored. */ + private void requireStoredDependencies( + String owner, DataType root, Set parsed, DataTypeManager types, Set visited) { + // A worklist, not recursion: caller text sets how deep pointer, array and member chains go. + // ArrayDeque admits no null, and a generic pointer has no pointed-to type. + ArrayDeque pending = new ArrayDeque<>(); + pending.push(root); + while (!pending.isEmpty()) { + DataType type = pending.pop(); + if (!visited.add(type)) continue; + // Pointer, array and bit-field types are built-in classes; look through them first. + if (type instanceof ghidra.program.model.data.Pointer || type instanceof ghidra.program.model.data.Array || + type instanceof ghidra.program.model.data.BitFieldDataType) { + for (DataType child : cTypeChildren(type)) if (child != null) pending.push(child); + continue; + } + if (type instanceof ghidra.program.model.data.BuiltInDataType) continue; + if (!parsed.contains(type)) { + if (types.contains(type)) { + requireUnambiguousType(type); + continue; + } + throw new RequestFailure("invalid_type_declarations", owner + + " embeds an unnamed or undeclared type (" + type.getName() + "); declare it by name in the same declarations"); + } + if (type instanceof ghidra.program.model.data.TypeDef || type instanceof ghidra.program.model.data.Composite) + for (DataType child : cTypeChildren(type)) if (child != null) pending.push(child); + } + } + private String symbolLeafName(Symbol symbol, String requested) throws ghidra.util.exception.InvalidInputException { // Fully qualified readback must be usable as an idempotent rename input. if (requested.equals(symbol.getName(true))) return symbol.getName(); @@ -7073,19 +8102,15 @@ public final class ReaGhidraBridge extends HeadlessScript { int id, String code, String message) throws IOException { - writeFailure(writer, id, code, message, null); + writeFailure(writer, id, new RequestFailure(code, message)); } - private static void writeFailure( - BufferedWriter writer, - int id, - String code, - String message, - JsonArray candidates) throws IOException { + private static void writeFailure(BufferedWriter writer, int id, RequestFailure failure) throws IOException { JsonObject error = new JsonObject(); - error.addProperty("code", code); - error.addProperty("message", message); - if (candidates != null) error.add("candidates", candidates); + error.addProperty("code", failure.code); + error.addProperty("message", failure.getMessage()); + if (failure.candidates != null) error.add("candidates", failure.candidates); + if (failure.requiredValue != null) error.addProperty("required_value", failure.requiredValue); JsonObject response = new JsonObject(); response.addProperty("id", id); response.addProperty("ok", false); @@ -7456,10 +8481,23 @@ public final class ReaGhidraBridge extends HeadlessScript { this(code, message, null); } + /** The measured value a per-call control must admit, for a bounded refusal only. */ + private final Integer requiredValue; + RequestFailure(String code, String message, JsonArray candidates) { + this(code, message, candidates, null); + } + + RequestFailure(String code, String message, JsonArray candidates, Integer requiredValue) { super(message); this.code = code; this.candidates = candidates; + this.requiredValue = requiredValue; + } + + /** The same failure, its facts kept, with context before its message. */ + RequestFailure prefixed(String context) { + return new RequestFailure(code, context + getMessage(), candidates, requiredValue); } } diff --git a/docs/getting-started/installation.md b/docs/getting-started/installation.md index 76cec37dc1..b7612e570c 100644 --- a/docs/getting-started/installation.md +++ b/docs/getting-started/installation.md @@ -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 diff --git a/docs/guides/native/native-investigation.md b/docs/guides/native/native-investigation.md index 8f8f11d858..0d965135db 100644 --- a/docs/guides/native/native-investigation.md +++ b/docs/guides/native/native-investigation.md @@ -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 diff --git a/docs/providers/ghidra-provider.md b/docs/providers/ghidra-provider.md index fc4686d0f5..4b0d82bdf7 100644 --- a/docs/providers/ghidra-provider.md +++ b/docs/providers/ghidra-provider.md @@ -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: diff --git a/docs/reference/rea-limit-inventory.md b/docs/reference/rea-limit-inventory.md index de911dd153..bde3322132 100644 --- a/docs/reference/rea-limit-inventory.md +++ b/docs/reference/rea-limit-inventory.md @@ -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` | diff --git a/package.json b/package.json index 35263816ea..a3138f2ef2 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/scripts/lib/real-ghidra-boundaries.mjs b/scripts/lib/real-ghidra-boundaries.mjs index f22df88ab1..d3f1884617 100644 --- a/scripts/lib/real-ghidra-boundaries.mjs +++ b/scripts/lib/real-ghidra-boundaries.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); diff --git a/scripts/verify-real-ghidra-type-edits.mjs b/scripts/verify-real-ghidra-type-edits.mjs new file mode 100644 index 0000000000..c75f251ba5 --- /dev/null +++ b/scripts/verify-real-ghidra-type-edits.mjs @@ -0,0 +1,1341 @@ +#!/usr/bin/env node +import { sha256File } from "./lib/verifier-file-sha256.mjs"; +import { createVerifierCommands } from "./lib/verify-commands.mjs"; +import { createVerifierMcpOwner } from "./lib/verifier-mcp-owner.mjs"; + +import assert from "node:assert/strict"; +import { mkdir, readdir, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { + requireMcpOperationResult, + requireMcpToolError, +} from "./lib/mcp-verifier-results.mjs"; +import { + createVerifierRun, + completeVerifierRun, + assertVerifierCleanupComplete, +} from "./lib/verifier-run.mjs"; +import { VerifierFixture } from "./lib/verifier-fixture.mjs"; +import { completeEvidenceClient } from "./lib/complete-evidence.mjs"; + +if (process.platform === "win32") + throw new Error("Ghidra database edits currently support Linux/macOS only."); +const run = createVerifierRun(); +// Ghidra children use the root as HOME and TMPDIR; a plain root admits them on every host. +const workspace = await VerifierFixture.open({ + prefix: "rea-ghidra-type-edits-", + private: false, +}); +const root = workspace.path; +const runtime = join(root, "runtime"), + checkpointDirectory = join(root, "checkpoints"); +const entrypoint = fileURLToPath(new URL("./rea.mjs", import.meta.url)); +const sourcePath = join(root, "fixture.c"), + target = join(root, "type-edit-fixture"); +const opaqueSourcePath = join(root, "opaque.c"), + opaqueTarget = join(root, "opaque-fixture"); +const env = { + ...process.env, + HOME: root, + XDG_CONFIG_HOME: join(root, "config"), + XDG_CACHE_HOME: join(root, "cache"), + XDG_DATA_HOME: join(root, "data"), + TMPDIR: runtime, + JDK_JAVA_OPTIONS: `-Duser.home=${root}`, + REA_ANALYSIS_PROVIDER: "ghidra", + REA_GHIDRA_CHECKPOINT_DIR: checkpointDirectory, +}; +for (const name of [ + "REA_GHIDRA_PROJECT_PATH", + "REA_GHIDRA_PROGRAM_NAME", + "REA_GHIDRA_SEED_FILE", + "REA_GHIDRA_NATIVEAOT_JAR", + "REA_GHIDRA_LANGUAGE_ID", + "REA_GHIDRA_COMPILER_SPEC_ID", + "REA_GHIDRA_DISABLED_ANALYZERS", +]) + delete env[name]; +const commands = await createVerifierCommands(); +const report = { + verifier: "ghidra-signature-and-type-edits", + phases: [], + target: null, +}; + +async function phase(name, operation) { + const start = performance.now(); + try { + const facts = await operation(); + report.phases.push({ + name, + status: "verified", + elapsed_ms: Math.round(performance.now() - start), + ...facts, + }); + } catch (cause) { + report.phases.push({ + name, + status: "failed", + elapsed_ms: Math.round(performance.now() - start), + }); + throw cause; + } +} +async function connect(environment = {}) { + const owner = createVerifierMcpOwner(); + const client = completeEvidenceClient( + new Client({ name: "rea-ghidra-type-edit-verifier", version: "1" }), + ); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [entrypoint, "mcp"], + env: { ...env, ...environment }, + stderr: "pipe", + }); + transport.stderr?.on("data", () => {}); + commands.adopt(owner, "type edit MCP connection"); + await owner.open(client, transport); + const raw = (name, args = {}) => + client.callTool({ name, arguments: args }, { timeout: 240000 }); + return { + raw, + call: async (name, args = {}) => + requireMcpOperationResult(await raw(name, args), name), + /** The refusal's single input issue and its recovery. */ + refused: async (name, args, field) => { + const error = requireMcpToolError(await raw(name, args)); + assert.equal(error.code, "invalid_request"); + assert.deepEqual( + error.details.issues.map((issue) => issue.path), + [[field]], + ); + return { + message: error.details.issues[0].message, + action: error.remediation.action, + }; + }, + /** The refusal bound to the per-call length control of Ghidra's C parser. */ + overLimit: async (name, args, limit) => { + const error = requireMcpToolError(await raw(name, args)); + assert.equal(error.code, "resource_constraint"); + assert.deepEqual(error.details.limit, { + control_kind: "parameter", + unit: "count", + applies_at: "next_call", + minimum: 16, + ...limit, + }); + assert.ok(error.message.includes(limit.parameter)); + assert.match(error.message, /Nothing in this call was applied/u); + }, + /** The refusal of nesting over parenthesis_max_depth, measured over the whole text. */ + overNesting: async (name, args, required) => { + const error = requireMcpToolError(await raw(name, args)); + assert.equal(error.code, "resource_constraint"); + const effective = args.parenthesis_max_depth ?? 8; + assert.deepEqual(error.details.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, + }); + assert.match( + error.message, + new RegExp(`nests parentheses ${String(required)} levels deep`, "u"), + ); + }, + close: () => owner.close(), + }; +} + +// Without debug information a Mach-O symbol keeps its leading underscore, +// and the function's primary name may be another label at the entry. +const procedure = + process.platform === "darwin" ? "_rea_session_total" : "rea_session_total"; +const sessionType = "/rea_caller_defined/session"; +const sessionDeclaration = + "struct session { int id; char name[32]; unsigned flags; double score; struct session *next; };"; +const signature = "double total(const struct session *s, unsigned mask)"; +const pseudocode = async (session) => + await session.call("procedure_pseudo_code", { + detail: "complete", + procedure, + }); +const typeStatus = async (session, type) => + (await session.call("inspect_native_data_type", { type })).status; + +try { + await mkdir(runtime); + await writeFile( + sourcePath, + `struct session { int id; char name[32]; unsigned flags; double score; struct session *next; }; +__attribute__((noinline)) double rea_session_total(const struct session *s, unsigned mask) { + double total = 0; + for (; s; s = s->next) if (s->flags & mask) total += s->score; + return total; +} +int main(void) { struct session one = { 1, "one", 16, 1.5, 0 }; return (int)rea_session_total(&one, 16); } +`, + ); + // No debug information: Ghidra must not recover the structure on its own. + // The macOS target is the object so the fixture needs no SDK link step. + await commands.exec( + "cc", + [ + "-O1", + "-g0", + "-fno-inline", + ...(process.platform === "darwin" ? ["-c"] : []), + sourcePath, + "-o", + target, + ], + { timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }, + ); + // With DWARF, Ghidra imports the forward-declared struct as an empty + // composite in the program's own archive: the type its parser fills in place. + // An ELF object embeds its DWARF and needs no link step; Mach-O keeps it in a + // separate dSYM, so macOS cross-compiles the object. + await writeFile( + opaqueSourcePath, + "struct rea_opaque;\n__attribute__((noinline)) void *rea_keep(struct rea_opaque *o) { return o; }\n", + ); + await commands.exec( + "cc", + [ + "-O1", + "-g", + "-c", + ...(process.platform === "darwin" + ? ["--target=x86_64-unknown-linux-gnu"] + : []), + opaqueSourcePath, + "-o", + opaqueTarget, + ], + { timeout: 120_000, maxBuffer: 16 * 1024 * 1024 }, + ); + const targetDigest = await sha256File(target); + report.target = { + sha256: targetDigest, + source: `self-built C fixture without debug information (${process.platform === "darwin" ? "object" : "executable"}); never executed`, + host: process.platform, + architecture: process.arch, + }; + + let before, baseline; + const first = await connect(); + try { + await first.call("open_binary", { path: target, provider_id: "ghidra" }); + await phase("analysis alone recovers no structure fields", async () => { + before = await pseudocode(first); + baseline = await first.call("procedure_info", { procedure }); + assert.doesNotMatch(before, /->(?:flags|score|next)/u); + assert.equal(await typeStatus(first, sessionType), "unavailable"); + return {}; + }); + await phase( + "a refused signature applies no name, comment or prototype", + async () => { + const rejected = { + procedure, + name: "rea_must_not_apply", + comment: "must not apply", + }; + const undefinedType = await first.refused( + "annotate_native_function", + { ...rejected, signature }, + "signature", + ); + assert.match(undefinedType.message, /does not define: session/u); + assert.match(undefinedType.action, /define_native_data_types/u); + const syntax = await first.refused( + "annotate_native_function", + { ...rejected, signature: "double total(int a" }, + "signature", + ); + assert.match(syntax.message, /line 1, column/u); + // The prototype's own parentheses are one level, so this reaches nine. + await first.overNesting( + "annotate_native_function", + { + ...rejected, + signature: `int total(int a[${"(".repeat(8)}1${")".repeat(8)}])`, + }, + 9, + ); + // The required depth is the text's deepest, not the first over the bound. + await first.overNesting( + "annotate_native_function", + { + ...rejected, + signature: `int total(int a[(((1)))], int b[${"(".repeat(10)}1${")".repeat(10)}])`, + parenthesis_max_depth: 3, + }, + 11, + ); + const long = `int total(int a /* ${"x".repeat(2040)} */)`; + await first.overLimit( + "annotate_native_function", + { ...rejected, signature: long }, + { + parameter: "signature_max_utf16", + effective_value: 2048, + maximum: 4096, + default_value: 2048, + required_value: long.length, + }, + ); + // Parentheses inside comments are not nesting, and comments cannot hide it. + await first.overNesting( + "annotate_native_function", + { + ...rejected, + signature: `int total(int a[${"( /*)*/".repeat(8)}1${")".repeat(8)}])`, + }, + 9, + ); + // Each is accepted by Ghidra's parser and applied differently or not at all. + for (const [refusedSignature, reason] of [ + ["double total(int a, int a)", /repeats parameter name a/u], + [ + "double total(int (*callback)(int))", + /function-pointer declarator at line 1, column 19/u, + ], + [ + "double (*total)(int a)", + /function-pointer declarator at line 1, column 9/u, + ], + ["double total(int a[4])", /applied a different prototype/u], + [ + "void total(int a) __attribute__((noreturn))", + /__attribute__ at line 1, column 19/u, + ], + [ + "__declspec(noreturn) void total(int a)", + /__declspec at line 1, column 1/u, + ], + [ + "static double total(int a)", + /specifier static at line 1, column 1/u, + ], + ["inline double total(int a)", /specifier inline/u], + [ + "double total(register int a)", + /specifier register at line 1, column 14/u, + ], + [ + "double total(int a) { return 1; }", + /function body at line 1, column 21/u, + ], + [ + "double total(int a = 3)", + /default argument or initializer at line 1, column 20/u, + ], + [ + "double total(int a); int y", + /second declaration at line 1, column 22/u, + ], + ['double total(int a) __asm__("g")', /__asm__ at line 1, column 21/u], + // Ghidra stores a native-width pointer for these and ignores the rest. + [ + "double total(int * __ptr64 a)", + /pointer-width qualifier __ptr64 \(Ghidra stores a native-width pointer\) at line 1, column 20/u, + ], + ["double total(int __far * a)", /pointer qualifier __far/u], + [ + "__forceinline double total(int a)", + /specifier __forceinline at line 1, column 1/u, + ], + [ + "[[noreturn]] double total(int a)", + /\[\[\.\.\.\]\] attribute at line 1, column 1/u, + ], + ["double total(enum rea_missing a)", /does not define: rea_missing/u], + ["#pragma pack(1)\ndouble total(int a)", /directive #pragma/u], + ]) { + const refusal = await first.refused( + "annotate_native_function", + { ...rejected, signature: refusedSignature }, + "signature", + ); + assert.match(refusal.message, reason); + } + assert.equal(await pseudocode(first), before); + const info = await first.call("procedure_info", { procedure }); + assert.equal(info.name, baseline.name); + assert.equal(info.signature, baseline.signature); + assert.equal(info.symbol.source, baseline.symbol.source); + // The parser's invented placeholder for the undefined tag was not stored. + assert.equal(await typeStatus(first, sessionType), "unavailable"); + assert.equal(await typeStatus(first, "/session"), "unavailable"); + return {}; + }, + ); + await phase( + "definitions are stored together, read back and marked caller-defined", + async () => { + const defined = await first.call("define_native_data_types", { + declarations: `${sessionDeclaration}\nenum mode { IDLE, BUSY = 5 }; typedef unsigned long count_t; union value { int i; float f; };`, + }); + assert.deepEqual( + defined.types.map(({ id, kind, status }) => [id, kind, status]), + [ + ["/rea_caller_defined/count_t", "typedef", "defined"], + ["/rea_caller_defined/mode", "enum", "defined"], + [sessionType, "struct", "defined"], + ["/rea_caller_defined/value", "union", "defined"], + ], + ); + assert.deepEqual(defined.effects, { + scope: "session-analysis-database", + source_bytes_modified: false, + }); + const layout = await first.call("inspect_native_data_type", { + type: sessionType, + }); + assert.equal(layout.source, "caller-defined"); + assert.equal(layout.size_bytes, 56); + assert.deepEqual( + layout.fields.map(({ name, offset_bytes }) => [name, offset_bytes]), + [ + ["id", 0], + ["name", 4], + ["flags", 36], + ["score", 40], + ["next", 48], + ], + ); + assert.equal( + (await first.call("inspect_native_data_type", { type: "/int" })) + .source, + "analysis-database", + ); + const repeated = await first.call("define_native_data_types", { + declarations: sessionDeclaration, + }); + assert.deepEqual( + repeated.types.map(({ status }) => status), + ["unchanged"], + ); + // Constructs the parser applies are proven by the stored layout. + const applied = await first.call("define_native_data_types", { + declarations: `/* comments are skipped */ +#pragma pack(push, 1) // wire layout +struct rea_packed { char a; int b; }; +#pragma /* restore */ pack(pop) +struct rea_natural { char a; int b; }; // after pop +struct rea_flexible { int n; char data[]; }; +struct rea_bits { unsigned low:3; unsigned high:5; }; +typedef struct rea_node { struct rea_node *next; const int v; } rea_node, *rea_node_ptr; +enum rea_flags { REA_NONE, REA_EIGHT = 8, REA_MASK = 0x35, REA_NEG = -2, REA_NEXT }; +typedef struct { volatile int k; } rea_unnamed_t;`, + }); + assert.deepEqual( + applied.types.map(({ name, kind, size_bytes }) => [ + name, + kind, + size_bytes, + ]), + [ + ["rea_bits", "struct", 4], + ["rea_flags", "enum", 4], + ["rea_flexible", "struct", 4], + ["rea_natural", "struct", 8], + ["rea_node", "struct", 16], + ["rea_node_ptr", "typedef", 8], + ["rea_packed", "struct", 5], + ["rea_unnamed_t", "struct", 4], + ], + ); + // Both qualifiers' lines and columns in the declarations text above. + assert.deepEqual(applied.dropped_qualifiers, [ + { qualifier: "const", line: 8, column: 50 }, + { qualifier: "volatile", line: 10, column: 18 }, + ]); + const inspect = (name) => + first.call("inspect_native_data_type", { + type: `/rea_caller_defined/${name}`, + }); + const packed = await inspect("rea_packed"); + assert.equal(packed.alignment_bytes, 1); + // Ghidra's generic pointer has no pointed-to type; the dependency and + // depth walks must skip that absent child rather than fail. + const generic = await first.call("define_native_data_types", { + declarations: "struct rea_generic { pointer p; int x; };", + }); + assert.deepEqual( + generic.types.map(({ name, size_bytes }) => [name, size_bytes]), + [["rea_generic", 16]], + ); + assert.deepEqual( + (await inspect("rea_generic")).fields.map(({ name, type_id }) => [ + name, + type_id, + ]), + [ + ["p", "/pointer"], + ["x", "/int"], + ], + ); + // Pure qualifiers are reported; a labelled pack push and pop applies. + const qualified = `struct rea_quals { int __w64 a; int __unaligned *b; int * __restrict c; }; +#pragma pack(push, rea, 1) +struct rea_labeled { char c; int i; }; +#pragma pack(pop, rea) +struct rea_after { char c; int i; };`; + const quals = await first.call("define_native_data_types", { + declarations: qualified, + }); + assert.deepEqual( + quals.types.map(({ name, size_bytes }) => [name, size_bytes]), + [ + ["rea_after", 8], + ["rea_labeled", 5], + ["rea_quals", 24], + ], + ); + assert.deepEqual( + quals.dropped_qualifiers, + ["__w64", "__unaligned", "__restrict"].map((spelling) => ({ + qualifier: spelling === "__restrict" ? "restrict" : spelling, + line: 1, + column: qualified.indexOf(spelling) + 1, + })), + ); + assert.deepEqual( + packed.fields.map(({ name, offset_bytes }) => [name, offset_bytes]), + [ + ["a", 0], + ["b", 1], + ], + ); + assert.deepEqual( + (await inspect("rea_natural")).fields.map( + ({ offset_bytes }) => offset_bytes, + ), + [0, 4], + ); + assert.deepEqual( + (await inspect("rea_flexible")).fields.map( + ({ name, offset_bytes, size_bytes, type_id }) => [ + name, + offset_bytes, + size_bytes, + type_id, + ], + ), + [ + ["n", 0, 4, "/int"], + ["data", 4, 0, "/char[0]"], + ], + ); + assert.deepEqual( + (await inspect("rea_bits")).fields.map( + ({ name, bit_size, bit_offset }) => [name, bit_size, bit_offset], + ), + [ + ["low", 3, 0], + ["high", 5, 3], + ], + ); + // Values implicit numbering cannot produce, each from one literal. + assert.deepEqual((await inspect("rea_flags")).members, [ + { name: "REA_EIGHT", value: "8" }, + { name: "REA_MASK", value: "53" }, + { name: "REA_NEG", value: "-2" }, + { name: "REA_NEXT", value: "-1" }, + { name: "REA_NONE", value: "0" }, + ]); + assert.equal( + (await inspect("rea_node_ptr")).referenced_type, + "/rea_caller_defined/rea_node *", + ); + // A // comment may end the text; Ghidra's lexer still needs a line break. + const noted = await first.call("define_native_data_types", { + declarations: "struct rea_noted { int x; }; // noted", + }); + assert.deepEqual( + noted.types.map(({ name, kind, size_bytes }) => [ + name, + kind, + size_bytes, + ]), + [["rea_noted", "struct", 4]], + ); + const maxPack = await first.call("define_native_data_types", { + declarations: + "#pragma pack(2147483647)\nstruct rea_pack_max { char c; int i; };", + }); + assert.deepEqual( + maxPack.types.map(({ name, size_bytes }) => [name, size_bytes]), + [["rea_pack_max", 8]], + ); + return { types: defined.types.length + applied.types.length }; + }, + ); + await phase( + "a conflicting or unsupported definition stores nothing", + async () => { + // A tag and a typedef share a Ghidra name only when they are one type. + // A sibling in the same text must stay unstored with them. + for (const declarations of [ + "struct rea_tag_alias { int x; }; typedef int rea_tag_alias; struct rea_tag_sibling { int y; };", + "enum rea_enum_alias { REA_A = 1 }; typedef int rea_enum_alias; struct rea_enum_sibling { int y; };", + ]) { + const error = requireMcpToolError( + await first.raw("define_native_data_types", { declarations }), + ); + assert.equal(error.code, "invalid_request"); + assert.equal(error.retryable, false); + assert.equal(error.recovery, undefined); + assert.deepEqual( + error.details?.issues?.map((issue) => ({ + path: issue.path, + reason: issue.reason, + })), + [{ path: ["declarations"], reason: "invalid_value" }], + ); + assert.equal( + error.details?.diagnostics?.remote_code, + "conflicting_type_definitions", + ); + assert.deepEqual(error.details?.related_operations, [ + "define_native_data_types", + ]); + } + for (const name of [ + "rea_tag_alias", + "rea_tag_sibling", + "rea_enum_alias", + "rea_enum_sibling", + ]) + assert.equal( + await typeStatus(first, `/rea_caller_defined/${name}`), + "unavailable", + ); + const conflict = await first.refused( + "define_native_data_types", + { + declarations: + "struct rea_sibling { int a; }; struct session { long other; };", + }, + "declarations", + ); + assert.match(conflict.message, /session/u); + assert.match(conflict.action, /does not replace/u); + assert.equal( + await typeStatus(first, "/rea_caller_defined/rea_sibling"), + "unavailable", + ); + // A different layout under an existing caller-defined name stores nothing. + const redefined = requireMcpToolError( + await first.raw("define_native_data_types", { + declarations: "struct session { long changed; };", + }), + ); + assert.equal(redefined.code, "invalid_request"); + assert.equal(redefined.retryable, false); + assert.equal( + redefined.details?.diagnostics?.remote_code, + "data_type_conflict", + ); + assert.deepEqual( + redefined.details?.issues?.map((issue) => ({ + path: issue.path, + reason: issue.reason, + })), + [{ path: ["declarations"], reason: "invalid_value" }], + ); + const kept = await first.call("inspect_native_data_type", { + type: sessionType, + }); + assert.equal(kept.size_bytes, 56); + assert.equal(kept.fields[0].name, "id"); + assert.equal(kept.fields[0].offset_bytes, 0); + // Integer.parseInt rejects this operand and Ghidra would keep the previous packing. + const overflow = requireMcpToolError( + await first.raw("define_native_data_types", { + declarations: + "#pragma pack(2147483648)\nstruct rea_pack_overflow { char c; int i; };", + }), + ); + assert.equal(overflow.code, "invalid_request"); + assert.equal(overflow.retryable, false); + assert.equal( + overflow.details?.diagnostics?.remote_code, + "invalid_type_declarations", + ); + assert.deepEqual( + overflow.details?.issues?.map((issue) => ({ + path: issue.path, + reason: issue.reason, + })), + [{ path: ["declarations"], reason: "invalid_value" }], + ); + assert.equal( + await typeStatus(first, "/rea_caller_defined/rea_pack_overflow"), + "unavailable", + ); + const builtin = await first.refused( + "define_native_data_types", + { declarations: "struct rea_other { int a; }; typedef long uint;" }, + "declarations", + ); + assert.match(builtin.message, /uint \(existing \/uint\)/u); + // Each is accepted by Ghidra's parser and dropped or stored differently. + // A definition admits no parentheses; Ghidra stores none of their forms as written. + const parenthesized = await first.refused( + "define_native_data_types", + { + declarations: `struct rea_kept { char ${"(".repeat(10)}x${")".repeat(10)}; };`, + }, + "declarations", + ); + assert.match( + parenthesized.message, + /a parenthesis .* at line 1, column 24/u, + ); + for (const [declarations, reason] of [ + [ + "struct rea_user { struct rea_missing *p; };", + /rea_missing without members/u, + ], + [ + "struct rea_callbacks { int (*fn)(int); };", + /a parenthesis \(a struct, union, enum or typedef definition admits none.*\) at line 1, column 28/u, + ], + [ + "struct rea_nested { struct { int a; } inner; };", + /unnamed or undeclared type/u, + ], + ["struct rea_broken { int a;", /C parser rejected declarations/u], + [ + "int rea_variable;", + /not a struct, union, enum or typedef definition \(int\) at line 1, column 1/u, + ], + [ + "struct rea_kept { int a; };\nint rea_tail = 5;", + /\(int\) at line 2, column 1/u, + ], + [ + "struct rea_kept { int a; } rea_instance;", + /variable or declarator \(rea_instance\) after the definition of rea_kept at line 1, column 28/u, + ], + [ + "struct rea_kept { int a; } *rea_pointer;", + /variable or declarator \(\*\) after the definition of rea_kept/u, + ], + [ + "static struct rea_kept { int a; } rea_static;", + /specifier static at line 1, column 1/u, + ], + ["extern struct rea_kept rea_extern;", /specifier extern/u], + ["struct rea_kept rea_plain;", /variable declaration \(rea_plain\)/u], + [ + "struct rea_kept { char a; int b; } __attribute__((packed));", + /__attribute__ \(use #pragma pack for packing\) at line 1, column 36/u, + ], + [ + "struct __attribute__((packed)) rea_kept { char a; int b; };", + /__attribute__/u, + ], + [ + "struct rea_kept { char a; int b __attribute__((aligned(16))); };", + /__attribute__/u, + ], + [ + "struct rea_kept { char a; _Alignas(16) int b; };", + /_Alignas .* at line 1, column 27/u, + ], + [ + "struct rea_kept { char a; __declspec(align(16)) int b; };", + /__declspec/u, + ], + ["struct rea_kept { char a; } __packed;", /__packed/u], + ["__extension__ struct rea_kept { int a; };", /__extension__/u], + [ + "#pragma once\nstruct rea_kept { int a; };", + /directive #pragma \(only #pragma pack is applied\) at line 1, column 1/u, + ], + ['#line 5 "x.h"\nstruct rea_kept { int a; };', /directive #line/u], + [ + "#pragma pack(1) /* a\r\nb */\nstruct rea_kept { int a; };", + /block comment that continues a directive onto another line at line 1, column 17/u, + ], + [ + "#pragma pack(push, (1))\nstruct rea_kept { int a; };", + /#pragma pack with operands Ghidra ignores or reads differently/u, + ], + ["enum { REA_A, REA_B };", /unnamed enum/u], + ["typedef enum { REA_A } rea_enum_t;", /unnamed enum/u], + // The audit of C.jj tokens Ghidra consumes without applying. + [ + "struct rea_kept { int * __ptr32 p; };", + /pointer-width qualifier __ptr32/u, + ], + [ + "struct rea_kept { int x; } packed;", + /attribute or extension packed/u, + ], + [ + "struct [[deprecated]] rea_kept { int a; };", + /\[\[\.\.\.\]\] attribute at line 1, column 8/u, + ], + [ + "@interface Foo\n@end\nstruct rea_kept { int a; };", + /Objective-C @ directive \(Ghidra skips its text\) at line 1, column 1/u, + ], + [ + "__pragma(pack(1)) struct rea_kept { char c; int i; };", + /pragma operator __pragma \(write #pragma pack instead\)/u, + ], + [ + "_Static_assert(1); struct rea_kept { int a; };", + /static assertion _Static_assert/u, + ], + [ + "struct __readableTo(x) rea_kept { int a; };", + /attribute or extension __readableTo/u, + ], + ["struct rea_kept { char c; \\\n int i; };", /backslash/u], + ...[ + "#pragma pack(0x1)", + "#pragma pack(010)", + "#pragma pack(show)", + "#pragma pack(pop, 1)", + ].map((pragma) => [ + `${pragma}\nstruct rea_kept { char c; int i; };`, + /#pragma pack with operands Ghidra ignores or reads differently \(.*\) at line 1, column 1/u, + ]), + [ + "# pragma pack(1)\nstruct rea_kept { char c; int i; };", + /# separated from its directive name/u, + ], + // Enum values, array sizes and bit-field widths are one plain literal. + [ + "enum rea_bad { FIRST = 1, MASK = FIRST << 4 };", + /the constant expression token FIRST .*write the computed value.* at line 1, column 34/u, + ], + ...[ + ["struct rea_kept { char a[sizeof(int)]; };", "sizeof"], + ["struct rea_kept { char a[(char)300]; };", "\\("], + ["enum rea_bad { A = 65536 * 65536 };", "\\*"], + ["enum rea_bad { A = 0b11 };", "0b11"], + ["enum rea_bad { A = 1.5 };", "\\."], + ["enum rea_bad { A = 1 ? 2 : 3 };", "\\?"], + ["enum rea_bad { A = ~0U >> 1 };", "~"], + ["enum rea_bad { A = 1 < 2 };", "<"], + ["enum rea_bad { A = 16u };", "16u"], + ["enum rea_bad { A = 07 };", "07"], + ["struct rea_kept { unsigned a : 1 << 4; };", "<"], + ].map(([declarations, token]) => [ + declarations, + new RegExp(`the constant expression token ${token} `, "u"), + ]), + [ + "enum rea_bad { A = 0x80000000 };", + /literal 0x80000000, outside int/u, + ], + [ + "enum rea_bad { A = 2147483647, B };", + /enumerator B, whose implicit value leaves int/u, + ], + // Ghidra ignores a bare push, so pop would restore nothing. + ...[ + "#pragma pack(push)\n#pragma pack(1)\nstruct rea_kept { char c; int i; };\n#pragma pack(pop)", + "#pragma pack(pop)\nstruct rea_kept { char c; int i; };", + ].map((declarations) => [ + declarations, + /#pragma pack with operands Ghidra ignores or reads differently \(.*\) at line 1, column 1/u, + ]), + [ + "#pragma pack(push, rea, 1)\n#pragma pack(pop)\nstruct rea_kept { char c; int i; };", + /#pragma pack with operands .* at line 2, column 1/u, + ], + // Ghidra invents an empty enum for an undefined tag. + [ + "struct rea_user2 { enum rea_missing_e m; };", + /enum rea_missing_e without members/u, + ], + ["enum rea_fwd;", /enum rea_fwd without members/u], + [ + "enum rea_mode { REA_BUSY = 1, REA_BUSY = 2 };", + /Ghidra's C parser reported declarations: duplicate enum value: rea_mode : REA_BUSY : 2/u, + ], + [ + "struct { int a; };", + /unnamed struct or union definition at line 1, column 8/u, + ], + [ + "struct rea_kept { char a['b']; };", + /string or character literal at line 1, column 26/u, + ], + [ + 'struct rea_kept { char a[sizeof("abc")]; };', + /constant expression token sizeof/u, + ], + [ + "struct rea_kept { int f; int f; };", + /rea_kept repeats member name f/u, + ], + ["struct rea_kept {};", /without members/u], + ]) { + const refusal = await first.refused( + "define_native_data_types", + { declarations }, + "declarations", + ); + assert.match(refusal.message, reason); + } + const longDeclarations = `struct rea_kept { int a; /* ${"x".repeat(4096)} */ };`; + await first.overLimit( + "define_native_data_types", + { declarations: longDeclarations }, + { + parameter: "declarations_max_utf16", + effective_value: 4096, + maximum: 8192, + default_value: 4096, + required_value: longDeclarations.length, + }, + ); + for (const name of [ + "rea_other", + "rea_user", + "rea_missing", + "rea_callbacks", + "rea_nested", + "rea_kept", + "rea_enum_t", + "rea_mode", + "rea_user2", + "rea_missing_e", + "rea_fwd", + "rea_bad", + ]) + assert.equal( + await typeStatus(first, `/rea_caller_defined/${name}`), + "unavailable", + ); + assert.equal( + (await first.call("inspect_native_data_type", { type: sessionType })) + .size_bytes, + 56, + ); + return {}; + }, + ); + await phase( + "an applied signature is read back and changes the cached decompilation", + async () => { + const updated = await first.call("annotate_native_function", { + procedure, + comment: "caller-authored prototype", + signature, + }); + assert.deepEqual(updated.annotations, { + address: updated.dossier.procedure.address, + name: baseline.name, + comment: "caller-authored prototype", + inline_comment: null, + // The prototype's own name, total, is not applied. + signature: `double ${baseline.name}(session * s, uint mask)`, + signature_source: "user_defined", + calling_convention: updated.annotations.calling_convention, + }); + // Ghidra has no const; the edit is applied and the qualifier reported. + assert.deepEqual(updated.dropped_qualifiers, [ + { qualifier: "const", line: 1, column: 14, parameter_index: 0 }, + ]); + // The function had no calling convention. The locked storage is the + // default convention's, and that convention is recorded with it. + const api = updated.dossier.native_api; + assert.equal(api.signature_source, "user_defined"); + assert.notEqual(updated.annotations.calling_convention, "unknown"); + assert.equal( + api.calling_convention, + updated.annotations.calling_convention, + ); + assert.deepEqual( + api.parameters.map(({ name, storage }) => [name, storage]), + process.arch === "arm64" + ? [ + ["s", "x0:8"], + ["mask", "w1:4"], + ] + : [ + ["s", "RDI:8"], + ["mask", "ESI:4"], + ], + ); + assert.equal( + api.return_type.storage, + process.arch === "arm64" ? "d0:8" : "XMM0_Qa:8", + ); + const after = await pseudocode(first); + for (const field of ["s->flags", "s->score", "s->next"]) + assert.ok(after.includes(field), `pseudocode must use ${field}`); + assert.doesNotMatch(after, /Unknown calling convention/u); + assert.match(updated.dossier.pseudocode, /s->flags/u); + // Readback is a valid signature edit and changes nothing. + const replayed = await first.call("annotate_native_function", { + procedure, + signature: updated.annotations.signature, + }); + assert.deepEqual(replayed.annotations, updated.annotations); + assert.equal(replayed.dropped_qualifiers, undefined); + // CR, CRLF and LF each end a line, and an unterminated prototype ending + // in a line comment is terminated after that comment. + const reflowed = await first.call("annotate_native_function", { + procedure, + signature: + "double total(\r const struct session *s,\r\n unsigned mask)\n// edited", + }); + assert.deepEqual(reflowed.annotations, updated.annotations); + assert.deepEqual(reflowed.dropped_qualifiers, [ + { qualifier: "const", line: 2, column: 3, parameter_index: 0 }, + ]); + // A terminated prototype may end in a // comment with no newline after it. + const commented = await first.call("annotate_native_function", { + procedure, + signature: `${updated.annotations.signature}; // noted`, + }); + assert.deepEqual(commented.annotations, updated.annotations); + assert.equal(commented.dropped_qualifiers, undefined); + return {}; + }, + ); + await first.call("close_binary"); + } finally { + await first.close(); + } + + await phase( + "checkpoint mode restores the types and prototype in a new process", + async () => { + const second = await connect(); + try { + await second.call("open_binary", { + path: target, + provider_id: "ghidra", + }); + const restored = await pseudocode(second); + assert.doesNotMatch(restored, /Unknown calling convention/u); + for (const field of ["s->flags", "s->score", "s->next"]) + assert.ok( + restored.includes(field), + `restored pseudocode must use ${field}`, + ); + const layout = await second.call("inspect_native_data_type", { + type: sessionType, + }); + assert.equal(layout.status, "available"); + assert.equal(layout.source, "caller-defined"); + const repeated = await second.call("define_native_data_types", { + declarations: sessionDeclaration, + }); + assert.deepEqual( + repeated.types.map(({ status }) => status), + ["unchanged"], + ); + await second.call("close_binary"); + return {}; + } finally { + await second.close(); + } + }, + ); + await phase( + "per-call bounds reach the bridge and bound the parsed text", + async () => { + const bounded = await connect(); + try { + await bounded.call("open_binary", { + path: target, + provider_id: "ghidra", + }); + const over = `double total(struct session *s, unsigned mask /* ${"x".repeat(20)} */)`; + await bounded.overLimit( + "annotate_native_function", + { procedure, signature: over, signature_max_utf16: 64 }, + { + parameter: "signature_max_utf16", + effective_value: 64, + maximum: 4096, + default_value: 2048, + required_value: over.length, + }, + ); + const declarations = + "struct rea_bounded { int first; int second; int third; };"; + await bounded.overLimit( + "define_native_data_types", + { declarations, declarations_max_utf16: 48 }, + { + parameter: "declarations_max_utf16", + effective_value: 48, + maximum: 8192, + default_value: 4096, + required_value: declarations.length, + }, + ); + assert.equal( + await typeStatus(bounded, "/rea_caller_defined/rea_bounded"), + "unavailable", + ); + // A prototype of exactly the admitted length, without the semicolon + // the parser needs, is applied. + const exact = "double total(struct session *s, unsigned mask)".replace( + ")", + `${" ".repeat(64 - 46)})`, + ); + assert.equal(exact.length, 64); + const fitted = await bounded.call("annotate_native_function", { + procedure, + signature: exact, + signature_max_utf16: 64, + }); + assert.equal(fitted.annotations.signature_source, "user_defined"); + assert.equal(fitted.dropped_qualifiers, undefined); + // Text within the lowered bound is still applied. + const within = await bounded.call("define_native_data_types", { + declarations: "struct rea_small { int a[2]; };", + declarations_max_utf16: 48, + }); + assert.deepEqual( + within.types.map(({ name, size_bytes }) => [name, size_bytes]), + [["rea_small", 8]], + ); + await bounded.call("close_binary"); + return {}; + } finally { + await bounded.close(); + } + }, + ); + await phase( + "caller floods within the length bounds are refused and the session survives", + async () => { + const flood = await connect(); + try { + await flood.call("open_binary", { + path: target, + provider_id: "ghidra", + }); + const kept = await flood.call("define_native_data_types", { + declarations: "struct rea_survivor { int a; };", + }); + assert.equal(kept.types[0].status, "defined"); + const max = 8192; + const floods = [ + [ + "define_native_data_types", + { declarations: "[".repeat(max), declarations_max_utf16: max }, + ], + [ + "define_native_data_types", + { + declarations: `struct rea_flood { char ${"(".repeat(max - 30)}`, + declarations_max_utf16: max, + }, + ], + [ + "define_native_data_types", + { + declarations: `struct rea_flood { int a${"[1]".repeat((max - 40) / 3)}; };`, + declarations_max_utf16: max, + }, + ], + [ + "define_native_data_types", + { + declarations: `struct rea_flood { int ${"*".repeat(max - 40)} p; };`, + declarations_max_utf16: max, + }, + ], + [ + "define_native_data_types", + { + // Each typedef adds a pointer level and a typedef level. + declarations: Array.from( + { length: 300 }, + (_, index) => + `typedef ${index === 0 ? "int" : `t${String(index - 1)}`} *t${String(index)};`, + ).join(""), + declarations_max_utf16: max, + }, + ], + [ + "annotate_native_function", + { + procedure, + signature: "[".repeat(4096), + signature_max_utf16: 4096, + }, + ], + [ + "annotate_native_function", + { + procedure, + signature: `int total(int ${"*".repeat(4000)} p)`, + signature_max_utf16: 4096, + }, + ], + [ + "annotate_native_function", + { + procedure, + signature: `int total(${"(".repeat(4000)}`, + signature_max_utf16: 4096, + }, + ], + ]; + const outcomes = []; + const errors = []; + for (const [name, args] of floods) { + // Each is refused with a typed result, never a lost connection. + const error = requireMcpToolError(await flood.raw(name, args)); + outcomes.push(error.code); + errors.push(error); + } + // The whole chain is measured: the struct, max - 40 pointers, then int. + assert.match( + errors[3].message, + new RegExp( + `defines rea_flood, chained ${String(max - 40 + 2)} levels deep .*, above the 256-level limit`, + "u", + ), + ); + assert.equal(errors[3].details.refusal.kind, "fixed_ceiling"); + assert.match( + errors[3].remediation.action, + /only fewer nested pointer, array, typedef or member levels does/u, + ); + // Pointer, array and typedef chains are refused before Ghidra walks them. + assert.deepEqual(outcomes, [ + "invalid_request", + "invalid_request", + "resource_constraint", + "resource_constraint", + "resource_constraint", + "invalid_request", + "resource_constraint", + "resource_constraint", + ]); + assert.equal( + ( + await flood.call("inspect_native_data_type", { + type: "/rea_caller_defined/rea_survivor", + }) + ).status, + "available", + ); + // A held database lock would fail this close's checkpoint save. + await flood.call("close_binary"); + return { flood_outcomes: outcomes }; + } finally { + await flood.close(); + } + }, + ); + await phase( + "a refused definition leaves an existing empty composite unchanged", + async () => { + const opaque = await connect(); + try { + await opaque.call("open_binary", { + path: opaqueTarget, + provider_id: "ghidra", + }); + const placeholder = "/DWARF/_UNCATEGORIZED_/rea_opaque"; + const fields = async () => { + const type = await opaque.call("inspect_native_data_type", { + type: placeholder, + }); + assert.equal(type.status, "available"); + return type.fields.length; + }; + assert.equal(await fields(), 0); + // Ghidra's parser fills this empty composite in place. The call refuses + // that replacement, and the placeholder stays empty. + const conflict = requireMcpToolError( + await opaque.raw("define_native_data_types", { + declarations: "struct rea_opaque { int x; };", + }), + ); + assert.equal(conflict.code, "invalid_request"); + assert.equal(conflict.retryable, false); + assert.equal( + conflict.details?.diagnostics?.remote_code, + "data_type_conflict", + ); + assert.deepEqual( + conflict.details?.issues?.map((issue) => ({ + path: issue.path, + reason: issue.reason, + })), + [{ path: ["declarations"], reason: "invalid_value" }], + ); + assert.equal(await fields(), 0); + // A parser diagnostic is refused, and the edit's rollback covers parsing. + const diagnostic = await opaque.refused( + "define_native_data_types", + { + declarations: + "struct rea_opaque { int x; }; enum rea_mode { REA_BUSY = 1, REA_BUSY = 2 };", + }, + "declarations", + ); + assert.match( + diagnostic.message, + /duplicate enum value: rea_mode : REA_BUSY : 2/u, + ); + assert.equal(await fields(), 0); + await opaque.call("close_binary"); + return {}; + } finally { + await opaque.close(); + } + }, + ); + assert.equal(await sha256File(target), targetDigest); + assert.deepEqual(await readdir(runtime), []); + report.status = "verified"; +} catch (cause) { + report.status = "failed"; + report.error = cause instanceof Error ? cause.stack : String(cause); + process.exitCode = 1; +} finally { + let cleanupVerified = false; + try { + await workspace.closeEarly([() => commands.close()]); + report.run = await completeVerifierRun(run); + assertVerifierCleanupComplete(report.run.process_lineage); + cleanupVerified = true; + } catch (cause) { + report.cleanup_error = String(cause); + report.retained_workspace = root; + process.exitCode = 1; + } + if (cleanupVerified && report.status === "verified") { + try { + await workspace.release(); + } catch (cause) { + report.cleanup_error = String(cause); + report.retained_workspace = root; + process.exitCode = 1; + } + } else if (report.retained_workspace === undefined) { + report.retained_workspace = root; + } + process.stdout.write(JSON.stringify(report, null, 2) + "\n"); +} diff --git a/scripts/verify/advertised-schemas/tools/annotate_native_function.json b/scripts/verify/advertised-schemas/tools/annotate_native_function.json index 59507620ec..f74de3bbc0 100644 --- a/scripts/verify/advertised-schemas/tools/annotate_native_function.json +++ b/scripts/verify/advertised-schemas/tools/annotate_native_function.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "70c17ea61092a8c3", + "input compact": "35e71f4fbd7e748e", "output compact": "fc6c5d5a78a47254" }, "patterns": {} diff --git a/scripts/verify/advertised-schemas/tools/define_native_data_types.json b/scripts/verify/advertised-schemas/tools/define_native_data_types.json new file mode 100644 index 0000000000..5912970af0 --- /dev/null +++ b/scripts/verify/advertised-schemas/tools/define_native_data_types.json @@ -0,0 +1,7 @@ +{ + "schemas": { + "input compact": "5cbbfe8ba3778c39", + "output compact": "fc6c5d5a78a47254" + }, + "patterns": {} +} diff --git a/scripts/verify/fixed-ceiling-registry.json b/scripts/verify/fixed-ceiling-registry.json index c1da44f036..de810419cf 100644 --- a/scripts/verify/fixed-ceiling-registry.json +++ b/scripts/verify/fixed-ceiling-registry.json @@ -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", diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts index 610244c7f1..bcbc2bb825 100644 --- a/src/cli/coreNativeCommands.ts +++ b/src/cli/coreNativeCommands.ts @@ -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, diff --git a/src/contracts/officialToolContracts.ts b/src/contracts/officialToolContracts.ts index 94272d028d..4fe7d75c9f 100644 --- a/src/contracts/officialToolContracts.ts +++ b/src/contracts/officialToolContracts.ts @@ -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 = 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( diff --git a/src/contracts/toolContractExamples.ts b/src/contracts/toolContractExamples.ts index a50af46de2..d98f5c3802 100644 --- a/src/contracts/toolContractExamples.ts +++ b/src/contracts/toolContractExamples.ts @@ -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" }, diff --git a/src/contracts/toolOutputSchemaGroups.ts b/src/contracts/toolOutputSchemaGroups.ts index 1f383c62fa..0315018d68 100644 --- a/src/contracts/toolOutputSchemaGroups.ts +++ b/src/contracts/toolOutputSchemaGroups.ts @@ -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), diff --git a/src/domain/analysisResourceLimits.ts b/src/domain/analysisResourceLimits.ts index 09cdf19538..af9c5d64b5 100644 --- a/src/domain/analysisResourceLimits.ts +++ b/src/domain/analysisResourceLimits.ts @@ -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; diff --git a/src/domain/analysisSettingDefinitions.ts b/src/domain/analysisSettingDefinitions.ts index 809cdb903b..794b061359 100644 --- a/src/domain/analysisSettingDefinitions.ts +++ b/src/domain/analysisSettingDefinitions.ts @@ -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", diff --git a/src/domain/native/nativeDataType.ts b/src/domain/native/nativeDataType.ts index 2380ae0db1..4260a5b90e 100644 --- a/src/domain/native/nativeDataType.ts +++ b/src/domain/native/nativeDataType.ts @@ -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(), diff --git a/src/domain/native/nativeFunctionAnnotations.ts b/src/domain/native/nativeFunctionAnnotations.ts index 3d49d1054d..d53a054205 100644 --- a/src/domain/native/nativeFunctionAnnotations.ts +++ b/src/domain/native/nativeFunctionAnnotations.ts @@ -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), diff --git a/src/ghidra/GhidraFunctionOperations.ts b/src/ghidra/GhidraFunctionOperations.ts index 9cd1d9ca96..276ee67ce8 100644 --- a/src/ghidra/GhidraFunctionOperations.ts +++ b/src/ghidra/GhidraFunctionOperations.ts @@ -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", diff --git a/src/ghidra/GhidraFunctionValues.ts b/src/ghidra/GhidraFunctionValues.ts index e4ec536f88..f2f9ae10d3 100644 --- a/src/ghidra/GhidraFunctionValues.ts +++ b/src/ghidra/GhidraFunctionValues.ts @@ -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, diff --git a/src/ghidra/GhidraProvider.behavior.test.ts b/src/ghidra/GhidraProvider.behavior.test.ts index 3be33d5b89..5e1deb129e 100644 --- a/src/ghidra/GhidraProvider.behavior.test.ts +++ b/src/ghidra/GhidraProvider.behavior.test.ts @@ -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, diff --git a/src/ghidra/GhidraProviderCapabilities.ts b/src/ghidra/GhidraProviderCapabilities.ts index dbfad13482..c2142c7475 100644 --- a/src/ghidra/GhidraProviderCapabilities.ts +++ b/src/ghidra/GhidraProviderCapabilities.ts @@ -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 [ diff --git a/src/ghidra/GhidraReleasePolicy.ts b/src/ghidra/GhidraReleasePolicy.ts index 1b4e1af3af..c59f10bdf3 100644 --- a/src/ghidra/GhidraReleasePolicy.ts +++ b/src/ghidra/GhidraReleasePolicy.ts @@ -145,6 +145,7 @@ const FLOW_INDEPENDENT_OPERATIONS: ReadonlySet = 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. */ diff --git a/src/ghidra/GhidraSessionError.ts b/src/ghidra/GhidraSessionError.ts index b19010c37e..4a375e5bc8 100644 --- a/src/ghidra/GhidraSessionError.ts +++ b/src/ghidra/GhidraSessionError.ts @@ -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" diff --git a/src/ghidra/GhidraSessionErrorProjection.ts b/src/ghidra/GhidraSessionErrorProjection.ts index b51587c8ec..b9f0677286 100644 --- a/src/ghidra/GhidraSessionErrorProjection.ts +++ b/src/ghidra/GhidraSessionErrorProjection.ts @@ -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 + >; + /** 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 +> = { + 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 & { + 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> | 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."; diff --git a/src/ghidra/GhidraSessionValues.test.ts b/src/ghidra/GhidraSessionValues.test.ts index 4c7650d95c..f594d6d558 100644 --- a/src/ghidra/GhidraSessionValues.test.ts +++ b/src/ghidra/GhidraSessionValues.test.ts @@ -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; diff --git a/src/ghidra/GhidraSessionValues.ts b/src/ghidra/GhidraSessionValues.ts index 6dcaedfd8e..78113f74d3 100644 --- a/src/ghidra/GhidraSessionValues.ts +++ b/src/ghidra/GhidraSessionValues.ts @@ -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 = new Set([ "annotate_native_function", + "define_native_data_types", ...GHIDRA_NAMING_OPERATIONS, ]); diff --git a/src/ghidra/GhidraSnapshotCache.test.ts b/src/ghidra/GhidraSnapshotCache.test.ts index 7736694a65..b4b875ead4 100644 --- a/src/ghidra/GhidraSnapshotCache.test.ts +++ b/src/ghidra/GhidraSnapshotCache.test.ts @@ -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); diff --git a/src/ghidra/protocol.test.ts b/src/ghidra/protocol.test.ts index cf4b9e2d2c..6c62357a27 100644 --- a/src/ghidra/protocol.test.ts +++ b/src/ghidra/protocol.test.ts @@ -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); +}); diff --git a/src/ghidra/protocol.ts b/src/ghidra/protocol.ts index 45fdef2a94..73a77020c9 100644 --- a/src/ghidra/protocol.ts +++ b/src/ghidra/protocol.ts @@ -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["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 = ( diff --git a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts index 2748d9dbce..5818ee14da 100644 --- a/tests/boundary/mcp/ghidraEvidenceMcp.test.ts +++ b/tests/boundary/mcp/ghidraEvidenceMcp.test.ts @@ -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", diff --git a/tests/boundary/mcp/ghidraTypeEditsMcp.test.ts b/tests/boundary/mcp/ghidraTypeEditsMcp.test.ts new file mode 100644 index 0000000000..f6ea24f03f --- /dev/null +++ b/tests/boundary/mcp/ghidraTypeEditsMcp.test.ts @@ -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>[] = []; + 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>[] = []; + 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; + }; + 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>[] = []; + 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) => + 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(); + } +}); diff --git a/tests/boundary/mcp/officialArguments.test.ts b/tests/boundary/mcp/officialArguments.test.ts index c45646fc36..7d3148912a 100644 --- a/tests/boundary/mcp/officialArguments.test.ts +++ b/tests/boundary/mcp/officialArguments.test.ts @@ -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>[] = []; const client = await connect({ diff --git a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts index 024c809f29..febc5cd842 100644 --- a/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts +++ b/tests/boundary/providers/ghidra/ghidraCheckpointLifecycle.test.ts @@ -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); + }, +); diff --git a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts index 6a92c30c64..b231a9efa3 100644 --- a/tests/boundary/providers/ghidra/ghidraClient.fixture.ts +++ b/tests/boundary/providers/ghidra/ghidraClient.fixture.ts @@ -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" diff --git a/tests/fixtures/fakeGhidra.mjs b/tests/fixtures/fakeGhidra.mjs index 2eeaff7b36..9ed380f8c0 100644 --- a/tests/fixtures/fakeGhidra.mjs +++ b/tests/fixtures/fakeGhidra.mjs @@ -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; diff --git a/tests/fixtures/fakeGhidraReplies.mjs b/tests/fixtures/fakeGhidraReplies.mjs index 0a7124d5ac..880fd60208 100644 --- a/tests/fixtures/fakeGhidraReplies.mjs +++ b/tests/fixtures/fakeGhidraReplies.mjs @@ -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",