From 4dccd4d252a88a1d479ce92cc86d866904c125ee Mon Sep 17 00:00:00 2001 From: Afloat Date: Mon, 30 Nov 2026 23:09:51 +0800 Subject: [PATCH] fix(comparison): retain function CFG entry identity (#14082) Co-authored-by: Vincent Koc --- docs/native-function-matching.md | 4 +- docs/reference/mcp-contracts.md | 7 +- .../NativeFunctionMatchingService.test.ts | 63 +++++++++++++++++ .../native/NativeFunctionMatchingService.ts | 2 +- src/domain/comparisonEvidenceIdentity.ts | 2 +- src/domain/functionComparison.test.ts | 56 +++++++++++++++ src/domain/functionComparisonDimensions.ts | 6 +- src/domain/functionComparisonNormalization.ts | 5 ++ .../native/functionStructuralCandidate.ts | 5 +- .../mcp/functionComparisonMcp.test.ts | 69 +++++++++++++++++++ tests/fixtures/functionCfgDossier.ts | 22 ++++++ 11 files changed, 230 insertions(+), 11 deletions(-) create mode 100644 tests/fixtures/functionCfgDossier.ts diff --git a/docs/native-function-matching.md b/docs/native-function-matching.md index e75f7415216..f320dc91373 100644 --- a/docs/native-function-matching.md +++ b/docs/native-function-matching.md @@ -117,7 +117,9 @@ respective targets, then compare those dossiers. Matching never claims behaviora equivalence. Optional informative CFG/call/string fingerprints from supplied dossiers connect unresolved candidate groups only. They require observed CFG, callees and strings, complete observed call coverage, no unresolved calls, and -the same analysis-profile identity. Empty leaf-function buckets are excluded. +the same analysis-profile identity. The CFG fingerprint retains the entry block +after address normalization; a function entry outside the observed block starts +cannot produce a structural candidate. Empty leaf-function buckets are excluded. `structural_candidate_sha256` identifies that derived candidate signature; its dossier link preserves the full supporting facts. Group membership does not assert that every member pair is a candidate or equivalent. diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 14a751bbd2e..a2eac1c0b14 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -2580,8 +2580,11 @@ dimensions carry this limitation inline. Numeric constants remain part of the exact comparison. Reconstruction verification and static/runtime correlation retain limitations from the selected dimension; an overall function claim includes all dimension limitations. Equal CFGs establish only equal observed -block sizes and successor relationships. Text from different provider -identities remains unknown. +block sizes, successor relationships, and entry-block positions. Relocation and +input block order do not change this comparison. The function entry must name a +known block start in the same address space; an absent or unresolvable entry +keeps `cfg` unknown, including an empty block inventory. Text from different +provider identities remains unknown. The `calls` and `references` dimensions share endpoint identity and name ambiguity rules. Calls retain procedure entry coordinates and direction; diff --git a/src/application/native/NativeFunctionMatchingService.test.ts b/src/application/native/NativeFunctionMatchingService.test.ts index 04cf4eb5cd9..280a211cd2b 100644 --- a/src/application/native/NativeFunctionMatchingService.test.ts +++ b/src/application/native/NativeFunctionMatchingService.test.ts @@ -9,6 +9,7 @@ import { AnalysisResourceConstraintError } from "../../domain/analysisErrorCore. import { DEFAULT_NATIVE_MATCHING_REPRESENTATION_BYTES } from "../../domain/analysisResourceLimits.js"; import { functionDossierSchema } from "../../domain/native/functionDossier.js"; import { procedureInfoSchema } from "../../domain/native/procedureInfo.js"; +import { functionCfgDossier } from "../../../tests/fixtures/functionCfgDossier.js"; import { nativeMatchingNamedInventory as nativeMatchingInventory, nativeMatchingInventory as unqualifiedInventory, @@ -188,6 +189,68 @@ it.each(["literals-only", "omissions-only", "paired", "unsupported"])( }, ); +it.each([ + { entryOffset: 0n, candidates: 1, connected: true }, + { entryOffset: 0x10n, candidates: 1, connected: false }, + { entryOffset: 1n, candidates: 0, connected: false }, +])( + "binds structural candidates to the observed CFG entry: $entryOffset", + async ({ entryOffset, candidates, connected }) => { + const profile = createAnalysisProfile(nativeMatchingProvider, { + fixture: "rooted-structural-candidates", + }); + const observation = (side: "1" | "2", offset: bigint, name: string) => { + const value = functionCfgDossier( + side === "1" ? 0x1000n : 0x2000n, + offset, + ); + value.procedure.name = name; + value.referenced_strings = [ + { + address: "0x9000", + source_address: value.procedure.address, + value: "informative marker", + }, + ]; + return createEvidence( + nativeMatchingTarget(side), + nativeMatchingProvider, + { + operation: "analyze_function", + parameters: { procedure: value.procedure.address }, + result: value, + analysisProfile: profile, + relationshipCoverage: { status: "complete" }, + }, + ); + }; + const left = observation("1", 0n, "old_behavior"); + const right = observation("2", entryOffset, "new_behavior"); + const rightAddress = `0x${(0x2000n + entryOffset).toString(16)}`; + const inventory = (side: "1" | "2", address: string, value: string) => + createEvidence(nativeMatchingTarget(side), nativeMatchingProvider, { + operation: "list_procedures", + parameters: {}, + result: [{ address, value }], + analysisProfile: profile, + }); + const { report } = await compare({ + left: inventory("1", "0x1000", "old_behavior"), + right: inventory("2", rightAddress, "new_behavior"), + left_observations: [left], + right_observations: [right], + }); + expect(report.source_coverage.left_structural_candidates).toBe(1); + expect(report.source_coverage.right_structural_candidates).toBe(candidates); + expect(report.summary).toEqual({ + matched: 0, + only_left: connected ? 0 : 1, + only_right: connected ? 0 : 1, + unresolved: connected ? 1 : 0, + }); + }, +); + it.each(["", "ram:"])( "keeps informative %s CFG/call/string fingerprints as unresolved candidates and refuses incomplete structural observations", async (space) => { diff --git a/src/application/native/NativeFunctionMatchingService.ts b/src/application/native/NativeFunctionMatchingService.ts index 88a93292750..2ed325f8371 100644 --- a/src/application/native/NativeFunctionMatchingService.ts +++ b/src/application/native/NativeFunctionMatchingService.ts @@ -201,7 +201,7 @@ const matchWithAdmission = async ( right_evidence_id: right.evidence_id, left_observation_ids: leftObservations.map((x) => x.evidence_id), right_observation_ids: rightObservations.map((x) => x.evidence_id), - algorithm: "exact-symbol-body-bytes-and-structural-candidates-v1", + algorithm: "exact-symbol-body-bytes-and-structural-candidates-v2", }, result: report, limitations, diff --git a/src/domain/comparisonEvidenceIdentity.ts b/src/domain/comparisonEvidenceIdentity.ts index d304701e1ce..2dd4f9cd83e 100644 --- a/src/domain/comparisonEvidenceIdentity.ts +++ b/src/domain/comparisonEvidenceIdentity.ts @@ -22,7 +22,7 @@ export const FUNCTION_COMPARISON_PROVIDER = { export const FUNCTION_COMPARISON_PROFILE = createAnalysisProfile( FUNCTION_COMPARISON_PROVIDER, - { workflow_revision: 2 }, + { workflow_revision: 3 }, ); const COMPARISON_EVIDENCE_IDENTITIES = { diff --git a/src/domain/functionComparison.test.ts b/src/domain/functionComparison.test.ts index c7e6a26b4d0..06879e8ab63 100644 --- a/src/domain/functionComparison.test.ts +++ b/src/domain/functionComparison.test.ts @@ -16,6 +16,7 @@ import { canonicalJson } from "./comparisonSemantics.js"; import { digestCanonicalValue } from "./canonicalDigest.js"; import { compareUnicodeCodePoints } from "./unicodeCodePointOrder.js"; import { jsonValueSchema } from "./jsonValue.js"; +import { functionCfgDossier } from "../../tests/fixtures/functionCfgDossier.js"; import { compareFunctions } from "./functionComparison.js"; import type { RelationshipCoverage } from "./relationshipCoverage.js"; @@ -738,6 +739,61 @@ describe("function comparison ordering controls", () => { }); }); +it.each([ + { entryOffset: 0n, status: "unchanged" }, + { entryOffset: 0x10n, status: "changed" }, +])( + "retains the CFG entry after relocation: $status", + ({ entryOffset, status }) => { + const left = observe("a", functionCfgDossier()); + const rightValue = functionCfgDossier(0x2000n, entryOffset); + rightValue.procedure.address = rightValue.procedure.address.replace( + "0x", + "0X00", + ); + rightValue.basic_blocks.reverse(); + const right = observe("b", rightValue); + const result = compareFunctions( + functionSnapshotFixture(left), + functionSnapshotFixture(right), + ); + expect(result.status).toBe(status); + expect( + result.dimensions.find(({ dimension }) => dimension === "cfg"), + ).toMatchObject({ status, left_count: 3, right_count: 3 }); + expect( + result.dimensions + .filter(({ dimension }) => dimension !== "cfg") + .every(({ status: value }) => value === "unchanged"), + ).toBe(true); + }, +); + +it.each(["0x1001", "0x1030", "ram:0x1000", "not-an-address"])( + "keeps CFG entry coordinates outside known block starts unknown: %s", + (entry) => { + const value = functionCfgDossier(); + value.procedure.address = entry; + const source = functionSnapshotFixture(observe("a", value)); + expect( + compareFunctions(source, source).dimensions.find( + ({ dimension }) => dimension === "cfg", + ), + ).toMatchObject({ status: "unknown", left_count: 3, right_count: 3 }); + }, +); + +it("keeps a declared but empty CFG without an observed entry block unknown", () => { + const value = functionCfgDossier(); + value.basic_blocks = []; + const source = functionSnapshotFixture(observe("a", value)); + expect( + compareFunctions(source, source).dimensions.find( + ({ dimension }) => dimension === "cfg", + ), + ).toMatchObject({ status: "unknown", left_count: 0, right_count: 0 }); +}); + describe("function comparison CFG address normalization", () => { it.each([ { start: "ram:0x1000", end: "rom:0x1004", successors: [] }, diff --git a/src/domain/functionComparisonDimensions.ts b/src/domain/functionComparisonDimensions.ts index 0af8905342c..2b0b6a156cd 100644 --- a/src/domain/functionComparisonDimensions.ts +++ b/src/domain/functionComparisonDimensions.ts @@ -658,8 +658,8 @@ const compareCfg = ( ): FunctionDimension => { const leftBlocks = left.dossier.basic_blocks; const rightBlocks = right.dossier.basic_blocks; - const leftGraph = normalizeCfg(leftBlocks); - const rightGraph = normalizeCfg(rightBlocks); + const leftGraph = normalizeCfg(leftBlocks, left.dossier.procedure.address); + const rightGraph = normalizeCfg(rightBlocks, right.dossier.procedure.address); if (leftGraph === null || rightGraph === null) return unresolvedDimension({ dimension: "cfg", @@ -667,7 +667,7 @@ const compareCfg = ( leftCount: leftBlocks.length, rightCount: rightBlocks.length, limitations: [ - "CFG addresses could not be normalized to local block indices.", + "CFG addresses and function entry could not be normalized to local block indices.", ], }); return compareValues("cfg", leftGraph, rightGraph, context); diff --git a/src/domain/functionComparisonNormalization.ts b/src/domain/functionComparisonNormalization.ts index 8860563235c..da72ecf5ddd 100644 --- a/src/domain/functionComparisonNormalization.ts +++ b/src/domain/functionComparisonNormalization.ts @@ -87,7 +87,10 @@ export const functionMatch = ( export const normalizeCfg = ( blocks: FunctionSnapshot["dossier"]["basic_blocks"], + entryAddress: string, ): readonly unknown[] | null => { + const entry = parseAddress(entryAddress); + if (entry === null) return null; const parsed: { block: (typeof blocks)[number]; start: bigint; @@ -114,6 +117,7 @@ export const normalizeCfg = ( if (new Set(ordered.map(({ start }) => start)).size !== ordered.length) return null; const indices = new Map(ordered.map(({ start }, index) => [start, index])); + if (entry.space !== space || !indices.has(entry.offset)) return null; const graph = []; for (const { block, start, end } of ordered) { const successors: number[] = []; @@ -125,6 +129,7 @@ export const normalizeCfg = ( successors.push(index); } graph.push({ + entry: start === entry.offset, size: String(end - start), successors: successors.sort((left, right) => left - right), }); diff --git a/src/domain/native/functionStructuralCandidate.ts b/src/domain/native/functionStructuralCandidate.ts index 8123f5009c9..a2734502479 100644 --- a/src/domain/native/functionStructuralCandidate.ts +++ b/src/domain/native/functionStructuralCandidate.ts @@ -24,10 +24,9 @@ export const functionStructuralCandidate = ( evidence.analysis_profile === null ) return null; - const cfg = normalizeCfg(dossier.basic_blocks); + const cfg = normalizeCfg(dossier.basic_blocks, dossier.procedure.address); if ( cfg === null || - cfg.length === 0 || dossier.callees.some( (callee) => !hasStableNativeSymbol(callee.name, callee.symbol), ) @@ -43,7 +42,7 @@ export const functionStructuralCandidate = ( // Empty leaf functions otherwise produce huge uninformative CFG-only buckets. if (calls.length === 0 && strings.length === 0) return null; return digestCanonicalValue({ - algorithm: "observed-cfg-calls-strings-v1", + algorithm: "observed-cfg-calls-strings-v2", profile: evidence.analysis_profile.digest, architecture, cfg, diff --git a/tests/boundary/mcp/functionComparisonMcp.test.ts b/tests/boundary/mcp/functionComparisonMcp.test.ts index e695c5e9706..109bacf1e89 100644 --- a/tests/boundary/mcp/functionComparisonMcp.test.ts +++ b/tests/boundary/mcp/functionComparisonMcp.test.ts @@ -19,6 +19,75 @@ import { createEvidence, parseEvidence } from "../../../src/domain/evidence.js"; import { observed } from "../../fixtures/analysisExecution.js"; import { reconstructionVerificationResultSchema } from "../../../src/domain/reconstructionVerificationSchemas.js"; import { functionDossierSchema } from "../../../src/domain/native/functionDossier.js"; +import { functionCfgDossier } from "../../fixtures/functionCfgDossier.js"; + +it.each([ + { entryOffset: 0n, status: "unchanged" }, + { entryOffset: 0x10n, status: "changed" }, + { entryOffset: 1n, status: "unknown" }, +])( + "compares retained CFG entry blocks through MCP: $status", + async ({ entryOffset, status }) => { + const session = createTestBinarySession(() => { + throw new Error("Retained CFG comparison must not launch a provider"); + }); + const { client } = await createApplicationMcpHarness({ session }); + const source = (side: "1" | "2", offset: bigint) => { + const value = functionCfgDossier( + side === "1" ? 0x1000n : 0x2000n, + offset, + ); + return createEvidence( + { + path: `/fixture/cfg-${side}.elf`, + sha256: side.repeat(64), + format: "elf", + }, + FUNCTION_COMPARISON_EXAMPLE.left.provider, + { + operation: "analyze_function", + parameters: { procedure: value.procedure.address }, + result: value, + confidence: "derived", + relationshipCoverage: { status: "complete" }, + }, + ); + }; + const left = source("1", 0n); + const right = source("2", entryOffset); + const response = await client.callTool({ + name: "compare_functions", + arguments: { left, right }, + }); + expect( + response.isError, + JSON.stringify(response.structuredContent), + ).not.toBe(true); + const comparison = parseEvidence(response.structuredContent); + expect(comparison.normalized_result).toMatchObject({ + status, + dimensions: expect.arrayContaining([ + expect.objectContaining({ + dimension: "cfg", + status, + left_count: 3, + right_count: 3, + }), + ]), + }); + expect(comparison.evidence_links).toEqual( + expect.arrayContaining([left.evidence_id, right.evidence_id]), + ); + for (const original of [left, right]) + expect( + session + .exportEvidenceBundle() + .records.find( + ({ evidence_id }) => evidence_id === original.evidence_id, + ), + ).toEqual(original); + }, +); it.each([ { leftSpace: "ram", rightSpace: "ram" }, diff --git a/tests/fixtures/functionCfgDossier.ts b/tests/fixtures/functionCfgDossier.ts new file mode 100644 index 00000000000..2900d999ce3 --- /dev/null +++ b/tests/fixtures/functionCfgDossier.ts @@ -0,0 +1,22 @@ +import { FUNCTION_COMPARISON_EXAMPLE } from "../../src/contracts/functionComparisonExample.js"; +import { functionDossierSchema } from "../../src/domain/native/functionDossier.js"; + +/** Synthetic connected CFG whose two possible entry blocks have different degrees. */ +export const functionCfgDossier = (base = 0x1000n, entryOffset = 0n) => { + const address = (offset: bigint) => `0x${(base + offset).toString(16)}`; + const value = functionDossierSchema.parse( + FUNCTION_COMPARISON_EXAMPLE.left.normalized_result, + ); + value.procedure.address = address(entryOffset); + value.basic_blocks = [ + { start: address(0n), end: address(1n), successors: [address(0x10n)] }, + { + start: address(0x10n), + end: address(0x12n), + successors: [address(0n), address(0x20n)], + }, + { start: address(0x20n), end: address(0x23n), successors: [] }, + ]; + value.unresolved_calls = []; + return value; +};