refactor(native): group analyst semantics workflows and contracts (#973)

This commit is contained in:
Ysopwnable
2026-10-07 22:40:48 +08:00
committed by GitHub
parent f8d84da127
commit ea4db4c9f7
69 changed files with 158 additions and 127 deletions
@@ -0,0 +1,548 @@
// Fake-backed composition coverage; real provider verification lives in
// `npm run verify:hopper` and `npm run verify:ghidra`.
import { describe, expect, it } from "vitest";
import { z } from "zod";
import {
createAnalysisExecution,
type AnalysisExecution,
type AnalysisOperation,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
} from "../../domain/analysisErrorCore.js";
import { EnhancedTools } from "../EnhancedTools.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
} from "../../domain/native/nativeInvestigationGraph.js";
import { err, ok } from "../../domain/result.js";
import type { Result } from "../../domain/result.js";
const target = "a".repeat(64);
const provider = { id: "fixture", name: "Fixture", version: "1" };
const evidence = [
{
kind: "interface_builder_resource" as const,
description: "Fixture UI archive",
location: { address: null, file_offset: null },
artifact_path: null,
artifact_sha256: null,
},
];
const graph = {
target_sha256: target,
provider: {
id: provider.id,
version: provider.version,
tool_version: "fixture",
},
nodes: [
{
id: "button",
kind: "control" as const,
name: "Build",
location: null,
attributes: {
class_name: "UIButton",
interface_builder_object_id: "button",
},
evidence,
},
{
id: "action",
kind: "action" as const,
name: "buildTapped:",
location: null,
attributes: { selector: "buildTapped:" },
evidence,
},
{
id: "controller",
kind: "view_controller" as const,
name: "BuildViewController",
location: null,
attributes: { class_name: "BuildViewController" },
evidence,
},
{
id: "selector",
kind: "objc_selector" as const,
name: "buildTapped:",
location: null,
attributes: {},
evidence,
},
],
edges: [
{
id: "button-action",
from: "button",
to: "action",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "action-selector",
from: "action",
to: "selector",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "action-controller",
from: "action",
to: "controller",
relation: "target_action" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
],
coverage: [],
truncated: false,
};
const execution = (
operation: AnalysisOperation,
result: unknown,
sha256 = target,
) =>
ok(
createAnalysisExecution(result, provider, {
subject: {
sha256,
path: "/fixture.app",
format: "mach-o",
architecture: "arm64",
},
}),
);
const testAnalysis = (
overrides: Partial<
Record<
AnalysisOperation,
(
parameters: Readonly<Record<string, unknown>>,
) => Result<AnalysisExecution, AnalysisError>
>
> = {},
uiGraph: z.input<typeof nativeInvestigationGraphSchema> = graph,
) => ({
execute: async (
operation: AnalysisOperation,
parameters: Readonly<Record<string, unknown>>,
): Promise<Result<AnalysisExecution, AnalysisError>> => {
const override = overrides[operation];
if (override !== undefined) return override(parameters);
switch (operation) {
case "procedure_address":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"Seed not available",
),
);
case "procedure_references":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"No typed reference reader in fixture",
),
);
case "inspect_native_dispatch_metadata":
return err(
new AnalysisCapabilityUnavailableError(
"fixture",
operation,
"No binary metadata reader in fixture",
),
);
case "decode_interface_builder":
return execution(operation, {
target_sha256: target,
documents: [
{
relative_path: "Base.lproj/Main.nib",
archive_sha256: "b".repeat(64),
document_kind: "nib",
object_count: 4,
connection_count: 3,
hierarchy_complete: true,
},
],
graph: uiGraph,
limitations: [],
});
case "list_names":
return execution(operation, [
{ address: "0x1000", name: "-[BuildViewController buildTapped:]" },
]);
case "procedure_callees":
return execution(
operation,
parameters.procedure === "0x1000" ? ["0x2000"] : [],
);
default:
throw new Error(`Unexpected provider operation: ${operation}`);
}
},
});
describe("native UI action trace", () => {
it("accepts an explicit native seed without an authored UI connection", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_address: () => execution("procedure_address", "0x1000"),
}),
).execute("trace_native_ui_action", { action: "0x1000" });
expect(result).toMatchObject({
ok: true,
value: {
start: "native:function:0x1000",
nodes: expect.arrayContaining([
expect.objectContaining({ id: "native:function:0x2000" }),
]),
},
});
});
it("builds the evidence path from the active app and native provider", async () => {
const tools = new EnhancedTools(testAnalysis());
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
const trace = nativeInvestigationTraceSchema.parse(result.value);
expect(trace.start).toBe("action");
expect(trace.nodes.map(({ id }) => id)).toContain("native:function:0x1000");
expect(trace.nodes.map(({ id }) => id)).toContain("native:function:0x2000");
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
}),
);
expect(trace.edges).toContainEqual(
expect.objectContaining({
relation: "provider_call",
to: "native:function:0x2000",
}),
);
expect(trace.coverage).toContainEqual(
expect.objectContaining({
facet: "cross_function_value_flow",
status: "unsupported",
}),
);
});
});
describe("bounded native UI tracing", () => {
it("continues handler traversal from its own depth when another UI branch is deeper", async () => {
const deepGraph = {
...graph,
nodes: [
...graph.nodes,
{
id: "view",
kind: "view" as const,
name: "Container",
location: null,
attributes: {},
evidence,
},
{
id: "nested-view",
kind: "view" as const,
name: "Nested container",
location: null,
attributes: {},
evidence,
},
],
edges: [
...graph.edges,
{
id: "controller-view",
from: "controller",
to: "view",
relation: "contains" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
{
id: "view-nested-view",
from: "view",
to: "nested-view",
relation: "contains" as const,
resolution: "observed" as const,
evidence,
limitations: [],
},
],
};
const result = await new EnhancedTools(testAnalysis({}, deepGraph)).execute(
"trace_native_ui_action",
{ action: "buildTapped:", max_depth: 3 },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(
nativeInvestigationTraceSchema
.parse(result.value)
.nodes.map(({ id }) => id),
).toContain("native:function:0x2000");
});
it("returns a typed input error for malformed direct metadata requests", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"inspect_native_dispatch_metadata",
{ max_records: 0 },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisInputError" },
});
});
it("binds dispatch metadata to the active target digest", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"inspect_native_dispatch_metadata",
{ max_records: 10 },
);
expect(result).toMatchObject({
ok: true,
value: { target_sha256: target },
});
});
});
describe("native UI query outcomes", () => {
it("resolves a control object ID through its authored action edge", async () => {
const tools = new EnhancedTools(testAnalysis());
const result = await tools.execute("trace_native_ui_action", {
action: "button",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toMatchObject({ start: "action" });
});
it("rejects UI and native observations with different target identities", async () => {
const tools = new EnhancedTools(
testAnalysis({
list_names: () => execution("list_names", [], "c".repeat(64)),
}),
);
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisOutputError",
operation: "decode_interface_builder",
},
});
});
it("returns candidates and a reason for an ambiguous selector", async () => {
const duplicateGraph = {
...graph,
nodes: [
...graph.nodes,
{
...graph.nodes[1],
id: "second-action",
},
],
};
const tools = new EnhancedTools(
testAnalysis({
decode_interface_builder: () =>
execution("decode_interface_builder", {
target_sha256: target,
documents: [],
graph: duplicateGraph,
limitations: [],
}),
}),
);
const result = await tools.execute("trace_native_ui_action", {
action: "buildTapped:",
});
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toMatchObject({
reason: "action_selector_matches_multiple_ui_connections",
nodes: [{ id: "action" }, { id: "second-action" }],
});
});
it("retains decoder truncation coverage when the action is absent", async () => {
const boundedGraph = {
...graph,
coverage: [
{
facet: "objects:Main.nib",
status: "partial" as const,
reason: "object_limit_reached",
examined: 2,
omitted: 1,
},
],
truncated: true,
};
const result = await new EnhancedTools(
testAnalysis({}, boundedGraph),
).execute("trace_native_ui_action", { action: "missing-selector" });
expect(result).toMatchObject({ ok: true, value: { truncated: true } });
if (!result.ok) return;
expect(result.value).toHaveProperty("coverage");
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "objects:Main.nib",
status: "partial",
reason: "object_limit_reached",
}),
]),
});
});
it("returns cancellation instead of a successful trace during callee expansion", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_callees: () =>
err(new AnalysisCancelledError("procedure_callees")),
}),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", operation: "procedure_callees" },
});
});
it("reports only callees left unprocessed by the edge limit", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_callees: (parameters) =>
execution(
"procedure_callees",
parameters.procedure === "0x1000"
? ["0x2000", "0x2001", "0x2002"]
: [],
),
}),
).execute("trace_native_ui_action", {
action: "buildTapped:",
max_depth: 4,
max_edges: 5,
});
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "static_native_calls",
status: "partial",
omitted: 1,
}),
]),
});
});
});
describe("native UI trace boundaries", () => {
it("retains unresolved dispatch evidence during callee expansion", async () => {
const result = await new EnhancedTools(
testAnalysis({ list_names: () => execution("list_names", []) }),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
unresolved: [
expect.objectContaining({
relation: "objc_dispatch",
resolution: "unresolved",
}),
],
});
});
it("returns cancellation when archive decoding is cancelled", async () => {
const result = await new EnhancedTools(
testAnalysis({
decode_interface_builder: () =>
err(new AnalysisCancelledError("decode_interface_builder")),
}),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
operation: "decode_interface_builder",
},
});
});
it("matches handlers after the dispatch inventory's former default limit", async () => {
const names = Array.from({ length: 5_000 }, (_, index) => ({
address: `0x${(index + 1).toString(16)}`,
name: `unrelated_symbol_${index}`,
}));
names.push({
address: "0x2000",
name: "-[BuildViewController buildTapped:]",
});
const result = await new EnhancedTools(
testAnalysis({ list_names: () => execution("list_names", names) }),
).execute("trace_native_ui_action", { action: "buildTapped:" });
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
nodes: expect.arrayContaining([
expect.objectContaining({ id: "native:function:0x2000" }),
]),
});
});
it("counts edges removed with nodes in bounded graph coverage", async () => {
const result = await new EnhancedTools(testAnalysis()).execute(
"trace_native_ui_action",
{ action: "missing-selector", max_nodes: 1 },
);
expect(result).toMatchObject({ ok: true });
if (!result.ok) return;
expect(result.value).toMatchObject({
coverage: expect.arrayContaining([
expect.objectContaining({
facet: "interface_builder_graph",
status: "partial",
omitted: 8,
}),
]),
});
});
});
@@ -0,0 +1,169 @@
import { describe, expect, it } from "vitest";
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
import { nativeApiBoundarySchema } from "../../domain/native/nativeApiBoundary.js";
import { projectNativeApiInspection } from "./NativeApiInspection.js";
describe("native API switch uncertainty", () => {
it("reports an unevidenced default path independently of known numeric cases", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
const boundary = dossier.native_api;
if (boundary?.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
const table = boundary.jump_tables[0];
if (table === undefined)
throw new TypeError("Ghidra jump-table fixture is unavailable");
const incomplete = functionDossierSchema.parse({
...dossier,
native_api: {
...boundary,
jump_tables: [{ ...table, default_targets: [] }],
},
});
expect(projectNativeApiInspection(incomplete).residual_unknowns).toContain(
"Which default or out-of-range path, if any, belongs to the dispatch at 0x401010?",
);
});
it("does not report evidenced defaults as unknown cases and retains genuinely unresolved mappings", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
const boundary = dossier.native_api;
if (boundary?.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
const table = boundary.jump_tables[0];
const mapping = table?.mappings[0];
if (table === undefined || mapping === undefined)
throw new TypeError("Ghidra jump-table fixture is unavailable");
const defaultTarget = {
target_address: mapping.target_address,
confidence: "high",
evidence: mapping.evidence,
};
const complete = functionDossierSchema.parse({
...dossier,
native_api: {
...boundary,
jump_tables: [{ ...table, default_targets: [defaultTarget] }],
},
});
expect(projectNativeApiInspection(complete).residual_unknowns).toEqual([]);
const unresolved = functionDossierSchema.parse({
...complete,
native_api: {
...boundary,
jump_tables: [
{
...table,
default_targets: [defaultTarget],
mappings: [
mapping,
{ ...mapping, case_value: null, target_address: "0x401030" },
],
},
],
},
});
expect(projectNativeApiInspection(unresolved).residual_unknowns).toContain(
"Which source-level case values correspond to every target dispatched at 0x401010?",
);
});
});
describe("native API inspection", () => {
it("preserves structured type and jump-table boundary evidence", () => {
const dossier = functionDossierSchema.parse(ghidraFunctionDossier());
expect(projectNativeApiInspection(dossier)).toMatchObject({
procedure: { address: "0x401000", name: "fixture_main" },
boundary: {
available: true,
return_type: { data_type: "int", confidence: "medium" },
jump_tables: [
{
dispatch_address: "0x401010",
data_sources: [{ address: "0x403000" }],
mappings: [
{
target_address: "0x401020",
},
],
},
],
},
unsupported_branches: [],
residual_unknowns: [],
});
});
it("preserves unsupported provider branches as residual unknowns", () => {
const value = ghidraFunctionDossier();
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new TypeError("Ghidra dossier fixture is invalid");
const dossier = functionDossierSchema.parse(
Object.fromEntries(
Object.entries(value).filter(([key]) => key !== "native_api"),
),
);
expect(projectNativeApiInspection(dossier)).toMatchObject({
boundary: { available: false },
unsupported_branches: [
"structured-boundary-types",
"jump-table-data-mapping",
],
residual_unknowns: [
expect.stringContaining("boundary types"),
expect.stringContaining("jump table"),
],
});
});
it("reports missing jump-table targets as an explicit unknown", () => {
const value = ghidraFunctionDossier();
const dossier = functionDossierSchema.parse(value);
const boundary = dossier.native_api;
if (boundary?.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
const table = boundary.jump_tables[0];
if (table === undefined)
throw new TypeError("Ghidra jump-table fixture is unavailable");
const incomplete = functionDossierSchema.parse({
...dossier,
native_api: {
...boundary,
jump_tables: [{ ...table, mappings: [] }],
},
});
expect(projectNativeApiInspection(incomplete).residual_unknowns).toContain(
"Which case values and targets belong to the dispatch at 0x401010?",
);
});
it("rejects boundary types placed in the wrong ABI role", () => {
const boundary = functionDossierSchema.parse(
ghidraFunctionDossier(),
).native_api;
if (boundary === null || boundary.available !== true)
throw new TypeError("Ghidra native API fixture is unavailable");
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
return_type: { ...boundary.return_type, role: "parameter" },
}).success,
).toBe(false);
expect(
nativeApiBoundarySchema.safeParse({
...boundary,
parameters: [
{
...boundary.return_type,
role: "return",
},
],
}).success,
).toBe(false);
});
});
@@ -0,0 +1,108 @@
import type { FunctionDossier } from "../../domain/hopperValues.js";
import {
nativeApiInspectionResultSchema,
type NativeApiBoundary,
type NativeApiInspectionResult,
} from "../../domain/native/nativeApiBoundary.js";
const unavailableBoundary = (): NativeApiBoundary => ({
available: false,
reason:
"The selected provider did not expose a structured native API boundary model.",
residual_unknowns: [
"What are the function's return and parameter boundary types?",
"Does this function dispatch through a jump table with recoverable data addresses?",
],
});
/** Project one analyzed-function dossier into inspectable native API substeps. */
export const projectNativeApiInspection = (
dossier: FunctionDossier,
): NativeApiInspectionResult => {
const boundary = dossier.native_api ?? unavailableBoundary();
const unsupportedBranches = boundary.available
? []
: ["structured-boundary-types", "jump-table-data-mapping"];
const residualUnknowns = boundary.available
? availableResidualUnknowns(boundary)
: boundary.residual_unknowns;
return nativeApiInspectionResultSchema.parse({
procedure: {
address: dossier.procedure.address,
name: dossier.procedure.name,
},
boundary,
substeps: [
{
operation: "analyze_function",
status: "completed",
observations: [
"provider function dossier",
"provider pseudocode classification",
"provider control-flow observations",
],
},
{
operation: "project_native_api_boundary",
status: boundary.available ? "completed" : "unsupported",
observations: boundary.available
? [
"return and parameter boundary types",
"confidence and inference evidence",
"jump-table dispatch, data, and target addresses",
]
: [boundary.reason],
},
{
operation: "preserve_residual_unknowns",
status: "completed",
observations:
residualUnknowns.length === 0
? ["no additional structured-boundary unknowns"]
: residualUnknowns,
},
],
unsupported_branches: unsupportedBranches,
residual_unknowns: residualUnknowns,
});
};
const availableResidualUnknowns = (
boundary: Extract<NativeApiBoundary, { readonly available: true }>,
): readonly string[] => {
const unknowns: string[] = [];
for (const table of boundary.jump_tables) {
if (table.default_targets.length === 0)
unknowns.push(
`Which default or out-of-range path, if any, belongs to the dispatch at ${table.dispatch_address}?`,
);
if (table.mappings.length === 0)
unknowns.push(
`Which case values and targets belong to the dispatch at ${table.dispatch_address}?`,
);
if (table.data_sources.length === 0)
unknowns.push(
`What backing data address produced the jump table dispatched at ${table.dispatch_address}?`,
);
if (
table.data_sources.some(
({ entry_count: count, entry_size_bytes: size }) =>
count === null || size === null,
)
)
unknowns.push(
`What are the exact entry size and count for candidate jump-table data dispatched at ${table.dispatch_address}?`,
);
if (table.mappings.some(({ case_value: value }) => value === null))
unknowns.push(
`Which source-level case values correspond to every target dispatched at ${table.dispatch_address}?`,
);
}
for (const value of [boundary.return_type, ...boundary.parameters]) {
if (value.confidence === "low")
unknowns.push(
`Can the inferred ${value.role} type ${value.data_type} be confirmed with imported metadata or an ABI probe?`,
);
}
return [...new Set(unknowns)];
};
@@ -0,0 +1,104 @@
import { describe, expect, it } from "vitest";
import { readNativeCallRoutes } from "./NativeCallRoutes.js";
import { createAnalysisExecution } from "../AnalysisProvider.js";
import { ghidraReferenceEdge } from "../../domain/ghidraValues.fixture.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { err, ok } from "../../domain/result.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
const provider = { id: "fixture", name: "Fixture", version: "1" };
describe("typed native call routes", () => {
it("preserves computed targets, ambiguity and targetless call sites", async () => {
const reference = jsonValueSchema.parse(ghidraReferenceEdge());
if (
reference === null ||
typeof reference !== "object" ||
Array.isArray(reference)
)
throw new TypeError("Invalid reference fixture");
const result = await readNativeCallRoutes(
{
execute: async () =>
ok(
createAnalysisExecution(
{
reference_kinds_available: true,
references: ["0x2000", "0x3000"].map((address) => ({
...reference,
source_address: "0x1004",
target_address: address,
target_procedure: { address },
kind: {
available: true,
provenance: "fixture-reference",
type: "COMPUTED_CALL",
flow: true,
call: true,
jump: false,
data: false,
read: false,
write: false,
indirect: true,
computed: true,
external: false,
conditional: false,
terminal: false,
primary: true,
operand_index: 0,
},
})),
unresolved_calls: [
{ address: "0x1008", reason: "No static target" },
],
},
provider,
),
),
},
"0x1000",
);
expect(result).toMatchObject({
ok: true,
value: {
routes: [
{
address: "0x2000",
relation: "indirect_call",
resolution: "ambiguous",
},
{
address: "0x3000",
relation: "indirect_call",
resolution: "ambiguous",
},
],
unknowns: [{ address: "0x1008" }],
},
});
});
it("does not fall back on cancellation or invalid typed output", async () => {
let calls = 0;
const cancelled = await readNativeCallRoutes(
{
execute: async () => {
calls++;
return err(new AnalysisCancelledError("procedure_references"));
},
},
"0x1000",
);
expect(cancelled).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
expect(calls).toBe(1);
const malformed = await readNativeCallRoutes(
{ execute: async () => ok(createAnalysisExecution({}, provider)) },
"0x1000",
);
expect(malformed).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
});
});
+101
View File
@@ -0,0 +1,101 @@
import { z } from "zod";
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
import {
parseRelatedAddresses,
referenceKindSchema,
} from "../../domain/hopperValues.js";
import { err, ok } from "../../domain/result.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
const referencesSchema = z.object({
reference_kinds_available: z.boolean().optional(),
references: z.array(
z.object({
source_address: z.string(),
target_address: z.string(),
target_procedure: z.object({ address: z.string() }).nullable(),
kind: referenceKindSchema,
}),
),
unresolved_calls: z
.array(z.object({ address: z.string(), reason: z.string() }))
.default([]),
});
/** Prefer typed static call references, preserving computed targets and targetless sites. */
export const readNativeCallRoutes = async (
analysis: AnalysisOperationPort,
procedure: string,
signal?: AbortSignal,
) => {
const options = signal === undefined ? {} : { signal };
const execution = await analysis.execute(
"procedure_references",
{ procedure, direction: "outgoing" },
options,
);
if (execution.ok) {
const parsed = referencesSchema.safeParse(execution.value.result);
if (!parsed.success)
return err(
new AnalysisOutputError(
"procedure_references",
"Invalid typed call references",
),
);
const references = parsed.data.references;
if (
parsed.data.reference_kinds_available === true ||
(references.length > 0 && references.every(({ kind }) => kind.available))
) {
const calls = references.filter(
({ kind }) => kind.available && kind.call,
);
const countBySite = new Map<string, Set<string>>();
for (const call of calls) {
const targets =
countBySite.get(call.source_address) ?? new Set<string>();
targets.add(call.target_address);
countBySite.set(call.source_address, targets);
}
return ok({
provider: execution.value.provider,
routes: calls.map((call) => ({
address: call.target_procedure?.address ?? call.target_address,
site: call.source_address,
relation:
call.kind.available && (call.kind.computed || call.kind.indirect)
? ("indirect_call" as const)
: ("direct_call" as const),
resolution:
(countBySite.get(call.source_address)?.size ?? 0) > 1
? ("ambiguous" as const)
: call.kind.available &&
(call.kind.computed || call.kind.indirect)
? ("resolved" as const)
: ("observed" as const),
})),
unknowns: parsed.data.unresolved_calls,
});
}
} else if (execution.error._tag !== "AnalysisCapabilityUnavailableError")
return err(execution.error);
const callees = await analysis.execute(
"procedure_callees",
{ procedure },
options,
);
if (!callees.ok) return callees;
const parsed = parseRelatedAddresses(callees.value.result, "callees");
return parsed.ok
? ok({
provider: callees.value.provider,
routes: parsed.value.map((address) => ({
address,
site: procedure,
relation: "provider_call" as const,
resolution: "inferred" as const,
})),
unknowns: [],
})
: parsed;
};
@@ -0,0 +1,68 @@
import { z } from "zod";
import {
nativeDispatchMetadataResultSchema,
inspectNativeDispatchMetadata,
} from "../../domain/native/objcSwiftMetadata.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { err, ok } from "../../domain/result.js";
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
import type { EnhancedResult } from "../EnhancedToolTypes.js";
/** Prefer validated binary metadata, otherwise preserve the bound provider's symbol-only coverage. */
export const inspectNativeDispatch = async (
analysis: AnalysisOperationPort,
maxRecords: number,
signal?: AbortSignal,
): EnhancedResult => {
const binaryMetadata = await analysis.execute(
"inspect_native_dispatch_metadata",
{ max_records: maxRecords },
signal === undefined ? {} : { signal },
);
if (binaryMetadata.ok)
return ok(
jsonValueSchema.parse(
nativeDispatchMetadataResultSchema.parse(binaryMetadata.value.result),
),
);
if (binaryMetadata.error._tag !== "AnalysisCapabilityUnavailableError")
return err(binaryMetadata.error);
const execution = await analysis.execute(
"list_names",
{},
signal === undefined ? {} : { signal },
);
if (!execution.ok) return err(execution.error);
const names = z
.array(
z.union([
z.strictObject({ address: z.string(), value: z.string() }),
z.strictObject({ address: z.string(), name: z.string() }),
]),
)
.safeParse(execution.value.result);
if (!names.success)
return err(
new AnalysisOutputError(
"list_names",
"provider returned an invalid inventory",
),
);
return ok(
jsonValueSchema.parse(
nativeDispatchMetadataResultSchema.parse({
target_sha256: execution.value.subject?.sha256 ?? null,
provider: execution.value.provider,
analysis_profile_digest:
execution.value.analysisProfile?.digest ?? null,
result: inspectNativeDispatchMetadata(
names.data.map((entry) => ({
address: entry.address,
name: "value" in entry ? entry.value : entry.name,
})),
maxRecords,
),
}),
),
);
};
@@ -0,0 +1,548 @@
import { z } from "zod";
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
import type { EnhancedResult } from "../EnhancedToolTypes.js";
import type { enhancedInputSchemas } from "../../contracts/enhancedInputs.js";
import { interfaceBuilderAnalysisSchema } from "../../domain/apple/interfaceBuilderGraph.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
traceNativeInvestigationGraph,
joinInterfaceBuilderDispatch,
} from "../../domain/native/nativeInvestigationGraph.js";
import { nativeDispatchMetadataResultSchema } from "../../domain/native/objcSwiftMetadata.js";
import { inspectNativeDispatch } from "./NativeDispatchMetadataInspection.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { readNativeCallRoutes } from "./NativeCallRoutes.js";
import { err, ok } from "../../domain/result.js";
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
type Input = z.output<typeof enhancedInputSchemas.trace_native_ui_action>;
/** Build a UI-to-code trace from the active app and selected native provider. */
export const traceNativeUiAction = async (
analysis: AnalysisOperationPort,
input: Input,
signal?: AbortSignal,
): EnhancedResult => {
const [uiExecution, metadataExecution] = await Promise.all([
analysis.execute(
"decode_interface_builder",
{
max_documents: 64,
max_objects: input.max_nodes,
max_connections: input.max_edges,
},
signal === undefined ? {} : { signal },
),
inspectNativeDispatch(analysis, 20_000, signal),
]);
if (!uiExecution.ok && uiExecution.error._tag === "AnalysisCancelledError")
return err(uiExecution.error);
if (!metadataExecution.ok) return err(metadataExecution.error);
const metadata = nativeDispatchMetadataResultSchema.parse(
metadataExecution.value,
);
const targetSha256 = metadata.target_sha256;
if (targetSha256 === null)
return err(
new AnalysisOutputError(
"inspect_native_dispatch_metadata",
"Dispatch metadata lacks target identity",
),
);
let graph = emptyGraph(targetSha256, metadata.provider);
const coverage = [];
if (uiExecution.ok) {
const decoded = interfaceBuilderAnalysisSchema.safeParse(
uiExecution.value.result,
);
if (!decoded.success)
return err(
new AnalysisOutputError(
"decode_interface_builder",
"artifact provider returned an invalid interface graph",
),
);
if (decoded.data.target_sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"decode_interface_builder",
"UI and native provider results refer to different target SHA-256 values",
),
);
graph = joinInterfaceBuilderDispatch(decoded.data.graph, metadata.result);
coverage.push({
facet: "interface_builder_archives",
status: decoded.data.documents.length > 0 ? "complete" : "unsupported",
reason:
decoded.data.documents.length > 0
? null
: "no_compiled_interface_builder_archives_found",
examined: decoded.data.documents.length,
omitted: 0,
});
const bounded = boundUiGraph(graph, input.max_nodes, input.max_edges);
graph = bounded.graph;
if (bounded.truncated)
coverage.push({
facet: "interface_builder_graph",
status: "partial",
reason: "native_trace_output_bounds_reached",
examined:
decoded.data.graph.nodes.length + decoded.data.graph.edges.length,
omitted: bounded.omitted,
});
} else {
coverage.push({
facet: "interface_builder_archives",
status: "unsupported",
reason: projectAnalysisError(uiExecution.error).message,
examined: 0,
omitted: 0,
});
}
let selected = resolveUiAction(graph, input.action);
if (selected.nodeId === null && selected.candidates.length === 0) {
const native = await analysis.execute(
"procedure_address",
{ procedure: input.action },
signal === undefined ? {} : { signal },
);
if (!native.ok && native.error._tag === "AnalysisCancelledError")
return err(native.error);
if (native.ok) {
const address = z.string().safeParse(native.value.result);
if (!address.success || native.value.subject?.sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"procedure_address",
"Native seed lacks a validated address or matching target identity",
),
);
const id = `native:function:${address.data}`;
graph.nodes.push({
id,
kind: "function",
name: input.action,
location: { address: address.data, file_offset: null },
attributes: { resolved_by: native.value.provider.id },
evidence: [
{
kind: "reference",
description: `Provider resolved the explicit native seed ${input.action}`,
location: { address: address.data, file_offset: null },
artifact_path: null,
artifact_sha256: targetSha256,
},
],
});
selected = { nodeId: id, candidates: [], reason: null };
}
}
if (selected.nodeId === null) {
coverage.push(...graph.coverage);
const trace = {
target_sha256: graph.target_sha256,
provider: graph.provider,
start: input.action,
direction: "forward" as const,
nodes: selected.candidates,
edges: [],
unresolved: [],
reached_depth: 0,
truncated: graph.truncated,
reason: selected.reason,
coverage,
limitations: [
"The query did not identify one unique authored UI action or native function; no handler path was inferred.",
],
};
return ok(
jsonValueSchema.parse(nativeInvestigationTraceSchema.parse(trace)),
);
}
const initial = traceNativeInvestigationGraph(graph, {
start: selected.nodeId,
direction: "forward",
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_edges: input.max_edges,
},
});
const expanded = await addDirectCallees({
analysis,
graph,
initial,
input,
targetSha256,
signal,
});
if (expanded.error !== undefined) return err(expanded.error);
coverage.push({
facet: "static_native_calls",
status: "partial",
reason:
"typed_direct_and_indirect_references_do_not_cover_all_runtime_dispatch; untyped_provider_callees_remain_inferred",
examined: expanded.examined,
omitted: expanded.omitted,
});
coverage.push({
facet: "cross_function_value_flow",
status: "unsupported",
reason:
"call edges identify control-flow candidates but do not recover argument, return, or shared-memory value relationships",
examined: 0,
omitted: 0,
});
const finalGraph = nativeInvestigationGraphSchema.parse({
...graph,
nodes: expanded.nodes,
edges: expanded.edges,
coverage: [...graph.coverage, ...coverage],
truncated: graph.truncated || expanded.truncated,
});
const trace = traceNativeInvestigationGraph(finalGraph, {
start: selected.nodeId,
direction: "forward",
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_edges: input.max_edges,
},
});
return ok(
jsonValueSchema.parse(
nativeInvestigationTraceSchema.parse({
...trace,
truncated: trace.truncated || expanded.truncated || graph.truncated,
reason:
expanded.truncated && trace.reason === null
? "native_call_traversal_bound_reached"
: graph.truncated && trace.reason === null
? "native_trace_output_bound_reached"
: trace.reason,
}),
),
);
};
const emptyGraph = (
targetSha256: string,
provider: {
readonly id: string;
readonly version: string | null;
},
) =>
nativeInvestigationGraphSchema.parse({
target_sha256: targetSha256,
provider: {
id: provider.id,
version: provider.version,
tool_version: "rea-native-ui-trace/1",
},
nodes: [],
edges: [],
coverage: [],
truncated: false,
});
const boundUiGraph = (
graph: z.infer<typeof nativeInvestigationGraphSchema>,
maxNodes: number,
maxEdges: number,
): {
readonly graph: z.infer<typeof nativeInvestigationGraphSchema>;
readonly truncated: boolean;
readonly omitted: number;
} => {
const nodes = graph.nodes.slice(0, maxNodes);
const nodeIds = new Set(nodes.map(({ id }) => id));
const eligibleEdges = graph.edges.filter(
(edge) =>
nodeIds.has(edge.from) && (edge.to === null || nodeIds.has(edge.to)),
);
const edges = eligibleEdges.slice(0, maxEdges);
const omitted =
graph.nodes.length - nodes.length + graph.edges.length - edges.length;
const truncated = omitted > 0;
return {
graph: nativeInvestigationGraphSchema.parse({
...graph,
nodes,
edges,
truncated: graph.truncated || truncated,
}),
truncated,
omitted,
};
};
const resolveUiAction = (
graph: z.infer<typeof nativeInvestigationGraphSchema>,
query: string,
): {
readonly nodeId: string | null;
readonly candidates: z.infer<typeof nativeInvestigationGraphSchema>["nodes"];
readonly reason: string | null;
} => {
const exactId = graph.nodes.find((node) => node.id === query);
if (exactId?.kind === "action")
return { nodeId: exactId.id, candidates: [], reason: null };
const actions = graph.nodes.filter(
(node) =>
node.kind === "action" &&
(node.name === query || node.attributes.selector === query),
);
if (actions.length === 1)
return { nodeId: actions[0]?.id ?? null, candidates: [], reason: null };
if (actions.length > 1)
return {
nodeId: null,
candidates: actions,
reason: "action_selector_matches_multiple_ui_connections",
};
const objectMatches = graph.nodes.filter(
(node) =>
["control", "view", "view_controller", "scene"].includes(node.kind) &&
(node.id === query ||
node.attributes.interface_builder_object_id === query ||
node.id.endsWith(`:object:${query}`)),
);
const actionIds = new Set(
graph.edges.flatMap((edge) =>
edge.resolution === "observed" &&
edge.relation === "target_action" &&
objectMatches.some(({ id }) => edge.from === id) &&
graph.nodes.some(({ id, kind }) => id === edge.to && kind === "action")
? [edge.to]
: [],
),
);
if (actionIds.size === 1)
return { nodeId: [...actionIds][0] ?? null, candidates: [], reason: null };
if (actionIds.size > 1)
return {
nodeId: null,
candidates: graph.nodes.filter(({ id }) => actionIds.has(id)),
reason: "interface_object_has_multiple_action_connections",
};
return {
nodeId: null,
candidates: [],
reason: "ui_action_or_object_not_found",
};
};
const addDirectCallees = async (input: {
readonly analysis: AnalysisOperationPort;
readonly graph: z.infer<typeof nativeInvestigationGraphSchema>;
readonly initial: z.infer<typeof nativeInvestigationTraceSchema>;
readonly input: Input;
readonly targetSha256: string;
readonly signal: AbortSignal | undefined;
}) => {
const nodes = new Map(input.initial.nodes.map((node) => [node.id, node]));
const edges = new Map(
[...input.initial.edges, ...input.initial.unresolved].map((edge) => [
edge.id,
edge,
]),
);
const addressNames = new Map<string, string>();
const depthByNode = graphNodeDepths(
input.initial.start,
input.initial.nodes,
input.initial.edges,
);
for (const node of nodes.values()) {
if (node.kind === "function" && node.location?.address !== null)
addressNames.set(node.location?.address ?? "", node.name);
}
const queue = input.initial.nodes.flatMap((node) =>
node.kind === "function" && node.location?.address != null
? [
{
node,
address: node.location.address,
depth: depthByNode.get(node.id) ?? input.initial.reached_depth,
},
]
: [],
);
const visited = new Set<string>();
let queueIndex = 0;
let examined = 0;
let omitted = 0;
let truncated = false;
while (queueIndex < queue.length) {
const current = queue[queueIndex++];
if (current === undefined || visited.has(current.address)) continue;
visited.add(current.address);
if (current.depth >= input.input.max_depth) {
truncated = true;
omitted += 1;
continue;
}
if (nodes.size >= input.input.max_nodes) {
truncated = true;
omitted += queue.length - queueIndex + 1;
break;
}
const execution = await readNativeCallRoutes(
input.analysis,
current.address,
input.signal,
);
examined += 1;
if (!execution.ok) {
if (execution.error._tag === "AnalysisCancelledError")
return { error: execution.error };
const id = `unknown-callees:${current.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "direct_call",
resolution: "unresolved",
reason: projectAnalysisError(execution.error).message,
evidence: [],
limitations: [
"The provider could not enumerate resolved direct callees.",
],
});
continue;
}
for (const unknown of execution.value.unknowns) {
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted++;
break;
}
const id = `unknown-dispatch:${current.address}:${unknown.address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "indirect_call",
resolution: "unresolved",
reason: unknown.reason,
evidence: [
{
kind: "reference",
description: unknown.reason,
location: { address: unknown.address, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
],
limitations: [],
});
}
for (const [index, route] of execution.value.routes.entries()) {
const address = route.address;
if (edges.size >= input.input.max_edges) {
truncated = true;
omitted += execution.value.routes.length - index;
break;
}
const targetId = `native:function:${address}`;
const evidence = [
{
kind: "reference" as const,
description: `${execution.value.provider.name} reported ${route.relation} from ${current.address} to ${address}`,
location: { address: route.site, file_offset: null },
artifact_path: null,
artifact_sha256: input.targetSha256,
},
];
if (!nodes.has(targetId)) {
if (nodes.size >= input.input.max_nodes) {
truncated = true;
omitted += 1;
const id = `unknown-node-bound:${current.address}:${address}`;
edges.set(id, {
id,
from: current.node.id,
to: null,
relation: "direct_call",
resolution: "unresolved",
reason: "native_trace_node_bound_reached",
evidence,
limitations: [],
});
continue;
}
const name = addressNames.get(address) ?? address;
const node = {
id: targetId,
kind: "function" as const,
name,
location: { address, file_offset: null },
attributes: { resolved_by: execution.value.provider.id },
evidence,
};
nodes.set(targetId, node);
queue.push({ node, address, depth: current.depth + 1 });
}
const edgeId = `call:${current.address}:${route.site}:${address}`;
edges.set(edgeId, {
id: edgeId,
from: current.node.id,
to: targetId,
relation: route.relation,
resolution: route.resolution,
evidence,
limitations: [
"A resolved static call edge does not establish runtime reachability.",
],
});
}
}
return {
nodes: [...nodes.values()],
edges: [...edges.values()],
examined,
omitted,
truncated,
};
};
const graphNodeDepths = (
start: string,
nodes: readonly z.infer<
typeof nativeInvestigationGraphSchema
>["nodes"][number][],
edges: readonly z.infer<
typeof nativeInvestigationGraphSchema
>["edges"][number][],
): ReadonlyMap<string, number> => {
const known = new Set(nodes.map(({ id }) => id));
const depths = new Map([[start, 0]]);
const queue = [start];
for (let index = 0; index < queue.length; index += 1) {
const current = queue[index];
if (current === undefined) continue;
const depth = depths.get(current) ?? 0;
for (const edge of edges) {
if (
edge.resolution === "unresolved" ||
edge.from !== current ||
edge.to === null ||
!known.has(edge.to) ||
depths.has(edge.to)
)
continue;
depths.set(edge.to, depth + 1);
queue.push(edge.to);
}
}
return depths;
};
@@ -0,0 +1,194 @@
import { describe, expect, it } from "vitest";
import { traceNativeValues } from "./NativeValueTrace.js";
import {
createAnalysisExecution,
type AnalysisOperationPort,
} from "../AnalysisProvider.js";
import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { ok, err } from "../../domain/result.js";
const subject = {
path: "/fixture",
sha256: "a".repeat(64),
format: "mach-o" as const,
architecture: "arm64" as const,
};
const provider = { id: "fixture", name: "Fixture", version: "1" };
const scalar = {
kind: "constant",
size_bytes: 4,
location: null,
constant_hex: "3",
};
const node = (id: string, address: string, opcode: string) => ({
id,
address,
sequence: 0,
opcode,
is_dead: true,
block_membership: "member",
inputs: [scalar, scalar],
output: scalar,
});
const analysis: AnalysisOperationPort = {
execute: async (operation, parameters) => {
if (operation === "resolve_native_call_targets")
return ok(
createAnalysisExecution(
{
call_site: "0x1000",
procedure: "0x1000",
status: "direct",
mechanism: "direct",
targets: [
{
address: "0x2000",
procedure: "0x2000",
status: "direct",
basis: "provider-reference",
references: [],
},
],
limitations: [],
},
provider,
{ subject },
),
);
const callee = parameters.procedure === "0x2000";
return ok(
createAnalysisExecution(
jsonValueSchema.parse({
...functionDossierSchema.parse(ghidraFunctionDossier()),
procedure: {
address: callee ? "0x2000" : "0x1000",
name: callee ? "callee" : "caller",
classification: null,
signature: null,
locals: [],
},
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: callee
? [node("return", "0x2000", "RETURN")]
: [node("call", "0x1000", "CALL")],
def_use: [],
effects: [],
parameters: callee
? [{ ordinal: 0, name: "value", data_type: "/int" }]
: [],
parameter_uses: callee
? [{ ordinal: 0, use: "return", input_index: 1 }]
: [],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
},
}),
provider,
{ subject },
),
);
},
};
describe("bounded native value dependency composition", () => {
it("reports work truncation and stable pagination without traversing ambiguous calls", async () => {
const bounded = await traceNativeValues(analysis, {
procedure: "0x1000",
max_functions: 1,
});
expect(bounded.ok).toBe(true);
if (bounded.ok)
expect(bounded.value).toMatchObject({
truncated: true,
decompilations: 1,
});
const page = await traceNativeValues(analysis, {
procedure: "0x1000",
limit: 1,
});
expect(page.ok).toBe(true);
if (page.ok)
expect(page.value).toMatchObject({ total_nodes: 3, next_offset: 1 });
const ambiguous = await traceNativeValues(
{
execute: async (operation, parameters, options) => {
if (operation !== "resolve_native_call_targets")
return analysis.execute(operation, parameters, options);
return ok(
createAnalysisExecution(
{
call_site: "0x1000",
procedure: "0x1000",
status: "ambiguous",
mechanism: "computed",
targets: [
{
address: "0x2000",
procedure: "0x2000",
status: "candidate",
basis: "provider-reference",
references: [],
},
],
limitations: [],
},
provider,
{ subject },
),
);
},
},
{ procedure: "0x1000" },
);
expect(ambiguous.ok).toBe(true);
if (ambiguous.ok)
expect(ambiguous.value).toMatchObject({
decompilations: 1,
edges: [expect.objectContaining({ status: "candidate" })],
});
});
it("propagates cancellation and rejects cross-target dependencies", async () => {
const controller = new AbortController();
controller.abort();
expect(
await traceNativeValues(
analysis,
{ procedure: "0x1000" },
controller.signal,
),
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
const cancelled = await traceNativeValues(
{
execute: async () =>
err(new AnalysisCancelledError("analyze_function")),
},
{ procedure: "0x1000" },
);
expect(cancelled.ok).toBe(false);
const mismatch = await traceNativeValues(
{
execute: async (operation, parameters, options) => {
const value = await analysis.execute(operation, parameters, options);
return value.ok && parameters.procedure === "0x2000"
? ok({
...value.value,
subject: { ...subject, sha256: "b".repeat(64) },
})
: value;
},
},
{ procedure: "0x1000" },
);
expect(mismatch).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError" },
});
});
});
+389
View File
@@ -0,0 +1,389 @@
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { nativeCallTargetsSchema } from "../../domain/native/nativeInstruction.js";
import {
nativeValueTraceInputSchema,
nativeValueTraceSchema,
} from "../../domain/native/nativeValueTrace.js";
import { createEvidence } from "../../domain/evidence.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { err, ok } from "../../domain/result.js";
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
import type { EnhancedResult } from "../EnhancedToolTypes.js";
/** Compose bounded high-p-code def-use graphs across exactly referenced call destinations. */
export const traceNativeValues = async (
analysis: AnalysisOperationPort,
parameters: unknown,
signal?: AbortSignal,
): EnhancedResult => {
const input = nativeValueTraceInputSchema.parse(parameters);
const nodes: typeof nativeValueTraceSchema._output.nodes = [];
const edges: typeof nativeValueTraceSchema._output.edges = [];
const procedures: typeof nativeValueTraceSchema._output.procedures = [];
const unknowns: typeof nativeValueTraceSchema._output.unknowns = [];
const callBindings: {
caller: string;
callee: string;
call: string;
argument_count: number;
output: boolean;
evidence_id: string;
}[] = [];
const pending = [{ procedure: input.procedure, depth: 0 }];
const visited = new Set<string>();
let targetSha256: string | undefined;
let truncated = false;
let decompilations = 0;
let callSites = 0;
let bytes = 0;
while (pending.length > 0) {
if (signal?.aborted)
return err(new AnalysisCancelledError("trace_native_values"));
const next = pending.shift();
if (next === undefined || visited.has(next.procedure)) continue;
if (decompilations >= input.max_functions) {
truncated = true;
unknowns.push({
procedure: next.procedure,
address: null,
reason: "decompilation budget reached",
});
break;
}
const execution = await analysis.execute(
"analyze_function",
{ procedure: next.procedure },
signal === undefined ? {} : { signal },
);
decompilations++;
if (!execution.ok) {
if (execution.error._tag === "AnalysisCancelledError")
return err(execution.error);
unknowns.push({
procedure: next.procedure,
address: null,
reason: execution.error.message,
});
continue;
}
const parsed = functionDossierSchema.safeParse(execution.value.result);
if (!parsed.success || execution.value.subject === null)
return err(
new AnalysisOutputError(
"trace_native_values",
"Function dossier lacks validated facts or artifact identity",
),
);
const dossier = parsed.data;
const address = dossier.procedure.address;
if (visited.has(address)) continue;
visited.add(next.procedure);
visited.add(address);
targetSha256 ??= execution.value.subject.sha256;
if (execution.value.subject.sha256 !== targetSha256)
return err(
new AnalysisOutputError(
"trace_native_values",
"Cross-function target digest mismatch",
),
);
const evidence = createEvidence(
execution.value.subject,
execution.value.provider,
{
operation: "analyze_function",
parameters: { procedure: next.procedure },
result: execution.value.result,
rawResult: execution.value.rawResult,
limitations: execution.value.limitations,
locations: execution.value.locations,
...(execution.value.analysisProfile === undefined
? {}
: { analysisProfile: execution.value.analysisProfile }),
},
);
const evidenceId = evidence.evidence_id;
procedures.push({
address,
depth: next.depth,
evidence_id: evidenceId,
provider: execution.value.provider.id,
analysis_profile_digest: execution.value.analysisProfile?.digest ?? null,
});
const flow = dossier.native_value_flow;
if (flow === null || !flow.available) {
unknowns.push({
procedure: address,
address: null,
reason: flow?.reason ?? "Provider has no native def-use model",
});
continue;
}
if (flow.truncated) {
truncated = true;
unknowns.push({
procedure: address,
address: null,
reason: "Provider p-code was truncated",
});
}
const ids = new Set<string>();
const qualified = (id: string) => `${address}/${id}`;
for (const operation of flow.operations) {
if (
operation.block_membership === "detached" ||
(operation.block_membership === "unavailable" && operation.is_dead)
)
continue;
const node = {
id: qualified(operation.id),
procedure: address,
evidence_id: evidenceId,
operation,
kind: "operation" as const,
parameter: null,
};
const size = Buffer.byteLength(JSON.stringify(node));
if (nodes.length >= input.max_nodes || bytes + size > 8 * 1024 * 1024) {
truncated = true;
break;
}
bytes += size;
ids.add(operation.id);
nodes.push(node);
}
for (const parameter of flow.parameters) {
if (nodes.length >= input.max_nodes) {
truncated = true;
break;
}
nodes.push({
id: `${address}/parameter:${parameter.ordinal}`,
procedure: address,
evidence_id: evidenceId,
kind: "parameter",
operation: null,
parameter,
});
}
for (const use of flow.parameter_uses) {
if (
!ids.has(use.use) ||
!nodes.some((node) => node.id === `${address}/parameter:${use.ordinal}`)
)
continue;
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: `${address}/parameter:${use.ordinal}`,
target: qualified(use.use),
input_index: use.input_index,
kind: "parameter-use",
status: "derived",
evidence_id: evidenceId,
});
}
for (const edge of flow.def_use) {
if (!ids.has(edge.definition) || !ids.has(edge.use)) continue;
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: qualified(edge.definition),
target: qualified(edge.use),
input_index: edge.input_index,
kind: "def-use",
status: "derived",
evidence_id: evidenceId,
});
}
for (const operation of flow.operations) {
if (
!ids.has(operation.id) ||
!["CALL", "CALLIND"].includes(operation.opcode)
)
continue;
if (callSites >= input.max_call_sites) {
truncated = true;
unknowns.push({
procedure: address,
address: operation.address,
reason: "Call-site resolution budget reached",
});
break;
}
callSites++;
const resolved = await analysis.execute(
"resolve_native_call_targets",
{ address: operation.address },
signal === undefined ? {} : { signal },
);
if (!resolved.ok) {
if (resolved.error._tag === "AnalysisCancelledError")
return err(resolved.error);
unknowns.push({
procedure: address,
address: operation.address,
reason: resolved.error.message,
});
continue;
}
const targets = nativeCallTargetsSchema.safeParse(resolved.value.result);
if (!targets.success)
return err(
new AnalysisOutputError(
"resolve_native_call_targets",
"Invalid static call resolution",
),
);
if (targets.data.targets.length === 0)
unknowns.push({
procedure: address,
address: operation.address,
reason: `Call target ${targets.data.status}`,
});
for (const target of targets.data.targets) {
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
const destination = target.procedure ?? target.address;
edges.push({
source: qualified(operation.id),
target: destination,
input_index: null,
kind: "call",
status: target.status,
evidence_id: evidenceId,
});
if (target.status !== "candidate")
callBindings.push({
caller: address,
callee: destination,
call: qualified(operation.id),
argument_count: Math.max(0, operation.inputs.length - 1),
output: operation.output !== null,
evidence_id: evidenceId,
});
if (next.depth < input.max_depth && target.status !== "candidate")
pending.push({ procedure: destination, depth: next.depth + 1 });
else if (!visited.has(destination)) {
truncated = true;
unknowns.push({
procedure: address,
address: operation.address,
reason:
target.status === "candidate"
? "Ambiguous call candidates were not traversed"
: "Call depth budget reached",
});
}
}
}
if (
truncated &&
(nodes.length >= input.max_nodes ||
edges.length >= input.max_edges ||
bytes >= 8 * 1024 * 1024)
)
break;
}
if (targetSha256 === undefined)
return err(
new AnalysisOutputError(
"trace_native_values",
"No seed function could be analyzed",
),
);
for (const binding of callBindings) {
const parameters = nodes.filter(
(node) => node.procedure === binding.callee && node.kind === "parameter",
);
if (parameters.length === 0)
unknowns.push({
procedure: binding.caller,
address: null,
reason: `Parameter bindings for ${binding.callee} are unavailable or omitted`,
});
for (const node of parameters) {
const ordinal = node.parameter?.ordinal;
if (ordinal === undefined || ordinal >= binding.argument_count) {
unknowns.push({
procedure: binding.caller,
address: null,
reason: `Argument ${ordinal ?? "unknown"} for ${binding.callee} was not recovered`,
});
continue;
}
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: binding.call,
target: node.id,
input_index: ordinal + 1,
kind: "argument-binding",
status: "derived",
evidence_id: binding.evidence_id,
});
}
if (binding.output)
for (const node of nodes.filter(
(node) =>
node.procedure === binding.callee &&
node.operation?.opcode === "RETURN" &&
node.operation.inputs.length > 1,
)) {
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: node.id,
target: binding.call,
input_index: 1,
kind: "return-binding",
status: "derived",
evidence_id: node.evidence_id,
});
}
}
const page = nodes.slice(input.offset, input.offset + input.limit);
const pageIds = new Set(page.map(({ id }) => id));
const result = nativeValueTraceSchema.parse({
seed: input.procedure,
target_sha256: targetSha256,
nodes: page,
edges: edges.filter(({ source }) => pageIds.has(source)),
procedures,
unknowns,
total_nodes: nodes.length,
total_edges: edges.length,
decompilations,
next_offset:
input.offset + page.length < nodes.length
? input.offset + page.length
: null,
truncated: truncated || page.length !== nodes.length,
limitations: [
"Static decompiler def-use graphs cover recovered block members; when membership is unavailable they exclude operations marked dead. Logical CALL argument positions bind to recovered HighParam ordinals and RETURN values bind to recovered CALL outputs; these are decompiler-derived dependencies, not original source or runtime observations. Missing parameters, variadic arguments and alias dependencies remain unknown.",
"LOAD and STORE are memory operations; object fields, persistent state and RNG semantics are not inferred from names or pseudocode.",
"Traversal caps depth, decompilations, call-site resolutions, nodes, edges and node payloads (8 MiB). Complete serialized output is bounded to 32 MiB. Pagination reruns analysis and returns edges whose source is on the node page; endpoints outside the page retain stable identities.",
],
});
if (Buffer.byteLength(JSON.stringify(result)) > 32 * 1024 * 1024)
return err(
new AnalysisOutputError(
"trace_native_values",
"Graph output exceeds 32 MiB; lower max_nodes, max_edges or page limit",
),
);
return ok(result);
};