mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 19:41:20 -05:00
3a8a717b02
* feat(ghidra): set function signatures and define the types they use annotate_native_function accepts an optional C prototype, applied with USER_DEFINED source in the same transaction as the name and comments, verified by readback and rolled back with them on refusal. define_native_data_types stores caller-authored struct, union, enum and typedef definitions atomically under /rea_caller_defined and refuses existing names. inspect_native_data_type reports those types with source caller-defined, and annotation readback reports the applied prototype and its source. Refs #14831 * feat(ghidra): bound caller C text with launch controls and refuse unapplied constructs The lengths of a signature and of type declarations and the nesting depth of parentheses are launch-only REA_ controls with measured defaults, floors and maxima, written into the bridge's session descriptor. A refusal names the control, its effective value, source and range. The bridge tokenizes caller C before Ghidra's parser sees it and refuses what that parser accepts without applying: attributes, storage-class specifiers, variable declarations, directives other than #pragma pack, literals, function bodies, default arguments, unnamed enums and repeated member names. A type name that names different types is refused. When a function has no calling convention and the prototype names none, the compiler specification's default convention, which Ghidra already uses to assign the locked storage, is recorded, and annotation readback reports the convention. Refs #14831 * fix(ghidra): apply the signature bound to the caller's text The bridge appended the semicolon its parser needs before checking the length, so a prototype of exactly the admitted length was refused. The readback prototype is documented as reusable only when its function and type names are C identifiers. Refs #14831 * chore(mcp): refresh advertised schema summaries for Ghidra type edits Refs #14831 * fix(ghidra): bound caller C text per call and report dropped qualifiers Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. The three launch-only environment controls left an agent that hit them with a restart as its only recovery. The two length bounds are now per-call parameters, signature_max_utf16 on annotate_native_function and declarations_max_utf16 on define_native_data_types, with the same defaults and measured maxima. A refusal reports details.limit with control_kind "parameter" and required_value, the text's length, so the generated recovery names the value to pass or asks for shorter text. The text fields no longer carry a schema maximum, so every over-length refusal is typed. Parenthesis nesting is a fixed ceiling of 8 levels, registered as a representation bound, because each level doubles parse time. The session descriptor no longer carries C parser limits, and the config module, environment entries and restart-only registry rows are removed. const and volatile are still applied without effect, because Ghidra's types have no representation for them. Both edits now return dropped_qualifiers with each qualifier's line and column, and for a signature its parameter index, null for the return type, instead of dropping them silently. * fix(ghidra): read caller C through one tokenizer and bound nesting per call The C admission scan tracked lines only at LF and read directives as raw lines matched by a regular expression, so a CR-only line break shifted dropped-qualifier positions and a trailing comment on #pragma pack was refused. One tokenizer now owns caller C positions, comments and literals: CR, LF and CRLF each end a line as in Ghidra's parser, and directives are admitted from its tokens, so comments read as whitespace there too. A block comment that would carry a directive onto another line is refused. Parenthesis nesting was a fixed ceiling justified by parse time, a resource limit. It is now the per-call parenthesis_max_depth (default 8, range 1..12) on both type-edit tools. The bridge measures the deepest nesting over the whole text and sends it, with a text's length, as the wire failure's required_value, so details.limit reports the bridge's own measurement instead of the adapter re-reading the request. The tokenizer also decides whether a prototype is terminated, so the parser sees the caller's text unchanged: no leading whitespace is stripped, and a trailing line comment no longer swallows the appended terminator. * fix(ghidra): parse caller C inside the edit's rollback and refuse parser diagnostics Ghidra's C parser writes the type database even with storeDataType false: a definition whose name matches an existing empty composite fills that type in place, in the parser's own nested transaction. Both type edits parsed before opening their transaction, so a refused definition, such as one conflicting with a DWARF placeholder, left that placeholder filled. Parsing, validation and storage now share the edit's one transaction, and parseCallerC refuses to run outside one. The parser also records diagnostics it cannot apply, such as a repeated enumerator it drops, and still reports success. Both edits now refuse any diagnostic with Ghidra's message, before anything is stored. The real-Ghidra verifier gains a phase with an ELF object whose DWARF declares an opaque struct, proving a refused definition leaves that empty composite unchanged, and refuses a repeated enumerator. * fix(ghidra): admit caller C from one audited table of tokens Ghidra drops Review kept finding one more construct Ghidra's C parser consumes without applying, because admission listed spellings piecemeal. The tokenizer now owns one table, audited against every token and production of Ghidra 12.2's C.jj and checked on Ghidra 12.2, in that grammar's own spellings: - Refused, because meaning is lost: __ptr32 and __ptr64 (stored as a native-width pointer), __near and __far, every attribute, declspec, __readableTo, alignas, packed and asm spelling, [[...]] attributes, storage and inline specifiers including __forceinline, __pragma and _Pragma, _Static_assert, Objective-C @ blocks (Ghidra skips their whole text), and backslashes. - Reported in dropped_qualifiers as pure qualifiers: every const and volatile spelling, restrict, __unaligned and __w64. #pragma pack is admitted only in the operand forms Ghidra applies as written with a decimal value; (0x1), (010), (show) and (pop, n) were ignored or read differently, and "# pragma" is a line marker Ghidra skips. An enum tag that neither the text nor the database defines made Ghidra invent an empty enum without a diagnostic; declarations now refuse it as they do an invented struct or union. Identifiers admit $, as C.jj's do, and the tokenizer reads numbers and [[ as single tokens. * fix(ghidra): bound caller type depth, admit only constant expressions Ghidra evaluates, refuse unmatched pack pops Recursion: the tokenizer's [[ lookahead re-entered next() for each "[", and the dependency walk recursed per pointer, array and member level. Both are iterative now. Ghidra 12.2's own data-type code recurses too: 1024 pointer or array levels resolve, 2048 exhaust the stack inside addDataType while its database lock is held, leaving the Program unable to save. Every parsed type's chain through pointers, arrays, typedefs and members, including existing database types, is now measured iteratively and refused beyond a fixed 256-level ceiling before Ghidra walks it. An unexpected StackOverflowError ends the session with a reason instead of being caught by the parser call, since Ghidra's lock may then be held. Constant expressions: Ghidra leaves names, casts, sizeof, floating and binary literals unevaluated and substitutes a default, so "MASK = FIRST << 4" was stored as 2, and it truncates values outside int. Enum values, array sizes and bit-field widths are admitted only as integer literals with arithmetic, shift, comparison, bitwise and logical operators, checked iteratively with C's rules to stay in int, including implicit enumerator values; anything else is refused at its position. Pragma pack: Ghidra ignores a bare (push), a pop with nothing pushed keeps the current packing, and a plain pop pops past labelled entries. The tokenizer tracks admitted pushes and admits a pop only when Ghidra's result matches C's. * fix(ghidra): admit constant expressions only as one literal, skip absent pointer targets, state the type-depth recovery truthfully Constant expressions: emulating C against Ghidra's own evaluator is an open-ended class of mismatches (comparisons, unsigned arithmetic such as ~0U >> 1 giving -1, names, casts, truncation). The evaluator is removed. Enum values, array sizes and bit-field widths are admitted only as one decimal or hex integer literal within int, optionally negated, without suffixes; anything else is refused at the first token that leaves that form, and the refusal says to write the computed value. Implicit enumerator values are still checked against int. Dependency walk: Ghidra's generic pointer has a null pointed-to type, and pushing it onto the ArrayDeque threw. Both the dependency and depth walks now take children from one cTypeChildren and skip an absent child. Type depth: the depth is measured over the whole chain before comparing it with the limit, so the refusal reports the depth it used, and it names the type from the parser's table rather than walking the type for a name. The recovery no longer suggests splitting into named types, which cannot help because depth counts through typedefs and existing types; it says only fewer nested levels do. * refactor(ghidra): refuse parentheses in definitions and keep parenthesis_max_depth on signatures only Under the literal-only rule for constant expressions, every parenthesis in a define_native_data_types text already ended in a refusal (function declarators, attributes, casts, sizeof, or a Ghidra diagnostic for a grouped declarator), so parenthesis_max_depth changed only which refusal a caller saw. A definition now refuses its first parenthesis at its position, and the parameter is removed from that tool's schema; it stays on annotate_native_function, whose prototype has a parameter list. * fix(ghidra): refuse distinct types that share one parser name Ghidra keeps struct tags, enum tags and typedefs in separate maps. Combining those maps dropped a typedef such as typedef int item when struct item was also defined, and the call still succeeded. Overlapping names are stored only when the definitions are equivalent, which keeps typedef struct s { ... } s as one struct. Any other overlap is refused with conflicting_type_definitions before the transaction stores anything. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(ghidra): roll back a composite the parser fills in place Ghidra's parser replaces an empty composite during parsing and returns that same object. A later same-path check would store the fill as unchanged. Record those empty composites before parsing and refuse if parsing fills one, so the open transaction restores them. A different layout of a non-empty caller type still conflicts and leaves the stored type in place. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(ghidra): close line comments at EOF and refuse overflowing pack values Ghidra's // skip token requires a line break, so a comment at the end of declarations or of an already-terminated signature was rejected. A newline is appended whenever the text ends in a line comment, before any semicolon added for an unterminated prototype. Integer.parseInt drops a pack operand outside a Java int and leaves the previous packing, so #pragma pack(2147483648) stored a natural layout. Decimal pack operands are admitted only when that parse succeeds. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(ghidra): assert the empty-composite refusal by code and readback Defining a struct over the DWARF placeholder fills that empty composite during parsing, so the refusal is data_type_conflict before the old name-conflict message. The verifier checks that code and that the placeholder still has no fields. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com>
635 lines
21 KiB
TypeScript
635 lines
21 KiB
TypeScript
import type { ConfigurationError } from "../domain/configurationErrors.js";
|
|
import { analysisErrorWithCleanupDependencies } from "../domain/analysisErrorCleanup.js";
|
|
import {
|
|
AnalysisError,
|
|
type AnalysisPartialObservation,
|
|
} from "../domain/analysisErrorBase.js";
|
|
import type { JsonValue } from "../domain/jsonValue.js";
|
|
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
|
|
import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js";
|
|
import type { GhidraDiagnosticsScope } from "./GhidraDiagnostics.js";
|
|
import { isGhidraByteSearchCursorMismatch } from "./GhidraByteSearchCursorFailure.js";
|
|
import { ghidraFileOffsetOutcome } from "./GhidraFileOffsetFailure.js";
|
|
import { GhidraAdmissionError } from "./GhidraAdmissionError.js";
|
|
import { GhidraLaunchSupportError } from "./GhidraJavaLaunch.js";
|
|
import {
|
|
GhidraLaunchError,
|
|
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
|
|
} from "./GhidraLauncher.js";
|
|
|
|
const MAX_CAUSE_DEPTH = 3;
|
|
const MAX_CAUSE_MESSAGE_BYTES = 2 * 1024;
|
|
const MAX_CAUSE_FIELD_BYTES = 1024;
|
|
const MAX_COMPILER_STDERR_BYTES = 8 * 1024;
|
|
const MAX_COMMAND_OUTPUT_BYTES = 8 * 1024;
|
|
|
|
/** Stable failure phase for one private Ghidra headless session. */
|
|
export type GhidraSessionFailureKind =
|
|
| "admission"
|
|
| "cancelled"
|
|
| "timeout"
|
|
| "start"
|
|
| "process"
|
|
| "protocol"
|
|
| "checkpoint"
|
|
| "remote"
|
|
| "analysis_timeout";
|
|
|
|
/** Message of the failure raised when the provider startup deadline elapses. */
|
|
export const GHIDRA_STARTUP_DEADLINE_ELAPSED =
|
|
"Ghidra startup deadline elapsed";
|
|
|
|
/**
|
|
* Whether the bridge reports that it stopped the request because its monitor
|
|
* was cancelled: `decompile_cancelled` from the native decompiler, or
|
|
* `request_cancelled` from a cancellation check elsewhere in the handler.
|
|
*/
|
|
export const isGhidraRemoteCancellation = (
|
|
failure: GhidraSessionError,
|
|
): boolean =>
|
|
failure.kind === "remote" &&
|
|
(failure.remoteCode === "decompile_cancelled" ||
|
|
failure.remoteCode === "request_cancelled");
|
|
|
|
/** Additional structured context for a Ghidra session failure. */
|
|
export interface GhidraSessionErrorOptions extends ErrorOptions {
|
|
readonly cancellation?: { readonly reason: unknown };
|
|
readonly configurationFailure?: ConfigurationError;
|
|
readonly partialObservation?: AnalysisPartialObservation;
|
|
readonly timeoutMs?: number;
|
|
readonly remoteCode?: string;
|
|
readonly cleanupFailure?: AnalysisError;
|
|
/** Caller cancellation that closed the session while this failure settled. */
|
|
readonly concurrentCancellation?: { readonly reason: unknown };
|
|
}
|
|
|
|
/** Provider-owned failure with bounded, token-redacted local diagnostics. */
|
|
export class GhidraSessionError extends Error {
|
|
readonly diagnostics: Readonly<Record<string, JsonValue>>;
|
|
readonly timeoutMs: number | undefined;
|
|
readonly remoteCode: string | undefined;
|
|
readonly cleanupFailure: AnalysisError | undefined;
|
|
readonly cancellation: { readonly reason: unknown } | undefined;
|
|
readonly configurationFailure: ConfigurationError | undefined;
|
|
readonly partialObservation: AnalysisPartialObservation | undefined;
|
|
readonly concurrentCancellation: { readonly reason: unknown } | undefined;
|
|
|
|
constructor(
|
|
readonly kind: GhidraSessionFailureKind,
|
|
message: string,
|
|
diagnostics: Readonly<Record<string, JsonValue>> = {},
|
|
options: GhidraSessionErrorOptions = {},
|
|
) {
|
|
super(message, options);
|
|
this.name = "GhidraSessionError";
|
|
this.diagnostics = structuredClone(diagnostics);
|
|
this.timeoutMs = options.timeoutMs;
|
|
this.remoteCode = options.remoteCode;
|
|
this.cleanupFailure = options.cleanupFailure;
|
|
this.cancellation = options.cancellation;
|
|
this.configurationFailure = options.configurationFailure;
|
|
this.partialObservation = options.partialObservation;
|
|
this.concurrentCancellation = options.concurrentCancellation;
|
|
}
|
|
|
|
/** Refresh diagnostics without discarding owned failure or cleanup facts. */
|
|
withDiagnostics(
|
|
diagnostics: Readonly<Record<string, JsonValue>>,
|
|
message = this.message,
|
|
): GhidraSessionError {
|
|
return this.#copy(diagnostics, this.cleanupFailure, message);
|
|
}
|
|
|
|
/** Join cleanup uncertainty, following both exact owners through later retry. */
|
|
withCleanupFailure(
|
|
cleanup: AnalysisError,
|
|
diagnostics = this.diagnostics,
|
|
): GhidraSessionError {
|
|
const combined =
|
|
this.cleanupFailure === undefined || this.cleanupFailure === cleanup
|
|
? cleanup
|
|
: analysisErrorWithCleanupDependencies(this.cleanupFailure, cleanup);
|
|
return this.#copy(diagnostics, combined);
|
|
}
|
|
|
|
/** Retain caller-safe completed facts without serializing snapshot byte buffers. */
|
|
withPartialObservation(
|
|
observation: AnalysisPartialObservation,
|
|
): GhidraSessionError {
|
|
return this.#copy(
|
|
this.diagnostics,
|
|
this.cleanupFailure,
|
|
this.message,
|
|
observation,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Keep this failure primary while recording that caller cancellation closed
|
|
* the session before it settled, so projections do not promise reuse.
|
|
*/
|
|
withConcurrentCancellation(cancellation: {
|
|
readonly reason: unknown;
|
|
}): GhidraSessionError {
|
|
return this.#copy(
|
|
{ ...this.diagnostics, session_closed_by_cancellation: true },
|
|
this.cleanupFailure,
|
|
this.message,
|
|
this.partialObservation,
|
|
cancellation,
|
|
);
|
|
}
|
|
|
|
#copy(
|
|
diagnostics: Readonly<Record<string, JsonValue>>,
|
|
cleanupFailure: AnalysisError | undefined,
|
|
message = this.message,
|
|
partialObservation = this.partialObservation,
|
|
concurrentCancellation = this.concurrentCancellation,
|
|
): GhidraSessionError {
|
|
return new GhidraSessionError(this.kind, message, diagnostics, {
|
|
...(Object.hasOwn(this, "cause") ? { cause: this.cause } : {}),
|
|
...(this.cancellation === undefined
|
|
? {}
|
|
: { cancellation: this.cancellation }),
|
|
...(this.configurationFailure === undefined
|
|
? {}
|
|
: { configurationFailure: this.configurationFailure }),
|
|
...(this.timeoutMs === undefined ? {} : { timeoutMs: this.timeoutMs }),
|
|
...(this.remoteCode === undefined ? {} : { remoteCode: this.remoteCode }),
|
|
...(cleanupFailure === undefined ? {} : { cleanupFailure }),
|
|
...(partialObservation === undefined ? {} : { partialObservation }),
|
|
...(concurrentCancellation === undefined
|
|
? {}
|
|
: { concurrentCancellation }),
|
|
});
|
|
}
|
|
}
|
|
|
|
/** Build a session failure while preserving bounded remote failure metadata. */
|
|
const createGhidraSessionError = (failure: {
|
|
readonly kind: GhidraSessionFailureKind;
|
|
readonly message: string;
|
|
readonly diagnostics: Readonly<Record<string, JsonValue>>;
|
|
readonly cause?: unknown;
|
|
readonly timeoutMs?: number;
|
|
readonly remoteCode?: string;
|
|
readonly cancellation?: { readonly reason: unknown };
|
|
readonly configurationFailure?: ConfigurationError;
|
|
readonly redact: (value: string, incomplete?: boolean) => string;
|
|
}): GhidraSessionError =>
|
|
new GhidraSessionError(
|
|
failure.kind,
|
|
failure.message,
|
|
{
|
|
...failure.diagnostics,
|
|
failure_kind: failure.kind,
|
|
failure_message: failure.message,
|
|
...(failure.remoteCode === undefined
|
|
? {}
|
|
: {
|
|
remote_code: failure.redact(failure.remoteCode),
|
|
remote_message: failure.message,
|
|
}),
|
|
},
|
|
{
|
|
...(failure.cancellation === undefined
|
|
? {}
|
|
: { cancellation: failure.cancellation }),
|
|
...(failure.cause === undefined ? {} : { cause: failure.cause }),
|
|
...(failure.configurationFailure === undefined
|
|
? {}
|
|
: { configurationFailure: failure.configurationFailure }),
|
|
...(failure.timeoutMs === undefined
|
|
? {}
|
|
: { timeoutMs: failure.timeoutMs }),
|
|
...(failure.remoteCode === undefined
|
|
? {}
|
|
: { remoteCode: failure.remoteCode }),
|
|
},
|
|
);
|
|
|
|
/**
|
|
* 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" ||
|
|
code === "invalid_regex_pattern" ||
|
|
code === "not_found" ||
|
|
code === "procedure_not_found" ||
|
|
code === "file_offset_unmapped" ||
|
|
code === "procedure_ambiguous" ||
|
|
code === "file_offset_ambiguous" ||
|
|
code === "ambiguous";
|
|
|
|
/** Bind session-failure construction to its causal diagnostic scope. */
|
|
export const bindGhidraSessionFailure =
|
|
(
|
|
diagnostics: (
|
|
scope: GhidraDiagnosticsScope,
|
|
) => Readonly<Record<string, JsonValue>>,
|
|
redact: (value: string, incomplete?: boolean) => string = (value) => value,
|
|
) =>
|
|
(
|
|
kind: GhidraSessionFailureKind,
|
|
message: string,
|
|
cause?: unknown,
|
|
options: Pick<
|
|
GhidraSessionErrorOptions,
|
|
"timeoutMs" | "remoteCode" | "cancellation" | "configurationFailure"
|
|
> = {},
|
|
): GhidraSessionError => {
|
|
const failure = createGhidraSessionError({
|
|
kind,
|
|
message: redact(message),
|
|
diagnostics: {
|
|
...diagnostics(
|
|
kind === "remote" &&
|
|
(isGhidraInputFailureCode(options.remoteCode) ||
|
|
options.remoteCode === "invalid_function_name" ||
|
|
isGhidraTypeEditRefusalCode(options.remoteCode) ||
|
|
isGhidraCParserLimitCode(options.remoteCode) ||
|
|
ghidraFileOffsetOutcome(options.remoteCode) !== undefined ||
|
|
isGhidraByteSearchCursorMismatch(options.remoteCode))
|
|
? "request"
|
|
: "session",
|
|
),
|
|
...(cause === undefined
|
|
? {}
|
|
: { failure_cause: describeCause(cause, redact) }),
|
|
},
|
|
redact,
|
|
...(cause === undefined ? {} : { cause }),
|
|
...options,
|
|
});
|
|
const cleanup =
|
|
cause instanceof DarwinProcessOwnershipInspectionError ||
|
|
cause instanceof GhidraLaunchError
|
|
? cause.cleanupFailure
|
|
: cause instanceof AnalysisError && cause.cleanupIncomplete
|
|
? cause
|
|
: undefined;
|
|
return cleanup === undefined
|
|
? failure
|
|
: failure.withCleanupFailure(cleanup);
|
|
};
|
|
|
|
/** Canonical factory contract shared by session lifecycle owners. */
|
|
export type GhidraSessionFailureFactory = ReturnType<
|
|
typeof bindGhidraSessionFailure
|
|
>;
|
|
|
|
const describeCause = (
|
|
cause: unknown,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
depth = 0,
|
|
): JsonValue => {
|
|
if (cause instanceof Error) {
|
|
return describeErrorCause(cause, redact, depth);
|
|
}
|
|
if (typeof cause === "string") {
|
|
const message = utf8HeadExcerpt(redact(cause), MAX_CAUSE_MESSAGE_BYTES);
|
|
return {
|
|
type: "string",
|
|
message: message.text,
|
|
...(message.truncated ? { message_truncated: true } : {}),
|
|
};
|
|
}
|
|
if (cause === null || typeof cause === "boolean")
|
|
return { type: cause === null ? "null" : "boolean", value: cause };
|
|
if (typeof cause === "number" && Number.isFinite(cause))
|
|
return { type: "number", value: cause };
|
|
return { type: typeof cause };
|
|
};
|
|
|
|
const describeErrorCause = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
depth: number,
|
|
): JsonValue => {
|
|
const message = utf8HeadExcerpt(
|
|
redact(cause.message),
|
|
MAX_CAUSE_MESSAGE_BYTES,
|
|
);
|
|
const name = utf8HeadExcerpt(redact(cause.name), MAX_CAUSE_FIELD_BYTES);
|
|
return {
|
|
name: name.text,
|
|
...(name.truncated ? { name_truncated: true } : {}),
|
|
message: message.text,
|
|
...(message.truncated ? { message_truncated: true } : {}),
|
|
...causeCode(cause, redact),
|
|
...causeAdmissionDetail(cause, redact),
|
|
...causeSignal(cause, redact),
|
|
...causeCommandOutcome(cause, redact),
|
|
...causeCompilerOutcome(cause, redact),
|
|
...causeLaunchOutcome(cause, redact),
|
|
...causeLaunchRollback(cause, redact, depth),
|
|
...nestedErrorCause(cause, redact, depth),
|
|
};
|
|
};
|
|
|
|
const causeCommandOutcome = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
if (!(cause instanceof GhidraLaunchSupportError)) return {};
|
|
const outcome = cause.outcome;
|
|
if (outcome === undefined) return {};
|
|
const stdout = utf8HeadExcerpt(
|
|
redact(outcome.stdout, outcome.outputTruncated !== false),
|
|
MAX_COMMAND_OUTPUT_BYTES,
|
|
);
|
|
const stderr = utf8HeadExcerpt(
|
|
redact(outcome.stderr, outcome.outputTruncated !== false),
|
|
MAX_COMMAND_OUTPUT_BYTES,
|
|
);
|
|
return {
|
|
command_outcome: {
|
|
stdout: stdout.text,
|
|
stderr: stderr.text,
|
|
stdoutBytes: outcome.stdoutBytes ?? Buffer.byteLength(outcome.stdout),
|
|
stderrBytes: outcome.stderrBytes ?? Buffer.byteLength(outcome.stderr),
|
|
stdoutTruncated: stdout.truncated,
|
|
stderrTruncated: stderr.truncated,
|
|
outputTruncated: outcome.outputTruncated,
|
|
killed: outcome.killed,
|
|
},
|
|
};
|
|
};
|
|
|
|
const causeAdmissionDetail = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
if (!(cause instanceof GhidraAdmissionError) || cause.detail === undefined)
|
|
return {};
|
|
const detail: Record<string, JsonValue> = {};
|
|
for (const [key, value] of Object.entries(cause.detail)) {
|
|
if (typeof value === "number") {
|
|
detail[key] = value;
|
|
continue;
|
|
}
|
|
const bounded = utf8HeadExcerpt(redact(value), MAX_CAUSE_FIELD_BYTES);
|
|
detail[key] = bounded.text;
|
|
}
|
|
return { detail };
|
|
};
|
|
|
|
const causeCode = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
const code = "code" in cause ? cause.code : undefined;
|
|
if (typeof code === "string") {
|
|
const bounded = utf8HeadExcerpt(redact(code), MAX_CAUSE_FIELD_BYTES);
|
|
return {
|
|
code: bounded.text,
|
|
...(bounded.truncated ? { code_truncated: true } : {}),
|
|
};
|
|
}
|
|
if (typeof code === "number" && Number.isFinite(code)) return { code };
|
|
return {};
|
|
};
|
|
|
|
const causeSignal = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
const signal = "signal" in cause ? cause.signal : undefined;
|
|
if (typeof signal === "string") {
|
|
const bounded = utf8HeadExcerpt(redact(signal), MAX_CAUSE_FIELD_BYTES);
|
|
return {
|
|
signal: bounded.text,
|
|
...(bounded.truncated ? { signal_truncated: true } : {}),
|
|
};
|
|
}
|
|
if (signal === null) return { signal: null };
|
|
return {};
|
|
};
|
|
|
|
const causeCompilerOutcome = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
if (!(cause instanceof DarwinProcessOwnershipInspectionError)) return {};
|
|
const outcome = cause.compilerOutcome;
|
|
if (outcome === undefined) return {};
|
|
const stderr = utf8HeadExcerpt(
|
|
redact(outcome.stderr),
|
|
MAX_COMPILER_STDERR_BYTES,
|
|
);
|
|
const code = boundedCompilerField(outcome.code, redact);
|
|
const signal = boundedCompilerField(outcome.signal, redact);
|
|
return {
|
|
compiler_outcome: {
|
|
...outcome,
|
|
code: code.value,
|
|
signal: signal.value,
|
|
stderr: stderr.text,
|
|
stderrTruncated: outcome.stderrTruncated || stderr.truncated,
|
|
...(code.truncated ? { codeTruncated: true } : {}),
|
|
...(signal.truncated ? { signalTruncated: true } : {}),
|
|
},
|
|
};
|
|
};
|
|
|
|
const boundedCompilerField = (
|
|
value: string | number | null,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): { readonly value: string | number | null; readonly truncated: boolean } => {
|
|
if (typeof value !== "string") return { value, truncated: false };
|
|
const bounded = utf8HeadExcerpt(redact(value), MAX_CAUSE_FIELD_BYTES);
|
|
return { value: bounded.text, truncated: bounded.truncated };
|
|
};
|
|
|
|
/** Project the producer's tagged rollback facts independently of the primary cause. */
|
|
const causeLaunchRollback = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
depth: number,
|
|
): Record<string, JsonValue> => {
|
|
if (
|
|
!(cause instanceof GhidraLaunchError) ||
|
|
cause.rollbackFailure === undefined
|
|
)
|
|
return {};
|
|
const rollback = cause.rollbackFailure;
|
|
if (rollback.kind === "rejected")
|
|
return {
|
|
rollback_failure: {
|
|
kind: rollback.kind,
|
|
...(depth >= MAX_CAUSE_DEPTH
|
|
? { cause_truncated: true }
|
|
: { cause: describeCause(rollback.cause, redact, depth + 1) }),
|
|
},
|
|
};
|
|
const result = rollback.result;
|
|
const reason = utf8HeadExcerpt(
|
|
redact(result.reason),
|
|
MAX_CAUSE_MESSAGE_BYTES,
|
|
);
|
|
const diagnostic = (value: string | undefined): Record<string, JsonValue> => {
|
|
if (value === undefined) return {};
|
|
const bounded = utf8HeadExcerpt(redact(value), MAX_CAUSE_MESSAGE_BYTES);
|
|
return {
|
|
diagnostic: bounded.text,
|
|
...(bounded.truncated ? { diagnostic_truncated: true } : {}),
|
|
};
|
|
};
|
|
// Share one member-evidence budget, matching a retained launcher-command stream.
|
|
// Keep the complete typed result on GhidraLaunchError for the process owner.
|
|
let remainingBytes = GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES;
|
|
const members = <Member>(
|
|
values: readonly Member[],
|
|
project: (value: Member) => JsonValue,
|
|
): { readonly rows: JsonValue[]; readonly omitted: number } => {
|
|
const rows: JsonValue[] = [];
|
|
for (const value of values) {
|
|
const row = project(value);
|
|
const bytes =
|
|
Buffer.byteLength(JSON.stringify(row)) + (rows.length === 0 ? 0 : 1);
|
|
if (bytes > remainingBytes) break;
|
|
remainingBytes -= bytes;
|
|
rows.push(row);
|
|
}
|
|
return { rows, omitted: values.length - rows.length };
|
|
};
|
|
const failures =
|
|
result.failures === undefined
|
|
? undefined
|
|
: members(result.failures, (failure) => ({
|
|
pid: failure.pid,
|
|
reason: failure.reason,
|
|
...diagnostic(failure.diagnostic),
|
|
}));
|
|
const unverified =
|
|
result.unverified === undefined
|
|
? undefined
|
|
: members(result.unverified, (member) => ({
|
|
pid: member.pid,
|
|
...diagnostic(member.diagnostic),
|
|
}));
|
|
return {
|
|
rollback_failure: {
|
|
kind: rollback.kind,
|
|
result: {
|
|
cleaned: false,
|
|
reason: reason.text,
|
|
...(reason.truncated ? { reason_truncated: true } : {}),
|
|
...(failures === undefined
|
|
? {}
|
|
: {
|
|
failures: failures.rows,
|
|
...(failures.omitted === 0
|
|
? {}
|
|
: { failures_omitted: failures.omitted }),
|
|
}),
|
|
...(unverified === undefined
|
|
? {}
|
|
: {
|
|
unverified: unverified.rows,
|
|
...(unverified.omitted === 0
|
|
? {}
|
|
: { unverified_omitted: unverified.omitted }),
|
|
}),
|
|
},
|
|
},
|
|
};
|
|
};
|
|
|
|
/** Retain a launch failure's launcher command outcome in its cause envelope. */
|
|
const causeLaunchOutcome = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
): Record<string, JsonValue> => {
|
|
if (!(cause instanceof GhidraLaunchError)) return {};
|
|
const launchSupport =
|
|
cause.launchSupport.length === 0
|
|
? {}
|
|
: {
|
|
launch_support: cause.launchSupport.map((output) => ({
|
|
...output,
|
|
stderr: redact(output.stderr),
|
|
})),
|
|
};
|
|
// A failed LaunchSupport helper reports its own command outcome in the
|
|
// nested cause; earlier helper warnings still belong to this launch.
|
|
if (cause.cause instanceof GhidraLaunchSupportError) return launchSupport;
|
|
const output = cause.capturedOutput;
|
|
if (output === undefined) return launchSupport;
|
|
const stdout = utf8HeadExcerpt(
|
|
redact(output.stdout),
|
|
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
|
|
);
|
|
const stderr = utf8HeadExcerpt(
|
|
redact(output.stderr),
|
|
GHIDRA_LAUNCH_COMMAND_OUTPUT_BYTES,
|
|
);
|
|
const truncated = output.truncated || stdout.truncated || stderr.truncated;
|
|
return {
|
|
...launchSupport,
|
|
launch_outcome: {
|
|
stdout: stdout.text,
|
|
stderr: stderr.text,
|
|
truncated,
|
|
...(output.stdout_bytes === undefined
|
|
? {}
|
|
: { stdout_bytes: output.stdout_bytes }),
|
|
...(output.stderr_bytes === undefined
|
|
? {}
|
|
: { stderr_bytes: output.stderr_bytes }),
|
|
...(output.exit_code === undefined
|
|
? {}
|
|
: { exit_code: output.exit_code }),
|
|
...(output.signal === undefined ? {} : { signal: output.signal }),
|
|
},
|
|
};
|
|
};
|
|
|
|
const nestedErrorCause = (
|
|
cause: Error,
|
|
redact: (value: string, incomplete?: boolean) => string,
|
|
depth: number,
|
|
): Record<string, JsonValue> => {
|
|
if (!("cause" in cause)) return {};
|
|
if (depth >= MAX_CAUSE_DEPTH) return { cause_truncated: true };
|
|
return { cause: describeCause(cause.cause, redact, depth + 1) };
|
|
};
|