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(dotnet): name the truncated instruction when an operand leaves the method body (#2704)
Yunzhou Li97268f40ea21
diff --git a/src/dotnet/ManagedCilDecoding.test.ts b/src/dotnet/ManagedCilDecoding.test.tsindex 4ba33f4c9..852762b2c 100644--- a/src/dotnet/ManagedCilDecoding.test.ts+++ b/src/dotnet/ManagedCilDecoding.test.ts@@ -67,6 +67,30 @@ const managedBodyWithRegion = ({.methods[0]?.body;};+const fatBody = (il: Buffer) => {+ const header = Buffer.alloc(12);+ header.writeUInt16LE(0x3013, 0);+ header.writeUInt16LE(8, 2);+ header.writeUInt32LE(il.length, 4);+ const bytes = buildManagedPeFixture({+ ilBody: Buffer.concat([header, il]),+ });+ return inspectManagedMembersBytes(bytes, managedPeFixtureTarget(bytes))+ .methods[0]?.body;+};++/** Build a tiny method body whose declared IL extent matches its supplied bytes. */+const tinyBody = (il: readonly number[]) => {+ const bytes = buildManagedPeFixture({+ ilBody: Buffer.from([(il.length << 2) | 0x02, ...il]),+ });+ const inspection = inspectManagedMembersBytes(+ bytes,+ managedPeFixtureTarget(bytes),+ );+ return { body: inspection.methods[0]?.body, coverage: inspection.coverage };+};+describe("managed CIL decoding", () => {it("reads fat method header size from the full flags-and-size word", () => {const il = Buffer.from([@@ -221,6 +245,187 @@ describe("managed CIL decoding", () => {});});+describe("managed operand extent diagnostics", () => {+ it.each([+ [[0x20], 0, "Instruction ldc.i4 at IL offset 0 leaves method body"],+ [+ [0x00, 0x20, 0x01],+ 1,+ "Instruction ldc.i4 at IL offset 1 leaves method body",+ ],+ [[0x2b], 0, "Instruction br.s at IL offset 0 leaves method body"],+ [[0x45, 0x02], 0, "Instruction switch at IL offset 0 leaves method body"],+ [+ [0xfe, 0x09, 0x00],+ 0,+ "Instruction ldarg at IL offset 0 leaves method body",+ ],+ [[0x00, 0xfe], 1, "Two-byte CIL opcode at IL offset 1 leaves method body"],+ ] as const)(+ "reports the instruction and IL offset for tiny IL %j",+ (il, decoded, issue) => {+ const { body, coverage } = tinyBody(il);+ expect(body).toMatchObject({+ status: "malformed",+ header_format: "tiny",+ il_size: il.length,+ decoded_instruction_count: decoded,+ normalized_il_sha256: null,+ issue,+ });+ expect(coverage.state).toBe("partial");+ },+ );++ it.each([+ ["short variable", Buffer.from([0x0e]), "ldarg.s"],+ ["wide variable", Buffer.from([0xfe, 0x09]), "ldarg"],+ ["int32 constant", Buffer.from([0x20]), "ldc.i4"],+ ["int64 constant", Buffer.from([0x21]), "ldc.i8"],+ ["float32 constant", Buffer.from([0x22]), "ldc.r4"],+ ["float64 constant", Buffer.from([0x23]), "ldc.r8"],+ ["short branch", Buffer.from([0x2b]), "br.s"],+ ["long branch", Buffer.from([0x38]), "br"],+ ["prefixed short constant", Buffer.from([0xfe, 0x12]), "unaligned."],+ ["string token", Buffer.from([0x72]), "ldstr"],+ ["type token", Buffer.from([0x71]), "ldobj"],+ ["field token", Buffer.from([0x7b]), "ldfld"],+ ["method token", Buffer.from([0x28]), "call"],+ ] as const)(+ "reports a truncated %s operand at its own instruction",+ (_label, il, name) => {+ expect(fatBody(il)).toMatchObject({+ status: "malformed",+ decoded_instruction_count: 0,+ normalized_il_sha256: null,+ issue: `Instruction ${name} at IL offset 0 leaves method body`,+ });+ },+ );++ // A width declared too small still passes the extent check when no operand+ // bytes are present, so the zero-byte cases above cannot catch it. Supplying+ // one byte less than the real width makes a wrong width let the read run,+ // which surfaces as the raw Buffer error rather than the diagnostic.+ it.each([+ ["wide variable", Buffer.from([0xfe, 0x09]), 2, "ldarg"],+ ["int32 constant", Buffer.from([0x20]), 4, "ldc.i4"],+ ["int64 constant", Buffer.from([0x21]), 8, "ldc.i8"],+ ["float32 constant", Buffer.from([0x22]), 4, "ldc.r4"],+ ["float64 constant", Buffer.from([0x23]), 8, "ldc.r8"],+ ["long branch", Buffer.from([0x38]), 4, "br"],+ ["method token", Buffer.from([0x28]), 4, "call"],+ ["type token", Buffer.from([0x71]), 4, "ldobj"],+ ["string token", Buffer.from([0x72]), 4, "ldstr"],+ ["field token", Buffer.from([0x7b]), 4, "ldfld"],+ ] as const)(+ "rejects a %s operand one byte short of its declared width",+ (_label, opcode, width, name) => {+ expect(+ fatBody(Buffer.concat([opcode, Buffer.alloc(width - 1)])),+ ).toMatchObject({+ status: "malformed",+ decoded_instruction_count: 0,+ normalized_il_sha256: null,+ issue: `Instruction ${name} at IL offset 0 leaves method body`,+ });+ },+ );++ // The extent check must also reject nothing that fits, so every multi-byte+ // width is exercised at exactly its own size with a known value. Each body+ // ends at its operand, so a width declared too large turns a valid operand+ // into the leaves-method-body diagnostic and these value assertions catch it.+ // The -0 constants keep the floating-point sign fix covered through this same+ // path.+ it.each([+ ["wide variable", [0xfe, 0x09], [0x01, 0x00], "variable", "1"],+ ["int32 constant", [0x20], [0x01, 0x00, 0x00, 0x00], "constant", "1"],+ [+ "int64 constant",+ [0x21],+ [0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],+ "constant",+ "1",+ ],+ ["float32 constant", [0x22], [0x00, 0x00, 0x00, 0x80], "constant", "-0"],+ [+ "float64 constant",+ [0x23],+ [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80],+ "constant",+ "-0",+ ],+ ["long branch", [0x38], [0x00, 0x00, 0x00, 0x00], "branch", "5"],+ ["method token", [0x28], [0x01, 0x00, 0x00, 0x00], "method", "0x00000001"],+ ["type token", [0x71], [0x02, 0x00, 0x00, 0x00], "type", "0x00000002"],+ ["string token", [0x72], [0x03, 0x00, 0x00, 0x00], "string", "0x00000003"],+ ["field token", [0x7b], [0x04, 0x00, 0x00, 0x00], "field", "0x00000004"],+ ] as const)(+ "decodes a %s operand at exactly its declared width",+ (_label, opcode, operand, operandKind, value) => {+ expect(fatBody(Buffer.from([...opcode, ...operand]))).toMatchObject({+ status: "present",+ issue: null,+ decoded_instruction_count: 1,+ anchors: [{ il_offset: 0, operand_kind: operandKind, operand: value }],+ });+ },+ );++ it("reports a switch whose target table is missing", () => {+ expect(+ fatBody(Buffer.from([0x00, 0x45, 0x02, 0x00, 0x00, 0x00])),+ ).toMatchObject({+ status: "malformed",+ decoded_instruction_count: 1,+ opcode_counts: { nop: 1 },+ issue: "Instruction switch at IL offset 1 leaves method body",+ });+ });++ it("reports a switch whose target count is itself truncated", () => {+ expect(fatBody(Buffer.from([0x45, 0x02]))).toMatchObject({+ status: "malformed",+ decoded_instruction_count: 0,+ issue: "Instruction switch at IL offset 0 leaves method body",+ });+ });++ it("preserves instructions decoded before a truncated operand", () => {+ expect(fatBody(Buffer.from([0x00, 0x20]))).toMatchObject({+ status: "malformed",+ il_size: 2,+ decoded_instruction_count: 1,+ opcode_counts: { nop: 1 },+ issue: "Instruction ldc.i4 at IL offset 1 leaves method body",+ });+ });++ it("keeps a complete operand-bearing body decodable", () => {+ expect(+ fatBody(Buffer.from([0x00, 0x20, 0x01, 0x00, 0x00, 0x00, 0x2a])),+ ).toMatchObject({+ status: "present",+ decoded_instruction_count: 3,+ opcode_counts: { nop: 1, "ldc.i4": 1, ret: 1 },+ issue: null,+ });+ });++ it("still decodes a switch whose targets fit", () => {+ const il = Buffer.from([+ 0x00, 0x45, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2a,+ ]);+ expect(fatBody(il)).toMatchObject({+ status: "present",+ il_size: il.length,+ opcode_counts: { nop: 1, switch: 1, ret: 1 },+ issue: null,+ });+ });+});+describe("managed exception region bounds", () => {it("marks out-of-method ranges malformed and preserves the raw EH clause", () => {expect(@@ -535,41 +740,3 @@ describe("managed exception section decoding", () => {});});});--describe("managed CIL truncated operands", () => {- const tinyBody = (il: readonly number[]) => {- const bytes = buildManagedPeFixture({- ilBody: Buffer.from([(il.length << 2) | 0x02, ...il]),- });- const inspection = inspectManagedMembersBytes(- bytes,- managedPeFixtureTarget(bytes),- );- return { body: inspection.methods[0]?.body, coverage: inspection.coverage };- };-- it.each([- [[0x20], 0, "Instruction ldc.i4 at IL offset 0 leaves method body"],- [- [0x00, 0x20, 0x01],- 1,- "Instruction ldc.i4 at IL offset 1 leaves method body",- ],- [[0x2b], 0, "Instruction br.s at IL offset 0 leaves method body"],- [[0x45, 0x02], 0, "Instruction switch at IL offset 0 leaves method body"],- [- [0xfe, 0x09, 0x00],- 0,- "Instruction ldarg at IL offset 0 leaves method body",- ],- [[0x00, 0xfe], 1, "Two-byte CIL opcode at IL offset 1 leaves method body"],- ])("names the instruction and IL offset for IL %j", (il, decoded, issue) => {- const { body, coverage } = tinyBody(il);- expect(body).toMatchObject({- status: "malformed",- decoded_instruction_count: decoded,- issue,- });- expect(coverage.state).toBe("partial");- });-});diff --git a/src/dotnet/ManagedMemberInstructionDecoder.ts b/src/dotnet/ManagedMemberInstructionDecoder.tsindex 01c2b7814..0c04b7a36 100644--- a/src/dotnet/ManagedMemberInstructionDecoder.ts+++ b/src/dotnet/ManagedMemberInstructionDecoder.ts@@ -271,82 +271,101 @@ type OperandReader = (il: Buffer, offset: number) => OperandResult;const floatingPointOperand = (value: number): string =>Object.is(value, -0) ? "-0" : String(value);-const FIXED_OPERAND_READERS = new Map<string, OperandReader>([+/**+ * A fixed-width operand declares its byte width next to its reader so the+ * extent check can bound the read before any value is consumed. Keeping both+ * facts in one entry is what stops the width and the reader from drifting.+ */+type FixedOperand = {+ readonly width: number;+ readonly read: OperandReader;+};++const fixed = (width: number, read: OperandReader): FixedOperand => ({+ width,+ read,+});++const FIXED_OPERAND_READERS = new Map<string, FixedOperand>([["none",- (_il, offset) => ({ next: offset, anchorKind: "none", value: null }),+ fixed(0, (_il, offset) => ({+ next: offset,+ anchorKind: "none",+ value: null,+ })),],["short-var",- (il, offset) => ({+ fixed(1, (il, offset) => ({next: offset + 1,anchorKind: "variable",value: String(il.readUInt8(offset)),- }),+ })),],["var",- (il, offset) => ({+ fixed(2, (il, offset) => ({next: offset + 2,anchorKind: "variable",value: String(il.readUInt16LE(offset)),- }),+ })),],["short-i",- (il, offset) => ({+ fixed(1, (il, offset) => ({next: offset + 1,anchorKind: "constant",value: String(il.readInt8(offset)),- }),+ })),],["i",- (il, offset) => ({+ fixed(4, (il, offset) => ({next: offset + 4,anchorKind: "constant",value: String(il.readInt32LE(offset)),- }),+ })),],["i8",- (il, offset) => ({+ fixed(8, (il, offset) => ({next: offset + 8,anchorKind: "constant",value: il.readBigInt64LE(offset).toString(),- }),+ })),],["r4",- (il, offset) => ({+ fixed(4, (il, offset) => ({next: offset + 4,anchorKind: "constant",value: floatingPointOperand(il.readFloatLE(offset)),- }),+ })),],["r8",- (il, offset) => ({+ fixed(8, (il, offset) => ({next: offset + 8,anchorKind: "constant",value: floatingPointOperand(il.readDoubleLE(offset)),- }),+ })),],["short-branch",- (il, offset) => ({+ fixed(1, (il, offset) => ({next: offset + 1,anchorKind: "branch",value: String(offset + 1 + il.readInt8(offset)),- }),+ })),],["branch",- (il, offset) => ({+ fixed(4, (il, offset) => ({next: offset + 4,anchorKind: "branch",value: String(offset + 4 + il.readInt32LE(offset)),- }),+ })),],]);@@ -361,13 +380,42 @@ const TOKEN_OPERAND_KINDS = new Map<["signature", "signature"],]);+/** Every token operand is a 4-byte metadata token. */+const TOKEN_OPERAND_WIDTH = 4;++/**+ * Bytes the operand at `offset` occupies, or `null` when the extent itself+ * cannot be read from `il`. This is the single extent authority: `readOperand`+ * must never be called for an operand whose extent it cannot bound, so no+ * operand read can leave the method body.+ */+const operandExtent = (+ il: Buffer,+ offset: number,+ kind: string,+): number | null => {+ const fixedOperand = FIXED_OPERAND_READERS.get(kind);+ if (fixedOperand !== undefined) return fixedOperand.width;+ if (kind === "switch") {+ if (offset > il.length - 4) return null;+ return 4 + il.readUInt32LE(offset) * 4;+ }+ return TOKEN_OPERAND_KINDS.has(kind) || kind === "token"+ ? TOKEN_OPERAND_WIDTH+ : 0;+};++/**+ * Read an operand whose extent is already known to fit. `next` is always+ * `offset + operandExtent(il, offset, kind)`; callers bound the read first.+ */const readOperand = (il: Buffer,offset: number,kind: string,): OperandResult => {- const fixed = FIXED_OPERAND_READERS.get(kind);- if (fixed !== undefined) return fixed(il, offset);+ const fixedOperand = FIXED_OPERAND_READERS.get(kind);+ if (fixedOperand !== undefined) return fixedOperand.read(il, offset);if (kind === "switch") {const count = il.readUInt32LE(offset);return {@@ -376,30 +424,15 @@ const readOperand = (value: String(count),};}+ if (!TOKEN_OPERAND_KINDS.has(kind) && kind !== "token")+ return { next: offset, anchorKind: "unknown", value: null };const raw = il.readUInt32LE(offset);const token = `0x${raw.toString(16).padStart(8, "0")}`;- const tokenOperandKind = TOKEN_OPERAND_KINDS.get(kind);- if (tokenOperandKind !== undefined)- return { next: offset + 4, anchorKind: tokenOperandKind, value: token };- if (kind === "token")- return { next: offset + 4, anchorKind: tokenKind(token), value: token };- return { next: offset, anchorKind: "unknown", value: null };-};--/** An operand cut off by the end of the IL body has no decodable value. */-const readOperandWithin = (- il: Buffer,- offset: number,- kind: string,-): OperandResult | undefined => {- try {- return readOperand(il, offset, kind);- } catch (cause: unknown) {- // Buffer reads past the IL body throw RangeError; report it as the- // instruction leaving the method body rather than as a Buffer message.- if (cause instanceof RangeError) return undefined;- throw cause;- }+ return {+ next: offset + TOKEN_OPERAND_WIDTH,+ anchorKind: TOKEN_OPERAND_KINDS.get(kind) ?? tokenKind(token),+ value: token,+ };};export const decodeInstructions = (@@ -432,15 +465,15 @@ export const decodeInstructions = (issue = `Unsupported CIL opcode 0x${code.toString(16)} at IL offset ${String(start)}`;break;}- const operand = readOperandWithin(il, offset, descriptor.operand);- if (- operand === undefined ||- operand.next < offset ||- operand.next > il.length- ) {+ // Bound the operand extent before reading its value. Reading first would+ // throw a raw Buffer RangeError out of a truncated body and replace this+ // diagnostic with the runtime message, losing the instruction identity.+ const extent = operandExtent(il, offset, descriptor.operand);+ if (extent === null || offset + extent > il.length) {issue = `Instruction ${descriptor.name} at IL offset ${String(start)} leaves method body`;break;}+ const operand = readOperand(il, offset, descriptor.operand);// 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);