Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(managed): compare observed call targets
morlutoc70eefad50a7
diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.mdindex b17100565..d9dea7fff 100644--- a/docs/managed-code-analysis.md+++ b/docs/managed-code-analysis.md@@ -386,6 +386,13 @@ constants, and bounded shape context. It reports all candidates at the winningscore and remains ambiguous when the evidence does not distinguish them. Thedigest does not itself remap metadata tokens.+Matched methods also compare aligned call sites. `call-shape` reports opcode and+operand-kind differences; `call-target` reports differences in the observed+target declaring-type or method name from `call_edges`. Target tokens remain+build-local and are not compared across artifacts. Missing or unaligned call+edges and missing target names leave that facet unknown; equal names do not+establish overload identity or runtime dispatch.+Tokens are always remapped through observed structure. A caller cannot carry`0x06001234` into a new MVID and assume it names the same method.diff --git a/src/contracts/managed/managedWorkflowToolContracts.ts b/src/contracts/managed/managedWorkflowToolContracts.tsindex 9124b2c42..4db8335ae 100644--- a/src/contracts/managed/managedWorkflowToolContracts.ts+++ b/src/contracts/managed/managedWorkflowToolContracts.ts@@ -75,7 +75,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [name: "compare_managed_members",...toolContractMetadata("compare_managed_members"),description:- "Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Signatures compare type operands by name, not by build-local metadata row. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",+ "Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Signatures compare type operands by name, not by build-local metadata row. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Matched methods also compare aligned call-site shapes and observed target declaring-type/method names; missing or unaligned call edges and target names remain unknown. These static names do not prove overload identity or runtime dispatch. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",kind: "application",inputSchema: compareManagedMembersInputSchema,outputSchema: comparisonOutputSchema,diff --git a/src/domain/managed/managedMemberComparison.ts b/src/domain/managed/managedMemberComparison.tsindex 1dbe8dff2..73b0277cc 100644--- a/src/domain/managed/managedMemberComparison.ts+++ b/src/domain/managed/managedMemberComparison.ts@@ -132,6 +132,7 @@ const methodComparisonItemSchema = comparisonItemSchema("cil","opcode-shape","call-shape",+ "call-target","field-shape","exception-shape","availability",@@ -217,6 +218,24 @@ const selectedTypes = (): ReadonlySet<string> | null =>result.selection === null ? null : new Set(result.selection.type_names);+const callEdgesByCaller = (+ result: ManagedMemberInspection,+): ReadonlyMap<+ string,+ readonly ManagedMemberInspection["call_edges"][number][]+> => {+ const edges = new Map<+ string,+ ManagedMemberInspection["call_edges"][number][]+ >();+ for (const edge of result.call_edges) {+ const callerEdges = edges.get(edge.caller_token);+ if (callerEdges === undefined) edges.set(edge.caller_token, [edge]);+ else callerEdges.push(edge);+ }+ return edges;+};+/** Compare managed members with constrained exact and structural identities. */export const compareManagedMembers = (left: ManagedMemberComparisonSide,@@ -233,6 +252,8 @@ export const compareManagedMembers = (signatureResolutionExamined:hasSignatureResolution(left.result) &&hasSignatureResolution(right.result),+ leftCallEdgesByCaller: callEdgesByCaller(left.result),+ rightCallEdgesByCaller: callEdgesByCaller(right.result),};const methodItems = buildMethodItems(methodMatches, itemContext);const fieldItems = buildFieldItems(fieldMatches, itemContext);diff --git a/src/domain/managed/managedMemberComparisonItems.ts b/src/domain/managed/managedMemberComparisonItems.tsindex 714b416bd..b4ae7500a 100644--- a/src/domain/managed/managedMemberComparisonItems.ts+++ b/src/domain/managed/managedMemberComparisonItems.ts@@ -11,6 +11,10 @@ import { signatureIdentity } from "./managedMemberSignatureIdentity.js";type Method = ManagedMemberInspection["methods"][number];type Field = ManagedMemberInspection["fields"][number];+type CallEdgesByCaller = ReadonlyMap<+ string,+ readonly ManagedMemberInspection["call_edges"][number][]+>;type MethodItem = ManagedMemberComparisonResult["methods"][number];type FieldItem = ManagedMemberComparisonResult["fields"][number];type UnmatchedComparison = Extract<@@ -32,6 +36,8 @@ interface ComparisonItemContext {readonly rightSelection: ReadonlySet<string> | null;/** Whether matching keyed signatures by resolved digests, not raw bytes. */readonly signatureResolutionExamined: boolean;+ readonly leftCallEdgesByCaller: CallEdgesByCaller;+ readonly rightCallEdgesByCaller: CallEdgesByCaller;}/** Whether an inventory observed every member of this member's declaring type. */@@ -61,9 +67,12 @@ interface UndecodedOneSidedNames {const methodDimensions = (left: Method,right: Method,+ leftCallEdgesByCaller: CallEdgesByCaller,+ rightCallEdgesByCaller: CallEdgesByCaller,): {readonly dimensions: MethodItem["dimensions"];readonly bodyUnknown: boolean;+ readonly callTargetUnknown: boolean;} => {const dimensions: MethodItem["dimensions"] = [];const headerFields = ["max_stack", "init_locals"] as const;@@ -98,9 +107,26 @@ const methodDimensions = ((right.body.status === "absent" && leftBodyComplete))dimensions.push("availability");- if (bothAbsent) return { dimensions, bodyUnknown: false };+ if (bothAbsent)+ return { dimensions, bodyUnknown: false, callTargetUnknown: false };+ const sameCallShape =+ callShape(left.body.anchors) === callShape(right.body.anchors);+ const callTargets = sameCallShape+ ? compareCallTargets(+ left,+ right,+ leftCallEdgesByCaller.get(left.token) ?? [],+ rightCallEdgesByCaller.get(right.token) ?? [],+ )+ : { changed: false, unknown: false };+ if (callTargets.changed) dimensions.push("call-target");if (!leftBodyComplete || !rightBodyComplete)- return { dimensions, bodyUnknown: true };+ return {+ dimensions,+ bodyUnknown: true,+ callTargetUnknown: callTargets.unknown,+ };+ if (!sameCallShape) dimensions.push("call-shape");// The decoded fingerprint omits switch targets and is not exact CIL identity.if (left.body.il_sha256 !== right.body.il_sha256 ||@@ -112,8 +138,6 @@ const methodDimensions = (canonicalize(right.body.opcode_counts))dimensions.push("opcode-shape");- if (callShape(left.body.anchors) !== callShape(right.body.anchors))- dimensions.push("call-shape");if (fieldShape(left.body.anchors) !== fieldShape(right.body.anchors))dimensions.push("field-shape");if (@@ -123,12 +147,59 @@ const methodDimensions = (dimensions.push("exception-shape");return {dimensions,+ callTargetUnknown: callTargets.unknown,bodyUnknown: headerFields.some((field) => left.body[field] === null || right.body[field] === null,),};};+const compareCallTargets = (+ left: Method,+ right: Method,+ leftEdges: readonly ManagedMemberInspection["call_edges"][number][],+ rightEdges: readonly ManagedMemberInspection["call_edges"][number][],+): { readonly changed: boolean; readonly unknown: boolean } => {+ const callAnchors = (method: Method) =>+ method.body.anchors.filter(+ ({ opcode, operand_kind }) =>+ opcode !== "ldtoken" && operand_kind === "method",+ );+ const leftAnchors = callAnchors(left);+ const rightAnchors = callAnchors(right);+ if (leftAnchors.length !== rightAnchors.length)+ return { changed: false, unknown: true };+ if (+ leftEdges.length !== leftAnchors.length ||+ rightEdges.length !== rightAnchors.length ||+ leftEdges.some(+ (edge, index) => edge.opcode !== leftAnchors[index]?.opcode,+ ) ||+ rightEdges.some(+ (edge, index) => edge.opcode !== rightAnchors[index]?.opcode,+ )+ )+ return { changed: false, unknown: true };++ let changed = false;+ let unknown = false;+ for (let index = 0; index < leftEdges.length; index++) {+ const leftEdge = leftEdges[index];+ const rightEdge = rightEdges[index];+ if (leftEdge === undefined || rightEdge === undefined) {+ unknown = true;+ continue;+ }+ for (const field of ["target_name", "target_declaring_type"] as const) {+ const leftValue = leftEdge[field];+ const rightValue = rightEdge[field];+ if (leftValue === null || rightValue === null) unknown = true;+ else if (leftValue !== rightValue) changed = true;+ }+ }+ return { changed, unknown };+};+const callShape = (anchors: Method["body"]["anchors"]): string =>JSON.stringify(anchors@@ -445,13 +516,21 @@ export const buildMethodItems = (pair.right.item,context.signatureResolutionExamined,);- const { dimensions: observedDimensions, bodyUnknown } = methodDimensions(+ const {+ dimensions: observedDimensions,+ bodyUnknown,+ callTargetUnknown,+ } = methodDimensions(pair.left.item,pair.right.item,+ context.leftCallEdgesByCaller,+ context.rightCallEdgesByCaller,);- const dimensions = bodyUnknown- ? [...observedDimensions, "body-coverage" as const]- : observedDimensions;+ const dimensions = [+ ...observedDimensions,+ ...(bodyUnknown ? (["body-coverage"] as const) : []),+ ...(callTargetUnknown ? (["availability"] as const) : []),+ ];const observedChange = observedDimensions.length > 0;items.push({item_id: `mmc_method_${digestCanonicalValue(@@ -464,7 +543,7 @@ export const buildMethodItems = ()}`,status: observedChange? "changed"- : bodyUnknown || signatureLimitations.length > 0+ : bodyUnknown || callTargetUnknown || signatureLimitations.length > 0? "unknown": "unchanged",left: methodIdentity(pair.left.item),@@ -485,6 +564,11 @@ export const buildMethodItems = ("Method body facets are unknown because at least one side has unavailable or partial body data.",]: []),+ ...(callTargetUnknown+ ? [+ "One or more call targets are unavailable because the observed method edges do not cover aligned call instructions or lack a target name or declaring type.",+ ]+ : []),],});}diff --git a/tests/boundary/mcp/managedMcp.test.ts b/tests/boundary/mcp/managedMcp.test.tsindex da68436c3..82352c3bd 100644--- a/tests/boundary/mcp/managedMcp.test.ts+++ b/tests/boundary/mcp/managedMcp.test.ts@@ -22,6 +22,7 @@ import { createServer } from "../../../src/server/createServer.js";import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";import { elf } from "../../../src/domain/binaryTarget.fixture.js";import { managedMemberInspectionSchema } from "../../../src/domain/managed/managedArtifact.js";+import { managedMemberComparisonResultSchema } from "../../../src/domain/managed/managedMemberComparison.js";type ManagedOutputAssertion = Awaited<ReturnType<typeof createOutputAssertion>>;@@ -96,6 +97,7 @@ it("runs every managed static inspection independently of an active native targename: "managed-independent-mcp",version: "1.0.0",});+const [clientTransport, serverTransport] =InMemoryTransport.createLinkedPair();try {@@ -206,6 +208,91 @@ it("runs every managed static inspection independently of an active native targe}}, 30_000);+it("compares observed call-target names through the managed MCP contract", async () => {+ const directory = await createTestTempDirectory("rea-managed-call-target-");+ const leftPath = join(directory, "left.dll");+ const rightPath = join(directory, "right.dll");+ const samePath = join(directory, "same.dll");+ const il = Buffer.from([0x28, 1, 0, 0, 0x0a, 0x2a]);+ const fixture = (memberRefName: string) =>+ buildManagedPeFixture({+ targetFramework: null,+ memberRefName,+ ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),+ });+ await Promise.all([+ writeFile(leftPath, fixture("Clear")),+ writeFile(rightPath, fixture("WriteLine")),+ writeFile(samePath, fixture("Clear")),+ ]);+ const session = composeBinarySession(new AnalysisProviderRegistry([]), [+ new ManagedStaticProvider(),+ ]);+ const server = createServer({ kind: "session", session });+ const client = new Client({ name: "managed-call-target-test", version: "1" });+ const [clientTransport, serverTransport] =+ InMemoryTransport.createLinkedPair();+ try {+ await server.connect(serverTransport);+ await client.connect(clientTransport);+ const outputAssertion = await createOutputAssertion(client);+ const inspect = async (path: string) =>+ inlineEvidence(+ structured(+ await client.callTool({+ name: "inspect_managed_members",+ arguments: { path },+ }),+ ),+ );+ const left = await inspect(leftPath);+ const right = await inspect(rightPath);+ const same = await inspect(samePath);+ for (const [evidence, name] of [+ [left, "Clear"],+ [right, "WriteLine"],+ ] as const) {+ const inspection = managedMemberInspectionSchema.parse(+ evidence.normalized_result,+ );+ expect(inspection.methods[0]?.body.anchors).toMatchObject([+ { opcode: "call", operand_kind: "method" },+ { opcode: "ret", operand_kind: "none" },+ ]);+ expect(inspection.call_edges[0]).toMatchObject({+ target_name: name,+ target_declaring_type:+ "System.Runtime.Versioning.TargetFrameworkAttribute",+ });+ }+ const compare = async (rightEvidence: Record<string, unknown>) =>+ structured(+ await client.callTool({+ name: "compare_managed_members",+ arguments: { left, right: rightEvidence },+ }),+ );+ const changed = inlineEvidence(await compare(right));+ outputAssertion.assert("compare_managed_members", changed);+ const changedReport = managedMemberComparisonResultSchema.parse(+ changed.normalized_result,+ );+ expect(changedReport.methods).toContainEqual(+ expect.objectContaining({+ status: "changed",+ dimensions: expect.arrayContaining(["call-target"]),+ }),+ );+ const unchanged = inlineEvidence(await compare(same));+ expect(+ managedMemberComparisonResultSchema.parse(unchanged.normalized_result)+ .methods,+ ).toContainEqual(expect.objectContaining({ status: "unchanged" }));+ } finally {+ await Promise.allSettled([client.close(), server.close(), session.close()]);+ }+});+it("opens a managed PE and executes the managed static provider through MCP", async () => {const directory = await createTestTempDirectory("rea-managed-mcp-");const path = join(directory, "fixture.exe");diff --git a/tests/boundary/providers/managed/managedMemberComparison.test.ts b/tests/boundary/providers/managed/managedMemberComparison.test.tsindex 523f8e2a4..3d48bdf2c 100644--- a/tests/boundary/providers/managed/managedMemberComparison.test.ts+++ b/tests/boundary/providers/managed/managedMemberComparison.test.ts@@ -333,27 +333,9 @@ describe("managed member comparison of nested types", () => {// from TypeDef 4 on the left into TypeDef 5 on the right.expect(pairs(compare(original, swapped))).toEqual({methods: [- [- "0x06000001",- "0x06000002",- "unchanged",- "exact-il-signature",- "exact",- ],- [- "0x06000002",- "0x06000001",- "unchanged",- "exact-il-signature",- "exact",- ],- [- "0x06000003",- "0x06000003",- "unchanged",- "exact-il-signature",- "exact",- ],+ ["0x06000001", "0x06000002", "unknown", "exact-il-signature", "exact"],+ ["0x06000002", "0x06000001", "unknown", "exact-il-signature", "exact"],+ ["0x06000003", "0x06000003", "unknown", "exact-il-signature", "exact"],],fields: [["0x04000001", "0x04000002", "unchanged", "field-signature", "exact"],@@ -382,7 +364,10 @@ describe("managed member comparison of nested types", () => {]);expect(comparison.methods.slice(0, 2).map(({ dimensions }) => dimensions),- ).toEqual([["cil"], ["cil"]]);+ ).toEqual([+ ["cil", "availability"],+ ["cil", "availability"],+ ]);expect(comparison.summary).toMatchObject({ changed: 2 });});@@ -437,9 +422,9 @@ describe("managed nested type names", () => {// Joined names would make both sides' Fixture.A+Inner one ambiguous group.expect(pairs(spelled).methods).toEqual([- ["0x06000001", "0x06000001", "unchanged", "exact-il-signature", "exact"],- ["0x06000003", "0x06000003", "unchanged", "exact-il-signature", "exact"],- ["0x06000002", "0x06000002", "unchanged", "exact-il-signature", "exact"],+ ["0x06000001", "0x06000001", "unknown", "exact-il-signature", "exact"],+ ["0x06000003", "0x06000003", "unknown", "exact-il-signature", "exact"],+ ["0x06000002", "0x06000002", "unknown", "exact-il-signature", "exact"],]);});@@ -551,6 +536,87 @@ describe("managed member comparison subject identity", () => {});});+describe("managed call-target comparison", () => {+ it("keeps changed call targets visible when another target fact is unavailable", () => {+ const il = Buffer.from([0x28, 1, 0, 0, 0x0a, 0x28, 1, 0, 0, 0x0a, 0x2a]);+ const observe = (+ name: string,+ path: string,+ alterEdges?: (+ edges: Inspection["call_edges"],+ ) => Inspection["call_edges"],+ ) => {+ const bytes = buildManagedPeFixture({+ targetFramework: null,+ memberRefName: name,+ ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),+ });+ const target = managedPeFixtureTarget(bytes, path);+ const inspection = inspectManagedMembersBytes(bytes, target);+ return createEvidence(+ target,+ {+ id: "call-target-fixture",+ name: "Call target fixture",+ version: "1",+ },+ {+ operation: "inspect_managed_members",+ parameters: {},+ result: jsonValueSchema.parse({+ ...inspection,+ call_edges:+ alterEdges?.(inspection.call_edges) ?? inspection.call_edges,+ }),+ confidence: "observed",+ authority: "shipped-artifact",+ },+ );+ };+ const left = observe("Clear", "/fixture/left.dll");+ const rightWithOneUnknownTarget = observe(+ "WriteLine",+ "/fixture/right.dll",+ (edges) =>+ edges.map((edge, index) =>+ index === 1+ ? { ...edge, target_name: null, target_declaring_type: null }+ : edge,+ ),+ );+ const result = executeManagedMemberComparison(+ compareManagedMembersInputSchema.parse({+ left,+ right: rightWithOneUnknownTarget,+ }),+ );+ if (!result.ok) throw result.error;+ const report = managedMemberComparisonResultSchema.parse(+ result.value.evidence.normalized_result,+ );+ expect(report.methods[0]).toMatchObject({+ status: "changed",+ dimensions: expect.arrayContaining(["call-target", "availability"]),+ limitations: [expect.stringContaining("call targets are unavailable")],+ });++ const unavailableEdges = observe(+ "Clear",+ "/fixture/no-edges.dll",+ () => [],+ );+ const unknown = executeManagedMemberComparison(+ compareManagedMembersInputSchema.parse({ left, right: unavailableEdges }),+ );+ if (!unknown.ok) throw unknown.error;+ expect(+ managedMemberComparisonResultSchema.parse(+ unknown.value.evidence.normalized_result,+ ).methods[0],+ ).toMatchObject({ status: "unknown", dimensions: ["availability"] });+ });+});+describe("managed member comparison path workflow", () => {it("preserves undecoded signatures as unknown through content-addressed partial Evidence", () => {const observe = (signature: number, path: string) => {