fix(javascript): integrate current main stability fixes
Include the merged Hopper reconnect-listener readiness fix so local and CI validation use the same current main recovery boundary. Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com>
This commit is contained in:
co-authored by
factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Kaoru0822
commit
b60248c462
@@ -19,6 +19,13 @@ import type { ProviderOperationHealth } from "../domain/providerOperationHealth.
|
||||
export interface ExecutionOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
/**
|
||||
* Set when a procedure selector came from provider output, such as a
|
||||
* revisited callee, rather than from the caller. A provider-derived
|
||||
* selector is never the caller's input mistake. Absent means the caller
|
||||
* supplied it.
|
||||
*/
|
||||
readonly selectorOrigin?: "provider";
|
||||
}
|
||||
|
||||
/** Closed operations accepted by provider-backed analysis sessions. */
|
||||
|
||||
@@ -26,6 +26,8 @@ import {
|
||||
validateDosComLength,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import { admitRawBinary } from "../domain/rawBinary.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import { mzWindowsHeaderOffset } from "../domain/dosMz.js";
|
||||
import {
|
||||
hasZipSignature,
|
||||
@@ -45,6 +47,8 @@ export interface BinaryTargetResolverOptions {
|
||||
readonly hostArchitecture?: NodeJS.Architecture;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}
|
||||
|
||||
@@ -61,7 +65,7 @@ export const parseBinaryTarget = async (
|
||||
> => {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const hostArchitecture = options.hostArchitecture ?? process.arch;
|
||||
const { targetKind, formatHint, signal } = options;
|
||||
const { targetKind, formatHint, signal, architecture, entryPoint } = options;
|
||||
const candidate = isAbsolute(input) ? input : resolve(cwd, input);
|
||||
try {
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
@@ -83,6 +87,40 @@ export const parseBinaryTarget = async (
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
const metadata = await handle.stat();
|
||||
throwIfTargetResolutionCancelled(signal);
|
||||
if (formatHint === "raw-binary") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"raw-binary format requires an executable target kind",
|
||||
),
|
||||
);
|
||||
const admitted = admitRawBinary({
|
||||
architecture,
|
||||
entryPoint,
|
||||
fileBytes: metadata.size,
|
||||
});
|
||||
if (!admitted.ok)
|
||||
return err(new BinaryTargetError(path, admitted.error));
|
||||
return ok({
|
||||
path,
|
||||
sourcePath: canonical,
|
||||
sha256: await sha256Handle(handle, path, metadata, signal),
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: admitted.value.architecture,
|
||||
availableArchitectures: [admitted.value.architecture],
|
||||
entryPoint: admitted.value.entryPoint,
|
||||
entryPointSource: admitted.value.entryPointSource,
|
||||
});
|
||||
}
|
||||
if (architecture !== undefined || entryPoint !== undefined)
|
||||
return err(
|
||||
new BinaryTargetError(
|
||||
path,
|
||||
"architecture and entry_point apply only with format=raw-binary",
|
||||
),
|
||||
);
|
||||
if (formatHint === "dos-com") {
|
||||
if (targetKind !== undefined && targetKind !== "executable")
|
||||
return err(
|
||||
@@ -194,7 +232,13 @@ const detectArtifactFormat = async (
|
||||
): Promise<
|
||||
| Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
| "dos-mz"
|
||||
| "dos-com"
|
||||
| "raw-binary"
|
||||
>
|
||||
| undefined
|
||||
> => {
|
||||
@@ -244,7 +288,13 @@ const namedArtifactFormat = (
|
||||
const isArchiveFormat = (
|
||||
format: Exclude<
|
||||
BinaryTarget["format"],
|
||||
"analysis-database" | "mach-o" | "elf" | "pe" | "dos-mz" | "dos-com"
|
||||
| "analysis-database"
|
||||
| "mach-o"
|
||||
| "elf"
|
||||
| "pe"
|
||||
| "dos-mz"
|
||||
| "dos-com"
|
||||
| "raw-binary"
|
||||
>,
|
||||
): format is Extract<BinaryTarget, { kind: "archive" }>["format"] =>
|
||||
isZipPackageFormat(format) || ["asar", "dmg", "pkg"].includes(format);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { AnalysisOperation } from "./AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
ExecutionOptions,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { parseRelatedAddresses } from "../domain/hopperValues.js";
|
||||
@@ -11,6 +14,7 @@ type AnalysisCall = (
|
||||
name: AnalysisOperation,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
signal?: AbortSignal,
|
||||
selectorOrigin?: ExecutionOptions["selectorOrigin"],
|
||||
) => Promise<Result<JsonValue, AnalysisError>>;
|
||||
|
||||
export interface CallPathTraceInput {
|
||||
@@ -114,7 +118,7 @@ const expandAddress = async (
|
||||
const relation = input.direction === "forward" ? "callees" : "callers";
|
||||
const tool =
|
||||
input.direction === "forward" ? "procedure_callees" : "procedure_callers";
|
||||
const result = await call(tool, { procedure: address }, signal);
|
||||
const result = await call(tool, { procedure: address }, signal, "provider");
|
||||
if (!result.ok) {
|
||||
state.failures.push({
|
||||
address,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
|
||||
import type { BinarySession } from "./binary/BinarySession.js";
|
||||
@@ -91,6 +92,8 @@ export const runDirectAnalysis = async (
|
||||
readonly signal?: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
} = {},
|
||||
): Promise<JsonValue> =>
|
||||
withProcessCancellation(options.signal, (signal) =>
|
||||
@@ -101,6 +104,12 @@ export const runDirectAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
@@ -187,6 +196,8 @@ const runAnalysis = async (
|
||||
readonly signal: AbortSignal;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
},
|
||||
): Promise<JsonValue> => {
|
||||
const { logger, signal, snapshotPath } = options;
|
||||
@@ -203,6 +214,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
});
|
||||
if (!prepared.ok) return cliError(prepared.error);
|
||||
const { snapshot } = prepared.value;
|
||||
@@ -214,6 +231,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
: { providerId: options.providerId }),
|
||||
@@ -246,6 +269,12 @@ const runAnalysis = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(snapshot === undefined ? {} : { snapshot }),
|
||||
...(options.providerId === undefined
|
||||
? {}
|
||||
@@ -440,6 +469,8 @@ const withProcessCancellation = async <Value>(
|
||||
const prepareSnapshot = async (options: {
|
||||
readonly path: string;
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshotPath: string | undefined;
|
||||
readonly signal: AbortSignal;
|
||||
}): Promise<
|
||||
@@ -458,6 +489,12 @@ const prepareSnapshot = async (options: {
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
});
|
||||
if (!target.ok) return target;
|
||||
if (!snapshotMatchesTarget(loaded.value.target, target.value))
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisOperation,
|
||||
type AnalysisOperationPort,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
interface RecordedCall {
|
||||
readonly operation: AnalysisOperation;
|
||||
readonly procedure: unknown;
|
||||
readonly origin: unknown;
|
||||
}
|
||||
|
||||
/** Port that knows `main` (0x1000, calling 0x2000) and rejects `nosuch`. */
|
||||
const recordingPort = () => {
|
||||
const calls: RecordedCall[] = [];
|
||||
const sentParameters: Readonly<Record<string, JsonValue>>[] = [];
|
||||
const port: AnalysisOperationPort = {
|
||||
execute: async (operation, parameters, options) => {
|
||||
sentParameters.push(parameters);
|
||||
calls.push({
|
||||
operation,
|
||||
procedure: parameters.procedure,
|
||||
origin: options?.selectorOrigin,
|
||||
});
|
||||
const known = (value: JsonValue) =>
|
||||
ok(createAnalysisExecution(value, provider));
|
||||
if (parameters.procedure === "nosuch")
|
||||
return err(new AnalysisInputError(operation));
|
||||
switch (operation) {
|
||||
case "procedure_address":
|
||||
return known(parameters.procedure === "main" ? "0x1000" : "0x2000");
|
||||
case "procedure_callees":
|
||||
return known(parameters.procedure === "0x1000" ? ["0x2000"] : []);
|
||||
case "procedure_pseudo_code":
|
||||
return known("int main(void) { return 0; }");
|
||||
case "address_name":
|
||||
return known("main");
|
||||
default:
|
||||
throw new Error(`Unexpected operation: ${operation}`);
|
||||
}
|
||||
},
|
||||
};
|
||||
return { calls, sentParameters, tools: new EnhancedTools(port) };
|
||||
};
|
||||
|
||||
const of = (
|
||||
calls: readonly RecordedCall[],
|
||||
operation: AnalysisOperation,
|
||||
): RecordedCall[] => calls.filter((call) => call.operation === operation);
|
||||
|
||||
describe("selector origin of composed workflows", () => {
|
||||
it("marks every call-graph expansion as provider-derived and the root selector as caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("get_call_graph", { address: "main" });
|
||||
|
||||
expect(result.ok, "the graph is built").toBe(true);
|
||||
expect(
|
||||
of(calls, "procedure_address"),
|
||||
"the caller's selector carries no provider origin",
|
||||
).toEqual([
|
||||
{ operation: "procedure_address", procedure: "main", origin: undefined },
|
||||
]);
|
||||
expect(
|
||||
of(calls, "procedure_callees"),
|
||||
"the canonical start and every discovered callee are provider-derived",
|
||||
).toEqual([
|
||||
{
|
||||
operation: "procedure_callees",
|
||||
procedure: "0x1000",
|
||||
origin: "provider",
|
||||
},
|
||||
{
|
||||
operation: "procedure_callees",
|
||||
procedure: "0x2000",
|
||||
origin: "provider",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks trace expansions as provider-derived and the start and goal as caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("trace_call_path", {
|
||||
start: "main",
|
||||
goal: "0x2000",
|
||||
});
|
||||
|
||||
expect(result.ok, "the trace completes").toBe(true);
|
||||
expect(
|
||||
of(calls, "procedure_address").map(({ origin }) => origin),
|
||||
"start and goal resolutions are caller-supplied",
|
||||
).toEqual([undefined, undefined]);
|
||||
expect(
|
||||
of(calls, "procedure_callees").map(({ origin }) => origin),
|
||||
"expansion of the resolved start is provider-derived",
|
||||
).toEqual(["provider"]);
|
||||
});
|
||||
|
||||
it("marks the canonical retry of batch_decompile as derived and keeps the unresolved fallback caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("batch_decompile", {
|
||||
addresses: ["main", "nosuch"],
|
||||
});
|
||||
|
||||
expect(result.ok, "per-item failures do not fail the batch").toBe(true);
|
||||
expect(
|
||||
of(calls, "procedure_pseudo_code")
|
||||
.map(({ procedure, origin }) => [procedure, origin])
|
||||
.sort(([left], [right]) => String(left).localeCompare(String(right))),
|
||||
"the resolved canonical address is derived; the failed item keeps the caller's text",
|
||||
).toEqual([
|
||||
["0x1000", "provider"],
|
||||
["nosuch", undefined],
|
||||
]);
|
||||
});
|
||||
|
||||
it("never copies the origin into the parameters sent to the provider", async () => {
|
||||
const { sentParameters, tools } = recordingPort();
|
||||
|
||||
await tools.execute("get_call_graph", { address: "main" });
|
||||
await tools.execute("trace_call_path", { start: "main" });
|
||||
await tools.execute("batch_decompile", { addresses: ["main"] });
|
||||
|
||||
expect(
|
||||
sentParameters.length,
|
||||
"workflows issued provider calls",
|
||||
).toBeGreaterThan(0);
|
||||
expect(
|
||||
sentParameters.some((parameters) => "selectorOrigin" in parameters),
|
||||
"the origin travels in the options only, never in Evidence-bound parameters",
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
ExecutionOptions,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
@@ -163,8 +164,8 @@ export class EnhancedTools {
|
||||
);
|
||||
case "trace_call_path":
|
||||
return traceCallPath(
|
||||
(name, arguments_, operationSignal) =>
|
||||
this.#call(name, arguments_, operationSignal),
|
||||
(name, arguments_, operationSignal, selectorOrigin) =>
|
||||
this.#call(name, arguments_, operationSignal, selectorOrigin),
|
||||
call.input,
|
||||
signal,
|
||||
);
|
||||
@@ -267,6 +268,7 @@ export class EnhancedTools {
|
||||
"procedure_pseudo_code",
|
||||
{ procedure: resolved.ok ? resolved.value : address },
|
||||
signal,
|
||||
resolved.ok ? "provider" : undefined,
|
||||
);
|
||||
if (!result.ok)
|
||||
return {
|
||||
@@ -361,6 +363,7 @@ export class EnhancedTools {
|
||||
tool,
|
||||
{ procedure: current.address },
|
||||
signal,
|
||||
"provider",
|
||||
);
|
||||
if (!result.ok) {
|
||||
graph[level].push({
|
||||
@@ -518,13 +521,13 @@ export class EnhancedTools {
|
||||
name: AnalysisOperation,
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
signal?: AbortSignal,
|
||||
selectorOrigin?: ExecutionOptions["selectorOrigin"],
|
||||
): Promise<Result<JsonValue, AnalysisError>> {
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(name));
|
||||
const execution = await this.analysis.execute(
|
||||
name,
|
||||
arguments_,
|
||||
signal === undefined ? {} : { signal },
|
||||
);
|
||||
const execution = await this.analysis.execute(name, arguments_, {
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
...(selectorOrigin === undefined ? {} : { selectorOrigin }),
|
||||
});
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(name));
|
||||
return execution.ok ? ok(execution.value.result) : execution;
|
||||
}
|
||||
|
||||
@@ -184,10 +184,7 @@ export const systemUninstallHost = (
|
||||
removeClient: (client) => removeClient(client, fileSystem),
|
||||
removeSkill: () =>
|
||||
removeManagedSkills(home, fileSystem, environment, platform),
|
||||
purgeData: async () => [
|
||||
await removeManagedPath(join(home, ".rea/cache"), "cache", fileSystem),
|
||||
await removeManagedPath(join(home, ".rea/state"), "state", fileSystem),
|
||||
],
|
||||
purgeData: () => purgeManagedData(join(home, ".rea"), fileSystem),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -380,6 +377,39 @@ const isOwnedRegistration = (value: unknown, client: SetupClient): boolean => {
|
||||
return isOwnedClientRegistrationCommand([command, ...args]);
|
||||
};
|
||||
|
||||
const purgeManagedData = async (
|
||||
root: string,
|
||||
fileSystem: UninstallFileSystem,
|
||||
): Promise<readonly UninstallItem[]> => {
|
||||
const names = ["cache", "state"];
|
||||
try {
|
||||
const stats = await fileSystem.stat(root);
|
||||
const linked = stats.isSymbolicLink();
|
||||
if (linked || stats.isDirectory?.() !== true)
|
||||
return names.map((name) =>
|
||||
item(
|
||||
name,
|
||||
"retained",
|
||||
`REA did not remove this item because its managed data root ${root} is ${linked ? "a symbolic link" : "not a directory"}. Verify the root before removing its data manually.`,
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return names.map((name) =>
|
||||
isMissing(cause)
|
||||
? item(name, "skipped", `${join(root, name)} does not exist.`)
|
||||
: item(
|
||||
name,
|
||||
"failed",
|
||||
`The managed data root ${root} could not be verified. Check its permissions, then rerun uninstall.`,
|
||||
),
|
||||
);
|
||||
}
|
||||
const items: UninstallItem[] = [];
|
||||
for (const name of names)
|
||||
items.push(await removeManagedPath(join(root, name), name, fileSystem));
|
||||
return items;
|
||||
};
|
||||
|
||||
const removeManagedPath = async (
|
||||
path: string,
|
||||
name: string,
|
||||
|
||||
@@ -497,7 +497,7 @@ export class BinarySession
|
||||
execute(
|
||||
name: Parameters<AnalysisOperationPort["execute"]>[0],
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
options?: Pick<ExecutionOptions, "signal" | "selectorOrigin">,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const generation = this.#transitionGeneration;
|
||||
const call = this.#execute(name, arguments_, options, this.#transition);
|
||||
@@ -535,7 +535,7 @@ export class BinarySession
|
||||
async #execute(
|
||||
name: Parameters<AnalysisOperationPort["execute"]>[0],
|
||||
arguments_: Readonly<Record<string, JsonValue>>,
|
||||
options: { readonly signal?: AbortSignal } | undefined,
|
||||
options: Pick<ExecutionOptions, "signal" | "selectorOrigin"> | undefined,
|
||||
transition: Promise<void>,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const transitioned = await this.#waitForTransition(
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExecutableFormatHint } from "../../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../../domain/binaryTargetTypes.js";
|
||||
import type { AnalysisProviderSelector } from "../../contracts/providerSelection.js";
|
||||
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
|
||||
import {
|
||||
@@ -22,6 +23,8 @@ export interface BinarySessionOpenOptions {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
}
|
||||
@@ -72,6 +75,12 @@ export const resolveSessionOpen = async (
|
||||
...(options.formatHint === undefined
|
||||
? {}
|
||||
: { formatHint: options.formatHint }),
|
||||
...(options.architecture === undefined
|
||||
? {}
|
||||
: { architecture: options.architecture }),
|
||||
...(options.entryPoint === undefined
|
||||
? {}
|
||||
: { entryPoint: options.entryPoint }),
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
});
|
||||
if (!parsed.ok) return parsed;
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { InvestigationRecordPort } from "../investigation/InvestigationRecordPort.js";
|
||||
import type { ExecutableFormatHint } from "../../domain/dosCom.js";
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
import type {
|
||||
BinaryArchitecture,
|
||||
BinaryTarget,
|
||||
} from "../../domain/binaryTargetTypes.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import type { AnalysisSnapshot } from "../../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js";
|
||||
@@ -44,6 +47,8 @@ export interface BinarySessionPort
|
||||
readonly signal?: AbortSignal;
|
||||
readonly targetKind?: BinaryTarget["kind"];
|
||||
readonly formatHint?: ExecutableFormatHint;
|
||||
readonly architecture?: BinaryArchitecture;
|
||||
readonly entryPoint?: string;
|
||||
readonly snapshot?: AnalysisSnapshot;
|
||||
readonly providerId?: AnalysisProviderSelector;
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
import { binaryTargetSummary } from "./BinaryTargetSummary.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import type { ProviderOperationHealth } from "../../domain/providerOperationHealth.js";
|
||||
import type {
|
||||
@@ -92,11 +93,7 @@ export const binarySessionStatus = ({
|
||||
: {
|
||||
open: true,
|
||||
...common,
|
||||
path: target.path,
|
||||
sha256: target.sha256,
|
||||
format: target.format,
|
||||
kind: target.kind,
|
||||
architecture: target.architecture ?? null,
|
||||
...binaryTargetSummary(target),
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
||||
|
||||
/** Preserve the admitted target interpretation in public lifecycle results. */
|
||||
export const binaryTargetSummary = (target: BinaryTarget) => ({
|
||||
path: target.path,
|
||||
format: target.format,
|
||||
kind: target.kind,
|
||||
sha256: target.sha256,
|
||||
architecture: target.architecture ?? null,
|
||||
...(target.format === "raw-binary" ? { entry_point: target.entryPoint } : {}),
|
||||
});
|
||||
@@ -246,6 +246,40 @@ describe("native UI action trace", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("native UI action selector origin", () => {
|
||||
it("marks provider-reported function addresses as derived and the action seed as caller-supplied", async () => {
|
||||
const inner = testAnalysis({
|
||||
procedure_address: () => execution("procedure_address", "0x1000"),
|
||||
});
|
||||
const recorded: { operation: string; origin: unknown }[] = [];
|
||||
|
||||
const result = await new EnhancedTools({
|
||||
execute: async (operation, parameters, options) => {
|
||||
recorded.push({ operation, origin: options?.selectorOrigin });
|
||||
return inner.execute(operation, parameters);
|
||||
},
|
||||
}).execute("trace_native_ui_action", { action: "0x1000" });
|
||||
|
||||
expect(result.ok, "the trace completes").toBe(true);
|
||||
expect(
|
||||
recorded
|
||||
.filter(({ operation }) => operation === "procedure_address")
|
||||
.map(({ origin }) => origin),
|
||||
"the caller's action seed carries no provider origin",
|
||||
).toEqual([undefined]);
|
||||
const probes = recorded.filter(
|
||||
({ operation }) =>
|
||||
operation === "procedure_references" ||
|
||||
operation === "procedure_callees",
|
||||
);
|
||||
expect(probes.length, "relationships were probed").toBeGreaterThan(0);
|
||||
expect(
|
||||
probes.every(({ origin }) => origin === "provider"),
|
||||
"every relationship probe uses a provider-reported address",
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bounded native UI tracing", () => {
|
||||
it("continues handler traversal from its own depth when another UI branch is deeper", async () => {
|
||||
const deepGraph = {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisOperationPort,
|
||||
ExecutionOptions,
|
||||
} from "../AnalysisProvider.js";
|
||||
import {
|
||||
parseRelatedAddresses,
|
||||
referenceKindSchema,
|
||||
@@ -26,8 +29,12 @@ export const readNativeCallRoutes = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
procedure: string,
|
||||
signal?: AbortSignal,
|
||||
selectorOrigin?: ExecutionOptions["selectorOrigin"],
|
||||
) => {
|
||||
const options = signal === undefined ? {} : { signal };
|
||||
const options = {
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
...(selectorOrigin === undefined ? {} : { selectorOrigin }),
|
||||
};
|
||||
const execution = await analysis.execute(
|
||||
"procedure_references",
|
||||
{ procedure, direction: "outgoing" },
|
||||
|
||||
@@ -411,6 +411,7 @@ const addDirectCallees = async (input: {
|
||||
input.analysis,
|
||||
current.address,
|
||||
input.signal,
|
||||
"provider",
|
||||
);
|
||||
examined += 1;
|
||||
if (!execution.ok) {
|
||||
|
||||
@@ -529,3 +529,32 @@ describe("bounded native value dependency composition", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("native value trace selector origin", () => {
|
||||
it("marks only the initial procedure as caller-supplied", async () => {
|
||||
const analyzed: { procedure: unknown; origin: unknown }[] = [];
|
||||
|
||||
const result = await traceNativeValues(
|
||||
{
|
||||
execute: async (operation, parameters, options) => {
|
||||
if (operation === "analyze_function")
|
||||
analyzed.push({
|
||||
procedure: parameters.procedure,
|
||||
origin: options?.selectorOrigin,
|
||||
});
|
||||
return analysis.execute(operation, parameters, options);
|
||||
},
|
||||
},
|
||||
{ procedure: "0x1000" },
|
||||
);
|
||||
|
||||
expect(result.ok, "the trace completes").toBe(true);
|
||||
expect(
|
||||
analyzed,
|
||||
"the caller's procedure is unmarked and the discovered callee is provider-derived",
|
||||
).toEqual([
|
||||
{ procedure: "0x1000", origin: undefined },
|
||||
{ procedure: "0x2000", origin: "provider" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,7 +57,10 @@ export const traceNativeValues = async (
|
||||
const execution = await analysis.execute(
|
||||
"analyze_function",
|
||||
{ procedure: next.procedure },
|
||||
signal === undefined ? {} : { signal },
|
||||
{
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
...(next.depth > 0 ? { selectorOrigin: "provider" as const } : {}),
|
||||
},
|
||||
);
|
||||
decompilations++;
|
||||
if (!execution.ok) {
|
||||
|
||||
@@ -147,22 +147,23 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
async *entries(signal?: AbortSignal): AsyncIterable<ArtifactEntry> {
|
||||
const filenames = new Set<string>();
|
||||
let index = 0;
|
||||
for await (const entry of this.#reader.getEntriesGenerator()) {
|
||||
abortIfNeeded(signal);
|
||||
// Each enumeration can replay valid entries, but a second record with
|
||||
// the same name must not replace an already emitted source identity.
|
||||
if (filenames.has(entry.filename))
|
||||
// ZIP member identity is its directory occurrence, not its filename.
|
||||
// Logical path uniqueness belongs to the artifact inventory boundary.
|
||||
const metadata = projectZipEntry(entry, index++);
|
||||
const stored = this.#entries.get(metadata.adapterKey);
|
||||
if (stored !== undefined && !sameArtifactEntry(metadata, stored.metadata))
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Artifact path collision: ${entry.filename}`,
|
||||
"integrity",
|
||||
`ZIP member identity changed during enumeration: ${entry.filename}`,
|
||||
);
|
||||
filenames.add(entry.filename);
|
||||
const metadata = projectZipEntry(entry);
|
||||
this.#entries.set(entry.filename, {
|
||||
source: entry,
|
||||
metadata: copyArtifactEntry(metadata),
|
||||
});
|
||||
if (stored === undefined)
|
||||
this.#entries.set(metadata.adapterKey, {
|
||||
source: entry,
|
||||
metadata: copyArtifactEntry(metadata),
|
||||
});
|
||||
yield metadata;
|
||||
}
|
||||
}
|
||||
@@ -203,7 +204,7 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
}
|
||||
}
|
||||
|
||||
const projectZipEntry = (entry: Entry): ArtifactEntry => {
|
||||
const projectZipEntry = (entry: Entry, index: number): ArtifactEntry => {
|
||||
const symlink = isSymlink(entry);
|
||||
return {
|
||||
path: entry.filename,
|
||||
@@ -216,7 +217,7 @@ const projectZipEntry = (entry: Entry): ArtifactEntry => {
|
||||
declaredSha256: null,
|
||||
unpacked: false,
|
||||
limitations: symlink ? ["Archive symlink target was not read."] : [],
|
||||
adapterKey: entry.filename,
|
||||
adapterKey: `zip-entry:${index}`,
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -8,9 +8,8 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "pino";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
formatSelectionOption,
|
||||
providerSelectionOption,
|
||||
directAnalysisOptionsFromCli,
|
||||
nativeOpenOptionFields,
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
|
||||
@@ -43,8 +42,7 @@ const registerOverviewCommands = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
});
|
||||
cli.command(CLI_COMMANDS.analyze, {
|
||||
description: "Get an overview of an app",
|
||||
@@ -75,12 +73,7 @@ const registerOverviewCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
);
|
||||
},
|
||||
@@ -97,12 +90,7 @@ const registerOverviewCommands = (
|
||||
args.path,
|
||||
"binary_overview",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -136,8 +124,7 @@ const registerDecompileCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "decompile", () =>
|
||||
@@ -152,12 +139,7 @@ const registerDecompileCommand = (
|
||||
"procedure_pseudo_code",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -168,13 +150,17 @@ const routesToJavaScriptAnalysis = async (
|
||||
path: string,
|
||||
options: {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly "target-format"?: "dos-com" | undefined;
|
||||
readonly "target-format"?: "dos-com" | "raw-binary" | undefined;
|
||||
readonly architecture?: string | undefined;
|
||||
readonly "entry-point"?: string | undefined;
|
||||
readonly provider?: string | undefined;
|
||||
},
|
||||
): Promise<boolean> =>
|
||||
options.provider === undefined &&
|
||||
options.snapshot === undefined &&
|
||||
options["target-format"] === undefined &&
|
||||
options.architecture === undefined &&
|
||||
options["entry-point"] === undefined &&
|
||||
(await isJavaScriptApplicationPath(path));
|
||||
|
||||
const isJavaScriptApplicationPath = async (path: string): Promise<boolean> => {
|
||||
@@ -215,8 +201,7 @@ const registerXrefsCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "xrefs", () =>
|
||||
@@ -231,12 +216,7 @@ const registerXrefsCommand = (
|
||||
"xrefs",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -270,8 +250,7 @@ const registerTraceCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "trace", () =>
|
||||
@@ -287,12 +266,7 @@ const registerTraceCommand = (
|
||||
),
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -326,8 +300,7 @@ const registerFunctionCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "function", () =>
|
||||
@@ -342,12 +315,7 @@ const registerFunctionCommand = (
|
||||
"analyze_function",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -381,8 +349,7 @@ const registerInstructionsCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.instructions, () =>
|
||||
@@ -397,12 +364,7 @@ const registerInstructionsCommand = (
|
||||
"read_function_instructions",
|
||||
),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -448,8 +410,7 @@ const registerSearchCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "search", () =>
|
||||
@@ -468,12 +429,7 @@ const registerSearchCommand = (
|
||||
mode: options.mode,
|
||||
case_sensitive: options.caseSensitive,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -5,9 +5,8 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
|
||||
import { logCliCommand } from "../cliLogging.js";
|
||||
import type { Logger } from "pino";
|
||||
import {
|
||||
directAnalysisOptions,
|
||||
formatSelectionOption,
|
||||
providerSelectionOption,
|
||||
directAnalysisOptionsFromCli,
|
||||
nativeOpenOptionFields,
|
||||
} from "./options.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
@@ -23,8 +22,7 @@ export const registerCoreNativeCommands = (
|
||||
"Verify loaded native bytes, source mappings, relocations and entry",
|
||||
args: z.object({ path: z.string().describe("Local executable path") }),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectNativeLoadImage, () =>
|
||||
@@ -32,12 +30,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"inspect_native_load_image",
|
||||
{},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -54,8 +47,7 @@ export const registerCoreNativeCommands = (
|
||||
.min(1)
|
||||
.default(256)
|
||||
.describe("Requested byte count"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.readBytes, () =>
|
||||
@@ -63,12 +55,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"read_bytes",
|
||||
{ address: args.address, length: options.length },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -79,8 +66,7 @@ export const registerCoreNativeCommands = (
|
||||
address: z.string().describe("Exact provider memory address"),
|
||||
}),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.addressToFileOffset, () =>
|
||||
@@ -88,12 +74,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
"address_to_file_offset",
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -154,8 +135,7 @@ export const registerCoreNativeCommands = (
|
||||
.max(5000)
|
||||
.default(1000)
|
||||
.describe("Maximum nodes on this page"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.traceNativeValues, () =>
|
||||
@@ -172,12 +152,7 @@ export const registerCoreNativeCommands = (
|
||||
offset: options.offset,
|
||||
limit: options.limit,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -189,8 +164,7 @@ export const registerCoreNativeCommands = (
|
||||
options: z.object({
|
||||
type: z.string().optional().describe("Exact database type category path"),
|
||||
address: z.string().optional().describe("Exact native address"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectNativeDataType, () =>
|
||||
@@ -203,12 +177,7 @@ export const registerCoreNativeCommands = (
|
||||
? {}
|
||||
: { address: options.address }),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -226,8 +195,7 @@ export const registerCoreNativeCommands = (
|
||||
address: z.string().describe("Exact native address"),
|
||||
}),
|
||||
options: z.object({
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, command, () =>
|
||||
@@ -235,12 +203,7 @@ export const registerCoreNativeCommands = (
|
||||
args.path,
|
||||
operation,
|
||||
{ address: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -273,8 +236,7 @@ const registerNativeDispatchMetadataCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load or update the local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: async ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-native-dispatch-metadata", () =>
|
||||
@@ -282,12 +244,7 @@ const registerNativeDispatchMetadataCommand = (
|
||||
args.path,
|
||||
"inspect_native_dispatch_metadata",
|
||||
{ max_records: options.maxRecords },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -332,8 +289,7 @@ const registerNativeUiActionCommand = (
|
||||
.max(5_000)
|
||||
.default(500)
|
||||
.describe("Maximum returned graph edges"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: async ({ args, options }) =>
|
||||
logCliCommand(logger, "trace-native-ui-action", () =>
|
||||
@@ -346,12 +302,7 @@ const registerNativeUiActionCommand = (
|
||||
max_nodes: options.maxNodes,
|
||||
max_edges: options.maxEdges,
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -374,8 +325,7 @@ const registerNativeApiCommand = (
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Load and update a local analysis snapshot"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, "inspect-native-api", () =>
|
||||
@@ -383,12 +333,7 @@ const registerNativeApiCommand = (
|
||||
args.path,
|
||||
"inspect_native_api",
|
||||
{ procedure: args.address },
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
@@ -417,8 +362,7 @@ const registerAnnotationCommand = (
|
||||
.string()
|
||||
.optional()
|
||||
.describe("Inline entry comment; empty text clears it"),
|
||||
"target-format": formatSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
...nativeOpenOptionFields,
|
||||
}),
|
||||
run: ({ args, options }) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.annotateNativeFunction, () =>
|
||||
@@ -435,12 +379,7 @@ const registerAnnotationCommand = (
|
||||
? {}
|
||||
: { inline_comment: options["inline-comment"] }),
|
||||
},
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
undefined,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
),
|
||||
directAnalysisOptionsFromCli(logger, options),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
+55
-1
@@ -2,6 +2,11 @@ import {
|
||||
executableFormatHintSchema,
|
||||
type ExecutableFormatHint,
|
||||
} from "../domain/dosCom.js";
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { analysisProviderSelectorSchema } from "../contracts/providerSelection.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import type { Logger } from "pino";
|
||||
@@ -15,16 +20,65 @@ export const providerSelectionOption = analysisProviderSelectorSchema
|
||||
/** Explicit interpretation for headerless native executable formats. */
|
||||
export const formatSelectionOption = executableFormatHintSchema
|
||||
.optional()
|
||||
.describe("Explicit headerless DOS COM interpretation");
|
||||
.describe(
|
||||
"Explicit headerless interpretation (dos-com or raw-binary); omission preserves header-based detection",
|
||||
);
|
||||
|
||||
export const architectureSelectionOption = binaryArchitectureSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied CPU family; required with --target-format raw-binary",
|
||||
);
|
||||
|
||||
export const entryPointSelectionOption = rawBinaryEntryPointSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied load and entry address (0xhex); required with --target-format raw-binary",
|
||||
);
|
||||
|
||||
/** Shared CLI flags that bind a native target interpretation. */
|
||||
export const nativeOpenOptionFields = {
|
||||
"target-format": formatSelectionOption,
|
||||
architecture: architectureSelectionOption,
|
||||
"entry-point": entryPointSelectionOption,
|
||||
provider: providerSelectionOption,
|
||||
};
|
||||
|
||||
/** Native CLI flags consumed when opening a target for one-shot analysis. */
|
||||
export interface NativeOpenCliFlags {
|
||||
readonly snapshot?: string | undefined;
|
||||
readonly provider?: AnalysisProviderSelector | undefined;
|
||||
readonly "target-format"?: ExecutableFormatHint | undefined;
|
||||
readonly architecture?: BinaryArchitecture | undefined;
|
||||
readonly "entry-point"?: string | undefined;
|
||||
}
|
||||
|
||||
export const directAnalysisOptions = (
|
||||
logger: Logger,
|
||||
snapshotPath: string | undefined,
|
||||
providerId: AnalysisProviderSelector | undefined,
|
||||
formatHint?: ExecutableFormatHint,
|
||||
architecture?: BinaryArchitecture,
|
||||
entryPoint?: string,
|
||||
) => ({
|
||||
logger,
|
||||
snapshotPath,
|
||||
...(formatHint === undefined ? {} : { formatHint }),
|
||||
...(architecture === undefined ? {} : { architecture }),
|
||||
...(entryPoint === undefined ? {} : { entryPoint }),
|
||||
...(providerId === undefined ? {} : { providerId }),
|
||||
});
|
||||
|
||||
/** Map native CLI flags onto the shared one-shot analysis options. */
|
||||
export const directAnalysisOptionsFromCli = (
|
||||
logger: Logger,
|
||||
options: NativeOpenCliFlags,
|
||||
) =>
|
||||
directAnalysisOptions(
|
||||
logger,
|
||||
options.snapshot,
|
||||
options.provider,
|
||||
options["target-format"],
|
||||
options.architecture,
|
||||
options["entry-point"],
|
||||
);
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { openBinaryInputSchema } from "./sessionLifecycleInputs.js";
|
||||
|
||||
describe("open_binary raw-binary input contract", () => {
|
||||
it("accepts header detection without architecture", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({ path: "/tmp/fixture.bin" }).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/legacy.com",
|
||||
format: "dos-com",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
it("accepts raw-binary with architecture and entry", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entry_point: "0x8000000",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
it("rejects raw-binary without architecture or entry", () => {
|
||||
const parsed = openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
});
|
||||
expect(parsed.success).toBe(false);
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects architecture without format=raw-binary", () => {
|
||||
expect(
|
||||
openBinaryInputSchema.safeParse({
|
||||
path: "/tmp/ecu.bin",
|
||||
architecture: "arm",
|
||||
entry_point: "0x8000000",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,11 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import { executableFormatHintSchema } from "../domain/dosCom.js";
|
||||
import { localPathStringSchema } from "../domain/localPath.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
rawBinarySelectionError,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { z } from "zod";
|
||||
import { analysisProviderSelectorSchema } from "./providerSelection.js";
|
||||
|
||||
@@ -25,16 +30,51 @@ const binaryTargetPathSchema = localPathStringSchema
|
||||
);
|
||||
|
||||
/** Input contract for opening a target with an optional staged snapshot. */
|
||||
export const openBinaryInputSchema = z.strictObject({
|
||||
path: binaryTargetPathSchema,
|
||||
format: executableFormatHintSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit headerless DOS COM interpretation; omission preserves header-based detection",
|
||||
),
|
||||
provider_id: analysisProviderSelectorSchema.optional(),
|
||||
snapshot_path: snapshotPathSchema.optional(),
|
||||
});
|
||||
export const openBinaryInputSchema = z
|
||||
.strictObject({
|
||||
path: binaryTargetPathSchema,
|
||||
format: executableFormatHintSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Explicit headerless interpretation: dos-com or raw-binary. Omission preserves header-based detection.",
|
||||
),
|
||||
architecture: binaryArchitectureSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied CPU family. Required with format=raw-binary; rejected otherwise.",
|
||||
),
|
||||
entry_point: rawBinaryEntryPointSchema
|
||||
.optional()
|
||||
.describe(
|
||||
"Caller-supplied load and entry address (0xhex). File offset 0 is mapped here. Required with format=raw-binary; rejected otherwise.",
|
||||
),
|
||||
provider_id: analysisProviderSelectorSchema.optional(),
|
||||
snapshot_path: snapshotPathSchema.optional(),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const pairing = rawBinarySelectionError({
|
||||
...(value.format === undefined ? {} : { format: value.format }),
|
||||
...(value.architecture === undefined
|
||||
? {}
|
||||
: { architecture: value.architecture }),
|
||||
...(value.entry_point === undefined
|
||||
? {}
|
||||
: { entryPoint: value.entry_point }),
|
||||
});
|
||||
if (pairing === undefined) return;
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path:
|
||||
value.format === "raw-binary"
|
||||
? value.architecture === undefined
|
||||
? ["architecture"]
|
||||
: ["entry_point"]
|
||||
: value.architecture === undefined
|
||||
? ["entry_point"]
|
||||
: ["architecture"],
|
||||
message: pairing,
|
||||
});
|
||||
});
|
||||
|
||||
/** Input contract for closing a target after an optional atomic snapshot. */
|
||||
export const closeBinaryInputSchema = z.strictObject({
|
||||
|
||||
@@ -69,7 +69,7 @@ export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
export const SESSION_TOOL_CONTRACTS = [
|
||||
session(
|
||||
"open_binary",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. format=dos-com explicitly interprets 1..65280 headerless bytes as a DOS COM analysis image; omission preserves header-based detection. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. Reopening the same target and profile retains its active database and metadata edits. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly; importing into a session with metadata mutations requires closing and reopening it first.",
|
||||
"Open a local executable, application bundle, archive, JavaScript, source map, plist, or analysis database after validation. format=dos-com explicitly interprets 1..65280 headerless bytes as a DOS COM analysis image. format=raw-binary interprets headerless bytes with a required architecture and entry_point; file offset 0 maps at that address. Omission preserves header-based detection. provider_id selects one deep provider or deterministic auto selection; the binding remains stable until close or an explicit switch, with no failure fallback. Reopening the same target and profile retains its active database and metadata edits. An optional analysis snapshot is imported atomically and must match the binary identity, concrete provider, and canonical analysis profile exactly; importing into a session with metadata mutations requires closing and reopening it first.",
|
||||
openBinaryInputSchema,
|
||||
),
|
||||
session(
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
|
||||
import { BINARY_ARCHITECTURES } from "../domain/binaryTargetTypes.js";
|
||||
import {
|
||||
binaryArchitectureSchema,
|
||||
rawBinaryEntryPointSchema,
|
||||
} from "../domain/rawBinary.js";
|
||||
import { nativeFunctionAnnotationsSchema } from "../domain/native/nativeFunctionAnnotations.js";
|
||||
import { nativeLoadImageSchema } from "../domain/native/nativeLoadImage.js";
|
||||
import { nativeUiResultSchema } from "../domain/native/nativeUiObservation.js";
|
||||
@@ -409,16 +413,33 @@ export const managedWorkflowOutputSchemas: Readonly<
|
||||
),
|
||||
};
|
||||
|
||||
const lifecycleTargetFields = {
|
||||
path: z.string(),
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
};
|
||||
const detectedLifecycleTargetSchema = z.object({
|
||||
...lifecycleTargetFields,
|
||||
format: targetFormatSchema.exclude(["raw-binary"]),
|
||||
});
|
||||
const rawLifecycleTargetSchema = z.object({
|
||||
...lifecycleTargetFields,
|
||||
format: z.literal("raw-binary"),
|
||||
kind: z.literal("executable"),
|
||||
architecture: binaryArchitectureSchema,
|
||||
entry_point: rawBinaryEntryPointSchema.describe(
|
||||
"Canonical caller-selected address where raw file offset 0 is mapped and execution is seeded.",
|
||||
),
|
||||
});
|
||||
|
||||
/** Exact structured-content schemas for target lifecycle operations. */
|
||||
export const sessionOutputSchemas = {
|
||||
open_binary: lifecycleResultOf(
|
||||
z.object({
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
}),
|
||||
z.discriminatedUnion("format", [
|
||||
detectedLifecycleTargetSchema,
|
||||
rawLifecycleTargetSchema,
|
||||
]),
|
||||
),
|
||||
close_binary: lifecycleResultOf(
|
||||
z.union([
|
||||
@@ -448,19 +469,15 @@ export const sessionOutputSchemas = {
|
||||
),
|
||||
binary_session: lifecycleResultOf(
|
||||
z.union([
|
||||
z.union([
|
||||
sessionProvider.extend({
|
||||
open: z.literal(false),
|
||||
}),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
path: z.string(),
|
||||
format: targetFormatSchema,
|
||||
kind: targetKindSchema,
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
}),
|
||||
]),
|
||||
sessionProvider.extend({ open: z.literal(false) }),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
...detectedLifecycleTargetSchema.shape,
|
||||
}),
|
||||
sessionProvider.extend({
|
||||
open: z.literal(true),
|
||||
...rawLifecycleTargetSchema.shape,
|
||||
}),
|
||||
]),
|
||||
),
|
||||
export_evidence_bundle: lifecycleResultOf(
|
||||
|
||||
@@ -56,6 +56,7 @@ export const targetFormatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
|
||||
@@ -66,7 +66,7 @@ export const analysisErrorRemediationAction = (
|
||||
if (error instanceof HopperRemoteError)
|
||||
return error.diagnosticType === "invalid_request"
|
||||
? "Correct the reported address, document, or arguments and retry."
|
||||
: "Review the Hopper diagnostic details; correct the request or retry if the failure was transient.";
|
||||
: "Review the Hopper diagnostic details and correct the request or target; run `rea doctor` if the provider itself is failing. Repeating the unchanged request is not expected to succeed.";
|
||||
if (error instanceof EvidenceReferenceError)
|
||||
return "Use an exact Evidence reference retained by this session, supply the complete inline Evidence, re-run its producer, or import its Evidence bundle. close_binary clears retained records.";
|
||||
if (
|
||||
@@ -282,7 +282,7 @@ const hopperProcessMessage = (error: HopperProcessError): string => {
|
||||
|
||||
const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (UNREADABLE_OUTPUT_TAGS.has(tag))
|
||||
return "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.";
|
||||
return "Analysis returned an unreadable result. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.";
|
||||
if (UNSUPPORTED_PROVIDER_TAGS.has(tag))
|
||||
return "This analysis is unavailable for the current target. Choose another analysis or target.";
|
||||
if (CANCELLED_TAGS.has(tag))
|
||||
@@ -290,7 +290,7 @@ const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (TIMEOUT_TAGS.has(tag))
|
||||
return "Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.";
|
||||
if (ADAPTER_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not complete. Retry once; if it continues, run `rea doctor`.";
|
||||
return "Analysis could not complete. Run `rea doctor` and review the reported details; repeating the unchanged request is not expected to succeed.";
|
||||
if (START_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not start or stopped unexpectedly. Run `rea doctor`, then try again.";
|
||||
return undefined;
|
||||
|
||||
@@ -384,6 +384,38 @@ describe("analysis error projection: provider failures", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("analysis error projection: retry guidance", () => {
|
||||
it.each([
|
||||
[
|
||||
"unreadable output",
|
||||
new AnalysisOutputError("inspect_firmware_regions", "report missing"),
|
||||
"unreadable_output",
|
||||
],
|
||||
[
|
||||
"adapter failure",
|
||||
new ProviderAdapterError("firmware", "inspect_firmware_regions"),
|
||||
"execution_failure",
|
||||
],
|
||||
[
|
||||
"Hopper remote failure",
|
||||
new HopperRemoteError(7, "Hopper analysis failed", {
|
||||
diagnosticType: "bridge_exception",
|
||||
operation: "trace_feature",
|
||||
}),
|
||||
"execution_failure",
|
||||
],
|
||||
])(
|
||||
"does not recommend an unchanged retry for non-retryable %s",
|
||||
(_name, error, code) => {
|
||||
const projected = projectAnalysisError(error);
|
||||
|
||||
expect(projected).toMatchObject({ code, retryable: false });
|
||||
for (const text of [projected.message, projected.remediation.action])
|
||||
expect(text).not.toMatch(/\bretry\b/iu);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("analysis error projection: caller contract", () => {
|
||||
it("preserves the reported output constraint without exposing its internal cause", () => {
|
||||
const projected = projectAnalysisError(
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
snapshotBinding,
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotTarget,
|
||||
snapshotMatchesTarget,
|
||||
} from "./analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
} from "./analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import type { BinaryTarget } from "./binaryTargetTypes.js";
|
||||
|
||||
const snapshotWithHistoricalEvidence = () => {
|
||||
const target = snapshotTarget(ANALYSIS_SNAPSHOT_TARGET);
|
||||
@@ -68,6 +70,54 @@ const snapshotWithHistoricalEvidence = () => {
|
||||
};
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("partitions raw snapshots and query identities by the canonical entry", () => {
|
||||
const target: BinaryTarget = {
|
||||
path: "/fixture/image.bin",
|
||||
sha256: ANALYSIS_SNAPSHOT_TARGET.sha256,
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
};
|
||||
const snapshot = snapshotTarget(target);
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const changed = {
|
||||
...target,
|
||||
entryPoint: "0x9000000",
|
||||
entryPointSource: "0x09000000",
|
||||
};
|
||||
expect(
|
||||
snapshotMatchesTarget(snapshot, {
|
||||
...target,
|
||||
entryPointSource: "0x8000000",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(snapshotMatchesTarget(snapshot, changed)).toBe(false);
|
||||
expect(analysisQueryId(snapshot, binding, "list_procedures", {})).not.toBe(
|
||||
analysisQueryId(snapshotTarget(changed), binding, "list_procedures", {}),
|
||||
);
|
||||
const parsed = analysisSnapshotSchema.parse({
|
||||
target: snapshot,
|
||||
binding,
|
||||
entries: [],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
});
|
||||
expect(parsed.target).toHaveProperty("entry_point", target.entryPoint);
|
||||
const { entry_point: _entry, ...legacy } = {
|
||||
...snapshot,
|
||||
entry_point: target.entryPoint,
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({ ...parsed, target: legacy }).success,
|
||||
).toBe(false);
|
||||
expect(snapshotTarget(ANALYSIS_SNAPSHOT_TARGET)).not.toHaveProperty(
|
||||
"entry_point",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves DOS MZ target and subject formats with the x86 family", () => {
|
||||
const target = {
|
||||
path: ANALYSIS_SNAPSHOT_TARGET.path,
|
||||
@@ -113,6 +163,37 @@ describe("analysis snapshot contract", () => {
|
||||
expect(parsed.evidence_bundle.records[0]?.subject?.format).toBe("dos-mz");
|
||||
});
|
||||
|
||||
it("rejects a snapshot subject path containing NUL", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
query_id: `query_${"0".repeat(64)}`,
|
||||
operation: "analyze_function",
|
||||
parameters: {},
|
||||
execution: {
|
||||
result: null,
|
||||
raw_result: null,
|
||||
provider: binding.provider,
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: {
|
||||
path: "a\u0000b",
|
||||
sha256: "a".repeat(64),
|
||||
format: "elf" as const,
|
||||
architecture: null,
|
||||
},
|
||||
},
|
||||
};
|
||||
expect(
|
||||
analysisSnapshotSchema.safeParse({
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding,
|
||||
entries: [entry],
|
||||
workflow_entries: [],
|
||||
evidence_bundle: createEvidenceBundle([]),
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts snapshots with more than ten thousand analysis entries", () => {
|
||||
const binding = snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE);
|
||||
const entry = {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
compareUnicodeCodePoints,
|
||||
compositeKey,
|
||||
} from "./unicodeCodePointOrder.js";
|
||||
import { localPathStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -39,6 +40,7 @@ import { digestSchema } from "./../domain/digests.js";
|
||||
import { prefixedDigestSchema } from "./../domain/digests.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
import { rawBinaryEntryPointSchema } from "./rawBinary.js";
|
||||
|
||||
const architectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
const formatSchema = z.enum([
|
||||
@@ -48,6 +50,7 @@ const formatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +68,7 @@ const formatSchema = z.enum([
|
||||
]);
|
||||
const kindSchema = z.enum(["executable", "database", "archive", "artifact"]);
|
||||
const subjectSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
path: localPathStringSchema,
|
||||
sha256: digestSchema,
|
||||
format: z.enum([
|
||||
...formatSchema.options,
|
||||
@@ -79,12 +82,22 @@ const subjectSchema = z.object({
|
||||
]),
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.object({
|
||||
const targetIdentitySchema = z.object({
|
||||
sha256: digestSchema,
|
||||
kind: kindSchema,
|
||||
format: formatSchema,
|
||||
architecture: architectureSchema.nullable(),
|
||||
});
|
||||
const targetSchema = z.discriminatedUnion("format", [
|
||||
targetIdentitySchema.extend({
|
||||
format: z.enum(
|
||||
formatSchema.options.filter((format) => format !== "raw-binary"),
|
||||
),
|
||||
}),
|
||||
targetIdentitySchema.extend({
|
||||
format: z.literal("raw-binary"),
|
||||
entry_point: rawBinaryEntryPointSchema,
|
||||
}),
|
||||
]);
|
||||
const bindingSchema = z
|
||||
.object({
|
||||
provider: committedProviderSchema,
|
||||
@@ -310,12 +323,16 @@ const canonicalJson = (value: unknown): string => {
|
||||
/** Project a binary into the path-free identity used for cache invalidation. */
|
||||
export const snapshotTarget = (
|
||||
target: BinaryTarget,
|
||||
): AnalysisSnapshotTarget => ({
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
format: target.format,
|
||||
architecture: target.architecture ?? null,
|
||||
});
|
||||
): AnalysisSnapshotTarget => {
|
||||
const identity = {
|
||||
sha256: target.sha256,
|
||||
kind: target.kind,
|
||||
architecture: target.architecture ?? null,
|
||||
};
|
||||
return target.format === "raw-binary"
|
||||
? { ...identity, format: target.format, entry_point: target.entryPoint }
|
||||
: { ...identity, format: target.format };
|
||||
};
|
||||
|
||||
/** Build the immutable provider/profile binding used by a cached snapshot. */
|
||||
export const snapshotBinding = (
|
||||
@@ -334,7 +351,10 @@ export const snapshotMatchesTarget = (
|
||||
snapshot.sha256 === target.sha256 &&
|
||||
snapshot.kind === target.kind &&
|
||||
snapshot.format === target.format &&
|
||||
snapshot.architecture === (target.architecture ?? null);
|
||||
snapshot.architecture === (target.architecture ?? null) &&
|
||||
(snapshot.format !== "raw-binary" ||
|
||||
(target.format === "raw-binary" &&
|
||||
snapshot.entry_point === target.entryPoint));
|
||||
|
||||
/** Compare a snapshot binding with the selected concrete analysis profile. */
|
||||
export const snapshotMatchesProfile = (
|
||||
|
||||
@@ -50,6 +50,7 @@ const artifactFormatSchema = z.enum([
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"hopper",
|
||||
"analysis-database",
|
||||
"ipa",
|
||||
|
||||
@@ -78,6 +78,13 @@ export type BinaryTarget =
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "raw-binary";
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
readonly executableRole?: never;
|
||||
readonly managed?: never;
|
||||
})
|
||||
| (ExecutableTarget & {
|
||||
readonly format: "pe";
|
||||
/** Provider-neutral PE image role observed from COFF characteristics. */
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { z } from "zod";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Headerless DOS COM interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.literal("dos-com");
|
||||
/** Headerless executable interpretation explicitly selected by the caller. */
|
||||
export const executableFormatHintSchema = z.enum(["dos-com", "raw-binary"]);
|
||||
/** Explicit executable interpretation for formats with no identifying header. */
|
||||
export type ExecutableFormatHint = z.infer<typeof executableFormatHintSchema>;
|
||||
|
||||
|
||||
@@ -291,6 +291,22 @@ describe("analysis evidence identity", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a subject local path containing NUL while admitting an empty path", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(evidence.subject).not.toBeNull();
|
||||
const withPath = (path: string) => ({
|
||||
...evidence,
|
||||
subject: { ...evidence.subject, local_path: path },
|
||||
});
|
||||
expect(evidenceSchema.safeParse(withPath("/tmp/fixture")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("")).success).toBe(true);
|
||||
expect(evidenceSchema.safeParse(withPath("a\u0000b")).success).toBe(false);
|
||||
});
|
||||
|
||||
it("binds an explicit unknown-subject reason into the semantic Evidence identity", () => {
|
||||
const reason = "Caller excluded the observed digest.";
|
||||
const observation = { operation: "health", parameters: {}, result: true };
|
||||
|
||||
@@ -2,6 +2,7 @@ import { z } from "zod";
|
||||
|
||||
import { digestCanonicalValue } from "./canonicalDigest.js";
|
||||
import { canonicalJsonDigestSteps } from "./canonicalJsonDigestSteps.js";
|
||||
import { nulFreeStringSchema } from "./localPath.js";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
@@ -43,6 +44,7 @@ const subjectSchema = z.object({
|
||||
"pe",
|
||||
"dos-mz",
|
||||
"dos-com",
|
||||
"raw-binary",
|
||||
"zip",
|
||||
"ipa",
|
||||
"apk",
|
||||
@@ -65,7 +67,7 @@ const subjectSchema = z.object({
|
||||
"entitlements",
|
||||
]),
|
||||
architecture: z.enum(BINARY_ARCHITECTURES).nullable(),
|
||||
local_path: z.string(),
|
||||
local_path: nulFreeStringSchema,
|
||||
});
|
||||
/** Source location attached to an evidence observation. */
|
||||
/** Source-location schema shared by evidence-bearing persistence formats. */
|
||||
|
||||
@@ -2,7 +2,9 @@ import { isAbsolute, relative, sep } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
/**
|
||||
* Preserve selected filesystem names while rejecting OS-invalid NUL bytes.
|
||||
* Reject OS-invalid NUL bytes in a local filesystem name. This is not a path
|
||||
* shape check: an empty or relative value is admitted here and narrowed by the
|
||||
* callers that need a nonempty or absolute path.
|
||||
*
|
||||
* The pattern spells NUL as `\x00` rather than `\u0000`. Both accept exactly the
|
||||
* same strings. The hex form also avoids the short `\0` spelling rejected by
|
||||
@@ -10,11 +12,13 @@ import { z } from "zod";
|
||||
* one advertised pattern cannot compile. See `offsetDateTimeSchema` for the
|
||||
* same hex-escape convention.
|
||||
*/
|
||||
export const localPathStringSchema = z
|
||||
export const nulFreeStringSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
.regex(/^[^\x00]*$/u, "Local filesystem paths cannot contain NUL");
|
||||
|
||||
/** A selected local filesystem path: nonempty and free of NUL bytes. */
|
||||
export const localPathStringSchema = nulFreeStringSchema.min(1);
|
||||
|
||||
/** Test lexical containment on the host platform; callers must resolve symlinks first. */
|
||||
export const isPathWithinRoot = (root: string, path: string): boolean => {
|
||||
const value = relative(root, path);
|
||||
|
||||
@@ -84,7 +84,7 @@ export const nativeLoadImageCheckSchema = z.strictObject({
|
||||
});
|
||||
|
||||
/** Read-only native image verification; verified applies only to declared coverage. */
|
||||
export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
export const nativeLoadImageSchema = z.union([
|
||||
z.strictObject({
|
||||
status: z.literal("unsupported"),
|
||||
reason: z.string().min(1),
|
||||
@@ -108,6 +108,23 @@ export const nativeLoadImageSchema = z.discriminatedUnion("status", [
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.enum(["verified", "mismatch"]),
|
||||
format: z.literal("raw-binary"),
|
||||
target_sha256: digest,
|
||||
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
|
||||
language_id: z.string().min(1),
|
||||
compiler_spec_id: z.string().min(1),
|
||||
base_address: address,
|
||||
file_bytes: integer.min(1),
|
||||
entry: z.strictObject({
|
||||
address: address,
|
||||
file_offset: z.literal(0),
|
||||
}),
|
||||
observations: nativeLoadImageObservationSchema,
|
||||
checks: z.array(nativeLoadImageCheckSchema),
|
||||
limitations: z.array(z.string().min(1)),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Provider-neutral native load-image result. */
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { executableFormatHintSchema } from "./dosCom.js";
|
||||
import {
|
||||
admitRawBinary,
|
||||
parseRawBinaryEntryPoint,
|
||||
rawBinarySelectionError,
|
||||
validateRawBinaryLength,
|
||||
} from "./rawBinary.js";
|
||||
|
||||
describe("headerless format hints", () => {
|
||||
it("admits dos-com and raw-binary names only", () => {
|
||||
expect(executableFormatHintSchema.safeParse("dos-com").success).toBe(true);
|
||||
expect(executableFormatHintSchema.safeParse("raw-binary").success).toBe(
|
||||
true,
|
||||
);
|
||||
expect(executableFormatHintSchema.safeParse("raw").success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("raw-binary entry addresses", () => {
|
||||
it("canonicalizes equivalent hex spellings without dropping the source", () => {
|
||||
const parsed = parseRawBinaryEntryPoint("0x08000000");
|
||||
expect(parsed).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
source: "0x08000000",
|
||||
canonical: "0x8000000",
|
||||
value: 0x8000000n,
|
||||
},
|
||||
});
|
||||
});
|
||||
it.each(["8000000", "0x", "0xgg", "0X8000000", ""])(
|
||||
"rejects malformed entry %s",
|
||||
(value) => {
|
||||
expect(parseRawBinaryEntryPoint(value).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary admission", () => {
|
||||
it("admits a little-endian ARM image mapped at the caller entry", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
fileBytes: 4,
|
||||
}),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x8000000",
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects an empty file", () => {
|
||||
expect(validateRawBinaryLength(0).ok).toBe(false);
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "x86",
|
||||
entryPoint: "0x1000",
|
||||
fileBytes: 0,
|
||||
}).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects a 32-bit mapping that exceeds the architecture width", () => {
|
||||
const result = admitRawBinary({
|
||||
architecture: "arm",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("expected overflow rejection");
|
||||
expect(result.error).toContain("arm address width");
|
||||
});
|
||||
it("allows a 64-bit mapping that would overflow 32-bit ARM", () => {
|
||||
expect(
|
||||
admitRawBinary({
|
||||
architecture: "arm64",
|
||||
entryPoint: "0xfffffffc",
|
||||
fileBytes: 8,
|
||||
}).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
it.each(["arm", "arm64"])(
|
||||
"rejects unaligned %s entries before provider selection",
|
||||
(architecture) => {
|
||||
for (const entryPoint of ["0x8000001", "0x8000002", "0x8000003"]) {
|
||||
expect(
|
||||
admitRawBinary({ architecture, entryPoint, fileBytes: 4 }),
|
||||
).toEqual({
|
||||
ok: false,
|
||||
error: `raw-binary ${architecture} entry_point ${entryPoint} must be 4-byte aligned`,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
it.each(["x86", "x86_64"])(
|
||||
"admits byte-aligned %s entries",
|
||||
(architecture) => {
|
||||
const admitted = admitRawBinary({
|
||||
architecture,
|
||||
entryPoint: "0x1001",
|
||||
fileBytes: 1,
|
||||
});
|
||||
if (!admitted.ok) throw new Error(admitted.error);
|
||||
expect(admitted.value.entryPoint).toBe("0x1001");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("raw-binary selection pairing", () => {
|
||||
it("requires architecture and entry with format=raw-binary", () => {
|
||||
expect(rawBinarySelectionError({ format: "raw-binary" })).toBe(
|
||||
"format=raw-binary requires architecture and entry_point",
|
||||
);
|
||||
expect(
|
||||
rawBinarySelectionError({
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
entryPoint: "0x8000000",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it("rejects architecture or entry without format=raw-binary", () => {
|
||||
expect(
|
||||
rawBinarySelectionError({ architecture: "arm", entryPoint: "0x1" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
expect(
|
||||
rawBinarySelectionError({ format: "dos-com", architecture: "x86" }),
|
||||
).toBe("architecture and entry_point apply only with format=raw-binary");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { BinaryArchitecture } from "./binaryTargetTypes.js";
|
||||
import type { ExecutableFormatHint } from "./dosCom.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Caller-visible CPU families admitted for headerless raw binaries. */
|
||||
export const BINARY_ARCHITECTURES = [
|
||||
"x86",
|
||||
"x86_64",
|
||||
"arm",
|
||||
"arm64",
|
||||
] as const satisfies readonly BinaryArchitecture[];
|
||||
|
||||
/** Provider-neutral CPU family for a caller-supplied raw-binary load. */
|
||||
export const binaryArchitectureSchema = z.enum(BINARY_ARCHITECTURES);
|
||||
|
||||
const RAW_BINARY_ENTRY_POINT = /^0x[0-9A-Fa-f]{1,16}$/u;
|
||||
|
||||
/** Hexadecimal load and entry address; file offset 0 is mapped here. */
|
||||
export const rawBinaryEntryPointSchema = z
|
||||
.string()
|
||||
.regex(RAW_BINARY_ENTRY_POINT, {
|
||||
message: "entry_point must be a hexadecimal address of the form 0x…",
|
||||
});
|
||||
|
||||
/** Canonicalized caller-supplied raw-binary entry with the original spelling. */
|
||||
export interface CanonicalRawBinaryEntry {
|
||||
readonly source: string;
|
||||
readonly canonical: string;
|
||||
readonly value: bigint;
|
||||
}
|
||||
|
||||
/** Parse a caller-supplied hex entry while preserving the source spelling. */
|
||||
export const parseRawBinaryEntryPoint = (
|
||||
value: string,
|
||||
): Result<CanonicalRawBinaryEntry, string> => {
|
||||
if (!RAW_BINARY_ENTRY_POINT.test(value))
|
||||
return err("entry_point must be a hexadecimal address of the form 0x…");
|
||||
const parsed = BigInt(value);
|
||||
return ok({
|
||||
source: value,
|
||||
canonical: `0x${parsed.toString(16)}`,
|
||||
value: parsed,
|
||||
});
|
||||
};
|
||||
|
||||
/** Reject empty or non-integral file extents for a headerless image. */
|
||||
export const validateRawBinaryLength = (
|
||||
length: number,
|
||||
): Result<null, string> =>
|
||||
Number.isSafeInteger(length) && length >= 1
|
||||
? ok(null)
|
||||
: err("raw-binary requires at least one file byte");
|
||||
|
||||
/** Admitted headerless load identity used by target resolution and profiles. */
|
||||
export interface RawBinaryAdmission {
|
||||
readonly architecture: Exclude<BinaryArchitecture, "mips">;
|
||||
readonly entryPoint: string;
|
||||
readonly entryPointSource: string;
|
||||
}
|
||||
|
||||
const addressWidth = (architecture: BinaryArchitecture): bigint =>
|
||||
architecture === "x86" || architecture === "arm"
|
||||
? 0xffffffffn
|
||||
: 0xffffffffffffffffn;
|
||||
|
||||
/** Validate architecture, entry, and that the mapped image fits the CPU width. */
|
||||
export const admitRawBinary = (input: {
|
||||
readonly architecture: unknown;
|
||||
readonly entryPoint: unknown;
|
||||
readonly fileBytes: number;
|
||||
}): Result<RawBinaryAdmission, string> => {
|
||||
const architecture = binaryArchitectureSchema.safeParse(input.architecture);
|
||||
if (!architecture.success)
|
||||
return err(
|
||||
"raw-binary format requires architecture (x86, x86_64, arm, or arm64)",
|
||||
);
|
||||
if (typeof input.entryPoint !== "string")
|
||||
return err(
|
||||
"raw-binary format requires entry_point as a hexadecimal address of the form 0x…",
|
||||
);
|
||||
const entry = parseRawBinaryEntryPoint(input.entryPoint);
|
||||
if (!entry.ok) return entry;
|
||||
if (
|
||||
(architecture.data === "arm" || architecture.data === "arm64") &&
|
||||
entry.value.value % 4n !== 0n
|
||||
)
|
||||
return err(
|
||||
`raw-binary ${architecture.data} entry_point ${entry.value.canonical} must be 4-byte aligned`,
|
||||
);
|
||||
const length = validateRawBinaryLength(input.fileBytes);
|
||||
if (!length.ok) return length;
|
||||
const last = entry.value.value + BigInt(input.fileBytes) - 1n;
|
||||
const max = addressWidth(architecture.data);
|
||||
if (entry.value.value > max || last > max)
|
||||
return err(
|
||||
`raw-binary mapping from ${entry.value.canonical} must fit in the ${architecture.data} address width`,
|
||||
);
|
||||
return ok({
|
||||
architecture: architecture.data,
|
||||
entryPoint: entry.value.canonical,
|
||||
entryPointSource: entry.value.source,
|
||||
});
|
||||
};
|
||||
|
||||
/** Describe the format/architecture/entry pairing without performing I/O. */
|
||||
export const rawBinarySelectionError = (input: {
|
||||
readonly format?: ExecutableFormatHint;
|
||||
readonly architecture?: unknown;
|
||||
readonly entryPoint?: unknown;
|
||||
}): string | undefined => {
|
||||
const hasArchitecture = input.architecture !== undefined;
|
||||
const hasEntry = input.entryPoint !== undefined;
|
||||
if (input.format === "raw-binary") {
|
||||
if (!hasArchitecture || !hasEntry)
|
||||
return "format=raw-binary requires architecture and entry_point";
|
||||
return undefined;
|
||||
}
|
||||
if (hasArchitecture || hasEntry)
|
||||
return "architecture and entry_point apply only with format=raw-binary";
|
||||
return undefined;
|
||||
};
|
||||
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
|
||||
serverSdkVersion: "2.3.1",
|
||||
clientSdkVersion: "2.3.1",
|
||||
coreSdkVersion: "2.3.1",
|
||||
skillVersion: "38",
|
||||
skillVersion: "39",
|
||||
} as const;
|
||||
|
||||
@@ -14,6 +14,7 @@ import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { GhidraInstallationInspection } from "./GhidraInstallation.js";
|
||||
import { ghidraMipsProfileParameters } from "./GhidraMipsProfile.js";
|
||||
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
|
||||
|
||||
import {
|
||||
ghidraProcessorUnsupportedReason,
|
||||
@@ -69,6 +70,57 @@ export const resolveGhidraAnalysisProfile = async (
|
||||
: null;
|
||||
if (pspExtension !== null && !pspExtension.ok) return pspExtension;
|
||||
const provider = { ...identity, version: installation.providerVersion };
|
||||
if (target.format === "raw-binary") {
|
||||
if (languageOverride !== undefined)
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new AnalysisUnsupportedTargetError(
|
||||
"resolve_analysis_profile",
|
||||
target.path,
|
||||
"REA_GHIDRA_LANGUAGE_ID cannot override the admitted raw-binary import.",
|
||||
),
|
||||
),
|
||||
);
|
||||
const language = ghidraRawBinaryLanguage(target.architecture);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
profile: createAnalysisProfile(provider, {
|
||||
target_kind: target.kind,
|
||||
target_format: target.format,
|
||||
architecture: target.architecture,
|
||||
available_architectures: [...target.availableArchitectures].sort(),
|
||||
import_mode: "ephemeral-source-immutable",
|
||||
annotation_policy: "atomic-function-entry-metadata-v1",
|
||||
load_image_observations: "source-mappings-entry-context-v2",
|
||||
function_body_evidence: "complete-inclusive-ranges-v1",
|
||||
function_references: "complete-body-and-entry-reference-manager-v2",
|
||||
string_inventory_evidence: "defined-data-coverage-v1",
|
||||
location_resolution: "explicit-address-exact-entry-symbol-first-v3",
|
||||
instruction_flow_evidence: "decoded-return-pcode-v1",
|
||||
instruction_references: "exact-address-incoming-v1",
|
||||
function_boundary_observations: "ghidra-terminal-call-limitations-v1",
|
||||
no_return_repair:
|
||||
installation.platform === "win32"
|
||||
? "disabled-windows-p0"
|
||||
: "returning-imports-decoded-return-v2",
|
||||
process_launch:
|
||||
installation.platform === "win32"
|
||||
? "official-headless-script-v1"
|
||||
: "inspected-jvm-launch-support-v1",
|
||||
load_image_evidence: "independent-raw-mapping-context-v2",
|
||||
jump_table_evidence: "typed-case-default-blocks-v1",
|
||||
decompiler_jump_loads: true,
|
||||
loader: "BinaryLoader",
|
||||
language_id: language.languageId,
|
||||
compiler_spec_id: language.compilerSpecId,
|
||||
language_selection: "caller-supplied-v1",
|
||||
entry_point: target.entryPoint,
|
||||
entry_seed: "external-entry-and-function-before-analysis-v1",
|
||||
analyzer_preset: "ghidra-default",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
const dosMz = target.format === "dos-mz";
|
||||
const dosCom = target.format === "dos-com";
|
||||
const dos = dosMz || dosCom;
|
||||
|
||||
+143
-77
@@ -1,5 +1,8 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import type { Stats } from "node:fs";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import type { Socket } from "node:net";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
@@ -42,11 +45,12 @@ import {
|
||||
type GhidraSessionInfo,
|
||||
} from "./GhidraSessionValues.js";
|
||||
import { createGhidraTargetSnapshot } from "./GhidraTargetSnapshot.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { readFileHandleChunks } from "../filesystem/readFileHandleChunks.js";
|
||||
import { readBoundedFileBytes } from "../process/BoundedFileBytes.js";
|
||||
import {
|
||||
openRegularFile,
|
||||
RegularFileChangedError,
|
||||
RegularFileAdmissionFailure,
|
||||
sameRegularFileState,
|
||||
} from "../filesystem/RegularFile.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
@@ -162,7 +166,12 @@ export class GhidraClient {
|
||||
}
|
||||
|
||||
/** Launch Ghidra once and require its exact post-analysis handshake. */
|
||||
start(signal?: AbortSignal): Promise<GhidraStartResult> {
|
||||
start(
|
||||
signal?: AbortSignal,
|
||||
progress?: ProgressReporter,
|
||||
): Promise<GhidraStartResult> {
|
||||
if (progress !== undefined)
|
||||
return this.#reportStartupWait(this.start(signal), signal, progress);
|
||||
if (this.#closePromise !== undefined)
|
||||
return this.#closePromise.then(
|
||||
() => this.start(signal),
|
||||
@@ -216,6 +225,41 @@ export class GhidraClient {
|
||||
return started;
|
||||
}
|
||||
|
||||
async #reportStartupWait(
|
||||
started: Promise<GhidraStartResult>,
|
||||
signal: AbortSignal | undefined,
|
||||
progress: ProgressReporter,
|
||||
): Promise<GhidraStartResult> {
|
||||
const startedAt = performance.now();
|
||||
let active = true;
|
||||
let reporting = false;
|
||||
const timer = setInterval(() => {
|
||||
if (!active || reporting || signal?.aborted) return;
|
||||
reporting = true;
|
||||
void Promise.resolve()
|
||||
.then(() => {
|
||||
if (!active || signal?.aborted) return;
|
||||
return progress.report({
|
||||
phase: "ghidra_startup",
|
||||
completed: 0,
|
||||
total: null,
|
||||
message: `Waiting for Ghidra startup (${String(Math.floor((performance.now() - startedAt) / 1000))}s elapsed); import, auto-analysis and bridge readiness may still be pending`,
|
||||
});
|
||||
})
|
||||
// Notification failure does not release the owned startup process.
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
reporting = false;
|
||||
});
|
||||
}, 10_000);
|
||||
try {
|
||||
return await started;
|
||||
} finally {
|
||||
active = false;
|
||||
clearInterval(timer);
|
||||
}
|
||||
}
|
||||
|
||||
/** Revalidate live bridge, provider, run, and profile metadata. */
|
||||
async ping(
|
||||
options: GhidraRequestOptions = {},
|
||||
@@ -231,9 +275,12 @@ export class GhidraClient {
|
||||
async callTool(
|
||||
operation: GhidraOperation,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
options: { readonly signal?: AbortSignal } = {},
|
||||
options: {
|
||||
readonly signal?: AbortSignal;
|
||||
readonly progress?: ProgressReporter;
|
||||
} = {},
|
||||
): Promise<Result<JsonValue, GhidraSessionError>> {
|
||||
const started = await this.start(options.signal);
|
||||
const started = await this.start(options.signal, options.progress);
|
||||
if (!started.ok) return started;
|
||||
return this.#requestQueue.run(
|
||||
operation,
|
||||
@@ -242,12 +289,66 @@ export class GhidraClient {
|
||||
);
|
||||
}
|
||||
|
||||
/** Read the private immutable source for independent import verification. */
|
||||
async readTargetSnapshot(
|
||||
/** Read the private immutable source for format parsers that require captured bytes. */
|
||||
readTargetSnapshot(
|
||||
maximumBytes?: number,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<GhidraTargetSnapshot, GhidraSessionError>> {
|
||||
if (this.#snapshotPath === undefined)
|
||||
return this.#withTargetSnapshot(async (handle, initial, path) => {
|
||||
if (
|
||||
maximumBytes !== undefined &&
|
||||
(!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)
|
||||
)
|
||||
throw new RangeError("Snapshot byte limit must be a safe integer");
|
||||
if (maximumBytes !== undefined && initial.size > maximumBytes)
|
||||
return {
|
||||
kind: "over-capacity",
|
||||
sourceBytesAtLeast: initial.size,
|
||||
maximumBytes,
|
||||
};
|
||||
const bytes = await readBoundedFileBytes(
|
||||
handle,
|
||||
maximumBytes ?? initial.size,
|
||||
signal,
|
||||
initial.size,
|
||||
);
|
||||
if (bytes === undefined || bytes.length !== initial.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
return { kind: "captured", bytes };
|
||||
}, signal);
|
||||
}
|
||||
|
||||
/** Measure the complete snapshot identity without retaining its bytes in memory. */
|
||||
hashTargetSnapshot(
|
||||
signal?: AbortSignal,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly sha256: string; readonly bytes: number },
|
||||
GhidraSessionError
|
||||
>
|
||||
> {
|
||||
return this.#withTargetSnapshot(async (handle, initial, path) => {
|
||||
const hash = createHash("sha256");
|
||||
let bytes = 0;
|
||||
for await (const chunk of readFileHandleChunks(handle, {
|
||||
end: initial.size,
|
||||
signal,
|
||||
})) {
|
||||
bytes += chunk.length;
|
||||
if (bytes > initial.size) throw new RegularFileChangedError(path);
|
||||
hash.update(chunk);
|
||||
}
|
||||
if (bytes !== initial.size) throw new RegularFileChangedError(path);
|
||||
return { sha256: hash.digest("hex"), bytes };
|
||||
}, signal);
|
||||
}
|
||||
|
||||
async #withTargetSnapshot<T>(
|
||||
read: (handle: FileHandle, initial: Stats, path: string) => Promise<T>,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<T, GhidraSessionError>> {
|
||||
const path = this.#snapshotPath;
|
||||
if (path === undefined)
|
||||
return err(
|
||||
this.#failure(
|
||||
"protocol",
|
||||
@@ -255,77 +356,42 @@ export class GhidraClient {
|
||||
),
|
||||
);
|
||||
try {
|
||||
if (maximumBytes !== undefined) {
|
||||
signal?.throwIfAborted();
|
||||
if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0)
|
||||
throw new RangeError("Snapshot byte limit must be a safe integer");
|
||||
const handle = await openRegularFile(this.#snapshotPath, {
|
||||
symlinks: "reject",
|
||||
});
|
||||
const owner = new OwnedFileHandle(handle);
|
||||
this.#snapshotOwners.add(owner);
|
||||
let result: GhidraTargetSnapshot;
|
||||
let readFailure: unknown;
|
||||
try {
|
||||
const metadata = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
if (metadata.size > maximumBytes)
|
||||
result = {
|
||||
kind: "over-capacity",
|
||||
sourceBytesAtLeast: metadata.size,
|
||||
maximumBytes,
|
||||
};
|
||||
else {
|
||||
const bytes = await readBoundedFileBytes(
|
||||
handle,
|
||||
maximumBytes,
|
||||
signal,
|
||||
metadata.size,
|
||||
);
|
||||
signal?.throwIfAborted();
|
||||
const after = await handle.stat();
|
||||
if (
|
||||
bytes !== undefined &&
|
||||
bytes.length === metadata.size &&
|
||||
sameRegularFileState(metadata, after)
|
||||
) {
|
||||
result = { kind: "captured", bytes };
|
||||
} else if (
|
||||
bytes === undefined &&
|
||||
after.isFile() &&
|
||||
after.size > maximumBytes
|
||||
) {
|
||||
result = {
|
||||
kind: "over-capacity",
|
||||
sourceBytesAtLeast: after.size,
|
||||
maximumBytes,
|
||||
};
|
||||
} else {
|
||||
throw new RegularFileChangedError(this.#snapshotPath);
|
||||
}
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
readFailure = cause;
|
||||
}
|
||||
try {
|
||||
await owner.close();
|
||||
this.#snapshotOwners.delete(owner);
|
||||
} catch (closeFailure: unknown) {
|
||||
throw new AggregateError(
|
||||
readFailure === undefined
|
||||
? [closeFailure]
|
||||
: [readFailure, closeFailure],
|
||||
"Ghidra target snapshot read or descriptor cleanup failed",
|
||||
);
|
||||
}
|
||||
if (readFailure !== undefined) throw readFailure;
|
||||
return ok(result!);
|
||||
}
|
||||
return ok({
|
||||
kind: "captured",
|
||||
bytes: await readFile(this.#snapshotPath),
|
||||
const handle = await openRegularFile(path, {
|
||||
symlinks: "reject",
|
||||
signal,
|
||||
});
|
||||
const owner = new OwnedFileHandle(handle);
|
||||
this.#snapshotOwners.add(owner);
|
||||
let result: Result<T, unknown>;
|
||||
try {
|
||||
const initial = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
if (!Number.isSafeInteger(initial.size) || initial.size < 0)
|
||||
throw new RangeError("Snapshot size must be a safe integer");
|
||||
const value = await read(handle, initial, path);
|
||||
signal?.throwIfAborted();
|
||||
const after = await handle.stat();
|
||||
signal?.throwIfAborted();
|
||||
if (!sameRegularFileState(initial, after))
|
||||
throw new RegularFileChangedError(path);
|
||||
result = ok(value);
|
||||
} catch (cause: unknown) {
|
||||
result = err(cause);
|
||||
}
|
||||
try {
|
||||
await owner.close();
|
||||
this.#snapshotOwners.delete(owner);
|
||||
} catch (closeFailure: unknown) {
|
||||
throw new AggregateError(
|
||||
result.ok ? [closeFailure] : [result.error, closeFailure],
|
||||
"Ghidra target snapshot read or descriptor cleanup failed",
|
||||
);
|
||||
}
|
||||
if (!result.ok) throw result.error;
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileAdmissionFailure)
|
||||
this.#snapshotOwners.add(cause.owner);
|
||||
return err(
|
||||
this.#failure(
|
||||
signal?.aborted === true ? "cancelled" : "protocol",
|
||||
|
||||
@@ -101,6 +101,11 @@ export interface GhidraHeadlessLauncherOptions {
|
||||
/** Select the admitted 16-bit real-mode MZ import instead of auto-detection. */
|
||||
readonly dosMz?: true;
|
||||
readonly dosCom?: true;
|
||||
readonly rawBinary?: {
|
||||
readonly languageId: string;
|
||||
readonly compilerSpecId: string;
|
||||
readonly baseAddr: string;
|
||||
};
|
||||
/** Explicit import language committed by the analysis profile. */
|
||||
readonly languageOverride?: GhidraLanguageOverride;
|
||||
/** Caller seeds committed by the analysis profile, applied before analysis. */
|
||||
@@ -201,6 +206,9 @@ export class GhidraHeadlessLauncher implements GhidraLauncher {
|
||||
...(this.options.dosMz === undefined
|
||||
? {}
|
||||
: { dosMz: this.options.dosMz }),
|
||||
...(this.options.rawBinary === undefined
|
||||
? {}
|
||||
: { rawBinary: this.options.rawBinary }),
|
||||
...(this.options.languageOverride === undefined
|
||||
? {}
|
||||
: { languageOverride: this.options.languageOverride }),
|
||||
@@ -411,6 +419,11 @@ export interface GhidraHeadlessArgumentOptions {
|
||||
readonly psp?: true;
|
||||
readonly dosMz?: true;
|
||||
readonly dosCom?: true;
|
||||
readonly rawBinary?: {
|
||||
readonly languageId: string;
|
||||
readonly compilerSpecId: string;
|
||||
readonly baseAddr: string;
|
||||
};
|
||||
readonly languageOverride?: GhidraLanguageOverride;
|
||||
/** Canonical seed snapshot passed to the pre-analysis seed script. */
|
||||
readonly seedPath?: string;
|
||||
@@ -426,6 +439,7 @@ export const ghidraHeadlessArguments = (
|
||||
(options.platform ?? process.platform) === "win32" ? win32 : posix;
|
||||
const bridgeDirectory = scriptPath.dirname(options.bridgeScriptPath);
|
||||
const override = options.languageOverride;
|
||||
const rawBinary = options.rawBinary;
|
||||
if (
|
||||
options.psp === true &&
|
||||
(options.dosMz === true ||
|
||||
@@ -435,6 +449,10 @@ export const ghidraHeadlessArguments = (
|
||||
throw new Error(
|
||||
"A PSP ELF import cannot be combined with DOS or a generic Ghidra language override.",
|
||||
);
|
||||
if (options.psp === true && rawBinary !== undefined)
|
||||
throw new Error(
|
||||
"A PSP ELF import cannot be combined with a raw-binary import.",
|
||||
);
|
||||
if (
|
||||
override !== undefined &&
|
||||
(options.dosMz === true || options.dosCom === true)
|
||||
@@ -442,6 +460,17 @@ export const ghidraHeadlessArguments = (
|
||||
throw new Error(
|
||||
"A Ghidra language override cannot be combined with a DOS import.",
|
||||
);
|
||||
if (override !== undefined && rawBinary !== undefined)
|
||||
throw new Error(
|
||||
"A Ghidra language override cannot be combined with a raw-binary import.",
|
||||
);
|
||||
if (
|
||||
rawBinary !== undefined &&
|
||||
(options.dosMz === true || options.dosCom === true)
|
||||
)
|
||||
throw new Error(
|
||||
"A raw-binary import cannot be combined with a DOS import.",
|
||||
);
|
||||
return [
|
||||
options.projectRoot,
|
||||
"rea-project",
|
||||
@@ -467,24 +496,35 @@ export const ghidraHeadlessArguments = (
|
||||
"-cspec",
|
||||
"default",
|
||||
]
|
||||
: options.psp === true
|
||||
? [
|
||||
"-loader",
|
||||
"PspElfLoader",
|
||||
"-processor",
|
||||
"Allegrex:LE:32:default",
|
||||
"-cspec",
|
||||
"default",
|
||||
]
|
||||
: override !== undefined
|
||||
: rawBinary === undefined
|
||||
? options.psp === true
|
||||
? [
|
||||
"-loader",
|
||||
"PspElfLoader",
|
||||
"-processor",
|
||||
override.languageId,
|
||||
...(override.compilerSpecId === undefined
|
||||
? []
|
||||
: ["-cspec", override.compilerSpecId]),
|
||||
"Allegrex:LE:32:default",
|
||||
"-cspec",
|
||||
"default",
|
||||
]
|
||||
: []),
|
||||
: override !== undefined
|
||||
? [
|
||||
"-processor",
|
||||
override.languageId,
|
||||
...(override.compilerSpecId === undefined
|
||||
? []
|
||||
: ["-cspec", override.compilerSpecId]),
|
||||
]
|
||||
: []
|
||||
: [
|
||||
"-loader",
|
||||
"BinaryLoader",
|
||||
"-loader-baseAddr",
|
||||
rawBinary.baseAddr,
|
||||
"-processor",
|
||||
rawBinary.languageId,
|
||||
"-cspec",
|
||||
rawBinary.compilerSpecId,
|
||||
]),
|
||||
"-readOnly",
|
||||
"-deleteProject",
|
||||
"-log",
|
||||
@@ -499,6 +539,14 @@ export const ghidraHeadlessArguments = (
|
||||
scriptPath.join(bridgeDirectory, "ReaGhidraPrepareCom.java"),
|
||||
]
|
||||
: []),
|
||||
...(rawBinary === undefined
|
||||
? []
|
||||
: [
|
||||
"-preScript",
|
||||
scriptPath.join(bridgeDirectory, "ReaGhidraPrepareRaw.java"),
|
||||
rawBinary.languageId,
|
||||
rawBinary.baseAddr,
|
||||
]),
|
||||
// Seeds follow any loader preparation and precede default auto-analysis.
|
||||
...(options.seedPath === undefined
|
||||
? []
|
||||
|
||||
@@ -12,17 +12,15 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
attestGhidraDosComLoadImage,
|
||||
attestGhidraDosLoadImage,
|
||||
attestGhidraRawBinaryLoadImage,
|
||||
} from "./GhidraLoadImageValues.js";
|
||||
import type { NativeAotPeResult } from "../domain/native/nativeAotPe.js";
|
||||
import type { GhidraTargetSnapshot } from "./GhidraClient.js";
|
||||
import type { GhidraClient } from "./GhidraClient.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
|
||||
type LoadImageSnapshotClient = {
|
||||
readonly readTargetSnapshot?: (
|
||||
maximumBytes?: number,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<Result<GhidraTargetSnapshot, GhidraSessionError>>;
|
||||
};
|
||||
type LoadImageSnapshotClient = Partial<
|
||||
Pick<GhidraClient, "hashTargetSnapshot" | "readTargetSnapshot">
|
||||
>;
|
||||
|
||||
type NativeLoadImageAttestationInput = {
|
||||
readonly target: BinaryTarget;
|
||||
@@ -37,7 +35,7 @@ type NativeLoadImageAttestationInput = {
|
||||
const isSignalAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
/** Independently verify measured load-image observations for admitted DOS targets. */
|
||||
/** Independently verify measured load-image observations for admitted DOS and raw-binary targets. */
|
||||
export const attestGhidraNativeLoadImage = async (
|
||||
input: NativeLoadImageAttestationInput,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
@@ -71,7 +69,7 @@ export const attestGhidraNativeLoadImage = async (
|
||||
nativeLoadImageSchema.parse({
|
||||
status: "unsupported",
|
||||
reason:
|
||||
"Independent load-image verification currently supports DOS MZ and explicit DOS COM targets only.",
|
||||
"Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
|
||||
observations: {
|
||||
...observations,
|
||||
metadata_recovery: [
|
||||
@@ -98,13 +96,17 @@ export const attestGhidraNativeLoadImage = async (
|
||||
);
|
||||
}
|
||||
}
|
||||
if (target.format !== "dos-mz" && target.format !== "dos-com") {
|
||||
if (
|
||||
target.format !== "dos-mz" &&
|
||||
target.format !== "dos-com" &&
|
||||
target.format !== "raw-binary"
|
||||
) {
|
||||
return ok(
|
||||
jsonValueSchema.parse(
|
||||
nativeLoadImageSchema.parse({
|
||||
status: "unsupported",
|
||||
reason:
|
||||
"Independent load-image verification currently supports DOS MZ and explicit DOS COM targets only.",
|
||||
"Independent load-image verification currently supports DOS MZ, explicit DOS COM, and caller-supplied raw-binary targets only.",
|
||||
observations,
|
||||
limitations: [
|
||||
"Other formats expose measured mappings and source identities; no format-specific verification was performed.",
|
||||
@@ -113,6 +115,33 @@ export const attestGhidraNativeLoadImage = async (
|
||||
),
|
||||
);
|
||||
}
|
||||
if (target.format === "raw-binary") {
|
||||
if (client.hashTargetSnapshot === undefined)
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", operation, {
|
||||
diagnostics: {
|
||||
reason:
|
||||
"The Ghidra client does not expose its immutable target snapshot identity for independent raw-binary load-image verification.",
|
||||
},
|
||||
}),
|
||||
);
|
||||
const snapshot = await client.hashTargetSnapshot(signal);
|
||||
if (!snapshot.ok) return err(mapSessionError(snapshot.error));
|
||||
if (isSignalAborted(signal))
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const attested = attestGhidraRawBinaryLoadImage(
|
||||
snapshot.value,
|
||||
target,
|
||||
observations,
|
||||
);
|
||||
return attested.ok
|
||||
? ok(jsonValueSchema.parse(attested.value))
|
||||
: err(
|
||||
new ProviderAdapterError("ghidra", operation, {
|
||||
diagnostics: { reason: attested.error },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (client.readTargetSnapshot === undefined)
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", operation, {
|
||||
@@ -122,14 +151,14 @@ export const attestGhidraNativeLoadImage = async (
|
||||
},
|
||||
}),
|
||||
);
|
||||
const snapshot = await client.readTargetSnapshot();
|
||||
const snapshot = await client.readTargetSnapshot(undefined, signal);
|
||||
if (!snapshot.ok) return err(mapSessionError(snapshot.error));
|
||||
if (snapshot.value.kind !== "captured")
|
||||
return err(
|
||||
new ProviderAdapterError("ghidra", operation, {
|
||||
diagnostics: {
|
||||
reason:
|
||||
"The uncapped DOS load-image snapshot was unexpectedly not captured.",
|
||||
"The uncapped load-image snapshot was unexpectedly not captured.",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
} from "../domain/native/nativeLoadImage.js";
|
||||
import { parseDosMzHeader, type DosMzHeader } from "../domain/dosMz.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
import { validateDosComLength } from "../domain/dosCom.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
|
||||
|
||||
const sha256 = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
@@ -325,3 +327,111 @@ export const attestGhidraDosComLoadImage = (
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const hexAddress = (value: bigint): string => `0x${value.toString(16)}`;
|
||||
|
||||
/** Verify a caller-supplied raw-binary mapping against measured Ghidra import facts. */
|
||||
export const attestGhidraRawBinaryLoadImage = (
|
||||
snapshot: { readonly sha256: string; readonly bytes: number },
|
||||
target: Extract<BinaryTarget, { format: "raw-binary" }>,
|
||||
observations: NativeLoadImageObservation,
|
||||
): Result<NativeLoadImage, string> => {
|
||||
if (snapshot.sha256 !== target.sha256)
|
||||
return err(
|
||||
"Ghidra raw-binary snapshot digest does not match the admitted target",
|
||||
);
|
||||
const language = ghidraRawBinaryLanguage(target.architecture);
|
||||
const base = BigInt(target.entryPoint);
|
||||
const last = hexAddress(base + BigInt(snapshot.bytes) - 1n);
|
||||
const checks: NativeLoadImageCheck[] = [];
|
||||
const check = (
|
||||
name: string,
|
||||
expected: JsonValue,
|
||||
observed: JsonValue,
|
||||
fileOffset: number | null = null,
|
||||
location: string | null = null,
|
||||
): void => {
|
||||
checks.push({
|
||||
name,
|
||||
matched: JSON.stringify(expected) === JSON.stringify(observed),
|
||||
expected,
|
||||
observed,
|
||||
file_offset: fileOffset,
|
||||
address: location,
|
||||
});
|
||||
};
|
||||
const source = observations.source_files[0];
|
||||
const mapping = observations.mappings[0];
|
||||
check("executable_format", "Raw Binary", observations.executable_format);
|
||||
check("language_id", language.languageId, observations.language_id);
|
||||
check(
|
||||
"compiler_spec_id",
|
||||
language.compilerSpecId,
|
||||
observations.compiler_spec_id,
|
||||
);
|
||||
// BinaryLoader's block base is independent of the Program image base.
|
||||
check("image_base", "0x0", observations.image_base);
|
||||
check("source_file_count", 1, observations.source_files.length);
|
||||
check("source_file_size", snapshot.bytes, source?.size ?? null);
|
||||
check("original_file_sha256", target.sha256, source?.original_sha256 ?? null);
|
||||
check("modified_file_sha256", target.sha256, source?.modified_sha256 ?? null);
|
||||
check("mapping_count", 1, observations.mappings.length);
|
||||
check(
|
||||
"mapping.file_offset",
|
||||
0,
|
||||
mapping?.file_offset ?? null,
|
||||
0,
|
||||
mapping?.start ?? null,
|
||||
);
|
||||
check(
|
||||
"mapping.start",
|
||||
target.entryPoint,
|
||||
mapping?.start ?? null,
|
||||
0,
|
||||
mapping?.start ?? null,
|
||||
);
|
||||
check("mapping.end", last, mapping?.end ?? null, 0, mapping?.end ?? null);
|
||||
check(
|
||||
"mapping.length",
|
||||
snapshot.bytes,
|
||||
mapping?.length ?? null,
|
||||
0,
|
||||
mapping?.start ?? null,
|
||||
);
|
||||
check(
|
||||
"mapping.sha256",
|
||||
snapshot.sha256,
|
||||
mapping?.sha256 ?? null,
|
||||
0,
|
||||
mapping?.start ?? null,
|
||||
);
|
||||
check(
|
||||
"entry_point",
|
||||
target.entryPoint,
|
||||
observations.entry_points.find((entry) => entry === target.entryPoint) ??
|
||||
null,
|
||||
);
|
||||
check("relocation_records", [], observations.relocations);
|
||||
return ok(
|
||||
nativeLoadImageSchema.parse({
|
||||
status: checks.every((item) => item.matched) ? "verified" : "mismatch",
|
||||
format: "raw-binary",
|
||||
target_sha256: target.sha256,
|
||||
architecture: target.architecture,
|
||||
language_id: language.languageId,
|
||||
compiler_spec_id: language.compilerSpecId,
|
||||
base_address: target.entryPoint,
|
||||
file_bytes: snapshot.bytes,
|
||||
entry: { address: target.entryPoint, file_offset: 0 },
|
||||
observations,
|
||||
checks,
|
||||
limitations: [
|
||||
"Raw binary is a headerless interpretation explicitly selected by the caller, not format identification from file bytes.",
|
||||
"Verification covers complete original/modified source identity, mapped file bytes, the caller-supplied entry, and the bound little-endian Ghidra language. File offset 0 is mapped at the entry address.",
|
||||
"Ghidra may report additional language-defined external entries outside the mapped image. They are preserved as observations; verification requires the caller-supplied entry and does not attest other entries.",
|
||||
"Reset vectors, memory-mapped I/O, big-endian and Thumb-only variants, and runtime boot behavior are not modeled or verified. No original executable bytes are changed.",
|
||||
"Mapping ends are inclusive; a mismatching digest identifies its source range, not the first differing byte.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { fixtureDosLoadImage } from "./GhidraLoadImage.fixture.js";
|
||||
import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
|
||||
import {
|
||||
nativeAotPeDigest,
|
||||
nativeAotPeFixture,
|
||||
@@ -177,6 +178,50 @@ describe("Ghidra provider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra raw-binary profile", () => {
|
||||
it("commits BinaryLoader language and caller-supplied entry", async () => {
|
||||
const ghidra = provider();
|
||||
const target: BinaryTarget = {
|
||||
path: "/tmp/ecu.bin",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
};
|
||||
expect(ghidra.inspectTargetSupport(target).status).toBe("supported");
|
||||
const resolved = await ghidra.resolveAnalysisProfile(target);
|
||||
expect(resolved.ok && resolved.value).toMatchObject({
|
||||
profile: {
|
||||
parameters: {
|
||||
target_format: "raw-binary",
|
||||
architecture: "arm",
|
||||
loader: "BinaryLoader",
|
||||
language_id: "ARM:LE:32:v7",
|
||||
compiler_spec_id: "default",
|
||||
language_selection: "caller-supplied-v1",
|
||||
entry_point: "0x8000000",
|
||||
},
|
||||
},
|
||||
});
|
||||
const shifted = await ghidra.resolveAnalysisProfile({
|
||||
...target,
|
||||
entryPoint: "0x8001000",
|
||||
entryPointSource: "0x8001000",
|
||||
});
|
||||
expect(resolved.ok && shifted.ok).toBe(true);
|
||||
if (!resolved.ok || !shifted.ok || resolved.value.profile === null)
|
||||
throw new Error("expected raw-binary profiles");
|
||||
expect(shifted.value.profile?.digest).not.toBe(
|
||||
resolved.value.profile.digest,
|
||||
);
|
||||
const windows = provider({ ...installationHost(), platform: "win32" });
|
||||
expect(windows.inspectTargetSupport(target).status).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra Mach-O slice support", () => {
|
||||
it("refuses universal targets whose selected slice cannot be enforced", () => {
|
||||
const ghidra = provider();
|
||||
@@ -718,6 +763,88 @@ describe("Ghidra result projection", () => {
|
||||
});
|
||||
|
||||
describe("Ghidra measured load-image projection", () => {
|
||||
it.each(["verified", "changed-snapshot", "cancelled"] as const)(
|
||||
"streams raw snapshot identity and preserves %s outcomes",
|
||||
async (state) => {
|
||||
const fixture = fixtureRawBinaryLoadImage();
|
||||
const controller = new AbortController();
|
||||
const signals: (AbortSignal | undefined)[] = [];
|
||||
const ghidra = provider(installationHost(), () => ({
|
||||
start: () => Promise.resolve(ok(sessionInfo())),
|
||||
callTool: (operation) => {
|
||||
if (operation !== "inspect_native_load_image")
|
||||
throw new Error(`unexpected operation ${operation}`);
|
||||
return Promise.resolve(
|
||||
ok(jsonValueSchema.parse(fixture.observation)),
|
||||
);
|
||||
},
|
||||
readTargetSnapshot: () => {
|
||||
throw new Error(
|
||||
"raw verification must not capture the complete file",
|
||||
);
|
||||
},
|
||||
hashTargetSnapshot: (signal) => {
|
||||
signals.push(signal);
|
||||
if (state === "cancelled") {
|
||||
controller.abort();
|
||||
return Promise.resolve(
|
||||
err(
|
||||
new GhidraSessionError(
|
||||
"cancelled",
|
||||
"Snapshot hashing cancelled",
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
...fixture.snapshot,
|
||||
...(state === "changed-snapshot"
|
||||
? { sha256: "f".repeat(64) }
|
||||
: {}),
|
||||
}),
|
||||
);
|
||||
},
|
||||
close: () => Promise.resolve(ok(null)),
|
||||
}));
|
||||
const resolved = await ghidra.resolveAnalysisProfile(fixture.target);
|
||||
if (!resolved.ok) throw resolved.error;
|
||||
if (resolved.value.profile === null)
|
||||
throw new Error("expected raw profile");
|
||||
const client = ghidra.createClient(
|
||||
fixture.target,
|
||||
resolved.value.profile,
|
||||
);
|
||||
try {
|
||||
const result = await client.execute(
|
||||
"inspect_native_load_image",
|
||||
{},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(signals).toEqual([controller.signal]);
|
||||
if (state === "verified") {
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.result).toMatchObject({
|
||||
status: "verified",
|
||||
observations: fixture.observation,
|
||||
});
|
||||
} else {
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag:
|
||||
state === "cancelled"
|
||||
? "AnalysisCancelledError"
|
||||
: "ProviderAdapterError",
|
||||
},
|
||||
});
|
||||
}
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
"verified",
|
||||
"mismatch",
|
||||
|
||||
@@ -87,12 +87,18 @@ import {
|
||||
windowsNativeAuthorityUnavailableReason,
|
||||
hasWindowsNativeAuthority,
|
||||
} from "../process/WindowsAuthority.js";
|
||||
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
|
||||
|
||||
/** Production seam for exercising provider projection without a real process. */
|
||||
export type GhidraProviderClientFactory = (
|
||||
options: GhidraClientOptions,
|
||||
) => Pick<GhidraClient, "start" | "callTool" | "close"> &
|
||||
Partial<Pick<GhidraClient, "runtimeLineage" | "readTargetSnapshot">>;
|
||||
Partial<
|
||||
Pick<
|
||||
GhidraClient,
|
||||
"runtimeLineage" | "readTargetSnapshot" | "hashTargetSnapshot"
|
||||
>
|
||||
>;
|
||||
|
||||
type GhidraProviderClientInstance = ReturnType<GhidraProviderClientFactory>;
|
||||
|
||||
@@ -440,6 +446,10 @@ export const createGhidraProviderClient = (input: {
|
||||
let extensionFailure: AnalysisError | undefined;
|
||||
// Replaced by the reported outcome once the session handshake is checked.
|
||||
const seedLimitations: string[] = [...ghidraSeedLimitations(seeds)];
|
||||
const rawLanguage =
|
||||
target.format === "raw-binary"
|
||||
? ghidraRawBinaryLanguage(target.architecture)
|
||||
: undefined;
|
||||
const targetLimitations = [
|
||||
...(target.format === "dos-mz"
|
||||
? [
|
||||
@@ -447,6 +457,13 @@ export const createGhidraProviderClient = (input: {
|
||||
"Static DOS analysis does not emulate BIOS, DOS interrupts, device ports, or self-modifying unpacking code. Packed targets require a separately identified unpacked artifact for original-program analysis; appended overlays are not the initialized load module.",
|
||||
]
|
||||
: []),
|
||||
...(target.format === "raw-binary"
|
||||
? [
|
||||
"Headerless raw-binary analysis uses the caller-supplied architecture and entry address; file offset 0 is mapped at that address. Headers are not discovered from file bytes.",
|
||||
"Little-endian generic Ghidra languages are used for x86, x86_64, arm, and arm64. Big-endian, Thumb-only, Cortex-M, and other processor variants are unsupported in this increment.",
|
||||
"Static analysis does not emulate reset vectors, memory-mapped I/O, or firmware boot sequences.",
|
||||
]
|
||||
: []),
|
||||
...(target.kind === "executable" && target.architecture === "mips"
|
||||
? (target.mips.limitations ?? [])
|
||||
: []),
|
||||
@@ -474,6 +491,15 @@ export const createGhidraProviderClient = (input: {
|
||||
: {}),
|
||||
...(target.format === "dos-mz" ? { dosMz: true } : {}),
|
||||
...(target.format === "dos-com" ? { dosCom: true } : {}),
|
||||
...(rawLanguage === undefined || target.format !== "raw-binary"
|
||||
? {}
|
||||
: {
|
||||
rawBinary: {
|
||||
languageId: rawLanguage.languageId,
|
||||
compilerSpecId: rawLanguage.compilerSpecId,
|
||||
baseAddr: target.entryPoint,
|
||||
},
|
||||
}),
|
||||
...(languageOverride === undefined ? {} : { languageOverride }),
|
||||
...(seeds === undefined ? {} : { analysisSeeds: seeds }),
|
||||
platform: installation.platform,
|
||||
@@ -495,13 +521,18 @@ export const createGhidraProviderClient = (input: {
|
||||
expectedLanguageId: "x86:LE:16:Real Mode",
|
||||
expectedCompilerSpecId: "default",
|
||||
}
|
||||
: languageOverride === undefined
|
||||
? {}
|
||||
: rawLanguage === undefined
|
||||
? languageOverride === undefined
|
||||
? {}
|
||||
: {
|
||||
expectedLanguageId: languageOverride.languageId,
|
||||
...(languageOverride.compilerSpecId === undefined
|
||||
? {}
|
||||
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
|
||||
}
|
||||
: {
|
||||
expectedLanguageId: languageOverride.languageId,
|
||||
...(languageOverride.compilerSpecId === undefined
|
||||
? {}
|
||||
: { expectedCompilerSpecId: languageOverride.compilerSpecId }),
|
||||
expectedLanguageId: rawLanguage.languageId,
|
||||
expectedCompilerSpecId: rawLanguage.compilerSpecId,
|
||||
}),
|
||||
...(psp
|
||||
? {
|
||||
@@ -573,7 +604,7 @@ export const createGhidraProviderClient = (input: {
|
||||
),
|
||||
);
|
||||
if (operation === "health") {
|
||||
const started = await client.start(options?.signal);
|
||||
const started = await client.start(options?.signal, options?.progress);
|
||||
if (!started.ok)
|
||||
return err(
|
||||
projectSessionError(
|
||||
@@ -596,7 +627,7 @@ export const createGhidraProviderClient = (input: {
|
||||
: parseGhidraInventoryInput(operation, parameters);
|
||||
if (!input.ok) return input;
|
||||
if (extensions.length > 0 || seeds !== undefined) {
|
||||
const started = await client.start(options?.signal);
|
||||
const started = await client.start(options?.signal, options?.progress);
|
||||
if (!started.ok)
|
||||
return err(
|
||||
projectSessionError(
|
||||
@@ -608,11 +639,12 @@ export const createGhidraProviderClient = (input: {
|
||||
const failed = await checkExtensions(operation, started.value);
|
||||
if (failed !== undefined) return err(failed);
|
||||
}
|
||||
const called = await client.callTool(
|
||||
operation,
|
||||
input.value,
|
||||
options?.signal === undefined ? {} : { signal: options.signal },
|
||||
);
|
||||
const called = await client.callTool(operation, input.value, {
|
||||
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
||||
...(options?.progress === undefined
|
||||
? {}
|
||||
: { progress: options.progress }),
|
||||
});
|
||||
if (!called.ok)
|
||||
return err(
|
||||
projectSessionError(
|
||||
@@ -637,7 +669,10 @@ export const createGhidraProviderClient = (input: {
|
||||
const address = input.value.address;
|
||||
if (typeof address === "string") {
|
||||
if (target.format === "pe" && nativeAotOwner !== undefined) {
|
||||
const started = await client.start(options?.signal);
|
||||
const started = await client.start(
|
||||
options?.signal,
|
||||
options?.progress,
|
||||
);
|
||||
if (!started.ok)
|
||||
return err(
|
||||
projectSessionError(
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BinaryArchitecture } from "../domain/binaryTargetTypes.js";
|
||||
|
||||
/** Bound Ghidra language for a caller-supplied raw-binary architecture. */
|
||||
export interface GhidraRawBinaryLanguage {
|
||||
readonly languageId: string;
|
||||
readonly compilerSpecId: "default";
|
||||
}
|
||||
|
||||
/**
|
||||
* Map the four caller-visible CPU families to little-endian generic Ghidra
|
||||
* languages. Big-endian, Thumb-only, and Cortex-M variants are out of scope.
|
||||
*/
|
||||
export const ghidraRawBinaryLanguage = (
|
||||
architecture: Exclude<BinaryArchitecture, "mips">,
|
||||
): GhidraRawBinaryLanguage => {
|
||||
switch (architecture) {
|
||||
case "x86":
|
||||
return { languageId: "x86:LE:32:default", compilerSpecId: "default" };
|
||||
case "x86_64":
|
||||
return { languageId: "x86:LE:64:default", compilerSpecId: "default" };
|
||||
case "arm":
|
||||
return { languageId: "ARM:LE:32:v7", compilerSpecId: "default" };
|
||||
case "arm64":
|
||||
return { languageId: "AARCH64:LE:64:v8A", compilerSpecId: "default" };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import type { NativeLoadImageObservation } from "../domain/native/nativeLoadImage.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
|
||||
|
||||
const hash = (bytes: Buffer): string =>
|
||||
createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
export const fixtureRawBinaryLoadImage = (): {
|
||||
snapshot: { sha256: string; bytes: number };
|
||||
target: Extract<BinaryTarget, { format: "raw-binary" }>;
|
||||
observation: NativeLoadImageObservation;
|
||||
} => {
|
||||
const bytes = Buffer.from("1eff2fe1", "hex");
|
||||
const digest = hash(bytes);
|
||||
return {
|
||||
snapshot: { sha256: digest, bytes: bytes.length },
|
||||
target: {
|
||||
path: "/tmp/ecu.bin",
|
||||
sha256: digest,
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x08000000",
|
||||
},
|
||||
observation: {
|
||||
executable_format: "Raw Binary",
|
||||
language_id: "ARM:LE:32:v7",
|
||||
compiler_spec_id: "default",
|
||||
image_base: "0x0",
|
||||
default_address_space: "ram",
|
||||
source_files: [
|
||||
{
|
||||
name: "ecu.bin",
|
||||
size: bytes.length,
|
||||
original_sha256: digest,
|
||||
modified_sha256: digest,
|
||||
},
|
||||
],
|
||||
mappings: [
|
||||
{
|
||||
block: "ram",
|
||||
start: "0x8000000",
|
||||
end: "0x8000003",
|
||||
address_space: "ram",
|
||||
initialized: true,
|
||||
loaded: true,
|
||||
overlay: false,
|
||||
length: bytes.length,
|
||||
source_file_index: 0,
|
||||
file_offset: 0,
|
||||
sha256: digest,
|
||||
},
|
||||
],
|
||||
relocations: [],
|
||||
entry_points: ["0x8000000"],
|
||||
entry_context: [],
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { attestGhidraRawBinaryLoadImage } from "./GhidraLoadImageValues.js";
|
||||
import { fixtureRawBinaryLoadImage } from "./GhidraRawBinaryLoadImage.fixture.js";
|
||||
import { ghidraRawBinaryLanguage } from "./GhidraRawBinaryLanguage.js";
|
||||
|
||||
describe("raw-binary Ghidra language binding", () => {
|
||||
it("maps the four admitted families to little-endian generic languages", () => {
|
||||
expect(ghidraRawBinaryLanguage("x86")).toEqual({
|
||||
languageId: "x86:LE:32:default",
|
||||
compilerSpecId: "default",
|
||||
});
|
||||
expect(ghidraRawBinaryLanguage("x86_64")).toEqual({
|
||||
languageId: "x86:LE:64:default",
|
||||
compilerSpecId: "default",
|
||||
});
|
||||
expect(ghidraRawBinaryLanguage("arm")).toEqual({
|
||||
languageId: "ARM:LE:32:v7",
|
||||
compilerSpecId: "default",
|
||||
});
|
||||
expect(ghidraRawBinaryLanguage("arm64")).toEqual({
|
||||
languageId: "AARCH64:LE:64:v8A",
|
||||
compilerSpecId: "default",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("raw-binary independent load-image checks", () => {
|
||||
it("verifies mapped bytes at the caller-supplied entry", () => {
|
||||
const f = fixtureRawBinaryLoadImage();
|
||||
const result = attestGhidraRawBinaryLoadImage(
|
||||
f.snapshot,
|
||||
f.target,
|
||||
f.observation,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
status: "verified",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
language_id: "ARM:LE:32:v7",
|
||||
base_address: "0x8000000",
|
||||
file_bytes: 4,
|
||||
entry: { address: "0x8000000", file_offset: 0 },
|
||||
},
|
||||
});
|
||||
});
|
||||
it("retains mismatch evidence for a drifted language", () => {
|
||||
const f = fixtureRawBinaryLoadImage();
|
||||
f.observation.language_id = "x86:LE:32:default";
|
||||
const result = attestGhidraRawBinaryLoadImage(
|
||||
f.snapshot,
|
||||
f.target,
|
||||
f.observation,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
value: { status: "mismatch", observations: f.observation },
|
||||
});
|
||||
});
|
||||
it("preserves additional language entries while requiring the caller entry", () => {
|
||||
const f = fixtureRawBinaryLoadImage();
|
||||
f.observation.entry_points = ["0x0", f.target.entryPoint, "0xffff0000"];
|
||||
expect(
|
||||
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: { status: "verified", observations: f.observation },
|
||||
});
|
||||
f.observation.entry_points = ["0x0", "0xffff0000"];
|
||||
expect(
|
||||
attestGhidraRawBinaryLoadImage(f.snapshot, f.target, f.observation),
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
status: "mismatch",
|
||||
checks: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
name: "entry_point",
|
||||
matched: false,
|
||||
observed: null,
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
it("rejects stale snapshot identity", () => {
|
||||
const f = fixtureRawBinaryLoadImage();
|
||||
expect(
|
||||
attestGhidraRawBinaryLoadImage(
|
||||
f.snapshot,
|
||||
{ ...f.target, sha256: "f".repeat(64) },
|
||||
f.observation,
|
||||
).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -140,6 +140,7 @@ export const hopperLoaderArgsForTarget = (
|
||||
return ok(["-l", "WinPE", flag]);
|
||||
case "dos-mz":
|
||||
case "dos-com":
|
||||
case "raw-binary":
|
||||
return err(
|
||||
new ProviderAdapterError("hopper", "resolve_analysis_profile"),
|
||||
);
|
||||
|
||||
@@ -5,6 +5,27 @@ import { silentLogger } from "../logger.js";
|
||||
import { HopperProvider } from "./HopperProvider.js";
|
||||
|
||||
describe("Hopper provider capabilities", () => {
|
||||
it("declines headerless raw-binary targets with a Ghidra-directed reason", () => {
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw new Error("expected valid configuration");
|
||||
const provider = new HopperProvider(config.value, silentLogger, {});
|
||||
expect(
|
||||
provider.inspectTargetSupport({
|
||||
path: "/tmp/ecu.bin",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x8000000",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
reason: expect.stringContaining("Ghidra"),
|
||||
});
|
||||
});
|
||||
it("declines DOS MZ targets with a provider-specific support reason", () => {
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw new Error("expected valid configuration");
|
||||
|
||||
@@ -123,6 +123,14 @@ export class HopperProvider implements AnalysisProviderCandidate {
|
||||
reason: "REA's Hopper adapter does not admit MIPS targets.",
|
||||
diagnostics,
|
||||
};
|
||||
if (target.format === "raw-binary")
|
||||
return {
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
reason:
|
||||
"Headerless raw-binary analysis requires the Ghidra adapter with a caller-supplied architecture and entry point.",
|
||||
diagnostics,
|
||||
};
|
||||
if (target.format === "dos-mz" || target.format === "dos-com")
|
||||
return {
|
||||
status: "unsupported",
|
||||
|
||||
@@ -5,6 +5,9 @@ import {
|
||||
RecordingIdaMcp,
|
||||
} from "../../tests/fixtures/idaMcp.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { decodeIdaToolResult } from "./IdaMcpConnection.js";
|
||||
import type { AnalysisOperation } from "../application/AnalysisProvider.js";
|
||||
import { IdaSessionClient } from "./IdaSessionClient.js";
|
||||
|
||||
@@ -96,3 +99,290 @@ describe("headless IDA operation failures", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const lookup = (query: string, fn: JsonValue, error: string | null) => [
|
||||
{ query, fn, error },
|
||||
];
|
||||
const knownFunction = { addr: "0x1000", name: "main", size: "0x20" };
|
||||
|
||||
const missingProcedureFixture = async (
|
||||
answer: (query: string) => JsonValue | undefined,
|
||||
) => {
|
||||
const { root, target } = await createIdaTarget();
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "headless");
|
||||
producer.overrideCall = (name, args) => {
|
||||
if (name !== "lookup_funcs") return undefined;
|
||||
const queries = args.queries;
|
||||
const query = Array.isArray(queries) ? String(queries[0]) : "";
|
||||
return answer(query);
|
||||
};
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "headless",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
return client;
|
||||
};
|
||||
|
||||
describe("headless IDA procedure lookup failures", () => {
|
||||
it.each([
|
||||
["Not found", "procedure_pseudo_code", "main"],
|
||||
["Not found", "procedure_address", "main"],
|
||||
["Not found", "analyze_function", "main"],
|
||||
["Not a function", "procedure_pseudo_code", "main"],
|
||||
["Not a function", "read_function_instructions", "main"],
|
||||
["Not a function", "procedure_pseudo_code", "0x1000"],
|
||||
["Not found", "procedure_assembly", "_missing"],
|
||||
["Not found", "procedure_pseudo_code", "main\nsecond line"],
|
||||
] as const)(
|
||||
"reports the upstream %s answer for %s of %s as an invalid request naming the procedure",
|
||||
async (upstream, operation, procedure) => {
|
||||
const client = await missingProcedureFixture((query) =>
|
||||
lookup(query, null, upstream),
|
||||
);
|
||||
try {
|
||||
const result = await client.execute(operation, { procedure });
|
||||
|
||||
if (result.ok) throw new Error("expected invalid input");
|
||||
expect(result.error._tag, "the caller's procedure is the fault").toBe(
|
||||
"AnalysisInputError",
|
||||
);
|
||||
const projected = projectAnalysisError(result.error);
|
||||
expect(projected.code, "the public code is invalid_request").toBe(
|
||||
"invalid_request",
|
||||
);
|
||||
expect(projected.category, "the category is invalid_input").toBe(
|
||||
"invalid_input",
|
||||
);
|
||||
expect(projected.retryable, "the caller can correct and retry").toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
projected.details,
|
||||
"the operation and exactly one issue that names the procedure in its message",
|
||||
).toEqual({
|
||||
operation,
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: `IDA could not resolve procedure ${JSON.stringify(procedure)}: ${upstream}.`,
|
||||
},
|
||||
],
|
||||
});
|
||||
if (!(result.error instanceof AnalysisInputError))
|
||||
throw new Error("expected an AnalysisInputError");
|
||||
expect(
|
||||
result.error.issues.map(({ message }) => message ?? "").join(""),
|
||||
"a control character in the query is carried JSON-escaped, never raw",
|
||||
).not.toContain("\n");
|
||||
expect(
|
||||
(result.error.cause as Error | undefined)?.message,
|
||||
"the upstream text stays on the retained cause",
|
||||
).toContain(upstream);
|
||||
expect(
|
||||
JSON.stringify(projected).toLowerCase(),
|
||||
"no retry or doctor advice for a caller mistake",
|
||||
).not.toMatch(/doctor|retry once/u);
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["an upstream exception text", lookup("main", null, "Database is closed")],
|
||||
["a function with an error", lookup("main", knownFunction, "Not found")],
|
||||
["neither a function nor an error", lookup("main", null, null)],
|
||||
[
|
||||
"a near-miss spelling of the not-found text",
|
||||
lookup("main", null, "not found"),
|
||||
],
|
||||
[
|
||||
"an exception text that merely contains the not-found text",
|
||||
lookup("main", null, "Database lookup failed: Not found"),
|
||||
],
|
||||
["a padded not-found text", lookup("main", null, " Not found ")],
|
||||
["an empty error", lookup("main", null, "")],
|
||||
["a whitespace-only error", lookup("main", null, " ")],
|
||||
["an answer for a different query", lookup("helper", null, "Not found")],
|
||||
])("keeps %s as unreadable output", async (_label, answer) => {
|
||||
const client = await missingProcedureFixture(() => answer);
|
||||
try {
|
||||
const result = await client.execute("procedure_pseudo_code", {
|
||||
procedure: "main",
|
||||
});
|
||||
|
||||
if (result.ok) throw new Error("expected unreadable output");
|
||||
expect(result.error._tag, "a producer fault, not caller input").toBe(
|
||||
"AnalysisProtocolError",
|
||||
);
|
||||
expect(
|
||||
projectAnalysisError(result.error).code,
|
||||
"unknown beats a wrong fact about the caller's input",
|
||||
).toBe("unreadable_output");
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps an unresolvable callee reported by IDA itself as unreadable output", async () => {
|
||||
const { root, target } = await createIdaTarget();
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "headless");
|
||||
producer.overrideCall = (name, args) => {
|
||||
if (name === "callees")
|
||||
return [
|
||||
{
|
||||
callees: [{ addr: "0x2000", name: "sub_2000", type: "internal" }],
|
||||
more: false,
|
||||
},
|
||||
];
|
||||
if (name !== "lookup_funcs") return undefined;
|
||||
const queries = args.queries;
|
||||
const query = Array.isArray(queries) ? String(queries[0]) : "";
|
||||
return query === "0x2000"
|
||||
? lookup(query, null, "Not a function")
|
||||
: lookup(query, knownFunction, null);
|
||||
};
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "headless",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
try {
|
||||
const result = await client.execute("procedure_callees", {
|
||||
procedure: "main",
|
||||
});
|
||||
|
||||
if (result.ok) throw new Error("expected unreadable output");
|
||||
expect(
|
||||
projectAnalysisError(result.error).code,
|
||||
"an address IDA itself reported is not the caller's mistake",
|
||||
).toBe("unreadable_output");
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-derived procedure selectors", () => {
|
||||
it.each(["Not found", "Not a function"])(
|
||||
"reports a derived selector answered %s as a producer fault",
|
||||
async (upstream) => {
|
||||
const client = await missingProcedureFixture((query) =>
|
||||
lookup(query, null, upstream),
|
||||
);
|
||||
try {
|
||||
const result = await client.execute(
|
||||
"procedure_callees",
|
||||
{ procedure: "0x2000" },
|
||||
{ selectorOrigin: "provider" },
|
||||
);
|
||||
|
||||
if (result.ok) throw new Error("expected a producer fault");
|
||||
expect(result.error._tag, "not the caller's mistake").toBe(
|
||||
"AnalysisProtocolError",
|
||||
);
|
||||
expect(
|
||||
projectAnalysisError(result.error).code,
|
||||
"projected as on main",
|
||||
).toBe("unreadable_output");
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("attached IDA procedure lookup failures", () => {
|
||||
it("leaves a failed legacy lookup as unreadable output", async () => {
|
||||
const { root, target } = await createIdaTarget();
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "attached");
|
||||
producer.overrideCall = (name) =>
|
||||
name === "get_function_by_name" ? null : undefined;
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "attached",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
try {
|
||||
const result = await client.execute("procedure_pseudo_code", {
|
||||
procedure: "main",
|
||||
});
|
||||
|
||||
if (result.ok) throw new Error("expected unreadable output");
|
||||
expect(
|
||||
projectAnalysisError(result.error).code,
|
||||
"the legacy profile keeps its pre-existing classification",
|
||||
).toBe("unreadable_output");
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves an MCP error reply for an unknown legacy name as unreadable output", async () => {
|
||||
const { root, target } = await createIdaTarget();
|
||||
roots.push(root);
|
||||
const producer = new RecordingIdaMcp(target, "attached");
|
||||
producer.beforeCall = async (name) => {
|
||||
if (name === "get_function_by_name")
|
||||
decodeIdaToolResult({
|
||||
content: [{ type: "text", text: "Function not found: main" }],
|
||||
isError: true,
|
||||
});
|
||||
};
|
||||
const client = new IdaSessionClient(
|
||||
{
|
||||
command: "fixture",
|
||||
args: [],
|
||||
env: {},
|
||||
mode: "attached",
|
||||
timeoutMs: 1000,
|
||||
workspaceRoot: root,
|
||||
},
|
||||
target,
|
||||
producer,
|
||||
);
|
||||
try {
|
||||
const result = await client.execute("procedure_pseudo_code", {
|
||||
procedure: "main",
|
||||
});
|
||||
|
||||
if (result.ok) throw new Error("expected unreadable output");
|
||||
expect(
|
||||
result.error._tag,
|
||||
"a producer error reply, not caller input",
|
||||
).toBe("AnalysisProtocolError");
|
||||
expect(
|
||||
projectAnalysisError(result.error).code,
|
||||
"the legacy profile keeps its existing classification",
|
||||
).toBe("unreadable_output");
|
||||
} finally {
|
||||
expect((await client.close()).ok).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -51,6 +51,11 @@ const identity = (fn: IdaFunction) => ({
|
||||
classification: null,
|
||||
body: unknownBody,
|
||||
});
|
||||
/** The only lookup answers upstream reports for a name or address that is not a function. */
|
||||
const MISSING_PROCEDURE_ANSWERS: ReadonlySet<string> = new Set([
|
||||
"Not found",
|
||||
"Not a function",
|
||||
]);
|
||||
const lines = (asm: IdaDisassembly) =>
|
||||
asm.lines.map(({ address, instruction }) => `${address}: ${instruction}`);
|
||||
|
||||
@@ -64,6 +69,7 @@ export class IdaOperationRunner {
|
||||
private readonly protocol: "legacy" | "modern",
|
||||
private readonly database?: string,
|
||||
private readonly signal?: AbortSignal,
|
||||
private readonly selectorOrigin?: "provider",
|
||||
) {}
|
||||
|
||||
async call(
|
||||
@@ -106,11 +112,42 @@ export class IdaOperationRunner {
|
||||
return result;
|
||||
}
|
||||
|
||||
async resolve(query: string): Promise<IdaFunction> {
|
||||
/**
|
||||
* Resolves a procedure. When `requestedBy` names the caller's operation, an
|
||||
* upstream "not found" or "not a function" answer is reported as invalid
|
||||
* input; every other failed lookup stays a producer fault. `run()` passes
|
||||
* `requestedBy` only for caller-supplied selectors. Provider-derived
|
||||
* selectors, such as the addresses composed workflows revisit, and the
|
||||
* callee resolution inside `relationships()` pass none, because those
|
||||
* addresses were reported by IDA itself.
|
||||
*/
|
||||
async resolve(query: string, requestedBy?: string): Promise<IdaFunction> {
|
||||
if (this.protocol === "modern") {
|
||||
const item = modernLookupSchema.parse(
|
||||
await this.call("lookup_funcs", { queries: [query] }),
|
||||
)[0];
|
||||
if (
|
||||
requestedBy !== undefined &&
|
||||
item?.query === query &&
|
||||
item.fn === null &&
|
||||
item.error !== null &&
|
||||
MISSING_PROCEDURE_ANSWERS.has(item.error)
|
||||
)
|
||||
throw new AnalysisInputError(
|
||||
requestedBy,
|
||||
{
|
||||
cause: new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item.error}`,
|
||||
),
|
||||
},
|
||||
[
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: `IDA could not resolve procedure ${JSON.stringify(query)}: ${item.error}.`,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (item?.fn == null || item.error !== null)
|
||||
throw new AnalysisProtocolError(
|
||||
`IDA function lookup failed for ${query}: ${item?.error ?? "missing function"}`,
|
||||
@@ -351,6 +388,7 @@ export class IdaOperationRunner {
|
||||
}
|
||||
const fn = await this.resolve(
|
||||
z.string().min(1).parse(parameters.procedure),
|
||||
this.selectorOrigin === "provider" ? undefined : operation,
|
||||
);
|
||||
this.locations.push({ kind: "address", address: fn.address });
|
||||
switch (operation) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../config/parseConfig.js";
|
||||
import { IdaProvider } from "./IdaProvider.js";
|
||||
|
||||
describe("IDA provider target support", () => {
|
||||
it("declines headerless raw-binary targets", () => {
|
||||
const config = parseConfig({});
|
||||
if (!config.ok) throw new Error("expected valid configuration");
|
||||
const provider = new IdaProvider(config.value, {});
|
||||
expect(
|
||||
provider.inspectTargetSupport({
|
||||
path: "/tmp/ecu.bin",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "raw-binary",
|
||||
architecture: "arm",
|
||||
availableArchitectures: ["arm"],
|
||||
entryPoint: "0x8000000",
|
||||
entryPointSource: "0x8000000",
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
reason: expect.stringContaining("Ghidra"),
|
||||
});
|
||||
});
|
||||
});
|
||||
+17
-9
@@ -109,15 +109,23 @@ export class IdaProvider implements AnalysisProviderCandidate {
|
||||
"REA's IDA adapter has no verified MIPS lane. Select a supported Ghidra profile instead.",
|
||||
diagnostics,
|
||||
};
|
||||
return target.kind === "executable"
|
||||
? { status: "supported", code: null, reason: null, diagnostics }
|
||||
: {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
reason:
|
||||
"IDA MCP integration admits executable inputs, not analysis databases. Select the original input binary.",
|
||||
diagnostics,
|
||||
};
|
||||
if (target.kind !== "executable")
|
||||
return {
|
||||
status: "unsupported",
|
||||
code: "target_kind_unsupported",
|
||||
reason:
|
||||
"IDA MCP integration admits executable inputs, not analysis databases. Select the original input binary.",
|
||||
diagnostics,
|
||||
};
|
||||
if (target.format === "raw-binary")
|
||||
return {
|
||||
status: "unsupported",
|
||||
code: "target_format_unsupported",
|
||||
reason:
|
||||
"IDA does not admit headerless raw binaries. Open the target with Ghidra and supply architecture and entry_point.",
|
||||
diagnostics,
|
||||
};
|
||||
return { status: "supported", code: null, reason: null, diagnostics };
|
||||
}
|
||||
async resolveAnalysisProfile(
|
||||
_target: BinaryTarget,
|
||||
|
||||
@@ -192,12 +192,7 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
throw new AnalysisProtocolError(
|
||||
"IDA operation changed after validation.",
|
||||
);
|
||||
const runner = new IdaOperationRunner(
|
||||
this.connection,
|
||||
this.config.mode === "attached" ? "legacy" : "modern",
|
||||
this.#database,
|
||||
options?.signal,
|
||||
);
|
||||
const runner = this.#runner(options);
|
||||
const result = await runner.run(operation, parameters);
|
||||
if (wasCancelled(options))
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
@@ -227,6 +222,16 @@ export class IdaSessionClient implements AnalysisClient {
|
||||
}
|
||||
}
|
||||
|
||||
#runner(options: ExecutionOptions | undefined): IdaOperationRunner {
|
||||
return new IdaOperationRunner(
|
||||
this.connection,
|
||||
this.config.mode === "attached" ? "legacy" : "modern",
|
||||
this.#database,
|
||||
options?.signal,
|
||||
options?.selectorOrigin,
|
||||
);
|
||||
}
|
||||
|
||||
#health(metadata: JsonValue) {
|
||||
return ok(
|
||||
createAnalysisExecution(
|
||||
|
||||
@@ -22,8 +22,10 @@ export const mcpProgressReporter = (
|
||||
method: "notifications/progress",
|
||||
params: {
|
||||
progressToken: token,
|
||||
progress: update.completed,
|
||||
...(update.total === null ? {} : { total: update.total }),
|
||||
// Status phases can repeat their work count while waiting. The
|
||||
// protocol requires every notification to advance; count emitted
|
||||
// observations without inventing a total amount of analysis work.
|
||||
progress: update.sequence,
|
||||
message: `${update.phase}: ${update.message}`,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ProcessCaptureResourceScope } from "../process/capture/ProcessCaptureLi
|
||||
import { ProcessCaptureError } from "../process/capture/ProcessCaptureError.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import { binaryTargetSummary } from "../application/binary/BinaryTargetSummary.js";
|
||||
import { UnknownRegistryError } from "../domain/unknownRegistryError.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
@@ -203,6 +204,12 @@ const registerOpenLifecycleTool = ({
|
||||
session.open(input.path, {
|
||||
signal: context.mcpReq.signal,
|
||||
...(input.format === undefined ? {} : { formatHint: input.format }),
|
||||
...(input.architecture === undefined
|
||||
? {}
|
||||
: { architecture: input.architecture }),
|
||||
...(input.entry_point === undefined
|
||||
? {}
|
||||
: { entryPoint: input.entry_point }),
|
||||
...(input.provider_id === undefined
|
||||
? {}
|
||||
: { providerId: input.provider_id }),
|
||||
@@ -213,13 +220,7 @@ const registerOpenLifecycleTool = ({
|
||||
? server.delivery.toCallToolResult(
|
||||
{
|
||||
ok: true,
|
||||
value: {
|
||||
path: opened.value.path,
|
||||
format: opened.value.format,
|
||||
kind: opened.value.kind,
|
||||
sha256: opened.value.sha256,
|
||||
architecture: opened.value.architecture ?? null,
|
||||
},
|
||||
value: binaryTargetSummary(opened.value),
|
||||
},
|
||||
openContract,
|
||||
)
|
||||
|
||||
@@ -67,8 +67,10 @@ describe("derived MCP operation boundary", () => {
|
||||
);
|
||||
|
||||
expect(result).toEqual({ ok: true, value: "complete" });
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([0, 2]);
|
||||
expect(notifications.every(({ params }) => params?.total === 2)).toBe(true);
|
||||
expect(notifications.map(({ params }) => params?.progress)).toEqual([1, 2]);
|
||||
expect(
|
||||
notifications.every(({ params }) => params?.total === undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("projects synchronous computation failures into a typed result", async () => {
|
||||
|
||||
Reference in New Issue
Block a user