refactor(test): keep coverage at behavioral boundaries (#474)

* refactor(test): keep coverage at behavioral boundaries

* fix(ci): restore package workflow temp-root classification
This commit is contained in:
morluto
2026-08-11 18:34:32 +08:00
committed by GitHub
parent d65730c4c2
commit d4dc940bd8
117 changed files with 1519 additions and 2419 deletions
@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import {
buildManagedPeFixture,
buildNativePeFixture,
managedPeFixtureTarget,
MANAGED_ARTIFACT_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed artifact failure classification", () => {
it("distinguishes native, malformed, unsupported, and bounded metadata", () => {
const nativeBytes = buildNativePeFixture();
const native = inspectManagedArtifactBytes(
nativeBytes,
managedPeFixtureTarget(nativeBytes),
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
expect(native).toMatchObject({
classification: { status: "not-managed" },
metadata: { status: "absent" },
coverage: { state: "unavailable" },
});
const malformedBytes = buildManagedPeFixture({
corruptMetadataSignature: true,
});
const malformed = inspectManagedArtifactBytes(
malformedBytes,
managedPeFixtureTarget(malformedBytes),
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
expect(malformed.classification.status).toBe("malformed");
expect(malformed.coverage.issues).toEqual([
expect.objectContaining({ code: "invalid-metadata-root" }),
]);
const unsupportedTableBytes = buildManagedPeFixture({
metadataValidMaskExtra: 1n << 50n,
});
const unsupportedTable = inspectManagedArtifactBytes(
unsupportedTableBytes,
managedPeFixtureTarget(unsupportedTableBytes),
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
expect(unsupportedTable.coverage.issues).toEqual([
expect.objectContaining({ code: "invalid-tables" }),
]);
const limitedBytes = buildManagedPeFixture();
const limited = inspectManagedArtifactBytes(
limitedBytes,
managedPeFixtureTarget(limitedBytes),
{ ...MANAGED_ARTIFACT_FIXTURE_LIMITS, maxMetadataBytes: 256 },
);
expect(limited.metadata.status).toBe("partial");
expect(limited.coverage.issues).toEqual([
expect.objectContaining({ code: "limit-exceeded" }),
]);
});
});
+137
View File
@@ -0,0 +1,137 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_ARTIFACT_FIXTURE_LIMITS,
MANAGED_MEMBER_FIXTURE_LIMITS,
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed artifact inventory", () => {
it("inventories module, assembly, framework, references, and resources without loading CLR code", () => {
const resource = Buffer.from("source-owned resource");
const bytes = buildManagedPeFixture({ resourceData: resource });
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
expect(result.classification).toMatchObject({
status: "managed",
runtime_family: "modern-dotnet",
implementation: "cil",
managed_architecture: "anycpu",
});
expect(result.pe.cli).toMatchObject({
flag_names: ["il-only"],
entry_point: { kind: "metadata-token", value: "0x06000001" },
});
expect(result.module).toMatchObject({
name: "Fixture.dll",
mvid: "00112233-4455-6677-8899-aabbccddeeff",
token: "0x00000001",
});
expect(result.assembly).toMatchObject({
name: "Fixture.Managed",
version: "1.2.3.4",
token: "0x20000001",
});
expect(result.target_frameworks).toEqual([".NETCoreApp,Version=v8.0"]);
expect(result.references).toMatchObject({
total: 1,
returned: 1,
complete: true,
items: [expect.objectContaining({ name: "System.Runtime" })],
});
expect(result.resources.items).toEqual([
expect.objectContaining({
name: "Fixture.resources",
embedded: true,
visibility: "private",
data_length: resource.length,
data_sha256: createHash("sha256").update(resource).digest("hex"),
}),
]);
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
});
it("keeps classification evidence complete when caller pages visible references", () => {
const bytes = buildManagedPeFixture({
references: ["System.Runtime", "UnityEngine.CoreModule"],
});
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
{
...MANAGED_ARTIFACT_FIXTURE_LIMITS,
referenceLimit: 1,
},
);
expect(result.classification.runtime_family).toBe("unity-mono");
expect(result.references).toMatchObject({
total: 2,
returned: 1,
complete: false,
});
expect(result.coverage.state).toBe("partial");
expect(result.coverage.issues).toEqual([]);
});
it("accepts CLI metadata GUIDs without RFC UUID version or variant bits", () => {
const bytes = buildManagedPeFixture({
mvid: Buffer.from("3aebc60edc4a544b1f458b4ed40b33b1", "hex"),
});
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
const members = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
const boundaries = inspectManagedNativeBoundariesBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
);
expect(result.module?.mvid).toBe("0ec6eb3a-4adc-4b54-1f45-8b4ed40b33b1");
expect(result.classification.status).toBe("managed");
expect(members.identity_scope.requires_mvid).toBe(result.module?.mvid);
expect(boundaries.identity_scope.requires_mvid).toBe(result.module?.mvid);
});
it("decodes ECMA-335 pointer and byref element types without swapping them", () => {
const bytes = buildManagedPeFixture({
fieldSignature: Buffer.from([0x06, 0x1d, 0x0f, 0x0f, 0x08]),
methodSignature: Buffer.from([
0x00, 0x02, 0x10, 0x08, 0x0f, 0x08, 0x10, 0x0e,
]),
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.fields.items[0]?.signature).toMatchObject({
parse_status: "decoded",
field_type: "i4**[]",
});
expect(result.methods.items[0]?.signature).toMatchObject({
parse_status: "decoded",
return_type: "i4&",
parameter_types: ["i4*", "string&"],
});
});
});
+114
View File
@@ -0,0 +1,114 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed CIL decoding", () => {
it("reads fat method header size from the full flags-and-size word", () => {
const il = Buffer.from([
0x21, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x22, 0x00,
0x00, 0x80, 0x3f, 0x26, 0x23, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf0,
0x3f, 0x26, 0xfe, 0x06, 0x01, 0x00, 0x00, 0x06, 0x26, 0x2a,
]);
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]),
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.methods.items[0]?.body).toMatchObject({
status: "present",
header_format: "fat",
il_size: il.length,
il_sha256: createHash("sha256").update(il).digest("hex"),
opcode_counts: {
"ldc.i8": 1,
pop: 4,
"ldc.r4": 1,
"ldc.r8": 1,
ldftn: 1,
ret: 1,
},
issue: null,
});
});
it("does not normalize reserved CIL opcodes as operand-free instructions", () => {
const bytes = buildManagedPeFixture({
ilBody: Buffer.from([0x0a, 0x24, 0x2a]),
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.methods.items[0]?.body).toMatchObject({
status: "malformed",
il_size: 2,
normalized_il_sha256: null,
decoded_instruction_count: 0,
issue: "Unsupported CIL opcode 0x24 at IL offset 0",
});
});
it("keeps the documented decoded-CIL v1 golden vector stable", () => {
const il = Buffer.from([0x00, 0x2a]);
const tinyBytes = buildManagedPeFixture({
ilBody: Buffer.from([0x0a, ...il]),
});
const fatHeader = Buffer.alloc(12);
fatHeader.writeUInt16LE(0x3013, 0);
fatHeader.writeUInt16LE(32, 2);
fatHeader.writeUInt32LE(il.length, 4);
fatHeader.writeUInt32LE(0x1100_0001, 8);
const fatBytes = buildManagedPeFixture({
ilBody: Buffer.concat([fatHeader, il]),
});
const tiny = inspectManagedMembersBytes(
tinyBytes,
managedPeFixtureTarget(tinyBytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
const fat = inspectManagedMembersBytes(
fatBytes,
managedPeFixtureTarget(fatBytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(tiny.methods.items[0]?.body).toMatchObject({
status: "present",
header_format: "tiny",
max_stack: 8,
init_locals: false,
local_var_sig_token: null,
il_size: 2,
il_sha256: createHash("sha256").update(il).digest("hex"),
normalized_il_sha256:
"5e5fad7741cb44bca3a4f045546b7449990da343f612f5f34c0ca30e9eee0636",
opcode_counts: { nop: 1, ret: 1 },
exception_regions: [],
});
expect(fat.methods.items[0]?.body).toMatchObject({
header_format: "fat",
max_stack: 32,
init_locals: true,
local_var_sig_token: "0x11000001",
il_sha256: tiny.methods.items[0]?.body.il_sha256,
normalized_il_sha256: tiny.methods.items[0]?.body.normalized_il_sha256,
});
});
});
+53
View File
@@ -0,0 +1,53 @@
import { createHash } from "node:crypto";
import { describe, expect, it } from "vitest";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed CIL limits", () => {
it("marks instruction-limited CIL as partial without assigning normalized identity", () => {
const bytes = buildManagedPeFixture();
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{
...MANAGED_MEMBER_FIXTURE_LIMITS,
maxMethodInstructions: 1,
},
);
const il = bytes.subarray(0x0a01, 0x0a0d);
expect(result.metadata.status).toBe("complete");
expect(result.methods.items[0]?.body).toMatchObject({
status: "partial",
il_size: 12,
il_sha256: createHash("sha256").update(il).digest("hex"),
normalized_il_sha256: null,
instruction_count: 1,
decoded_instruction_count: 1,
truncated_instructions: 1,
issue:
"Instruction decode reached max_method_instructions 1 before the end of the method body",
});
expect(result.coverage).toEqual({
state: "partial",
issues: [
{
code: "limit-exceeded",
scope: "method.0x06000001.body.instructions",
offset: 0x0a00,
detail:
"Instruction decode reached max_method_instructions 1 before the end of the method body",
},
],
});
expect(result.limitations.join(" ")).toContain(
"has no normalized CIL identity",
);
});
});
+114
View File
@@ -0,0 +1,114 @@
import { describe, expect, it } from "vitest";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import {
buildManagedPeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed member inspection", () => {
it("inspects metadata members, signatures, CIL hashes, call edges, and field anchors", () => {
const bytes = buildManagedPeFixture();
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.identity_scope).toEqual({
token_identity: "build-local",
requires_artifact_sha256: managedPeFixtureTarget(bytes).sha256,
requires_mvid: "00112233-4455-6677-8899-aabbccddeeff",
});
expect(result.types.items).toEqual([
expect.objectContaining({
token: "0x02000001",
full_name: "Fixture.Program",
field_list: { first_row: 1, last_row: 1, count: 1 },
method_list: { first_row: 1, last_row: 1, count: 1 },
}),
]);
expect(result.fields.items).toEqual([
expect.objectContaining({
token: "0x04000001",
declaring_type: "Fixture.Program",
name: "counter",
signature: expect.objectContaining({
kind: "field",
parse_status: "decoded",
field_type: "i4",
}),
}),
]);
expect(result.methods.items).toEqual([
expect.objectContaining({
token: "0x06000001",
declaring_type: "Fixture.Program",
name: "Main",
rva: 0x2800,
signature: expect.objectContaining({
kind: "method",
parse_status: "decoded",
return_type: "void",
parameter_types: [],
}),
body: expect.objectContaining({
status: "present",
header_format: "tiny",
file_offset: 0x0a00,
il_size: 12,
instruction_count: 4,
decoded_instruction_count: 4,
truncated_instructions: 0,
opcode_counts: { "ldarg.0": 1, ldfld: 1, call: 1, ret: 1 },
anchors: [
{
il_offset: 1,
opcode: "ldfld",
operand_kind: "field",
operand: "0x04000001",
},
{
il_offset: 6,
opcode: "call",
operand_kind: "method",
operand: "0x0a000001",
},
],
}),
}),
]);
expect(result.member_refs.items).toEqual([
expect.objectContaining({
token: "0x0a000001",
name: ".ctor",
signature: expect.objectContaining({
kind: "method",
parse_status: "decoded",
parameter_types: ["string"],
}),
}),
]);
expect(result.call_edges.items).toEqual([
{
caller_token: "0x06000001",
caller: "Fixture.Program.Main",
opcode: "call",
target_token: "0x0a000001",
target_kind: "member-ref",
target_name: ".ctor",
},
]);
expect(result.field_accesses.items).toEqual([
{
method_token: "0x06000001",
method: "Fixture.Program.Main",
opcode: "ldfld",
field_token: "0x04000001",
field_name: "counter",
},
]);
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
});
});
@@ -0,0 +1,119 @@
import { describe, expect, it } from "vitest";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
import {
buildManagedPeFixture,
buildNativePeFixture,
managedPeFixtureTarget,
MANAGED_MEMBER_FIXTURE_LIMITS,
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
} from "./ManagedPe.fixture.js";
describe("managed native boundaries", () => {
it("inspects managed/native PInvoke declarations without verifying native exports", () => {
const bytes = buildManagedPeFixture({
pinvoke: {
moduleName: "user32.dll",
importName: "MessageBoxW",
mappingFlags: 0x0345,
},
readyToRun: true,
});
const result = inspectManagedNativeBoundariesBytes(
bytes,
managedPeFixtureTarget(bytes),
MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS,
);
expect(result.cli_native).toMatchObject({
il_only: true,
ready_to_run_signature: true,
managed_native_header_rva: 0x2700,
managed_native_header_size: 4,
});
expect(result.module_refs.items).toEqual([
{
token: "0x1a000001",
row_offset: expect.any(Number),
name: "user32.dll",
},
]);
expect(result.pinvoke_imports.items).toEqual([
expect.objectContaining({
token: "0x1c000001",
member_token: "0x06000001",
member_kind: "method",
member_name: "Main",
import_name: "MessageBoxW",
import_scope_token: "0x1a000001",
import_scope_name: "user32.dll",
no_mangle: true,
char_set: "unicode",
call_convention: "stdcall",
supports_last_error: true,
verification: "managed-declaration-only",
}),
]);
expect(result.native_implementations.items).toEqual([
expect.objectContaining({
token: "0x06000001",
name: "Main",
pinvoke_declared: true,
boundary_kind: "pinvoke",
body_interpretation: "native-or-runtime",
}),
]);
expect(result.summary).toMatchObject({
module_ref_count: 1,
pinvoke_import_count: 1,
native_implementation_count: 1,
ready_to_run: true,
mixed_mode_or_native_header: true,
});
expect(result.limitations).toContain(
"P/Invoke rows prove managed import declarations only; this inspection does not verify that a native library, export, thunk, or provider-qualified function exists.",
);
});
it("keeps member evidence bounded and typed for pagination and unavailable metadata", () => {
const bytes = buildManagedPeFixture();
const paged = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{
...MANAGED_MEMBER_FIXTURE_LIMITS,
methodLimit: 0 + 1,
instructionAnchorLimit: 1,
},
);
expect(paged.methods).toMatchObject({
total: 1,
returned: 1,
complete: true,
});
expect(paged.methods.items[0]?.body.anchors).toHaveLength(1);
const nativeBytes = buildNativePeFixture();
const native = inspectManagedMembersBytes(
nativeBytes,
managedPeFixtureTarget(nativeBytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(native.metadata.status).toBe("absent");
expect(native.coverage.state).toBe("unavailable");
const malformedBytes = buildManagedPeFixture({
corruptMetadataSignature: true,
});
const malformed = inspectManagedMembersBytes(
malformedBytes,
managedPeFixtureTarget(malformedBytes),
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(malformed.metadata.status).toBe("malformed");
expect(malformed.coverage.issues).toEqual([
expect.objectContaining({ code: "invalid-metadata-root" }),
]);
});
});
+512
View File
@@ -0,0 +1,512 @@
import { createHash } from "node:crypto";
import type { BinaryTarget } from "../domain/binaryTarget.js";
interface ManagedPeFixtureOptions {
readonly cliFlags?: number;
readonly corruptMetadataSignature?: boolean;
readonly fieldName?: string;
readonly fieldSignature?: Buffer;
readonly ilBody?: Buffer;
readonly metadataValidMaskExtra?: bigint;
readonly methodName?: string;
readonly methodSignature?: Buffer;
readonly mvid?: Buffer;
readonly pinvoke?: {
readonly importName?: string;
readonly mappingFlags?: number;
readonly moduleName?: string;
};
readonly readyToRun?: boolean;
readonly references?: readonly string[];
readonly resourceData?: Buffer;
readonly targetFramework?: string;
readonly typeName?: string;
readonly typeNamespace?: string;
}
const textEncoder = new TextEncoder();
const align4 = (value: number): number => (value + 3) & ~3;
const cString = (value: string): Buffer => Buffer.from(`${value}\0`, "utf8");
class StringHeap {
readonly #chunks: Buffer[] = [Buffer.from([0])];
#size = 1;
add(value: string): number {
if (value.length === 0) return 0;
const index = this.#size;
const chunk = cString(value);
this.#chunks.push(chunk);
this.#size += chunk.length;
return index;
}
toBuffer(): Buffer {
return Buffer.concat(this.#chunks);
}
}
class BlobHeap {
readonly #chunks: Buffer[] = [Buffer.from([0])];
#size = 1;
add(value: Buffer): number {
if (value.length === 0) return 0;
if (value.length > 0x7f)
throw new RangeError("Managed PE fixture blob is too large");
const index = this.#size;
this.#chunks.push(Buffer.from([value.length]), value);
this.#size += value.length + 1;
return index;
}
toBuffer(): Buffer {
return Buffer.concat(this.#chunks);
}
}
const DEFAULT_MVID = Buffer.from([
0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xaa, 0xbb, 0xcc,
0xdd, 0xee, 0xff,
]);
/** Generous bounds for inventory assertions over the source-owned PE fixture. */
export const MANAGED_ARTIFACT_FIXTURE_LIMITS = {
referenceOffset: 0,
referenceLimit: 100,
resourceOffset: 0,
resourceLimit: 100,
attributeOffset: 0,
attributeLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
};
/** Generous bounds for member assertions over the source-owned PE fixture. */
export const MANAGED_MEMBER_FIXTURE_LIMITS = {
typeOffset: 0,
typeLimit: 100,
methodOffset: 0,
methodLimit: 100,
fieldOffset: 0,
fieldLimit: 100,
memberRefOffset: 0,
memberRefLimit: 100,
edgeOffset: 0,
edgeLimit: 100,
instructionAnchorLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
maxMethodBodyBytes: 1024 * 1024,
maxMethodInstructions: 1_000,
};
/** Member bounds for fixture tests that inspect a real local path. */
export const MANAGED_MEMBER_PATH_FIXTURE_LIMITS = {
...MANAGED_MEMBER_FIXTURE_LIMITS,
maxFileBytes: 1024 * 1024,
};
/** Generous native-boundary bounds for the source-owned PE fixture. */
export const MANAGED_NATIVE_BOUNDARY_FIXTURE_LIMITS = {
moduleRefOffset: 0,
moduleRefLimit: 100,
importOffset: 0,
importLimit: 100,
implementationOffset: 0,
implementationLimit: 100,
maxMetadataBytes: 1024 * 1024,
maxTableRows: 1_000,
maxHeapItemBytes: 1024 * 1024,
};
/** Describe fixture bytes as the managed PE target consumed by static inspectors. */
export const managedPeFixtureTarget = (
bytes: Buffer,
path = "/fixture.exe",
): BinaryTarget => ({
path,
sha256: createHash("sha256").update(bytes).digest("hex"),
kind: "executable",
format: "pe",
architecture: "x86",
availableArchitectures: ["x86"],
executableRole: "application",
managed: true,
});
const guidHeap = (mvid: Buffer = DEFAULT_MVID): Buffer => {
if (mvid.length !== 16)
throw new RangeError("Managed PE fixture MVID must be 16 bytes");
return Buffer.from(mvid);
};
const u16 = (value: number): Buffer => {
const bytes = Buffer.alloc(2);
bytes.writeUInt16LE(value, 0);
return bytes;
};
const u32 = (value: number): Buffer => {
const bytes = Buffer.alloc(4);
bytes.writeUInt32LE(value, 0);
return bytes;
};
const moduleRow = (name: number): Buffer =>
Buffer.concat([u16(0), u16(name), u16(1), u16(0), u16(0)]);
const typeRefRow = (name: number, namespace: number): Buffer =>
Buffer.concat([u16(0), u16(name), u16(namespace)]);
const typeDefRow = (
name: number,
namespace: number,
fieldList: number,
methodList: number,
): Buffer =>
Buffer.concat([
u32(0x0010_0001),
u16(name),
u16(namespace),
u16((1 << 2) | 1),
u16(fieldList),
u16(methodList),
]);
const fieldRow = (name: number, signature: number): Buffer =>
Buffer.concat([u16(0x0001), u16(name), u16(signature)]);
interface MethodDefRowInput {
readonly name: number;
readonly signature: number;
readonly rva?: number;
readonly flags?: number;
readonly implFlags?: number;
}
const methodDefRow = ({
name,
signature,
rva = 0,
flags = 0x0016,
implFlags = 0,
}: MethodDefRowInput): Buffer =>
Buffer.concat([
u32(rva),
u16(implFlags),
u16(flags),
u16(name),
u16(signature),
u16(0),
]);
const memberRefRow = (name: number, signature: number): Buffer =>
Buffer.concat([u16((1 << 3) | 1), u16(name), u16(signature)]);
const moduleRefRow = (name: number): Buffer => Buffer.concat([u16(name)]);
const implMapRow = (
importName: number,
importScope: number,
mappingFlags: number,
): Buffer =>
Buffer.concat([
u16(mappingFlags),
u16((1 << 1) | 1),
u16(importName),
u16(importScope),
]);
const assemblyRow = (name: number): Buffer =>
Buffer.concat([
u32(0x0000_8004),
u16(1),
u16(2),
u16(3),
u16(4),
u32(0),
u16(0),
u16(name),
u16(0),
]);
const assemblyRefRow = (name: number, keyOrToken: number): Buffer =>
Buffer.concat([
u16(8),
u16(0),
u16(0),
u16(0),
u32(0),
u16(keyOrToken),
u16(name),
u16(0),
u16(0),
]);
const customAttributeRow = (value: number): Buffer =>
Buffer.concat([u16((1 << 5) | 14), u16((1 << 3) | 3), u16(value)]);
const manifestResourceRow = (name: number): Buffer =>
Buffer.concat([u32(0), u32(2), u16(name), u16(0)]);
const fixedStringAttributeBlob = (value: string): Buffer => {
const bytes = Buffer.from(textEncoder.encode(value));
if (bytes.length > 0x7f)
throw new RangeError("Managed PE fixture target framework is too long");
return Buffer.concat([Buffer.from([1, 0, bytes.length]), bytes, u16(0)]);
};
const metadataStreamHeader = (
relativeOffset: number,
size: number,
name: string,
): Buffer => {
const named = cString(name);
const paddedName = Buffer.alloc(align4(named.length));
named.copy(paddedName);
return Buffer.concat([u32(relativeOffset), u32(size), paddedName]);
};
const metadataRoot = (
tables: Buffer,
strings: Buffer,
guid: Buffer,
blob: Buffer,
): Buffer => {
const version = Buffer.from("v4.0.30319\0\0", "utf8");
const header = Buffer.concat([
u32(0x424a_5342),
u16(1),
u16(1),
u32(0),
u32(version.length),
version,
u16(0),
u16(4),
]);
const streamHeaderSize =
metadataStreamHeader(0, 0, "#~").length +
metadataStreamHeader(0, 0, "#Strings").length +
metadataStreamHeader(0, 0, "#GUID").length +
metadataStreamHeader(0, 0, "#Blob").length;
let offset = align4(header.length + streamHeaderSize);
const tablesOffset = offset;
offset = align4(offset + tables.length);
const stringsOffset = offset;
offset = align4(offset + strings.length);
const guidOffset = offset;
offset = align4(offset + guid.length);
const blobOffset = offset;
const headers = Buffer.concat([
metadataStreamHeader(tablesOffset, tables.length, "#~"),
metadataStreamHeader(stringsOffset, strings.length, "#Strings"),
metadataStreamHeader(guidOffset, guid.length, "#GUID"),
metadataStreamHeader(blobOffset, blob.length, "#Blob"),
]);
const root = Buffer.alloc(align4(blobOffset + blob.length));
header.copy(root, 0);
headers.copy(root, header.length);
tables.copy(root, tablesOffset);
strings.copy(root, stringsOffset);
guid.copy(root, guidOffset);
blob.copy(root, blobOffset);
return root;
};
const tablesStream = (
rows: ReadonlyMap<number, readonly Buffer[]>,
extraValidMask: bigint,
): Buffer => {
let valid = extraValidMask;
for (const table of rows.keys()) valid |= 1n << BigInt(table);
const header = Buffer.alloc(24);
header.writeUInt8(2, 4);
header.writeUInt8(1, 7);
header.writeBigUInt64LE(valid, 8);
const counts: Buffer[] = [];
for (let index = 0; index <= 44; index += 1) {
const tableRows = rows.get(index);
if (tableRows === undefined) continue;
counts.push(u32(tableRows.length));
}
const data: Buffer[] = [];
for (let index = 0; index <= 44; index += 1) {
const tableRows = rows.get(index);
if (tableRows === undefined) continue;
data.push(...tableRows);
}
return Buffer.concat([header, ...counts, ...data]);
};
const buildManagedFixtureMetadata = (
options: ManagedPeFixtureOptions,
): Buffer => {
const strings = new StringHeap();
const blobs = new BlobHeap();
const moduleName = strings.add("Fixture.dll");
const assemblyName = strings.add("Fixture.Managed");
const attributeName = strings.add("TargetFrameworkAttribute");
const attributeNamespace = strings.add("System.Runtime.Versioning");
const constructorName = strings.add(".ctor");
const typeName = strings.add(options.typeName ?? "Program");
const typeNamespace = strings.add(options.typeNamespace ?? "Fixture");
const fieldName = strings.add(options.fieldName ?? "counter");
const methodName = strings.add(options.methodName ?? "Main");
const pinvokeModuleName =
options.pinvoke === undefined
? null
: strings.add(options.pinvoke.moduleName ?? "user32.dll");
const pinvokeImportName =
options.pinvoke === undefined
? null
: strings.add(options.pinvoke.importName ?? "MessageBoxW");
const resourceName = strings.add("Fixture.resources");
const referenceNames = options.references ?? ["System.Runtime"];
const referenceStringIndexes = referenceNames.map((name) =>
strings.add(name),
);
const tokenBlob = blobs.add(Buffer.from("b77a5c561934e089", "hex"));
const fieldSignature = blobs.add(
options.fieldSignature ?? Buffer.from([0x06, 0x08]),
);
const methodSignature = blobs.add(
options.methodSignature ?? Buffer.from([0x00, 0x00, 0x01]),
);
const constructorSignature = blobs.add(Buffer.from([0x20, 0x01, 0x01, 0x0e]));
const attributeBlob = blobs.add(
fixedStringAttributeBlob(
options.targetFramework ?? ".NETCoreApp,Version=v8.0",
),
);
const rows = new Map<number, readonly Buffer[]>([
[0, [moduleRow(moduleName)]],
[1, [typeRefRow(attributeName, attributeNamespace)]],
[2, [typeDefRow(typeName, typeNamespace, 1, 1)]],
[4, [fieldRow(fieldName, fieldSignature)]],
[
6,
[
methodDefRow({
name: methodName,
signature: methodSignature,
rva: 0x2800,
flags: options.pinvoke === undefined ? 0x0016 : 0x2016,
}),
],
],
[10, [memberRefRow(constructorName, constructorSignature)]],
[12, [customAttributeRow(attributeBlob)]],
...(pinvokeModuleName === null
? []
: ([[26, [moduleRefRow(pinvokeModuleName)]]] as const)),
...(pinvokeImportName === null
? []
: ([
[
28,
[
implMapRow(
pinvokeImportName,
1,
options.pinvoke?.mappingFlags ?? 0x0344,
),
],
],
] as const)),
[32, [assemblyRow(assemblyName)]],
[35, referenceStringIndexes.map((name) => assemblyRefRow(name, tokenBlob))],
[40, [manifestResourceRow(resourceName)]],
]);
const metadata = metadataRoot(
tablesStream(rows, options.metadataValidMaskExtra ?? 0n),
strings.toBuffer(),
guidHeap(options.mvid),
blobs.toBuffer(),
);
if (options.corruptMetadataSignature === true) metadata.writeUInt32LE(0, 0);
return metadata;
};
const buildManagedFixtureImage = (
options: ManagedPeFixtureOptions,
metadata: Buffer,
): Buffer => {
const resourceData = options.resourceData ?? Buffer.from("resource-data");
const resourceDirectory = Buffer.concat([
u32(resourceData.length),
resourceData,
]);
const image = Buffer.alloc(0x1000);
image.write("MZ", 0, "ascii");
image.writeUInt32LE(0x80, 0x3c);
image.writeUInt32LE(0x0000_4550, 0x80);
const coff = 0x84;
image.writeUInt16LE(0x014c, coff);
image.writeUInt16LE(1, coff + 2);
image.writeUInt16LE(0x00e0, coff + 16);
image.writeUInt16LE(0x0102, coff + 18);
const optional = coff + 20;
image.writeUInt16LE(0x010b, optional);
image.writeUInt32LE(0x2000, optional + 20);
image.writeUInt32LE(0x0040_0000, optional + 28);
image.writeUInt32LE(0x1000, optional + 32);
image.writeUInt32LE(0x200, optional + 36);
image.writeUInt32LE(0x3000, optional + 56);
image.writeUInt32LE(0x200, optional + 60);
image.writeUInt32LE(16, optional + 92);
image.writeUInt32LE(0x2000, optional + 96 + 14 * 8);
image.writeUInt32LE(72, optional + 96 + 14 * 8 + 4);
const section = optional + 0x00e0;
image.write(".text\0\0\0", section, "ascii");
image.writeUInt32LE(0x1000, section + 8);
image.writeUInt32LE(0x2000, section + 12);
image.writeUInt32LE(0x0e00, section + 16);
image.writeUInt32LE(0x0200, section + 20);
image.writeUInt32LE(0x6000_0020, section + 36);
const cli = 0x0200;
image.writeUInt32LE(72, cli);
image.writeUInt16LE(2, cli + 4);
image.writeUInt16LE(5, cli + 6);
image.writeUInt32LE(0x2100, cli + 8);
image.writeUInt32LE(metadata.length, cli + 12);
image.writeUInt32LE(options.cliFlags ?? 1, cli + 16);
image.writeUInt32LE(0x0600_0001, cli + 20);
image.writeUInt32LE(0x2600, cli + 24);
image.writeUInt32LE(resourceDirectory.length, cli + 28);
if (options.readyToRun === true) {
image.writeUInt32LE(0x2700, cli + 64);
image.writeUInt32LE(4, cli + 68);
image.write("RTR\0", 0x0900, "ascii");
}
(
options.ilBody ??
Buffer.from([
0x32, 0x02, 0x7b, 0x01, 0x00, 0x00, 0x04, 0x28, 0x01, 0x00, 0x00, 0x0a,
0x2a,
])
).copy(image, 0x0a00);
metadata.copy(image, 0x0300);
resourceDirectory.copy(image, 0x0800);
return image;
};
/** Build a source-owned PE32/CLI fixture without committing compiled binaries. */
export const buildManagedPeFixture = (
options: ManagedPeFixtureOptions = {},
): Buffer =>
buildManagedFixtureImage(options, buildManagedFixtureMetadata(options));
/** Build a syntactically valid PE32 fixture with no CLI directory. */
export const buildNativePeFixture = (): Buffer => {
const image = buildManagedPeFixture();
const cliDirectory = 0x84 + 20 + 96 + 14 * 8;
image.writeUInt32LE(0, cliDirectory);
image.writeUInt32LE(0, cliDirectory + 4);
return image;
};