Files
reverse-engineering-anything/src/application/DirectAnalysis.ts
T
morluto cab39c640a fix(native)!: resolve name and import selectors through one owner (#14250)
* fix(native)!: resolve name and import selectors through one owner

find_xrefs_to_name matched names exactly against list_names, while
procedure_callers and procedure_references used each provider's own
procedure lookup. One import selector therefore resolved differently per
tool, and each tool failed on a different provider. Hopper also refused
every target outside a procedure, so it could not answer incoming
references to an import.

- NativeSymbolSelection owns name resolution for find_xrefs_to_name, xrefs
  and the incoming procedure tools: exact name, then a provider-reported
  external import by imported or library-qualified name, then the
  provider's procedure lookup. CLI and MCP both run through it.
- When a provider refuses a name for xrefs, procedure_callers or incoming
  procedure_references, REA resolves it once and asks again by address.
- The Ghidra and Hopper bridges answer an explicit address outside every
  procedure (an import slot, imported name or data label) with its recorded
  references and their containing procedures.
- XrefsAddressResolution is removed.

BREAKING CHANGE: procedure_references.procedure may now identify an address
outside every procedure, with classification null and an unavailable body.
find_xrefs_to_name adds resolved_name and candidates, and resolves bare
import names on Ghidra.

Fixes #14160
Fixes #14184

* fix(native): order selector candidates by code point

The domain ordering rule forbids localeCompare.

* fix(native): retry only names outside every procedure and keep retry facts

- Answer a refused name by address only when the provider observes that
  address outside every procedure. An interior label stays refused instead
  of selecting its containing procedure.
- Return a retry's own failure unless it is another lookup miss.
- Retain Hopper's native address-target reply as raw Evidence, with its
  target identity and caller completeness.

* fix(native): retry at exact procedure entries and return containment failures

- An import resolved to a procedure's exact entry, such as Ghidra's external
  function for kernel32.dll::VirtualAlloc, is answered by that address;
  only an address strictly inside a procedure keeps the refusal.
- A containment lookup that fails for any reason other than the provider
  lacking it is returned with its facts instead of the name refusal.

* test(ida): answer unknown names as Not found in the verifier fixture

The verifier's fake IDA resolved every lookup_funcs query to main. With
xrefs names now resolved by the shared selector owner, an unknown name
such as not-an-address reaches the provider's procedure lookup, which the
fake answered with main, so xrefs succeeded instead of the expected
invalid_request. Real IDA answers an unknown name with "Not found"; the
fixture now does too, and the verifier's contract is unchanged.

* fix(native): keep provider ambiguity and declare the procedure-lookup fallback

- The Ghidra bridge sends every matching entry of an ambiguous procedure
  selector as structured candidates. The projection carries them as the
  typed ambiguous-selector refusal, and the shared owner no longer treats
  an ambiguous lookup as a missing name, so find_xrefs_to_name returns the
  ambiguity with its candidates.
- find_xrefs_to_name requires list_names or procedure_address, plus xrefs,
  so providers without a name inventory, such as IDA and Kuna, report it as
  available with the effects of the calls it makes.

* fix(native): answer a provider-ambiguous name by its unique exact name

Ghidra's procedure lookup matches leaf names, so a global work and ns::work
make work ambiguous, while the shared owner resolves the exact name work.
When the provider reports an ambiguity, the shared owner now retries only by
a unique exact-name match and otherwise keeps the provider's ambiguity and
candidates.

* fix(native): resolve incoming procedure names through the shared owner first

procedure_callers and incoming procedure_references asked the provider by
name first, so Ghidra's leaf-name lookup could answer "work" with ns::work
while find_xrefs_to_name selected the exact label work. These tools now
resolve the name with the shared owner first and ask the provider by its
address when that address is outside every procedure or a procedure's exact
entry. A name the owner cannot resolve, or one inside a procedure, still goes
to the provider's procedure lookup, which owns alias and thunk spellings.
xrefs keeps provider-first resolution.

* fix(native): retain snapshot replay for resolved symbol selectors
2026-11-24 15:23:06 +00:00

969 lines
34 KiB
TypeScript

import {
admitOneShotOperation,
type DirectAnalysisTool,
type DirectEnhancedToolName,
} from "./oneShotOperationInput.js";
import { completedOperationEvidence } from "./binary/SessionEvidenceReuse.js";
import type { EspFlashSelection } from "../domain/firmware/espFlashLocation.js";
import { dispatchQueuedInterrupts } from "../process/queuedInterrupts.js";
import type { BinaryTarget } from "../domain/binaryTargetTypes.js";
import type { NativeLoadSelection } from "../domain/rawBinary.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { DirectAnalysisDependencies } from "./DirectAnalysisDependencies.js";
import type { BinarySession } from "./binary/BinarySession.js";
import type { SessionProviderRoute } from "./binary/SessionProviderRouter.js";
import {
routeAllowsSnapshotReplay,
routeProviderIdentity,
} from "./binary/SessionProviderPolicy.js";
import type { ResolvedSessionOpen } from "./binary/BinarySessionOpen.js";
import { silentLogger } from "../logger.js";
import type { Logger } from "pino";
import { withEvidenceCallerInputPath } from "../domain/evidence.js";
import { createImmutableEvidenceBundle } from "../domain/evidenceBundle.js";
import { recognizeEvidence } from "../domain/evidenceValidation.js";
import {
retainAnalysisResultSources,
type AnalysisResultWithSources,
} from "./investigation/recordEvidenceSources.js";
import {
createInvestigationEvidenceClosureChecker,
collectInvestigationEvidenceClosure,
} from "./investigation/InvestigationEvidence.js";
import type { Evidence } from "../domain/evidence.js";
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
import {
ARTIFACT_ANALYSIS_OPERATIONS,
type ArtifactAnalysisOperation,
} from "../contracts/artifactToolContracts.js";
import {
isManagedToolName,
type ManagedToolName,
} from "../contracts/managed/managedToolContracts.js";
import {
EvidenceFileError,
AnalysisSnapshotMismatchError,
type PublishedEvidenceFile,
} from "../domain/evidenceErrors.js";
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { access, stat } from "node:fs/promises";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import {
requestsStandaloneDecompile,
requiresNativeSourceAdmissionBeforeReplay,
} from "./binary/AnalysisSnapshotCache.js";
import {
snapshotBindingMismatch,
snapshotEvidenceForQuery,
} from "../domain/analysisSnapshot.js";
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import { profilelessNativeDispatchProfile } from "./binary/ProfilelessNativeWorkflowSnapshot.js";
import { err, ok, type Result } from "../domain/result.js";
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
import type { AnalysisExecution } from "../ports/AnalysisProvider.js";
import { createAnalysisExecutionEvidence } from "../domain/analysisObservation.js";
import { REA_WORKFLOW_PROVIDER } from "../domain/investigationProviders.js";
import { workflowAnalysisProfile } from "./WorkflowAnalysisProfile.js";
import {
composedLimitationBudget,
executeComposedWorkflow,
createWorkflowEvidence,
retainPartialWorkflowEvidence,
workflowSnapshotRecord,
recordWorkflowUnknowns,
} from "./WorkflowEvidence.js";
import type { AnalysisProviderSelector } from "../domain/providerSelection.js";
import { executeWithNativeSymbolSelection } from "./NativeSymbolSelection.js";
import { cancelledBy, CallerAbort } from "../domain/analysisErrorCore.js";
import type { BinaryTargetError } from "../domain/configurationErrors.js";
import {
directAnalysisCleanupFailure,
projectDirectAnalysisFailure,
projectInvocationFailure,
managedAnalysisCleanupFailure,
withSessionCleanup,
} from "./DirectAnalysisCleanup.js";
import { completeProviderEvidence } from "./ProviderOperationExecution.js";
import { BUNDLE_RESOURCE_OPERATIONS } from "../ports/BundleResourceOperations.js";
import { classifyBinaryTargetFilesystemFailure } from "../domain/binaryTargetFilesystemFailure.js";
// These one-shot CLI questions require native utilities, not a deep engine.
// Runtime observation retains the ordinary session and authority checks.
const NATIVE_INSPECTION_OPERATIONS: ReadonlySet<string> = new Set([
"inspect_macho",
"inspect_signature",
"list_architectures",
"inspect_plist",
"demangle_swift",
] satisfies readonly NativeToolName[]);
const ARTIFACT_ANALYSIS_OPERATION_SET: ReadonlySet<string> = new Set(
ARTIFACT_ANALYSIS_OPERATIONS,
);
/**
* Open one binary, execute one tool, and always release provider resources.
* Unlike MCP mode, every CLI invocation is intentionally isolated and does not
* retain a target, provider session or runtime setting for a subsequent
* command. Failures are projected for that invocation lifetime, so they never
* offer same-session reuse or runtime updates; a new invocation's launch
* environment or arguments carry any changed limit.
*/
export const runDirectAnalysis = async (
dependencies: DirectAnalysisDependencies,
path: string,
tool: DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
options: {
readonly logger?: Logger;
readonly snapshotPath?: string | undefined;
readonly signal?: AbortSignal;
readonly providerId?: AnalysisProviderSelector;
readonly loadSelection?: NativeLoadSelection;
readonly espFlash?: EspFlashSelection;
readonly includeEvidenceSources?: boolean;
} = {},
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> =>
withProcessCancellation(options.signal, (signal) => {
const admitted = admitOneShotOperation(tool, arguments_, signal);
if (!admitted.ok)
return Promise.resolve(err(cliError(admitted.error, path)));
return runAnalysis(
dependencies,
path,
admitted.value.name,
admitted.value.input,
{
evidenceParameters: arguments_,
logger: options.logger ?? silentLogger,
snapshotPath: options.snapshotPath,
signal,
...(options.includeEvidenceSources === true
? { includeEvidenceSources: true }
: {}),
...targetSelection(options),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
},
);
});
/** How the caller asks an artifact target to be read. */
export interface ArtifactTargetSelection {
readonly loadSelection?: NativeLoadSelection;
readonly espFlash?: EspFlashSelection;
}
/** The caller's target interpretation, forwarded unchanged to every open. */
const targetSelection = (options: {
readonly loadSelection?: NativeLoadSelection;
readonly espFlash?: EspFlashSelection;
}) => ({
...(options.loadSelection === undefined
? {}
: { loadSelection: options.loadSelection }),
...(options.espFlash === undefined ? {} : { espFlash: options.espFlash }),
});
/** Execute one provider-native semantic operation with atomic provenance. */
export const runProviderAnalysis = async (
dependencies: DirectAnalysisDependencies,
...[path, tool, arguments_, logger = silentLogger, signal, selection]:
| readonly [
path: string,
tool: NativeToolName | ArtifactAnalysisOperation | ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
logger?: Logger | undefined,
signal?: AbortSignal | undefined,
]
| readonly [
path: string,
tool: ArtifactAnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
logger: Logger | undefined,
signal: AbortSignal | undefined,
selection: ArtifactTargetSelection,
]
): Promise<Result<Evidence, JsonValue>> =>
withProcessCancellation(signal, async (operationSignal) => {
// Preserve the selected path and original arguments as request facts.
const evidenceParameters = { ...arguments_, input_path: path };
if (isManagedToolName(tool)) {
const evidence = await managedCallerEvidence(
dependencies,
path,
tool,
arguments_,
operationSignal,
);
// Completed Evidence already carries the caller's path.
return evidence.ok ? evidence : err(cliError(evidence.error, path));
}
const admitted = admitOneShotOperation(tool, arguments_, operationSignal);
if (!admitted.ok) return err(cliError(admitted.error, path));
return runAnalysis(
dependencies,
path,
admitted.value.name,
admitted.value.input,
{
logger,
snapshotPath: undefined,
signal: operationSignal,
evidenceParameters,
...targetSelection(selection ?? {}),
...(ARTIFACT_ANALYSIS_OPERATION_SET.has(tool)
? { createSession: dependencies.createArtifactBinarySession }
: NATIVE_INSPECTION_OPERATIONS.has(tool)
? { createSession: dependencies.createNativeBinarySession }
: {}),
},
);
});
/**
* Run one managed operation on a caller-selected path, keeping its typed
* failure so a composed command can retain earlier Evidence beside it.
*/
export const runManagedProviderEvidence = (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> =>
withProcessCancellation(signal, (operationSignal) =>
managedCallerEvidence(
dependencies,
path,
tool,
arguments_,
operationSignal,
),
);
/** Managed Evidence bound to the caller's path and its request facts. */
const managedCallerEvidence = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
operationSignal: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> => {
// Preserve the selected path and original arguments as request facts.
const original = await runManagedProviderAnalysis(
dependencies,
path,
tool,
arguments_,
{ ...arguments_, input_path: path },
operationSignal,
);
await dispatchQueuedInterrupts();
if (!original.ok)
return err(retainFinalCancellation(original.error, tool, operationSignal));
const evidence = withEvidenceCallerInputPath(original.value, path);
if (operationSignal.aborted)
return err(
cancelledBy(tool, operationSignal, {
partialObservation: evidence,
}),
);
return ok(evidence);
};
/** Execute managed metadata inspection in an isolated managed-only session. */
export const runManagedProviderExecution = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
signal?: AbortSignal,
parameters: Readonly<Record<string, JsonValue>> = {},
recoveryParameters?: Readonly<Record<string, JsonValue>>,
): Promise<Result<AnalysisExecution, AnalysisError>> =>
withProcessCancellation(signal, async (operationSignal) => {
const admitted = admitOneShotOperation(tool, parameters, operationSignal);
if (!admitted.ok) return admitted;
const session = await dependencies.createManagedBinarySession();
return withSessionCleanup(
session,
async () => {
const opened = await session.open(path, { signal: operationSignal });
if (!opened.ok) return opened;
return recoveryParameters === undefined ||
session.executeForDirectObservation === undefined
? await session.execute(admitted.value.name, admitted.value.input, {
signal: operationSignal,
})
: await session.executeForDirectObservation(
admitted.value.name,
admitted.value.input,
recoveryParameters,
{ signal: operationSignal },
);
},
managedAnalysisCleanupFailure,
);
});
/** Preserve typed managed Evidence before selecting its CLI delivery. */
const runManagedProviderAnalysis = async (
dependencies: Pick<DirectAnalysisDependencies, "createManagedBinarySession">,
path: string,
tool: ManagedToolName,
arguments_: Readonly<Record<string, JsonValue>>,
evidenceParameters: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
): Promise<Result<Evidence, AnalysisError>> => {
const execution = await runManagedProviderExecution(
dependencies,
path,
tool,
signal,
arguments_,
evidenceParameters,
);
if (!execution.ok) return execution;
const value = execution.value;
return ok(
createAnalysisExecutionEvidence(
tool,
evidenceParameters,
value,
"observed",
{ immutable: true },
),
);
};
const runAnalysis = async (
dependencies: DirectAnalysisDependencies,
path: string,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
arguments_: Readonly<Record<string, JsonValue>>,
options: {
readonly logger: Logger;
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
readonly evidenceParameters?: Readonly<Record<string, JsonValue>>;
readonly createSession?: () => BinarySession | Promise<BinarySession>;
readonly includeEvidenceSources?: boolean;
readonly providerId?: AnalysisProviderSelector;
readonly loadSelection?: NativeLoadSelection;
readonly espFlash?: EspFlashSelection;
},
): Promise<AnalysisResultWithSources<Evidence, JsonValue>> => {
const { logger, signal, snapshotPath } = options;
const evidenceParameters = options.evidenceParameters ?? arguments_;
let session: BinarySession;
if (options.createSession !== undefined) {
session = await options.createSession();
} else {
const config = dependencies.readConfiguration();
if (!config.ok) return err(cliError(config.error));
session = await (
tool === "inspect_native_dispatch_metadata" && snapshotPath === undefined
? dependencies.createNativeDispatchBinarySession
: dependencies.createBinarySession
)(config.value, logger);
}
let publishedSnapshot: PublishedEvidenceFile | undefined;
let sourceEvidence: readonly Evidence[] | undefined;
const captureSources = (
evidence: Evidence,
supplied: readonly Evidence[] = [],
): Result<null, AnalysisError> => {
if (!options.includeEvidenceSources) return ok(null);
const records = new Map(
supplied.map((record) => [record.evidence_id, record]),
);
const collected = collectInvestigationEvidenceClosure(
{
evidenceForAnalysis: (id) =>
records.get(id) ?? session.evidenceForAnalysis(id),
},
evidence.evidence_links,
);
sourceEvidence = collected.records;
return collected.result;
};
const execute = async (): Promise<Result<Evidence, AnalysisError>> => {
let isDirectory = false;
if (BUNDLE_RESOURCE_OPERATIONS.has(tool)) {
const inspected = await inspectBundleResourceInput(path);
if (!inspected.ok) return inspected;
isDirectory = inspected.value;
}
if (BUNDLE_RESOURCE_OPERATIONS.has(tool) && isDirectory) {
const opened = await session.openBundleResources(path, { signal });
if (!opened.ok) return opened;
const execution = await session.execute(tool, arguments_, { signal });
if (!execution.ok) return execution;
return ok(
withEvidenceCallerInputPath(
createAnalysisExecutionEvidence(
tool,
evidenceParameters,
execution.value,
"observed",
),
path,
),
);
}
const prepared = await prepareSnapshot({
session,
path,
snapshotPath,
signal,
...targetSelection(options),
});
if (!prepared.ok) return prepared;
const { snapshot } = prepared.value;
let resolvedTarget: ResolvedSessionOpen | undefined;
if (snapshot !== undefined && prepared.value.target !== undefined) {
const preview = await session.previewTarget(prepared.value.target, {
signal,
snapshot,
...targetSelection(options),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
});
if (!preview.ok) return preview;
resolvedTarget = preview.value;
const route = preview.value.route;
const bindingProfile =
route.profile ?? nativeDispatchBindingProfile(route, tool);
const evidenceProfile = analysisProfileForRoute(route, tool);
// A parsed Windows path does not prove Ghidra's native snapshot owner
// admitted the selected source; CLI replay must wait for that client.
if (
bindingProfile !== undefined &&
evidenceProfile !== undefined &&
!requiresNativeSourceAdmissionBeforeReplay(
route.binding?.identity.id,
) &&
tool !== "trace_native_ui_action" &&
tool !== "decompile_all" &&
!requestsStandaloneDecompile(tool, arguments_) &&
routeAllowsSnapshotReplay(route, tool)
) {
const cached = snapshotEvidenceForQuery(snapshot, {
target: preview.value.target,
bindingProfile,
operation: tool,
parameters: arguments_,
provider: isWorkflowEvidenceTool(tool)
? REA_WORKFLOW_PROVIDER
: routeProviderIdentity(route, tool),
evidenceProfile,
});
if (cached !== undefined) {
const records = new Map(
snapshot.evidence_bundle.records.map((record) => [
record.evidence_id,
record,
]),
);
const checkClosure = createInvestigationEvidenceClosureChecker({
evidenceForAnalysis: (id) => records.get(id),
});
if (checkClosure(cached.evidence_links)) {
const evidence = withEvidenceCallerInputPath(cached, path);
const captured = captureSources(
evidence,
snapshot.evidence_bundle.records,
);
if (!captured.ok)
return err(captured.error.retainPartialObservation(evidence));
return ok(evidence);
}
}
}
}
const openOptions = {
signal,
...targetSelection(options),
...(snapshot === undefined ? {} : { snapshot }),
...(options.providerId === undefined
? {}
: { providerId: options.providerId }),
};
const opened =
resolvedTarget === undefined
? await session.open(path, openOptions)
: await session.openResolvedTarget(resolvedTarget, openOptions);
if (!opened.ok) return opened;
const evidenceProfile = analysisProfileForEvidence(session, tool);
const executed = await executeAnalysisTool({
session,
openedTarget: opened.value,
tool,
arguments: arguments_,
evidenceParameters,
signal,
evidenceProfile,
saveSnapshot: snapshotPath !== undefined,
});
if (!executed.ok) {
if (options.includeEvidenceSources) {
const partial = recognizeEvidence(executed.error.partialObservation);
if (!partial.ok) executed.error.retainSecondaryFailure(partial.error);
else if (partial.value !== undefined) {
const captured = captureSources(partial.value);
if (!captured.ok)
executed.error.retainSecondaryFailure(captured.error);
}
}
return executed;
}
const { cachePolicy } = executed.value;
const evidence = withEvidenceCallerInputPath(executed.value.evidence, path);
// Provider execution may have already recorded the same semantic Evidence
// without this invocation's request path. Import replaces that metadata
// while retaining the authenticated result and snapshot binding.
const captured = captureSources(evidence);
if (!captured.ok)
return err(captured.error.retainPartialObservation(evidence));
const recorded = session.importEvidenceBundle(
createImmutableEvidenceBundle([evidence]),
);
if (!recorded.ok)
return err(recorded.error.retainPartialObservation(evidence));
if (isWorkflowEvidenceTool(tool)) {
const unknowns = recordWorkflowUnknowns({
name: tool,
result: evidence.normalized_result,
evidenceId: evidence.evidence_id,
recordUnknown: (unknown) => session.recordUnknown(unknown),
evidenceRetained: true,
});
if (!unknowns.ok)
return err(unknowns.error.retainPartialObservation(evidence));
}
if (
isWorkflowEvidenceTool(tool) &&
tool !== "trace_native_ui_action" &&
snapshotPath !== undefined &&
session.allowsSnapshotReplay(tool)
) {
const workflowRecord = workflowSnapshotRecord(
evidence,
tool,
evidenceProfile,
cachePolicy,
);
if (workflowRecord !== undefined) {
const recorded = session.recordWorkflowSnapshot(workflowRecord);
if (!recorded.ok)
return err(recorded.error.retainPartialObservation(evidence));
}
}
if (!SNAPSHOT_UNWRITTEN_TOOLS.has(tool) && snapshotPath !== undefined) {
const snapshot = session.exportAnalysisSnapshot();
if (!snapshot.ok)
return err(snapshot.error.retainPartialObservation(evidence));
const written = await session.writeAnalysisSnapshot(
snapshot.value,
snapshotPath,
true,
);
if (written.ok) publishedSnapshot = written.value;
else {
const published =
written.error instanceof EvidenceFileError
? written.error.published
: undefined;
if (published?.path !== undefined)
publishedSnapshot = { path: published.path, bytes: published.bytes };
const released =
published !== undefined && (await session.closeFileResources()).ok;
if (!released || published?.path === undefined)
return err(written.error.retainPartialObservation(evidence));
}
}
return ok(evidence);
};
const outcome = await withSessionCleanup<{
readonly result: Result<Evidence, AnalysisError>;
readonly cleanupError?: AnalysisError;
}>(
session,
async () => {
const result = await execute();
if (
!result.ok &&
result.error.sourcePublicationRecovery?.completed.kind ===
"retained-evidence"
) {
const retained = session.evidenceForAnalysis(
result.error.sourcePublicationRecovery.completed.evidence_id,
);
if (retained !== undefined)
result.error.sourcePublicationRecovery = {
...result.error.sourcePublicationRecovery,
completed: {
kind: "inline-evidence",
retention: "one-shot-session",
source_closure: "not-established",
evidence: retained,
},
};
}
return { result };
},
(value, cleanupError) => ({ ...value, cleanupError }),
);
await dispatchQueuedInterrupts();
const result = outcome.result.ok
? completeProviderEvidence(outcome.result.value, signal)
: err(retainFinalCancellation(outcome.result.error, tool, signal));
if (!result.ok && publishedSnapshot !== undefined)
result.error.retainDiagnostics({
analysis_snapshot: { ...publishedSnapshot },
});
if (outcome.cleanupError !== undefined) {
// A committed snapshot remains published even when final close fails.
if (result.ok && publishedSnapshot !== undefined)
outcome.cleanupError.retainDiagnostics({
analysis_snapshot: { ...publishedSnapshot },
});
return {
...err(directAnalysisCleanupFailure(result, outcome.cleanupError, path)),
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
};
}
return {
...(result.ok ? ok(result.value) : err(cliError(result.error, path))),
...(sourceEvidence === undefined ? {} : { sourceEvidence }),
};
};
/** Preserve an earlier failure and a cancellation observed during final cleanup. */
const retainFinalCancellation = (
failure: AnalysisError,
tool: string,
signal: AbortSignal,
): AnalysisError =>
signal.aborted
? analysisErrorWithCancellation(failure, cancelledBy(tool, signal))
: failure;
/** Composed commands whose one-shot call never writes the snapshot file. */
const SNAPSHOT_UNWRITTEN_TOOLS: ReadonlySet<string> = new Set([
"decompile_all",
"trace_native_ui_action",
]);
/**
* A composed answer is rebuilt, not re-observed: its source reads that the
* snapshot holds can still replay without starting the provider.
*/
const workflowSnapshotNotSavedLimitation = (reason: string): string =>
`Not saved for snapshot replay as a composed answer: ${reason}. The snapshot records this Evidence and the source reads it can replay; repeating the call composes the answer again, starting the provider only for reads the snapshot lacks.`;
const executeAnalysisTool = async (input: {
readonly session: BinarySession;
readonly openedTarget: BinaryTarget;
readonly tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool;
readonly arguments: Readonly<Record<string, JsonValue>>;
readonly evidenceParameters: Readonly<Record<string, JsonValue>>;
readonly signal: AbortSignal;
readonly evidenceProfile: AnalysisProfileCommitment | undefined;
readonly saveSnapshot: boolean;
}): Promise<
Result<
{
readonly evidence: Evidence;
readonly cachePolicy?: "live";
},
AnalysisError
>
> => {
const { session, tool, signal, evidenceProfile } = input;
if (tool === "analyze_function") {
const { executeFunctionAnalysisEvidence } =
await import("./FunctionAnalysisEvidence.js");
let result = await executeFunctionAnalysisEvidence(
session,
input.arguments,
input.openedTarget,
{
signal,
// The session reports when a saved one-shot answer cannot replay.
...(input.saveSnapshot
? { snapshotContext: "one-shot-target" as const }
: {}),
},
);
result = retainAnalysisResultSources(
tool,
(source) => session.recordEvidence(source),
result,
);
return result.ok ? ok({ evidence: result.value }) : result;
}
if (isWorkflowEvidenceTool(tool)) {
const { EnhancedTools } = await import("./EnhancedTools.js");
let result = await executeComposedWorkflow(
session,
(observed) =>
new EnhancedTools(observed).execute(tool, input.arguments, signal),
composedLimitationBudget(tool),
);
retainPartialWorkflowEvidence(result, {
target: input.openedTarget,
operation: tool,
parameters: input.evidenceParameters,
upstreamProfile: evidenceProfile,
});
result = retainAnalysisResultSources(
tool,
(source) => session.recordEvidence(source),
result,
);
if (!result.ok) return result;
// Mirrors the workflow snapshot record DirectAnalysis keeps afterwards.
const workflowReplayRefusal = !input.saveSnapshot
? undefined
: SNAPSHOT_UNWRITTEN_TOOLS.has(tool)
? `Not saved: ${tool} does not write analysis snapshots, so --snapshot recorded nothing for this call.`
: session.allowsSnapshotReplay(tool) &&
evidenceProfile !== undefined &&
result.value.cachePolicy !== "live"
? undefined
: workflowSnapshotNotSavedLimitation(
result.value.cachePolicy === "live"
? "it depends on live provider answers"
: "it is not bound to a replayable provider profile",
);
const evidence = createWorkflowEvidence({
target: input.openedTarget,
operation: tool,
parameters: input.evidenceParameters,
result: result.value.result,
upstreamProfile: evidenceProfile,
upstreamLimitations:
workflowReplayRefusal === undefined
? result.value.limitations
: [...result.value.limitations, workflowReplayRefusal],
...(result.value.evidenceLinks === undefined
? {}
: { upstreamEvidenceLinks: result.value.evidenceLinks }),
});
return ok({
evidence,
...(result.value.cachePolicy === undefined
? {}
: { cachePolicy: result.value.cachePolicy }),
});
}
// A saved one-shot snapshot binds every read to this call's own target.
const executionOptions = {
signal,
...(input.saveSnapshot
? { snapshotContext: "one-shot-target" as const }
: {}),
};
const result = await executeWithNativeSymbolSelection(
session,
tool,
input.arguments,
(arguments_) =>
session.executeForDirectObservation(
tool,
arguments_,
input.evidenceParameters,
executionOptions,
),
executionOptions,
);
if (!result.ok) return result;
const evidence = completedOperationEvidence(
tool,
input.evidenceParameters,
result.value,
{
target: input.openedTarget,
admitRecovery: session.admitRecoveryObservation.bind(session),
evidenceById: (id) => session.evidenceForAnalysis(id),
},
);
return evidence.ok ? ok({ evidence: evidence.value }) : evidence;
};
const withProcessCancellation = async <Value>(
suppliedSignal: AbortSignal | undefined,
operation: (signal: AbortSignal) => Promise<Value>,
): Promise<Value> => {
if (suppliedSignal !== undefined) return operation(suppliedSignal);
const controller = new AbortController();
const interrupt = (): void =>
controller.abort(CallerAbort.forProcessSignal("SIGINT"));
const terminate = (): void =>
controller.abort(CallerAbort.forProcessSignal("SIGTERM"));
// Package runners can forward a terminal interrupt after REA already received
// it directly. Keep both guards installed until provider cleanup has settled.
process.on("SIGINT", interrupt);
process.on("SIGTERM", terminate);
try {
return await operation(controller.signal);
} finally {
process.off("SIGINT", interrupt);
process.off("SIGTERM", terminate);
}
};
const prepareSnapshot = async (options: {
readonly session: Pick<
BinarySession,
"readAnalysisSnapshot" | "resolveTarget"
>;
readonly path: string;
readonly loadSelection?: NativeLoadSelection;
readonly espFlash?: EspFlashSelection;
readonly snapshotPath: string | undefined;
readonly signal: AbortSignal;
}): Promise<
Result<
{ readonly snapshot?: AnalysisSnapshot; readonly target?: BinaryTarget },
AnalysisError
>
> => {
const { path, snapshotPath, session } = options;
if (snapshotPath === undefined || !(await fileExists(snapshotPath)))
return ok({});
const loaded = await session.readAnalysisSnapshot(
snapshotPath,
options.signal,
);
if (!loaded.ok) return loaded;
const target = await session.resolveTarget(path, {
signal: options.signal,
...targetSelection(options),
});
if (!target.ok) return target;
const mismatch = snapshotBindingMismatch(
loaded.value,
target.value,
undefined,
);
if (mismatch?.target !== undefined)
return err(
new AnalysisSnapshotMismatchError(
"Analysis snapshot target does not match the requested binary",
mismatch,
),
);
return ok({ snapshot: loaded.value, target: target.value });
};
const inspectBundleResourceInput = async (
path: string,
): Promise<Result<boolean, BinaryTargetError>> => {
const callerPath = absoluteCallerPath(path);
try {
return ok((await stat(callerPath)).isDirectory());
} catch (cause: unknown) {
const failure = classifyBinaryTargetFilesystemFailure(callerPath, cause);
if (failure !== undefined) return err(failure);
throw cause;
}
};
const analysisProfileForRoute = (
route: SessionProviderRoute,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
const profile = route.profile;
const nativeDispatchProfile =
profile === null || profile === undefined
? nativeDispatchBindingProfile(route, tool)
: undefined;
if (profile === null || profile === undefined) {
if (nativeDispatchProfile === undefined) return undefined;
return isWorkflowEvidenceTool(tool)
? workflowAnalysisProfile(nativeDispatchProfile, tool)
: nativeDispatchProfile;
}
if (isWorkflowEvidenceTool(tool))
return workflowAnalysisProfile(profile, tool);
const provider = routeProviderIdentity(route, tool);
return provider.id === profile.provider.id ? profile : undefined;
};
const nativeDispatchBindingProfile = (
route: SessionProviderRoute,
operation: string,
): AnalysisProfileCommitment | undefined => {
if (operation !== "inspect_native_dispatch_metadata") return undefined;
return profilelessNativeDispatchProfile(route);
};
const analysisProfileForEvidence = (
session: BinarySession,
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
if (!isWorkflowEvidenceTool(tool)) return session.analysisProfile(tool);
return session.analysisProfile() ?? session.analysisProfile(tool);
};
const isWorkflowEvidenceTool = (
tool:
| NativeToolName
| ArtifactAnalysisOperation
| ManagedToolName
| DirectAnalysisTool,
): tool is DirectEnhancedToolName =>
tool === "binary_overview" ||
tool === "inspect_native_api" ||
tool === "inspect_native_dispatch_metadata" ||
tool === "trace_feature" ||
tool === "trace_native_values" ||
tool === "trace_native_ui_action" ||
tool === "decompile_all";
const fileExists = async (path: string): Promise<boolean> => {
try {
await access(path);
return true;
} catch (cause: unknown) {
if (
typeof cause === "object" &&
cause !== null &&
"code" in cause &&
cause.code === "ENOENT"
)
return false;
throw cause;
}
};
const cliError = (
error: AnalysisError,
callerInputPath?: string,
): JsonValue => ({
error: "Analysis failed",
...(callerInputPath === undefined
? projectInvocationFailure(error)
: projectDirectAnalysisFailure(error, callerInputPath)),
});