test(dotnet): prove scoped member ownership within the caller budget (#13369)

This commit is contained in:
morluto authored and GitHub committed 2026-11-22 09:30:54 +00:00
1 parent 62114e940f
commit 2e8bdfd808
3 files changed
+142 -153

No files matched your search

+84 -72
View File
@@ -3,24 +3,24 @@ import { describe, expect, vi } from "vitest";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { managedDecodeBudget } from "../domain/managed/managedDecodeBudget.js";
import * as ownershipProducer from "../domain/managed/managedMemberOwnership.js";
import {
attachManagedDecodeBudget,
ManagedDecodeBudget,
ManagedRepresentationFailure,
} from "../domain/managed/managedDecodeBudget.js";
import { memberDeclaringTypeRowLookup } from "../domain/managed/managedMemberOwnership.js";
import { memberListIndexSize } from "../domain/managed/managedMemberPointers.js";
import { readTypeMemberListFacts } from "../domain/managed/managedTypeMemberLists.js";
import {
metadataRowOffset,
readManagedMetadataLayout,
} from "../domain/managed/managedMetadataLayout.js";
import { buildManagedMemberSelectionCapacityFixture } from "../../tests/fixtures/managedMemberCapacity.js";
const { memberDeclaringTypeRowLookup } = ownershipProducer;
import {
buildManagedMemberPointerFixture,
buildManagedPeFixture,
managedPeFixtureTarget,
} from "./ManagedPe.fixture.js";
import { readManagedPeLayout } from "../domain/managed/managedPeReader.js";
import { ManagedReaderFailure } from "../domain/managed/managedReaderFailure.js";
const metadataLayout = (bytes: Buffer) => {
const pe = readManagedPeLayout(bytes);
@@ -65,6 +65,8 @@ describe("managed declaring type ownership", () => {
const target = managedPeFixtureTarget(bytes);
const members = inspectManagedMembersBytes(bytes, target);
const artifact = inspectManagedArtifactBytes(bytes, target);
const ownerNames = ["<Module>", "Fixture.A", "Fixture.B"];
let expectedAttributeOwner: string | null | undefined;
for (const [table, starts] of [
["fields", fields],
["methods", methods],
@@ -80,15 +82,16 @@ describe("managed declaring type ownership", () => {
break;
}
}
return owner === null ? null : members.types[owner]?.full_name;
return owner === null ? null : ownerNames[owner];
});
expect(members[table].map((member) => member.declaring_type)).toEqual(
expected,
);
if (table === "methods") expectedAttributeOwner = expected[0];
}
expect(artifact.attributes[0]?.type_name).toBe(
members.methods[0]?.declaring_type,
);
expect(artifact.attributes[0]).toMatchObject({
type_name: expectedAttributeOwner,
});
},
);
@@ -126,16 +129,8 @@ describe("managed declaring type ownership", () => {
const bytes = buildManagedPeFixture();
const layout = metadataLayout(bytes);
const facts = readTypeMemberListFacts(bytes, layout);
const budget = managedDecodeBudget(layout);
const capacityFailure = new ManagedReaderFailure({
code: "resource-limit",
scope: "metadata.representation",
offset: layout.table(2)?.offset ?? null,
detail: "No remaining ownership index capacity",
});
const admission = vi.spyOn(budget, "reserve").mockImplementation(() => {
throw capacityFailure;
});
attachManagedDecodeBudget(layout, new ManagedDecodeBudget(1));
const lookup = () => memberDeclaringTypeRowLookup(bytes, layout, 6, facts);
let allocations = 0;
vi.stubGlobal(
"Uint32Array",
@@ -147,41 +142,57 @@ describe("managed declaring type ownership", () => {
}),
);
try {
expect(() =>
memberDeclaringTypeRowLookup(bytes, layout, 6, facts),
).toThrow(capacityFailure);
expect(() =>
memberDeclaringTypeRowLookup(bytes, layout, 6, facts),
).toThrow(capacityFailure);
expect(admission).toHaveBeenCalledTimes(1);
const [first, retry] = [0, 1].map(() => {
try {
return lookup();
} catch (cause: unknown) {
return cause;
}
});
expect(first).toBeInstanceOf(ManagedRepresentationFailure);
expect(first).toMatchObject({
issue: {
scope: "metadata.representation",
offset: layout.table(2)?.offset,
},
});
expect(retry).toBe(first);
expect(allocations).toBe(0);
} finally {
vi.unstubAllGlobals();
admission.mockRestore();
}
});
});
describe("selected FieldList and MethodList interval iteration", () => {
it("skips building full-table owner lookups when monotonic intervals apply", () => {
const bytes = buildManagedMemberSelectionCapacityFixture(200);
const target = managedPeFixtureTarget(bytes);
const spy = vi.spyOn(ownershipProducer, "memberDeclaringTypeRowLookup");
try {
const selected = inspectManagedMembersBytes(bytes, target, {
it("completes one selected field and method within the caller's representation budget", () => {
const bytes = buildManagedPeFixture({
additionalEmptyTypes: 2,
fieldRowCount: 4096,
methodRowCount: 4096,
distinctMemberNames: true,
firstTypeFieldRowCount: 1,
firstTypeMethodRowCount: 1,
});
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{
typeNames: ["Fixture.Empty0"],
});
expect(spy).not.toHaveBeenCalled();
expect(selected.coverage).toEqual({ state: "complete", issues: [] });
expect(selected.fields).toMatchObject([
{ name: "Field0", declaring_type: "Fixture.Empty0" },
]);
expect(selected.methods).toMatchObject([
{ name: "Method0", declaring_type: "Fixture.Empty0" },
]);
} finally {
spy.mockRestore();
}
maxRepresentationBytes: 48 * 1024,
},
);
expect(result.coverage).toEqual({ state: "complete", issues: [] });
expect(result.fields).toMatchObject([
{ token: "0x04000001", name: "Field0", declaring_type: "Fixture.Empty0" },
]);
expect(result.methods).toMatchObject([
{
token: "0x06000001",
name: "Method0",
declaring_type: "Fixture.Empty0",
},
]);
});
it("falls back cleanly when FieldList or MethodList pointers decrease", () => {
@@ -205,31 +216,32 @@ describe("selected FieldList and MethodList interval iteration", () => {
bytes.writeUInt16LE(3, row3 + methodColOffset);
bytes.writeUInt16LE(2, row4 + methodColOffset);
const spy = vi.spyOn(ownershipProducer, "memberDeclaringTypeRowLookup");
try {
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{ typeNames: ["Fixture.Empty0", "Fixture.Empty1"] },
);
expect(spy).toHaveBeenCalled();
expect(result.coverage.state).toBe("partial");
expect(result.coverage.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
code: "invalid-row",
detail: expect.stringContaining("FieldList start 2 decreases"),
}),
expect.objectContaining({
code: "invalid-row",
detail: expect.stringContaining("MethodList start 2 decreases"),
}),
]),
);
expect(result.fields.map(({ name }) => name)).toEqual(["Field0"]);
expect(result.methods.map(({ name }) => name)).toEqual(["Method0"]);
} finally {
spy.mockRestore();
}
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{ typeNames: ["Fixture.Empty0", "Fixture.Empty1"] },
);
expect(result.coverage).toMatchObject({
state: "partial",
issues: expect.arrayContaining([
expect.objectContaining({
code: "invalid-row",
offset: row4 + fieldColOffset,
detail: expect.stringContaining("FieldList start 2 decreases"),
}),
expect.objectContaining({
code: "invalid-row",
offset: row4 + methodColOffset,
detail: expect.stringContaining("MethodList start 2 decreases"),
}),
]),
});
expect(result.fields.map(({ name }) => name)).toEqual(["Field0"]);
expect(result.methods.map(({ name }) => name)).toEqual(["Method0"]);
expect(result.user_strings).toEqual({
state: "partial",
literals: [],
issues: [],
});
});
});
+33 -58
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vitest";
import { expect, it, vi } from "vitest";
import {
attachManagedDecodeBudget,
@@ -10,8 +10,6 @@ import { buildManagedMemberPointerFixture } from "./ManagedPe.fixture.js";
import { readManagedPeLayout } from "../domain/managed/managedPeReader.js";
import { ManagedReaderFailure } from "../domain/managed/managedReaderFailure.js";
const representationCapacity = 64 * 1024 * 1024;
const pointerFixture = () => {
const bytes = buildManagedMemberPointerFixture();
const pe = readManagedPeLayout(bytes);
@@ -25,72 +23,49 @@ const pointerFixture = () => {
// the metadata version/string admission already exercised by the parser.
const budget = new ManagedDecodeBudget();
attachManagedDecodeBudget(layout, budget);
const indexBytes =
((layout.table(6)?.rowCount ?? 0) + 1) * Uint32Array.BYTES_PER_ELEMENT +
256;
return { bytes, layout, budget, indexBytes };
// Two MethodDef rows and the zero sentinel need three uint32 slots.
return { bytes, layout, budget, indexBytes: 3 * 4 + 256 };
};
describe("managed member pointer index capacity", () => {
it("rejects insufficient capacity before allocating the inverse index", () => {
it.each([
["one byte short", 1, 0],
["exact capacity", 0, 1],
] as const)(
"constructs the inverse pointer index at %s",
(_label, shortfall, expectedAllocations) => {
const { bytes, layout, budget, indexBytes } = pointerFixture();
budget.reserve(representationCapacity - indexBytes + 1, null);
budget.reserve(budget.maximumBytes - indexBytes + shortfall, null);
const lookup = () => memberListRowLookup(bytes, layout, 6);
let allocations = 0;
let failure: unknown;
// Proxy forwards static BYTES_PER_ELEMENT too: losing it would produce a
// NaN admission failure and falsely pass a before-allocation assertion.
// Forward static width facts too so invalid allocation setup cannot pass as refusal.
vi.stubGlobal(
"Uint32Array",
new Proxy(Uint32Array, {
construct(target, arguments_, newTarget) {
allocations += 1;
return Reflect.construct(target, arguments_, newTarget);
construct(target, args, newTarget) {
allocations++;
return Reflect.construct(target, args, newTarget);
},
}),
);
try {
memberListRowLookup(bytes, layout, 6);
} catch (cause: unknown) {
failure = cause;
if (shortfall === 1) {
expect(lookup).toThrow(
expect.objectContaining({
issue: expect.objectContaining({
code: "resource-limit",
scope: "metadata.representation",
offset: layout.table(5)?.offset,
}),
}),
);
} else {
for (const read of [lookup(), lookup()])
expect([read(1), read(2)]).toEqual([2, 1]);
expect(() => budget.reserve(1, null)).toThrow(ManagedReaderFailure);
}
expect(allocations).toBe(expectedAllocations);
} finally {
vi.unstubAllGlobals();
}
expect(failure).toBeInstanceOf(ManagedReaderFailure);
expect(failure).toMatchObject({
issue: {
code: "resource-limit",
scope: "metadata.representation",
offset: layout.table(5)?.offset,
},
});
expect(allocations).toBe(0);
});
it("reuses one layout's index without allocating or charging it again", () => {
const { bytes, layout, budget, indexBytes } = pointerFixture();
budget.reserve(representationCapacity - indexBytes, null);
let allocations = 0;
let observed: number[];
vi.stubGlobal(
"Uint32Array",
new Proxy(Uint32Array, {
construct(target, arguments_, newTarget) {
allocations += 1;
return Reflect.construct(target, arguments_, newTarget);
},
}),
);
try {
const first = memberListRowLookup(bytes, layout, 6);
const repeated = memberListRowLookup(bytes, layout, 6);
observed = [first(1), first(2), repeated(1), repeated(2)];
} finally {
vi.unstubAllGlobals();
}
expect(observed).toEqual([2, 1, 2, 1]);
expect(allocations).toBe(1);
expect(() => budget.reserve(1, null)).toThrow(ManagedReaderFailure);
});
});
},
);
+25 -23
View File
@@ -27,12 +27,6 @@ describe("managed member pointer ownership", () => {
methodPointers: [1, 2],
streamName: "#-" as const,
},
{
label: "ordinary direct lists",
fieldPointers: null,
methodPointers: null,
streamName: "#~" as const,
},
{
label: "empty pointer tables with direct lists",
fieldPointers: [],
@@ -92,6 +86,13 @@ describe("invalid managed member pointers", () => {
"preserves member facts and independent ownership for $label",
({ rows, owners }) => {
const bytes = buildManagedMemberPointerFixture({ [pointers]: rows });
const layout = metadataLayout(bytes);
const pointerTable = layout.table(table === "fields" ? 3 : 5);
if (pointerTable === undefined)
throw new Error("Fixture omitted pointer table");
const diagnosticOffset =
pointerTable.offset +
(rows[0] === rows[1] ? pointerTable.rowSize : 0);
const result = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
@@ -103,7 +104,7 @@ describe("invalid managed member pointers", () => {
expect.objectContaining({
code: "invalid-row",
scope,
offset: expect.any(Number),
offset: diagnosticOffset,
}),
]),
);
@@ -140,39 +141,40 @@ describe("invalid managed member pointers", () => {
);
},
);
});
describe("managed constructor ownership and pointer stream extent", () => {
it.each([
{ label: "zero row", methodPointers: [2, 0] },
{ label: "duplicate row", methodPointers: [2, 2] },
{ label: "malformed table", methodPointers: [2, 0] },
{ label: "omitted constructor row", methodPointers: [2] },
])(
"preserves attribute facts with an unknown constructor owner for $label",
({ methodPointers }) => {
const controlBytes = buildManagedMemberPointerFixture();
const control = inspectManagedArtifactBytes(
controlBytes,
managedPeFixtureTarget(controlBytes),
).attributes[0];
if (control === undefined)
throw new Error("Fixture omitted custom attribute");
expect(control.type_name).toBe("Fixture.B");
const bytes = buildManagedMemberPointerFixture({ methodPointers });
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
);
expect(result.coverage.state).toBe("partial");
expect(result.coverage.issues).toEqual(
expect.arrayContaining([
expect(result.coverage).toMatchObject({
state: "partial",
issues: expect.arrayContaining([
expect.objectContaining({
code: "invalid-row",
scope: "metadata.MethodPtr",
}),
]),
);
expect(result.attributes).toEqual([
{ ...control, row_offset: expect.any(Number), type_name: null },
});
expect(result.attributes).toMatchObject([
{
token: "0x0c000001",
parent_token: "0x20000001",
constructor_token: "0x06000001",
type_name: null,
value_length: 12,
value_sha256:
"ef46e4e6444ea51d2479d5870ab66cc91e5030b036261b008b2beb1c346524c0",
},
]);
},
);