fix(native): retain partial format facts and explicit coverage

Preserve XML and Interface Builder identity at their parsing boundary, retain usable Objective-C slots with precise coverage, and keep native trace failures distinct from absence. Add caller-selected Interface Builder summaries backed by complete retained Evidence, and preserve comparison limitations.

Reviewed fixes: #1969, #2088, #2108, #2513, #2639, #2684, #2731, #2759, #2875, #2888, #2889, #2970, #2971, #3002.

Validation: relevant native/domain focused lane passed 142 tests; earlier Interface Builder/MCP checks passed 24 tests. Real native UI and Ghidra producer coverage was not repeated.
This commit is contained in:
morluto committed 2026-10-14 08:29:16 +08:00
1 parent d4bd65c53c
commit 55dd21a5e2
59 files changed
+2602 -499

No files matched your search

@@ -12,6 +12,7 @@ import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisCapabilityUnavailableError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { EnhancedTools } from "../EnhancedTools.js";
import {
@@ -615,6 +616,25 @@ describe("native UI query outcomes", () => {
});
});
it("returns native seed resolution failures instead of reporting not found", async () => {
const result = await new EnhancedTools(
testAnalysis({
procedure_address: () =>
err(
new AnalysisOutputError(
"procedure_address",
"invalid address response",
),
),
}),
).execute("trace_native_ui_action", { action: "missing-selector" });
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisOutputError", operation: "procedure_address" },
});
});
it("returns cancellation instead of a successful trace during callee expansion", async () => {
const result = await new EnhancedTools(
testAnalysis({
@@ -125,6 +125,11 @@ export const traceNativeUiAction = async (
);
if (!native.ok && native.error._tag === "AnalysisCancelledError")
return err(native.error);
if (
!native.ok &&
native.error._tag !== "AnalysisCapabilityUnavailableError"
)
return err(native.error);
if (native.ok) {
const address = z.string().safeParse(native.value.result);
if (!address.success || native.value.subject?.sha256 !== targetSha256)
+311 -45
View File
@@ -8,7 +8,10 @@ import { ghidraFunctionDossier } from "../../domain/ghidraValues.fixture.js";
import { functionDossierSchema } from "../../domain/hopperValues.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { nativeValueTraceSchema } from "../../domain/native/nativeValueTrace.js";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import { ok, err } from "../../domain/result.js";
const subject = {
@@ -181,52 +184,71 @@ describe("native value parameter-use node membership", () => {
});
});
it("preserves operation IDs that collide with generated parameter IDs", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const address = base.procedure.address;
const execution = createAnalysisExecution(
{
...base,
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: [
node("parameter:0", address, "COPY"),
node("use", address, "COPY"),
],
def_use: [],
effects: [],
parameters: [{ ordinal: 0, name: "value", data_type: "/int" }],
parameter_uses: [{ ordinal: 0, use: "use", input_index: 1 }],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
},
},
provider,
{ subject },
);
const result = await traceNativeValues(
{ execute: async () => ok(execution) },
{ procedure: address, max_nodes: 2 },
);
if (!result.ok) throw result.error;
const parsedResult = nativeValueTraceSchema.parse(result.value);
expect(parsedResult).toMatchObject({
total_nodes: 2,
total_edges: 1,
edges: [
it.each([3, 4])(
"keeps parameter identity separate from colliding operation IDs with max_nodes=%i",
async (max_nodes) => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const address = base.procedure.address;
const execution = createAnalysisExecution(
{
source: `${address}/parameter:0`,
target: `${address}/use`,
kind: "parameter-use",
...base,
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: [
node("parameter:0", address, "COPY"),
node("parameter:0#1", address, "COPY"),
node("use", address, "COPY"),
],
def_use: [],
effects: [],
parameters: [{ ordinal: 0, name: "value", data_type: "/int" }],
parameter_uses: [{ ordinal: 0, use: "use", input_index: 1 }],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [],
},
},
],
});
});
provider,
{ subject },
);
const result = await traceNativeValues(
{ execute: async () => ok(execution) },
{ procedure: address, max_nodes },
);
if (!result.ok) throw result.error;
const parsedResult = nativeValueTraceSchema.parse(result.value);
expect(parsedResult).toMatchObject({
total_nodes: max_nodes,
total_edges: max_nodes === 3 ? 0 : 1,
edges:
max_nodes === 3
? []
: [
{
source: `${address}/parameter:0#2`,
target: `${address}/use`,
kind: "parameter-use",
},
],
});
expect(
parsedResult.nodes
.filter(({ kind }) => kind === "operation")
.map(({ id }) => id),
).toEqual([
`${address}/parameter:0`,
`${address}/parameter:0#1`,
`${address}/use`,
]);
expect(new Set(parsedResult.nodes.map(({ id }) => id)).size).toBe(
max_nodes,
);
},
);
});
const nativeFlowDossier = (
@@ -316,6 +338,97 @@ const callBindingAnalysis = (
},
});
describe("native value failed-callee traversal", () => {
it("attempts a repeated failed selector once and still analyzes a later callee", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const caller = nativeFlowDossier(base, {
address: "0x1000",
name: "caller",
operations: [
node("bad-1", "0x1100", "CALL"),
node("bad-2", "0x1104", "CALL"),
node("good", "0x1108", "CALL"),
],
parameters: [],
});
const good = nativeFlowDossier(base, {
address: "0x3000",
name: "good",
operations: [],
parameters: [],
});
const attempts: string[] = [];
const port: AnalysisOperationPort = {
execute: async (operation, parameters) => {
if (operation === "resolve_native_call_targets") {
const destination =
parameters.address === "0x1108" ? "0x3000" : "0x2000";
return ok(
createAnalysisExecution(
{
call_site: String(parameters.address),
procedure: "0x1000",
status: "direct",
mechanism: "direct",
targets: [
{
address: destination,
procedure: destination,
status: "direct",
basis: "provider-reference",
references: [],
},
],
limitations: [],
},
provider,
{ subject },
),
);
}
expect(operation).toBe("analyze_function");
const selector = String(parameters.procedure);
attempts.push(selector);
if (selector === "0x2000")
return err(
new AnalysisOutputError("analyze_function", "Callee unavailable"),
);
return ok(
createAnalysisExecution(
selector === "0x1000" ? caller : good,
provider,
{ subject },
),
);
},
};
// A new invocation retries the failed selector: failures are not cached
// across traces, and successful procedure identity remains separate.
for (let run = 0; run < 2; run++) {
attempts.length = 0;
const result = await traceNativeValues(port, {
procedure: "0x1000",
max_functions: 3,
});
if (!result.ok) throw result.error;
const trace = nativeValueTraceSchema.parse(result.value);
expect(attempts).toEqual(["0x1000", "0x2000", "0x3000"]);
expect(trace.decompilations).toBe(3);
expect(trace.procedures.map(({ address }) => address)).toEqual([
"0x1000",
"0x3000",
]);
expect(trace.unknowns).toContainEqual({
procedure: "0x2000",
address: null,
reason: expect.stringContaining("Callee unavailable"),
});
expect(trace.edges.filter(({ kind }) => kind === "call")).toHaveLength(3);
expect(trace.truncated).toBe(false);
}
});
});
describe("native value call-binding fan-out", () => {
it("preserves binding order and edge-budget behavior for repeated callees", async () => {
const callCount = 128;
@@ -558,3 +671,156 @@ describe("native value trace selector origin", () => {
]);
});
});
describe("native value node byte budgets", () => {
it("stops admitting parameters after an operation exceeds the byte budget", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const value = nativeFlowDossier(base, {
address: "0x1000",
name: "caller",
operations: [node("use", "0x1000", "a".repeat(9 * 1024 * 1024))],
parameters: [{ ordinal: 0, name: "value", data_type: "/int" }],
});
const result = await traceNativeValues(
{
execute: async () =>
ok(createAnalysisExecution(value, provider, { subject })),
},
{ procedure: "0x1000" },
);
if (!result.ok) throw result.error;
expect(nativeValueTraceSchema.parse(result.value)).toMatchObject({
truncated: true,
total_nodes: 0,
total_edges: 0,
nodes: [],
edges: [],
});
});
it.each([
{ label: "plain text", name: "a".repeat(9 * 1024 * 1024) },
{ label: "JSON escapes", name: "\0".repeat(2 * 1024 * 1024) },
])("rejects an oversized parameter encoded with $label", async ({ name }) => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const value = nativeFlowDossier(base, {
address: "0x1000",
name: "caller",
operations: [
node("parameter:0", "0x1000", "COPY"),
node("use", "0x1000", "MULTIEQUAL"),
],
parameters: [{ ordinal: 0, name, data_type: "/int" }],
});
const parsed = functionDossierSchema.parse(value);
if (!parsed.native_value_flow?.available)
throw new Error("Invalid fixture");
parsed.native_value_flow.parameter_uses = [
{ ordinal: 0, use: "use", input_index: 0 },
];
const result = await traceNativeValues(
{
execute: async () =>
ok(createAnalysisExecution(parsed, provider, { subject })),
},
{ procedure: "0x1000" },
);
if (!result.ok) throw result.error;
const trace = nativeValueTraceSchema.parse(result.value);
expect(trace).toMatchObject({
truncated: true,
total_nodes: 2,
total_edges: 0,
nodes: [
expect.objectContaining({ kind: "operation" }),
expect.objectContaining({ kind: "operation" }),
],
});
});
it("shares the byte budget across operation and parameter nodes", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const value = nativeFlowDossier(base, {
address: "0x1000",
name: "caller",
operations: [node("use", "0x1000", "MULTIEQUAL")],
parameters: [0, 1].map((ordinal) => ({
ordinal,
name: "a".repeat(5 * 1024 * 1024),
data_type: "/int",
})),
});
const parsed = functionDossierSchema.parse(value);
if (!parsed.native_value_flow?.available)
throw new Error("Invalid fixture");
parsed.native_value_flow.parameter_uses = [0, 1].map((ordinal) => ({
ordinal,
use: "use",
input_index: ordinal,
}));
const result = await traceNativeValues(
{
execute: async () =>
ok(createAnalysisExecution(parsed, provider, { subject })),
},
{ procedure: "0x1000" },
);
if (!result.ok) throw result.error;
const trace = nativeValueTraceSchema.parse(result.value);
expect(trace).toMatchObject({
truncated: true,
total_nodes: 2,
total_edges: 1,
});
expect(trace.nodes.map(({ id }) => id)).toEqual([
"0x1000/use",
"0x1000/parameter:0",
]);
expect(trace.edges[0]?.source).toBe("0x1000/parameter:0");
const retainedBytes = trace.nodes.reduce(
(total, value) => total + Buffer.byteLength(JSON.stringify(value)),
0,
);
expect(retainedBytes).toBeLessThanOrEqual(8 * 1024 * 1024);
});
});
describe("native value byte-bound call bindings", () => {
it("omits argument bindings to rejected callee parameter nodes", async () => {
const base = functionDossierSchema.parse(ghidraFunctionDossier());
const caller = nativeFlowDossier(base, {
address: "0x1000",
name: "caller",
operations: [node("call", "0x1000", "CALL")],
parameters: [],
});
const callee = nativeFlowDossier(base, {
address: "0x2000",
name: "callee",
operations: [node("return", "0x2000", "RETURN")],
parameters: [
{ ordinal: 0, name: "a".repeat(9 * 1024 * 1024), data_type: "/int" },
],
});
const result = await traceNativeValues(
callBindingAnalysis("0x1000", "0x2000", caller, callee),
{ procedure: "0x1000" },
);
if (!result.ok) throw result.error;
const trace = nativeValueTraceSchema.parse(result.value);
expect(trace.truncated).toBe(true);
expect(trace.nodes.map(({ kind }) => kind)).toEqual([
"operation",
"operation",
]);
expect(trace.edges.map(({ kind }) => kind)).toEqual([
"call",
"return-binding",
]);
expect(trace.unknowns).toContainEqual(
expect.objectContaining({
reason: "Parameter bindings for 0x2000 are unavailable or omitted",
}),
);
});
});
+63 -31
View File
@@ -12,6 +12,9 @@ import {
import { err, ok } from "../../domain/result.js";
import type { AnalysisOperationPort } from "../AnalysisProvider.js";
import type { EnhancedResult } from "../EnhancedToolTypes.js";
import { jsonParts } from "../../domain/jsonSerialization.js";
const NODE_PAYLOAD_BYTES = 8 * 1024 * 1024;
/** Compose bounded high-p-code def-use graphs across exactly referenced call destinations. */
export const traceNativeValues = async (
@@ -21,7 +24,6 @@ export const traceNativeValues = async (
): EnhancedResult => {
const input = nativeValueTraceInputSchema.parse(parameters);
const nodes: typeof nativeValueTraceSchema._output.nodes = [];
const nodeIds = new Set<string>();
const edges: typeof nativeValueTraceSchema._output.edges = [];
const procedures: typeof nativeValueTraceSchema._output.procedures = [];
const unknowns: typeof nativeValueTraceSchema._output.unknowns = [];
@@ -34,17 +36,46 @@ export const traceNativeValues = async (
evidence_id: string;
}[] = [];
const pending = [{ procedure: input.procedure, depth: 0 }];
const attempted = new Set<string>();
const visited = new Set<string>();
let targetSha256: string | undefined;
let truncated = false;
let decompilations = 0;
let callSites = 0;
let bytes = 0;
let nodeBudgetReached = false;
const retainNode = (value: (typeof nodes)[number]): boolean => {
if (nodeBudgetReached) return false;
if (nodes.length >= input.max_nodes) {
truncated = true;
nodeBudgetReached = true;
return false;
}
let size = 0;
// Reuse bounded JSON encoding to count escapes and UTF-8 expansion
// before allocating a complete serialized node that might not fit.
for (const part of jsonParts(value)) {
size += Buffer.byteLength(part);
if (size > NODE_PAYLOAD_BYTES - bytes) {
truncated = true;
nodeBudgetReached = true;
return false;
}
}
bytes += size;
nodes.push(value);
return true;
};
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 (
next === undefined ||
attempted.has(next.procedure) ||
visited.has(next.procedure)
)
continue;
if (decompilations >= input.max_functions) {
truncated = true;
unknowns.push({
@@ -54,6 +85,9 @@ export const traceNativeValues = async (
});
break;
}
// An exact selector is attempted once per trace, even on failure. Only
// successful dossiers establish canonical procedure identity in visited.
attempted.add(next.procedure);
const execution = await analysis.execute(
"analyze_function",
{ procedure: next.procedure },
@@ -135,6 +169,10 @@ export const traceNativeValues = async (
});
}
const ids = new Set<string>();
// Keep generated parameter identity independent of which operations fit
// the budget, while preserving every provider-supplied operation ID.
const operationIds = new Set(flow.operations.map(({ id }) => id));
const parameterIds = new Map<number, string>();
const qualified = (id: string) => `${address}/${id}`;
for (const operation of flow.operations) {
if (
@@ -150,44 +188,37 @@ export const traceNativeValues = async (
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;
if (!retainNode(node)) break;
ids.add(operation.id);
nodes.push(node);
nodeIds.add(node.id);
}
for (const parameter of flow.parameters) {
if (nodes.length >= input.max_nodes) {
truncated = true;
const parameterId = `parameter:${parameter.ordinal}`;
let localId = parameterId;
for (let suffix = 1; operationIds.has(localId); suffix++)
localId = `${parameterId}#${suffix}`;
const id = qualified(localId);
if (
!retainNode({
id,
procedure: address,
evidence_id: evidenceId,
kind: "parameter",
operation: null,
parameter,
})
)
break;
}
const id = `${address}/parameter:${parameter.ordinal}`;
nodes.push({
id,
procedure: address,
evidence_id: evidenceId,
kind: "parameter",
operation: null,
parameter,
});
nodeIds.add(id);
parameterIds.set(parameter.ordinal, id);
}
for (const use of flow.parameter_uses) {
if (
!ids.has(use.use) ||
!nodeIds.has(`${address}/parameter:${use.ordinal}`)
)
continue;
const source = parameterIds.get(use.ordinal);
if (!ids.has(use.use) || source === undefined) continue;
if (edges.length >= input.max_edges) {
truncated = true;
break;
}
edges.push({
source: `${address}/parameter:${use.ordinal}`,
source,
target: qualified(use.use),
input_index: use.input_index,
kind: "parameter-use",
@@ -295,9 +326,10 @@ export const traceNativeValues = async (
}
if (
truncated &&
(nodes.length >= input.max_nodes ||
(nodeBudgetReached ||
nodes.length >= input.max_nodes ||
edges.length >= input.max_edges ||
bytes >= 8 * 1024 * 1024)
bytes >= NODE_PAYLOAD_BYTES)
)
break;
}