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): validate metadata operands and locals declarations
morluto667402846c53
diff --git a/docs/managed-code-analysis.md b/docs/managed-code-analysis.mdindex 0a293bbc5..b17100565 100644--- a/docs/managed-code-analysis.md+++ b/docs/managed-code-analysis.md@@ -519,6 +519,19 @@ CLI `#GUID` heap values retain their exact 16-byte GUID text. REA does not imposRFC 4122 UUID version or variant bits on MVID, EncId, or EncBaseId becauseECMA-335 metadata does not require those bit patterns. Tokens and RVAs arebuild-local coordinates, not durable cross-build identities or native addresses.+Field and method signatures validate embedded TypeDefOrRefOrSpec operands+against the artifact's metadata tables. An invalid operand leaves the member+name and raw signature digest available while marking that signature malformed+and coverage partial.+A fat method header's nonzero LocalVarSigTok must name an existing StandAloneSig+row whose blob is a structurally valid LocalVarSig. REA validates its local+types and exact blob coverage but does not project their identities. An invalid+token or malformed signature leaves decoded CIL anchors intact but marks the+body malformed and coverage partial. Unsupported local type encodings retain+the readable body with partial coverage. Zero continues to mean no locals+signature. Comparison detects whether a locals declaration is present, but raw+table tokens are not cross-build identities and local type contents are not+compared.## Decoded-CIL fingerprint@@ -544,6 +557,10 @@ Tuple operands use these exact projections:- signed integer and variable operands: decimal strings; floating-pointoperands: JavaScript's `String` representation of the decoded IEEE value.+For `ldtoken` MemberRef operands, `operand_kind` follows the parsed member+signature (`field` or `method`); if that signature does not establish the kind,+the anchor keeps the generic `token` classification.+Opcode names retain short/long forms and prefix opcodes. This makes the value areproducible decoded-tuple fingerprint, not a canonical semantic CIL identity:it does not resolve tokens across MVIDs, does not commit full control flow or@@ -712,6 +729,10 @@ Managed member comparisons report a `metadata` dimension when an observedMethodDef flags or implementation flags value differs, including accessibilityor synchronization changes. Observed method-body `init_locals` and `max_stack`differences also contribute to `metadata`, even when CIL decoding is incomplete.+For complete bodies, presence or absence of a locals signature also contributes;+the locals table token is build-local and is not compared. Local type contents+are not currently compared, so this facet does not establish equivalent locals+declarations.An unavailable header value keeps body coverage unknown rather than establishingequality or a difference. These comparisons are separate from the CIL/signaturematching tiers: identical instructions do not establish unchanged method metadata.diff --git a/src/domain/managed/managedMemberComparisonItems.ts b/src/domain/managed/managedMemberComparisonItems.tsindex ea44add11..714b416bd 100644--- a/src/domain/managed/managedMemberComparisonItems.ts+++ b/src/domain/managed/managedMemberComparisonItems.ts@@ -73,10 +73,16 @@ const methodDimensions = (right.body[field] !== null &&left.body[field] !== right.body[field],);+ const localsPresenceChanged =+ left.body.status === "present" &&+ right.body.status === "present" &&+ (left.body.local_var_sig_token !== null) !==+ (right.body.local_var_sig_token !== null);if (left.flags !== right.flags ||left.impl_flags !== right.impl_flags ||- headerChanged+ headerChanged ||+ localsPresenceChanged)dimensions.push("metadata");if (signatureIdentity(left.signature) !== signatureIdentity(right.signature))diff --git a/src/dotnet/ManagedMemberInspector.test.ts b/src/dotnet/ManagedMemberInspector.test.tsindex bf50c56ed..aeac0c8f5 100644--- a/src/dotnet/ManagedMemberInspector.test.ts+++ b/src/dotnet/ManagedMemberInspector.test.ts@@ -5,6 +5,7 @@ import {ManagedDecodeBudget,managedDecodeBudget,} from "./ManagedDecodeBudget.js";+import { metadataRowCursor, readMetadataBlob } from "./ManagedMetadataHeaps.js";import {metadataRowOffset,readManagedMetadataLayout,@@ -42,6 +43,39 @@ const ldstrBody = (tokens: readonly string[]): Buffer => {};describe("managed method body anchors", () => {+ it.each([+ ["field", Buffer.from([0x06, 0x08]), "field"],+ ["method", Buffer.from([0x00, 0x00, 0x01]), "method"],+ ["unknown", Buffer.from([0x7f]), "token"],+ ] as const)(+ "classifies ldtoken MemberRefs from their parsed %s signature",+ (_label, memberRefSignature, expectedKind) => {+ const il = Buffer.from([0xd0, 1, 0, 0, 0x0a, 0x26, 0x2a]);+ const bytes = buildManagedPeFixture({+ targetFramework: null,+ memberRefName: "Counter",+ memberRefParentRaw: 8,+ memberRefSignature,+ ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),+ });+ const result = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );++ expect(result.member_refs[0]?.signature.kind).toBe(+ expectedKind === "token" ? "unknown" : expectedKind,+ );+ expect(result.methods[0]?.body.anchors[0]).toMatchObject({+ opcode: "ldtoken",+ operand_kind: expectedKind,+ operand: "0x0a000001",+ });+ expect(result.call_edges).toEqual([]);+ expect(result.field_accesses).toEqual([]);+ },+ );+it("keeps operand-free instructions in anchors so branch comparison constants stay recoverable", () => {// ldloc.s 4; ldc.i4.4; bne.un.s +0; ret. The constant this branch compares// against is carried by the operand-free ldc.i4.4 opcode itself, so the@@ -90,6 +124,189 @@ describe("managed method body anchors", () => {});});+it.each([0x06000001, 0x11000001])(+ "marks an invalid LocalVarSigTok %s malformed without losing CIL",+ (token) => {+ const body = Buffer.alloc(13);+ body.writeUInt16LE(0x3003, 0);+ body.writeUInt16LE(8, 2);+ body.writeUInt32LE(1, 4);+ body[12] = 0x2a;+ const bytes = buildManagedPeFixture({ ilBody: body });+ const initial = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ const offset = initial.methods[0]?.body.file_offset;+ if (offset === null || offset === undefined)+ throw new Error("fixture body has no offset");+ bytes.writeUInt32LE(token, offset + 8);+ const result = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ expect(result.methods[0]?.body).toMatchObject({+ status: "malformed",+ local_var_sig_token: `0x${token.toString(16).padStart(8, "0")}`,+ anchors: expect.arrayContaining([+ expect.objectContaining({ opcode: "ret" }),+ ]),+ });+ expect(result.coverage).toMatchObject({+ state: "partial",+ issues: [+ expect.objectContaining({ code: "invalid-row", offset: offset + 8 }),+ ],+ });+ },+);++it.each([+ ["valid LocalVarSig", Buffer.from([0x07, 0x01, 0x08]), "present"],+ [+ "valid pinned LocalVarSig",+ Buffer.from([0x07, 0x01, 0x45, 0x08]),+ "present",+ ],+ [+ "valid pinned by-reference LocalVarSig",+ Buffer.from([0x07, 0x01, 0x45, 0x10, 0x08]),+ "present",+ ],+ [+ "valid pinned pointer with a nested custom modifier",+ Buffer.from([0x07, 0x01, 0x45, 0x0f, 0x1f, 0x04, 0x08]),+ "present",+ ],+ [+ "valid pinned function pointer with a TYPEDBYREF return",+ Buffer.from([0x07, 0x01, 0x45, 0x1b, 0x00, 0x00, 0x16]),+ "present",+ ],+ ["wrong signature kind", Buffer.from([0x00, 0x00, 0x01]), "malformed"],+ ["truncated LocalVarSig", Buffer.from([0x07, 0x01]), "malformed"],+] as const)(+ "checks the StandAloneSig payload kind: %s",+ (_name, standaloneSignature, status) => {+ const body = Buffer.alloc(13);+ body.writeUInt16LE(0x3003, 0);+ body.writeUInt16LE(8, 2);+ body.writeUInt32LE(1, 4);+ body.writeUInt32LE(0x11000001, 8);+ body[12] = 0x2a;+ const bytes = buildManagedPeFixture({+ ilBody: body,+ standaloneSignatures: [standaloneSignature],+ });+ const result = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ expect(result.methods[0]?.body.status).toBe(status);+ if (status === "present")+ expect(result.coverage).toMatchObject({ state: "complete", issues: [] });+ else+ expect(result.coverage).toMatchObject({+ state: "partial",+ issues: [expect.objectContaining({ code: expect.any(String) })],+ });+ },+);++it.each([+ [+ "void local element",+ Buffer.from([0x07, 0x01, 0x01]),+ "malformed",+ "invalid-blob",+ 2,+ ],+ [+ "local modifier after PINNED constraint",+ Buffer.from([0x07, 0x01, 0x45, 0x1f, 0x04, 0x08]),+ "malformed",+ "invalid-blob",+ 3,+ ],+ [+ "PINNED typed reference local",+ Buffer.from([0x07, 0x01, 0x45, 0x16]),+ "malformed",+ "invalid-blob",+ 3,+ ],+ [+ "trailing signature data",+ Buffer.from([0x07, 0x01, 0x08, 0xff]),+ "malformed",+ "invalid-blob",+ 3,+ ],+ [+ "unsupported local element",+ Buffer.from([0x07, 0x01, 0xff]),+ "partial",+ "unsupported-signature",+ 2,+ ],+ [+ "zero local count with trailing byte",+ Buffer.from([0x07, 0x00, 0xff]),+ "malformed",+ "invalid-blob",+ 1,+ ],+] as const)(+ "preserves CIL and reports %s at its source byte",+ (_name, standaloneSignature, status, code, localOffset) => {+ const body = Buffer.alloc(13);+ body.writeUInt16LE(0x3003, 0);+ body.writeUInt16LE(8, 2);+ body.writeUInt32LE(1, 4);+ body.writeUInt32LE(0x11000001, 8);+ body[12] = 0x2a;+ const bytes = buildManagedPeFixture({+ ilBody: body,+ standaloneSignatures: [standaloneSignature],+ });+ const pe = readManagedPeLayout(bytes);+ if (pe.cli === null) throw new Error("fixture has no CLI header");+ const layout = readManagedMetadataLayout(+ bytes,+ pe.rvaToOffset(pe.cli.metadata.rva, pe.cli.metadata.size, "metadata"),+ pe.cli.metadata.size,+ );+ const row = metadataRowCursor(bytes, layout, 17, 1);+ const blob = readMetadataBlob(+ bytes,+ layout,+ row.readIndex(layout.blobIndexSize),+ layout.blob.size,+ );+ const blobOffset = blob.byteOffset - bytes.byteOffset;+ const result = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ expect(result.methods[0]?.body).toMatchObject({+ status,+ anchors: expect.arrayContaining([+ expect.objectContaining({ opcode: "ret" }),+ ]),+ });+ expect(result.coverage).toMatchObject({+ state: "partial",+ issues: [+ expect.objectContaining({+ code,+ scope: "metadata.StandAloneSig:0x11000001.signature",+ offset: blobOffset + localOffset,+ }),+ ],+ });+ },+);+describe("managed member inspection", () => {it("keeps metadata handles distinct from calls and field accesses", () => {const il = Buffer.from([@@ -1731,6 +1948,33 @@ it("decodes generic instantiation member signatures as complete coverage", () =>expect(result.coverage).toMatchObject({ state: "complete", issues: [] });});+it.each([+ ["reserved TypeDefOrRef tag", Buffer.from([0x06, 0x12, 0x07])],+ ["missing TypeSpec row", Buffer.from([0x06, 0x12, 0x06])],+])(+ "retains a field with an invalid signature type operand: %s",+ (_name, fieldSignature) => {+ const bytes = buildManagedPeFixture({ fieldSignature });+ const result = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ expect(result.fields[0]).toMatchObject({+ name: "counter",+ signature: { kind: "field", parse_status: "malformed", field_type: null },+ });+ expect(result.coverage).toMatchObject({+ state: "partial",+ issues: [+ expect.objectContaining({+ code: "invalid-row",+ scope: "Field:0x04000001.signature",+ }),+ ],+ });+ },+);+it.each([["single-dimension general array", [0x14, 0x08, 0x01, 0x00, 0x00], "i4[...]"],[diff --git a/src/dotnet/ManagedMemberInspector.ts b/src/dotnet/ManagedMemberInspector.tsindex 4f543edcd..d937ff73f 100644--- a/src/dotnet/ManagedMemberInspector.ts+++ b/src/dotnet/ManagedMemberInspector.ts@@ -283,6 +283,14 @@ export const inspectManagedMembersBytes = (pe,ranges,signatureTypeName,+ memberRefKinds: new Map(+ memberRefs.refs.flatMap((memberRef) =>+ memberRef.signature.kind === "field" ||+ memberRef.signature.kind === "method"+ ? [[memberRef.token, memberRef.signature.kind] as const]+ : [],+ ),+ ),memberLists,selected,methodOffset,diff --git a/src/dotnet/ManagedMemberInspectorCore.ts b/src/dotnet/ManagedMemberInspectorCore.tsindex 5e9a7ef40..b684fa91e 100644--- a/src/dotnet/ManagedMemberInspectorCore.ts+++ b/src/dotnet/ManagedMemberInspectorCore.ts@@ -9,7 +9,10 @@ import type {ManagedMemberInspection,ManagedParseIssue,} from "../domain/managed/managedArtifact.js";-import { managedDecodeBudget } from "./ManagedDecodeBudget.js";+import {+ managedDecodeBudget,+ type ManagedDecodeBudget,+} from "./ManagedDecodeBudget.js";import {readManagedTypeNesting,type ManagedTypeNesting,@@ -455,7 +458,13 @@ const arrayShape = (};/** Grammar position of the element being decoded (ECMA-335 II.23.2). */-type SignaturePosition = "field" | "return" | "parameter" | "type" | "pointee";+type SignaturePosition =+ | "field"+ | "local"+ | "return"+ | "parameter"+ | "type"+ | "pointee";// Custom modifiers do not change the position they precede.const currentPosition = (@@ -470,13 +479,13 @@ const currentPosition = (return "type";};-// VOID is a RetType or a pointee; TYPEDBYREF is a RetType or Param; BYREF-// prefixes a RetType, Param, or (since ref fields) a field type.+// VOID is a RetType or a pointee; TYPEDBYREF is a RetType, Param, or local;+// BYREF prefixes a RetType, Param, local, or (since ref fields) a field type.const POSITION_ELEMENTS: ReadonlyMap<number, readonly SignaturePosition[]> =new Map([[0x01, ["return", "pointee"]],- [0x16, ["return", "parameter"]],- [0x10, ["return", "parameter", "field"]],+ [0x16, ["return", "parameter", "local"]],+ [0x10, ["return", "parameter", "local", "field"]],]);/** Decode a type operand once; spec callers also validate its metadata coordinate. */@@ -531,6 +540,7 @@ const readTypeSignature = (): { readonly value: string; readonly next: number } => {const stack: TypeContinuation[] = [];let cursor = offset;+ let pinned = false;for (;;) {let value: string | undefined;const kind = blob[cursor];@@ -545,6 +555,26 @@ const readTypeSignature = (`element type 0x${kind.toString(16)} is not valid in a ${currentPosition(stack, base)} position`,cursor,);+ if (kind === 0x45) {+ if (base !== "local")+ throw managedFailure(+ "unsupported-signature",+ "signature",+ "unsupported element type 0x45",+ cursor,+ );+ if (+ pinned ||+ stack.some(({ kind: frameKind }) => frameKind !== "modifiers")+ )+ return malformedSignature(+ "PINNED is not valid in this type position",+ cursor,+ );+ pinned = true;+ cursor += 1;+ continue;+ }const named = ELEMENT_TYPES.get(kind);if (named !== undefined) {value = named;@@ -554,6 +584,11 @@ const readTypeSignature = (stack.push({ kind: "suffix", suffix });cursor += 1;} else if (kind === 0x1f || kind === 0x20) {+ if (pinned && currentPosition(stack, base) === "local")+ return malformedSignature(+ "custom modifier follows the LocalVarSig PINNED constraint",+ cursor,+ );const token = readTypeOperand(blob, cursor + 1, layout);operands?.push({ offset: cursor + 1, ...token });const modifier = `${kind === 0x1f ? "modreq" : "modopt"}:${String(token.value)}`;@@ -573,6 +608,11 @@ const readTypeSignature = (value = `${kind === 0x1e ? "mvar" : "var"}:${String(variable.value)}`;cursor = variable.next;} else if (kind === 0x16) {+ if (pinned && currentPosition(stack, base) === "local")+ return malformedSignature(+ "TYPEDBYREF cannot have a LocalVarSig PINNED constraint",+ cursor,+ );value = "typedbyref";cursor += 1;} else if (kind === 0x14) {@@ -653,6 +693,53 @@ const readTypeSignature = (}};+/** Validate a StandAloneSig LocalVarSig without projecting local type identities. */+export const validateLocalSignature = (+ layout: ManagedMetadataLayout,+ blob: Buffer,+ {+ scope,+ blobOffset,+ }: { readonly scope: string; readonly blobOffset: number },+ budget: ManagedDecodeBudget,+): ManagedParseIssue | null => {+ budget.admitTransient(blob.length * 256, blobOffset);+ try {+ if (blob[0] !== 0x07)+ malformedSignature("StandAloneSig row does not contain a LocalVarSig", 0);+ const count = readCompressed(blob, 1);+ if (count.value === 0 || count.value > 0xfffe)+ malformedSignature(+ `LocalVarSig local count ${String(count.value)} is outside the ECMA-335 range`,+ 1,+ );+ let cursor = count.next;+ for (let index = 0; index < count.value; index += 1) {+ const local = readTypeSignature(blob, cursor, "local", { layout });+ cursor = local.next;+ }+ if (cursor !== blob.length)+ malformedSignature("Trailing LocalVarSig data", cursor);+ return null;+ } catch (cause: unknown) {+ if (+ !(cause instanceof ManagedReaderFailure) ||+ (cause.issue.code !== "invalid-blob" &&+ cause.issue.code !== "invalid-row" &&+ cause.issue.code !== "unsupported-signature")+ )+ throw cause;+ return {+ ...cause.issue,+ scope,+ offset:+ cause.issue.offset === null+ ? blobOffset+ : blobOffset + cause.issue.offset,+ };+ }+};+const CALLING_CONVENTION_NAMES = new Map([[0, "default"],[1, "c"],@@ -745,8 +832,12 @@ type DecodedSignature = Omit<*/const decodeSignature = (blob: Buffer,+ layout?: ManagedMetadataLayout,operands: TypeOperand[] = [],+ issueSink?: (issue: ManagedParseIssue) => void,+ scope = "signature",): DecodedSignature => {+ let kind: DecodedSignature["kind"] = "unknown";try {if (blob.length === 0)throw managedFailure("invalid-blob", "signature", "empty signature", 0);@@ -754,7 +845,11 @@ const decodeSignature = (// 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", { operands });+ kind = "field";+ const fieldType = readTypeSignature(blob, 1, "field", {+ operands,+ ...(layout === undefined ? {} : { layout }),+ });return {kind: "field",parse_status: fieldType.next === blob.length ? "decoded" : "partial",@@ -769,14 +864,17 @@ const decodeSignature = (};}const header = readMethodSignatureHeader(blob, 0, "member");+ kind = "method";const returnType = readTypeSignature(blob, header.next, "return", {operands,+ ...(layout === undefined ? {} : { layout }),});let offset = returnType.next;const parameters: string[] = [];for (let index = 0; index < header.parameterCount; index += 1) {const parameter = readTypeSignature(blob, offset, "parameter", {operands,+ ...(layout === undefined ? {} : { layout }),});parameters.push(parameter.value);offset = parameter.next;@@ -796,11 +894,14 @@ const decodeSignature = (if (!(cause instanceof ManagedReaderFailure)) throw cause;if (cause.issue.code !== "invalid-blob" &&+ cause.issue.code !== "invalid-row" &&cause.issue.code !== "unsupported-signature")throw cause;+ if (cause.issue.code === "invalid-row")+ issueSink?.({ ...cause.issue, scope });return {- kind: "unknown",+ kind: cause.issue.code === "invalid-row" ? kind : "unknown",parse_status:cause.issue.code === "unsupported-signature"? "unsupported"@@ -883,20 +984,64 @@ const resolvedSha256 = (return hash.digest("hex");};-export const signature = (+const projectSignature = (blob: Buffer,- rawSha256?: string,- typeName: SignatureTypeName = () => null,+ rawSha256: string | undefined,+ typeName: SignatureTypeName,+ decoded: DecodedSignature,+ operands: readonly TypeOperand[],): ManagedSignature => {- const operands: TypeOperand[] = [];- const decoded = decodeSignature(blob, operands);return {raw_length: blob.length,raw_sha256: rawSha256 ?? sha256Bytes(blob),resolved_sha256:- decoded.kind === "unknown"+ decoded.kind === "unknown" || decoded.parse_status === "malformed"? null: resolvedSha256(blob, operands, typeName),...decoded,};};++/** Standalone signature decoding used by tests and signature identity utilities. */+export const signature = (+ blob: Buffer,+ rawSha256?: string,+ typeName: SignatureTypeName = () => null,+): ManagedSignature => {+ const operands: TypeOperand[] = [];+ return projectSignature(+ blob,+ rawSha256,+ typeName,+ decodeSignature(blob, undefined, operands),+ operands,+ );+};++/** Decode a metadata-owned signature while validating referenced table rows. */+export const metadataSignature = (+ blob: Buffer,+ {+ rawSha256,+ typeName,+ layout,+ issues,+ scope,+ }: {+ readonly rawSha256: string;+ readonly typeName: SignatureTypeName;+ readonly layout: ManagedMetadataLayout;+ readonly issues: ManagedParseIssue[];+ readonly scope: string;+ },+): ManagedSignature => {+ const operands: TypeOperand[] = [];+ const decoded = decodeSignature(+ blob,+ layout,+ operands,+ (issue) => issues.push(issue),+ scope,+ );+ return projectSignature(blob, rawSha256, typeName, decoded, operands);+};diff --git a/src/dotnet/ManagedMemberInstructionDecoder.ts b/src/dotnet/ManagedMemberInstructionDecoder.tsindex 80c3ae908..5f8d814de 100644--- a/src/dotnet/ManagedMemberInstructionDecoder.ts+++ b/src/dotnet/ManagedMemberInstructionDecoder.ts@@ -241,15 +241,13 @@ const OPCODES = new Map<]);const tokenKind = (token: string): ManagedInstructionAnchor["operand_kind"] => {- if (- token.startsWith("0x06") ||- token.startsWith("0x0a") ||- token.startsWith("0x2b")- )- return "method";+ if (token.startsWith("0x06") || token.startsWith("0x2b")) return "method";if (token.startsWith("0x04")) return "field";if (token.startsWith("0x70")) return "string";if (token.startsWith("0x11")) return "signature";+ // MemberRef rows can name either fields or methods; the table alone cannot+ // establish the kind. Callers with parsed metadata may supply that fact.+ if (token.startsWith("0x0a")) return "token";if (token.startsWith("0x01") ||token.startsWith("0x02") ||@@ -413,6 +411,7 @@ const readOperand = (il: Buffer,offset: number,kind: string,+ memberRefKind?: (token: string) => "field" | "method" | undefined,): OperandResult => {const fixedOperand = FIXED_OPERAND_READERS.get(kind);if (fixedOperand !== undefined) return fixedOperand.read(il, offset);@@ -430,7 +429,10 @@ const readOperand = (const token = `0x${raw.toString(16).padStart(8, "0")}`;return {next: offset + TOKEN_OPERAND_WIDTH,- anchorKind: TOKEN_OPERAND_KINDS.get(kind) ?? tokenKind(token),+ anchorKind:+ TOKEN_OPERAND_KINDS.get(kind) ??+ (kind === "token" ? memberRefKind?.(token) : undefined) ??+ tokenKind(token),value: token,};};@@ -438,6 +440,7 @@ const readOperand = (export const decodeInstructions = (il: Buffer,admitInstruction?: (offset: number) => void,+ memberRefKind?: (token: string) => "field" | "method" | undefined,): {readonly parsed: readonly ParsedInstruction[];readonly instructionStarts: readonly number[];@@ -473,7 +476,12 @@ export const decodeInstructions = (issue = `Instruction ${descriptor.name} at IL offset ${String(start)} leaves method body`;break;}- const operand = readOperand(il, offset, descriptor.operand);+ const operand = readOperand(+ il,+ offset,+ descriptor.operand,+ memberRefKind,+ );// Charge each actual instruction before growing the decoded arrays.// A multi-byte operand must not consume a full record per raw IL byte.admitInstruction?.(start);diff --git a/src/dotnet/ManagedMemberRows.ts b/src/dotnet/ManagedMemberRows.tsindex 1e69d3d29..1ab876e31 100644--- a/src/dotnet/ManagedMemberRows.ts+++ b/src/dotnet/ManagedMemberRows.ts@@ -8,7 +8,7 @@ import type { ManagedPeLayout } from "./ManagedPeReader.js";import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";import {- signature,+ metadataSignature,signatureGenericArity,type ManagedCallEdge,type ManagedExportedType,@@ -28,7 +28,10 @@ import {readMetadataBlob,readMetadataString,} from "./ManagedMetadataHeaps.js";-import { readManagedValue } from "./ManagedReaderFailure.js";+import {+ appendManagedParseIssues,+ readManagedValue,+} from "./ManagedReaderFailure.js";import { methodBody } from "./ManagedMethodBodyReader.js";import { memberDeclaringTypeRowLookup } from "./ManagedMemberOwnership.js";import type { TypeMemberListFacts } from "./ManagedTypeMemberLists.js";@@ -106,7 +109,13 @@ export const parseFields = (declaring_type: declared?.fullName ?? null,name,flags,- signature: budgetedSignature(sig, layout, signatureTypeName),+ signature: budgetedSignature(+ sig,+ layout,+ signatureTypeName,+ issues,+ `Field:${token}.signature`,+ ),});}, issues);}@@ -240,7 +249,13 @@ export const parseMemberRefs = (layout.rowCounts,);const parentName = typeName(parentToken);- const decoded = budgetedSignature(sig, layout, signatureTypeName);+ const decoded = budgetedSignature(+ sig,+ layout,+ signatureTypeName,+ issues,+ `MemberRef:${token}.signature`,+ );refs.push({token,row_offset: cursor.start,@@ -267,6 +282,7 @@ interface ParseMethodsInput {readonly pe: ManagedPeLayout;readonly ranges: readonly TypeRange[];readonly signatureTypeName: SignatureTypeName;+ readonly memberRefKinds: ReadonlyMap<string, "field" | "method">;readonly memberLists: TypeMemberListFacts;readonly selected?: SelectedTypeTokens;readonly methodOffset?: number;@@ -279,6 +295,7 @@ export const parseMethods = ({pe,ranges,signatureTypeName,+ memberRefKinds,memberLists,selected = null,methodOffset = 0,@@ -347,18 +364,25 @@ export const parseMethods = ({layout.blob.size,);cursor.readIndex(layout.tableIndexSize(8));- const decoded = budgetedSignature(sig, layout, signatureTypeName);+ const decoded = budgetedSignature(+ sig,+ layout,+ signatureTypeName,+ issues,+ `MethodDef:${token}.signature`,+ );core.set(token, {...member,genericArity: signatureGenericArity(decoded),});- const read = methodBody(- bytes,- pe,- rva,- { implFlags, flags },- managedDecodeBudget(layout),- );+ const read = methodBody(bytes, pe, rva, {+ implementation: { implFlags, flags },+ budget: managedDecodeBudget(layout),+ metadataLayout: layout,+ methodToken: token,+ memberRefKinds,+ });+ appendManagedParseIssues(issues, read.issues);if (!read.scanned) unscannedMethods += 1;methods.push({token,@@ -490,12 +514,20 @@ const budgetedSignature = (bytes: Buffer,layout: ManagedMetadataLayout,signatureTypeName: SignatureTypeName,-): ReturnType<typeof signature> => {+ issues: ManagedParseIssue[],+ scope: string,+): ReturnType<typeof metadataSignature> => {const budget = managedDecodeBudget(layout);budget.admitTransient(bytes.length * 256, layout.blob.offset);try {return admitManagedProjection(- signature(bytes, budget.digest(bytes, "sha256"), signatureTypeName),+ metadataSignature(bytes, {+ rawSha256: budget.digest(bytes, "sha256"),+ typeName: signatureTypeName,+ layout,+ issues,+ scope,+ }),budget,);} finally {diff --git a/src/dotnet/ManagedMethodBodyReader.ts b/src/dotnet/ManagedMethodBodyReader.tsindex e30463910..55988fed3 100644--- a/src/dotnet/ManagedMethodBodyReader.ts+++ b/src/dotnet/ManagedMethodBodyReader.ts@@ -9,8 +9,15 @@ import {parseExceptionRegions,} from "./ManagedMemberInstructionDecoder.js";import { validateExceptionRegionRanges } from "./ManagedExceptionRegionValidation.js";-import { sha256Bytes } from "./ManagedMetadataHeaps.js";+import {+ metadataRowCursor,+ readMetadataBlob,+ sha256Bytes,+} from "./ManagedMetadataHeaps.js";+import { validateLocalSignature } from "./ManagedMemberInspectorCore.js";import { ManagedReaderFailure } from "./ManagedReaderFailure.js";+import type { ManagedMetadataLayout } from "./ManagedMetadataLayout.js";+import type { ManagedParseIssue } from "../domain/managed/managedArtifact.js";const bodyStatus = (decodedIssue: string | null,@@ -66,34 +73,51 @@ const readMethodBodyHeader = (};};+export interface MethodBodyContext {+ readonly implementation: {+ readonly implFlags: number;+ readonly flags: number;+ };+ readonly budget: ManagedDecodeBudget;+ readonly metadataLayout: ManagedMetadataLayout;+ readonly methodToken: string;+ readonly memberRefKinds: ReadonlyMap<string, "field" | "method">;+}+/** Decode admitted managed CIL, retaining unavailable implementation metadata as partial. */export const methodBody = (bytes: Buffer,pe: ManagedPeLayout,rva: number,- implementation: { readonly implFlags: number; readonly flags: number } = {- implFlags: 0,- flags: 0,- },- budget?: ManagedDecodeBudget,+ context: MethodBodyContext,): {readonly body: ManagedMethodBody;+ readonly issues: readonly ManagedParseIssue[];/*** Whether every CIL instruction was decoded, independent of exception-region* validity. A body with no CIL, absent or native, has nothing left unscanned.*/readonly scanned: boolean;} => {+ const issues: ManagedParseIssue[] = [];// Without CIL there is nothing left unscanned.if (rva === 0)- return { body: emptyMethodBody(rva, "absent", null), scanned: true };+ return {+ body: emptyMethodBody(rva, "absent", null),+ scanned: true,+ issues,+ };const native =- (implementation.implFlags & 7) !== 0 ||- (implementation.flags & 0x2000) !== 0;+ (context.implementation.implFlags & 7) !== 0 ||+ (context.implementation.flags & 0x2000) !== 0;if (native) {const issue ="CIL decoding is unavailable for native, runtime, unmanaged, or P/Invoke implementations";- return { body: emptyMethodBody(rva, "partial", issue), scanned: true };+ return {+ body: emptyMethodBody(rva, "partial", issue),+ scanned: true,+ issues,+ };}try {const offset = pe.rvaToOffset(rva, 1, "method.body");@@ -113,9 +137,8 @@ export const methodBody = (// separate instruction for every byte. Retained output is charged below.const decoded = decodeInstructions(il,- budget === undefined- ? undefined- : (start) => budget.admitTransient(256, ilOffset + start),+ (start) => context.budget.admitTransient(256, ilOffset + start),+ (token) => context.memberRefKinds.get(token),);const opcodeCounts: Record<string, number> = {};for (const instruction of decoded.parsed)@@ -148,17 +171,75 @@ export const methodBody = (bytes,sectionOffset,offset + methodExtent,- budget,+ context.budget,),header.ilSize,decoded.instructionStarts,): null;- const status = bodyStatus(- decoded.issue,- decoded.truncated,- exceptionRegions,- );+ let localSigIssue: string | null = null;+ let localSigFailure: "malformed" | "partial" | null = null;+ if (header.localSig !== 0) {+ const table = header.localSig >>> 24;+ const row = header.localSig & 0x00ff_ffff;+ const rows = context.metadataLayout.table(17)?.rowCount ?? 0;+ if (table !== 17 || row === 0 || row > rows) {+ localSigIssue = `LocalVarSigTok 0x${header.localSig.toString(16).padStart(8, "0")} does not name an existing StandAloneSig row`;+ localSigFailure = "malformed";+ issues.push({+ code: "invalid-row",+ scope: `MethodDef:${context.methodToken}.body.local_var_sig_token`,+ offset: offset + 8,+ detail: localSigIssue,+ });+ } else {+ const signatureScope = `metadata.StandAloneSig:0x${header.localSig.toString(16).padStart(8, "0")}.signature`;+ try {+ const cursor = metadataRowCursor(+ bytes,+ context.metadataLayout,+ 17,+ row,+ );+ const blob = readMetadataBlob(+ bytes,+ context.metadataLayout,+ cursor.readIndex(context.metadataLayout.blobIndexSize),+ context.metadataLayout.blob.size,+ );+ const signatureIssue = validateLocalSignature(+ context.metadataLayout,+ blob,+ {+ scope: signatureScope,+ blobOffset: blob.byteOffset - bytes.byteOffset,+ },+ context.budget,+ );+ if (signatureIssue !== null) {+ localSigIssue = signatureIssue.detail;+ localSigFailure =+ signatureIssue.code === "unsupported-signature"+ ? "partial"+ : "malformed";+ issues.push(signatureIssue);+ }+ } catch (cause: unknown) {+ if (+ cause instanceof ManagedReaderFailure &&+ cause.issue.code === "resource-limit"+ )+ throw cause;+ if (!(cause instanceof ManagedReaderFailure)) throw cause;+ localSigIssue = cause.issue.detail;+ localSigFailure = "malformed";+ issues.push({ ...cause.issue, scope: signatureScope });+ }+ }+ }+ const status =+ localSigFailure ??+ bodyStatus(decoded.issue, decoded.truncated, exceptionRegions);const body: ManagedMethodBody = {status,header_format: header.format,@@ -181,6 +262,7 @@ export const methodBody = (anchors,exception_regions: exceptionRegions?.regions ?? [],issue:+ localSigIssue ??decoded.issue ??(exceptionRegions?.status === "malformed"? exceptionRegions.issue@@ -190,8 +272,9 @@ export const methodBody = (: null),};return {- body: budget === undefined ? body : admitManagedProjection(body, budget),+ body: admitManagedProjection(body, context.budget),scanned: decoded.issue === null && decoded.truncated === 0,+ issues,};} catch (cause: unknown) {if (@@ -211,10 +294,11 @@ export const methodBody = (cause instanceof Error ? cause.message : "Method body parse failed",),scanned: false,+ issues,};} finally {// IL and exception-section bookkeeping coexist until the body is built.- budget?.releaseTransient();+ context.budget.releaseTransient();}};diff --git a/src/dotnet/ManagedPe.fixture.ts b/src/dotnet/ManagedPe.fixture.tsindex 64a212708..7c61a6d5a 100644--- a/src/dotnet/ManagedPe.fixture.ts+++ b/src/dotnet/ManagedPe.fixture.ts@@ -36,6 +36,8 @@ interface ManagedPeFixtureOptions {readonly methodSpecMethods?: readonly number[];/** Instantiation blob shared by every MethodSpec row. */readonly methodSpecInstantiation?: Buffer;+ /** StandAloneSig LocalVarSig blobs, one row each. */+ readonly standaloneSignatures?: readonly Buffer[];/** TypeSpec signature blobs, one TypeSpec row each. */readonly typeSpecSignatures?: readonly Buffer[];/** Raw ResolutionScope coded value of the TypeRef row; null by default. */@@ -612,6 +614,7 @@ interface FixtureMetadataRowContext {readonly attributeBlob: number;readonly typeSpecSignatures: readonly number[];readonly methodSpecInstantiation: number;+ readonly standaloneSignatures: readonly number[];};readonly heapSizes: {readonly strings: MetadataIndexSize;@@ -735,6 +738,16 @@ const specTables = (heapSizes: FixtureMetadataRowContext["heapSizes"],widths: FixtureIndexWidths,): readonly (readonly [number, readonly Buffer[]])[] => [+ ...(indexes.standaloneSignatures.length === 0+ ? []+ : ([+ [+ 17,+ indexes.standaloneSignatures.map((signature) =>+ metadataIndex(signature, heapSizes.blobs),+ ),+ ],+ ] as const)),...(indexes.typeSpecSignatures.length === 0? []: ([@@ -782,6 +795,7 @@ const fixtureIndexWidths = ({...(indexes.pinvokeModuleName === null ? [] : ([[26, 1]] as const)),...(indexes.pinvokeImportName === null ? [] : ([[28, 1]] as const)),[27, indexes.typeSpecSignatures.length],+ [17, indexes.standaloneSignatures.length],[32, options.assemblyRowCount ?? 1],[35, referenceStringIndexes.length],[39, indexes.exportedTypes.length],@@ -1034,6 +1048,9 @@ const buildManagedFixtureMetadata = (const methodSignature = blobs.add(options.methodSignature ?? Buffer.from([0x00, 0x00, 0x01]),);+ const standaloneSignatures = (options.standaloneSignatures ?? []).map(+ (signature) => blobs.add(signature),+ );const referenceBlobs = referenceBlobIndexes(blobs, options);const attributeBlob = blobs.add(fixedStringAttributeBlob(@@ -1068,6 +1085,7 @@ const buildManagedFixtureMetadata = (tokenBlob,fieldSignature,methodSignature,+ standaloneSignatures,attributeBlob,...referenceBlobs,},diff --git a/tests/boundary/cli/managedMemberSummaryCli.test.ts b/tests/boundary/cli/managedMemberSummaryCli.test.tsindex 7ffa4ca42..37d6bb57c 100644--- a/tests/boundary/cli/managedMemberSummaryCli.test.ts+++ b/tests/boundary/cli/managedMemberSummaryCli.test.ts@@ -83,6 +83,39 @@ cliTest(},);+cliTest(+ "classifies a field MemberRef loaded by ldtoken in the CLI inspection",+ async ({ cli }) => {+ const root = await createTestTempDirectory("rea-managed-ldtoken-cli-");+ const path = join(root, "field-token.dll");+ const il = Buffer.from([0xd0, 1, 0, 0, 0x0a, 0x26, 0x2a]);+ await writeFile(+ path,+ buildManagedPeFixture({+ targetFramework: null,+ memberRefName: "Counter",+ memberRefParentRaw: 8,+ memberRefSignature: Buffer.from([0x06, 0x08]),+ ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),+ }),+ );+ const inspected = await cli.run({+ arguments: ["inspect-managed-members", path, "--json"],+ });+ expect(inspected.exitCode).toBe(0);+ const evidence = parseEvidence(inspected.json);+ const result = managedMemberInspectionSchema.parse(+ evidence.normalized_result,+ );+ expect(result.member_refs[0]?.signature.kind).toBe("field");+ expect(result.methods[0]?.body.anchors[0]).toMatchObject({+ opcode: "ldtoken",+ operand_kind: "field",+ operand: "0x0a000001",+ });+ },+);+cliTest("retains complete member Evidence for exact CLI pages after process exit and target removal",async ({ cli }) => {@@ -371,6 +404,39 @@ cliTest(},);+cliTest(+ "preserves decoded CIL and reports invalid LocalVarSigTok through CLI Evidence",+ async ({ cli }) => {+ const root = await createTestTempDirectory("rea-member-locals-token-");+ const path = join(root, "fixture.dll");+ const body = Buffer.alloc(13);+ body.writeUInt16LE(0x3003, 0);+ body.writeUInt16LE(8, 2);+ body.writeUInt32LE(1, 4);+ body.writeUInt32LE(0x06000001, 8);+ body[12] = 0x2a;+ await writeFile(path, buildManagedPeFixture({ ilBody: body }));++ const result = await cli.run({+ arguments: ["inspect-managed-members", path, "--json"],+ });+ expect(result.exitCode).toBe(0);+ const evidence = parseEvidence(result.json);+ const inspection = managedMemberInspectionSchema.parse(+ evidence.normalized_result,+ );+ expect(inspection.methods[0]?.body).toMatchObject({+ status: "malformed",+ local_var_sig_token: "0x06000001",+ anchors: [expect.objectContaining({ opcode: "ret" })],+ });+ expect(inspection.coverage).toMatchObject({+ state: "partial",+ issues: [expect.objectContaining({ code: "invalid-row" })],+ });+ },+);+cliTest.for((process.platform === "win32"? (["event"] as const)diff --git a/tests/boundary/mcp/managedMcp.test.ts b/tests/boundary/mcp/managedMcp.test.tsindex 6328dd162..da68436c3 100644--- a/tests/boundary/mcp/managedMcp.test.ts+++ b/tests/boundary/mcp/managedMcp.test.ts@@ -21,9 +21,45 @@ import { ManagedStaticProvider } from "../../../src/dotnet/ManagedStaticProviderimport { createServer } from "../../../src/server/createServer.js";import { buildManagedPeFixture } from "../../../src/dotnet/ManagedPe.fixture.js";import { elf } from "../../../src/domain/binaryTarget.fixture.js";+import { managedMemberInspectionSchema } from "../../../src/domain/managed/managedArtifact.js";type ManagedOutputAssertion = Awaited<ReturnType<typeof createOutputAssertion>>;+const fieldTokenFixture = (): Buffer => {+ const il = Buffer.from([0xd0, 1, 0, 0, 0x0a, 0x26, 0x2a]);+ return buildManagedPeFixture({+ targetFramework: null,+ memberRefName: "Counter",+ memberRefParentRaw: 8,+ memberRefSignature: Buffer.from([0x06, 0x08]),+ ilBody: Buffer.concat([Buffer.from([(il.length << 2) | 2]), il]),+ });+};++const assertFieldMemberRefToken = async (+ client: Client,+ path: string,+): Promise<void> => {+ const fieldToken = structured(+ await client.callTool({+ name: "inspect_managed_members",+ arguments: { path },+ }),+ );+ const inspection = managedMemberInspectionSchema.parse(+ fieldToken.normalized_result,+ );+ expect(inspection.member_refs[0]?.signature).toMatchObject({+ kind: "field",+ parse_status: "decoded",+ });+ expect(inspection.methods[0]?.body.anchors[0]).toMatchObject({+ opcode: "ldtoken",+ operand_kind: "field",+ operand: "0x0a000001",+ });+};+it("runs every managed static inspection independently of an active native target", async () => {const directory = await createTestTempDirectory("rea-managed-independent-mcp-",@@ -31,6 +67,7 @@ it("runs every managed static inspection independently of an active native targeconst path = join(directory, "fixture.dll");const otherPath = join(directory, "other-fixture.dll");const partialPath = join(directory, "partial-method.dll");+ const fieldTokenPath = join(directory, "field-token.dll");await writeFile(path, buildManagedPeFixture());await writeFile(otherPath, buildManagedPeFixture({ methodName: "Other" }));await writeFile(@@ -40,6 +77,7 @@ it("runs every managed static inspection independently of an active native targeilBody: Buffer.from([0x06, 0x2a]),}),);+ await writeFile(fieldTokenPath, fieldTokenFixture());const session = composeBinarySession(new AnalysisProviderRegistry([]), [new ManagedStaticProvider(),]);@@ -161,6 +199,7 @@ it("runs every managed static inspection independently of an active native targecoverage: { state: "partial" },},});+ await assertFieldMemberRefToken(client, fieldTokenPath);} finally {await Promise.all([client.close(), server.close()]);await session.close();diff --git a/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts b/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.tsindex de09facb7..ac5f528cd 100644--- a/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts+++ b/tests/boundary/providers/managed/managedMemberComparisonPartialBodies.test.ts@@ -164,3 +164,39 @@ describe("managed member partial body comparison", () => {});});});++describe("managed locals signature comparison", () => {+ it("compares observed presence but not build-local tokens", () => {+ const inspectWithLocals = (token: number, path: string) => {+ const body = Buffer.alloc(13);+ body.writeUInt16LE(0x3003, 0);+ body.writeUInt16LE(8, 2);+ body.writeUInt32LE(1, 4);+ body.writeUInt32LE(token, 8);+ body[12] = 0x2a;+ const standaloneSignatures = Array.from(+ { length: token & 0x00ff_ffff },+ () => Buffer.from([0x07, 0x01, 0x08]),+ );+ return inspect(+ buildManagedPeFixture({ ilBody: body, standaloneSignatures }),+ path,+ );+ };+ const absent = inspectWithLocals(0, "/tmp/locals-absent.dll");+ const presentOne = inspectWithLocals(0x11000001, "/tmp/locals-one.dll");+ const presentTwo = inspectWithLocals(0x11000002, "/tmp/locals-two.dll");+ expect(presentOne.result.methods[0]?.body.status).toBe("present");+ expect(presentTwo.result.methods[0]?.body.status).toBe("present");+ expect(compareManagedMembers(absent, presentOne).methods[0]).toMatchObject({+ status: "changed",+ dimensions: ["metadata"],+ });+ expect(+ compareManagedMembers(presentOne, presentTwo).methods[0],+ ).toMatchObject({+ status: "unchanged",+ dimensions: [],+ });+ });+});