feat(native): add investigation features (#486)

* feat(native): add UI and dispatch investigation workflows

* feat(ghidra): support macOS host validation

* docs: update native investigation capabilities

* feat(artifacts): decode compiled Interface Builder archives

* feat(ghidra): expose bounded p-code value flow

* test(ghidra): split host and cross-format verification

* fix(verify): follow complete result contracts

* refactor: remove unused authorization and schema helpers

* refactor: remove unused evidence result alias

* fix(ghidra): report jump-table evidence precisely

* fix(verify): align browser scenario fixture schema

* fix(setup): compare parsed client config structurally

* test(ghidra): verify AArch64 jump-table mappings

* fix(ghidra): recover AArch64 byte jump tables

* test(artifacts): verify compiled interface builder archives

* feat(native): trace UI actions through handlers

* fix(tests): update native trace and shutdown fixtures

* fix(verification): diagnose browser scenario failures

* fix(browser): wrap scenario snapshots in capture state

* fix(native): bind and bound investigation workflows

* fix(artifacts): preserve bounded interface builder evidence

* fix(ghidra): enforce admitted hosts and preflight tools

* fix(native): preserve trace cancellation and bounds

* test(application): expect bound analysis target evidence

* fix(native): preserve investigation bounds and cancellation

* fix(application): preserve bundle and unresolved trace evidence

* style(test): format artifact subject fixture
This commit is contained in:
morluto
2026-09-30 00:41:05 +08:00
committed by GitHub
parent fa26affc86
commit ed933d1893
87 changed files with 6771 additions and 375 deletions
+1
View File
@@ -275,6 +275,7 @@ export class ArtifactOperationError extends AnalysisError {
| "inventory_artifact"
| "inspect_artifact"
| "extract_artifact"
| "decode_interface_builder"
| "analyze_javascript_application",
readonly reason:
| "cancelled"
+36 -1
View File
@@ -92,7 +92,6 @@ export const ghidraNativeApiBoundary = () => ({
{
case_value: 0,
target_address: "0x401020",
data_addresses: ["0x403000"],
confidence: "medium" as const,
evidence: [
{
@@ -149,6 +148,42 @@ export const ghidraFunctionDossier = (includeAssembly = true): JsonValue => {
referenced_names: [],
basic_blocks: [{ start: "0x401000", end: "0x401006", successors: [] }],
native_api: ghidraNativeApiBoundary(),
native_value_flow: {
available: true,
provenance: "ghidra-high-pcode",
operations: [
{
id: "0x401000#0",
address: "0x401000",
sequence: 0,
opcode: "COPY",
is_dead: false,
inputs: [
{
kind: "constant",
size_bytes: 4,
location: null,
constant_hex: "2a",
},
],
output: {
kind: "register",
size_bytes: 4,
location: "register:0x0",
constant_hex: null,
},
},
],
def_use: [],
effects: [],
truncated: false,
omitted_operations_lower_bound: 0,
known_omitted_inputs: 0,
known_omitted_edges: 0,
limitations: [
"High p-code is a decompiler-derived intra-function representation, not original source or runtime behavior.",
],
},
limitations: [
"Unresolved computed or indirect flows without target addresses are not represented as reference edges.",
"Thunk and external classifications are Ghidra FunctionManager observations; they do not resolve targetless calls.",
+2
View File
@@ -4,6 +4,7 @@ import type { JsonValue } from "./jsonValue.js";
import { AnalysisOutputError, HopperProtocolError } from "./errors.js";
import { err, ok, type Result } from "./result.js";
import { nativeApiBoundarySchema } from "./nativeApiBoundary.js";
import { nativeValueFlowSchema } from "./nativeValueFlow.js";
export interface AddressedName {
readonly address: string;
@@ -176,6 +177,7 @@ export const functionDossierSchema = z
.strict(),
),
native_api: nativeApiBoundarySchema.nullable().default(null),
native_value_flow: nativeValueFlowSchema.nullable().default(null),
limitations: z.array(z.string()).default([]),
})
.strict();
+319
View File
@@ -0,0 +1,319 @@
import { describe, expect, it } from "vitest";
import { buildBinary, parseBinary } from "plist";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
parseInterfaceBuilderRecords,
} from "./interfaceBuilderGraph.js";
const hash = "a".repeat(64);
describe("compiled Interface Builder graph projection", () => {
it("normalizes object, hierarchy, action, outlet, and segue facts", () => {
const raw = {
"com.apple.ibtool.document.objects": {
controller: { customClass: "StoreViewController", label: "Store" },
button: { class: "UIButton", title: "Build" },
next: { customClass: "BuildViewController" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "buildTapped:",
destinationId: "controller",
},
{ type: "segue", identifier: "showBuild", destinationId: "next" },
],
controller: [
{ type: "outlet", label: "buildButton", destinationId: "button" },
],
},
"com.apple.ibtool.document.hierarchy": [
{ objectID: "controller", children: [{ objectID: "button" }] },
],
"com.apple.ibtool.document.classes": { StoreViewController: {} },
};
const decoded = parseInterfaceBuilderRecords(raw);
expect(decoded.objects).toHaveLength(3);
expect(decoded.connections.map(({ kind }) => kind)).toEqual([
"action",
"segue",
"outlet",
]);
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Views/Main.storyboardc/scene.nib/objects.nib",
archiveSha256: hash,
documentKind: "storyboard_scene",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
expect(result.graph.nodes.some(({ name }) => name === "buildTapped:")).toBe(
true,
);
expect(result.graph.nodes[0]?.evidence[0]).toMatchObject({
artifact_path: "Views/Main.storyboardc/scene.nib/objects.nib",
artifact_sha256: hash,
});
expect(result.graph.edges).toContainEqual(
expect.objectContaining({
relation: "segue_to",
resolution: "observed",
}),
);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "hierarchy:Views/Main.storyboardc/scene.nib/objects.nib",
status: "complete",
}),
);
});
it("keeps missing external destinations as unresolved evidence", () => {
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Legacy.nib",
archiveSha256: hash,
documentKind: "nib",
raw: {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
},
"com.apple.ibtool.document.connections": {
button: [
{ type: "action", label: "save:", destinationId: "external" },
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({ max_objects: 3 }),
});
expect(result.graph.edges).toContainEqual(
expect.objectContaining({
relation: "target_action",
resolution: "unresolved",
reason: "endpoint_omitted_by_object_limit",
evidence: [
expect.objectContaining({
kind: "interface_builder_resource",
artifact_path: "Legacy.nib",
artifact_sha256: hash,
}),
],
}),
);
const retainedNodes = new Set(result.graph.nodes.map(({ id }) => id));
expect(
result.graph.edges.every(
({ from, to }) =>
retainedNodes.has(from) && (to === null || retainedNodes.has(to)),
),
).toBe(true);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "graph_nodes",
status: "partial",
reason: "max_objects_reached",
}),
);
expect(result.graph.truncated).toBe(true);
});
it("reads recognized objects from a compiled NSKeyedArchiver object table", () => {
const bytes = buildBinary({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{ $class: { UID: 2 }, title: "Build", identifier: "build-button" },
{
$classname: "UIButton",
$classes: ["UIButton", "UIControl", "UIView", "NSObject"],
},
],
$top: { root: { UID: 1 } },
});
const parsed = parseInterfaceBuilderRecords(parseBinary(bytes));
expect(parsed.objects).toMatchObject([
{
id: "1",
kind: "control",
class_name: "UIButton",
name: "Build",
},
]);
});
});
describe("Interface Builder parser bounds", () => {
it("reports connections discarded by the parser's hard ceiling", () => {
const connections = Array.from({ length: 40_001 }, (_, index) => ({
type: "custom-connection",
label: `action${String(index)}:`,
}));
const raw = {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
},
"com.apple.ibtool.document.connections": { button: connections },
};
const parsed = parseInterfaceBuilderRecords(raw);
expect(parsed.connections).toHaveLength(40_000);
expect(parsed.omittedConnections).toBe(1);
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "Main.storyboardc/scene.nib",
archiveSha256: hash,
documentKind: "storyboard_scene",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:Main.storyboardc/scene.nib",
status: "partial",
omitted: 1,
}),
);
});
});
describe("keyed archive decoding and graph limits", () => {
it("preserves keyed archive UID identities, arrays, and control actions", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$version: 100000,
$objects: [
"$null",
{
subviews: [{ UID: 2 }],
$class: { UID: 5 },
},
{ $class: { UID: 6 } },
{ $class: { UID: 7 } },
{
source: { UID: 3 },
destination: { UID: 2 },
label: "runAction:",
$class: { UID: 8 },
},
{ $classname: "UIView", $classes: ["UIView", "NSObject"] },
{ $classname: "UIButton", $classes: ["UIButton", "UIView"] },
{
$classname: "ViewController",
$classes: ["ViewController", "NSObject"],
},
{
$classname: "NSNibControlConnector",
$classes: ["NSNibControlConnector", "NSObject"],
},
[{ UID: 1 }],
],
$top: { root: { UID: 9 } },
});
expect(parsed.objects.map(({ id }) => id)).toContain("2");
expect(parsed.hierarchy).toMatchObject([
{
objectID: "1",
children: [{ objectID: "2" }],
},
]);
expect(parsed.connections).toContainEqual(
expect.objectContaining({
kind: "action",
source_id: "2",
destination_id: "3",
label: "runAction:",
}),
);
});
it("reports records omitted by the parser's hard object ceiling", () => {
const objects = Object.fromEntries(
Array.from({ length: 20_001 }, (_, index) => [
`object-${index}`,
{ class: "UIView" },
]),
);
const parsed = parseInterfaceBuilderRecords({
"com.apple.ibtool.document.objects": objects,
});
expect(parsed.objects).toHaveLength(20_000);
expect(parsed.objectCount).toBe(20_001);
expect(parsed.omittedObjects).toBe(1);
});
it("keeps hierarchy edges out of the connection edge budget", () => {
const relativePath = "Main.nib";
const result = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath,
archiveSha256: hash,
documentKind: "nib",
raw: {
"com.apple.ibtool.document.objects": {
button: { class: "UIButton" },
controller: { customClass: "MainViewController" },
parent: { class: "UIView" },
child: { class: "UIView" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "run:",
destinationId: "controller",
},
],
},
"com.apple.ibtool.document.hierarchy": [
{
objectID: "parent",
children: [
{ objectID: "child", children: [{ objectID: "button" }] },
],
},
],
},
},
],
limits: interfaceBuilderLimitsSchema.parse({
max_objects: 20,
max_connections: 1,
}),
});
expect(
result.graph.edges.filter(({ relation }) => relation === "target_action"),
).toHaveLength(3);
expect(result.graph.coverage).toContainEqual(
expect.objectContaining({
facet: `connections:${relativePath}`,
status: "complete",
omitted: 0,
}),
);
});
});
+880
View File
@@ -0,0 +1,880 @@
import { z } from "zod";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceLimitsSchema,
} from "./nativeInvestigationGraph.js";
import { jsonValueSchema } from "./jsonValue.js";
const recordSchema = z.record(z.string(), z.unknown());
const objectNode = z.strictObject({
id: z.string().min(1),
kind: z.enum([
"view_controller",
"view",
"control",
"constraint",
"layout_guide",
"resource",
"placeholder",
"external_object",
"other",
]),
class_name: z.string().nullable(),
name: z.string().min(1),
attributes: z.record(z.string(), jsonValueSchema),
});
const connection = z.strictObject({
id: z.string().min(1),
kind: z.enum(["outlet", "action", "segue", "other"]),
source_id: z.string().min(1),
destination_id: z.string().nullable(),
label: z.string().nullable(),
attributes: z.record(z.string(), jsonValueSchema),
});
/** One compiled Interface Builder document projected from ibtool output. */
export const interfaceBuilderDocumentSchema = z.strictObject({
relative_path: z.string().min(1),
archive_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
document_kind: z.enum(["nib", "storyboard_scene"]),
object_count: z.number().int().nonnegative(),
connection_count: z.number().int().nonnegative(),
hierarchy_complete: z.boolean(),
});
/** Normalized read-only Interface Builder graph with archive provenance. */
export const interfaceBuilderAnalysisSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
documents: z.array(interfaceBuilderDocumentSchema).max(64),
graph: nativeInvestigationGraphSchema,
limitations: z.array(z.string()),
});
type InterfaceBuilderAnalysis = z.infer<typeof interfaceBuilderAnalysisSchema>;
export type InterfaceBuilderObject = z.infer<typeof objectNode>;
export type InterfaceBuilderConnection = z.infer<typeof connection>;
export interface InterfaceBuilderDocumentInput {
readonly relativePath: string;
readonly archiveSha256: string;
readonly documentKind: "nib" | "storyboard_scene";
readonly raw: unknown;
}
/** Parse ibtool dictionaries or compiled keyed archives into typed records. */
export const parseInterfaceBuilderRecords = (
value: unknown,
): {
readonly objects: readonly InterfaceBuilderObject[];
readonly connections: readonly InterfaceBuilderConnection[];
readonly hierarchy: readonly unknown[];
readonly classes: Readonly<Record<string, unknown>>;
readonly objectCount: number;
readonly omittedObjects: number;
readonly omittedConnections: number;
} => {
const root = record(value);
const keyed = parseKeyedArchive(root);
if (keyed !== null) return keyed;
const objectsRaw = record(root["com.apple.ibtool.document.objects"]);
const connectionsRaw = record(root["com.apple.ibtool.document.connections"]);
const hierarchyRaw = root["com.apple.ibtool.document.hierarchy"];
const classesRaw = record(root["com.apple.ibtool.document.classes"]);
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let omittedConnections = 0;
const objectEntries = Object.entries(objectsRaw);
for (const [id, raw] of objectEntries.slice(0, 20_000)) {
const attributes = record(raw);
const className = firstString(
attributes["customClass"],
attributes["class"],
attributes["isa"],
);
const label = firstString(
attributes["label"],
attributes["title"],
attributes["name"],
className,
);
objects.push(
objectNode.parse({
id,
kind: classifyObject(className),
class_name: className,
name: label ?? id,
attributes: jsonSafeRecord(attributes),
}),
);
}
for (const [sourceId, rawConnections] of Object.entries(connectionsRaw)) {
if (!Array.isArray(rawConnections)) continue;
for (const [index, raw] of rawConnections.entries()) {
if (connections.length >= 40_000) {
omittedConnections += rawConnections.length - index;
break;
}
const item = record(raw);
const type = firstString(item.type, item.connectionType) ?? "unknown";
const destination = firstString(
item["destination-id"],
item.destinationId,
);
const label = firstString(item.label, item.selector, item.identifier);
connections.push(
connection.parse({
id: `${sourceId}:connection:${index}`,
kind: classifyConnection(type),
source_id: sourceId,
destination_id: destination,
label,
attributes: jsonSafeRecord(item),
}),
);
}
}
return {
objects,
connections,
hierarchy: Array.isArray(hierarchyRaw) ? hierarchyRaw.slice(0, 20_000) : [],
classes: classesRaw,
objectCount: objectEntries.length,
omittedObjects: Math.max(0, objectEntries.length - 20_000),
omittedConnections,
};
};
/** Project class and connection objects from an NSKeyedArchiver object table. */
const parseKeyedArchive = (
root: Record<string, unknown>,
): ReturnType<typeof parseInterfaceBuilderRecords> | null => {
if (root.$archiver !== "NSKeyedArchiver" || !Array.isArray(root.$objects))
return null;
const objectTable = root.$objects;
const resolve = (value: unknown, depth = 0): unknown => {
if (depth > 16) return null;
const uid = record(value).UID;
if (typeof uid === "number") {
const target = objectTable[uid];
const resolved = target === undefined ? null : resolve(target, depth + 1);
return typeof resolved === "object" &&
resolved !== null &&
!Array.isArray(resolved)
? { ...resolved, archiveUID: uid }
: resolved;
}
if (Array.isArray(value))
return value.map((item) => resolve(item, depth + 1));
if (typeof value !== "object" || value === null) return value;
const output: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value)) {
if (key === "$class") {
const classObject = record(
typeof record(child).UID === "number"
? objectTable[record(child).UID as number]
: child,
);
output.className = firstString(classObject.$classname);
} else output[key] = resolve(child, depth + 1);
}
return output;
};
const toHierarchy = (value: unknown, depth = 0): unknown[] => {
if (depth > 32) return [];
if (Array.isArray(value))
return value.flatMap((item) => toHierarchy(item, depth + 1));
if (typeof value !== "object" || value === null) return [];
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
const children = Object.entries(item)
.filter(([key]) =>
/(?:subviews|contentview|childviewcontrollers|children|views)$/iu.test(
key,
),
)
.flatMap(([, child]) => toHierarchy(child, depth + 1));
return objectId === null ? children : [{ objectID: objectId, children }];
};
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
let omittedConnections = 0;
for (const [index, raw] of objectTable.entries()) {
if (index === 0) continue;
const resolved = record(resolve(raw));
const className = firstString(resolved.className);
if (className === null) continue;
objectCount += 1;
const fields = Object.fromEntries(
Object.entries(resolved).filter(([key]) => key !== "className"),
);
const authoredId = firstString(fields.objectID, fields["object-id"]);
const objectId =
authoredId ??
(typeof fields.archiveUID === "number"
? String(fields.archiveUID)
: String(index));
const kind = classifyObject(className);
if (objects.length < 20_000)
objects.push(
objectNode.parse({
id: objectId,
kind,
class_name: className,
name:
firstString(
fields.label,
fields.title,
fields.identifier,
fields.accessibilityLabel,
className,
) ?? `object ${String(index)}`,
attributes: jsonSafeRecord(fields),
}),
);
if (
/(?:Outlet|Connection|Segue|ActionConnection|ControlConnector)/iu.test(
className,
)
) {
const controlAction = /ControlConnector/iu.test(className);
const source = firstObjectReference(
controlAction ? fields.destination : fields.source,
controlAction ? fields.to : fields.from,
controlAction ? fields.target : fields.owner,
);
if (source === null) continue;
const kind = controlAction ? "action" : classifyConnection(className);
const parsedConnection = connection.parse({
id: `archive:${objectId}`,
kind,
source_id: source,
destination_id: firstObjectReference(
controlAction ? fields.source : fields.destination,
controlAction ? fields.from : fields.to,
controlAction ? fields.owner : fields.target,
),
label: firstString(
fields.label,
fields.selector,
fields.identifier,
fields.action,
),
attributes: jsonSafeRecord(fields),
});
if (connections.length < 40_000) connections.push(parsedConnection);
else omittedConnections += 1;
}
}
const top = record(root.$top);
const topObject = resolve(top.root ?? top.UITopLevelObjectsKey);
const hierarchy = toHierarchy(topObject);
const classes = Object.fromEntries(
objectTable.flatMap((raw) => {
const item = record(raw);
const name = firstString(item.$classname);
return name === null
? []
: [
[
name,
{
superclasses: Array.isArray(item.$classes) ? item.$classes : [],
},
],
];
}),
);
return {
objects,
connections,
hierarchy,
classes,
objectCount,
omittedObjects: Math.max(0, objectCount - 20_000),
omittedConnections,
};
};
/** Build the graph returned by the static Interface Builder archive decoder. */
export const buildInterfaceBuilderAnalysis = (input: {
readonly targetSha256: string;
readonly toolVersion: string;
readonly documents: readonly InterfaceBuilderDocumentInput[];
readonly limits: z.output<typeof interfaceBuilderLimitsSchema>;
}) => {
const nodes = new Map<
string,
z.infer<
typeof import("./nativeInvestigationGraph.js").nativeInvestigationNodeSchema
>
>();
const edges: z.infer<
typeof import("./nativeInvestigationGraph.js").nativeInvestigationEdgeSchema
>[] = [];
const coverage = [] as Array<{
facet: string;
status: "complete" | "partial" | "unsupported" | "not_requested";
reason: string | null;
examined: number;
omitted: number;
}>;
const summaries: Array<z.infer<typeof interfaceBuilderDocumentSchema>> = [];
let truncated = false;
let omittedObjects = 0;
let omittedConnections = 0;
let omittedGraphNodes = 0;
for (const document of input.documents.slice(0, input.limits.max_documents)) {
const parsed = parseInterfaceBuilderRecords(document.raw);
const prefix = `ib:${document.relativePath}:`;
const rootId = `${prefix}root`;
const objectIds = new Set(parsed.objects.map(({ id }) => id));
const evidenceFor = (description: string) => [
{
kind: "interface_builder_resource" as const,
description: `${document.relativePath}: ${description}`,
location: { address: null, file_offset: null },
artifact_path: document.relativePath,
artifact_sha256: document.archiveSha256,
},
];
const addNode = (
node: z.infer<
typeof import("./nativeInvestigationGraph.js").nativeInvestigationNodeSchema
>,
): boolean => {
if (nodes.has(node.id)) return true;
if (nodes.size >= input.limits.max_objects) {
truncated = true;
omittedGraphNodes += 1;
return false;
}
nodes.set(node.id, node);
return true;
};
const rootNode = {
id: rootId,
kind:
document.documentKind === "nib"
? ("scene" as const)
: ("storyboard" as const),
name: document.relativePath,
location: null,
attributes: { document_kind: document.documentKind },
evidence: evidenceFor("compiled document"),
};
addNode(rootNode);
let documentObjectCount = 0;
for (const object of parsed.objects.slice(0, input.limits.max_objects)) {
const id = `${prefix}object:${object.id}`;
const kind = object.kind === "other" ? "unknown" : object.kind;
if (
!addNode({
id,
kind,
name: object.name,
location: null,
attributes: {
...object.attributes,
interface_builder_object_id: object.id,
class_name: object.class_name,
},
evidence: evidenceFor(`object ${object.id}`),
})
) {
break;
}
documentObjectCount += 1;
}
let connectionEdgeCount = 0;
let hierarchyEdgeCount = 0;
let documentOmittedConnections = 0;
let documentOmittedHierarchyEdges = 0;
const objectNodeId = (objectId: string): string =>
`${prefix}object:${objectId}`;
const addEdge = (
edge: (typeof edges)[number],
isHierarchy: boolean,
): void => {
if (
isHierarchy
? hierarchyEdgeCount >= input.limits.max_objects
: connectionEdgeCount >= input.limits.max_connections * 3
) {
truncated = true;
if (isHierarchy) {
documentOmittedHierarchyEdges += 1;
} else {
omittedConnections += 1;
documentOmittedConnections += 1;
}
return;
}
edges.push(edge);
if (isHierarchy) hierarchyEdgeCount += 1;
else connectionEdgeCount += 1;
};
const connect = (
id: string,
from: string,
to: string | null,
relation: "contains" | "outlet_to" | "target_action" | "segue_to",
description: string,
reason?: string,
) => {
if (!nodes.has(from)) {
truncated = true;
if (relation === "contains" && id.includes(":hierarchy:")) {
documentOmittedHierarchyEdges += 1;
} else {
omittedConnections += 1;
documentOmittedConnections += 1;
}
return;
}
const evidence = evidenceFor(description);
const unresolvedEndpoint = to !== null && !nodes.has(to);
if (unresolvedEndpoint) truncated = true;
const edgeTo = unresolvedEndpoint ? null : to;
const edgeReason = unresolvedEndpoint
? "endpoint_omitted_by_object_limit"
: (reason ?? "destination_unresolved");
addEdge(
edgeTo === null
? {
id,
from,
to: null,
relation,
resolution: "unresolved",
reason: edgeReason,
evidence,
limitations: [],
}
: {
id,
from,
to: edgeTo,
relation,
resolution: "observed",
evidence,
limitations: [],
},
relation === "contains" && id.includes(":hierarchy:"),
);
};
let hierarchyCount = 0;
let hierarchyTruncated = false;
const visitHierarchy = (value: unknown, parentId: string): void => {
if (hierarchyCount >= input.limits.max_objects) {
truncated = true;
hierarchyTruncated = true;
return;
}
if (Array.isArray(value)) {
for (const child of value) visitHierarchy(child, parentId);
return;
}
if (typeof value !== "object" || value === null) return;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
let nextParent = parentId;
if (objectId !== null) {
const known = objectIds.has(objectId);
const childId = known
? objectNodeId(objectId)
: `${prefix}unknown:${objectId}`;
if (
!known &&
!addNode({
id: childId,
kind: "unknown",
name: firstString(item.label, item.name) ?? objectId,
location: null,
attributes: { interface_builder_object_id: objectId },
evidence: evidenceFor(`hierarchy item ${objectId}`),
})
)
hierarchyTruncated = true;
connect(
`${prefix}hierarchy:${parentId}:${childId}`,
parentId,
childId,
"contains",
`hierarchy ${objectId}`,
);
nextParent = childId;
hierarchyCount += 1;
}
visitHierarchy(item.children, nextParent);
};
for (const hierarchy of parsed.hierarchy) visitHierarchy(hierarchy, rootId);
for (const [index, item] of parsed.connections
.slice(0, input.limits.max_connections)
.entries()) {
const sourceId = objectNodeId(item.source_id);
if (!nodes.has(sourceId))
addNode({
id: sourceId,
kind: "unknown",
name: item.source_id,
location: null,
attributes: { interface_builder_object_id: item.source_id },
evidence: evidenceFor(`connection source ${item.source_id}`),
});
const destinationId =
item.destination_id === null ? null : objectNodeId(item.destination_id);
if (item.kind === "action") {
const actionId = `${prefix}action:${item.id}`;
const selectorId =
item.label === null
? null
: `${prefix}selector:${item.destination_id ?? "unknown"}:${item.label}`;
addNode({
id: actionId,
kind: "action",
name: item.label ?? "unlabeled action",
location: null,
attributes: {
selector: item.label,
destination_id: item.destination_id,
...item.attributes,
},
evidence: evidenceFor(`action ${item.id}`),
});
connect(
`${actionId}:source`,
sourceId,
actionId,
"target_action",
`action source ${item.source_id}`,
);
if (selectorId !== null) {
addNode({
id: selectorId,
kind: "objc_selector",
name: item.label ?? "unknown selector",
location: null,
attributes: { destination_id: item.destination_id },
evidence: evidenceFor(`selector ${item.label}`),
});
connect(
`${actionId}:selector`,
actionId,
selectorId,
"target_action",
`selector ${item.label}`,
);
}
if (destinationId === null || !nodes.has(destinationId))
connect(
`${actionId}:destination`,
actionId,
null,
"target_action",
`action destination ${item.destination_id ?? "missing"}`,
"destination_object_missing_or_external",
);
else
connect(
`${actionId}:destination`,
actionId,
destinationId,
"target_action",
`action destination ${item.destination_id}`,
);
} else if (item.kind === "outlet") {
const outletId = `${prefix}outlet:${item.id}`;
addNode({
id: outletId,
kind: "outlet",
name: item.label ?? item.id,
location: null,
attributes: item.attributes,
evidence: evidenceFor(`outlet ${item.id}`),
});
connect(
`${outletId}:source`,
sourceId,
outletId,
"contains",
`outlet source ${item.source_id}`,
);
if (destinationId === null || !nodes.has(destinationId))
connect(
`${outletId}:destination`,
outletId,
null,
"outlet_to",
`outlet ${item.label ?? item.id}`,
"destination_object_missing_or_external",
);
else
connect(
`${outletId}:destination`,
outletId,
destinationId,
"outlet_to",
`outlet ${item.label ?? item.id}`,
);
} else if (item.kind === "segue") {
if (destinationId === null || !nodes.has(destinationId))
connect(
`${prefix}segue:${index}`,
sourceId,
null,
"segue_to",
`segue ${item.label ?? item.id}`,
"destination_scene_missing",
);
else
connect(
`${prefix}segue:${index}`,
sourceId,
destinationId,
"segue_to",
`segue ${item.label ?? item.id}`,
);
} else {
connect(
`${prefix}unknown-connection:${index}`,
sourceId,
null,
"contains",
`connection type ${item.kind}`,
"unsupported_connection_type",
);
}
}
const objectsTruncated =
parsed.omittedObjects > 0 || parsed.objects.length > documentObjectCount;
const parserOmittedConnections = parsed.omittedConnections;
const connectionsTruncated =
parserOmittedConnections > 0 ||
parsed.connections.length > input.limits.max_connections;
omittedObjects +=
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount);
omittedConnections +=
Math.max(0, parsed.connections.length - input.limits.max_connections) +
parserOmittedConnections;
summaries.push({
relative_path: document.relativePath,
archive_sha256: document.archiveSha256,
document_kind: document.documentKind,
object_count: parsed.objectCount,
connection_count: parsed.connections.length + parserOmittedConnections,
hierarchy_complete: parsed.hierarchy.length > 0 && !truncated,
});
coverage.push(
{
facet: `objects:${document.relativePath}`,
status: objectsTruncated ? "partial" : "complete",
reason: objectsTruncated ? "object_limit_reached" : null,
examined: documentObjectCount,
omitted:
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount),
},
{
facet: `connections:${document.relativePath}`,
status:
connectionsTruncated || documentOmittedConnections > 0
? "partial"
: "complete",
reason:
connectionsTruncated || documentOmittedConnections > 0
? "connection_limit_reached"
: null,
examined: Math.min(
parsed.connections.length,
input.limits.max_connections,
),
omitted:
Math.max(
0,
parsed.connections.length - input.limits.max_connections,
) +
documentOmittedConnections +
parserOmittedConnections,
},
{
facet: `hierarchy:${document.relativePath}`,
status:
parsed.hierarchy.length === 0
? "unsupported"
: hierarchyTruncated || documentOmittedHierarchyEdges > 0
? "partial"
: "complete",
reason:
parsed.hierarchy.length === 0
? "archive_hierarchy_not_decoded"
: hierarchyTruncated || documentOmittedHierarchyEdges > 0
? "graph_limit_reached"
: null,
examined: hierarchyCount,
omitted: documentOmittedHierarchyEdges,
},
{
facet: `classes:${document.relativePath}`,
status:
Object.keys(parsed.classes).length > 0 ? "complete" : "unsupported",
reason:
Object.keys(parsed.classes).length > 0
? null
: "archive_class_table_not_decoded",
examined: Object.keys(parsed.classes).length,
omitted: 0,
},
);
}
if (input.documents.length > input.limits.max_documents) {
truncated = true;
coverage.push({
facet: "documents",
status: "partial",
reason: "document_limit_reached",
examined: input.limits.max_documents,
omitted: input.documents.length - input.limits.max_documents,
});
}
if (omittedGraphNodes > 0)
coverage.push({
facet: "graph_nodes",
status: "partial",
reason: "max_objects_reached",
examined: nodes.size,
omitted: omittedGraphNodes,
});
return interfaceBuilderAnalysisSchema.parse({
target_sha256: input.targetSha256,
documents: summaries,
graph: {
target_sha256: input.targetSha256,
provider: {
id: "rea-artifact-graph",
version: "1",
tool_version: input.toolVersion,
},
nodes: [...nodes.values()],
edges,
coverage,
truncated: truncated || omittedObjects > 0 || omittedConnections > 0,
},
limitations: [
"The graph reflects recognized Interface Builder archive fields and connections; omitted private or unrecognized archive fields remain unknown.",
"A target-action selector is an Interface Builder observation and does not prove that the binary contains a matching implementation.",
"Decoded constraints, runtime visibility, dynamic UI creation, and pixel geometry are not inferred from these archives.",
],
});
};
const record = (value: unknown): Record<string, unknown> =>
recordSchema.safeParse(value).data ?? {};
const firstString = (...values: unknown[]): string | null => {
for (const value of values)
if (typeof value === "string" && value.length > 0) return value;
return null;
};
const firstObjectReference = (...values: unknown[]): string | null => {
for (const value of values) {
const direct = firstString(value);
if (direct !== null) return direct;
const item = record(value);
const objectId = firstString(
item.objectID,
item["object-id"],
item.id,
item.identifier,
typeof item.archiveUID === "number" ? String(item.archiveUID) : null,
);
if (objectId !== null) return objectId;
}
return null;
};
const classifyObject = (
className: string | null,
): InterfaceBuilderObject["kind"] => {
const value = className?.toLowerCase() ?? "";
if (value.includes("constraint")) return "constraint";
if (value.includes("layoutguide")) return "layout_guide";
if (value.includes("placeholder") || value.includes("firstresponder"))
return "placeholder";
if (
value.includes("image") ||
value.includes("color") ||
value.includes("font")
)
return "resource";
if (value.includes("external")) return "external_object";
if (value.includes("viewcontroller") || value.includes("windowcontroller"))
return "view_controller";
if (
value.includes("button") ||
value.includes("control") ||
value.includes("textfield") ||
value.includes("slider") ||
value.includes("menuitem")
)
return "control";
if (
value.includes("view") ||
value.includes("window") ||
value.includes("cell")
)
return "view";
return "other";
};
const classifyConnection = (
type: string,
): InterfaceBuilderConnection["kind"] => {
const value = type.toLowerCase();
if (value.includes("outlet")) return "outlet";
if (value.includes("action")) return "action";
if (value.includes("segue")) return "segue";
return "other";
};
const jsonSafeRecord = (value: Record<string, unknown>) =>
Object.fromEntries(
Object.entries(value).flatMap(([key, item]) => {
try {
const serialized = JSON.stringify(item);
if (serialized === undefined) return [];
const parsed = jsonValueSchema.safeParse(JSON.parse(serialized));
return parsed.success ? [[key, parsed.data]] : [];
} catch {
return [];
}
}),
);
/** Hard limits shared by Interface Builder archive aggregation and tracing. */
export const interfaceBuilderLimitsSchema = z.strictObject({
max_documents: z.number().int().min(1).max(64).default(64),
max_objects: z.number().int().min(1).max(20_000).default(20_000),
max_connections: z.number().int().min(1).max(40_000).default(40_000),
trace: nativeInvestigationTraceLimitsSchema.default({
max_depth: 8,
max_nodes: 250,
max_edges: 500,
}),
});
+1 -1
View File
@@ -52,6 +52,7 @@ const jumpTableDataSourceSchema = z
provenance: z.enum([
"ghidra-decompiler-load-table",
"ghidra-dispatch-block-data-reference",
"ghidra-aarch64-byte-table",
]),
entry_size_bytes: z.number().int().min(1).nullable(),
entry_count: z.number().int().min(0).nullable(),
@@ -64,7 +65,6 @@ const jumpTableMappingSchema = z
.object({
case_value: z.number().int().nullable(),
target_address: z.string().min(1),
data_addresses: z.array(z.string().min(1)),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
})
+344
View File
@@ -0,0 +1,344 @@
import { describe, expect, it } from "vitest";
import {
nativeInvestigationGraphSchema,
joinInterfaceBuilderDispatch,
traceNativeInvestigationGraph,
} from "./nativeInvestigationGraph.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
} from "./interfaceBuilderGraph.js";
const evidence = [
{
kind: "reference" as const,
description: "fixture edge",
location: { address: "0x1000", file_offset: 0 },
artifact_path: null,
artifact_sha256: null,
},
];
const graph = nativeInvestigationGraphSchema.parse({
target_sha256: "a".repeat(64),
provider: { id: "fixture", version: "1", tool_version: "test" },
nodes: [
{
id: "a",
kind: "control",
name: "button",
location: null,
attributes: {},
evidence,
},
{
id: "b",
kind: "function",
name: "handler",
location: null,
attributes: {},
evidence,
},
{
id: "c",
kind: "state_value",
name: "balance",
location: null,
attributes: {},
evidence,
},
],
edges: [
{
id: "1",
from: "a",
to: "b",
relation: "target_action",
resolution: "observed",
evidence,
limitations: [],
},
{
id: "2",
from: "b",
to: "c",
relation: "writes",
resolution: "inferred",
evidence,
limitations: ["static slice"],
},
{
id: "3",
from: "b",
to: null,
relation: "swift_witness_dispatch",
resolution: "unresolved",
reason: "witness table unavailable",
evidence,
limitations: [],
},
],
coverage: [],
truncated: false,
});
describe("native investigation graph traces", () => {
it("retains observed and inferred route edges plus unresolved dispatch", () => {
const trace = traceNativeInvestigationGraph(graph, { start: "a" });
expect(trace.nodes.map(({ id }) => id)).toEqual(["a", "b", "c"]);
expect(trace.edges.map(({ resolution }) => resolution)).toEqual([
"observed",
"inferred",
]);
expect(trace.unresolved).toHaveLength(1);
expect(trace.unresolved[0]).toMatchObject({
reason: "witness table unavailable",
});
const fromHandler = traceNativeInvestigationGraph(graph, { start: "b" });
expect(fromHandler.unresolved[0]).toMatchObject({
relation: "swift_witness_dispatch",
reason: "witness table unavailable",
});
});
it("stops at explicit node and edge bounds", () => {
const trace = traceNativeInvestigationGraph(graph, {
start: "a",
limits: { max_nodes: 2, max_edges: 1 },
});
expect(trace.truncated).toBe(true);
expect(trace.reason).toBe("max_edges_reached");
expect(trace.nodes).toHaveLength(2);
});
it("does not retain a resolved edge beyond the depth boundary", () => {
const trace = traceNativeInvestigationGraph(graph, {
start: "a",
limits: { max_depth: 0 },
});
expect(trace.nodes.map(({ id }) => id)).toEqual(["a"]);
expect(trace.edges).toEqual([]);
expect(trace.truncated).toBe(true);
expect(trace.reason).toBe("max_depth_reached");
});
it("reports an unknown seed instead of treating it as an empty answer", () => {
expect(
traceNativeInvestigationGraph(graph, { start: "missing" }),
).toMatchObject({
reason: "start_node_missing",
nodes: [],
truncated: false,
});
});
});
describe("Interface Builder dispatch joins", () => {
it("joins a UI action to the target controller class, not the source control", () => {
const ui = buildInterfaceBuilderAnalysis({
targetSha256: "b".repeat(64),
toolVersion: "test",
documents: [
{
relativePath: "Main.storyboardc/scene.nib/objects.nib",
archiveSha256: "c".repeat(64),
documentKind: "storyboard_scene",
raw: {
"com.apple.ibtool.document.objects": {
controller: { customClass: "BuildViewController" },
button: { class: "UIButton", title: "Build" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "buildTapped:",
destinationId: "controller",
},
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
const joined = joinInterfaceBuilderDispatch(ui.graph, {
objc_classes: [],
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
selector: "buildTapped:",
method_type: "instance",
implementation_address: "0x1000",
location: { address: "0x1000", file_offset: 0 },
decode: { status: "decoded", reason: null },
evidence,
},
],
swift_conformances: [],
swift_dispatch_slots: [],
swift_symbols: [],
relative_pointers: [],
coverage: [],
db_save_result: null,
});
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
to: "native:function:0x1000",
}),
);
});
it("chooses an instance method and matches category-qualified owner names", () => {
const ui = buildInterfaceBuilderAnalysis({
targetSha256: "b".repeat(64),
toolVersion: "test",
documents: [
{
relativePath: "Main.nib",
archiveSha256: "c".repeat(64),
documentKind: "nib",
raw: {
"com.apple.ibtool.document.objects": {
controller: { customClass: "BuildViewController" },
button: { class: "UIButton" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "buildTapped:",
destinationId: "controller",
},
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
const metadata = {
objc_classes: [],
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
selector: "buildTapped:",
method_type: "class" as const,
implementation_address: "0x9999",
location: { address: "0x9999", file_offset: 0 },
decode: { status: "decoded" as const, reason: null },
evidence,
},
{
class_name: "BuildViewController(BuilderActions)",
selector: "buildTapped:",
method_type: "instance" as const,
implementation_address: "0x1000",
location: { address: "0x1000", file_offset: 0 },
decode: { status: "decoded" as const, reason: null },
evidence,
},
],
swift_conformances: [],
swift_dispatch_slots: [],
swift_symbols: [],
relative_pointers: [],
coverage: [],
db_save_result: null,
};
const joined = joinInterfaceBuilderDispatch(ui.graph, metadata);
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
to: "native:function:0x1000",
}),
);
expect(joined.edges).not.toContainEqual(
expect.objectContaining({ to: "native:function:0x9999" }),
);
});
});
describe("placeholder dispatch joins", () => {
it("keeps a unique selector match inferred when the receiver is only a placeholder", () => {
const ui = buildInterfaceBuilderAnalysis({
targetSha256: "b".repeat(64),
toolVersion: "test",
documents: [
{
relativePath: "Main.storyboardc/scene.nib/objects.nib",
archiveSha256: "c".repeat(64),
documentKind: "storyboard_scene",
raw: {
"com.apple.ibtool.document.objects": {
receiver: { class: "NSStoryboardPlaceholder" },
button: { class: "UIButton", title: "Build" },
},
"com.apple.ibtool.document.connections": {
button: [
{
type: "action",
label: "buildTapped:",
destinationId: "receiver",
},
],
},
},
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
const joined = joinInterfaceBuilderDispatch(ui.graph, {
objc_classes: [],
objc_protocols: [],
swift_decls: [],
objc_ivars: [],
objc_dispatch_implementations: [
{
class_name: "BuildViewController",
selector: "buildTapped:",
method_type: "instance",
implementation_address: "0x1000",
location: { address: "0x1000", file_offset: null },
decode: { status: "partial", reason: "symbol_name_only" },
evidence,
},
],
swift_conformances: [],
swift_dispatch_slots: [],
swift_symbols: [],
relative_pointers: [],
coverage: [],
db_save_result: null,
});
expect(joined.edges).toContainEqual(
expect.objectContaining({
relation: "objc_dispatch",
resolution: "inferred",
to: "native:function:0x1000",
limitations: [
expect.stringContaining("receiver is an unresolved placeholder"),
],
}),
);
expect(joined.coverage).toContainEqual(
expect.objectContaining({
facet: "ui_to_objc_dispatch",
status: "partial",
reason: "some_action_receivers_remain_placeholders",
}),
);
});
});
+424
View File
@@ -0,0 +1,424 @@
import { z } from "zod";
import {
nativeMetadataEvidenceSchema,
nativeMetadataLocationSchema,
type ObjcSwiftMetadata,
} from "./objcSwiftMetadata.js";
import { jsonValueSchema } from "./jsonValue.js";
/** Entity kinds shared by decoded Interface Builder archives and native code. */
export const nativeInvestigationNodeKindSchema = z.enum([
"storyboard",
"scene",
"view_controller",
"view",
"control",
"constraint",
"layout_guide",
"resource",
"placeholder",
"external_object",
"outlet",
"action",
"segue",
"objc_class",
"objc_selector",
"swift_declaration",
"swift_requirement",
"dispatch_table",
"dispatch_slot",
"thunk",
"function",
"state_value",
"global_value",
"field",
"branch_condition",
"sink",
"unknown",
]);
type NativeInvestigationNodeKind = z.infer<
typeof nativeInvestigationNodeKindSchema
>;
/** One UI, dispatch, or value entity with optional decoded source location. */
export const nativeInvestigationNodeSchema = z.strictObject({
id: z.string().min(1),
kind: nativeInvestigationNodeKindSchema,
name: z.string().min(1),
location: nativeMetadataLocationSchema.nullable(),
attributes: z.record(z.string(), jsonValueSchema),
evidence: z.array(nativeMetadataEvidenceSchema),
});
type NativeInvestigationNode = z.infer<typeof nativeInvestigationNodeSchema>;
/** Relationship types preserve UI wiring, native dispatch, and value flow. */
export const nativeInvestigationRelationSchema = z.enum([
"contains",
"outlet_to",
"target_action",
"segue_to",
"objc_dispatch",
"swift_witness_dispatch",
"swift_vtable_dispatch",
"thunk_to",
"direct_call",
"reads",
"writes",
"flows_to",
"controls",
]);
type NativeInvestigationRelation = z.infer<
typeof nativeInvestigationRelationSchema
>;
/** An observed, inferred, or unresolved relationship between entities. */
export const nativeInvestigationEdgeSchema = z.discriminatedUnion(
"resolution",
[
z.strictObject({
id: z.string().min(1),
from: z.string().min(1),
to: z.string().min(1),
relation: nativeInvestigationRelationSchema,
resolution: z.enum(["observed", "inferred"]),
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
limitations: z.array(z.string()),
}),
z.strictObject({
id: z.string().min(1),
from: z.string().min(1),
to: z.null(),
relation: nativeInvestigationRelationSchema,
resolution: z.literal("unresolved"),
reason: z.string().min(1),
evidence: z.array(nativeMetadataEvidenceSchema),
limitations: z.array(z.string()),
}),
],
);
export type NativeInvestigationEdge = z.infer<
typeof nativeInvestigationEdgeSchema
>;
/** Explicit inventory coverage so missing graph parts are not read as absent. */
export const nativeInvestigationCoverageSchema = z.strictObject({
facet: z.string().min(1),
status: z.enum(["complete", "partial", "unsupported", "not_requested"]),
reason: z.string().nullable(),
examined: z.number().int().nonnegative(),
omitted: z.number().int().nonnegative(),
});
/** Complete provider-neutral graph bound to one immutable target identity. */
export const nativeInvestigationGraphSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
provider: z.strictObject({
id: z.string().min(1),
version: z.string().nullable(),
tool_version: z.string().min(1),
}),
nodes: z.array(nativeInvestigationNodeSchema),
edges: z.array(nativeInvestigationEdgeSchema),
coverage: z.array(nativeInvestigationCoverageSchema),
truncated: z.boolean(),
});
export type NativeInvestigationGraph = z.infer<
typeof nativeInvestigationGraphSchema
>;
/** Caller-controlled hard limits for a bounded relationship trace. */
export const nativeInvestigationTraceLimitsSchema = z.strictObject({
max_depth: z.number().int().min(0).max(32).default(8),
max_nodes: z.number().int().min(1).max(2000).default(250),
max_edges: z.number().int().min(1).max(5000).default(500),
});
export type NativeInvestigationTraceLimits = z.infer<
typeof nativeInvestigationTraceLimitsSchema
>;
/** Exact graph route and any unresolved edges encountered along the route. */
export const nativeInvestigationTraceSchema = z.strictObject({
target_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
provider: nativeInvestigationGraphSchema.shape.provider,
start: z.string().min(1),
direction: z.enum(["forward", "backward"]),
nodes: z.array(nativeInvestigationNodeSchema),
edges: z.array(nativeInvestigationEdgeSchema),
unresolved: z.array(nativeInvestigationEdgeSchema),
reached_depth: z.number().int().nonnegative(),
truncated: z.boolean(),
reason: z.string().nullable(),
coverage: z.array(nativeInvestigationCoverageSchema),
limitations: z.array(z.string().min(1)),
});
export type NativeInvestigationTrace = z.infer<
typeof nativeInvestigationTraceSchema
>;
/** Trace known relationships while retaining unknown indirect dispatch edges. */
export const traceNativeInvestigationGraph = (
graph: NativeInvestigationGraph,
input: {
readonly start: string;
readonly direction?: "forward" | "backward";
readonly limits?: Partial<NativeInvestigationTraceLimits>;
},
): NativeInvestigationTrace => {
const start = graph.nodes.find(({ id }) => id === input.start);
if (start === undefined)
return {
target_sha256: graph.target_sha256,
provider: graph.provider,
start: input.start,
direction: input.direction ?? "forward",
nodes: [],
edges: [],
unresolved: [],
reached_depth: 0,
truncated: false,
reason: "start_node_missing",
coverage: graph.coverage,
limitations: [
"The requested start node is absent from the supplied graph.",
],
};
const limits = nativeInvestigationTraceLimitsSchema.parse(input.limits ?? {});
const direction = input.direction ?? "forward";
const nodeById = new Map(graph.nodes.map((node) => [node.id, node]));
const visited = new Set([start.id]);
const selectedEdges = new Map<string, NativeInvestigationEdge>();
const unresolved = new Map<string, NativeInvestigationEdge>();
const queue: Array<{ id: string; depth: number }> = [
{ id: start.id, depth: 0 },
];
let reachedDepth = 0;
let truncated = false;
let reason: string | null = null;
while (queue.length > 0) {
const current = queue.shift();
if (current === undefined) break;
reachedDepth = Math.max(reachedDepth, current.depth);
const adjacent = graph.edges.filter((edge) =>
direction === "forward"
? edge.from === current.id
: edge.to === current.id,
);
for (const edge of adjacent) {
if (selectedEdges.size + unresolved.size >= limits.max_edges) {
truncated = true;
reason = "max_edges_reached";
break;
}
if (edge.resolution === "unresolved") {
unresolved.set(edge.id, edge);
continue;
}
const nextId = direction === "forward" ? edge.to : edge.from;
const alreadyVisited = visited.has(nextId);
if (!alreadyVisited && current.depth >= limits.max_depth) {
truncated = true;
reason ??= "max_depth_reached";
continue;
}
selectedEdges.set(edge.id, edge);
if (alreadyVisited) continue;
if (visited.size >= limits.max_nodes) {
truncated = true;
reason = "max_nodes_reached";
break;
}
if (!nodeById.has(nextId)) {
truncated = true;
reason ??= "edge_target_missing_from_graph";
continue;
}
visited.add(nextId);
queue.push({ id: nextId, depth: current.depth + 1 });
}
if (reason === "max_edges_reached" || reason === "max_nodes_reached") break;
}
return {
target_sha256: graph.target_sha256,
provider: graph.provider,
start: start.id,
direction,
nodes: [...visited].flatMap((id) => {
const node = nodeById.get(id);
return node === undefined ? [] : [node];
}),
edges: [...selectedEdges.values()],
unresolved: [...unresolved.values()],
reached_depth: reachedDepth,
truncated,
reason,
coverage: graph.coverage,
limitations: [
"Static analysis does not prove that an authored UI action is reachable or executed at runtime.",
"Provider call graphs may omit unresolved indirect dispatch.",
],
};
};
/** Join authored UI actions to exact Objective-C method symbols when known. */
export const joinInterfaceBuilderDispatch = (
graph: NativeInvestigationGraph,
metadata: ObjcSwiftMetadata,
): NativeInvestigationGraph => {
const nodes = new Map(graph.nodes.map((node) => [node.id, node]));
const edges = [...graph.edges];
const existingEdgeIds = new Set(edges.map(({ id }) => id));
const selectorNodesByAction = new Map<string, string>();
for (const edge of edges) {
if (
edge.resolution === "observed" &&
edge.relation === "target_action" &&
nodes.get(edge.to)?.kind === "objc_selector"
)
selectorNodesByAction.set(edge.from, edge.to);
}
let examined = 0;
let resolved = 0;
let inferredWithoutOwnerClass = 0;
for (const action of nodes.values()) {
if (action.kind !== "action") continue;
const selector = action.attributes.selector;
if (typeof selector !== "string" || selector.length === 0) continue;
const selectorNodeId = selectorNodesByAction.get(action.id);
if (selectorNodeId === undefined) continue;
const destinationEdge = edges.find(
(edge) =>
edge.resolution === "observed" &&
edge.relation === "target_action" &&
edge.from === action.id &&
["view_controller", "placeholder", "external_object"].includes(
nodes.get(edge.to)?.kind ?? "",
),
);
if (
destinationEdge === undefined ||
destinationEdge.resolution !== "observed"
)
continue;
const owner = nodes.get(destinationEdge.to);
examined += 1;
const declaredClass = owner?.attributes.class_name;
const className =
typeof declaredClass === "string" &&
declaredClass.length > 0 &&
owner?.kind === "view_controller"
? declaredClass
: null;
const candidates = metadata.objc_dispatch_implementations.filter(
(candidate) =>
candidate.method_type === "instance" &&
candidate.selector === selector &&
(className === null ||
candidate.class_name.replace(/\([^)]*\)$/u, "") === className),
);
const implementation = candidates.length === 1 ? candidates[0] : undefined;
const edgeId = `dispatch:${selectorNodeId}:${className ?? owner?.id ?? "unknown"}:${selector}`;
if (existingEdgeIds.has(edgeId)) continue;
existingEdgeIds.add(edgeId);
if (
implementation === undefined ||
implementation.implementation_address === null
) {
edges.push({
id: edgeId,
from: selectorNodeId,
to: null,
relation: "objc_dispatch",
resolution: "unresolved",
reason:
candidates.length > 1
? "selector_has_multiple_candidate_implementations"
: "implementation_not_resolved_from_provider_symbols",
evidence: [
...action.evidence,
...candidates.flatMap(({ evidence }) => evidence),
],
limitations: [
"A missing or ambiguous symbol match does not prove that the runtime implementation is absent.",
],
});
continue;
}
const functionId = `native:function:${implementation.implementation_address}`;
if (!nodes.has(functionId))
nodes.set(functionId, {
id: functionId,
kind: "function",
name: `${implementation.class_name} ${selector}`,
location: {
address: implementation.implementation_address,
file_offset: implementation.location.file_offset,
},
attributes: {
class_name: implementation.class_name,
selector,
method_type: implementation.method_type,
},
evidence: implementation.evidence,
});
edges.push({
id: edgeId,
from: selectorNodeId,
to: functionId,
relation: "objc_dispatch",
resolution: "inferred",
evidence: [...action.evidence, ...implementation.evidence],
limitations:
className === null
? [
"The selector uniquely matches a symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
]
: [
"The Interface Builder target and symbolized method agree on class and selector; runtime dispatch and dynamically supplied targets were not observed.",
],
});
resolved += 1;
if (className === null) inferredWithoutOwnerClass += 1;
}
return nativeInvestigationGraphSchema.parse({
...graph,
provider: {
id: "rea-native-investigation",
version: null,
tool_version: "rea-native-investigation/1",
},
nodes: [...nodes.values()],
edges,
coverage: [
...graph.coverage,
{
facet: "ui_to_objc_dispatch",
status:
examined === resolved && inferredWithoutOwnerClass === 0
? "complete"
: "partial",
reason:
examined === resolved && inferredWithoutOwnerClass === 0
? null
: inferredWithoutOwnerClass > 0
? "some_action_receivers_remain_placeholders"
: "some_action_implementations_not_resolved",
examined,
omitted: examined - resolved + inferredWithoutOwnerClass,
},
],
});
};
+66
View File
@@ -0,0 +1,66 @@
import { z } from "zod";
/** A decompiler p-code varnode location or literal value. */
export const nativeVarnodeSchema = z.strictObject({
kind: z.enum(["constant", "address", "register", "unique", "other"]),
size_bytes: z.number().int().nonnegative(),
location: z.string().nullable(),
constant_hex: z
.string()
.regex(/^[0-9a-f]+$/u)
.nullable(),
});
/** One high-p-code operation recovered for a single function. */
export const nativePcodeOperationSchema = z.strictObject({
id: z.string().min(1),
address: z.string().min(1),
sequence: z.number().int().nonnegative(),
opcode: z.string().min(1),
is_dead: z.boolean(),
inputs: z.array(nativeVarnodeSchema),
output: nativeVarnodeSchema.nullable(),
});
/** A def-use relation between operations in one recovered HighFunction. */
export const nativePcodeDefUseSchema = z.strictObject({
definition: z.string().min(1),
use: z.string().min(1),
input_index: z.number().int().nonnegative(),
});
/** Memory and branch operations as directly named by Ghidra p-code. */
export const nativePcodeEffectSchema = z.strictObject({
operation: z.string().min(1),
kind: z.enum([
"memory_read",
"memory_write",
"conditional_branch",
"indirect_branch",
"direct_call",
"indirect_call",
]),
operand_input: z.number().int().nonnegative().nullable(),
value_input: z.number().int().nonnegative().nullable(),
});
/** Bounded data-flow observations; STORE is not necessarily a persistent/global write. */
export const nativeValueFlowSchema = z.discriminatedUnion("available", [
z.strictObject({
available: z.literal(true),
provenance: z.literal("ghidra-high-pcode"),
operations: z.array(nativePcodeOperationSchema),
def_use: z.array(nativePcodeDefUseSchema),
effects: z.array(nativePcodeEffectSchema),
truncated: z.boolean(),
omitted_operations_lower_bound: z.number().int().nonnegative(),
known_omitted_inputs: z.number().int().nonnegative(),
known_omitted_edges: z.number().int().nonnegative(),
limitations: z.array(z.string().min(1)),
}),
z.strictObject({
available: z.literal(false),
reason: z.string().min(1),
limitations: z.array(z.string().min(1)),
}),
]);
+28
View File
@@ -5,6 +5,7 @@ import {
isDbSaveComplete,
isGetterSelector,
isSetterSelector,
inspectNativeDispatchMetadata,
objcSwiftMetadataSchema,
propertyNameFromSelector,
swiftDeclsByKind,
@@ -101,4 +102,31 @@ describe("ObjC/Swift metadata", () => {
const result = objcSwiftMetadataSchema.safeParse(meta);
expect(result.success).toBe(true);
});
it("bounds symbol projections and labels symbol-only metadata as partial", () => {
const result = inspectNativeDispatchMetadata(
[
{ address: "ram:0x1000", name: "OBJC_CLASS_$_StoreController" },
{ address: "ram:0x2000", name: "-[StoreController buildTapped:]" },
{ address: "ram:0x3000", name: "$s5Store7launchyyF" },
],
2,
);
expect(result.objc_classes).toHaveLength(1);
expect(result.objc_dispatch_implementations).toHaveLength(1);
expect(result.swift_symbols).toHaveLength(0);
expect(result.coverage).toContainEqual(
expect.objectContaining({
facet: "objc_class_symbols",
status: "partial",
reason: expect.stringContaining("record_limit_reached"),
}),
);
expect(result.coverage).toContainEqual(
expect.objectContaining({
facet: "swift_dispatch_tables",
status: "unsupported",
}),
);
});
});
+304
View File
@@ -64,6 +64,130 @@ export const objcClassSchema = z.strictObject({
});
export type ObjcClass = z.infer<typeof objcClassSchema>;
/** Exact location of a decoded native metadata value when the provider knows it. */
export const nativeMetadataLocationSchema = z.strictObject({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
});
export type NativeMetadataLocation = z.infer<
typeof nativeMetadataLocationSchema
>;
/** Provider-neutral decode state; absence never silently means unsupported. */
export const nativeMetadataDecodeSchema = z.strictObject({
status: z.enum(["decoded", "partial", "unsupported", "invalid"]),
reason: z.string().nullable(),
});
export type NativeMetadataDecode = z.infer<typeof nativeMetadataDecodeSchema>;
/** Evidence attached to one dispatch edge or metadata record. */
export const nativeMetadataEvidenceSchema = z.strictObject({
kind: z.enum([
"binary_metadata",
"interface_builder_resource",
"symbol",
"reference",
"decompiler",
]),
description: z.string().min(1),
location: nativeMetadataLocationSchema,
artifact_path: z.string().min(1).nullable().default(null),
artifact_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable()
.default(null),
});
export type NativeMetadataEvidence = z.infer<
typeof nativeMetadataEvidenceSchema
>;
/** Objective-C ivar layout, retaining encoded type and exact storage offset. */
export const objcIvarSchema = z.strictObject({
class_name: z.string().min(1),
name: z.string().min(1),
type_encoding: z.string().nullable(),
offset: z.number().int().nonnegative().nullable(),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcIvar = z.infer<typeof objcIvarSchema>;
/** Selector implementation resolved from a class or metaclass method list. */
export const objcDispatchImplementationSchema = z.strictObject({
class_name: z.string().min(1),
selector: z.string().min(1),
method_type: z.enum(["instance", "class"]),
implementation_address: z.string().nullable(),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
/** Swift protocol conformance and its associated witness-table location. */
export const swiftConformanceSchema = z.strictObject({
type_name: z.string().min(1),
protocol_name: z.string().min(1),
module: z.string().nullable(),
witness_table: nativeMetadataLocationSchema,
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftConformance = z.infer<typeof swiftConformanceSchema>;
/** A typed slot in a Swift protocol witness table or class vtable. */
export const swiftDispatchSlotSchema = z.strictObject({
owner: z.string().min(1),
table_kind: z.enum(["witness_table", "class_vtable"]),
slot_index: z.number().int().nonnegative(),
requirement: z.string().nullable(),
implementation: z.string().nullable(),
implementation_address: z.string().nullable(),
thunk_address: z.string().nullable(),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftDispatchSlot = z.infer<typeof swiftDispatchSlotSchema>;
/** Signed-relative pointer as stored in an Apple binary metadata structure. */
export const relativePointerSchema = z.strictObject({
field: nativeMetadataLocationSchema,
target: nativeMetadataLocationSchema,
displacement: z.number().int(),
indirectable: z.boolean(),
indirect: z.boolean().nullable(),
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type RelativePointer = z.infer<typeof relativePointerSchema>;
/** A raw Swift-mangled symbol when a provider has not decoded its metadata. */
export const swiftSymbolSchema = z.strictObject({
mangled_name: z.string().min(1),
address: z.string().min(1),
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type SwiftSymbol = z.infer<typeof swiftSymbolSchema>;
/** Per-facet coverage; empty arrays are meaningful only with this record. */
export const nativeMetadataCoverageSchema = z.strictObject({
facet: z.string().min(1),
status: z.enum(["complete", "partial", "unsupported", "not_requested"]),
reason: z.string().nullable(),
examined: z.number().int().nonnegative(),
decoded: z.number().int().nonnegative(),
});
export type NativeMetadataCoverage = z.infer<
typeof nativeMetadataCoverageSchema
>;
/** Swift declaration kind. */
export const swiftDeclKindSchema = z.enum([
"class",
@@ -129,10 +253,190 @@ export const objcSwiftMetadataSchema = z.strictObject({
objc_classes: z.array(objcClassSchema).default([]),
objc_protocols: z.array(objcProtocolSchema).default([]),
swift_decls: z.array(swiftDeclSchema).default([]),
objc_ivars: z.array(objcIvarSchema).default([]),
objc_dispatch_implementations: z
.array(objcDispatchImplementationSchema)
.default([]),
swift_conformances: z.array(swiftConformanceSchema).default([]),
swift_dispatch_slots: z.array(swiftDispatchSlotSchema).default([]),
swift_symbols: z.array(swiftSymbolSchema).default([]),
relative_pointers: z.array(relativePointerSchema).default([]),
coverage: z.array(nativeMetadataCoverageSchema).default([]),
db_save_result: dbSaveResultSchema.nullable(),
});
export type ObjcSwiftMetadata = z.infer<typeof objcSwiftMetadataSchema>;
/** Provider and target identity for one normalized dispatch-metadata result. */
export const nativeDispatchMetadataResultSchema = z.strictObject({
target_sha256: z
.string()
.regex(/^[a-f0-9]{64}$/u)
.nullable(),
provider: z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().nullable(),
}),
analysis_profile_digest: z.string().min(1).nullable(),
result: objcSwiftMetadataSchema,
});
export type NativeDispatchMetadataResult = z.infer<
typeof nativeDispatchMetadataResultSchema
>;
/** Decode only facts visible in a provider's existing name inventory. */
export const inspectNativeDispatchMetadata = (
names: readonly { readonly address: string; readonly name: string }[],
maxRecords = 5_000,
): ObjcSwiftMetadata => {
const symbolEvidence = (name: string, address: string) => [
{
kind: "symbol" as const,
description: `Provider symbol ${name}`,
location: { address, file_offset: null },
artifact_path: null,
artifact_sha256: null,
},
];
const classNames = new Set<string>();
const implementations = new Map<string, ObjcDispatchImplementation>();
const swiftSymbols: SwiftSymbol[] = [];
const examinedNames = names.slice(0, maxRecords);
for (const entry of examinedNames) {
const classMatch = /(?:OBJC_CLASS_|OBJC_METACLASS_)\$_([^\s]+)/u.exec(
entry.name,
);
if (classMatch?.[1] !== undefined) classNames.add(classMatch[1]);
const methodMatch = /^([+-])\[([^\s\]]+)\s+([^\]]+)\]$/u.exec(entry.name);
if (methodMatch?.[1] !== undefined && methodMatch[2] && methodMatch[3]) {
const methodType = methodMatch[1] === "+" ? "class" : "instance";
const selector = methodMatch[3];
implementations.set(`${methodMatch[2]}:${selector}:${methodType}`, {
class_name: methodMatch[2],
selector,
method_type: methodType,
implementation_address: entry.address,
location: { address: entry.address, file_offset: null },
decode: { status: "partial", reason: "symbol_name_only" },
evidence: symbolEvidence(entry.name, entry.address),
});
classNames.add(methodMatch[2]);
}
if (/^(?:_?\$s|_Tt)/u.test(entry.name))
swiftSymbols.push({
mangled_name: entry.name,
address: entry.address,
decode: { status: "partial", reason: "mangled_symbol_not_demangled" },
evidence: symbolEvidence(entry.name, entry.address),
});
}
const methodsByClass = new Map<string, ObjcMethod[]>();
for (const implementation of implementations.values()) {
const methods = methodsByClass.get(implementation.class_name) ?? [];
methods.push({
selector: implementation.selector,
method_type: implementation.method_type,
address: parseMetadataAddress(implementation.implementation_address),
is_required: false,
is_optional: false,
});
methodsByClass.set(implementation.class_name, methods);
}
const classes: ObjcClass[] = [...classNames].sort().map((name) => ({
name,
super_class: null,
is_meta_class: false,
is_root_class: false,
methods: methodsByClass.get(name) ?? [],
properties: [],
protocols: [],
ivar_count: 0,
instance_size: null,
}));
const decodedImplementations = [...implementations.values()].sort(
(left, right) =>
`${left.class_name}:${left.selector}`.localeCompare(
`${right.class_name}:${right.selector}`,
),
);
const swift = swiftSymbols.length > 0;
return objcSwiftMetadataSchema.parse({
objc_classes: classes,
objc_dispatch_implementations: decodedImplementations,
swift_symbols: swiftSymbols,
coverage: [
{
facet: "objc_class_symbols",
status: "partial",
reason:
names.length > examinedNames.length
? "record_limit_reached_and_symbol_names_are_not_runtime_class_metadata"
: "symbol_names_do_not_recover_all_runtime_class_metadata",
examined: examinedNames.length,
decoded: classes.length,
},
{
facet: "objc_dispatch_implementations",
status: decodedImplementations.length > 0 ? "partial" : "unsupported",
reason:
names.length > examinedNames.length
? "record_limit_reached_and_only_symbolized_methods_are_resolved"
: decodedImplementations.length > 0
? "only_symbolized_methods_are_resolved"
: "provider_name_inventory_has_no_objc_method_symbols",
examined: examinedNames.length,
decoded: decodedImplementations.length,
},
{
facet: "objc_ivar_layouts",
status: "unsupported",
reason: "symbol_inventory_does_not_expose_runtime_ivar_layouts",
examined: 0,
decoded: 0,
},
{
facet: "swift_declarations",
status: swift ? "partial" : "unsupported",
reason: swift
? "symbols_are_not_demangled_declarations"
: "no_swift_symbols_observed",
examined: swiftSymbols.length,
decoded: 0,
},
{
facet: "swift_dispatch_tables",
status: "unsupported",
reason:
"provider_name_inventory_does_not_decode_witness_or_class_vtables",
examined: 0,
decoded: 0,
},
{
facet: "relative_pointers",
status: "unsupported",
reason:
"provider_name_inventory_does_not_decode_binary_relative_pointers",
examined: 0,
decoded: 0,
},
],
db_save_result: null,
});
};
const parseMetadataAddress = (address: string | null): number | null => {
if (address === null) return null;
const match = /(?:^|:)0x([0-9a-f]+)$/iu.exec(address);
if (match?.[1] === undefined) return null;
const value = Number.parseInt(match[1], 16);
return Number.isSafeInteger(value) ? value : null;
};
/** Check if a selector name looks like a getter. */
export function isGetterSelector(selector: string): boolean {
return /^[a-z][a-zA-Z0-9_]*$/u.test(selector) && !selector.includes(":");