Merge origin/main into feat/native-call-observation

Follow #973's native ownership: the call-observation schemas move to
src/domain/native/, and the contract now lives in src/contracts/native/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 14:47:05 +00:00
co-authored by Claude Opus 5.5
75 changed files with 165 additions and 134 deletions
+166
View File
@@ -0,0 +1,166 @@
import { z } from "zod";
const inferenceConfidenceSchema = z.enum(["low", "medium", "high"]);
const inferenceEvidenceSchema = z
.object({
kind: z.enum([
"signature-source",
"decompiler-type",
"type-lock",
"calling-convention",
"jump-table",
]),
source: z.string().min(1),
detail: z.string().min(1),
})
.strict();
const inferredBoundaryTypeFacts = {
ordinal: z.number().int().min(0).nullable(),
name: z.string().min(1).nullable(),
data_type: z.string().min(1),
size_bytes: z.number().int().min(0).nullable(),
storage: z.string().min(1).nullable(),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
decompiler_artifacts: z.array(
z.enum([
"recovered-signature",
"register-or-stack-storage",
"compiler-generated-variable",
]),
),
} as const;
const inferredReturnTypeSchema = z.strictObject({
...inferredBoundaryTypeFacts,
role: z.literal("return"),
ordinal: z.null(),
name: z.null(),
});
const inferredParameterTypeSchema = z.strictObject({
...inferredBoundaryTypeFacts,
role: z.literal("parameter"),
ordinal: z.number().int().min(0),
});
const jumpTableDataSourceSchema = z
.object({
address: z.string().min(1),
provenance: z.enum([
"ghidra-decompiler-load-table",
"ghidra-dispatch-block-data-reference",
"ghidra-aarch64-byte-table",
"ghidra-aarch64-halfword-table",
]),
entry_size_bytes: z.number().int().min(1).nullable(),
entry_count: z.number().int().min(0).nullable(),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
})
.strict();
const jumpTableMappingSchema = z
.object({
case_value: z.number().int().nullable(),
target_address: z.string().min(1),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
})
.strict();
const jumpTableDefaultTargetSchema = z.strictObject({
target_address: z.string().min(1),
confidence: inferenceConfidenceSchema,
evidence: z.array(inferenceEvidenceSchema).min(1),
});
const inferredJumpTableSchema = z
.object({
dispatch_address: z.string().min(1),
data_sources: z.array(jumpTableDataSourceSchema),
mappings: z.array(jumpTableMappingSchema),
default_targets: z.array(jumpTableDefaultTargetSchema).default([]),
limitations: z.array(z.string()),
})
.strict();
const availableNativeApiBoundarySchema = z
.object({
available: z.literal(true),
provenance: z.string().min(1),
signature_source: z.string().min(1),
calling_convention: z.string().min(1),
return_type: inferredReturnTypeSchema,
parameters: z.array(inferredParameterTypeSchema),
jump_tables: z.array(inferredJumpTableSchema),
pseudocode: z
.object({
classification: z.literal("decompiler-generated-non-source"),
compilable: z.literal(false),
})
.strict(),
decompiler_artifacts: z.array(
z.enum([
"recovered-signature",
"register-and-stack-variables",
"compiler-generated-control-flow",
"pointer-arithmetic",
"pseudocode",
]),
),
limitations: z.array(z.string()),
})
.strict();
const unavailableNativeApiBoundarySchema = z
.object({
available: z.literal(false),
reason: z.string().min(1),
residual_unknowns: z.array(z.string().min(1)).min(1),
})
.strict();
/** Provider-neutral native API boundary observations attached to a function dossier. */
export const nativeApiBoundarySchema = z.discriminatedUnion("available", [
unavailableNativeApiBoundarySchema,
availableNativeApiBoundarySchema,
]);
/** One validated provider-neutral native API boundary observation. */
export type NativeApiBoundary = z.infer<typeof nativeApiBoundarySchema>;
const nativeApiInspectionSubstepSchema = z
.object({
operation: z.enum([
"analyze_function",
"project_native_api_boundary",
"preserve_residual_unknowns",
]),
status: z.enum(["completed", "unsupported"]),
observations: z.array(z.string().min(1)),
})
.strict();
/** Agent-facing projection of structured native API reconstruction substeps. */
export const nativeApiInspectionResultSchema = z
.object({
procedure: z
.object({
address: z.string().min(1),
name: z.string().min(1),
})
.strict(),
boundary: nativeApiBoundarySchema,
substeps: z.array(nativeApiInspectionSubstepSchema).length(3),
unsupported_branches: z.array(z.string().min(1)),
residual_unknowns: z.array(z.string().min(1)),
})
.strict();
/** One validated agent-facing native API inspection result. */
export type NativeApiInspectionResult = z.infer<
typeof nativeApiInspectionResultSchema
>;
+198
View File
@@ -0,0 +1,198 @@
import { z } from "zod";
const hexSchema = z.string().regex(/^0x[0-9a-f]+$/u);
/** Objective-C class names and selectors never contain spaces or brackets. */
const objcName = z
.string()
.min(1)
.regex(/^[^\s[\]]+$/u, "Use the bare name without spaces or brackets");
const functionBreakpoint = {
kind: z.literal("function"),
name: z
.string()
.min(1)
.describe(
"Exact symbol name, such as `open`, a C++ or mangled Swift symbol, or `-[NSString length]`.",
),
};
const objcMethodBreakpoint = {
kind: z.literal("objc-method"),
selector: objcName.describe(
"Selector such as `dataTaskWithRequest:completionHandler:`.",
),
};
/** One function or Objective-C method whose entries are observed. */
export const nativeCallBreakpointSchema = z.discriminatedUnion("kind", [
z.strictObject({
...functionBreakpoint,
module: z
.string()
.min(1)
.optional()
.describe(
"Image file name that defines the symbol, such as `libsystem_kernel.dylib`; omit to match every image.",
),
}),
z.strictObject({
...objcMethodBreakpoint,
class_name: objcName
.optional()
.describe("Implementing class; omit to match every class."),
method_type: z.enum(["instance", "class", "any"]).default("any"),
}),
]);
/**
* Launch the active Mach-O as an owned process under LLDB and observe calls.
* Duration and event bounds keep runtime observation finite.
*/
export const nativeCallObservationInputSchema = z.strictObject({
breakpoints: z.array(nativeCallBreakpointSchema).min(1),
arguments: z.array(z.string()).default([]),
environment: z
.record(
z
.string()
.min(1)
.regex(/^[^=\0]+$/u, "Environment names cannot contain '=' or NUL"),
z.string().regex(/^[^\0]*$/u, "Environment values cannot contain NUL"),
)
.default({})
.describe("Overrides on top of the environment REA runs with."),
working_directory: z.string().min(1).optional(),
duration_ms: z
.number()
.int()
.min(100)
.max(600_000)
.default(10_000)
.describe(
"Observation window; the process is killed if it is still running.",
),
max_events: z
.number()
.int()
.min(1)
.max(100_000)
.default(1_000)
.describe(
"Stop observing and kill the process after this many recorded entries.",
),
argument_registers: z
.number()
.int()
.min(0)
.max(8)
.default(4)
.describe(
"Integer argument registers to record per entry (arm64 has 8, x86_64 has 6).",
),
backtrace_frames: z
.number()
.int()
.min(0)
.max(64)
.default(0)
.describe("Caller frames to record per entry."),
});
export type NativeCallObservationInput = z.infer<
typeof nativeCallObservationInputSchema
>;
/** A code address with the image and symbol LLDB attributes to it. */
export const nativeCodeLocationSchema = z.strictObject({
load_address: hexSchema,
file_address: hexSchema.nullable(),
module: z.string().nullable(),
module_path: z.string().nullable(),
symbol: z.string().nullable(),
});
/** One observed entry into a requested function or method. */
export const nativeCallEventSchema = z.strictObject({
sequence: z.number().int().nonnegative(),
elapsed_ms: z.number().nonnegative(),
thread_id: z.number().int().nonnegative(),
breakpoint_index: z.number().int().nonnegative(),
...nativeCodeLocationSchema.shape,
/** Dynamic class of an instance-method receiver, read without running code. */
receiver_class: z.string().nullable(),
/** Selector string read from the `_cmd` register of an Objective-C method. */
selector: z.string().nullable(),
registers: z.array(z.strictObject({ name: z.string(), value: hexSchema })),
backtrace: z.array(nativeCodeLocationSchema),
});
const capturedOutputSchema = z.strictObject({
text: z.string(),
bytes: z.number().int().nonnegative(),
truncated: z.boolean(),
});
/** Observed calls, the process lifecycle, and breakpoint resolution. */
export const nativeCallObservationResultSchema = z.strictObject({
target: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
architecture: z.string(),
arguments: z.array(z.string()),
working_directory: z.string().nullable(),
}),
debugger: z.strictObject({
path: z.string(),
sha256: z.string().regex(/^[0-9a-f]{64}$/u),
version: z.string().nullable(),
}),
process: z.strictObject({
pid: z.number().int().positive(),
outcome: z.enum([
"exited",
"duration-elapsed",
"event-limit",
"stop-limit",
]),
exit_status: z.number().int().nullable(),
exit_description: z.string().nullable(),
/** REA confirmed the process is gone when observation ended. */
terminated: z.boolean(),
elapsed_ms: z.number().nonnegative(),
stdout: capturedOutputSchema,
stderr: capturedOutputSchema,
/** Signal and exception stops LLDB reported; the process continued past each. */
other_stops: z.array(z.string()),
}),
breakpoints: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
request: z.discriminatedUnion("kind", [
z.strictObject({
...functionBreakpoint,
module: z.string().nullable(),
}),
z.strictObject({
...objcMethodBreakpoint,
class_name: z.string().nullable(),
method_type: z.enum(["instance", "class", "any"]),
}),
]),
location_count: z.number().int().nonnegative(),
locations: z.array(nativeCodeLocationSchema),
}),
),
events: z.array(nativeCallEventSchema),
coverage: z.strictObject({
status: z.enum(["complete", "partial"]),
event_limit_reached: z.boolean(),
/** Requests that matched no code in any image loaded while observing. */
unresolved_breakpoints: z.array(z.number().int().nonnegative()),
}),
limitations: z.array(z.string()),
});
export type NativeCallObservationResult = z.infer<
typeof nativeCallObservationResultSchema
>;
+59
View File
@@ -0,0 +1,59 @@
import { z } from "zod";
import { nativeMetadataRecoverySchema } from "./nativeMetadataRecovery.js";
/** Select a database type by exact category path or a defined typed data address. */
export const nativeDataTypeInputSchema = z
.strictObject({
type: z.string().min(1).optional(),
address: z.string().min(1).optional(),
document: z.string().optional(),
})
.refine(
(value) => (value.type === undefined) !== (value.address === undefined),
"Supply exactly one of type or address",
);
/** Types remain analysis database observations; child identities can be inspected separately. */
export const nativeDataTypeSchema = z.strictObject({
status: z.enum(["available", "unavailable"]),
reason: z.string().nullable(),
id: z.string().nullable(),
name: z.string().nullable(),
kind: z.enum([
"struct",
"union",
"enum",
"pointer",
"array",
"typedef",
"scalar",
"unsupported",
"unavailable",
]),
source: z.literal("analysis-database"),
source_archive: z.string().nullable(),
address: z.string().nullable(),
size_bytes: z.number().int().nonnegative().nullable(),
alignment_bytes: z.number().int().positive().nullable(),
packing_enabled: z.boolean().nullable(),
referenced_type: z.string().nullable(),
array_count: z.number().int().nonnegative().nullable(),
array_stride_bytes: z.number().int().nonnegative().nullable(),
fields: z.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string().nullable(),
offset_bytes: z.number().int().nonnegative(),
size_bytes: z.number().int().nonnegative().nullable(),
type_id: z.string(),
bit_size: z.number().int().nonnegative().nullable(),
bit_offset: z.number().int().nonnegative().nullable(),
status: z.enum(["observed", "unsupported"]),
flexible_tail: z.literal("unknown"),
}),
),
members: z.array(z.strictObject({ name: z.string(), value: z.string() })),
total_fields: z.number().int().nonnegative(),
truncated: z.boolean(),
limitations: z.array(z.string()),
metadata_recovery: nativeMetadataRecoverySchema.optional(),
});
@@ -0,0 +1,52 @@
import { z } from "zod";
import { functionDossierSchema } from "../hopperValues.js";
/** One explicit function's analyst-authored metadata changes. */
export const nativeFunctionAnnotationsInputSchema = z
.strictObject({
procedure: z.string().min(1),
name: z.string().min(1).optional(),
comment: z
.string()
.optional()
.describe("Regular entry comment; empty text clears it"),
inline_comment: z
.string()
.optional()
.describe("Inline entry comment; empty text clears it"),
})
.refine(
(value) =>
value.name !== undefined ||
value.comment !== undefined ||
value.inline_comment !== undefined,
"Supply at least one annotation change",
);
/** Readback and refreshed analysis after one atomic metadata edit. */
export const nativeFunctionAnnotationsSchema = z
.strictObject({
annotations: z.strictObject({
address: z.string().min(1),
name: z.string().min(1),
comment: z.string().nullable(),
inline_comment: z.string().nullable(),
}),
dossier: functionDossierSchema,
effects: z.strictObject({
scope: z.literal("session-analysis-database"),
source_bytes_modified: z.literal(false),
persists_after_close: z.literal(false),
}),
})
.superRefine((value, context) => {
if (
value.annotations.address !== value.dossier.procedure.address ||
value.annotations.name !== value.dossier.procedure.name
)
context.addIssue({
code: "custom",
message:
"Annotation readback disagrees with refreshed function identity",
});
});
+157
View File
@@ -0,0 +1,157 @@
import { z } from "zod";
import { jsonValueSchema } from "../jsonValue.js";
const hexAddress = z.string().regex(/^0x[a-fA-F0-9]+$/u);
const coverage = <Schema extends z.ZodType>(item: Schema) =>
z.object({
items: z.array(item),
total: z.number().int().min(0).nullable(),
exhaustive: z.boolean(),
limitations: z.array(z.string()),
});
const nativeCommandInvocationSchema = z.object({
tool: z.string().min(1),
command: z.array(z.string()),
tool_version: z.string().nullable(),
version_reason: z.string().nullable(),
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
exit: z.object({
code: z.number().int().nullable(),
signal: z.string().nullable(),
}),
stdout_bytes: z.number().int().min(0),
stderr_bytes: z.number().int().min(0),
});
const architectureSchema = z.object({
name: z.string(),
cpu_type: z.string().nullable(),
cpu_subtype: z.string().nullable(),
file_offset: z.number().int().min(0).nullable(),
size: z.number().int().min(0).nullable(),
alignment: z.number().int().min(0).nullable(),
});
const permissionSchema = z.object({
read: z.boolean().nullable(),
write: z.boolean().nullable(),
execute: z.boolean().nullable(),
raw: z.string().nullable(),
});
const sectionSchema = z.object({
segment: z.string(),
name: z.string(),
address: hexAddress.nullable(),
size: z.number().int().min(0).nullable(),
file_offset: z.number().int().min(0).nullable(),
alignment: z.number().int().min(0).nullable(),
flags: z.array(z.string()),
});
const segmentSchema = z.object({
name: z.string(),
vm_address: hexAddress.nullable(),
vm_size: z.number().int().min(0).nullable(),
file_offset: z.number().int().min(0).nullable(),
file_size: z.number().int().min(0).nullable(),
maximum_permissions: permissionSchema,
initial_permissions: permissionSchema,
sections: coverage(sectionSchema),
});
const symbolSchema = z.object({
name: z.string(),
address: hexAddress.nullable(),
weak: z.boolean().nullable(),
reexport: z.boolean().nullable(),
source: z.string().nullable(),
});
const dependencySchema = z.object({
path: z.string(),
kind: z.string(),
current_version: z.string().nullable(),
compatibility_version: z.string().nullable(),
});
const loadCommandSchema = z.object({
index: z.number().int().min(0),
kind: z.string(),
fields: z.record(z.string(), z.union([z.string(), z.number(), z.null()])),
});
const buildMetadataSchema = z.object({
platform: z.string().nullable(),
minimum_os: z.string().nullable(),
sdk: z.string().nullable(),
tools: z.array(z.object({ name: z.string(), version: z.string() })),
});
export const inspectMachoSchema = z.object({
format: z.literal("mach-o"),
endian: z.enum(["little", "big"]).nullable(),
word_size: z.union([z.literal(32), z.literal(64)]).nullable(),
file_type: z.string().nullable(),
flags: z.array(z.string()),
uuid: z.string().nullable(),
entrypoints: coverage(z.object({ file_offset: z.number().int().min(0) })),
architectures: coverage(architectureSchema),
build_metadata: coverage(buildMetadataSchema),
load_commands: coverage(loadCommandSchema),
dependencies: coverage(dependencySchema),
imports: coverage(symbolSchema),
exports: coverage(symbolSchema),
segments: coverage(segmentSchema),
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
export const inspectSignatureSchema = z.object({
signed: z.boolean(),
identifier: z.string().nullable(),
team_identifier: z.string().nullable(),
format: z.string().nullable(),
cdhashes: z.array(z.string()),
hash_algorithms: z.array(z.string()),
authorities: z.array(z.string()),
designated_requirement: z.string().nullable(),
entitlements: jsonValueSchema.nullable(),
timestamp: z.string().nullable(),
hardened_runtime: z.boolean().nullable(),
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
export const inspectPlistSchema = z.object({
format: z.enum(["xml", "binary", "json", "unknown"]),
value: jsonValueSchema,
bundle: z.object({
identifier: z.string().nullable(),
executable: z.string().nullable(),
name: z.string().nullable(),
version: z.string().nullable(),
short_version: z.string().nullable(),
}),
source_path: z.string(),
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
export const listArchitecturesSchema = z.object({
architectures: coverage(architectureSchema),
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
export const demangleSwiftSchema = z.object({
symbols: z.array(
z.object({
input: z.string(),
output: z.string(),
status: z.enum(["demangled", "unchanged", "invalid"]),
}),
),
provenance: z.array(nativeCommandInvocationSchema),
limitations: z.array(z.string()),
});
export type NativeCommandInvocation = z.infer<
typeof nativeCommandInvocationSchema
>;
export type InspectMacho = z.infer<typeof inspectMachoSchema>;
export type InspectSignature = z.infer<typeof inspectSignatureSchema>;
+90
View File
@@ -0,0 +1,90 @@
import { z } from "zod";
/** Exact instruction location within the active analysis program. */
export const nativeInstructionInputSchema = z.strictObject({
address: z.string().min(1),
document: z.string().optional(),
});
const reference = z.strictObject({
target_address: z.string(),
type: z.string(),
call: z.boolean(),
jump: z.boolean(),
indirect: z.boolean(),
computed: z.boolean(),
operand_index: z.number().int(),
});
/** Provider-decoded facts for one instruction; operand tokens preserve their native ordering. */
export const nativeInstructionSchema = z.strictObject({
address: z.string(),
status: z.enum([
"decoded",
"not-instruction-boundary",
"data",
"undecodable",
"outside-memory",
]),
procedure: z.string().nullable(),
architecture: z.string(),
mode: z.string(),
bytes: z.string().nullable(),
length: z.number().int().positive().nullable(),
mnemonic: z.string().nullable(),
raw_disassembly: z.string().nullable(),
operands: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
raw: z.string(),
provider_type: z.number().int(),
components: z.array(
z.strictObject({
kind: z.enum(["register", "immediate", "address", "unknown"]),
text: z.string(),
value: z.string().nullable(),
bit_width: z.number().int().nonnegative().nullable(),
}),
),
memory_addressing: z.literal("unavailable"),
}),
),
flow: z.strictObject({
kind: z.enum([
"call",
"jump",
"return",
"fallthrough",
"terminal",
"unavailable",
]),
conditional: z.boolean(),
computed: z.boolean(),
direct_destinations: z.array(z.string()),
}),
references: z.array(reference),
limitations: z.array(z.string()),
});
/** Static target resolution preserves provider references as evidence, never runtime certainty. */
export const nativeCallTargetsSchema = z.strictObject({
call_site: z.string(),
procedure: z.string().nullable(),
status: z.enum([
"direct",
"resolved-indirect",
"ambiguous",
"unresolved",
"not-call",
"unavailable",
]),
mechanism: z.enum(["direct", "computed", "indirect", "unavailable"]),
targets: z.array(
z.strictObject({
address: z.string(),
procedure: z.string().nullable(),
status: z.enum(["direct", "resolved-indirect", "candidate"]),
basis: z.literal("provider-reference"),
references: z.array(reference),
}),
),
limitations: z.array(z.string()),
});
@@ -0,0 +1,350 @@
import { describe, expect, it } from "vitest";
import {
nativeInvestigationGraphSchema,
joinInterfaceBuilderDispatch,
traceNativeInvestigationGraph,
} from "./nativeInvestigationGraph.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
} from "../apple/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: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
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: "resolved",
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: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
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: "resolved",
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: [],
objc_categories: [],
swift_decls: [],
objc_ivars: [],
objc_protocol_records: [],
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",
}),
);
});
});
@@ -0,0 +1,433 @@
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",
"indirect_call",
"provider_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", "resolved", "ambiguous"]),
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;
const adjacency = new Map<string, NativeInvestigationEdge[]>();
for (const edge of graph.edges) {
const nodeId = direction === "forward" ? edge.from : edge.to;
if (nodeId === null) continue;
const entries = adjacency.get(nodeId);
if (entries === undefined) adjacency.set(nodeId, [edge]);
else entries.push(edge);
}
while (queue.length > 0) {
const current = queue.shift();
if (current === undefined) break;
reachedDepth = Math.max(reachedDepth, current.depth);
const adjacent = adjacency.get(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_binary_metadata_or_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:
className !== null && implementation.decode.status === "decoded"
? "resolved"
: "inferred",
evidence: [...action.evidence, ...implementation.evidence],
limitations:
className === null
? [
"The selector uniquely matches a encoded or symbolized method, but the Interface Builder receiver is an unresolved placeholder; runtime dispatch was not observed.",
]
: [
"The Interface Builder target and encoded or 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,
},
],
});
};
+120
View File
@@ -0,0 +1,120 @@
import { z } from "zod";
import { nativeMetadataRecoverySummarySchema } from "./nativeMetadataRecovery.js";
import { jsonValueSchema } from "../jsonValue.js";
const integer = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const digest = z.string().regex(/^[a-f0-9]{64}$/u);
const hexBytes = z.string().regex(/^(?:[a-f0-9]{2})*$/u);
const address = z.string().min(1);
/** Measured provider image, without exporting the complete executable bytes. */
export const nativeLoadImageObservationSchema = z.strictObject({
metadata_recovery: z.array(nativeMetadataRecoverySummarySchema).optional(),
executable_format: z.string().min(1),
language_id: z.string().min(1),
compiler_spec_id: z.string().min(1),
image_base: address,
default_address_space: z.string().min(1),
source_files: z.array(
z.strictObject({
name: z.string(),
size: integer,
original_sha256: digest,
modified_sha256: digest,
}),
),
mappings: z.array(
z.strictObject({
block: z.string(),
start: address,
end: address,
address_space: z.string().min(1),
initialized: z.boolean(),
loaded: z.boolean(),
overlay: z.boolean(),
length: integer.min(1),
source_file_index: integer.nullable(),
file_offset: integer.nullable(),
sha256: digest.nullable(),
}),
),
relocations: z.array(
z.strictObject({
address,
segment: integer.max(0xffff).nullable(),
offset: integer.max(0xffff).nullable(),
status: z.string().min(1),
type: z.number().int(),
values: z.array(
z
.number()
.int()
.min(Number.MIN_SAFE_INTEGER)
.max(Number.MAX_SAFE_INTEGER),
),
original_bytes_hex: hexBytes.nullable(),
memory_bytes_hex: hexBytes.nullable(),
}),
),
entry_points: z.array(address),
entry_context: z.array(
z.strictObject({
address,
registers: z.array(
z.strictObject({
name: z.string().min(1),
value_hex: z
.string()
.regex(/^0x[a-f0-9]+$/u)
.nullable(),
}),
),
}),
),
});
/** Independent comparison, preserving both expectations and measured values. */
export const nativeLoadImageCheckSchema = z.strictObject({
name: z.string().min(1),
matched: z.boolean(),
expected: jsonValueSchema,
observed: jsonValueSchema,
file_offset: integer.nullable(),
address: address.nullable(),
});
/** Read-only native image verification; verified applies only to declared coverage. */
export const nativeLoadImageSchema = z.discriminatedUnion("status", [
z.strictObject({
status: z.literal("unsupported"),
reason: z.string().min(1),
observations: nativeLoadImageObservationSchema,
limitations: z.array(z.string().min(1)),
}),
z.strictObject({
status: z.enum(["verified", "mismatch"]),
format: z.enum(["dos-mz", "dos-com"]),
target_sha256: digest,
load_segment: integer.max(0xffff),
header_bytes: integer,
module_bytes: integer,
overlay_bytes: integer,
entry: z.strictObject({
relative_segment: integer.max(0xffff),
offset: integer.max(0xffff),
linear_address: address,
}),
observations: nativeLoadImageObservationSchema,
checks: z.array(nativeLoadImageCheckSchema),
limitations: z.array(z.string().min(1)),
}),
]);
/** Provider-neutral native load-image result. */
export type NativeLoadImage = z.infer<typeof nativeLoadImageSchema>;
/** Measured source mappings, bytes, relocations and entries. */
export type NativeLoadImageObservation = z.infer<
typeof nativeLoadImageObservationSchema
>;
/** One independently compared native import fact. */
export type NativeLoadImageCheck = z.infer<typeof nativeLoadImageCheckSchema>;
@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import {
nativeMetadataRecoverySchema,
nativeMetadataRecoverySummarySchema,
} from "./nativeMetadataRecovery.js";
import { jsonValueSchema } from "../jsonValue.js";
const metadata = {
format: "dotnet-nativeaot",
status: "partial",
header_address: "0x401000",
format_major: 9,
format_minor: 1,
method_table_address: "0x402000",
name_origin: "generated",
original_name: null,
base_size_bytes: 24,
related_type: { address: "0x403000", type: null },
interfaces: [],
virtual_slots: [
{
slot: 0,
slot_address: "0x402018",
target_address: null,
procedure_name: null,
basis: "method-table-pointer",
},
],
derived_memory: {
address: "0x402000",
size_bytes: 128,
sha256: "a".repeat(64),
file_offset: null,
},
diagnostics: ["candidate annotation missing"],
limitations: ["Names are generated; original fields unknown"],
};
describe("NativeAOT recovery evidence", () => {
it("preserves generated identities, unresolved relationships and null virtual targets", () => {
expect(
jsonValueSchema.parse(nativeMetadataRecoverySchema.parse(metadata)),
).toEqual(metadata);
});
it("rejects invented source authority and original file offsets for derived memory", () => {
expect(
nativeMetadataRecoverySchema.safeParse({
...metadata,
original_name: "InventedClass",
}).success,
).toBe(false);
expect(
nativeMetadataRecoverySchema.safeParse({
...metadata,
derived_memory: { ...metadata.derived_memory, file_offset: 128 },
}).success,
).toBe(false);
});
it("keeps a negative discovery explicit without fabricating a header", () => {
const summary = {
format: "dotnet-nativeaot",
status: "not_applicable",
reason: "No supported row layout found",
analysis_artifact_sha256: "b".repeat(64),
header_address: null,
discovery: null,
format_major: null,
format_minor: null,
method_tables: 0,
types: [],
derived_memory: null,
coverage: null,
diagnostics: [],
limitations: [],
};
expect(nativeMetadataRecoverySummarySchema.parse(summary)).toEqual(summary);
});
});
@@ -0,0 +1,62 @@
import { z } from "zod";
const address = z.string().regex(/^0x[0-9a-f]+$/u);
const relatedType = z.strictObject({ address, type: z.string().nullable() });
/** Runtime-format metadata recovered in an analysis image, with explicit inference boundaries. */
export const nativeMetadataRecoverySchema = z.strictObject({
format: z.literal("dotnet-nativeaot"),
status: z.enum(["complete", "partial"]),
header_address: address,
format_major: z.number().int().nonnegative(),
format_minor: z.number().int().nonnegative(),
method_table_address: address,
name_origin: z.enum(["generated", "inferred"]),
original_name: z.null(),
base_size_bytes: z.number().int().nonnegative(),
related_type: relatedType.nullable(),
interfaces: z.array(relatedType),
virtual_slots: z.array(
z.strictObject({
slot: z.number().int().nonnegative(),
slot_address: address,
target_address: address.nullable(),
procedure_name: z.string().nullable(),
basis: z.literal("method-table-pointer"),
}),
),
derived_memory: z.strictObject({
address,
size_bytes: z.number().int().nonnegative(),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
file_offset: z.null(),
}),
diagnostics: z.array(z.string()),
limitations: z.array(z.string()),
});
/** Discover a recovered runtime format and reusable type identities from the loaded image. */
export const nativeMetadataRecoverySummarySchema = z.strictObject({
format: z.literal("dotnet-nativeaot"),
status: z.enum(["complete", "partial", "not_applicable"]),
reason: z.string().nullable(),
analysis_artifact_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
header_address: address.nullable(),
discovery: z.enum(["symbol", "signature-heuristic"]).nullable(),
format_major: z.number().int().nonnegative().nullable(),
format_minor: z.number().int().nonnegative().nullable(),
method_tables: z.number().int().nonnegative(),
types: z.array(relatedType),
derived_memory: nativeMetadataRecoverySchema.shape.derived_memory.nullable(),
coverage: z
.strictObject({
frozen_object_candidates: z.number().int().nonnegative(),
frozen_objects_annotated: z.number().int().nonnegative(),
basis: z.literal(
"rehydrated-pointer-candidates-and-committed-instance-types",
),
})
.nullable(),
diagnostics: z.array(z.string()),
limitations: z.array(z.string()),
});
+142
View File
@@ -0,0 +1,142 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import { decodeCanonicalBase64 } from "../webScreenshot.js";
const scope = {
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
screenshot: z.boolean().default(true),
accessibility: z.boolean().default(true),
max_nodes: z
.number()
.int()
.positive()
.safe()
.default(500)
.describe(
"Maximum accessibility nodes per capture; increase for large windows.",
),
};
/** Opt-in passive observation binds one already-running process and window. */
export const nativeUiObservationInputSchema = z.strictObject(scope);
/** Active scenarios use explicit actions and leave application state as-is. */
export const nativeUiScenarioInputSchema = z.strictObject({
...scope,
steps: z
.array(
z.discriminatedUnion("kind", [
z.strictObject({
kind: z.literal("click"),
path: z.array(z.number().int().nonnegative()).max(32),
}),
z.strictObject({
kind: z.literal("scroll"),
path: z.array(z.number().int().nonnegative()).max(32),
direction: z.enum(["increment", "decrement"]),
}),
z.strictObject({
kind: z.literal("key-entry"),
path: z.array(z.number().int().nonnegative()).max(32),
text: z.string(),
}),
z.strictObject({
kind: z.literal("wait"),
milliseconds: z
.number()
.int()
.min(0)
.max(180_000)
.describe(
"Wait duration in milliseconds, within the 180-second operation deadline.",
),
}),
]),
)
.min(1),
});
/** Ordered captures and failures distinguish missing observation from a failed action. */
const nativeUiScreenshotSchema = z
.strictObject({
mime_type: z.literal("image/png"),
base64: z.string().min(4),
sha256: z.string().regex(/^[a-f0-9]{64}$/u),
width: z.number().int().positive(),
height: z.number().int().positive(),
})
.superRefine((screenshot, context) => {
const bytes = decodeCanonicalBase64(screenshot.base64);
if (bytes === undefined) {
context.addIssue({
code: "custom",
message: "Invalid canonical PNG base64",
});
return;
}
if (createHash("sha256").update(bytes).digest("hex") !== screenshot.sha256)
context.addIssue({
code: "custom",
message: "PNG screenshot digest mismatch",
});
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.subarray(12, 16).toString("ascii") !== "IHDR"
) {
context.addIssue({
code: "custom",
message: "Screenshot bytes are not a PNG image",
});
return;
}
if (
bytes.readUInt32BE(16) !== screenshot.width ||
bytes.readUInt32BE(20) !== screenshot.height
)
context.addIssue({
code: "custom",
message: "PNG screenshot dimensions mismatch",
});
});
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
export const nativeUiSnapshotSchema = z.strictObject({
window: z.strictObject({
pid: z.number().int().positive(),
window_id: z.number().int().positive(),
executable: z.string(),
launch_time: z.number(),
title: z.string(),
}),
nodes: z.array(
z.strictObject({
path: z.array(z.number().int().nonnegative()),
role: z.string().nullable(),
title: z.string().nullable(),
value: z.string().nullable(),
actions: z.array(z.string()),
children_count: z.number().int().nonnegative(),
}),
),
truncated: z.boolean(),
screenshot: nativeUiScreenshotSchema.nullable(),
gaps: z.array(z.string()),
});
export const nativeUiResultSchema = z.strictObject({
target_sha256: z.string(),
initial: nativeUiSnapshotSchema,
steps: z.array(
z.strictObject({
index: z.number().int().nonnegative(),
kind: z.string(),
before: nativeUiSnapshotSchema,
after: nativeUiSnapshotSchema.nullable(),
outcome: z.enum(["completed", "failed", "cancelled"]),
reason: z.string().nullable(),
}),
),
restore: z.literal("leave-as-is"),
limitations: z.array(z.string()),
});
+87
View File
@@ -0,0 +1,87 @@
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(),
block_membership: z
.enum(["member", "detached", "unavailable"])
.default("unavailable"),
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),
parameters: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
}),
)
.default([]),
parameter_uses: z
.array(
z.strictObject({
ordinal: z.number().int().nonnegative(),
use: z.string(),
input_index: z.number().int().nonnegative(),
}),
)
.default([]),
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)),
}),
]);
+73
View File
@@ -0,0 +1,73 @@
import { z } from "zod";
import { nativePcodeOperationSchema } from "./nativeValueFlow.js";
/** Work and output budgets for a static procedure-seeded dependency graph. */
export const nativeValueTraceInputSchema = z.strictObject({
procedure: z.string().min(1),
max_depth: z.number().int().min(0).max(16).default(3),
max_functions: z.number().int().min(1).max(64).default(16),
max_call_sites: z.number().int().min(1).max(4096).default(256),
max_nodes: z.number().int().min(1).max(20_000).default(5_000),
max_edges: z.number().int().min(1).max(40_000).default(10_000),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(5_000).default(1_000),
});
/** Def-use observations and call relationships retain separate authority. */
export const nativeValueTraceSchema = z.strictObject({
seed: z.string(),
target_sha256: z.string(),
nodes: z.array(
z.strictObject({
id: z.string(),
procedure: z.string(),
evidence_id: z.string(),
kind: z.enum(["operation", "parameter"]),
operation: nativePcodeOperationSchema.nullable(),
parameter: z
.strictObject({
ordinal: z.number().int().nonnegative(),
name: z.string(),
data_type: z.string(),
})
.nullable(),
}),
),
edges: z.array(
z.strictObject({
source: z.string(),
target: z.string(),
input_index: z.number().int().nonnegative().nullable(),
kind: z.enum([
"def-use",
"call",
"parameter-use",
"argument-binding",
"return-binding",
]),
status: z.enum(["derived", "direct", "resolved-indirect", "candidate"]),
evidence_id: z.string(),
}),
),
procedures: z.array(
z.strictObject({
address: z.string(),
depth: z.number().int().nonnegative(),
evidence_id: z.string(),
provider: z.string(),
analysis_profile_digest: z.string().nullable(),
}),
),
unknowns: z.array(
z.strictObject({
procedure: z.string(),
address: z.string().nullable(),
reason: z.string(),
}),
),
total_nodes: z.number().int().nonnegative(),
total_edges: z.number().int().nonnegative(),
decompilations: z.number().int().nonnegative(),
next_offset: z.number().int().nonnegative().nullable(),
truncated: z.boolean(),
limitations: z.array(z.string()),
});
+174
View File
@@ -0,0 +1,174 @@
import { fc } from "@fast-check/vitest";
import { describe, expect, it } from "vitest";
import {
countMethodsByType,
isDbSaveComplete,
isGetterSelector,
isSetterSelector,
inspectNativeDispatchMetadata,
propertyNameFromSelector,
swiftDeclsByKind,
type ObjcMethod,
type SwiftDecl,
type DbSaveResult,
} from "./objcSwiftMetadata.js";
describe("ObjC/Swift metadata", () => {
it("identifies getter selectors", () => {
expect(isGetterSelector("name")).toBe(true);
expect(isGetterSelector("setName:")).toBe(false);
expect(isGetterSelector("set")).toBe(true);
});
it("identifies setter selectors", () => {
expect(isSetterSelector("setName:")).toBe(true);
expect(isSetterSelector("name")).toBe(false);
});
it("extracts property name from selector", () => {
expect(propertyNameFromSelector("name")).toBe("name");
expect(propertyNameFromSelector("setName:")).toBe("name");
expect(propertyNameFromSelector("set")).toBe("set");
});
it("counts methods by type", () => {
const methods: ObjcMethod[] = [
{
selector: "init",
method_type: "instance",
address: 0x1000,
is_required: false,
is_optional: false,
},
{
selector: "alloc",
method_type: "class",
address: 0x2000,
is_required: false,
is_optional: false,
},
];
const counts = countMethodsByType(methods);
expect(counts.instance).toBe(1);
expect(counts.class).toBe(1);
expect(counts.ivar_getter).toBe(0);
expect(counts.ivar_setter).toBe(0);
});
it("filters Swift declarations by kind", () => {
const decls: SwiftDecl[] = [
{
kind: "class",
name: "Foo",
module: null,
access_level: "public",
super_class: null,
protocols: [],
is_final: false,
is_required: false,
is_convenience_init: false,
is_override: false,
},
];
const classes = swiftDeclsByKind(decls, "class");
expect(classes).toHaveLength(1);
expect(classes[0]!.name).toBe("Foo");
});
it("checks database save completeness", () => {
const result: DbSaveResult = {
operation: "save",
succeeded: true,
preserved_names: 10,
preserved_comments: 5,
preserved_bookmarks: 3,
database_path: "/tmp/db.hop",
error: null,
};
expect(isDbSaveComplete(result, 10, 5, 3)).toBe(true);
expect(isDbSaveComplete(result, 11, 5, 3)).toBe(false);
});
it("is monotone in every expected count and total at the observed count", () => {
fc.assert(
fc.property(
fc.record({
operation: fc.constantFrom(
"save",
"readback",
"open_database",
"close_database",
"export",
"import",
),
succeeded: fc.boolean(),
preserved_names: fc.nat({ max: 50 }),
preserved_comments: fc.nat({ max: 50 }),
preserved_bookmarks: fc.nat({ max: 50 }),
database_path: fc.option(fc.string(), { nil: null }),
error: fc.option(fc.string(), { nil: null }),
}),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
fc.nat({ max: 50 }),
(result, names, comments, bookmarks) => {
// Completeness is downward closed: if demanding more was met,
// demanding less must also be met.
if (isDbSaveComplete(result, names + 1, comments, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments + 1, bookmarks)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
if (isDbSaveComplete(result, names, comments, bookmarks + 1)) {
expect(isDbSaveComplete(result, names, comments, bookmarks)).toBe(
true,
);
}
// Expecting exactly what was preserved is complete iff the save worked.
expect(
isDbSaveComplete(
result,
result.preserved_names,
result.preserved_comments,
result.preserved_bookmarks,
),
).toBe(result.succeeded);
},
),
{ numRuns: 200 },
);
});
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",
}),
);
});
});
+538
View File
@@ -0,0 +1,538 @@
import { z } from "zod";
/** Objective-C method type. */
export const objcMethodTypeSchema = z.enum([
"instance",
"class",
"ivar_getter",
"ivar_setter",
]);
export type ObjcMethodType = z.infer<typeof objcMethodTypeSchema>;
/** Objective-C property attribute. */
export const objcPropertyAttributeSchema = z.strictObject({
name: z.string().min(1),
value: z.string(),
is_weak: z.boolean().default(false),
is_atomic: z.boolean().default(false),
is_copy: z.boolean().default(false),
is_strong: z.boolean().default(false),
});
/** Objective-C method metadata. */
export const objcMethodSchema = z.strictObject({
selector: z.string().min(1),
method_type: objcMethodTypeSchema,
address: z.number().int().nullable(),
is_required: z.boolean().default(false),
is_optional: z.boolean().default(false),
});
export type ObjcMethod = z.infer<typeof objcMethodSchema>;
/** Objective-C property metadata. */
export const objcPropertySchema = z.strictObject({
name: z.string().min(1),
type_encoding: z.string().nullable(),
attributes: z.array(objcPropertyAttributeSchema).default([]),
is_readonly: z.boolean().default(false),
getter: z.string().nullable(),
setter: z.string().nullable(),
});
/** Objective-C protocol metadata. */
export const objcProtocolSchema = z.strictObject({
name: z.string().min(1),
methods: z.array(objcMethodSchema).default([]),
optional_methods: z.array(objcMethodSchema).default([]),
properties: z.array(objcPropertySchema).default([]),
});
/** Objective-C class metadata. */
export const objcClassSchema = z.strictObject({
name: z.string().min(1),
super_class: z.string().nullable(),
is_meta_class: z.boolean().default(false),
is_root_class: z.boolean().default(false),
methods: z.array(objcMethodSchema).default([]),
properties: z.array(objcPropertySchema).default([]),
protocols: z.array(z.string()).default([]),
ivar_count: z.number().int().nonnegative().default(0),
instance_size: z.number().int().nonnegative().nullable(),
location: z
.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
})
.optional(),
superclass_address: z.string().nullable().optional(),
metaclass_address: z.string().nullable().optional(),
decode: z
.object({
status: z.enum(["decoded", "partial", "unsupported", "invalid"]),
reason: z.string().nullable(),
})
.optional(),
evidence: z
.array(
z.object({
kind: z.literal("binary_metadata"),
description: z.string(),
location: z.object({
address: z.string().nullable(),
file_offset: z.number().int().nonnegative().nullable(),
}),
artifact_path: z.string(),
artifact_sha256: z.string(),
}),
)
.optional(),
});
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(),
});
/** 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(),
size: z.number().int().nonnegative().nullable().default(null),
alignment: z.number().int().positive().nullable().default(null),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** Encoded Objective-C protocol declaration with required and optional method facts. */
export const objcProtocolRecordSchema = z.strictObject({
name: z.string(),
adopted_protocols: z.array(z.string()),
methods: z.array(objcMethodSchema),
optional_methods: z.array(objcMethodSchema),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** 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(),
/** Category that adds this method, when it is not defined by the class itself. */
category: z.string().nullable().optional(),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
export type ObjcDispatchImplementation = z.infer<
typeof objcDispatchImplementationSchema
>;
/** Objective-C category: methods, protocols and properties added to a class. */
export const objcCategorySchema = z.strictObject({
name: z.string().min(1),
/** Extended class; external classes come from the category's bind symbol. */
class_name: z.string().min(1).nullable(),
class_source: z.enum(["local", "external", "unresolved"]),
instance_methods: z.array(z.string()),
class_methods: z.array(z.string()),
protocols: z.array(z.string()),
properties: z.array(objcPropertySchema),
location: nativeMetadataLocationSchema,
decode: nativeMetadataDecodeSchema,
evidence: z.array(nativeMetadataEvidenceSchema).min(1),
});
/** 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),
});
/** 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),
});
/** 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),
});
/** 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(),
});
/** Swift declaration kind. */
export const swiftDeclKindSchema = z.enum([
"class",
"struct",
"enum",
"protocol",
"extension",
"actor",
"global_var",
"global_func",
]);
export type SwiftDeclKind = z.infer<typeof swiftDeclKindSchema>;
/** Swift access level. */
export const swiftAccessLevelSchema = z.enum([
"private",
"fileprivate",
"internal",
"public",
"open",
]);
/** Swift declaration metadata. */
export const swiftDeclSchema = z.strictObject({
kind: swiftDeclKindSchema,
name: z.string().min(1),
module: z.string().nullable(),
access_level: swiftAccessLevelSchema.default("internal"),
super_class: z.string().nullable(),
protocols: z.array(z.string()).default([]),
is_final: z.boolean().default(false),
is_required: z.boolean().default(false),
is_convenience_init: z.boolean().default(false),
is_override: z.boolean().default(false),
});
export type SwiftDecl = z.infer<typeof swiftDeclSchema>;
/** Database save/read operation type. */
export const dbOperationSchema = z.enum([
"save",
"readback",
"open_database",
"close_database",
"export",
"import",
]);
/** Database save operation result. */
export const dbSaveResultSchema = z.strictObject({
operation: dbOperationSchema,
succeeded: z.boolean(),
preserved_names: z.number().int().nonnegative().default(0),
preserved_comments: z.number().int().nonnegative().default(0),
preserved_bookmarks: z.number().int().nonnegative().default(0),
database_path: z.string().nullable(),
error: z.string().nullable(),
});
export type DbSaveResult = z.infer<typeof dbSaveResultSchema>;
/** Result of deeper ObjC/Swift metadata extraction. */
export const objcSwiftMetadataSchema = z.strictObject({
objc_classes: z.array(objcClassSchema).default([]),
objc_protocols: z.array(objcProtocolSchema).default([]),
objc_categories: z.array(objcCategorySchema).default([]),
swift_decls: z.array(swiftDeclSchema).default([]),
objc_ivars: z.array(objcIvarSchema).default([]),
objc_protocol_records: z.array(objcProtocolRecordSchema).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,
});
/** 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(":");
}
/** Check if a selector name looks like a setter. */
export function isSetterSelector(selector: string): boolean {
return selector.startsWith("set") && selector.endsWith(":");
}
/** Extract property name from a getter/setter selector. */
export function propertyNameFromSelector(selector: string): string | null {
if (isSetterSelector(selector)) {
const inner = selector.slice(3, -1);
return inner.charAt(0).toLowerCase() + inner.slice(1);
}
if (isGetterSelector(selector)) {
return selector;
}
return null;
}
/** Count ObjC methods by type. */
export function countMethodsByType(
methods: readonly ObjcMethod[],
): Record<ObjcMethodType, number> {
return {
instance: methods.filter((m) => m.method_type === "instance").length,
class: methods.filter((m) => m.method_type === "class").length,
ivar_getter: methods.filter((m) => m.method_type === "ivar_getter").length,
ivar_setter: methods.filter((m) => m.method_type === "ivar_setter").length,
};
}
/** Get all Swift declarations of a specific kind. */
export function swiftDeclsByKind(
decls: readonly SwiftDecl[],
kind: SwiftDeclKind,
): SwiftDecl[] {
return decls.filter((d) => d.kind === kind);
}
/** Check if a database save preserved all expected items. */
export function isDbSaveComplete(
result: DbSaveResult,
expectedNames: number,
expectedComments: number,
expectedBookmarks: number,
): boolean {
return (
result.succeeded &&
result.preserved_names >= expectedNames &&
result.preserved_comments >= expectedComments &&
result.preserved_bookmarks >= expectedBookmarks
);
}