feat: evolve REA analysis platform

This commit is contained in:
morluto
2026-07-12 19:32:13 +08:00
parent 1f235cb52f
commit 4f18e26ee5
47 changed files with 1841 additions and 334 deletions
+37
View File
@@ -0,0 +1,37 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type { AnalysisError } from "../domain/errors.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Result } from "../domain/result.js";
export interface ExecutionOptions {
readonly signal?: AbortSignal;
}
/** Provider-neutral application capability for one analysis operation. */
export interface AnalysisOperationPort {
execute(
operation: string,
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
): Promise<Result<JsonValue, AnalysisError>>;
}
/** Provider session bound to exactly one parsed artifact. */
export interface AnalysisClient extends AnalysisOperationPort {
close(): Promise<void>;
}
export type AnalysisClientFactory = (target: BinaryTarget) => AnalysisClient;
export interface ProviderIdentity {
readonly id: string;
readonly name: string;
readonly version: string | null;
}
/** Factory and capability declaration for an analysis implementation. */
export interface AnalysisProvider {
identity(): ProviderIdentity;
capabilities(): readonly string[];
createClient(target: BinaryTarget): AnalysisClient;
}
+47 -21
View File
@@ -3,18 +3,30 @@ import { parseBinaryTarget } from "../domain/binaryTarget.js";
import {
HopperCancelledError,
NoBinaryOpenError,
type HopperError,
type AnalysisError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { HopperToolPort } from "./HopperToolPort.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type {
AnalysisClient,
AnalysisClientFactory,
AnalysisOperationPort,
AnalysisProvider,
} from "./AnalysisProvider.js";
/** A closeable Hopper port created for exactly one parsed target. */
export interface BinaryClient extends HopperToolPort {
close(): Promise<void>;
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
export interface BinarySessionPort extends AnalysisOperationPort {
open(
path: string,
options?: {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
},
): Promise<Result<BinaryTarget, AnalysisError>>;
close(): Promise<Result<null, AnalysisError>>;
status(): JsonValue;
activeTarget(): BinaryTarget | undefined;
}
/** Production seam for creating one unstarted client for a parsed target. */
export type BinaryClientFactory = (target: BinaryTarget) => BinaryClient;
/**
* Owns the single active target shared by CLI and MCP adapters.
@@ -24,13 +36,20 @@ export type BinaryClientFactory = (target: BinaryTarget) => BinaryClient;
* down. A failed switch recreates the previous target instead of retaining a
* client whose bridge was already shut down.
*/
export class BinarySession implements HopperToolPort {
export class BinarySession implements BinarySessionPort {
#active:
| { readonly target: BinaryTarget; readonly client: BinaryClient }
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
| undefined;
#transition: Promise<void> = Promise.resolve();
readonly #calls = new Set<Promise<unknown>>();
constructor(readonly createClient: BinaryClientFactory) {}
readonly #createClient: AnalysisClientFactory;
constructor(readonly provider: AnalysisProvider | AnalysisClientFactory) {
this.#createClient =
typeof provider === "function"
? provider
: (target) => provider.createClient(target);
}
/**
* Open or switch targets after draining calls against the current target.
@@ -42,7 +61,7 @@ export class BinarySession implements HopperToolPort {
readonly signal?: AbortSignal;
readonly targetKind?: BinaryTarget["kind"];
} = {},
): Promise<Result<BinaryTarget, HopperError>> {
): Promise<Result<BinaryTarget, AnalysisError>> {
return this.#serialize(async () => {
if (isAborted(options.signal)) return err(new HopperCancelledError());
const parsed = await parseBinaryTarget(
@@ -59,8 +78,8 @@ export class BinarySession implements HopperToolPort {
const previous = this.#active;
this.#active = undefined;
await previous?.client.close();
const client = this.createClient(parsed.value);
const started = await client.callTool("health", {}, options);
const client = this.#createClient(parsed.value);
const started = await client.execute("health", {}, options);
if (!started.ok) {
await client.close();
await this.#restore(previous);
@@ -77,7 +96,7 @@ export class BinarySession implements HopperToolPort {
}
/** Close the active target, if any. */
close(): Promise<Result<null, HopperError>> {
close(): Promise<Result<null, AnalysisError>> {
return this.#serialize(async () => {
const previous = this.#active;
this.#active = undefined;
@@ -95,26 +114,33 @@ export class BinarySession implements HopperToolPort {
: {
open: true,
path: target.path,
sha256: target.sha256,
format: target.format,
kind: target.kind,
architecture: target.architecture ?? null,
};
}
/** Return the immutable artifact identity captured before Hopper launched. */
activeTarget(): BinaryTarget | undefined {
return this.#active?.target;
}
/**
* Invoke a Hopper tool against the active target.
* Calls may overlap, but a pending target transition prevents new calls from
* entering until the transition has settled.
*/
async callTool(
async execute(
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
): Promise<Result<JsonValue, HopperError>> {
): Promise<Result<JsonValue, AnalysisError>> {
const transitioned = await this.#waitForTransition(options?.signal);
if (!transitioned.ok) return transitioned;
const active = this.#active;
if (active === undefined) return err(new NoBinaryOpenError());
const call = active.client.callTool(name, arguments_, options);
const call = active.client.execute(name, arguments_, options);
this.#calls.add(call);
try {
return await call;
@@ -138,12 +164,12 @@ export class BinarySession implements HopperToolPort {
async #restore(
previous:
| { readonly target: BinaryTarget; readonly client: BinaryClient }
| { readonly target: BinaryTarget; readonly client: AnalysisClient }
| undefined,
): Promise<void> {
if (previous === undefined) return;
const client = this.createClient(previous.target);
const started = await client.callTool("health", {});
const client = this.#createClient(previous.target);
const started = await client.execute("health", {});
if (started.ok) this.#active = { target: previous.target, client };
else await client.close();
}
+8 -3
View File
@@ -1,7 +1,8 @@
import { parseConfig } from "../config.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { createBinarySession } from "./runtime.js";
import { silentLogger, type Logger } from "../logger.js";
import { createEvidence } from "../domain/evidence.js";
/**
* Open one binary, execute one tool, and always release the bridge session.
@@ -22,9 +23,13 @@ export const runDirectAnalysis = async (
const opened = await session.open(path);
if (!opened.ok)
return { error: opened.error._tag, message: opened.error.message };
const result = await session.callTool(tool, arguments_);
const result = await session.execute(tool, arguments_);
return result.ok
? result.value
? createEvidence(opened.value, {
operation: tool,
parameters: arguments_,
result: result.value,
})
: { error: result.error._tag, message: result.error.message };
} finally {
await session.close();
+176 -8
View File
@@ -1,7 +1,7 @@
import type { HopperToolPort } from "./HopperToolPort.js";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { HopperProtocolError, type HopperError } from "../domain/errors.js";
import { AnalysisProtocolError, type AnalysisError } from "../domain/errors.js";
import {
parseDocuments,
parseAddressedPage,
@@ -16,9 +16,15 @@ import {
discoverObjcProtocols,
discoverSwiftClasses,
} from "../domain/symbolAnalysis.js";
import type { JsonValue } from "../hopper/protocol.js";
import type { JsonValue } from "../domain/jsonValue.js";
type EnhancedResult = Promise<Result<JsonValue, HopperError>>;
type EnhancedResult = Promise<Result<JsonValue, AnalysisError>>;
type TraceMatch = { type: string; address: string; value: string };
type TraceReference = {
target_address: string;
source_address: string;
containing_procedure: JsonValue;
};
/**
* Composes official Hopper operations into bounded reverse-engineering tools.
@@ -26,7 +32,7 @@ type EnhancedResult = Promise<Result<JsonValue, HopperError>>;
* validates them, allowing direct callers to use the same service safely.
*/
export class EnhancedTools {
constructor(private readonly hopper: HopperToolPort) {}
constructor(private readonly analysis: AnalysisOperationPort) {}
/** Parse inputs again at the direct-call boundary, then dispatch exhaustively. */
execute(
@@ -81,6 +87,12 @@ export class EnhancedTools {
? this.#call("analyze_function", parsed.data, signal)
: invalidInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.#traceFeature(parsed.data, signal)
: invalidInput(name, parsed.error);
}
}
}
@@ -253,6 +265,155 @@ export class EnhancedTools {
});
}
async #traceFeature(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): EnhancedResult {
const searched = await this.#literalMatches(input, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await this.#traceReferences(
searched.value.matches,
input.limit,
input.max_operations - searched.value.operations,
signal,
);
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
}
async #literalMatches(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive
? input.query
: input.query.toLowerCase();
for (const [tool, type] of [
["list_strings", "string"],
["list_procedures", "procedure"],
] as const) {
let offset = 0;
while (
operations < input.max_operations &&
matches.length < input.limit
) {
operations += 1;
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
}
async #traceReferences(
matches: readonly TraceMatch[],
limit: number,
operationBudget: number,
signal?: AbortSignal,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of matches) {
if (operations >= operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await this.#call(
"xrefs",
{ address: match.address },
signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisProtocolError("xrefs returned a non-array result"),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisProtocolError("xrefs returned a non-address value"),
);
if (operations >= operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await this.#call(
"resolve_containing_procedure",
{ address: source },
signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
}
async #allProcedures(signal?: AbortSignal) {
return this.#allAddressed("list_procedures", signal);
}
@@ -272,6 +433,13 @@ export class EnhancedTools {
if (!page.value.hasMore || page.value.nextOffset === null) {
return ok(entries);
}
if (page.value.nextOffset <= offset) {
return err(
new AnalysisProtocolError(
`${tool} returned a non-advancing pagination offset`,
),
);
}
offset = page.value.nextOffset;
}
}
@@ -280,8 +448,8 @@ export class EnhancedTools {
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<JsonValue, HopperError>> {
return this.hopper.callTool(
): Promise<Result<JsonValue, AnalysisError>> {
return this.analysis.execute(
name,
arguments_,
signal === undefined ? {} : { signal },
@@ -292,7 +460,7 @@ export class EnhancedTools {
const invalidInput = (name: EnhancedToolName, cause: Error): EnhancedResult =>
Promise.resolve(
err(
new HopperProtocolError(`Invalid ${name} input after MCP validation`, {
new AnalysisProtocolError(`Invalid ${name} input after MCP validation`, {
cause,
}),
),
-17
View File
@@ -1,17 +0,0 @@
import type { HopperError } from "../domain/errors.js";
import type { Result } from "../domain/result.js";
import type { JsonValue } from "../hopper/protocol.js";
/** Application-owned capability for invoking one official Hopper tool. */
export interface HopperToolPort {
/**
* Invoke a declared bridge operation with JSON-safe arguments.
* Implementations return expected Hopper, timeout, and cancellation failures
* as values and must honor an already-aborted signal.
*/
callTool(
name: string,
arguments_: Readonly<Record<string, JsonValue>>,
options?: { readonly signal?: AbortSignal },
): Promise<Result<JsonValue, HopperError>>;
}
+2 -23
View File
@@ -1,9 +1,6 @@
import { fileURLToPath } from "node:url";
import type { AppConfig } from "../config.js";
import { BinarySession } from "./BinarySession.js";
import { HopperApplicationLauncher } from "../hopper/BridgeLauncher.js";
import { HopperClient } from "../hopper/HopperClient.js";
import { HopperProvider } from "../hopper/HopperProvider.js";
import { silentLogger, type Logger } from "../logger.js";
/**
@@ -15,23 +12,5 @@ export const createBinarySession = (
config: AppConfig,
logger: Logger = silentLogger,
): BinarySession => {
const bridgeScriptPath = fileURLToPath(
new URL("../../bridge/hopper_bridge.py", import.meta.url),
);
return new BinarySession(
(target) =>
new HopperClient({
launcher: new HopperApplicationLauncher({
launcherPath: config.hopperLauncherPath,
targetPath: target.path,
targetKind: target.kind,
loaderArgs:
config.hopperLoaderArgs.length > 0
? config.hopperLoaderArgs
: target.loaderArgs,
bridgeScriptPath,
}),
logger: logger.child({ layer: "bridge" }),
}),
);
return new BinarySession(new HopperProvider(config, logger));
};