refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
+10 -20
View File
@@ -44,13 +44,10 @@ describe("managed artifact inventory", () => {
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(result.references).toEqual([
expect.objectContaining({ name: "System.Runtime" }),
]);
expect(result.resources).toEqual([
expect.objectContaining({
name: "Fixture.resources",
embedded: true,
@@ -62,26 +59,19 @@ describe("managed artifact inventory", () => {
expect(result.coverage).toMatchObject({ state: "complete", issues: [] });
});
it("keeps classification evidence complete when caller pages visible references", () => {
it("returns all references inline while classifying from the full inventory", () => {
const bytes = buildManagedPeFixture({
references: ["System.Runtime", "UnityEngine.CoreModule"],
});
const result = inspectManagedArtifactBytes(
bytes,
managedPeFixtureTarget(bytes),
{
...MANAGED_ARTIFACT_FIXTURE_LIMITS,
referenceLimit: 1,
},
MANAGED_ARTIFACT_FIXTURE_LIMITS,
);
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.references).toHaveLength(2);
expect(result.coverage.state).toBe("complete");
expect(result.coverage.issues).toEqual([]);
});
@@ -124,11 +114,11 @@ describe("managed artifact inventory", () => {
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.fields.items[0]?.signature).toMatchObject({
expect(result.fields[0]?.signature).toMatchObject({
parse_status: "decoded",
field_type: "i4**[]",
});
expect(result.methods.items[0]?.signature).toMatchObject({
expect(result.methods[0]?.signature).toMatchObject({
parse_status: "decoded",
return_type: "i4&",
parameter_types: ["i4*", "string&"],
+8 -38
View File
@@ -27,16 +27,6 @@ export interface ManagedInspectionLimits extends ManagedInventoryInput {
readonly maxTableRows: number;
}
const emptyPage = (offset: number, limit: number) => ({
items: [],
offset,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: offset === 0,
});
const flagNames = (flags: number): string[] => {
const names: string[] = [];
for (const [mask, name] of [
@@ -100,7 +90,6 @@ const base = (
bytes: Buffer,
layout: ManagedPeLayout,
) => ({
schema_version: 1 as const,
artifact: {
path: target.path,
sha256: target.sha256,
@@ -114,7 +103,6 @@ const unavailableResult = (
target: BinaryTarget,
bytes: Buffer,
layout: ManagedPeLayout,
limits: ManagedInspectionLimits,
): ManagedArtifactInspection => {
const malformed = layout.cliDirectoryPresent;
const issues = layout.cliIssue === null ? [] : [layout.cliIssue];
@@ -150,9 +138,9 @@ const unavailableResult = (
module: null,
assembly: null,
target_frameworks: [],
references: emptyPage(limits.referenceOffset, limits.referenceLimit),
resources: emptyPage(limits.resourceOffset, limits.resourceLimit),
attributes: emptyPage(limits.attributeOffset, limits.attributeLimit),
references: [],
resources: [],
attributes: [],
coverage: {
state: malformed ? "partial" : "unavailable",
issues,
@@ -295,7 +283,6 @@ interface PartialMetadataContext {
readonly target: BinaryTarget;
readonly bytes: Buffer;
readonly layout: ManagedPeLayout;
readonly limits: ManagedInspectionLimits;
readonly issue: ManagedParseIssue;
}
@@ -303,7 +290,6 @@ const partialMetadataResult = ({
target,
bytes,
layout,
limits,
issue,
}: PartialMetadataContext): ManagedArtifactInspection => ({
...base(target, bytes, layout),
@@ -331,9 +317,9 @@ const partialMetadataResult = ({
module: null,
assembly: null,
target_frameworks: [],
references: emptyPage(limits.referenceOffset, limits.referenceLimit),
resources: emptyPage(limits.resourceOffset, limits.resourceLimit),
attributes: emptyPage(limits.attributeOffset, limits.attributeLimit),
references: [],
resources: [],
attributes: [],
coverage: { state: "partial", issues: [issue] },
limitations: [
"CLI metadata triage stopped at the reported bounded format or resource limit.",
@@ -364,13 +350,6 @@ const mapResources = (
}
};
const inventoryPagesComplete = (
inventory: ReturnType<typeof readManagedMetadataInventory>,
): boolean =>
inventory.references.complete &&
inventory.resources.complete &&
inventory.attributes.complete;
/** Inspect PE/CLI identity directly from bounded bytes without CLR loading. */
export const inspectManagedArtifactBytes = (
bytes: Buffer,
@@ -378,8 +357,7 @@ export const inspectManagedArtifactBytes = (
limits: ManagedInspectionLimits,
): ManagedArtifactInspection => {
const layout = readManagedPeLayout(bytes);
if (layout.cli === null)
return unavailableResult(target, bytes, layout, limits);
if (layout.cli === null) return unavailableResult(target, bytes, layout);
const cli = layout.cli;
if (cli.metadata.size > limits.maxMetadataBytes)
return managedArtifactInspectionSchema.parse(
@@ -387,7 +365,6 @@ export const inspectManagedArtifactBytes = (
target,
bytes,
layout,
limits,
issue: {
code: "limit-exceeded",
scope: "cli.metadata",
@@ -416,7 +393,6 @@ export const inspectManagedArtifactBytes = (
target,
bytes,
layout,
limits,
issue: cause.issue,
}),
);
@@ -430,13 +406,7 @@ export const inspectManagedArtifactBytes = (
resourceDirectory,
);
const issues = [...resourceIssues, ...inventory.issues];
const pagesComplete = inventoryPagesComplete(inventory);
const limitations = [
...(pagesComplete
? []
: [
"At least one caller-selected metadata page omits rows; use its offset and total to continue.",
]),
...(issues.length === 0
? []
: [
@@ -464,7 +434,7 @@ export const inspectManagedArtifactBytes = (
resources: inventory.resources,
attributes: inventory.attributes,
coverage: {
state: pagesComplete && issues.length === 0 ? "complete" : "partial",
state: issues.length === 0 ? "complete" : "partial",
issues,
},
limitations,
+6 -6
View File
@@ -29,7 +29,7 @@ describe("managed CIL decoding", () => {
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.methods.items[0]?.body).toMatchObject({
expect(result.methods[0]?.body).toMatchObject({
status: "present",
header_format: "fat",
il_size: il.length,
@@ -56,7 +56,7 @@ describe("managed CIL decoding", () => {
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(result.methods.items[0]?.body).toMatchObject({
expect(result.methods[0]?.body).toMatchObject({
status: "malformed",
il_size: 2,
normalized_il_sha256: null,
@@ -89,7 +89,7 @@ describe("managed CIL decoding", () => {
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(tiny.methods.items[0]?.body).toMatchObject({
expect(tiny.methods[0]?.body).toMatchObject({
status: "present",
header_format: "tiny",
max_stack: 8,
@@ -102,13 +102,13 @@ describe("managed CIL decoding", () => {
opcode_counts: { nop: 1, ret: 1 },
exception_regions: [],
});
expect(fat.methods.items[0]?.body).toMatchObject({
expect(fat.methods[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,
il_sha256: tiny.methods[0]?.body.il_sha256,
normalized_il_sha256: tiny.methods[0]?.body.normalized_il_sha256,
});
});
});
+1 -1
View File
@@ -23,7 +23,7 @@ describe("managed CIL limits", () => {
const il = bytes.subarray(0x0a01, 0x0a0d);
expect(result.metadata.status).toBe("complete");
expect(result.methods.items[0]?.body).toMatchObject({
expect(result.methods[0]?.body).toMatchObject({
status: "partial",
il_size: 12,
il_sha256: createHash("sha256").update(il).digest("hex"),
+9
View File
@@ -0,0 +1,9 @@
/** Internal parser and artifact-admission safeguards for managed PE inspection. */
export const MANAGED_INSPECTION_DEFAULTS = Object.freeze({
maxFileBytes: 268_435_456,
maxMetadataBytes: 67_108_864,
maxTableRows: 100_000,
maxHeapItemBytes: 1_048_576,
maxMethodBodyBytes: 1_048_576,
maxMethodInstructions: 10_000,
});
+6 -6
View File
@@ -21,7 +21,7 @@ describe("managed member inspection", () => {
requires_artifact_sha256: managedPeFixtureTarget(bytes).sha256,
requires_mvid: "00112233-4455-6677-8899-aabbccddeeff",
});
expect(result.types.items).toEqual([
expect(result.types).toEqual([
expect.objectContaining({
token: "0x02000001",
full_name: "Fixture.Program",
@@ -29,7 +29,7 @@ describe("managed member inspection", () => {
method_list: { first_row: 1, last_row: 1, count: 1 },
}),
]);
expect(result.fields.items).toEqual([
expect(result.fields).toEqual([
expect.objectContaining({
token: "0x04000001",
declaring_type: "Fixture.Program",
@@ -41,7 +41,7 @@ describe("managed member inspection", () => {
}),
}),
]);
expect(result.methods.items).toEqual([
expect(result.methods).toEqual([
expect.objectContaining({
token: "0x06000001",
declaring_type: "Fixture.Program",
@@ -79,7 +79,7 @@ describe("managed member inspection", () => {
}),
}),
]);
expect(result.member_refs.items).toEqual([
expect(result.member_refs).toEqual([
expect.objectContaining({
token: "0x0a000001",
name: ".ctor",
@@ -90,7 +90,7 @@ describe("managed member inspection", () => {
}),
}),
]);
expect(result.call_edges.items).toEqual([
expect(result.call_edges).toEqual([
{
caller_token: "0x06000001",
caller: "Fixture.Program.Main",
@@ -100,7 +100,7 @@ describe("managed member inspection", () => {
target_name: ".ctor",
},
]);
expect(result.field_accesses.items).toEqual([
expect(result.field_accesses).toEqual([
{
method_token: "0x06000001",
method: "Fixture.Program.Main",
+12 -30
View File
@@ -19,8 +19,6 @@ import {
managedFailure,
} from "./ManagedReaderFailure.js";
import {
emptyPage,
page,
parseTypes,
typeRanges,
type ManagedMemberInspectionLimits,
@@ -41,7 +39,6 @@ const unavailable = (
issue: ManagedParseIssue | null,
): ManagedMemberInspection =>
managedMemberInspectionSchema.parse({
schema_version: 1,
artifact: {
path: target.path,
sha256: target.sha256,
@@ -59,12 +56,12 @@ const unavailable = (
requires_artifact_sha256: target.sha256,
requires_mvid: null,
},
types: emptyPage(limits.typeOffset, limits.typeLimit),
fields: emptyPage(limits.fieldOffset, limits.fieldLimit),
methods: emptyPage(limits.methodOffset, limits.methodLimit),
member_refs: emptyPage(limits.memberRefOffset, limits.memberRefLimit),
call_edges: emptyPage(limits.edgeOffset, limits.edgeLimit),
field_accesses: emptyPage(limits.edgeOffset, limits.edgeLimit),
types: [],
fields: [],
methods: [],
member_refs: [],
call_edges: [],
field_accesses: [],
coverage: {
state: "unavailable",
issues: issue === null ? [] : [issue],
@@ -144,12 +141,6 @@ const readMemberInventory = (
bytes,
layout,
{
referenceOffset: 0,
referenceLimit: 1,
resourceOffset: 0,
resourceLimit: 1,
attributeOffset: 0,
attributeLimit: 1,
maxHeapItemBytes: limits.maxHeapItemBytes,
},
resourceDirectory(pe),
@@ -190,7 +181,6 @@ export const inspectManagedMembersBytes = (
memberRefs.core,
);
return managedMemberInspectionSchema.parse({
schema_version: 1,
artifact: {
path: target.path,
sha256: target.sha256,
@@ -208,20 +198,12 @@ export const inspectManagedMembersBytes = (
requires_artifact_sha256: target.sha256,
requires_mvid: inventory.module?.mvid ?? null,
},
types: page(types, limits.typeOffset, limits.typeLimit),
fields: page(fields.fields, limits.fieldOffset, limits.fieldLimit),
methods: page(methods.methods, limits.methodOffset, limits.methodLimit),
member_refs: page(
memberRefs.refs,
limits.memberRefOffset,
limits.memberRefLimit,
),
call_edges: page(related.callEdges, limits.edgeOffset, limits.edgeLimit),
field_accesses: page(
related.fieldAccesses,
limits.edgeOffset,
limits.edgeLimit,
),
types,
fields: fields.fields,
methods: methods.methods,
member_refs: memberRefs.refs,
call_edges: related.callEdges,
field_accesses: related.fieldAccesses,
coverage: {
state: coverageIssues.length === 0 ? "complete" : "partial",
issues: coverageIssues,
+6 -58
View File
@@ -11,24 +11,13 @@ import {
sha256Bytes,
} from "./ManagedMetadataHeaps.js";
export type ManagedPage<Item> = {
readonly items: readonly Item[];
readonly offset: number;
readonly limit: number;
readonly total: number;
readonly returned: number;
readonly dropped: number;
readonly complete: boolean;
};
export type ManagedType = ManagedMemberInspection["types"]["items"][number];
export type ManagedField = ManagedMemberInspection["fields"]["items"][number];
export type ManagedMethod = ManagedMemberInspection["methods"]["items"][number];
export type ManagedMemberRef =
ManagedMemberInspection["member_refs"]["items"][number];
export type ManagedCallEdge =
ManagedMemberInspection["call_edges"]["items"][number];
export type ManagedType = ManagedMemberInspection["types"][number];
export type ManagedField = ManagedMemberInspection["fields"][number];
export type ManagedMethod = ManagedMemberInspection["methods"][number];
export type ManagedMemberRef = ManagedMemberInspection["member_refs"][number];
export type ManagedCallEdge = ManagedMemberInspection["call_edges"][number];
export type ManagedFieldAccess =
ManagedMemberInspection["field_accesses"]["items"][number];
ManagedMemberInspection["field_accesses"][number];
export type ManagedSignature = ManagedMethod["signature"];
export type ManagedMethodBody = ManagedMethod["body"];
export type ManagedInstructionAnchor = ManagedMethodBody["anchors"][number];
@@ -36,17 +25,6 @@ export type ManagedExceptionRegion =
ManagedMethodBody["exception_regions"][number];
export interface ManagedMemberInspectionLimits {
readonly typeOffset: number;
readonly typeLimit: number;
readonly methodOffset: number;
readonly methodLimit: number;
readonly fieldOffset: number;
readonly fieldLimit: number;
readonly memberRefOffset: number;
readonly memberRefLimit: number;
readonly edgeOffset: number;
readonly edgeLimit: number;
readonly instructionAnchorLimit: number;
readonly maxMetadataBytes: number;
readonly maxTableRows: number;
readonly maxHeapItemBytes: number;
@@ -86,36 +64,6 @@ export interface ParsedInstruction {
readonly operand: string | null;
}
export const emptyPage = <Item>(
offset: number,
limit: number,
): ManagedPage<Item> => ({
items: [],
offset,
limit,
total: 0,
returned: 0,
dropped: 0,
complete: offset === 0,
});
export const page = <Item>(
all: readonly Item[],
offset: number,
limit: number,
): ManagedPage<Item> => {
const items = all.slice(offset, offset + limit);
return {
items,
offset,
limit,
total: all.length,
returned: items.length,
dropped: all.length - items.length,
complete: offset === 0 && offset + limit >= all.length,
};
};
const rowRange = (
table: MetadataTableLayout | undefined,
start: number,
+30 -66
View File
@@ -19,27 +19,10 @@ import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
type ModuleIdentity = NonNullable<ManagedArtifactInspection["module"]>;
type AssemblyIdentity = NonNullable<ManagedArtifactInspection["assembly"]>;
type AssemblyReference =
ManagedArtifactInspection["references"]["items"][number];
type ManagedResource = ManagedArtifactInspection["resources"]["items"][number];
type CustomAttribute = ManagedArtifactInspection["attributes"]["items"][number];
type ManagedPage<Item> = {
readonly items: readonly Item[];
readonly offset: number;
readonly limit: number;
readonly total: number;
readonly returned: number;
readonly dropped: number;
readonly complete: boolean;
};
type AssemblyReference = ManagedArtifactInspection["references"][number];
type ManagedResource = ManagedArtifactInspection["resources"][number];
type CustomAttribute = ManagedArtifactInspection["attributes"][number];
export interface ManagedInventoryInput {
readonly referenceOffset: number;
readonly referenceLimit: number;
readonly resourceOffset: number;
readonly resourceLimit: number;
readonly attributeOffset: number;
readonly attributeLimit: number;
readonly maxHeapItemBytes: number;
}
@@ -53,9 +36,9 @@ export interface ManagedMetadataInventory {
readonly assembly: AssemblyIdentity | null;
readonly targetFrameworks: readonly string[];
readonly referenceNames: readonly string[];
readonly references: ManagedPage<AssemblyReference>;
readonly resources: ManagedPage<ManagedResource>;
readonly attributes: ManagedPage<CustomAttribute>;
readonly references: readonly AssemblyReference[];
readonly resources: readonly ManagedResource[];
readonly attributes: readonly CustomAttribute[];
readonly issues: readonly ManagedParseIssue[];
}
@@ -72,28 +55,17 @@ const safeRead = <Value>(
}
};
const pageRows = <Item>(
const readRows = <Item>(
descriptor: MetadataTableLayout | undefined,
offset: number,
limit: number,
read: (row: number) => Item | undefined,
): ManagedPage<Item> => {
): readonly Item[] => {
const total = descriptor?.rowCount ?? 0;
const items: Item[] = [];
const end = Math.min(total, offset + limit);
for (let index = offset; index < end; index += 1) {
for (let index = 0; index < total; index += 1) {
const item = read(index + 1);
if (item !== undefined) items.push(item);
}
return {
items,
offset,
limit,
total,
returned: items.length,
dropped: total - items.length,
complete: offset === 0 && end === total && items.length === total,
};
return items;
};
const uniqueIssues = (
@@ -102,24 +74,20 @@ const uniqueIssues = (
...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values(),
];
const readPagedReferences = (
const readReferences = (
bytes: Buffer,
layout: ManagedMetadataLayout,
input: ManagedInventoryInput,
issues: ManagedParseIssue[],
): ManagedPage<AssemblyReference> =>
pageRows(
layout.table(35),
input.referenceOffset,
input.referenceLimit,
(row) =>
safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
): readonly AssemblyReference[] =>
readRows(layout.table(35), (row) =>
safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
);
const readPagedResources = ({
const readResources = ({
bytes,
layout,
input,
@@ -131,8 +99,8 @@ const readPagedResources = ({
readonly input: ManagedInventoryInput;
readonly resourceDirectory: ManagedResourceDirectory | null;
readonly issues: ManagedParseIssue[];
}): ManagedPage<ManagedResource> =>
pageRows(layout.table(40), input.resourceOffset, input.resourceLimit, (row) =>
}): readonly ManagedResource[] =>
readRows(layout.table(40), (row) =>
safeRead(
() =>
readResource({
@@ -147,21 +115,17 @@ const readPagedResources = ({
),
);
const readPagedAttributes = (
const readAttributes = (
bytes: Buffer,
layout: ManagedMetadataLayout,
input: ManagedInventoryInput,
issues: ManagedParseIssue[],
): ManagedPage<CustomAttribute> =>
pageRows(
layout.table(12),
input.attributeOffset,
input.attributeLimit,
(row) =>
safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
): readonly CustomAttribute[] =>
readRows(layout.table(12), (row) =>
safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
);
const collectReferenceNames = (
@@ -223,15 +187,15 @@ export const readManagedMetadataInventory = (
() => readAssembly(bytes, layout, input.maxHeapItemBytes),
issues,
) ?? null;
const references = readPagedReferences(bytes, layout, input, issues);
const resources = readPagedResources({
const references = readReferences(bytes, layout, input, issues);
const resources = readResources({
bytes,
layout,
input,
resourceDirectory,
issues,
});
const attributes = readPagedAttributes(bytes, layout, input, issues);
const attributes = readAttributes(bytes, layout, input, issues);
const referenceNames = collectReferenceNames(
bytes,
layout,
+3 -4
View File
@@ -21,10 +21,9 @@ import type { ManagedResourceDirectory } from "./ManagedMetadataInventory.js";
type ModuleIdentity = NonNullable<ManagedArtifactInspection["module"]>;
type AssemblyIdentity = NonNullable<ManagedArtifactInspection["assembly"]>;
type AssemblyReference =
ManagedArtifactInspection["references"]["items"][number];
type ManagedResource = ManagedArtifactInspection["resources"]["items"][number];
type CustomAttribute = ManagedArtifactInspection["attributes"]["items"][number];
type AssemblyReference = ManagedArtifactInspection["references"][number];
type ManagedResource = ManagedArtifactInspection["resources"][number];
type CustomAttribute = ManagedArtifactInspection["attributes"][number];
const publicKeyIdentity = (
bytes: Buffer,
+2 -4
View File
@@ -74,10 +74,8 @@ export const methodBody = (
opcodeCounts[instruction.opcode] =
(opcodeCounts[instruction.opcode] ?? 0) + 1;
const anchors = decoded.parsed
.map((instruction, index) => ({ instruction, index }))
.filter(({ instruction }) => instruction.operandKind !== "none")
.slice(0, limits.instructionAnchorLimit)
.map(({ instruction }) => ({
.filter((instruction) => instruction.operandKind !== "none")
.map((instruction) => ({
il_offset: instruction.offset,
opcode: instruction.opcode,
operand_kind: instruction.operandKind,
+6 -47
View File
@@ -13,25 +13,12 @@ import {
} from "./ManagedMetadataHeaps.js";
import { managedTableRowCounts } from "./ManagedMetadataInventory.js";
import type { ManagedMetadataInventory } from "./ManagedMetadataInventory.js";
import type { ManagedNativeBoundaryInspectionLimits } from "./ManagedNativeBoundaryInspector.js";
import type { ManagedPeLayout } from "./ManagedPeReader.js";
type Page<Item> = {
readonly items: readonly Item[];
readonly offset: number;
readonly limit: number;
readonly total: number;
readonly returned: number;
readonly dropped: number;
readonly complete: boolean;
};
type ModuleRef =
ManagedNativeBoundaryInspection["module_refs"]["items"][number];
type NativeImport =
ManagedNativeBoundaryInspection["pinvoke_imports"]["items"][number];
type ModuleRef = ManagedNativeBoundaryInspection["module_refs"][number];
type NativeImport = ManagedNativeBoundaryInspection["pinvoke_imports"][number];
type NativeImplementation =
ManagedNativeBoundaryInspection["native_implementations"]["items"][number];
ManagedNativeBoundaryInspection["native_implementations"][number];
interface MemberCore {
readonly token: string;
@@ -46,24 +33,6 @@ interface MemberCore {
const flagsHex = (value: number): string =>
`0x${value.toString(16).padStart(4, "0")}`;
const page = <Item>(
items: readonly Item[],
offset: number,
limit: number,
): Page<Item> => {
const safeOffset = Math.min(offset, items.length);
const selected = items.slice(safeOffset, safeOffset + limit);
return {
items: selected,
offset,
limit,
total: items.length,
returned: selected.length,
dropped: Math.max(0, items.length - safeOffset - selected.length),
complete: safeOffset === 0 && selected.length === items.length,
};
};
export const parseModuleRefs = (
bytes: Buffer,
layout: ManagedMetadataLayout,
@@ -378,7 +347,6 @@ export const cliNative = (
interface BoundaryInspectionContext {
readonly target: BinaryTarget;
readonly bytes: Buffer;
readonly limits: ManagedNativeBoundaryInspectionLimits;
readonly pe: ManagedPeLayout;
readonly layout: ManagedMetadataLayout;
readonly inventory: ManagedMetadataInventory;
@@ -392,7 +360,6 @@ interface BoundaryInspectionContext {
export const buildNativeBoundaryInspection = ({
target,
bytes,
limits,
layout,
inventory,
moduleRefs,
@@ -421,17 +388,9 @@ export const buildNativeBoundaryInspection = ({
requires_mvid: inventory.module?.mvid ?? null,
},
cli_native: native,
module_refs: page(
moduleRefs,
limits.moduleRefOffset,
limits.moduleRefLimit,
),
pinvoke_imports: page(imports, limits.importOffset, limits.importLimit),
native_implementations: page(
implementations,
limits.implementationOffset,
limits.implementationLimit,
),
module_refs: moduleRefs,
pinvoke_imports: imports,
native_implementations: implementations,
summary: {
module_ref_count: moduleRefs.length,
pinvoke_import_count: imports.length,
@@ -32,14 +32,14 @@ describe("managed native boundaries", () => {
managed_native_header_rva: 0x2700,
managed_native_header_size: 4,
});
expect(result.module_refs.items).toEqual([
expect(result.module_refs).toEqual([
{
token: "0x1a000001",
row_offset: expect.any(Number),
name: "user32.dll",
},
]);
expect(result.pinvoke_imports.items).toEqual([
expect(result.pinvoke_imports).toEqual([
expect.objectContaining({
token: "0x1c000001",
member_token: "0x06000001",
@@ -55,7 +55,7 @@ describe("managed native boundaries", () => {
verification: "managed-declaration-only",
}),
]);
expect(result.native_implementations.items).toEqual([
expect(result.native_implementations).toEqual([
expect.objectContaining({
token: "0x06000001",
name: "Main",
@@ -76,23 +76,14 @@ describe("managed native boundaries", () => {
);
});
it("keeps member evidence bounded and typed for pagination and unavailable metadata", () => {
it("returns complete member inventories inline and reports unavailable metadata", () => {
const bytes = buildManagedPeFixture();
const paged = inspectManagedMembersBytes(
bytes,
managedPeFixtureTarget(bytes),
{
...MANAGED_MEMBER_FIXTURE_LIMITS,
methodLimit: 0 + 1,
instructionAnchorLimit: 1,
},
MANAGED_MEMBER_FIXTURE_LIMITS,
);
expect(paged.methods).toMatchObject({
total: 1,
returned: 1,
complete: true,
});
expect(paged.methods.items[0]?.body.anchors).toHaveLength(1);
expect(paged.methods).toHaveLength(1);
const nativeBytes = buildNativePeFixture();
const native = inspectManagedMembersBytes(
+3 -29
View File
@@ -28,12 +28,6 @@ import {
} from "./ManagedNativeBoundaryHelpers.js";
export interface ManagedNativeBoundaryInspectionLimits {
readonly moduleRefOffset: number;
readonly moduleRefLimit: number;
readonly importOffset: number;
readonly importLimit: number;
readonly implementationOffset: number;
readonly implementationLimit: number;
readonly maxMetadataBytes: number;
readonly maxTableRows: number;
readonly maxHeapItemBytes: number;
@@ -41,18 +35,6 @@ export interface ManagedNativeBoundaryInspectionLimits {
type Inventory = ReturnType<typeof readManagedMetadataInventory>;
const emptyPage = <Item>(): ManagedNativeBoundaryInspection["module_refs"] & {
items: readonly Item[];
} => ({
items: [],
offset: 0,
limit: 0,
total: 0,
returned: 0,
dropped: 0,
complete: true,
});
const emptyInspection = (
target: BinaryTarget,
bytes: Buffer,
@@ -60,7 +42,6 @@ const emptyInspection = (
issues: readonly ManagedParseIssue[] = [],
): ManagedNativeBoundaryInspection =>
managedNativeBoundaryInspectionSchema.parse({
schema_version: 1,
artifact: {
path: target.path,
sha256: target.sha256,
@@ -90,9 +71,9 @@ const emptyInspection = (
managed_native_header_rva: 0,
managed_native_header_size: 0,
},
module_refs: emptyPage(),
pinvoke_imports: emptyPage(),
native_implementations: emptyPage(),
module_refs: [],
pinvoke_imports: [],
native_implementations: [],
summary: {
module_ref_count: 0,
pinvoke_import_count: 0,
@@ -139,12 +120,6 @@ const readBoundaryInventory = (
bytes,
layout,
{
referenceOffset: 0,
referenceLimit: 0,
resourceOffset: 0,
resourceLimit: 0,
attributeOffset: 0,
attributeLimit: 0,
maxHeapItemBytes: limits.maxHeapItemBytes,
},
resourceDirectory,
@@ -218,7 +193,6 @@ export const inspectManagedNativeBoundariesBytes = (
return buildNativeBoundaryInspection({
target,
bytes,
limits,
pe,
layout,
inventory,
-23
View File
@@ -75,12 +75,6 @@ const DEFAULT_MVID = Buffer.from([
/** 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,
@@ -88,17 +82,6 @@ export const MANAGED_ARTIFACT_FIXTURE_LIMITS = {
/** 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,
@@ -114,12 +97,6 @@ export const MANAGED_MEMBER_PATH_FIXTURE_LIMITS = {
/** 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,
+21 -56
View File
@@ -37,6 +37,7 @@ import { err, ok } from "../domain/result.js";
import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
import { MANAGED_INSPECTION_DEFAULTS } from "./ManagedInspectionDefaults.js";
const IDENTITY: ProviderIdentity = Object.freeze(MANAGED_STATIC_PROVIDER);
@@ -47,12 +48,10 @@ export class ManagedStaticProvider implements AnalysisProvider {
Object.freeze({
provider: IDENTITY,
operation: contract.name,
inputContractVersion: 1,
outputContractVersion: 1,
available: true as const,
reason: null,
pagination: "offset" as const,
exhaustive: false,
pagination: "none" as const,
exhaustive: true,
effects: Object.freeze({
mutatesArtifact: false,
launchesProcess: false,
@@ -63,7 +62,7 @@ export class ManagedStaticProvider implements AnalysisProvider {
requiresRoot: false,
}),
limits: Object.freeze({
maxResults: 500,
maxResults: null,
maxPayloadBytes: 4 * 1024 * 1024,
timeoutMs: null,
}),
@@ -116,7 +115,7 @@ class ManagedStaticClient implements AnalysisClient {
try {
if (options?.signal?.aborted === true)
return err(new AnalysisCancelledError(operation));
const maxFileBytes = maxRequestedFileBytes(operation, parameters);
const maxFileBytes = MANAGED_INSPECTION_DEFAULTS.maxFileBytes;
const metadata = await stat(this.target.path);
if (metadata.size > maxFileBytes)
return err(
@@ -239,17 +238,6 @@ const limitationsFor = (operation: ManagedToolName): readonly string[] =>
],
);
const maxRequestedFileBytes = (
operation: ManagedToolName,
parameters: Readonly<Record<string, JsonValue>>,
): number => {
if (operation === "inspect_managed_artifact")
return managedArtifactInputSchema.parse(parameters).max_file_bytes;
if (operation === "inspect_managed_native_boundaries")
return managedNativeBoundaryInputSchema.parse(parameters).max_file_bytes;
return managedMemberInputSchema.parse(parameters).max_file_bytes;
};
const inspectManagedOperation = (
operation: ManagedToolName,
parameters: Readonly<Record<string, JsonValue>>,
@@ -260,51 +248,28 @@ const inspectManagedOperation = (
| ManagedMemberInspection
| ManagedNativeBoundaryInspection => {
if (operation === "inspect_managed_artifact") {
const input = managedArtifactInputSchema.parse(parameters);
managedArtifactInputSchema.parse(parameters);
return inspectManagedArtifactBytes(bytes, target, {
referenceOffset: input.reference_offset,
referenceLimit: input.reference_limit,
resourceOffset: input.resource_offset,
resourceLimit: input.resource_limit,
attributeOffset: input.attribute_offset,
attributeLimit: input.attribute_limit,
maxMetadataBytes: input.max_metadata_bytes,
maxTableRows: input.max_table_rows,
maxHeapItemBytes: input.max_heap_item_bytes,
maxMetadataBytes: MANAGED_INSPECTION_DEFAULTS.maxMetadataBytes,
maxTableRows: MANAGED_INSPECTION_DEFAULTS.maxTableRows,
maxHeapItemBytes: MANAGED_INSPECTION_DEFAULTS.maxHeapItemBytes,
});
}
if (operation === "inspect_managed_native_boundaries") {
const input = managedNativeBoundaryInputSchema.parse(parameters);
managedNativeBoundaryInputSchema.parse(parameters);
return inspectManagedNativeBoundariesBytes(bytes, target, {
moduleRefOffset: input.module_ref_offset,
moduleRefLimit: input.module_ref_limit,
importOffset: input.import_offset,
importLimit: input.import_limit,
implementationOffset: input.implementation_offset,
implementationLimit: input.implementation_limit,
maxMetadataBytes: input.max_metadata_bytes,
maxTableRows: input.max_table_rows,
maxHeapItemBytes: input.max_heap_item_bytes,
maxMetadataBytes: MANAGED_INSPECTION_DEFAULTS.maxMetadataBytes,
maxTableRows: MANAGED_INSPECTION_DEFAULTS.maxTableRows,
maxHeapItemBytes: MANAGED_INSPECTION_DEFAULTS.maxHeapItemBytes,
});
}
const input = managedMemberInputSchema.parse(parameters);
managedMemberInputSchema.parse(parameters);
return inspectManagedMembersBytes(bytes, target, {
typeOffset: input.type_offset,
typeLimit: input.type_limit,
methodOffset: input.method_offset,
methodLimit: input.method_limit,
fieldOffset: input.field_offset,
fieldLimit: input.field_limit,
memberRefOffset: input.member_ref_offset,
memberRefLimit: input.member_ref_limit,
edgeOffset: input.edge_offset,
edgeLimit: input.edge_limit,
instructionAnchorLimit: input.instruction_anchor_limit,
maxMetadataBytes: input.max_metadata_bytes,
maxTableRows: input.max_table_rows,
maxHeapItemBytes: input.max_heap_item_bytes,
maxMethodBodyBytes: input.max_method_body_bytes,
maxMethodInstructions: input.max_method_instructions,
maxMetadataBytes: MANAGED_INSPECTION_DEFAULTS.maxMetadataBytes,
maxTableRows: MANAGED_INSPECTION_DEFAULTS.maxTableRows,
maxHeapItemBytes: MANAGED_INSPECTION_DEFAULTS.maxHeapItemBytes,
maxMethodBodyBytes: MANAGED_INSPECTION_DEFAULTS.maxMethodBodyBytes,
maxMethodInstructions: MANAGED_INSPECTION_DEFAULTS.maxMethodInstructions,
});
};
@@ -335,7 +300,7 @@ const managedLocations = (
...(result.module === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [{ kind: "file-offset" as const, offset: result.module.row_offset }]),
...result.methods.items
...result.methods
.filter((method) => method.body.file_offset !== null)
.slice(0, 8)
.map((method) => ({
@@ -347,7 +312,7 @@ const managedLocations = (
...(result.module === null
? [{ kind: "file-offset" as const, offset: 0 }]
: [{ kind: "file-offset" as const, offset: result.module.row_offset }]),
...result.pinvoke_imports.items.slice(0, 8).map((mapping) => ({
...result.pinvoke_imports.slice(0, 8).map((mapping) => ({
kind: "file-offset" as const,
offset: mapping.row_offset,
})),