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 nominal signatures across metadata builds (#3059)
Jeremy Levartovskyeab789aed74a
diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.mdindex 27b7c7e54..def21a291 100644--- a/docs/managed-code-analysis.md+++ b/docs/managed-code-analysis.md@@ -244,8 +244,8 @@ Names and semantic labels do not establish durable member identity. Comparisonpreserves observed differences, structural inferences, and unknowns separately.Cross-version matching first pairs members of the same declared type and name:-methods by exact CIL/signature identity, then by raw signature, then by-structural body shape; fields by raw signature. Exact CIL/signature identity+methods by exact CIL/signature identity, then by signature, then by+structural body shape; fields by signature. Exact CIL/signature identityrequires equal raw CIL digests and decoded fingerprints. Equal decodedfingerprints alone cannot establish an exact match: they omit switch targetsand collapse distinct NaN encodings. Only then may a remap pair a@@ -258,18 +258,50 @@ type, so it pairs by name only when no other member shares its exactCIL/signature key, never by structural shape alone, and any remap group itjoins stays ambiguous. The exact-signature key uses names only as part of thatfull tuple; names alone never select a pair. Duplicate tuples remain ambiguous-rather than being paired by token order. The raw signature is exact whether or+rather than being paired by token order. Every round compares signatures by+`resolved_sha256`: the raw signature with each TypeDef or TypeRef operand+replaced by a digest of that type's namespace and name, hashed as separate+values so `A` + `B.C` differs from `A.B` + `C`, after its enclosing types for a+nested type (`Outer/Inner`). The defining assembly is not part of the name:+a TypeDef and a TypeRef with the same namespace and name compare as the+same nominal name, and a TypeRef's ResolutionScope assembly is ignored, so a type+forwarded from one assembly to another still pairs. Two different types with+the same full name in different assemblies therefore have equal name digests.+Comparison reports this scope limitation inline; it does not establish CLR+type identity or runtime binding equivalence.+Nesting deeper than 64 levels is not named, and such a signature compares by+its raw digest. Comparison keys keep resolved and raw digests apart, so a raw+digest never pairs with an equal resolved one.+Raw signature bytes name types by metadata row, and rows are build-local, so+the same signature usually has different raw bytes in two builds. A signature+that names no types resolves to its raw digest. When an operand cannot be+resolved, such as a TypeSpec, or when REA could not parse the signature, the+raw digest stands in. Missing or unreadable TypeDef and TypeRef operands are+reported as coverage issues. Invalid NestedClass rows retain their failure+reasons and withhold TypeDef signature identities; type names and nesting are+parsed once by their shared owner. Each current inspection records+`signature_resolution: "type-names-v1"`, even when none of its operands can be+resolved. Historical Evidence defaults this attestation to `null`. When either+observation predates resolution, both sides compare raw digests, which pair only where type rows agree,+and the comparison reports that limitation. The signature is exact whether ornot REA decoded it, so undecoded signatures pair by that tuple too, but theynever enter structural rounds. An unmatched member is therefore reported as`unknown`, not added or removed, when its own signature was not decoded or whenthe other side has an unpaired member, one-sided or ambiguous, with the same-declared type and name whose signature was not decoded.+declared type and name whose signature was not decoded. When both observations+attest type-name resolution, a decoded signature that still compares by its raw+digest is treated the same way: an unmatched member with one, or beside an+unpaired same-named member with one, is `unknown`, because its raw bytes name+types by build-local row. A matched unresolved signature also remains unknown+unless another observed dimension establishes a change; identical row bytes+can reference different TypeSpec contents. Its resolution limitation is retained+even when another dimension changes.For a matched method, an unavailable or partial body makes body-shape facetsunknown while preserving observed signature differences. For complete bodies,a difference in either the raw CIL digest or the decoded fingerprint is reportedin the `cil` dimension, including reordered switch targets with equal decoded-fingerprints. Structural identity compares normalized signatures, the limited+fingerprints. Structural identity compares resolved signatures, the limiteddecoded-CIL tuple fingerprint,constants, and bounded shape context. It reports all candidates at the winningscore and remains ambiguous when the evidence does not distinguish them. Thediff --git a/src/contracts/managed/managedWorkflowExamples.ts b/src/contracts/managed/managedWorkflowExamples.tsindex 6e5d836ec..96f1c7267 100644--- a/src/contracts/managed/managedWorkflowExamples.ts+++ b/src/contracts/managed/managedWorkflowExamples.ts@@ -21,6 +21,7 @@ const emptyManagedMembers = (sha256: string,mvid: string,): ManagedMemberInspection => ({+ signature_resolution: null,artifact: {path: `/examples/${sha256.slice(0, 8)}.dll`,sha256,@@ -88,6 +89,7 @@ const runtimeMembers = (): ManagedMemberInspection => {signature: {raw_length: 3,raw_sha256: "3".repeat(64),+ resolved_sha256: "3".repeat(64),kind: "method",parse_status: "decoded",calling_convention: "default",diff --git a/src/contracts/managed/managedWorkflowToolContracts.ts b/src/contracts/managed/managedWorkflowToolContracts.tsindex a668e4a00..3fcdbae93 100644--- a/src/contracts/managed/managedWorkflowToolContracts.ts+++ b/src/contracts/managed/managedWorkflowToolContracts.ts@@ -98,7 +98,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 raw 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. 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. 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: compareManagedMembersReferenceInputSchema,outputSchema: comparisonOutputSchema,diff --git a/src/domain/analysisView/managedMemberView.ts b/src/domain/analysisView/managedMemberView.tsindex de82c9880..75eb14a0f 100644--- a/src/domain/analysisView/managedMemberView.ts+++ b/src/domain/analysisView/managedMemberView.ts@@ -64,6 +64,7 @@ const nullableCount = z.number().int().nonnegative().nullable();/** Keep identity, selection and coverage; member collections remain retained. */export const managedMemberSummarySchema = z.strictObject({+ signature_resolution: member.signature_resolution,artifact: member.artifact,module: member.module,metadata: member.metadata,@@ -90,6 +91,7 @@ export const managedMemberSummarySchema = z.strictObject({});export const managedMembersViewContextSchema = z.strictObject({+ signature_resolution: member.signature_resolution,identity_scope: member.identity_scope,selection: member.selection.unwrap(),source_metadata_status: member.metadata.shape.status,@@ -269,6 +271,7 @@ export const projectManagedMemberView = (view,page,...shared,+ signature_resolution: report.signature_resolution,identity_scope: report.identity_scope,selection: report.selection,source_metadata_status: report.metadata.status,diff --git a/src/domain/managed/managedArtifact.ts b/src/domain/managed/managedArtifact.tsindex f41173ba6..d41f01026 100644--- a/src/domain/managed/managedArtifact.ts+++ b/src/domain/managed/managedArtifact.ts@@ -79,6 +79,13 @@ const customAttributeSchema = z.object({const managedSignatureSchema = z.object({raw_length: z.number().int().min(0),raw_sha256: digestSchema,+ // Evidence recorded before this field existed reads back as null.+ resolved_sha256: digestSchema+ .nullable()+ .default(null)+ .describe(+ "SHA-256 of the raw signature with each TypeDef or TypeRef operand replaced by that type's namespace-qualified name; equals raw_sha256 when the signature names no types. Unlike raw_sha256 it does not depend on build-local metadata rows. Null when the signature could not be decoded or names a type REA could not resolve, such as a TypeSpec.",+ ),kind: z.enum(["method", "field", "unknown"]),parse_status: z.enum(["decoded", "partial", "unsupported", "malformed"]),calling_convention: z.string().nullable(),@@ -438,6 +445,13 @@ export const managedArtifactInspectionSchema = z.object({/** Provider-neutral, execution-free metadata/signature/IL member inspection. */export const managedMemberInspectionSchema = z.object({+ signature_resolution: z+ .literal("type-names-v1")+ .nullable()+ .default(null)+ .describe(+ "Signature type-name resolution was examined, including unresolved operands; null means historical Evidence without this attestation.",+ ),artifact: z.object({path: z.string().min(1),sha256: digestSchema,diff --git a/src/domain/managed/managedMemberComparison.ts b/src/domain/managed/managedMemberComparison.tsindex 77e382dc7..4f58590a7 100644--- a/src/domain/managed/managedMemberComparison.ts+++ b/src/domain/managed/managedMemberComparison.ts@@ -18,6 +18,7 @@ import {buildMethodItems,} from "./managedMemberComparisonItems.js";import { keyMembers, sha256 } from "./managedMemberComparisonMatch.js";+import { hasSignatureResolution } from "./managedMemberSignatureIdentity.js";import { digestSchema } from "../digests.js";import { prefixedDigestSchema } from "../digests.js";@@ -231,6 +232,9 @@ export const compareManagedMembers = (rightComplete: right.result.metadata.status === "complete",leftSelection: selectedTypes(left.result),rightSelection: selectedTypes(right.result),+ signatureResolutionExamined:+ hasSignatureResolution(left.result) &&+ hasSignatureResolution(right.result),};const methodItems = buildMethodItems(methodMatches, itemContext);const fieldItems = buildFieldItems(fieldMatches, itemContext);diff --git a/src/domain/managed/managedMemberComparisonCoverage.ts b/src/domain/managed/managedMemberComparisonCoverage.tsindex fce7b25fb..cb8700474 100644--- a/src/domain/managed/managedMemberComparisonCoverage.ts+++ b/src/domain/managed/managedMemberComparisonCoverage.ts@@ -3,6 +3,7 @@ import type {ManagedMemberComparisonSide,} from "./managedMemberComparison.js";import type { ManagedMemberInspection } from "./managedArtifact.js";+import { hasSignatureResolution } from "./managedMemberSignatureIdentity.js";interface ComparisonCoverageInput {readonly left: ManagedMemberInspection;@@ -108,8 +109,27 @@ export const comparisonLimitations = (const limitations: string[] = ["Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.","Methods pair within one declared type and name by exact CIL/signature, then signature, then structural shape; only then may exact CIL/signature or structural shape alone remap across declared types or names, never taking a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Names alone are never a matching basis.",- "Fields pair by declared type, name, and signature, then remap by exact decoded signature alone under the same rule; an undecoded signature is compared only by its raw bytes, and an unmatched member with one stays unknown.",+ "Fields pair by declared type, name, and signature, then remap by exact decoded signature alone under the same rule; an undecoded signature is compared only for an exact signature match, and an unmatched member with one stays unknown.",];+ const namesTypes = (result: ManagedMemberInspection) =>+ result.methods.some(+ ({ signature }) =>+ signature.resolved_sha256 !== null &&+ signature.resolved_sha256 !== signature.raw_sha256,+ ) ||+ result.fields.some(+ ({ signature }) =>+ signature.resolved_sha256 !== null &&+ signature.resolved_sha256 !== signature.raw_sha256,+ );+ if (+ hasSignatureResolution(left) &&+ hasSignatureResolution(right) &&+ (namesTypes(left) || namesTypes(right))+ )+ limitations.push(+ "Signature type operands compare by namespace, name, and enclosing names only; defining assemblies and CLR type identity are not established by this comparison.",+ );if (left.coverage.state !== "complete" || right.coverage.state !== "complete")limitations.push("At least one managed member observation is partial.");if (!sameSelection(left, right))@@ -120,6 +140,10 @@ export const comparisonLimitations = (limitations.push(`Both observations cover only the selected declaring types (${left.selection.type_names.join(", ")}); member totals and statuses describe those types, not the whole assembly.`,);+ if (!hasSignatureResolution(left) || !hasSignatureResolution(right))+ limitations.push(+ "At least one managed member observation does not attest signature type-name resolution, so signatures compare by raw bytes, which name types by build-local metadata row.",+ );if (left.exported_types === null || right.exported_types === null)limitations.push("At least one managed member observation predates ExportedType inspection; its exported and forwarded types are unknown.",diff --git a/src/domain/managed/managedMemberComparisonItems.ts b/src/domain/managed/managedMemberComparisonItems.tsindex 61bfd7c18..ea252a46f 100644--- a/src/domain/managed/managedMemberComparisonItems.ts+++ b/src/domain/managed/managedMemberComparisonItems.ts@@ -8,6 +8,7 @@ import {identityOf,sha256,} from "./managedMemberComparisonMatch.js";+import { signatureIdentity } from "./managedMemberSignatureIdentity.js";type Method = ManagedMemberInspection["methods"][number];type Field = ManagedMemberInspection["fields"][number];@@ -30,6 +31,8 @@ interface ComparisonItemContext {/** Declaring types each side selected; null when it inspected every type. */readonly leftSelection: ReadonlySet<string> | null;readonly rightSelection: ReadonlySet<string> | null;+ /** Whether matching keyed signatures by resolved digests, not raw bytes. */+ readonly signatureResolutionExamined: boolean;}/** Whether an inventory observed every member of this member's declaring type. */@@ -42,10 +45,15 @@ const inventoryCovers = ((selection === null ||(member.declaring_type !== null && selection.has(member.declaring_type)));-/** Declared type and name of each unpaired member, per side, whose signature was not decoded. */+/**+ * Declared type and name of each unpaired member, per side, whose signature+ * was not decoded, or was decoded but not resolved while matching keyed+ * resolved signatures.+ */interface UndecodedOneSidedNames {- readonly left: ReadonlySet<string>;- readonly right: ReadonlySet<string>;+ readonly resolved: boolean;+ readonly undecoded: Readonly<Record<"left" | "right", ReadonlySet<string>>>;+ readonly unresolved: Readonly<Record<"left" | "right", ReadonlySet<string>>>;}const methodDimensions = (@@ -58,7 +66,7 @@ const methodDimensions = (const dimensions: MethodItem["dimensions"] = [];if (left.flags !== right.flags || left.impl_flags !== right.impl_flags)dimensions.push("metadata");- if (left.signature.raw_sha256 !== right.signature.raw_sha256)+ if (signatureIdentity(left.signature) !== signatureIdentity(right.signature))dimensions.push("signature");const leftBodyComplete =left.body.status === "present" && left.body.truncated_instructions === 0;@@ -146,7 +154,7 @@ const methodOnlyItem = (context.rightSelection,member.left,),- oppositeUndecodedNames: undecoded.right,+ unpaired: undecoded,opposite: "right",inventory: "method",});@@ -168,7 +176,7 @@ const methodOnlyItem = (context.leftSelection,member.right,),- oppositeUndecodedNames: undecoded.left,+ unpaired: undecoded,opposite: "left",inventory: "method",});@@ -190,13 +198,15 @@ const methodOnlyItem = (* decoded, so no shape round could seek a changed counterpart, or the other* inventory has an unpaired (one-sided or ambiguous) same-named member whose* signature was not decoded, which may be this member with a changed- * signature.+ * signature. A decoded signature that names a type REA could not name, while+ * the comparison otherwise keys resolved signatures, is compared by raw bytes+ * that name types by build-local row, so it is treated the same way.*/const absenceLimitations = (member: Method | Field,opposite: {readonly oppositeComplete: boolean;- readonly oppositeUndecodedNames: ReadonlySet<string>;+ readonly unpaired: UndecodedOneSidedNames;readonly opposite: "left" | "right";readonly inventory: "method" | "field";},@@ -209,17 +219,46 @@ const absenceLimitations = (...(member.signature.parse_status === "decoded"? []: [- `signature-not-decoded: The member's ${member.signature.parse_status} signature was compared only by exact declared type, name, and raw bytes, so a changed or renamed counterpart could not be sought.`,+ `signature-not-decoded: The member's ${member.signature.parse_status} signature was compared only by exact declared type, name, and signature bytes, so a changed or renamed counterpart could not be sought.`,]),...(member.signature.parse_status === "decoded" &&- opposite.oppositeUndecodedNames.size > 0 &&- opposite.oppositeUndecodedNames.has(identityOf(member))+ opposite.unpaired.undecoded[opposite.opposite].has(identityOf(member))? [`counterpart-signature-not-decoded: The ${opposite.opposite} ${opposite.inventory} inventory has an unpaired member with the same declared type and name whose signature was not decoded, so it may be this member with a changed signature.`,]: []),+ ...(unresolved(member, opposite.unpaired.resolved)+ ? [+ `signature-not-resolved: The member's signature names a type REA could not name, so it was compared by raw bytes, which name types by build-local metadata row; a counterpart whose referenced type moved rows could not be found.`,+ ]+ : []),+ ...(member.signature.parse_status === "decoded" &&+ !unresolved(member, opposite.unpaired.resolved) &&+ opposite.unpaired.unresolved[opposite.opposite].has(identityOf(member))+ ? [+ `counterpart-signature-not-resolved: The ${opposite.opposite} ${opposite.inventory} inventory has an unpaired member with the same declared type and name whose signature names a type REA could not name, so it may be this member.`,+ ]+ : []),];+/** A known signature form whose type operands still compare by raw bytes. */+const unresolved = (member: Method | Field, resolved: boolean): boolean =>+ resolved &&+ member.signature.kind !== "unknown" &&+ member.signature.resolved_sha256 === null;++/** Equal build-local bytes cannot establish equal unresolved type operands. */+const pairedSignatureLimitations = (+ left: Method | Field,+ right: Method | Field,+ examined: boolean,+): string[] =>+ unresolved(left, examined) || unresolved(right, examined)+ ? [+ "signature-not-resolved: At least one signature names a type REA could not resolve; equal build-local row bytes do not establish equivalent signature types.",+ ]+ : [];+/*** Declared names of unpaired members whose signature was not decoded: one-sided* members and candidates of ambiguous groups, which also remain unpaired.@@ -229,29 +268,47 @@ interface Unpaired {readonly identity: string;}-const undecodedOneSidedNames = (members: {- readonly leftOnly: readonly Unpaired[];- readonly rightOnly: readonly Unpaired[];- readonly ambiguous: readonly {- readonly left: readonly Unpaired[];- readonly right: readonly Unpaired[];- }[];-}): UndecodedOneSidedNames => {- const names = (side: readonly Unpaired[]) =>- new Set(- side- .filter(({ item }) => item.signature.parse_status !== "decoded")- .map(({ identity }) => identity),- );- return {- left: names([+const undecodedOneSidedNames = (+ members: {+ readonly leftOnly: readonly Unpaired[];+ readonly rightOnly: readonly Unpaired[];+ readonly ambiguous: readonly {+ readonly left: readonly Unpaired[];+ readonly right: readonly Unpaired[];+ }[];+ },+ resolved: boolean,+): UndecodedOneSidedNames => {+ const sides = {+ left: [...members.leftOnly,...members.ambiguous.flatMap(({ left }) => left),- ]),- right: names([+ ],+ right: [...members.rightOnly,...members.ambiguous.flatMap(({ right }) => right),- ]),+ ],+ };+ const names = (+ side: readonly Unpaired[],+ keep: (item: Method | Field) => boolean,+ ) =>+ new Set(+ side.filter(({ item }) => keep(item)).map(({ identity }) => identity),+ );+ const undecoded = (item: Method | Field) =>+ item.signature.parse_status !== "decoded";+ const notResolved = (item: Method | Field) => unresolved(item, resolved);+ return {+ resolved,+ undecoded: {+ left: names(sides.left, undecoded),+ right: names(sides.right, undecoded),+ },+ unresolved: {+ left: names(sides.left, notResolved),+ right: names(sides.right, notResolved),+ },};};@@ -267,7 +324,7 @@ const fieldOnlyItem = (context.rightSelection,member.left,),- oppositeUndecodedNames: undecoded.right,+ unpaired: undecoded,opposite: "right",inventory: "field",});@@ -288,7 +345,7 @@ const fieldOnlyItem = (context.leftSelection,member.right,),- oppositeUndecodedNames: undecoded.left,+ unpaired: undecoded,opposite: "left",inventory: "field",});@@ -305,14 +362,14 @@ const fieldOnlyItem = (/*** Name only evidence shared by the whole group. Exact-signature ambiguities- * include both declared-identity collisions and unresolved raw-signature choices.+ * include both declared-identity collisions and unresolved signature choices.*/const ambiguityLimitation = (members: "methods" | "fields",basis: MethodItem["match"]["basis"],): string =>basis === "exact-signature"- ? `Multiple managed ${members} share the same raw signature; REA did not guess declared ownership or a token remap.`+ ? `Multiple managed ${members} share the same signature; REA did not guess declared ownership or a token remap.`: basis === "exact-il-signature"? "Multiple managed methods share the same CIL and signature; REA did not guess a token remap.": members === "methods"@@ -325,6 +382,11 @@ export const buildMethodItems = (): MethodItem[] => {const items: MethodItem[] = [];for (const pair of matches.pairs) {+ const signatureLimitations = pairedSignatureLimitations(+ pair.left.item,+ pair.right.item,+ context.signatureResolutionExamined,+ );const { dimensions: observedDimensions, bodyUnknown } = methodDimensions(pair.left.item,pair.right.item,@@ -341,7 +403,7 @@ export const buildMethodItems = (})}`,status: observedChange? "changed"- : bodyUnknown+ : bodyUnknown || signatureLimitations.length > 0? "unknown": "unchanged",left: methodIdentity(pair.left.item),@@ -355,11 +417,14 @@ export const buildMethodItems = (},dimensions,evidence_links: [context.leftEvidenceId, context.rightEvidenceId],- limitations: bodyUnknown- ? [- "Method body facets are unknown because at least one side has unavailable or partial body data.",- ]- : [],+ limitations: [+ ...signatureLimitations,+ ...(bodyUnknown+ ? [+ "Method body facets are unknown because at least one side has unavailable or partial body data.",+ ]+ : []),+ ],});}for (const ambiguous of matches.ambiguous) {@@ -384,7 +449,10 @@ export const buildMethodItems = (limitations: [ambiguityLimitation("methods", ambiguous.basis)],});}- const undecoded = undecodedOneSidedNames(matches);+ const undecoded = undecodedOneSidedNames(+ matches,+ context.signatureResolutionExamined,+ );for (const item of matches.leftOnly)items.push(methodOnlyItem({ left: item.item }, context, undecoded));for (const item of matches.rightOnly)@@ -398,16 +466,25 @@ export const buildFieldItems = (): FieldItem[] => {const items: FieldItem[] = [];for (const pair of matches.pairs) {+ const signatureLimitations = pairedSignatureLimitations(+ pair.left.item,+ pair.right.item,+ context.signatureResolutionExamined,+ );const changed =- pair.left.item.signature.raw_sha256 !==- pair.right.item.signature.raw_sha256 ||+ signatureIdentity(pair.left.item.signature) !==+ signatureIdentity(pair.right.item.signature) ||pair.left.item.flags !== pair.right.item.flags;items.push({item_id: `mmc_field_${sha256({left: pair.left.item.token,right: pair.right.item.token,})}`,- status: changed ? "changed" : "unchanged",+ status: changed+ ? "changed"+ : signatureLimitations.length > 0+ ? "unknown"+ : "unchanged",left: fieldIdentity(pair.left.item),right: fieldIdentity(pair.right.item),match: {@@ -418,7 +495,7 @@ export const buildFieldItems = (candidate_right_tokens: [],},evidence_links: [context.leftEvidenceId, context.rightEvidenceId],- limitations: [],+ limitations: signatureLimitations,});}for (const ambiguous of matches.ambiguous)@@ -440,7 +517,10 @@ export const buildFieldItems = (evidence_links: [context.leftEvidenceId, context.rightEvidenceId],limitations: [ambiguityLimitation("fields", ambiguous.basis)],});- const undecoded = undecodedOneSidedNames(matches);+ const undecoded = undecodedOneSidedNames(+ matches,+ context.signatureResolutionExamined,+ );for (const item of matches.leftOnly)items.push(fieldOnlyItem({ left: item.item }, context, undecoded));for (const item of matches.rightOnly)diff --git a/src/domain/managed/managedMemberComparisonMatch.ts b/src/domain/managed/managedMemberComparisonMatch.tsindex e18da9ef5..a9b203599 100644--- a/src/domain/managed/managedMemberComparisonMatch.ts+++ b/src/domain/managed/managedMemberComparisonMatch.ts@@ -11,6 +11,10 @@ import type {ManagedMemberComparisonResult,ManagedMemberComparisonSide,} from "./managedMemberComparison.js";+import {+ comparableSides,+ signatureIdentity,+} from "./managedMemberSignatureIdentity.js";import type { JsonValue } from "../jsonValue.js";export const sha256 = (value: JsonValue): string => {@@ -22,6 +26,7 @@ export const sha256 = (value: JsonValue): string => {type Method = ManagedMemberInspection["methods"][number];type Field = ManagedMemberInspection["fields"][number];+type MatchBasis =ManagedMemberComparisonResult["methods"][number]["match"]["basis"];type ConcreteMatchBasis = Exclude<MatchBasis, "none">;@@ -32,7 +37,8 @@ interface Keyed<Item> {readonly identity: string;readonly exactKey: string | null;readonly signatureKey: string | null;- readonly rawSignatureKey: string;+ /** The name-free exact signature, resolved where both sides resolve it. */+ readonly signatureId: string;readonly structuralKey: string | null;}@@ -52,35 +58,32 @@ interface Ambiguous<Item> {const keyMethod = (item: Method): Keyed<Method> => ({item,identity: identityOf(item),- rawSignatureKey: item.signature.raw_sha256,+ signatureId: signatureIdentity(item.signature),exactKey:item.body.status === "present" &&item.body.il_sha256 !== null &&item.body.normalized_il_sha256 !== null? sha256(["method-exact",- item.signature.raw_sha256,+ signatureIdentity(item.signature),item.body.il_sha256,item.body.normalized_il_sha256,]): null,- // The raw blob is the exact signature; decoding only feeds shape keys.+ // The blob, with type operands named, is the exact signature; decoding+ // only gates the shape keys.signatureKey: sha256(["method-signature",item.declaring_type,item.name,- item.signature.raw_sha256,+ signatureIdentity(item.signature),]),structuralKey:item.signature.parse_status === "decoded" && item.body.status === "present"? sha256(["method-structural",- item.signature.kind,- item.signature.calling_convention,- item.signature.generic_parameter_count,- item.signature.parameter_count,- item.signature.return_type,- item.signature.parameter_types,+ // Decoded type strings carry build-local rows; the identity names them.+ signatureIdentity(item.signature),item.body.status,item.body.header_format,item.body.il_size,@@ -106,18 +109,18 @@ const keyMethod = (item: Method): Keyed<Method> => ({const keyField = (item: Field): Keyed<Field> => ({item,identity: identityOf(item),- rawSignatureKey: item.signature.raw_sha256,+ signatureId: signatureIdentity(item.signature),exactKey:item.signature.parse_status === "decoded"- ? sha256(["field-exact", item.signature.raw_sha256])+ ? sha256(["field-exact", signatureIdentity(item.signature)]): null,// Only an undecoded field reaches this round: a decoded field with the- // same raw signature already met its counterpart in the exact round.+ // same signature already met its counterpart in the exact round.signatureKey: sha256(["field-signature",item.declaring_type,item.name,- item.signature.raw_sha256,+ signatureIdentity(item.signature),]),structuralKey: sha256(["field-structural",@@ -142,7 +145,7 @@ const matchMethods = ({basis: "exact-signature",key: ({ signatureKey }) => signatureKey,- competitionKey: ({ rawSignatureKey }) => rawSignatureKey,+ competitionKey: ({ signatureId }) => signatureId,},{basis: "structural-method-shape",@@ -181,7 +184,7 @@ const matchFields = ({basis: "exact-signature",key: ({ signatureKey }) => signatureKey,- competitionKey: ({ rawSignatureKey }) => rawSignatureKey,+ competitionKey: ({ signatureId }) => signatureId,},{basis: "field-signature",@@ -326,7 +329,7 @@ const matchByKeys = <Item extends Declared>({right.filter((item) => !usedRight.has(item)),ownerlessContested([unpairedOf(left, pairedLeft), unpairedOf(right, pairedRight)],- (member) => member.rawSignatureKey,+ (member) => member.signatureId,),)) {for (const item of group.left) usedLeft.add(item);@@ -348,7 +351,7 @@ const unresolvedSignatureAmbiguities = <Item extends Declared>(contested: ReadonlySet<string>,): Ambiguous<Item>[] => {const key = (member: Keyed<Item>): string =>- competitionIdentityKey(member, member.rawSignatureKey) ?? "";+ competitionIdentityKey(member, member.signatureId) ?? "";const leftGroups = groupBy(left, key);const rightGroups = groupBy(right, key);const groups: Ambiguous<Item>[] = [];@@ -526,12 +529,13 @@ const matchObserved = <Item extends Declared>(};export const keyMembers = (- left: ManagedMemberComparisonSide,- right: ManagedMemberComparisonSide,+ observedLeft: ManagedMemberComparisonSide,+ observedRight: ManagedMemberComparisonSide,): {readonly methodMatches: ReturnType<typeof matchMethods>;readonly fieldMatches: ReturnType<typeof matchFields>;} => {+ const [left, right] = comparableSides(observedLeft, observedRight);const sides = { inLeft: observedBy(left), inRight: observedBy(right) };return {methodMatches: matchObserved(diff --git a/src/domain/managed/managedMemberSignatureIdentity.test.ts b/src/domain/managed/managedMemberSignatureIdentity.test.tsnew file mode 100644index 000000000..a07c2c1c1--- /dev/null+++ b/src/domain/managed/managedMemberSignatureIdentity.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from "vitest";+import { signatureIdentity } from "./managedMemberSignatureIdentity.js";++type Signature = Parameters<typeof signatureIdentity>[0];++const digest = "ab".repeat(32);+const signature = (raw: string, resolved: string | null) =>+ ({ raw_sha256: raw, resolved_sha256: resolved }) as Signature;++describe("managed signature identity", () => {+ it("keeps a raw digest apart from an equal resolved digest", () => {+ // An undecodable blob can hold another signature's resolved preimage, so+ // its raw digest can equal that signature's resolved digest.+ expect(signatureIdentity(signature(digest, null))).not.toBe(+ signatureIdentity(signature("cd".repeat(32), digest)),+ );+ });++ it("matches resolved digests and raw digests among themselves", () => {+ expect(signatureIdentity(signature("01".repeat(32), digest))).toBe(+ signatureIdentity(signature("02".repeat(32), digest)),+ );+ expect(signatureIdentity(signature(digest, null))).toBe(+ signatureIdentity(signature(digest, null)),+ );+ });+});diff --git a/src/domain/managed/managedMemberSignatureIdentity.ts b/src/domain/managed/managedMemberSignatureIdentity.tsnew file mode 100644index 000000000..e683aa7c9--- /dev/null+++ b/src/domain/managed/managedMemberSignatureIdentity.ts@@ -0,0 +1,64 @@+import type { ManagedMemberInspection } from "./managedArtifact.js";+import type { ManagedMemberComparisonSide } from "./managedMemberComparison.js";++type Method = ManagedMemberInspection["methods"][number];+type Field = ManagedMemberInspection["fields"][number];++/**+ * The exact signature across builds: raw bytes with type operands resolved to+ * names. Raw bytes name types by build-local rows, so they stand in only when+ * REA could not resolve the operands, or for Evidence recorded before it did.+ * The kind is part of the key: an undecodable blob can hold another+ * signature's resolved preimage, so its raw digest can equal that resolved+ * digest without the two being the same signature.+ */+export const signatureIdentity = ({+ raw_sha256,+ resolved_sha256,+}: Method["signature"]): string =>+ resolved_sha256 === null+ ? `raw:${raw_sha256}`+ : `resolved:${resolved_sha256}`;++/**+ * The producer attests examination independently of whether it could resolve+ * any operands. A current inventory of only unresolved types is not legacy.+ */+export const hasSignatureResolution = (+ result: ManagedMemberInspection,+): boolean =>+ result.signature_resolution !== null ||+ (result.methods.length === 0 && result.fields.length === 0);++const withoutResolution = <Member extends Method | Field>(+ members: readonly Member[],+): Member[] =>+ members.map((member) => ({+ ...member,+ signature: { ...member.signature, resolved_sha256: null },+ }));++/**+ * Compare raw signatures on both sides when either observation predates+ * resolved digests; a resolved digest never equals a raw one for a signature+ * that names a type, so mixing them would lose pairs a raw comparison finds.+ */+export const comparableSides = (+ left: ManagedMemberComparisonSide,+ right: ManagedMemberComparisonSide,+): readonly [ManagedMemberComparisonSide, ManagedMemberComparisonSide] => {+ if (+ hasSignatureResolution(left.result) &&+ hasSignatureResolution(right.result)+ )+ return [left, right];+ const raw = (side: ManagedMemberComparisonSide) => ({+ ...side,+ result: {+ ...side.result,+ methods: withoutResolution(side.result.methods),+ fields: withoutResolution(side.result.fields),+ },+ });+ return [raw(left), raw(right)];+};diff --git a/src/dotnet/ManagedMemberInspector.test.ts b/src/dotnet/ManagedMemberInspector.test.tsindex 69fadc629..924679511 100644--- a/src/dotnet/ManagedMemberInspector.test.ts+++ b/src/dotnet/ManagedMemberInspector.test.ts@@ -1526,11 +1526,15 @@ it("decodes generic instantiation member signatures as complete coverage", () =>// shape, with TypeRef/TypeSpec coded tokens kept as encoded.const bytes = buildManagedPeFixture({methodSignature: Buffer.from([- 0x00, 0x01, 0x01, 0x15, 0x12, 0x71, 0x01, 0x0e,+ 0x00, 0x01, 0x01, 0x15, 0x12, 0x09, 0x01, 0x0e,]),fieldSignature: Buffer.from([- 0x06, 0x15, 0x11, 0x0a, 0x02, 0x13, 0x00, 0x1e, 0x01,+ 0x06, 0x15, 0x11, 0x0d, 0x02, 0x13, 0x00, 0x1e, 0x01,]),+ typeReferences: [+ { namespace: "System", name: "Func`1" },+ { namespace: "System", name: "ValueTuple`2" },+ ],});const result = inspectManagedMembersBytes(bytes,@@ -1540,12 +1544,12 @@ it("decodes generic instantiation member signatures as complete coverage", () =>expect(result.methods[0]?.signature).toMatchObject({parse_status: "decoded",return_type: "void",- parameter_types: ["class:113<string>"],+ parameter_types: ["class:9<string>"],issue: null,});expect(result.fields[0]?.signature).toMatchObject({parse_status: "decoded",- field_type: "valuetype:10<var:0,mvar:1>",+ field_type: "valuetype:13<var:0,mvar:1>",});expect(result.coverage).toMatchObject({ state: "complete", issues: [] });});diff --git a/src/dotnet/ManagedMemberInspector.ts b/src/dotnet/ManagedMemberInspector.tsindex ab074d146..9a70f0cd5 100644--- a/src/dotnet/ManagedMemberInspector.ts+++ b/src/dotnet/ManagedMemberInspector.ts@@ -29,7 +29,9 @@ import {type TypeRange,} from "./ManagedMemberInspectorCore.js";import { edgeTargets } from "./ManagedMethodSpecs.js";+import { signatureTypeNames } from "./ManagedSignatureTypeNames.js";import { typeNameLookup } from "./ManagedTypeNames.js";+import { managedTypeReferences } from "./ManagedTypeReferences.js";import { parseUserStrings } from "./ManagedUserStrings.js";import { readTypeMemberListFacts } from "./ManagedTypeMemberLists.js";import {@@ -72,6 +74,7 @@ const unavailable = (requires_mvid: null,},types: [],+ signature_resolution: "type-names-v1",exported_types: null,user_strings: null,fields: [],@@ -204,11 +207,22 @@ export const inspectManagedMembersBytes = (appendManagedParseIssues(issues, parsedTypes.issues);const exportedTypes = parseExportedTypes(bytes, layout);appendManagedParseIssues(issues, exportedTypes.issues);- const fields = parseFields(bytes, layout, ranges, memberLists, selected);+ const typeReferences = managedTypeReferences(bytes, layout, issues);+ const signatureTypeName = signatureTypeNames(+ layout,+ issues,+ parsedTypes,+ typeReferences,+ );+ const fields = parseFields(bytes, layout, ranges, memberLists, {+ signatureTypeName,+ selected,+ });const memberRefs = parseMemberRefs(bytes,layout,- typeNameLookup(bytes, layout, ranges, issues),+ typeNameLookup(bytes, layout, ranges, issues, typeReferences),+ signatureTypeName,);appendManagedParseIssues(issues, memberRefs.issues);const methods = parseMethods({@@ -216,6 +230,7 @@ export const inspectManagedMembersBytes = (layout,pe,ranges,+ signatureTypeName,memberLists,selected,methodOffset,@@ -275,6 +290,7 @@ export const inspectManagedMembersBytes = (selected === null? parsedTypes.types: parsedTypes.types.filter((type) => selected.has(type.token)),+ signature_resolution: "type-names-v1",exported_types: exportedTypes.exportedTypes,fields: fields.fields,methods: methods.methods,diff --git a/src/dotnet/ManagedMemberInspectorCore.ts b/src/dotnet/ManagedMemberInspectorCore.tsindex 858a6c2fb..eeb280c0a 100644--- a/src/dotnet/ManagedMemberInspectorCore.ts+++ b/src/dotnet/ManagedMemberInspectorCore.ts@@ -1,3 +1,5 @@+import { createHash } from "node:crypto";+import {managedFailure,ManagedReaderFailure,@@ -8,6 +10,10 @@ import type {ManagedParseIssue,} from "../domain/managed/managedArtifact.js";import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import {+ readManagedTypeNesting,+ type ManagedTypeNesting,+} from "./ManagedTypeNesting.js";import type {ManagedMetadataLayout,MetadataTableLayout,@@ -158,12 +164,14 @@ export const parseTypes = (): {readonly types: readonly ManagedType[];readonly issues: readonly ManagedParseIssue[];+ readonly nesting: ManagedTypeNesting;} => {const typeTable = layout.table(2);const fields = memberListTable(layout, 4);const methods = memberListTable(layout, 6);const items: ManagedType[] = [];const issues: ManagedParseIssue[] = [];+ const nesting = readManagedTypeNesting(bytes, layout, issues);for (let row = 1; row <= (typeTable?.rowCount ?? 0); row += 1) {readManagedValue(() => {const cursor = metadataRowCursor(bytes, layout, 2, row);@@ -234,7 +242,7 @@ export const parseTypes = (});}, issues);}- return { types: items, issues };+ return { types: items, issues, nesting };};export const readCompressed = (@@ -492,11 +500,26 @@ const readTypeOperand = (return token;};+/** A TypeDefOrRefOrSpec coded index embedded in a signature blob. */+interface TypeOperand {+ readonly offset: number;+ readonly next: number;+ readonly value: number;+}+const readTypeSignature = (blob: Buffer,offset: number,base: SignaturePosition,- layout?: ManagedMetadataLayout,+ {+ layout,+ operands,+ }: {+ /** Validate each type operand against these tables, as specs require. */+ readonly layout?: ManagedMetadataLayout;+ /** Collect each type operand, to resolve it by name. */+ readonly operands?: TypeOperand[];+ } = {},): { readonly value: string; readonly next: number } => {const stack: TypeContinuation[] = [];let cursor = offset;@@ -524,6 +547,7 @@ const readTypeSignature = (cursor += 1;} else if (kind === 0x1f || kind === 0x20) {const token = readTypeOperand(blob, cursor + 1, layout);+ operands?.push({ offset: cursor + 1, ...token });const modifier = `${kind === 0x1f ? "modreq" : "modopt"}:${String(token.value)}`;// A modifier frame on top was pushed by the directly preceding byte;// keep an adjacent run together and in source order.@@ -533,6 +557,7 @@ const readTypeSignature = (cursor = token.next;} else if (kind === 0x11 || kind === 0x12) {const token = readTypeOperand(blob, cursor + 1, layout);+ operands?.push({ offset: cursor + 1, ...token });value = `${kind === 0x11 ? "valuetype" : "class"}:${String(token.value)}`;cursor = token.next;} else if (kind === 0x1e || kind === 0x13) {@@ -553,6 +578,7 @@ const readTypeSignature = (cursor + 1,);const token = readTypeOperand(blob, cursor + 2, layout, [2, 1]);+ operands?.push({ offset: cursor + 2, ...token });const argumentCount = readCompressed(blob, token.next);if (argumentCount.value === 0)return malformedSignature(@@ -674,7 +700,7 @@ export const specSignature = (const types: string[] = [];// Each Type consumes at least one byte, so a false count fails on truncation.for (let index = 0; index < count; index += 1) {- const type = readTypeSignature(blob, cursor, "type", layout);+ const type = readTypeSignature(blob, cursor, "type", { layout });types.push(type.value);cursor = type.next;}@@ -700,13 +726,19 @@ export const specSignature = (}};-type DecodedSignature = Omit<ManagedSignature, "raw_length" | "raw_sha256">;+type DecodedSignature = Omit<+ ManagedSignature,+ "raw_length" | "raw_sha256" | "resolved_sha256"+>;/*** Decode a field or member method signature. A malformed or unsupported blob* decodes as kind `unknown` with its reason.*/-const decodeSignature = (blob: Buffer): DecodedSignature => {+const decodeSignature = (+ blob: Buffer,+ operands: TypeOperand[] = [],+): DecodedSignature => {try {if (blob.length === 0)throw managedFailure("invalid-blob", "signature", "empty signature", 0);@@ -714,7 +746,7 @@ const decodeSignature = (blob: Buffer): DecodedSignature => {// FieldSig (II.23.2.4) is exactly FIELD; a flagged FIELD header is not a// method header either, so it is malformed below.if (first === 0x06) {- const fieldType = readTypeSignature(blob, 1, "field");+ const fieldType = readTypeSignature(blob, 1, "field", { operands });return {kind: "field",parse_status: fieldType.next === blob.length ? "decoded" : "partial",@@ -729,11 +761,15 @@ const decodeSignature = (blob: Buffer): DecodedSignature => {};}const header = readMethodSignatureHeader(blob, 0, "member");- const returnType = readTypeSignature(blob, header.next, "return");+ const returnType = readTypeSignature(blob, header.next, "return", {+ operands,+ });let offset = returnType.next;const parameters: string[] = [];for (let index = 0; index < header.parameterCount; index += 1) {- const parameter = readTypeSignature(blob, offset, "parameter");+ const parameter = readTypeSignature(blob, offset, "parameter", {+ operands,+ });parameters.push(parameter.value);offset = parameter.next;}@@ -801,11 +837,58 @@ export const signatureGenericArity = (? (decoded.generic_parameter_count ?? 0): null;+/**+ * SHA-256 of the namespace-qualified name of a TypeDefOrRefOrSpec coded index,+ * or null when it has no name.+ */+export type SignatureTypeName = (codedIndex: number) => Buffer | null;++/**+ * Each type operand is replaced by 0xff, which never starts a compressed+ * coded index, then the 32-byte name digest; a blob without type operands+ * keeps its raw digest. So no decodable signature's resolved preimage is+ * another's, but an undecodable blob can hold one, and its raw digest then+ * equals that resolved digest. Comparison keys the two kinds apart.+ */+const OPERAND_MARKER = Buffer.from([0xff]);++/**+ * Digest the blob with each type operand replaced by its type's name digest,+ * so the value does not depend on build-local row numbers.+ */+const resolvedSha256 = (+ blob: Buffer,+ operands: readonly TypeOperand[],+ typeName: SignatureTypeName,+): string | null => {+ const hash = createHash("sha256");+ let copied = 0;+ for (const operand of operands) {+ const name = typeName(operand.value);+ if (name === null) return null;+ hash.update(blob.subarray(copied, operand.offset));+ hash.update(OPERAND_MARKER);+ hash.update(name);+ copied = operand.next;+ }+ hash.update(blob.subarray(copied));+ return hash.digest("hex");+};+export const signature = (blob: Buffer,rawSha256?: string,-): ManagedSignature => ({- raw_length: blob.length,- raw_sha256: rawSha256 ?? sha256Bytes(blob),- ...decodeSignature(blob),-});+ typeName: SignatureTypeName = () => null,+): ManagedSignature => {+ const operands: TypeOperand[] = [];+ const decoded = decodeSignature(blob, operands);+ return {+ raw_length: blob.length,+ raw_sha256: rawSha256 ?? sha256Bytes(blob),+ resolved_sha256:+ decoded.kind === "unknown"+ ? null+ : resolvedSha256(blob, operands, typeName),+ ...decoded,+ };+};diff --git a/src/dotnet/ManagedMemberRows.ts b/src/dotnet/ManagedMemberRows.tsindex 0eb03c542..1a5af8f0b 100644--- a/src/dotnet/ManagedMemberRows.ts+++ b/src/dotnet/ManagedMemberRows.ts@@ -17,6 +17,7 @@ import {type ManagedMemberRef,type ManagedMethod,type MemberCore,+ type SignatureTypeName,type TypeRange,} from "./ManagedMemberInspectorCore.js";import {@@ -49,7 +50,13 @@ export const parseFields = (layout: ManagedMetadataLayout,ranges: readonly TypeRange[],memberLists: TypeMemberListFacts,- selected: SelectedTypeTokens = null,+ {+ signatureTypeName,+ selected = null,+ }: {+ readonly signatureTypeName: SignatureTypeName;+ readonly selected?: SelectedTypeTokens;+ },): {readonly fields: readonly ManagedField[];readonly core: ReadonlyMap<string, MemberCore>;@@ -99,7 +106,7 @@ export const parseFields = (declaring_type: declared?.fullName ?? null,name,flags,- signature: budgetedSignature(sig, layout),+ signature: budgetedSignature(sig, layout, signatureTypeName),});}, issues);}@@ -181,6 +188,7 @@ export const parseMemberRefs = (bytes: Buffer,layout: ManagedMetadataLayout,typeName: (token: string | null) => string | null,+ signatureTypeName: SignatureTypeName,): {readonly refs: readonly ManagedMemberRef[];readonly core: ReadonlyMap<string, MemberCore>;@@ -232,7 +240,7 @@ export const parseMemberRefs = (layout.rowCounts,);const parentName = typeName(parentToken);- const decoded = budgetedSignature(sig, layout);+ const decoded = budgetedSignature(sig, layout, signatureTypeName);refs.push({token,row_offset: cursor.start,@@ -258,6 +266,7 @@ interface ParseMethodsInput {readonly layout: ManagedMetadataLayout;readonly pe: ManagedPeLayout;readonly ranges: readonly TypeRange[];+ readonly signatureTypeName: SignatureTypeName;readonly memberLists: TypeMemberListFacts;readonly selected?: SelectedTypeTokens;readonly methodOffset?: number;@@ -269,6 +278,7 @@ export const parseMethods = ({layout,pe,ranges,+ signatureTypeName,memberLists,selected = null,methodOffset = 0,@@ -337,7 +347,7 @@ export const parseMethods = ({layout.blob.size,);cursor.readIndex(layout.tableIndexSize(8));- const decoded = budgetedSignature(sig, layout);+ const decoded = budgetedSignature(sig, layout, signatureTypeName);core.set(token, {...member,genericArity: signatureGenericArity(decoded),@@ -479,12 +489,13 @@ const callerNameBytes = (method: ManagedMethod): number =>const budgetedSignature = (bytes: Buffer,layout: ManagedMetadataLayout,+ signatureTypeName: SignatureTypeName,): ReturnType<typeof signature> => {const budget = managedDecodeBudget(layout);budget.admitTransient(bytes.length * 256, layout.blob.offset);try {return admitManagedProjection(- signature(bytes, budget.digest(bytes, "sha256")),+ signature(bytes, budget.digest(bytes, "sha256"), signatureTypeName),budget,);} finally {diff --git a/src/dotnet/ManagedPe.fixture.ts b/src/dotnet/ManagedPe.fixture.tsindex 0d4cf4978..89347edbf 100644--- a/src/dotnet/ManagedPe.fixture.ts+++ b/src/dotnet/ManagedPe.fixture.ts@@ -53,6 +53,15 @@ interface ManagedPeFixtureOptions {readonly targetFramework?: string | null;readonly typeName?: string;readonly typeNamespace?: string;+ /** NestedClass rows as [nested, enclosing] TypeDef rows. */+ readonly nestedTypes?: readonly (readonly [number, number])[];+ /** TypeRef rows after the TargetFrameworkAttribute row, from row 2. */+ readonly typeReferences?: readonly {+ readonly namespace: string;+ readonly name: string;+ /** TypeRef row of the enclosing type, for a nested type. */+ readonly enclosingRow?: number;+ }[];/** Raw #US stream bytes; omitted means the metadata has no #US stream. */readonly userStringHeap?: Buffer;readonly virtualSectionSize?: number;@@ -590,6 +599,11 @@ interface FixtureMetadataRowContext {readonly name: number;readonly namespace: number;}[];+ readonly typeReferences: readonly {+ readonly name: number;+ readonly namespace: number;+ readonly enclosingRow?: number;+ }[];readonly tokenBlob: number;readonly fieldSignature: number;readonly methodSignature: number;@@ -668,6 +682,52 @@ const exportedTypeTable = (],];+const typeRefTable = (+ options: ManagedPeFixtureOptions,+ indexes: FixtureMetadataRowContext["indexes"],+ heapSizes: FixtureMetadataRowContext["heapSizes"],+ widths: FixtureIndexWidths,+): readonly [number, readonly Buffer[]] => [+ 1,+ [+ typeRefRow(+ indexes.attributeName,+ indexes.attributeNamespace,+ heapSizes.strings,+ metadataIndex(options.typeRefScopeRaw ?? 0, widths.resolutionScope),+ ),+ ...indexes.typeReferences.map(({ name, namespace, enclosingRow }) =>+ typeRefRow(+ name,+ namespace,+ heapSizes.strings,+ metadataIndex(+ enclosingRow === undefined ? 0 : (enclosingRow << 2) | 3,+ widths.resolutionScope,+ ),+ ),+ ),+ ],+];++const nestedClassTable = (+ options: ManagedPeFixtureOptions,+ widths: FixtureIndexWidths,+): readonly (readonly [number, readonly Buffer[]])[] =>+ (options.nestedTypes?.length ?? 0) === 0+ ? []+ : [+ [+ 41,+ (options.nestedTypes ?? []).map(([nested, enclosing]) =>+ Buffer.concat([+ metadataIndex(nested, widths.table(2)),+ metadataIndex(enclosing, widths.table(2)),+ ]),+ ),+ ],+ ];+const specTables = (options: ManagedPeFixtureOptions,indexes: FixtureMetadataRowContext["indexes"],@@ -706,7 +766,7 @@ const fixtureIndexWidths = ({}: FixtureMetadataRowContext): FixtureIndexWidths => {const rowCounts = new Map<number, number>([[0, options.moduleRowCount ?? 1],- [1, 1],+ [1, indexes.typeReferences.length + 1],[2, indexes.additionalTypeNames.length + 1],[4, 1],[6, options.methodRowCount ?? 1],@@ -725,6 +785,7 @@ const fixtureIndexWidths = ({[35, referenceStringIndexes.length],[39, indexes.exportedTypes.length],[40, 1],+ [41, options.nestedTypes?.length ?? 0],[43, options.methodSpecMethods?.length ?? 0],]);const count = (table: number): number => rowCounts.get(table) ?? 0;@@ -772,17 +833,7 @@ const fixtureMetadataRows = ({moduleRow(indexes.moduleName, heapSizes.strings, heapSizes.guids),),],- [- 1,- [- typeRefRow(- indexes.attributeName,- indexes.attributeNamespace,- heapSizes.strings,- metadataIndex(options.typeRefScopeRaw ?? 0, widths.resolutionScope),- ),- ],- ],+ typeRefTable(options, indexes, heapSizes, widths),[2,[...indexes.additionalTypeNames, indexes.typeName].map((name) =>@@ -887,6 +938,7 @@ const fixtureMetadataRows = ({],...exportedTypeTable(options, indexes, heapSizes, widths),...specTables(options, indexes, heapSizes, widths),+ ...nestedClassTable(options, widths),[40,[@@ -959,6 +1011,13 @@ const buildManagedFixtureMetadata = (namespace: strings.add(namespace),}),);+ const typeReferences = (options.typeReferences ?? []).map(+ ({ namespace, name, enclosingRow }) => ({+ name: strings.add(name),+ namespace: strings.add(namespace),+ ...(enclosingRow === undefined ? {} : { enclosingRow }),+ }),+ );const referenceNames = options.references ?? ["System.Runtime"];const referenceStringIndexes = referenceNames.map((name) =>strings.add(name),@@ -1000,6 +1059,7 @@ const buildManagedFixtureMetadata = (pinvokeImportName,resourceName,exportedTypes,+ typeReferences,tokenBlob,fieldSignature,methodSignature,diff --git a/src/dotnet/ManagedSignatureResolution.test.ts b/src/dotnet/ManagedSignatureResolution.test.tsnew file mode 100644index 000000000..d4711c33a--- /dev/null+++ b/src/dotnet/ManagedSignatureResolution.test.ts@@ -0,0 +1,332 @@+import { createHash } from "node:crypto";++import { describe, expect, it, vi } from "vitest";++import {+ attachManagedDecodeBudget,+ ManagedDecodeBudget,+} from "./ManagedDecodeBudget.js";+import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";+import {+ parseTypes,+ signature,+ typeRanges,+} from "./ManagedMemberInspectorCore.js";+import {+ metadataRowOffset,+ readManagedMetadataLayout,+} from "./ManagedMetadataLayout.js";+import {+ buildManagedPeFixture,+ managedPeFixtureTarget,+} from "./ManagedPe.fixture.js";+import { readManagedPeLayout } from "./ManagedPeReader.js";+import { signatureTypeNames } from "./ManagedSignatureTypeNames.js";+import { managedTypeReferences } from "./ManagedTypeReferences.js";+import { readTypeMemberListFacts } from "./ManagedTypeMemberLists.js";++// A top-level type's name digest, as ManagedSignatureTypeNames forms it.+const nameDigest = (name: string): Buffer => {+ const dot = name.lastIndexOf(".");+ return createHash("sha256")+ .update(Buffer.from([0]))+ .update(dot === -1 ? "" : name.slice(0, dot))+ .update(Buffer.from([0]))+ .update(name.slice(dot + 1))+ .digest();+};++const metadataLayout = (bytes: Buffer) => {+ const pe = readManagedPeLayout(bytes);+ if (pe.cli === null) throw new Error("Fixture has no CLI metadata");+ return readManagedMetadataLayout(+ bytes,+ pe.rvaToOffset(pe.cli.metadata.rva, pe.cli.metadata.size, "cli.metadata"),+ pe.cli.metadata.size,+ );+};++const named =+ (names: Readonly<Record<number, string>>) =>+ (codedIndex: number): Buffer | null => {+ const name = names[codedIndex];+ return name === undefined ? null : nameDigest(name);+ };++describe("resolved member signature digests", () => {+ it("names modifier, class, and generic type operands instead of their rows", () => {+ // modreq(M) G<P> on the left and the same types at other rows on the right.+ const left = signature(+ Buffer.from([0x06, 0x1f, 0x05, 0x15, 0x12, 0x09, 0x01, 0x11, 0x0d]),+ undefined,+ named({ 0x05: "N.Mod", 0x09: "N.G`1", 0x0d: "N.P" }),+ );+ const right = signature(+ Buffer.from([0x06, 0x1f, 0x15, 0x15, 0x12, 0x19, 0x01, 0x11, 0x1d]),+ undefined,+ named({ 0x15: "N.Mod", 0x19: "N.G`1", 0x1d: "N.P" }),+ );++ expect(left.raw_sha256).not.toBe(right.raw_sha256);+ expect(left.resolved_sha256).toMatch(/^[0-9a-f]{64}$/u);+ expect(left.resolved_sha256).toBe(right.resolved_sha256);+ });++ it("keeps the raw digest for a signature without type operands", () => {+ const decoded = signature(Buffer.from([0x00, 0x01, 0x08, 0x0e]));++ expect(decoded.resolved_sha256).toBe(decoded.raw_sha256);+ });++ it("withholds the digest when an operand has no name", () => {+ expect(+ signature(Buffer.from([0x06, 0x12, 0x05]), undefined, named({}))+ .resolved_sha256,+ ).toBeNull();+ });++ it("leaves a blob forged from a resolved preimage undecoded", () => {+ // The resolved preimage of class "A": 0xff, then the name digest. 0xff+ // never starts a compressed coded index, so the forged blob does not+ // decode and has only a raw digest, equal to the resolved one; comparison+ // tags the two kinds apart.+ const forged = signature(+ Buffer.concat([Buffer.from([0x06, 0x12, 0xff]), nameDigest("A")]),+ );+ const resolved = signature(+ Buffer.from([0x06, 0x12, 0x05]),+ undefined,+ named({ 0x05: "A" }),+ );++ expect(forged.parse_status).toBe("malformed");+ expect(forged.resolved_sha256).toBeNull();+ expect(forged.raw_sha256).toBe(resolved.resolved_sha256);+ });++ it.each([+ ["a TypeSpec, whose blob member inspection does not decode", (1 << 2) | 2],+ ["a TypeRef row outside its table", (9 << 2) | 1],+ ])("does not name %s", (_name, codedIndex) => {+ const bytes = buildManagedPeFixture({+ fieldSignature: Buffer.from([0x06, 0x12, codedIndex]),+ });+ const field = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ ).fields[0];++ expect(field?.signature.parse_status).toBe("decoded");+ expect(field?.signature.resolved_sha256).toBeNull();+ });++ it("names each type operand once, so repeated operands are not charged again", () => {+ const bytes = buildManagedPeFixture({+ typeReferences: [{ namespace: "System", name: "Uri" }],+ });+ const layout = metadataLayout(bytes);+ const budget = new ManagedDecodeBudget();+ attachManagedDecodeBudget(layout, budget);+ const typeName = signatureTypeNames(+ layout,+ [],+ {+ types: [],+ nesting: { enclosing: new Map(), complete: true },+ },+ managedTypeReferences(bytes, layout, []),+ );+ const uri = (2 << 2) | 1;++ expect(typeName(uri)).toEqual(nameDigest("System.Uri"));+ const reserve = vi.spyOn(budget, "reserve");+ expect(typeName(uri)).toEqual(nameDigest("System.Uri"));+ expect(reserve).not.toHaveBeenCalled();+ });++ it("bounds name loading before resolving a deep real TypeRef scope chain", () => {+ const name = "X".repeat(2048);+ const rows = 10_000;+ const bytes = buildManagedPeFixture({+ fieldSignature: Buffer.from([0x06, 0x12, (2 << 2) | 1]),+ typeReferences: Array.from({ length: rows }, (_, index) => ({+ namespace: "",+ name,+ ...(index + 1 === rows ? {} : { enclosingRow: index + 3 }),+ })),+ });+ const layout = metadataLayout(bytes);+ const first =+ metadataRowOffset(layout, 1, 2) ++ layout.codedIndexSize("ResolutionScope");+ const sharedName =+ layout.stringIndexSize === 4+ ? bytes.readUInt32LE(first)+ : bytes.readUInt16LE(first);+ for (let row = 3; row <= rows + 1; row += 1) {+ const offset =+ metadataRowOffset(layout, 1, row) ++ layout.codedIndexSize("ResolutionScope");+ if (layout.stringIndexSize === 4) bytes.writeUInt32LE(sharedName, offset);+ else bytes.writeUInt16LE(sharedName, offset);+ }+ const issues: Parameters<typeof managedTypeReferences>[2] = [];+ const parsedTypes = parseTypes(+ bytes,+ layout,+ typeRanges(bytes, layout, issues, readTypeMemberListFacts(bytes, layout)),+ );+ const resolve = signatureTypeNames(+ layout,+ issues,+ parsedTypes,+ managedTypeReferences(bytes, layout, issues),+ );+ expect(() => resolve((2 << 2) | 1)).not.toThrow();+ expect(resolve((2 << 2) | 1)).toBeNull();+ expect(issues).toEqual([]);+ const inspection = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ expect(inspection.coverage).toEqual({ state: "complete", issues: [] });+ expect(inspection.fields[0]).toBeDefined();+ expect(inspection.fields[0]?.signature.resolved_sha256).toBeNull();+ });+});++const fieldOf = (options: Parameters<typeof buildManagedPeFixture>[0]) => {+ const bytes = buildManagedPeFixture(options);+ return inspectManagedMembersBytes(bytes, managedPeFixtureTarget(bytes));+};++describe("type operand names", () => {+ it("keeps a TypeRef's namespace and name apart", () => {+ const resolved = (namespace: string, name: string) =>+ fieldOf({+ typeReferences: [{ namespace, name }],+ fieldSignature: Buffer.from([0x06, 0x12, (2 << 2) | 1]),+ }).fields[0]?.signature.resolved_sha256;++ expect(resolved("A", "B.C")).toMatch(/^[0-9a-f]{64}$/u);+ expect(resolved("A", "B.C")).not.toBe(resolved("A.B", "C"));+ });++ it("keeps a TypeDef's namespace and name apart", () => {+ const resolved = (typeNamespace: string, typeName: string) =>+ fieldOf({+ typeNamespace,+ typeName,+ fieldSignature: Buffer.from([0x06, 0x12, 1 << 2]),+ }).fields[0]?.signature.resolved_sha256;++ expect(resolved("A", "B.C")).toMatch(/^[0-9a-f]{64}$/u);+ expect(resolved("A", "B.C")).not.toBe(resolved("A.B", "C"));+ });++ it("names a TypeDef and a TypeRef of one namespace and name alike", () => {+ const definition = fieldOf({+ fieldSignature: Buffer.from([0x06, 0x12, 1 << 2]),+ }).fields[0]?.signature.resolved_sha256;+ const reference = fieldOf({+ typeReferences: [{ namespace: "Fixture", name: "Program" }],+ fieldSignature: Buffer.from([0x06, 0x12, (2 << 2) | 1]),+ }).fields[0]?.signature.resolved_sha256;++ expect(definition).toMatch(/^[0-9a-f]{64}$/u);+ expect(definition).toBe(reference);+ });++ it("reports an unreadable TypeRef operand row once in coverage", () => {+ const uri = (2 << 2) | 1;+ const bytes = buildManagedPeFixture({+ typeReferences: [{ namespace: "System", name: "Uri" }],+ fieldSignature: Buffer.from([0x06, 0x12, uri]),+ methodSignature: Buffer.from([0x00, 0x00, 0x12, uri]),+ });+ const layout = metadataLayout(bytes);+ // An out-of-range name index makes TypeRef row 2 unreadable.+ bytes.writeUInt16LE(+ 0xffff,+ metadataRowOffset(layout, 1, 2) ++ layout.codedIndexSize("ResolutionScope"),+ );+ const inspection = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );++ expect(inspection.fields[0]?.signature.resolved_sha256).toBeNull();+ expect(inspection.coverage.state).toBe("partial");+ expect(inspection.coverage.issues).toEqual([+ expect.objectContaining({+ code: "invalid-heap-index",+ scope: "metadata.#Strings",+ }),+ ]);+ });++ it("retains an operand outside its type table as incomplete coverage", () => {+ const inspection = fieldOf({+ fieldSignature: Buffer.from([0x06, 0x12, (9 << 2) | 1]),+ });++ expect(inspection.fields[0]?.signature.resolved_sha256).toBeNull();+ expect(inspection.coverage.state).toBe("partial");+ expect(inspection.coverage.issues).toEqual([+ expect.objectContaining({ code: "invalid-row" }),+ ]);+ });++ it("preserves readable TypeRef names while withholding an invalid scope's signature identity", () => {+ const inspection = fieldOf({+ typeRefScopeRaw: (99 << 2) | 2,+ fieldSignature: Buffer.from([0x06, 0x12, (1 << 2) | 1]),+ memberRefParentRaw: (1 << 3) | 1,+ });+ expect(inspection.fields[0]?.signature.resolved_sha256).toBeNull();+ expect(inspection.member_refs[0]?.parent_name).toBe(+ "System.Runtime.Versioning.TargetFrameworkAttribute",+ );+ expect(inspection.coverage.state).toBe("partial");+ expect(inspection.coverage.issues).toEqual([+ expect.objectContaining({+ code: "invalid-row",+ scope: "metadata.TypeRef:0x01000001",+ }),+ ]);+ });++ it.each([+ {+ rows: [+ [1, 2],+ [1, 2],+ ],+ },+ {+ rows: [+ [1, 2],+ [1, 3],+ ],+ },+ { rows: [[1, 1]] },+ { rows: [[1, 0]] },+ { rows: [[0, 2]] },+ { rows: [[1, 4]] },+ ] as const)(+ "withholds TypeDef identity for invalid nesting $rows",+ ({ rows }) => {+ const inspection = fieldOf({+ additionalEmptyTypes: 2,+ nestedTypes: rows,+ fieldSignature: Buffer.from([0x06, 0x12, 1 << 2]),+ });+ expect(inspection.fields[0]?.signature.resolved_sha256).toBeNull();+ expect(inspection.coverage.state).toBe("partial");+ expect(inspection.coverage.issues).toEqual([+ expect.objectContaining({ code: "invalid-row" }),+ ]);+ },+ );+});diff --git a/src/dotnet/ManagedSignatureTypeNames.test.ts b/src/dotnet/ManagedSignatureTypeNames.test.tsnew file mode 100644index 000000000..4c6665e70--- /dev/null+++ b/src/dotnet/ManagedSignatureTypeNames.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vitest";++import {+ MAX_TYPE_NESTING_DEPTH,+ nestedTypeDigests,+} from "./ManagedSignatureTypeNames.js";++/** Rows 1..length, each nested in the row before it. */+const chain = (length: number) => {+ const calls: number[] = [];+ const link = (row: number) => {+ calls.push(row);+ return row >= 1 && row <= length+ ? {+ namespace: "",+ name: `T${String(row)}`,+ enclosingRow: row > 1 ? row - 1 : null,+ }+ : null;+ };+ return { calls, digest: nestedTypeDigests(link, () => undefined) };+};++describe("nested signature type digests", () => {+ it("reads each row of a chain within the nesting cap once", () => {+ const { calls, digest } = chain(MAX_TYPE_NESTING_DEPTH);+ for (let row = MAX_TYPE_NESTING_DEPTH; row >= 1; row -= 1)+ expect(digest(row)).toBeInstanceOf(Buffer);++ expect(calls).toHaveLength(MAX_TYPE_NESTING_DEPTH);+ });++ it("does not name a type nested deeper than the cap, and stops at the cap", () => {+ const { calls, digest } = chain(4_000);++ expect(digest(4_000)).toBeNull();+ expect(calls.length).toBeLessThanOrEqual(MAX_TYPE_NESTING_DEPTH + 1);+ expect(digest(MAX_TYPE_NESTING_DEPTH)).toBeInstanceOf(Buffer);+ expect(digest(MAX_TYPE_NESTING_DEPTH + 1)).toBeNull();+ });++ it("reads shared parents once when many types are nested past the cap", () => {+ // Rows 1..64 form a chain; rows 1001..2000 are each nested in row 64, one+ // level past the cap. Naming the deepest types first must not reread the+ // chain for each of them.+ const calls: number[] = [];+ const children = 1_000;+ const link = (row: number) => {+ calls.push(row);+ if (row >= 1 && row <= MAX_TYPE_NESTING_DEPTH)+ return {+ namespace: "",+ name: `T${String(row)}`,+ enclosingRow: row > 1 ? row - 1 : null,+ };+ return row > 1_000 && row <= 1_000 + children+ ? {+ namespace: "",+ name: `C${String(row)}`,+ enclosingRow: MAX_TYPE_NESTING_DEPTH,+ }+ : null;+ };+ const digest = nestedTypeDigests(link, () => undefined);+ for (let row = 1_001; row <= 1_000 + children; row += 1)+ expect(digest(row)).toBeNull();++ // No row is read twice; the walk can stop at the cap before the outermost.+ expect(new Set(calls).size).toBe(calls.length);+ expect(calls.length).toBeLessThanOrEqual(MAX_TYPE_NESTING_DEPTH + children);+ });++ it("names every type of a long chain in linear time", () => {+ const { calls, digest } = chain(4_000);+ for (let row = 1; row <= 4_000; row += 1) digest(row);++ // Rows past the cap may each walk at most the cap; none rewalks below it.+ expect(calls.length).toBeLessThanOrEqual(+ 4_000 * (MAX_TYPE_NESTING_DEPTH + 1),+ );+ expect(calls.filter((row) => row === 1)).toHaveLength(1);+ });++ it("does not name a type whose nesting is cyclic", () => {+ const digest = nestedTypeDigests(+ (row) => ({+ namespace: "",+ name: `T${String(row)}`,+ enclosingRow: row === 1 ? 2 : 1,+ }),+ () => undefined,+ );++ expect(digest(1)).toBeNull();+ expect(digest(2)).toBeNull();+ });++ it("tells a nested type from a top-level type with its joined name", () => {+ const nested = nestedTypeDigests(+ (row) =>+ row === 1+ ? { namespace: "", name: "Outer", enclosingRow: null }+ : { namespace: "", name: "Inner", enclosingRow: 1 },+ () => undefined,+ );+ const flat = nestedTypeDigests(+ () => ({ namespace: "", name: "Outer/Inner", enclosingRow: null }),+ () => undefined,+ );++ expect(nested(2)).not.toEqual(flat(1));+ });+});diff --git a/src/dotnet/ManagedSignatureTypeNames.ts b/src/dotnet/ManagedSignatureTypeNames.tsnew file mode 100644index 000000000..8313565d9--- /dev/null+++ b/src/dotnet/ManagedSignatureTypeNames.ts@@ -0,0 +1,194 @@+import { createHash } from "node:crypto";++import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";+import type {+ parseTypes,+ SignatureTypeName,+} from "./ManagedMemberInspectorCore.js";+import { metadataToken } from "./ManagedMetadataHeaps.js";+import type { ManagedTypeReferenceLookup } from "./ManagedTypeReferences.js";+import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";+import { managedFailure, readManagedValue } from "./ManagedReaderFailure.js";++const TYPE_REF = 1;+const TYPE_DEF = 2;+/** One type's own namespace and name, and its enclosing type's row if nested. */+interface TypeLink {+ readonly namespace: string;+ readonly name: string;+ readonly enclosingRow: number | null;+}++/**+ * Deepest type nesting REA names, counting the outermost type as 1. Real+ * assemblies nest a few levels; the cap bounds the walk a hostile chain of+ * NestedClass rows or TypeRef ResolutionScopes can force per operand.+ */+export const MAX_TYPE_NESTING_DEPTH = 64;++/** Digest prefixes that keep a top-level type apart from a nested one. */+const TOP_LEVEL = Buffer.from([0]);+const NESTED = Buffer.from([1]);+/**+ * Separates a namespace from a name. #Strings entries end at NUL, so neither+ * holds one, and `A` + `B.C` stays apart from `A.B` + `C`.+ */+const NAME_SEPARATOR = Buffer.from([0]);++interface NamedRow {+ readonly digest: Buffer;+ readonly depth: number;+}++/**+ * Digest each row's type name after its enclosing types' names: a top-level+ * type hashes its namespace and name, each framed, and a nested type hashes+ * its enclosing type's digest and its own namespace and name, as+ * `Outer/Inner` would read. Each+ * row is read and digested once, so naming a chain is linear in its length.+ * A gap, a cycle, or nesting deeper than `MAX_TYPE_NESTING_DEPTH` has no+ * digest. `retain` is charged once per row read and once per remembered row.+ */+export const nestedTypeDigests = (+ link: (row: number) => TypeLink | null,+ retain: () => void,+): ((row: number) => Buffer | null) => {+ const named = new Map<number, NamedRow | null>();+ const remember = (row: number, value: NamedRow | null): void => {+ retain();+ named.set(row, value);+ };+ // Rows a walk read but could not name, such as the parents of a type nested+ // past the cap, are still read only once.+ const links = new Map<number, TypeLink | null>();+ const readLink = (row: number): TypeLink | null => {+ const known = links.get(row);+ if (known !== undefined) return known;+ const read = link(row);+ retain();+ links.set(row, read);+ return read;+ };+ return (row) => {+ // Walk out to a named row or the outermost type, at most past the cap.+ const path: { readonly row: number; readonly link: TypeLink }[] = [];+ const seen = new Set<number>();+ let outer: NamedRow | null = null;+ for (let current: number | null = row; current !== null;) {+ const known = named.get(current);+ if (known !== undefined) {+ if (known === null) {+ for (const step of path) remember(step.row, null);+ return null;+ }+ outer = known;+ break;+ }+ if (seen.has(current)) {+ // Every row on a cycle, and every row nested in one, has no name.+ for (const step of path) remember(step.row, null);+ return null;+ }+ if (path.length === MAX_TYPE_NESTING_DEPTH) {+ // The row the walk started from is nested past the cap.+ remember(row, null);+ return null;+ }+ const step = readLink(current);+ if (step === null) {+ remember(current, null);+ for (const visited of path) remember(visited.row, null);+ return null;+ }+ seen.add(current);+ path.push({ row: current, link: step });+ current = step.enclosingRow;+ }+ // Name inward from the outermost row; a row past the cap, and every row+ // nested in it, has no name.+ let inner: NamedRow | null = outer;+ let exceeded = false;+ for (const step of path.reverse()) {+ const depth = (inner?.depth ?? 0) + 1;+ exceeded ||= depth > MAX_TYPE_NESTING_DEPTH;+ if (exceeded) {+ remember(step.row, null);+ continue;+ }+ const hash = createHash("sha256");+ if (inner === null) hash.update(TOP_LEVEL);+ else hash.update(NESTED).update(inner.digest);+ hash+ .update(step.link.namespace)+ .update(NAME_SEPARATOR)+ .update(step.link.name);+ inner = { digest: hash.digest(), depth };+ remember(step.row, inner);+ }+ return exceeded ? null : (inner?.digest ?? null);+ };+};++/**+ * Name signature type operands independently of their metadata rows: a TypeDef+ * or TypeRef by namespace and name, after its enclosing types for a nested+ * type, as in `Outer/Inner`. A TypeDef and a TypeRef with the same name are+ * the same nominal name, and a TypeRef's resolution scope assembly is not part of its+ * name, so a type forwarded between assemblies keeps its name. A TypeSpec, an+ * unreadable row, cyclic nesting, or nesting deeper than the cap has no name,+ * so its signature has no resolved digest; an unreadable row's failure is+ * retained in `issues`, once per row. Each coded index and each row is+ * named and digested once, so repeated operands cost a lookup.+ */+export const signatureTypeNames = (+ layout: ManagedMetadataLayout,+ issues: ManagedParseIssue[],+ parsedTypes: Pick<ReturnType<typeof parseTypes>, "types" | "nesting">,+ reference: ManagedTypeReferenceLookup,+): SignatureTypeName => {+ const retain = () => managedDecodeBudget(layout).reserve(128, null);+ managedDecodeBudget(layout).reserve(parsedTypes.types.length * 128, null);+ const types = new Map<string, (typeof parsedTypes.types)[number]>();+ for (const type of parsedTypes.types) types.set(type.token, type);+ const definitions = nestedTypeDigests((row) => {+ if (!parsedTypes.nesting.complete) return null;+ const type = types.get(metadataToken(TYPE_DEF, row));+ if (+ type === undefined &&+ (row < 1 || row > (layout.table(TYPE_DEF)?.rowCount ?? 0))+ ) {+ readManagedValue(() => {+ throw managedFailure(+ "invalid-row",+ `metadata.signature.type:${TYPE_DEF}:${row}`,+ `Signature references an unavailable TypeDef row ${row}`,+ );+ }, issues);+ return null;+ }+ if (type === undefined) return null;+ return {+ namespace: type.namespace,+ name: type.name,+ enclosingRow: parsedTypes.nesting.enclosing.get(row) ?? null,+ };+ }, retain);+ const references = nestedTypeDigests((row) => {+ const value = reference(row);+ return value?.scopeValid === true ? value : null;+ }, retain);+ const digests = new Map<number, Buffer | null>();+ return (codedIndex) => {+ let digest = digests.get(codedIndex);+ if (digest === undefined) {+ managedDecodeBudget(layout).reserve(256, null);+ const row = codedIndex >>> 2;+ const table = codedIndex & 3;+ digest =+ table === 0 ? definitions(row) : table === 1 ? references(row) : null;+ digests.set(codedIndex, digest);+ }+ return digest;+ };+};diff --git a/src/dotnet/ManagedTypeNames.ts b/src/dotnet/ManagedTypeNames.tsindex ab3b34c8f..ef4a96472 100644--- a/src/dotnet/ManagedTypeNames.ts+++ b/src/dotnet/ManagedTypeNames.ts@@ -1,4 +1,4 @@-import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import type { ManagedTypeReferenceLookup } from "./ManagedTypeReferences.js";import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";import {fullName,@@ -11,11 +11,9 @@ import {type ManagedMetadataLayout,} from "./ManagedMetadataLayout.js";import {- metadataCodedTokenInvalidReason,metadataRowCursor,metadataToken,readMetadataBlob,- readMetadataString,} from "./ManagedMetadataHeaps.js";import { managedFailure, readManagedValue } from "./ManagedReaderFailure.js";@@ -31,62 +29,18 @@ export const typeNameLookup = (layout: ManagedMetadataLayout,ranges: readonly TypeRange[],issues: ManagedParseIssue[],+ references: ManagedTypeReferenceLookup,): ((token: string | null) => string | null) => {const names = new Map<string, string | null>();- const checkedScopes = new Set<number>();- const validateScopeChain = (row: number): void => {- const path = new Set<number>();- let current = row;- while (!checkedScopes.has(current)) {- const cursor = metadataRowCursor(bytes, layout, 1, current);- if (path.has(current)) {- issues.push({- code: "invalid-row",- scope: `metadata.TypeRef:${metadataToken(1, current)}`,- offset: cursor.start,- detail: "TypeRef ResolutionScope chain contains a cycle",- });- break;- }- // Admit the chain's visited entry and retained validation-cache entry.- managedDecodeBudget(layout).reserve(128, cursor.start);- path.add(current);- const raw = cursor.readIndex(layout.codedIndexSize("ResolutionScope"));- const reason = metadataCodedTokenInvalidReason(- raw,- 2,- [0, 26, 35, 1],- layout.rowCounts,- );- if (reason !== null) {- issues.push({- code: "invalid-row",- scope: `metadata.TypeRef:${metadataToken(1, current)}`,- offset: cursor.start,- detail: `TypeRef ResolutionScope coded index 0x${raw.toString(16)} is invalid: ${reason}`,- });- break;- }- // Null scopes are legal; non-TypeRef scopes terminate local validation.- if (raw === 0 || (raw & 3) !== 3) break;- current = Math.floor(raw / 4);- }- for (const visited of path) checkedScopes.add(visited);- };const definitionName = (table: 1 | 2, row: number): string | null => {if (table === 2) {metadataRowOffset(layout, 2, row);return ranges[row - 1]?.fullName ?? null;}- const cursor = metadataRowCursor(bytes, layout, 1, row);- cursor.readIndex(layout.codedIndexSize("ResolutionScope"));- readManagedValue(() => validateScopeChain(row), issues);- const name = cursor.readIndex(layout.stringIndexSize);- const namespace = cursor.readIndex(layout.stringIndexSize);- return fullName(- readMetadataString(bytes, layout, namespace, layout.strings.size),- readMetadataString(bytes, layout, name, layout.strings.size),- );+ const reference = references(row);+ return reference === null+ ? null+ : fullName(reference.namespace, reference.name);};const specName = (row: number): string | null => {const cursor = metadataRowCursor(bytes, layout, 27, row);diff --git a/src/dotnet/ManagedTypeNesting.ts b/src/dotnet/ManagedTypeNesting.tsnew file mode 100644index 000000000..7dfbbdd4d--- /dev/null+++ b/src/dotnet/ManagedTypeNesting.ts@@ -0,0 +1,45 @@+import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import { metadataRowCursor, metadataToken } from "./ManagedMetadataHeaps.js";+import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";+import { managedFailure, readManagedValue } from "./ManagedReaderFailure.js";+import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";++/** Parsed NestedClass facts shared by declaring types and signature operands. */+export interface ManagedTypeNesting {+ readonly enclosing: ReadonlyMap<number, number>;+ readonly complete: boolean;+}++export const readManagedTypeNesting = (+ bytes: Buffer,+ layout: ManagedMetadataLayout,+ issues: ManagedParseIssue[],+): ManagedTypeNesting => {+ const initialIssues = issues.length;+ const typeCount = layout.table(2)?.rowCount ?? 0;+ const enclosing = new Map<number, number>();+ for (let row = 1; row <= (layout.table(41)?.rowCount ?? 0); row += 1) {+ readManagedValue(() => {+ const cursor = metadataRowCursor(bytes, layout, 41, row);+ const nested = cursor.readIndex(layout.tableIndexSize(2));+ const outer = cursor.readIndex(layout.tableIndexSize(2));+ if (+ nested < 1 ||+ outer < 1 ||+ nested > typeCount ||+ outer > typeCount ||+ nested === outer ||+ enclosing.has(nested)+ )+ throw managedFailure(+ "invalid-row",+ `metadata.NestedClass:${metadataToken(41, row)}`,+ `NestedClass requires a unique nested type and distinct existing enclosing type; observed ${nested} -> ${outer}`,+ cursor.start,+ );+ managedDecodeBudget(layout).reserve(128, cursor.start);+ enclosing.set(nested, outer);+ }, issues);+ }+ return { enclosing, complete: issues.length === initialIssues };+};diff --git a/src/dotnet/ManagedTypeReferences.ts b/src/dotnet/ManagedTypeReferences.tsnew file mode 100644index 000000000..6b436a410--- /dev/null+++ b/src/dotnet/ManagedTypeReferences.ts@@ -0,0 +1,140 @@+import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";+import {+ metadataCodedTokenInvalidReason,+ metadataRowCursor,+ metadataToken,+ readMetadataString,+} from "./ManagedMetadataHeaps.js";+import { readManagedValue } from "./ManagedReaderFailure.js";+import { metadataRowOffset } from "./ManagedMetadataLayout.js";+import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";++export interface ManagedTypeReference {+ readonly namespace: string;+ readonly name: string;+ readonly enclosingRow: number | null;+ readonly scopeValid: boolean;+}++export type ManagedTypeReferenceLookup = (+ row: number,+) => ManagedTypeReference | null;++interface TypeReferenceRow {+ readonly nameIndex: number;+ readonly namespaceIndex: number;+ readonly enclosingRow: number | null;+ readonly scopeValid: boolean;+}++/** Own each TypeRef source tuple and scope validation once per inspection. */+export const managedTypeReferences = (+ bytes: Buffer,+ layout: ManagedMetadataLayout,+ issues: ManagedParseIssue[],+): ManagedTypeReferenceLookup => {+ const rows = new Map<number, TypeReferenceRow | null>();+ const names = new Map<number, ManagedTypeReference | null>();+ const checked = new Map<number, boolean>();+ const read = (row: number): TypeReferenceRow | null => {+ const cached = rows.get(row);+ if (cached !== undefined) return cached;+ // Admit the parsed row, validation entry and bounded walk bookkeeping.+ managedDecodeBudget(layout).reserve(384, null);+ const value =+ readManagedValue(() => {+ const cursor = metadataRowCursor(bytes, layout, 1, row);+ const raw = cursor.readIndex(layout.codedIndexSize("ResolutionScope"));+ const reason = metadataCodedTokenInvalidReason(+ raw,+ 2,+ [0, 26, 35, 1],+ layout.rowCounts,+ );+ if (reason !== null)+ issues.push({+ code: "invalid-row",+ scope: `metadata.TypeRef:${metadataToken(1, row)}`,+ offset: cursor.start,+ detail: `TypeRef ResolutionScope coded index 0x${raw.toString(16)} is invalid: ${reason}`,+ });+ return {+ nameIndex: cursor.readIndex(layout.stringIndexSize),+ namespaceIndex: cursor.readIndex(layout.stringIndexSize),+ enclosingRow:+ raw !== 0 && (raw & 3) === 3 ? Math.floor(raw / 4) : null,+ scopeValid: reason === null,+ };+ }, issues) ?? null;+ rows.set(row, value);+ return value;+ };+ const validate = (row: number): boolean => {+ const prior = checked.get(row);+ if (prior !== undefined) return prior;+ const path: number[] = [];+ const seen = new Set<number>();+ let current: number | null = row;+ let valid = true;+ while (current !== null) {+ const known = checked.get(current);+ if (known !== undefined) {+ valid = known;+ break;+ }+ if (seen.has(current)) {+ issues.push({+ code: "invalid-row",+ scope: `metadata.TypeRef:${metadataToken(1, current)}`,+ offset: metadataRowOffset(layout, 1, current),+ detail: "TypeRef ResolutionScope chain contains a cycle",+ });+ valid = false;+ break;+ }+ seen.add(current);+ path.push(current);+ const value = read(current);+ if (value === null || !value.scopeValid) {+ valid = false;+ break;+ }+ current = value.enclosingRow;+ }+ for (const visited of path) checked.set(visited, valid);+ return valid;+ };+ return (row) => {+ const cached = names.get(row);+ if (cached !== undefined) return cached;+ const value = read(row);+ if (value === null) return null;+ const scopeValid = validate(row);+ // Scope validation loads only scalar row facts. The digest owner's nesting+ // cap determines which names are requested, rather than preloading parents.+ managedDecodeBudget(layout).reserve(128, null);+ const named =+ readManagedValue(+ () => ({+ namespace: readMetadataString(+ bytes,+ layout,+ value.namespaceIndex,+ layout.strings.size,+ ),+ name: readMetadataString(+ bytes,+ layout,+ value.nameIndex,+ layout.strings.size,+ ),+ enclosingRow: value.enclosingRow,+ scopeValid,+ }),+ issues,+ ) ?? null;+ names.set(row, named);+ return named;+ };+};diff --git a/tests/boundary/mcp/managedMemberSummaryMcp.test.ts b/tests/boundary/mcp/managedMemberSummaryMcp.test.tsindex 810e8e9c8..e08355988 100644--- a/tests/boundary/mcp/managedMemberSummaryMcp.test.ts+++ b/tests/boundary/mcp/managedMemberSummaryMcp.test.ts@@ -119,6 +119,7 @@ it("summarizes selected members and pages every original collection after the fiunmatched_type_names: ["Missing.Type"],});expect(view.summary.coverage).toEqual(report.coverage);+ expect(view.summary.signature_resolution).toBe("type-names-v1");expect(view.summary.identity_scope).toEqual(report.identity_scope);expect(view.summary).not.toHaveProperty("methods");for (const detail of [undefined, "complete"]) {@@ -163,6 +164,7 @@ it("summarizes selected members and pages every original collection after the fiif (page.kind !== "managed-members")throw new Error("Unexpected page kind");expect(page.page.collection).toBe(collection);+ expect(page.signature_resolution).toBe("type-names-v1");expect(page.selection).toEqual(report.selection);expect(page.coverage.total).toBe(rows.length);paged.push(...page.page.rows);@@ -199,6 +201,7 @@ it("keeps collections that historical member Evidence never examined unknown", aexported_types: _exported,user_strings: _strings,selection: _selection,+ signature_resolution: _resolution,...recorded} = managedMemberInspectionSchema.parse(parent.normalized_result);const historical = createEvidence(undefined, parent.provider, {@@ -217,6 +220,7 @@ it("keeps collections that historical member Evidence never examined unknown", asummary.value.normalized_result,);expect(view.summary.reported_counts.exported_types).toBeNull();+ expect(view.summary.signature_resolution).toBeNull();expect(view.summary.reported_counts.user_strings).toBeNull();expect(view.summary.user_strings).toBeNull();expect(view.summary.selection).toBeNull();diff --git a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.tsindex 0b3a69f6f..fe4a83596 100644--- a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts+++ b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts@@ -6,6 +6,7 @@ import {compareManagedMembers,managedMemberComparisonResultSchema,} from "../../../../src/domain/managed/managedMemberComparison.js";+import { managedMemberInspectionSchema } from "../../../../src/domain/managed/managedArtifact.js";import { inspectManagedMembersBytes } from "../../../../src/dotnet/ManagedMemberInspector.js";import {buildManagedPeFixture,@@ -1131,7 +1132,12 @@ describe("managed member comparison of consumed ownerless ambiguity", () => {declaring_type: owner,declaring_type_token: owner === null ? null : method.declaring_type_token,name,- signature: { ...method.signature, raw_sha256: raw.repeat(64) },+ // An operand-free signature: its resolved digest is the raw one.+ signature: {+ ...method.signature,+ raw_sha256: raw.repeat(64),+ resolved_sha256: raw.repeat(64),+ },body: {...method.body,normalized_il_sha256: raw.repeat(64),@@ -1586,6 +1592,561 @@ describe("managed member comparison of unresolved owners", () => {});});+// Signatures name types by TypeDef/TypeRef row. The right build inserts a+// TypeDef and a TypeRef ahead of the ones its members use, so the same+// types sit at different rows and the raw signature bytes differ.+const LIST_REFERENCE = {+ namespace: "System.Collections.Generic",+ name: "List`1",+};+const leftBuild = {+ typeReferences: [LIST_REFERENCE],+};+const rightBuild = {+ additionalEmptyTypes: 1,+ typeReferences: [{ namespace: "System", name: "Uri" }, LIST_REFERENCE],+};+// List`1 is TypeRef row 2 on the left and row 3 on the right; Program is+// TypeDef row 1 on the left and row 2 on the right.+const leftTypes = { list: (2 << 2) | 1, program: 1 << 2 };+const rightTypes = { list: (3 << 2) | 1, program: 2 << 2 };+// List`1<Program> counter+const fieldSignature = (types: typeof leftTypes) =>+ Buffer.from([0x06, 0x15, 0x12, types.list, 0x01, 0x12, types.program]);+// List`1<Program> Main(Program)+const methodSignature = (types: typeof leftTypes) =>+ Buffer.from([+ 0x00,+ 0x01,+ 0x15,+ 0x12,+ types.list,+ 0x01,+ 0x12,+ types.program,+ 0x12,+ types.program,+ ]);+const changedIl = Buffer.from([+ 0x32, 0x02, 0x7b, 0x02, 0x00, 0x00, 0x04, 0x28, 0x02, 0x00, 0x00, 0x0a, 0x2a,+]);++const compareBuilds = (+ left: Parameters<typeof buildManagedPeFixture>[0],+ right: Parameters<typeof buildManagedPeFixture>[0],+) => {+ const leftInspection = inspect(+ buildManagedPeFixture(left),+ "/tmp/left-build.dll",+ );+ const rightInspection = inspect(+ buildManagedPeFixture(right),+ "/tmp/right-build.dll",+ );+ return compareManagedMembers(+ { evidenceId: leftInspection.evidenceId, result: leftInspection.result },+ {+ evidenceId: rightInspection.evidenceId,+ result: rightInspection.result,+ },+ );+};++describe("managed member comparison across builds", () => {+ it("pairs members whose signatures name the same types at different metadata rows", () => {+ const result = compareBuilds(+ {+ ...leftBuild,+ fieldSignature: fieldSignature(leftTypes),+ methodSignature: methodSignature(leftTypes),+ },+ {+ ...rightBuild,+ fieldSignature: fieldSignature(rightTypes),+ methodSignature: methodSignature(rightTypes),+ },+ );++ expect(result.methods).toEqual([+ expect.objectContaining({+ status: "unchanged",+ dimensions: [],+ match: expect.objectContaining({ basis: "exact-il-signature" }),+ }),+ ]);+ expect(result.fields).toEqual([+ expect.objectContaining({+ status: "unchanged",+ match: expect.objectContaining({ basis: "field-signature" }),+ }),+ ]);+ });++ it("pairs a method by declared type, name, and resolved signature when its CIL changed", () => {+ const result = compareBuilds(+ { ...leftBuild, methodSignature: methodSignature(leftTypes) },+ {+ ...rightBuild,+ methodSignature: methodSignature(rightTypes),+ ilBody: changedIl,+ },+ );++ expect(result.methods).toEqual([+ expect.objectContaining({+ status: "changed",+ dimensions: ["cil"],+ match: expect.objectContaining({ basis: "exact-signature" }),+ }),+ ]);+ });++ it("pairs a renamed method by structural shape when its signature names the same types", () => {+ const result = compareBuilds(+ { ...leftBuild, methodSignature: methodSignature(leftTypes) },+ {+ ...rightBuild,+ methodName: "Renamed",+ methodSignature: methodSignature(rightTypes),+ ilBody: changedIl,+ },+ );++ expect(result.methods).toEqual([+ expect.objectContaining({+ status: "changed",+ match: expect.objectContaining({+ basis: "structural-method-shape",+ confidence: "high",+ }),+ }),+ ]);+ });++ it("does not pair members whose identical signature bytes name different types", () => {+ // TypeDef row 1 is Program on the left and Empty0 on the right.+ const result = compareBuilds(+ {+ fieldSignature: Buffer.from([0x06, 0x12, leftTypes.program]),+ methodSignature: Buffer.from([0x00, 0x00, 0x12, leftTypes.program]),+ },+ {+ additionalEmptyTypes: 1,+ fieldSignature: Buffer.from([0x06, 0x12, leftTypes.program]),+ methodSignature: Buffer.from([0x00, 0x00, 0x12, leftTypes.program]),+ },+ );++ expect(result.methods.map(({ status }) => status).sort()).toEqual([+ "added",+ "removed",+ ]);+ expect(result.fields.map(({ status }) => status).sort()).toEqual([+ "added",+ "removed",+ ]);+ });+});++describe("managed member comparison of resolved signatures", () => {+ it("pairs a partially decoded field by declared type, name, and resolved signature", () => {+ // Trailing data after the field type leaves the signature partial.+ const result = compareBuilds(+ { fieldSignature: Buffer.from([0x06, 0x12, leftTypes.program, 0x00]) },+ {+ additionalEmptyTypes: 1,+ fieldSignature: Buffer.from([0x06, 0x12, rightTypes.program, 0x00]),+ },+ );++ expect(result.fields).toEqual([+ expect.objectContaining({+ status: "unchanged",+ match: expect.objectContaining({ basis: "exact-signature" }),+ }),+ ]);+ });++ it("does not pair a raw digest with an equal resolved digest", () => {+ // class Fixture.Program on the left; on the right, the bytes of its+ // resolved preimage, which do not decode and so compare by raw digest.+ const programDigest = createHash("sha256")+ .update(Buffer.from([0]))+ .update("Fixture")+ .update(Buffer.from([0]))+ .update("Program")+ .digest();+ const left = inspect(+ buildManagedPeFixture({+ methodSignature: Buffer.from([0x00, 0x00, 0x12, leftTypes.program]),+ }),+ "/tmp/left-collision.dll",+ );+ const right = inspect(+ buildManagedPeFixture({+ methodSignature: Buffer.concat([+ Buffer.from([0x00, 0x00, 0x12, 0xff]),+ programDigest,+ ]),+ }),+ "/tmp/right-collision.dll",+ );+ // The collision this guards against must exist: the right blob does not+ // decode, and its raw digest is the left signature's resolved digest.+ const [leftMethod] = left.result.methods;+ const [rightMethod] = right.result.methods;+ expect(rightMethod?.signature.resolved_sha256).toBeNull();+ expect(rightMethod?.signature.raw_sha256).toBe(+ leftMethod?.signature.resolved_sha256,+ );++ const result = compareManagedMembers(+ { evidenceId: left.evidenceId, result: left.result },+ { evidenceId: right.evidenceId, result: right.result },+ );++ expect(+ result.methods.filter(({ match }) => match.status === "matched"),+ ).toEqual([]);+ });++ it("compares raw signatures against Evidence recorded before resolution", () => {+ // Both signatures name Program, TypeDef row 1, in the same build.+ const build = () =>+ buildManagedPeFixture({+ fieldSignature: Buffer.from([0x06, 0x12, leftTypes.program]),+ methodSignature: Buffer.from([+ 0x00,+ 0x01,+ 0x01,+ 0x12,+ leftTypes.program,+ ]),+ });+ const left = inspect(build(), "/tmp/left-recorded.dll");+ const right = inspect(build(), "/tmp/right-current.dll");+ const withoutResolution = <Member extends { signature: object }>(+ members: readonly Member[],+ ) =>+ members.map((member) => {+ const { resolved_sha256: _omitted, ...recorded } = member.signature as {+ resolved_sha256: unknown;+ };+ return { ...member, signature: recorded };+ });+ const recorded = managedMemberInspectionSchema.parse({+ ...left.result,+ signature_resolution: undefined,+ methods: withoutResolution(left.result.methods),+ fields: withoutResolution(left.result.fields),+ member_refs: withoutResolution(left.result.member_refs),+ });+ expect(recorded.methods[0]?.signature.resolved_sha256).toBeNull();++ const result = compareManagedMembers(+ { evidenceId: left.evidenceId, result: recorded },+ { evidenceId: right.evidenceId, result: right.result },+ );++ expect(result.methods).toEqual([+ expect.objectContaining({ status: "unchanged" }),+ ]);+ expect(result.fields).toEqual([+ expect.objectContaining({ status: "unchanged" }),+ ]);+ expect(result.limitations).toContain(+ "At least one managed member observation does not attest signature type-name resolution, so signatures compare by raw bytes, which name types by build-local metadata row.",+ );+ });+});++describe("managed member comparison of nested signature types", () => {+ const fieldOfType = (codedIndex: number) =>+ Buffer.from([0x06, 0x12, codedIndex]);+ const statuses = (result: ReturnType<typeof compareBuilds>) =>+ result.fields.map(({ status }) => status).sort();++ it("pairs a nested TypeDef by its enclosing type at different rows", () => {+ // Fixture.Empty0/Fixture.Program is TypeDef row 2, then row 3.+ const result = compareBuilds(+ {+ additionalEmptyTypes: 1,+ nestedTypes: [[2, 1]],+ fieldSignature: fieldOfType(2 << 2),+ },+ {+ additionalEmptyTypes: 2,+ nestedTypes: [[3, 1]],+ fieldSignature: fieldOfType(3 << 2),+ },+ );++ expect(statuses(result)).toEqual(["unchanged"]);+ });++ it("tells same-named TypeDefs apart by their enclosing types", () => {+ // TypeDef row 2 is nested in Empty0 on the left only.+ const result = compareBuilds(+ {+ additionalEmptyTypes: 2,+ nestedTypes: [[2, 1]],+ fieldSignature: fieldOfType(2 << 2),+ },+ { additionalEmptyTypes: 2, fieldSignature: fieldOfType(2 << 2) },+ );++ expect(statuses(result)).toEqual(["added", "removed"]);+ });++ it("does not name a TypeDef whose nesting is cyclic", () => {+ const bytes = buildManagedPeFixture({+ additionalEmptyTypes: 2,+ nestedTypes: [+ [1, 2],+ [2, 1],+ ],+ fieldSignature: fieldOfType(1 << 2),+ });+ const field = inspect(bytes, "/tmp/cyclic.dll").result.fields[0];++ expect(field?.signature.parse_status).toBe("decoded");+ expect(field?.signature.resolved_sha256).toBeNull();+ });++ const enumerator = (enclosingRow: number) => ({+ namespace: "",+ name: "Enumerator",+ enclosingRow,+ });+ const list = { namespace: "System.Collections.Generic", name: "List`1" };+ const dictionary = {+ namespace: "System.Collections.Generic",+ name: "Dictionary`2",+ };++ it("pairs a nested TypeRef by its enclosing TypeRef at different rows", () => {+ // List`1/Enumerator is TypeRef row 3, then row 4.+ const result = compareBuilds(+ {+ typeReferences: [list, enumerator(2)],+ fieldSignature: fieldOfType((3 << 2) | 1),+ },+ {+ typeReferences: [dictionary, list, enumerator(3)],+ fieldSignature: fieldOfType((4 << 2) | 1),+ },+ );++ expect(statuses(result)).toEqual(["unchanged"]);+ });++ it("tells same-named TypeRefs apart by their enclosing TypeRefs", () => {+ // List`1/Enumerator on the left, Dictionary`2/Enumerator on the right.+ const result = compareBuilds(+ {+ typeReferences: [list, enumerator(2)],+ fieldSignature: fieldOfType((3 << 2) | 1),+ },+ {+ typeReferences: [dictionary, enumerator(2)],+ fieldSignature: fieldOfType((3 << 2) | 1),+ },+ );++ expect(statuses(result)).toEqual(["added", "removed"]);+ });+});++describe("managed member comparison of unresolved signatures", () => {+ // A TypeSpec operand has no name, so the method compares by raw bytes,+ // while the default field resolves.+ const typeSpecs = [Buffer.from([0x1d, 0x08]), Buffer.from([0x1d, 0x0e])];+ const unresolvedAt = (row: number) => ({+ typeSpecSignatures: typeSpecs,+ methodSignature: Buffer.from([0x00, 0x00, 0x12, (row << 2) | 2]),+ });+ const resolved = {+ methodSignature: Buffer.from([0x00, 0x00, 0x12, leftTypes.program]),+ };+ const methodLimitations = (result: ReturnType<typeof compareBuilds>) =>+ result.methods.map(({ status, limitations }) => [status, limitations]);++ it("does not establish unchanged signatures from identical unresolved row bytes", () => {+ const result = compareBuilds(unresolvedAt(1), {+ ...unresolvedAt(1),+ typeSpecSignatures: [...typeSpecs].reverse(),+ });+ expect(methodLimitations(result)).toEqual([+ ["unknown", [expect.stringMatching(/^signature-not-resolved:/u)]],+ ]);+ });++ it("retains a known CIL change beside an unresolved signature", () => {+ const result = compareBuilds(unresolvedAt(1), {+ ...unresolvedAt(1),+ ilBody: Buffer.from([0x0a, 0x17, 0x2a]),+ });+ expect(methodLimitations(result)).toEqual([+ ["changed", [expect.stringMatching(/^signature-not-resolved:/u)]],+ ]);+ expect(result.methods[0]?.dimensions).toContain("cil");+ });++ it("keeps a partially decoded field's unresolved type unknown after pairing", () => {+ const fieldSignature = Buffer.from([0x06, 0x12, (1 << 2) | 2, 0xff]);+ const result = compareBuilds(+ { typeSpecSignatures: typeSpecs, fieldSignature },+ { typeSpecSignatures: [...typeSpecs].reverse(), fieldSignature },+ );+ expect(result.fields).toEqual([+ expect.objectContaining({+ status: "unknown",+ limitations: [expect.stringMatching(/^signature-not-resolved:/u)],+ }),+ ]);+ });++ it("retains unknown signatures when every member has an unresolved operand", () => {+ const at = (row: number) => ({+ ...unresolvedAt(row),+ fieldSignature: Buffer.from([0x06, 0x12, (row << 2) | 2]),+ });+ const result = compareBuilds(at(1), at(2));+ expect(+ [...result.methods, ...result.fields].map(({ status }) => status),+ ).toEqual(["unknown", "unknown", "unknown", "unknown"]);+ expect(result.limitations).not.toEqual(+ expect.arrayContaining([+ expect.stringContaining(+ "does not attest signature type-name resolution",+ ),+ ]),+ );+ });++ it("keeps an unmatched unresolved method unknown in a resolved comparison", () => {+ for (const result of [+ compareBuilds(unresolvedAt(1), unresolvedAt(2)),+ compareBuilds(unresolvedAt(2), unresolvedAt(1)),+ ])+ expect(methodLimitations(result)).toEqual([+ ["unknown", [expect.stringMatching(/^signature-not-resolved:/u)]],+ ["unknown", [expect.stringMatching(/^signature-not-resolved:/u)]],+ ]);+ });++ it("keeps a resolved method unknown beside an unresolved same-named counterpart", () => {+ for (const [left, right] of [+ [unresolvedAt(1), resolved],+ [resolved, unresolvedAt(1)],+ ] as const) {+ const result = compareBuilds(left, right);+ const unresolvedSide = left === resolved ? "right" : "left";+ expect(+ result.methods.map(({ status, left: leftItem, limitations }) => [+ status,+ (leftItem === null) === (unresolvedSide === "left")+ ? "resolved"+ : "unresolved",+ limitations,+ ]),+ ).toEqual(+ expect.arrayContaining([+ [+ "unknown",+ "unresolved",+ [expect.stringMatching(/^signature-not-resolved:/u)],+ ],+ [+ "unknown",+ "resolved",+ [+ expect.stringMatching(+ new RegExp(+ `^counterpart-signature-not-resolved: The ${unresolvedSide} method inventory`,+ "u",+ ),+ ),+ ],+ ],+ ]),+ );+ }+ });+});++describe("managed member comparison limitations for resolved signatures", () => {+ it("does not report missing resolved digests for observations without signatures", () => {+ const base = inspect(buildManagedPeFixture(), "/tmp/no-members.dll");+ const empty = {+ ...base,+ result: { ...base.result, methods: [], fields: [] },+ };+ const result = compareManagedMembers(empty, empty);++ expect(result.limitations).not.toContain(+ "At least one managed member observation does not attest signature type-name resolution, so signatures compare by raw bytes, which name types by build-local metadata row.",+ );+ });+});++describe("managed member comparison of resolved-signature contention", () => {+ it("contests an ownerless method across builds whose raw signature bytes differ", () => {+ const base = inspect(buildManagedPeFixture(), "/tmp/ownerless-builds.dll");+ const [method] = base.result.methods;+ if (method === undefined) throw new Error("Expected a fixture method");+ // The same signature names a type at another row in the right build.+ const member = (raw: string, body: string, stack: number) => ({+ ...method,+ signature: {+ ...method.signature,+ raw_sha256: raw.repeat(64),+ resolved_sha256: "e".repeat(64),+ },+ body: {+ ...method.body,+ normalized_il_sha256: body.repeat(64),+ max_stack: stack,+ },+ });+ const withOwnerless = {+ ...base,+ result: {+ ...base.result,+ fields: [],+ methods: [+ member("a", "a", 1),+ {+ ...member("a", "b", 2),+ token: "0x06000002",+ declaring_type: null,+ declaring_type_token: null,+ },+ ],+ },+ };+ const resolvedOnly = {+ ...base,+ result: { ...base.result, fields: [], methods: [member("f", "c", 3)] },+ };+ for (const result of [+ compareManagedMembers(withOwnerless, resolvedOnly),+ compareManagedMembers(resolvedOnly, withOwnerless),+ ]) {+ expect(result.methods).toEqual([+ expect.objectContaining({+ status: "unknown",+ match: expect.objectContaining({+ status: "ambiguous",+ basis: "exact-signature",+ }),+ }),+ ]);+ expect(result.summary).toMatchObject({ added: 0, removed: 0 });+ }+ });+});+/*** Add copies of the fixture's method and field, each pair declared by another* type, to an inspection. The copies come from `source`, so they can carrydiff --git a/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts b/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.tsindex bd5df1505..ededba08d 100644--- a/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts+++ b/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts@@ -19,7 +19,7 @@ const hash = (bytes: Buffer): string =>createHash("sha256").update(bytes).digest("hex");describe("managed member partial body comparison", () => {- it("keeps unavailable body facets unknown while retaining an observed signature change", () => {+ it("keeps unavailable body facets unknown and a raw-only signature difference unchanged", () => {const left = inspect(buildManagedPeFixture(), "/tmp/left-body-partial.dll");const right = inspect(buildManagedPeFixture(),@@ -85,9 +85,11 @@ describe("managed member partial body comparison", () => {result: rightSignatureChanged,},);+ // Raw bytes that resolve to the same types, as when a rebuild moves a+ // referenced type to another metadata row, are not a signature change.expect(signatureChanged.methods[0]).toMatchObject({- status: "changed",- dimensions: ["signature"],+ status: "unchanged",+ dimensions: [],});const bothAbsent = compareManagedMembers(