refactor(managed): split metadata analysis

This commit is contained in:
morluto
2026-07-18 05:49:14 +00:00
parent e2c868c4bd
commit 20c88dd567
17 changed files with 3687 additions and 2983 deletions
+80 -36
View File
@@ -161,16 +161,21 @@ const unavailableResult = (
});
};
const runtimeClassification = (
layout: ManagedPeLayout,
metadata: ManagedMetadataLayout,
interface RuntimeClassificationInput {
readonly layout: ManagedPeLayout;
readonly metadata: ManagedMetadataLayout;
readonly inventory: ManagedMetadataInventory;
}
const runtimeFamilyFor = (
cli: ManagedCliHeader,
inventory: ManagedMetadataInventory,
metadata: ManagedMetadataLayout,
layout: ManagedPeLayout,
): Pick<
ManagedArtifactInspection["classification"],
"runtime_family" | "implementation" | "managed_architecture" | "evidence"
"runtime_family" | "evidence"
> => {
const cli = layout.cli;
if (cli === null) throw new TypeError("Managed classification requires CLI");
const evidence: ManagedArtifactInspection["classification"]["evidence"] = [
{
code: "cli-header-observed",
@@ -232,22 +237,47 @@ const runtimeClassification = (
: (metadata.table(12)?.offset ?? null),
});
}
const implementation =
(cli.flags & 1) === 0
? ("cpp-cli-mixed" as const)
: cli.readyToRunSignature
? ("cil-and-ready-to-run" as const)
: (metadata.rowCounts[6] ?? 0) === 0
? ("metadata-only" as const)
: ("cil" as const);
const managedArchitecture =
layout.architecture === "x86" && (cli.flags & 1) !== 0
? (cli.flags & 0x0000_0002) !== 0
? "x86"
: (cli.flags & 0x0002_0000) !== 0
? "anycpu-prefer-32"
: "anycpu"
: layout.architecture;
return { runtime_family: runtimeFamily, evidence };
};
const implementationFor = (
cli: ManagedCliHeader,
metadata: ManagedMetadataLayout,
): ManagedArtifactInspection["classification"]["implementation"] => {
if ((cli.flags & 1) === 0) return "cpp-cli-mixed";
if (cli.readyToRunSignature) return "cil-and-ready-to-run";
return (metadata.rowCounts[6] ?? 0) === 0 ? "metadata-only" : "cil";
};
const managedArchitectureFor = (
layout: ManagedPeLayout,
cli: ManagedCliHeader,
): ManagedArtifactInspection["classification"]["managed_architecture"] => {
if (layout.architecture !== "x86" || (cli.flags & 1) === 0)
return layout.architecture;
if ((cli.flags & 0x0000_0002) !== 0) return "x86";
if ((cli.flags & 0x0002_0000) !== 0) return "anycpu-prefer-32";
return "anycpu";
};
const runtimeClassification = ({
layout,
metadata,
inventory,
}: RuntimeClassificationInput): Pick<
ManagedArtifactInspection["classification"],
"runtime_family" | "implementation" | "managed_architecture" | "evidence"
> => {
const cli = layout.cli;
if (cli === null) throw new TypeError("Managed classification requires CLI");
const { runtime_family: runtimeFamily, evidence } = runtimeFamilyFor(
cli,
inventory,
metadata,
layout,
);
const implementation = implementationFor(cli, metadata);
const managedArchitecture = managedArchitectureFor(layout, cli);
evidence.push({
code: "managed-architecture-derived",
detail: `Managed architecture ${managedArchitecture} is derived from PE machine and CLI flags.`,
@@ -261,13 +291,21 @@ const runtimeClassification = (
};
};
const partialMetadataResult = (
target: BinaryTarget,
bytes: Buffer,
layout: ManagedPeLayout,
limits: ManagedInspectionLimits,
issue: ManagedParseIssue,
): ManagedArtifactInspection => ({
interface PartialMetadataContext {
readonly target: BinaryTarget;
readonly bytes: Buffer;
readonly layout: ManagedPeLayout;
readonly limits: ManagedInspectionLimits;
readonly issue: ManagedParseIssue;
}
const partialMetadataResult = ({
target,
bytes,
layout,
limits,
issue,
}: PartialMetadataContext): ManagedArtifactInspection => ({
...base(target, bytes, layout),
classification: {
status: "malformed",
@@ -338,11 +376,17 @@ export const inspectManagedArtifactBytes = (
const cli = layout.cli;
if (cli.metadata.size > limits.maxMetadataBytes)
return managedArtifactInspectionSchema.parse(
partialMetadataResult(target, bytes, layout, limits, {
code: "limit-exceeded",
scope: "cli.metadata",
offset: cli.headerOffset + 8,
detail: `CLI metadata size exceeds max_metadata_bytes ${String(limits.maxMetadataBytes)}`,
partialMetadataResult({
target,
bytes,
layout,
limits,
issue: {
code: "limit-exceeded",
scope: "cli.metadata",
offset: cli.headerOffset + 8,
detail: `CLI metadata size exceeds max_metadata_bytes ${String(limits.maxMetadataBytes)}`,
},
}),
);
let metadata: ManagedMetadataLayout;
@@ -361,7 +405,7 @@ export const inspectManagedArtifactBytes = (
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
return managedArtifactInspectionSchema.parse(
partialMetadataResult(target, bytes, layout, limits, cause.issue),
partialMetadataResult({ target, bytes, layout, limits, issue: cause.issue }),
);
}
const resourceIssues: ManagedParseIssue[] = [];
@@ -395,7 +439,7 @@ export const inspectManagedArtifactBytes = (
classification: {
status: "managed",
container: "pe",
...runtimeClassification(layout, metadata, inventory),
...runtimeClassification({ layout, metadata, inventory }),
},
metadata: {
status: issues.length === 0 ? "complete" : "partial",
+133 -538
View File
@@ -4,23 +4,18 @@ import type {
} from "../domain/managedArtifact.js";
import {
METADATA_TABLE_NAMES,
metadataRowOffset,
type ManagedMetadataLayout,
type MetadataTableLayout,
} from "./ManagedMetadataLayout.js";
import {
MetadataRowCursor,
metadataToken,
readMetadataBlob,
readMetadataGuid,
readMetadataString,
sha256Bytes,
strongNameToken,
} from "./ManagedMetadataHeaps.js";
import {
ManagedReaderFailure,
managedFailure,
} from "./ManagedReaderFailure.js";
readAssembly,
readAssemblyReference,
readCustomAttribute,
readModule,
readResource,
} from "./ManagedMetadataInventoryRows.js";
import { metadataToken } from "./ManagedMetadataHeaps.js";
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
type ModuleIdentity = NonNullable<ManagedArtifactInspection["module"]>;
type AssemblyIdentity = NonNullable<ManagedArtifactInspection["assembly"]>;
@@ -64,469 +59,6 @@ export interface ManagedMetadataInventory {
readonly issues: readonly ManagedParseIssue[];
}
const rowCursor = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: number,
row: number,
): MetadataRowCursor => {
const descriptor = layout.table(table);
const start = metadataRowOffset(layout, table, row);
if (descriptor === undefined)
throw managedFailure(
"invalid-row",
`metadata.${String(table)}`,
"Metadata table is absent",
start,
);
return new MetadataRowCursor(
bytes,
start,
start + descriptor.rowSize,
`metadata.${descriptor.name}`,
);
};
const publicKeyIdentity = (
bytes: Buffer,
kind: "public-key" | "public-key-token",
): AssemblyIdentity["public_key"] => ({
kind: bytes.length === 0 ? "none" : kind,
byte_length: bytes.length,
sha256: bytes.length === 0 ? null : sha256Bytes(bytes),
token:
bytes.length === 0
? null
: kind === "public-key"
? strongNameToken(bytes)
: bytes.length === 8
? bytes.toString("hex")
: null,
});
const readModule = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ModuleIdentity | null => {
const table = layout.table(0);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor(bytes, layout, 0, 1);
const generation = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const mvid = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encBaseId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
return {
name,
generation,
mvid,
enc_id: encId,
enc_base_id: encBaseId,
token: metadataToken(0, 1),
row_offset: table.offset,
};
};
const readAssembly = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): AssemblyIdentity | null => {
const table = layout.table(32);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor(bytes, layout, 32, 1);
const hashAlgorithm = cursor.readUInt32();
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const key = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
hash_algorithm: hashAlgorithm,
public_key: publicKeyIdentity(
key,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
token: metadataToken(32, 1),
row_offset: table.offset,
};
};
const readAssemblyReference = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): AssemblyReference => {
const cursor = rowCursor(bytes, layout, 35, row);
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const keyOrToken = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const hashValue = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
public_key_or_token: publicKeyIdentity(
keyOrToken,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
hash_value_sha256: hashValue.length === 0 ? null : sha256Bytes(hashValue),
hash_value_length: hashValue.length,
token: metadataToken(35, row),
row_offset: metadataRowOffset(layout, 35, row),
};
};
const codedToken = (
raw: number,
bits: number,
tables: readonly (number | undefined)[],
): string | null => {
if (raw === 0) return null;
const tag = raw & (2 ** bits - 1);
const row = Math.floor(raw / 2 ** bits);
const table = tables[tag];
return table === undefined || row === 0 ? null : metadataToken(table, row);
};
const readTypeName = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: 1 | 2,
row: number,
maxBytes: number,
): string | null => {
const descriptor = layout.table(table);
if (descriptor === undefined || row < 1 || row > descriptor.rowCount)
return null;
const cursor = rowCursor(bytes, layout, table, row);
if (table === 1) cursor.readIndex(layout.codedIndexSize("ResolutionScope"));
else cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const namespace = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
};
const declaringTypeForMethod = (
bytes: Buffer,
layout: ManagedMetadataLayout,
methodRow: number,
maxBytes: number,
): string | null => {
const types = layout.table(2);
const methods = layout.table(6);
if (types === undefined || methods === undefined) return null;
for (let row = 1; row <= types.rowCount; row += 1) {
const cursor = rowCursor(bytes, layout, 2, row);
cursor.readUInt32();
const nameIndex = cursor.readIndex(layout.stringIndexSize);
const namespaceIndex = cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
const methodEnd =
row === types.rowCount
? methods.rowCount + 1
: methodListForType(bytes, layout, row + 1);
if (methodRow < methodStart || methodRow >= methodEnd) continue;
const name = readMetadataString(bytes, layout, nameIndex, maxBytes);
const namespace = readMetadataString(
bytes,
layout,
namespaceIndex,
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
}
return null;
};
const methodListForType = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
): number => {
const cursor = rowCursor(bytes, layout, 2, row);
cursor.readUInt32();
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
return cursor.readIndex(layout.tableIndexSize(6));
};
const attributeTypeName = (
bytes: Buffer,
layout: ManagedMetadataLayout,
rawType: number,
maxBytes: number,
): string | null => {
const tag = rawType & 7;
const row = Math.floor(rawType / 8);
if (row === 0) return null;
if (tag === 2) return declaringTypeForMethod(bytes, layout, row, maxBytes);
if (tag !== 3) return null;
const memberRefs = layout.table(10);
if (memberRefs === undefined || row > memberRefs.rowCount) return null;
const cursor = rowCursor(bytes, layout, 10, row);
const parent = cursor.readIndex(layout.codedIndexSize("MemberRefParent"));
const parentTag = parent & 7;
const parentRow = Math.floor(parent / 8);
if (parentTag === 0)
return readTypeName(bytes, layout, 2, parentRow, maxBytes);
if (parentTag === 1)
return readTypeName(bytes, layout, 1, parentRow, maxBytes);
if (parentTag === 3)
return declaringTypeForMethod(bytes, layout, parentRow, maxBytes);
return null;
};
const decodeCompressedLength = (
blob: Buffer,
offset: number,
): { readonly length: number; readonly prefix: number } | undefined => {
const first = blob[offset];
if (first === undefined) return undefined;
if ((first & 0x80) === 0) return { length: first, prefix: 1 };
if ((first & 0xc0) === 0x80 && blob[offset + 1] !== undefined)
return {
length: ((first & 0x3f) << 8) | (blob[offset + 1] ?? 0),
prefix: 2,
};
if (
(first & 0xe0) === 0xc0 &&
blob[offset + 1] !== undefined &&
blob[offset + 2] !== undefined &&
blob[offset + 3] !== undefined
)
return {
length:
(first & 0x1f) * 0x01_00_00_00 +
(blob[offset + 1] ?? 0) * 0x01_00_00 +
(blob[offset + 2] ?? 0) * 0x0100 +
(blob[offset + 3] ?? 0),
prefix: 4,
};
return undefined;
};
const decodeFixedString = (blob: Buffer): string | null => {
if (blob.length < 3 || blob.readUInt16LE(0) !== 1 || blob[2] === 0xff)
return null;
const length = decodeCompressedLength(blob, 2);
if (length === undefined) return null;
const start = 2 + length.prefix;
if (start > blob.length - length.length) return null;
try {
return new TextDecoder("utf-8", { fatal: true }).decode(
blob.subarray(start, start + length.length),
);
} catch {
return null;
}
};
const readCustomAttribute = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): CustomAttribute => {
const cursor = rowCursor(bytes, layout, 12, row);
const parentRaw = cursor.readIndex(
layout.codedIndexSize("HasCustomAttribute"),
);
const typeRaw = cursor.readIndex(
layout.codedIndexSize("CustomAttributeType"),
);
const value = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const parent = codedToken(
parentRaw,
5,
[
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
44, 43,
],
);
if (parent === null)
throw managedFailure(
"invalid-row",
"metadata.CustomAttribute",
"CustomAttribute parent coded index is invalid",
cursor.start,
);
const typeName = attributeTypeName(bytes, layout, typeRaw, maxBytes);
return {
parent_token: parent,
constructor_token: codedToken(typeRaw, 3, [undefined, undefined, 6, 10]),
type_name: typeName,
value_length: value.length,
value_sha256: sha256Bytes(value),
decoded_fixed_string:
typeName === "System.Runtime.Versioning.TargetFrameworkAttribute"
? decodeFixedString(value)
: null,
token: metadataToken(12, row),
row_offset: cursor.start,
};
};
const readResource = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
directory: ManagedResourceDirectory | null,
issues: ManagedParseIssue[],
): ManagedResource => {
const cursor = rowCursor(bytes, layout, 40, row);
const declaredOffset = cursor.readUInt32();
const flags = cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const implementationRaw = cursor.readIndex(
layout.codedIndexSize("Implementation"),
);
const implementationToken = codedToken(implementationRaw, 2, [38, 35, 39]);
let dataLength: number | null = null;
let dataSha256: string | null = null;
if (implementationRaw === 0) {
if (directory === null || declaredOffset > directory.size - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: directory?.offset ?? null,
detail: "Embedded resource offset leaves the CLI resources directory",
});
} else {
const start = directory.offset + declaredOffset;
dataLength = bytes.readUInt32LE(start);
if (dataLength > directory.size - declaredOffset - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start,
detail: "Embedded resource length leaves the CLI resources directory",
});
} else if (dataLength > maxBytes) {
issues.push({
code: "limit-exceeded",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start + 4,
detail: `Embedded resource exceeds max_heap_item_bytes ${String(maxBytes)}; digest omitted`,
});
} else {
dataSha256 = sha256Bytes(
bytes.subarray(start + 4, start + 4 + dataLength),
);
}
}
}
return {
name,
flags,
visibility:
(flags & 7) === 1 ? "public" : (flags & 7) === 2 ? "private" : "unknown",
implementation_token: implementationToken,
embedded: implementationRaw === 0,
declared_offset: declaredOffset,
data_length: dataLength,
data_sha256: dataSha256,
token: metadataToken(40, row),
row_offset: cursor.start,
};
};
const safeRead = <Value>(
operation: () => Value,
issues: ManagedParseIssue[],
@@ -570,6 +102,111 @@ const uniqueIssues = (
...new Map(issues.map((issue) => [JSON.stringify(issue), issue])).values(),
];
const readPagedReferences = (
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,
),
);
const readPagedResources = ({
bytes,
layout,
input,
resourceDirectory,
issues,
}: {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly input: ManagedInventoryInput;
readonly resourceDirectory: ManagedResourceDirectory | null;
readonly issues: ManagedParseIssue[];
}): ManagedPage<ManagedResource> =>
pageRows(layout.table(40), input.resourceOffset, input.resourceLimit, (row) =>
safeRead(
() =>
readResource({
bytes,
layout,
row,
maxBytes: input.maxHeapItemBytes,
directory: resourceDirectory,
issues,
}),
issues,
),
);
const readPagedAttributes = (
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,
),
);
const collectReferenceNames = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
issues: ManagedParseIssue[],
): readonly string[] => {
const names: string[] = [];
const referenceTable = layout.table(35);
for (let row = 1; row <= (referenceTable?.rowCount ?? 0); row += 1) {
const reference = safeRead(
() => readAssemblyReference(bytes, layout, row, maxBytes),
issues,
);
if (reference !== undefined) names.push(reference.name);
}
return names;
};
const collectTargetFrameworks = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
issues: ManagedParseIssue[],
): readonly string[] => {
const targetFrameworks: string[] = [];
const attributeTable = layout.table(12);
for (let row = 1; row <= (attributeTable?.rowCount ?? 0); row += 1) {
const attribute = safeRead(
() => readCustomAttribute(bytes, layout, row, maxBytes),
issues,
);
if (
attribute?.parent_token === metadataToken(32, 1) &&
attribute.type_name ===
"System.Runtime.Versioning.TargetFrameworkAttribute" &&
attribute.decoded_fixed_string !== null &&
!targetFrameworks.includes(attribute.decoded_fixed_string)
)
targetFrameworks.push(attribute.decoded_fixed_string);
}
return targetFrameworks;
};
/** Inventory bounded identity tables without CLR reflection or execution. */
export const readManagedMetadataInventory = (
bytes: Buffer,
@@ -586,73 +223,31 @@ export const readManagedMetadataInventory = (
() => readAssembly(bytes, layout, input.maxHeapItemBytes),
issues,
) ?? null;
const references = pageRows(
layout.table(35),
input.referenceOffset,
input.referenceLimit,
(row) =>
safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
const references = readPagedReferences(bytes, layout, input, issues);
const resources = readPagedResources({
bytes,
layout,
input,
resourceDirectory,
issues,
});
const attributes = readPagedAttributes(bytes, layout, input, issues);
const referenceNames = collectReferenceNames(
bytes,
layout,
input.maxHeapItemBytes,
issues,
);
const resources = pageRows(
layout.table(40),
input.resourceOffset,
input.resourceLimit,
(row) =>
safeRead(
() =>
readResource(
bytes,
layout,
row,
input.maxHeapItemBytes,
resourceDirectory,
issues,
),
issues,
),
const targetFrameworks = collectTargetFrameworks(
bytes,
layout,
input.maxHeapItemBytes,
issues,
);
const attributes = pageRows(
layout.table(12),
input.attributeOffset,
input.attributeLimit,
(row) =>
safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
),
);
const referenceNames: string[] = [];
const referenceTable = layout.table(35);
for (let row = 1; row <= (referenceTable?.rowCount ?? 0); row += 1) {
const reference = safeRead(
() => readAssemblyReference(bytes, layout, row, input.maxHeapItemBytes),
issues,
);
if (reference !== undefined) referenceNames.push(reference.name);
}
const targetFrameworks: string[] = [];
const attributeTable = layout.table(12);
for (let row = 1; row <= (attributeTable?.rowCount ?? 0); row += 1) {
const attribute = safeRead(
() => readCustomAttribute(bytes, layout, row, input.maxHeapItemBytes),
issues,
);
if (
attribute?.parent_token === metadataToken(32, 1) &&
attribute.type_name ===
"System.Runtime.Versioning.TargetFrameworkAttribute" &&
attribute.decoded_fixed_string !== null &&
!targetFrameworks.includes(attribute.decoded_fixed_string)
)
targetFrameworks.push(attribute.decoded_fixed_string);
}
return {
module,
assembly,
targetFrameworks: targetFrameworks.sort(),
targetFrameworks: [...targetFrameworks].sort(),
referenceNames: [...new Set(referenceNames)].sort(),
references,
resources,
+513
View File
@@ -0,0 +1,513 @@
import type {
ManagedArtifactInspection,
ManagedParseIssue,
} from "../domain/managedArtifact.js";
import {
metadataRowOffset,
type ManagedMetadataLayout,
} from "./ManagedMetadataLayout.js";
import {
MetadataRowCursor,
metadataToken,
readMetadataBlob,
readMetadataGuid,
readMetadataString,
sha256Bytes,
strongNameToken,
} from "./ManagedMetadataHeaps.js";
import { managedFailure } from "./ManagedReaderFailure.js";
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];
interface RowCursorContext {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly table: number;
readonly row: number;
}
const rowCursor = ({
bytes,
layout,
table,
row,
}: RowCursorContext): MetadataRowCursor => {
const descriptor = layout.table(table);
const start = metadataRowOffset(layout, table, row);
if (descriptor === undefined)
throw managedFailure(
"invalid-row",
`metadata.${String(table)}`,
"Metadata table is absent",
start,
);
return new MetadataRowCursor(
bytes,
start,
start + descriptor.rowSize,
`metadata.${descriptor.name}`,
);
};
const publicKeyIdentity = (
bytes: Buffer,
kind: "public-key" | "public-key-token",
): AssemblyIdentity["public_key"] => ({
kind: bytes.length === 0 ? "none" : kind,
byte_length: bytes.length,
sha256: bytes.length === 0 ? null : sha256Bytes(bytes),
token:
bytes.length === 0
? null
: kind === "public-key"
? strongNameToken(bytes)
: bytes.length === 8
? bytes.toString("hex")
: null,
});
export const readModule = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ModuleIdentity | null => {
const table = layout.table(0);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor({ bytes, layout, table: 0, row: 1 });
const generation = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const mvid = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
const encBaseId = readMetadataGuid(
bytes,
layout,
cursor.readIndex(layout.guidIndexSize),
);
return {
name,
generation,
mvid,
enc_id: encId,
enc_base_id: encBaseId,
token: metadataToken(0, 1),
row_offset: table.offset,
};
};
export const readAssembly = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): AssemblyIdentity | null => {
const table = layout.table(32);
if (table === undefined || table.rowCount === 0) return null;
const cursor = rowCursor({ bytes, layout, table: 32, row: 1 });
const hashAlgorithm = cursor.readUInt32();
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const key = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
hash_algorithm: hashAlgorithm,
public_key: publicKeyIdentity(
key,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
token: metadataToken(32, 1),
row_offset: table.offset,
};
};
export const readAssemblyReference = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): AssemblyReference => {
const cursor = rowCursor({ bytes, layout, table: 35, row });
const version = [
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
cursor.readUInt16(),
].join(".");
const flags = cursor.readUInt32();
const keyOrToken = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const culture = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const hashValue = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
return {
name,
version,
culture: culture.length === 0 ? null : culture,
flags,
public_key_or_token: publicKeyIdentity(
keyOrToken,
(flags & 1) === 0 ? "public-key-token" : "public-key",
),
hash_value_sha256: hashValue.length === 0 ? null : sha256Bytes(hashValue),
hash_value_length: hashValue.length,
token: metadataToken(35, row),
row_offset: metadataRowOffset(layout, 35, row),
};
};
const codedToken = (
raw: number,
bits: number,
tables: readonly (number | undefined)[],
): string | null => {
if (raw === 0) return null;
const tag = raw & (2 ** bits - 1);
const row = Math.floor(raw / 2 ** bits);
const table = tables[tag];
return table === undefined || row === 0 ? null : metadataToken(table, row);
};
interface ReadTypeNameContext {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly table: 1 | 2;
readonly row: number;
readonly maxBytes: number;
}
const readTypeName = ({
bytes,
layout,
table,
row,
maxBytes,
}: ReadTypeNameContext): string | null => {
const descriptor = layout.table(table);
if (descriptor === undefined || row < 1 || row > descriptor.rowCount)
return null;
const cursor = rowCursor({ bytes, layout, table, row });
if (table === 1) cursor.readIndex(layout.codedIndexSize("ResolutionScope"));
else cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const namespace = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
};
const declaringTypeForMethod = (
bytes: Buffer,
layout: ManagedMetadataLayout,
methodRow: number,
maxBytes: number,
): string | null => {
const types = layout.table(2);
const methods = layout.table(6);
if (types === undefined || methods === undefined) return null;
for (let row = 1; row <= types.rowCount; row += 1) {
const cursor = rowCursor({ bytes, layout, table: 2, row });
cursor.readUInt32();
const nameIndex = cursor.readIndex(layout.stringIndexSize);
const namespaceIndex = cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
const methodStart = cursor.readIndex(layout.tableIndexSize(6));
const methodEnd =
row === types.rowCount
? methods.rowCount + 1
: methodListForType(bytes, layout, row + 1);
if (methodRow < methodStart || methodRow >= methodEnd) continue;
const name = readMetadataString(bytes, layout, nameIndex, maxBytes);
const namespace = readMetadataString(
bytes,
layout,
namespaceIndex,
maxBytes,
);
return namespace.length === 0 ? name : `${namespace}.${name}`;
}
return null;
};
const methodListForType = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
): number => {
const cursor = rowCursor({ bytes, layout, table: 2, row });
cursor.readUInt32();
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.stringIndexSize);
cursor.readIndex(layout.codedIndexSize("TypeDefOrRef"));
cursor.readIndex(layout.tableIndexSize(4));
return cursor.readIndex(layout.tableIndexSize(6));
};
const attributeTypeName = (
bytes: Buffer,
layout: ManagedMetadataLayout,
rawType: number,
maxBytes: number,
): string | null => {
const tag = rawType & 7;
const row = Math.floor(rawType / 8);
if (row === 0) return null;
if (tag === 2) return declaringTypeForMethod(bytes, layout, row, maxBytes);
if (tag !== 3) return null;
const memberRefs = layout.table(10);
if (memberRefs === undefined || row > memberRefs.rowCount) return null;
const cursor = rowCursor({ bytes, layout, table: 10, row });
const parent = cursor.readIndex(layout.codedIndexSize("MemberRefParent"));
const parentTag = parent & 7;
const parentRow = Math.floor(parent / 8);
if (parentTag === 0)
return readTypeName({ bytes, layout, table: 2, row: parentRow, maxBytes });
if (parentTag === 1)
return readTypeName({ bytes, layout, table: 1, row: parentRow, maxBytes });
if (parentTag === 3)
return declaringTypeForMethod(bytes, layout, parentRow, maxBytes);
return null;
};
const decodeCompressedLength = (
blob: Buffer,
offset: number,
): { readonly length: number; readonly prefix: number } | undefined => {
const first = blob[offset];
if (first === undefined) return undefined;
if ((first & 0x80) === 0) return { length: first, prefix: 1 };
if ((first & 0xc0) === 0x80 && blob[offset + 1] !== undefined)
return {
length: ((first & 0x3f) << 8) | (blob[offset + 1] ?? 0),
prefix: 2,
};
if (
(first & 0xe0) === 0xc0 &&
blob[offset + 1] !== undefined &&
blob[offset + 2] !== undefined &&
blob[offset + 3] !== undefined
)
return {
length:
(first & 0x1f) * 0x01_00_00_00 +
(blob[offset + 1] ?? 0) * 0x01_00_00 +
(blob[offset + 2] ?? 0) * 0x0100 +
(blob[offset + 3] ?? 0),
prefix: 4,
};
return undefined;
};
const decodeFixedString = (blob: Buffer): string | null => {
if (blob.length < 3 || blob.readUInt16LE(0) !== 1 || blob[2] === 0xff)
return null;
const length = decodeCompressedLength(blob, 2);
if (length === undefined) return null;
const start = 2 + length.prefix;
if (start > blob.length - length.length) return null;
try {
return new TextDecoder("utf-8", { fatal: true }).decode(
blob.subarray(start, start + length.length),
);
} catch {
return null;
}
};
export const readCustomAttribute = (
bytes: Buffer,
layout: ManagedMetadataLayout,
row: number,
maxBytes: number,
): CustomAttribute => {
const cursor = rowCursor({ bytes, layout, table: 12, row });
const parentRaw = cursor.readIndex(
layout.codedIndexSize("HasCustomAttribute"),
);
const typeRaw = cursor.readIndex(
layout.codedIndexSize("CustomAttributeType"),
);
const value = readMetadataBlob(
bytes,
layout,
cursor.readIndex(layout.blobIndexSize),
maxBytes,
);
const parent = codedToken(
parentRaw,
5,
[
6, 4, 1, 2, 8, 9, 10, 0, 14, 23, 20, 17, 26, 27, 32, 35, 38, 39, 40, 42,
44, 43,
],
);
if (parent === null)
throw managedFailure(
"invalid-row",
"metadata.CustomAttribute",
"CustomAttribute parent coded index is invalid",
cursor.start,
);
const typeName = attributeTypeName(bytes, layout, typeRaw, maxBytes);
return {
parent_token: parent,
constructor_token: codedToken(typeRaw, 3, [undefined, undefined, 6, 10]),
type_name: typeName,
value_length: value.length,
value_sha256: sha256Bytes(value),
decoded_fixed_string:
typeName === "System.Runtime.Versioning.TargetFrameworkAttribute"
? decodeFixedString(value)
: null,
token: metadataToken(12, row),
row_offset: cursor.start,
};
};
interface ReadResourceContext {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly row: number;
readonly maxBytes: number;
readonly directory: ManagedResourceDirectory | null;
readonly issues: ManagedParseIssue[];
}
export const readResource = ({
bytes,
layout,
row,
maxBytes,
directory,
issues,
}: ReadResourceContext): ManagedResource => {
const cursor = rowCursor({ bytes, layout, table: 40, row });
const declaredOffset = cursor.readUInt32();
const flags = cursor.readUInt32();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const implementationRaw = cursor.readIndex(
layout.codedIndexSize("Implementation"),
);
const implementationToken = codedToken(implementationRaw, 2, [38, 35, 39]);
let dataLength: number | null = null;
let dataSha256: string | null = null;
if (implementationRaw === 0) {
if (directory === null || declaredOffset > directory.size - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: directory?.offset ?? null,
detail: "Embedded resource offset leaves the CLI resources directory",
});
} else {
const start = directory.offset + declaredOffset;
dataLength = bytes.readUInt32LE(start);
if (dataLength > directory.size - declaredOffset - 4) {
issues.push({
code: "invalid-resource",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start,
detail: "Embedded resource length leaves the CLI resources directory",
});
} else if (dataLength > maxBytes) {
issues.push({
code: "limit-exceeded",
scope: `metadata.ManifestResource:${metadataToken(40, row)}`,
offset: start + 4,
detail: `Embedded resource exceeds max_heap_item_bytes ${String(maxBytes)}; digest omitted`,
});
} else {
dataSha256 = sha256Bytes(
bytes.subarray(start + 4, start + 4 + dataLength),
);
}
}
}
return {
name,
flags,
visibility:
(flags & 7) === 1 ? "public" : (flags & 7) === 2 ? "private" : "unknown",
implementation_token: implementationToken,
embedded: implementationRaw === 0,
declared_offset: declaredOffset,
data_length: dataLength,
data_sha256: dataSha256,
token: metadataToken(40, row),
row_offset: cursor.start,
};
};
+116 -129
View File
@@ -1,4 +1,8 @@
import { managedFailure } from "./ManagedReaderFailure.js";
import {
computeRowSize,
type RowSizeContext,
} from "./ManagedMetadataRowSizes.js";
export const METADATA_TABLE_NAMES = [
"Module",
@@ -80,7 +84,7 @@ export interface ManagedMetadataLayout {
codedIndexSize(name: CodedIndexName): 2 | 4;
}
type CodedIndexName = keyof typeof CODED_INDEXES;
export type CodedIndexName = keyof typeof CODED_INDEXES;
const CODED_INDEXES = {
TypeDefOrRef: { bits: 2, tables: [2, 1, 27] },
@@ -196,129 +200,15 @@ const codedSize = (
const tableSize = (index: number, rows: readonly number[]): 2 | 4 =>
(rows[index] ?? 0) < 0x1_0000 ? 2 : 4;
const rowSize = (
table: number,
rowCounts: readonly number[],
heaps: { readonly string: 2 | 4; readonly guid: 2 | 4; readonly blob: 2 | 4 },
): number => {
const t = (index: number): number => tableSize(index, rowCounts);
const c = (name: CodedIndexName): number => codedSize(name, rowCounts);
const { string: s, guid: g, blob: b } = heaps;
switch (table) {
case 0:
return 2 + s + g * 3;
case 1:
return c("ResolutionScope") + s * 2;
case 2:
return 4 + s * 2 + c("TypeDefOrRef") + t(4) + t(6);
case 3:
return t(4);
case 4:
return 2 + s + b;
case 5:
return t(6);
case 6:
return 8 + s + b + t(8);
case 7:
return t(8);
case 8:
return 4 + s;
case 9:
return t(2) + c("TypeDefOrRef");
case 10:
return c("MemberRefParent") + s + b;
case 11:
return 2 + c("HasConstant") + b;
case 12:
return c("HasCustomAttribute") + c("CustomAttributeType") + b;
case 13:
return c("HasFieldMarshal") + b;
case 14:
return 2 + c("HasDeclSecurity") + b;
case 15:
return 6 + t(2);
case 16:
return 4 + t(4);
case 17:
return b;
case 18:
return t(2) + t(20);
case 19:
return t(20);
case 20:
return 2 + s + c("TypeDefOrRef");
case 21:
return t(2) + t(23);
case 22:
return t(23);
case 23:
return 2 + s + b;
case 24:
return 2 + t(6) + c("HasSemantics");
case 25:
return t(2) + c("MethodDefOrRef") * 2;
case 26:
return s;
case 27:
return b;
case 28:
return 2 + c("MemberForwarded") + s + t(26);
case 29:
return 4 + t(4);
case 30:
return 8;
case 31:
return 4;
case 32:
return 16 + b + s * 2;
case 33:
return 4;
case 34:
return 12;
case 35:
return 12 + b * 2 + s * 2;
case 36:
return 4 + t(35);
case 37:
return 12 + t(35);
case 38:
return 4 + s + b;
case 39:
return 8 + s * 2 + c("Implementation");
case 40:
return 8 + s + c("Implementation");
case 41:
return t(2) * 2;
case 42:
return 4 + c("TypeOrMethodDef") + s;
case 43:
return c("MethodDefOrRef") + b;
case 44:
return t(42) + c("TypeDefOrRef");
default:
throw managedFailure(
"invalid-tables",
"metadata.tables",
`Metadata table ${String(table)} is unsupported`,
);
}
};
interface ParsedStreams {
readonly streams: ReadonlyMap<string, MetadataStream>;
readonly version: string;
}
/** Parse ECMA-335 stream and table layout with checked byte extents. */
export const readManagedMetadataLayout = (
artifact: Buffer,
const readMetadataStreams = (
bytes: Buffer,
rootOffset: number,
size: number,
maxTableRows: number,
): ManagedMetadataLayout => {
if (size < 20 || rootOffset < 0 || rootOffset > artifact.length - size)
throw managedFailure(
"invalid-metadata-root",
"metadata.root",
"CLI metadata directory leaves the artifact byte range",
rootOffset,
);
const bytes = artifact.subarray(rootOffset, rootOffset + size);
): ParsedStreams => {
if (bytes.readUInt32LE(0) !== 0x424a_5342)
throw managedFailure(
"invalid-metadata-root",
@@ -365,6 +255,26 @@ export const readManagedMetadataLayout = (
});
cursor = named.next;
}
return { streams, version };
};
interface HeapSizes {
readonly string: 2 | 4;
readonly guid: 2 | 4;
readonly blob: 2 | 4;
}
interface ParsedTablesHeader {
readonly tableBytes: Buffer;
readonly tablesOffset: number;
readonly heaps: HeapSizes;
readonly valid: bigint;
}
const readTablesHeader = (
bytes: Buffer,
streams: ReadonlyMap<string, MetadataStream>,
): ParsedTablesHeader => {
const tablesStream = streamByName(streams, ["#~", "#-"]);
if (tablesStream === undefined)
throw managedFailure(
@@ -372,7 +282,7 @@ export const readManagedMetadataLayout = (
"metadata.tables",
"Required metadata table stream #~ or #- is absent",
);
const tableBytes = artifact.subarray(
const tableBytes = bytes.subarray(
tablesStream.offset,
tablesStream.offset + tablesStream.size,
);
@@ -391,6 +301,15 @@ export const readManagedMetadataLayout = (
"Metadata valid mask names unsupported tables outside the admitted ECMA-335 range",
tablesStream.offset + 8,
);
return { tableBytes, tablesOffset: tablesStream.offset, heaps, valid };
};
const readRowCounts = (
tableBytes: Buffer,
valid: bigint,
maxTableRows: number,
tablesOffset: number,
): readonly number[] => {
const rowCounts = Array<number>(METADATA_TABLE_NAMES.length).fill(0);
let tableCursor = 24;
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
@@ -402,23 +321,56 @@ export const readManagedMetadataLayout = (
"limit-exceeded",
`metadata.${METADATA_TABLE_NAMES[index] ?? String(index)}`,
`Metadata table row count ${String(count)} exceeds max_table_rows ${String(maxTableRows)}`,
tablesStream.offset + tableCursor,
tablesOffset + tableCursor,
);
rowCounts[index] = count;
tableCursor += 4;
}
return rowCounts;
};
const buildRowSizeContext = (
rowCounts: readonly number[],
heaps: HeapSizes,
): RowSizeContext => ({
tableSize: (index) => tableSize(index, rowCounts),
codedSize: (name) => codedSize(name, rowCounts),
stringSize: heaps.string,
guidSize: heaps.guid,
blobSize: heaps.blob,
});
const buildMetadataTables = ({
tableBytes,
rowCounts,
heaps,
valid,
tablesOffset,
}: {
readonly tableBytes: Buffer;
readonly rowCounts: readonly number[];
readonly heaps: HeapSizes;
readonly valid: bigint;
readonly tablesOffset: number;
}): ReadonlyMap<number, MetadataTableLayout> => {
const tables = new Map<number, MetadataTableLayout>();
const context = buildRowSizeContext(rowCounts, heaps);
let tableCursor = 24;
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
if ((valid & (1n << BigInt(index))) === 0n) continue;
tableCursor += 4;
}
for (let index = 0; index < METADATA_TABLE_NAMES.length; index += 1) {
const count = rowCounts[index] ?? 0;
if ((valid & (1n << BigInt(index))) === 0n) continue;
const sizeOfRow = rowSize(index, rowCounts, heaps);
const sizeOfRow = computeRowSize(index, context);
const byteLength = count * sizeOfRow;
if (!Number.isSafeInteger(byteLength))
throw managedFailure(
"invalid-tables",
"metadata.tables",
"Metadata table byte size overflowed",
tablesStream.offset + tableCursor,
tablesOffset + tableCursor,
);
requireRange(tableBytes, tableCursor, byteLength, "metadata.table-data");
tables.set(index, {
@@ -426,11 +378,47 @@ export const readManagedMetadataLayout = (
name: METADATA_TABLE_NAMES[index] ?? `Table${String(index)}`,
rowCount: count,
rowSize: sizeOfRow,
offset: tablesStream.offset + tableCursor,
offset: tablesOffset + tableCursor,
});
tableCursor += byteLength;
}
const layout: ManagedMetadataLayout = {
return tables;
};
/** Parse ECMA-335 stream and table layout with checked byte extents. */
export const readManagedMetadataLayout = (
artifact: Buffer,
rootOffset: number,
size: number,
maxTableRows: number,
): ManagedMetadataLayout => {
if (size < 20 || rootOffset < 0 || rootOffset > artifact.length - size)
throw managedFailure(
"invalid-metadata-root",
"metadata.root",
"CLI metadata directory leaves the artifact byte range",
rootOffset,
);
const bytes = artifact.subarray(rootOffset, rootOffset + size);
const { streams, version } = readMetadataStreams(bytes, rootOffset);
const { tableBytes, tablesOffset, heaps, valid } = readTablesHeader(
artifact,
streams,
);
const rowCounts = readRowCounts(
tableBytes,
valid,
maxTableRows,
tablesOffset,
);
const tables = buildMetadataTables({
tableBytes,
rowCounts,
heaps,
valid,
tablesOffset,
});
return {
rootOffset,
size,
version,
@@ -447,7 +435,6 @@ export const readManagedMetadataLayout = (
tableIndexSize: (index) => tableSize(index, rowCounts),
codedIndexSize: (name) => codedSize(name, rowCounts),
};
return layout;
};
/** Resolve a one-based metadata row to its exact file offset. */
+78
View File
@@ -0,0 +1,78 @@
import { managedFailure } from "./ManagedReaderFailure.js";
import type { CodedIndexName } from "./ManagedMetadataLayout.js";
export interface RowSizeContext {
readonly tableSize: (index: number) => number;
readonly codedSize: (name: CodedIndexName) => number;
readonly stringSize: 2 | 4;
readonly guidSize: 2 | 4;
readonly blobSize: 2 | 4;
}
type RowSizeFactory = (context: RowSizeContext) => number;
const ROW_SIZE_FACTORIES: readonly RowSizeFactory[] = [
({ stringSize: s, guidSize: g }) => 2 + s + g * 3,
({ codedSize: c, stringSize: s }) => c("ResolutionScope") + s * 2,
({ tableSize: t, codedSize: c, stringSize: s }) =>
4 + s * 2 + c("TypeDefOrRef") + t(4) + t(6),
({ tableSize: t }) => t(4),
({ stringSize: s, blobSize: b }) => 2 + s + b,
({ tableSize: t }) => t(6),
({ tableSize: t, stringSize: s, blobSize: b }) => 8 + s + b + t(8),
({ tableSize: t }) => t(8),
({ stringSize: s }) => 4 + s,
({ tableSize: t, codedSize: c }) => t(2) + c("TypeDefOrRef"),
({ codedSize: c, stringSize: s, blobSize: b }) =>
c("MemberRefParent") + s + b,
({ codedSize: c, blobSize: b }) => 2 + c("HasConstant") + b,
({ codedSize: c, blobSize: b }) =>
c("HasCustomAttribute") + c("CustomAttributeType") + b,
({ codedSize: c, blobSize: b }) => c("HasFieldMarshal") + b,
({ codedSize: c, blobSize: b }) => 2 + c("HasDeclSecurity") + b,
({ tableSize: t }) => 6 + t(2),
({ tableSize: t }) => 4 + t(4),
({ blobSize: b }) => b,
({ tableSize: t }) => t(2) + t(20),
({ tableSize: t }) => t(20),
({ stringSize: s, codedSize: c }) => 2 + s + c("TypeDefOrRef"),
({ tableSize: t }) => t(2) + t(23),
({ tableSize: t }) => t(23),
({ stringSize: s, blobSize: b }) => 2 + s + b,
({ tableSize: t, codedSize: c }) => 2 + t(6) + c("HasSemantics"),
({ tableSize: t, codedSize: c }) => t(2) + c("MethodDefOrRef") * 2,
({ stringSize: s }) => s,
({ blobSize: b }) => b,
({ tableSize: t, codedSize: c, stringSize: s }) =>
2 + c("MemberForwarded") + s + t(26),
({ tableSize: t }) => 4 + t(4),
() => 8,
() => 4,
({ blobSize: b, stringSize: s }) => 16 + b + s * 2,
() => 4,
() => 12,
({ blobSize: b, stringSize: s }) => 12 + b * 2 + s * 2,
({ tableSize: t }) => 4 + t(35),
({ tableSize: t }) => 12 + t(35),
({ stringSize: s, blobSize: b }) => 4 + s + b,
({ stringSize: s, codedSize: c }) => 8 + s * 2 + c("Implementation"),
({ stringSize: s, codedSize: c }) => 8 + s + c("Implementation"),
({ tableSize: t }) => t(2) * 2,
({ stringSize: s, codedSize: c }) => 4 + c("TypeOrMethodDef") + s,
({ codedSize: c, blobSize: b }) => c("MethodDefOrRef") + b,
({ tableSize: t, codedSize: c }) => t(42) + c("TypeDefOrRef"),
];
export const computeRowSize = (
table: number,
context: RowSizeContext,
): number => {
const factory = ROW_SIZE_FACTORIES[table];
if (factory === undefined)
throw managedFailure(
"invalid-tables",
"metadata.tables",
`Metadata table ${String(table)} is unsupported`,
);
return factory(context);
};
+499
View File
@@ -0,0 +1,499 @@
import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
managedNativeBoundaryInspectionSchema,
type ManagedNativeBoundaryInspection,
type ManagedParseIssue,
} from "../domain/managedArtifact.js";
import {
metadataRowOffset,
type ManagedMetadataLayout,
} from "./ManagedMetadataLayout.js";
import {
MetadataRowCursor,
metadataToken,
readMetadataString,
} from "./ManagedMetadataHeaps.js";
import { managedTableRowCounts } from "./ManagedMetadataInventory.js";
import type { ManagedMetadataInventory } from "./ManagedMetadataInventory.js";
import { managedFailure } from "./ManagedReaderFailure.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 NativeImplementation =
ManagedNativeBoundaryInspection["native_implementations"]["items"][number];
interface MemberCore {
readonly token: string;
readonly rowOffset: number;
readonly kind: NativeImport["member_kind"];
readonly name: string;
readonly flags: number;
readonly implFlags: number | null;
readonly rva: number | null;
}
interface RowCursorContext {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly table: number;
readonly row: number;
}
const rowCursor = ({
bytes,
layout,
table,
row,
}: RowCursorContext): MetadataRowCursor => {
const descriptor = layout.table(table);
const start = metadataRowOffset(layout, table, row);
if (descriptor === undefined)
throw managedFailure(
"invalid-row",
`metadata.${String(table)}`,
"Metadata table is absent",
start,
);
return new MetadataRowCursor(
bytes,
start,
start + descriptor.rowSize,
`metadata.${descriptor.name}`,
);
};
const codedToken = (
raw: number,
tagBits: number,
tables: readonly number[],
): string | null => {
const tagMask = (1 << tagBits) - 1;
const table = tables[raw & tagMask];
const row = raw >> tagBits;
if (table === undefined || row === 0) return null;
return metadataToken(table, row);
};
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,
maxBytes: number,
): readonly ModuleRef[] => {
const refs: ModuleRef[] = [];
const table = layout.table(26);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor({ bytes, layout, table: 26, row });
refs.push({
token: metadataToken(26, row),
row_offset: cursor.start,
name: readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
),
});
}
return refs;
};
export const parseFields = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ReadonlyMap<string, MemberCore> => {
const fields = new Map<string, MemberCore>();
const table = layout.table(4);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor({ bytes, layout, table: 4, row });
const flags = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
cursor.readIndex(layout.blobIndexSize);
const token = metadataToken(4, row);
fields.set(token, {
token,
rowOffset: cursor.start,
kind: "field",
name,
flags,
implFlags: null,
rva: null,
});
}
return fields;
};
export const parseMethods = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ReadonlyMap<string, MemberCore> => {
const methods = new Map<string, MemberCore>();
const table = layout.table(6);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor({ bytes, layout, table: 6, row });
const rva = cursor.readUInt32();
const implFlags = cursor.readUInt16();
const flags = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
cursor.readIndex(layout.blobIndexSize);
cursor.readIndex(layout.tableIndexSize(8));
const token = metadataToken(6, row);
methods.set(token, {
token,
rowOffset: cursor.start,
kind: "method",
name,
flags,
implFlags,
rva,
});
}
return methods;
};
interface ParseImplMapsContext {
readonly bytes: Buffer;
readonly layout: ManagedMetadataLayout;
readonly maxBytes: number;
readonly modules: readonly ModuleRef[];
readonly members: ReadonlyMap<string, MemberCore>;
}
export const parseImplMaps = ({
bytes,
layout,
maxBytes,
modules,
members,
}: ParseImplMapsContext): readonly NativeImport[] => {
const moduleNames = new Map(modules.map((module) => [module.token, module]));
const imports: NativeImport[] = [];
const table = layout.table(28);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor({ bytes, layout, table: 28, row });
const mappingFlags = cursor.readUInt16();
const memberToken = codedToken(
cursor.readIndex(layout.codedIndexSize("MemberForwarded")),
1,
[4, 6],
);
const importName = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const importScopeRow = cursor.readIndex(layout.tableIndexSize(26));
const importScopeToken =
importScopeRow === 0 ? null : metadataToken(26, importScopeRow);
const member = memberToken === null ? undefined : members.get(memberToken);
imports.push({
token: metadataToken(28, row),
row_offset: cursor.start,
mapping_flags: mappingFlags,
mapping_flags_hex: flagsHex(mappingFlags),
member_token: memberToken,
member_kind: member?.kind ?? "unknown",
member_name: member?.name ?? null,
import_name: importName,
import_scope_token: importScopeToken,
import_scope_name:
importScopeToken === null
? null
: (moduleNames.get(importScopeToken)?.name ?? null),
no_mangle: (mappingFlags & 0x0001) !== 0,
char_set: charSet(mappingFlags),
call_convention: callConvention(mappingFlags),
supports_last_error: (mappingFlags & 0x0040) !== 0,
best_fit: bestFit(mappingFlags),
throw_on_unmappable_char: throwOnUnmappable(mappingFlags),
verification: "managed-declaration-only",
});
}
return imports;
};
const charSet = (flags: number): NativeImport["char_set"] => {
switch (flags & 0x0006) {
case 0x0000:
return "not-specified";
case 0x0002:
return "ansi";
case 0x0004:
return "unicode";
case 0x0006:
return "auto";
default:
return "unknown";
}
};
const callConvention = (flags: number): NativeImport["call_convention"] => {
switch (flags & 0x0700) {
case 0x0000:
return "not-specified";
case 0x0100:
return "winapi";
case 0x0200:
return "cdecl";
case 0x0300:
return "stdcall";
case 0x0400:
return "thiscall";
case 0x0500:
return "fastcall";
default:
return "unknown";
}
};
const bestFit = (flags: number): NativeImport["best_fit"] => {
switch (flags & 0x0030) {
case 0x0000:
return "assembly-default";
case 0x0010:
return "enabled";
case 0x0020:
return "disabled";
default:
return "unknown";
}
};
const throwOnUnmappable = (
flags: number,
): NativeImport["throw_on_unmappable_char"] => {
switch (flags & 0x3000) {
case 0x0000:
return "assembly-default";
case 0x1000:
return "enabled";
case 0x2000:
return "disabled";
default:
return "unknown";
}
};
export const nativeImplementations = (
methods: Iterable<MemberCore>,
pinvokeTokens: ReadonlySet<string>,
): readonly NativeImplementation[] => {
const implementations: NativeImplementation[] = [];
for (const method of methods) {
const implFlags = method.implFlags ?? 0;
const codeType = codeTypeFor(implFlags);
const managedKind = managedKindFor(implFlags);
const pinvokeDeclared =
pinvokeTokens.has(method.token) || (method.flags & 0x2000) !== 0;
if (!pinvokeDeclared && codeType === "il" && managedKind === "managed")
continue;
implementations.push({
token: method.token,
row_offset: method.rowOffset,
name: method.name,
rva: method.rva ?? 0,
flags: method.flags,
impl_flags: implFlags,
code_type: codeType,
managed_kind: managedKind,
pinvoke_declared: pinvokeDeclared,
boundary_kind: boundaryKind(pinvokeDeclared, codeType, managedKind),
body_interpretation:
codeType === "il" && managedKind === "managed" && !pinvokeDeclared
? "managed-cil"
: method.rva === 0
? "not-file-backed"
: "native-or-runtime",
});
}
return implementations;
};
const codeTypeFor = (implFlags: number): NativeImplementation["code_type"] => {
switch (implFlags & 0x0003) {
case 0x0000:
return "il";
case 0x0001:
return "native";
case 0x0002:
return "optil";
case 0x0003:
return "runtime";
default:
return "unknown";
}
};
const managedKindFor = (
implFlags: number,
): NativeImplementation["managed_kind"] => {
switch (implFlags & 0x0004) {
case 0x0000:
return "managed";
case 0x0004:
return "unmanaged";
default:
return "unknown";
}
};
const boundaryKind = (
pinvokeDeclared: boolean,
codeType: NativeImplementation["code_type"],
managedKind: NativeImplementation["managed_kind"],
): NativeImplementation["boundary_kind"] => {
if (pinvokeDeclared) return "pinvoke";
if (codeType === "native") return "native-body";
if (codeType === "runtime") return "runtime-provided";
if (managedKind === "unmanaged") return "unmanaged-method";
return "mixed-or-unknown";
};
export const cliNative = (
pe: ManagedPeLayout,
): ManagedNativeBoundaryInspection["cli_native"] => {
if (pe.cli === null)
return {
il_only: false,
requires_32bit: false,
strong_name_signed: false,
native_entry_point: false,
ready_to_run_signature: false,
managed_native_header_rva: 0,
managed_native_header_size: 0,
};
return {
il_only: (pe.cli.flags & 0x0000_0001) !== 0,
requires_32bit: (pe.cli.flags & 0x0000_0002) !== 0,
strong_name_signed: (pe.cli.flags & 0x0000_0008) !== 0,
native_entry_point: (pe.cli.flags & 0x0000_0010) !== 0,
ready_to_run_signature: pe.cli.readyToRunSignature,
managed_native_header_rva: pe.cli.managedNativeHeader.rva,
managed_native_header_size: pe.cli.managedNativeHeader.size,
};
};
interface BoundaryInspectionContext {
readonly target: BinaryTarget;
readonly bytes: Buffer;
readonly limits: ManagedNativeBoundaryInspectionLimits;
readonly pe: ManagedPeLayout;
readonly layout: ManagedMetadataLayout;
readonly inventory: ManagedMetadataInventory;
readonly moduleRefs: readonly ModuleRef[];
readonly imports: readonly NativeImport[];
readonly implementations: readonly NativeImplementation[];
readonly native: ManagedNativeBoundaryInspection["cli_native"];
readonly issues: readonly ManagedParseIssue[];
}
export const buildNativeBoundaryInspection = ({
target,
bytes,
limits,
layout,
inventory,
moduleRefs,
imports,
implementations,
native,
issues,
}: BoundaryInspectionContext): ManagedNativeBoundaryInspection =>
managedNativeBoundaryInspectionSchema.parse({
schema_version: 1,
artifact: {
path: target.path,
sha256: target.sha256,
byte_length: bytes.length,
format: "pe",
},
module: inventory.module,
metadata: {
status: issues.length === 0 ? "complete" : "partial",
version: layout.version,
table_row_counts: managedTableRowCounts(layout),
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: target.sha256,
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,
),
summary: {
module_ref_count: moduleRefs.length,
pinvoke_import_count: imports.length,
native_implementation_count: implementations.length,
ready_to_run: native.ready_to_run_signature,
mixed_mode_or_native_header:
native.managed_native_header_rva !== 0 ||
native.managed_native_header_size !== 0 ||
native.native_entry_point,
},
coverage: {
state: issues.length === 0 ? "complete" : "partial",
issues,
},
limitations: [
"P/Invoke rows prove managed import declarations only; this inspection does not verify that a native library, export, thunk, or provider-qualified function exists.",
"Managed metadata tokens are build-local coordinates and are only meaningful with the reported artifact SHA-256 and MVID.",
"ReadyToRun, NativeAOT, C++/CLI, and IL2CPP native semantics require separately selected native-provider evidence; this tool does not translate managed tokens into native addresses.",
],
});
+156 -525
View File
@@ -4,30 +4,29 @@ import {
type ManagedNativeBoundaryInspection,
type ManagedParseIssue,
} from "../domain/managedArtifact.js";
import {
metadataRowOffset,
type ManagedMetadataLayout,
readManagedMetadataLayout,
} from "./ManagedMetadataLayout.js";
import {
MetadataRowCursor,
metadataToken,
readMetadataString,
} from "./ManagedMetadataHeaps.js";
import {
readManagedMetadataInventory,
managedTableRowCounts,
type ManagedResourceDirectory,
} from "./ManagedMetadataInventory.js";
import {
readManagedMetadataLayout,
type ManagedMetadataLayout,
} from "./ManagedMetadataLayout.js";
import {
readManagedPeLayout,
type ManagedPeLayout,
} from "./ManagedPeReader.js";
import { ManagedReaderFailure } from "./ManagedReaderFailure.js";
import {
ManagedReaderFailure,
managedFailure,
} from "./ManagedReaderFailure.js";
buildNativeBoundaryInspection,
cliNative,
nativeImplementations,
parseFields,
parseImplMaps,
parseMethods,
parseModuleRefs,
} from "./ManagedNativeBoundaryHelpers.js";
/** Bounds for execution-free managed/native boundary inspection. */
export interface ManagedNativeBoundaryInspectionLimits {
readonly moduleRefOffset: number;
readonly moduleRefLimit: number;
@@ -40,396 +39,25 @@ export interface ManagedNativeBoundaryInspectionLimits {
readonly maxHeapItemBytes: number;
}
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 NativeImplementation =
ManagedNativeBoundaryInspection["native_implementations"]["items"][number];
type Inventory = ReturnType<typeof readManagedMetadataInventory>;
interface MemberCore {
readonly token: string;
readonly rowOffset: number;
readonly kind: NativeImport["member_kind"];
readonly name: string;
readonly flags: number;
readonly implFlags: number | null;
readonly rva: number | null;
}
const emptyPage = <Item>(): ManagedNativeBoundaryInspection["module_refs"] & {
items: readonly Item[];
} => ({
items: [],
offset: 0,
limit: 0,
total: 0,
returned: 0,
dropped: 0,
complete: true,
});
const rowCursor = (
bytes: Buffer,
layout: ManagedMetadataLayout,
table: number,
row: number,
): MetadataRowCursor => {
const descriptor = layout.table(table);
const start = metadataRowOffset(layout, table, row);
if (descriptor === undefined)
throw managedFailure(
"invalid-row",
`metadata.${String(table)}`,
"Metadata table is absent",
start,
);
return new MetadataRowCursor(
bytes,
start,
start + descriptor.rowSize,
`metadata.${descriptor.name}`,
);
};
const codedToken = (
raw: number,
tagBits: number,
tables: readonly number[],
): string | null => {
const tagMask = (1 << tagBits) - 1;
const table = tables[raw & tagMask];
const row = raw >> tagBits;
if (table === undefined || row === 0) return null;
return metadataToken(table, row);
};
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,
};
};
const parseModuleRefs = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): readonly ModuleRef[] => {
const refs: ModuleRef[] = [];
const table = layout.table(26);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor(bytes, layout, 26, row);
refs.push({
token: metadataToken(26, row),
row_offset: cursor.start,
name: readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
),
});
}
return refs;
};
const parseFields = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ReadonlyMap<string, MemberCore> => {
const fields = new Map<string, MemberCore>();
const table = layout.table(4);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor(bytes, layout, 4, row);
const flags = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
cursor.readIndex(layout.blobIndexSize);
const token = metadataToken(4, row);
fields.set(token, {
token,
rowOffset: cursor.start,
kind: "field",
name,
flags,
implFlags: null,
rva: null,
});
}
return fields;
};
const parseMethods = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
): ReadonlyMap<string, MemberCore> => {
const methods = new Map<string, MemberCore>();
const table = layout.table(6);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor(bytes, layout, 6, row);
const rva = cursor.readUInt32();
const implFlags = cursor.readUInt16();
const flags = cursor.readUInt16();
const name = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
cursor.readIndex(layout.blobIndexSize);
cursor.readIndex(layout.tableIndexSize(8));
const token = metadataToken(6, row);
methods.set(token, {
token,
rowOffset: cursor.start,
kind: "method",
name,
flags,
implFlags,
rva,
});
}
return methods;
};
const parseImplMaps = (
bytes: Buffer,
layout: ManagedMetadataLayout,
maxBytes: number,
modules: readonly ModuleRef[],
members: ReadonlyMap<string, MemberCore>,
): readonly NativeImport[] => {
const moduleNames = new Map(modules.map((module) => [module.token, module]));
const imports: NativeImport[] = [];
const table = layout.table(28);
for (let row = 1; row <= (table?.rowCount ?? 0); row += 1) {
const cursor = rowCursor(bytes, layout, 28, row);
const mappingFlags = cursor.readUInt16();
const memberToken = codedToken(
cursor.readIndex(layout.codedIndexSize("MemberForwarded")),
1,
[4, 6],
);
const importName = readMetadataString(
bytes,
layout,
cursor.readIndex(layout.stringIndexSize),
maxBytes,
);
const importScopeRow = cursor.readIndex(layout.tableIndexSize(26));
const importScopeToken =
importScopeRow === 0 ? null : metadataToken(26, importScopeRow);
const member = memberToken === null ? undefined : members.get(memberToken);
imports.push({
token: metadataToken(28, row),
row_offset: cursor.start,
mapping_flags: mappingFlags,
mapping_flags_hex: flagsHex(mappingFlags),
member_token: memberToken,
member_kind: member?.kind ?? "unknown",
member_name: member?.name ?? null,
import_name: importName,
import_scope_token: importScopeToken,
import_scope_name:
importScopeToken === null
? null
: (moduleNames.get(importScopeToken)?.name ?? null),
no_mangle: (mappingFlags & 0x0001) !== 0,
char_set: charSet(mappingFlags),
call_convention: callConvention(mappingFlags),
supports_last_error: (mappingFlags & 0x0040) !== 0,
best_fit: bestFit(mappingFlags),
throw_on_unmappable_char: throwOnUnmappable(mappingFlags),
verification: "managed-declaration-only",
});
}
return imports;
};
const charSet = (flags: number): NativeImport["char_set"] => {
switch (flags & 0x0006) {
case 0x0000:
return "not-specified";
case 0x0002:
return "ansi";
case 0x0004:
return "unicode";
case 0x0006:
return "auto";
default:
return "unknown";
}
};
const callConvention = (flags: number): NativeImport["call_convention"] => {
switch (flags & 0x0700) {
case 0x0000:
return "not-specified";
case 0x0100:
return "winapi";
case 0x0200:
return "cdecl";
case 0x0300:
return "stdcall";
case 0x0400:
return "thiscall";
case 0x0500:
return "fastcall";
default:
return "unknown";
}
};
const bestFit = (flags: number): NativeImport["best_fit"] => {
switch (flags & 0x0030) {
case 0x0000:
return "assembly-default";
case 0x0010:
return "enabled";
case 0x0020:
return "disabled";
default:
return "unknown";
}
};
const throwOnUnmappable = (
flags: number,
): NativeImport["throw_on_unmappable_char"] => {
switch (flags & 0x3000) {
case 0x0000:
return "assembly-default";
case 0x1000:
return "enabled";
case 0x2000:
return "disabled";
default:
return "unknown";
}
};
const nativeImplementations = (
methods: Iterable<MemberCore>,
pinvokeTokens: ReadonlySet<string>,
): readonly NativeImplementation[] => {
const implementations: NativeImplementation[] = [];
for (const method of methods) {
const implFlags = method.implFlags ?? 0;
const codeType = codeTypeFor(implFlags);
const managedKind = managedKindFor(implFlags);
const pinvokeDeclared =
pinvokeTokens.has(method.token) || (method.flags & 0x2000) !== 0;
if (!pinvokeDeclared && codeType === "il" && managedKind === "managed")
continue;
implementations.push({
token: method.token,
row_offset: method.rowOffset,
name: method.name,
rva: method.rva ?? 0,
flags: method.flags,
impl_flags: implFlags,
code_type: codeType,
managed_kind: managedKind,
pinvoke_declared: pinvokeDeclared,
boundary_kind: boundaryKind(pinvokeDeclared, codeType, managedKind),
body_interpretation:
codeType === "il" && managedKind === "managed" && !pinvokeDeclared
? "managed-cil"
: method.rva === 0
? "not-file-backed"
: "native-or-runtime",
});
}
return implementations;
};
const codeTypeFor = (implFlags: number): NativeImplementation["code_type"] => {
switch (implFlags & 0x0003) {
case 0x0000:
return "il";
case 0x0001:
return "native";
case 0x0002:
return "optil";
case 0x0003:
return "runtime";
default:
return "unknown";
}
};
const managedKindFor = (
implFlags: number,
): NativeImplementation["managed_kind"] => {
switch (implFlags & 0x0004) {
case 0x0000:
return "managed";
case 0x0004:
return "unmanaged";
default:
return "unknown";
}
};
const boundaryKind = (
pinvokeDeclared: boolean,
codeType: NativeImplementation["code_type"],
managedKind: NativeImplementation["managed_kind"],
): NativeImplementation["boundary_kind"] => {
if (pinvokeDeclared) return "pinvoke";
if (codeType === "native") return "native-body";
if (codeType === "runtime") return "runtime-provided";
if (managedKind === "unmanaged") return "unmanaged-method";
return "mixed-or-unknown";
};
const cliNative = (
pe: ManagedPeLayout,
): ManagedNativeBoundaryInspection["cli_native"] => {
if (pe.cli === null)
return {
il_only: false,
requires_32bit: false,
strong_name_signed: false,
native_entry_point: false,
ready_to_run_signature: false,
managed_native_header_rva: 0,
managed_native_header_size: 0,
};
return {
il_only: (pe.cli.flags & 0x0000_0001) !== 0,
requires_32bit: (pe.cli.flags & 0x0000_0002) !== 0,
strong_name_signed: (pe.cli.flags & 0x0000_0008) !== 0,
native_entry_point: (pe.cli.flags & 0x0000_0010) !== 0,
ready_to_run_signature: pe.cli.readyToRunSignature,
managed_native_header_rva: pe.cli.managedNativeHeader.rva,
managed_native_header_size: pe.cli.managedNativeHeader.size,
};
};
const unavailable = (
const emptyInspection = (
target: BinaryTarget,
bytes: Buffer,
limits: ManagedNativeBoundaryInspectionLimits,
issue: ManagedParseIssue | null,
classification: "not-managed" | "malformed" | "not-available" | "managed",
issues: readonly ManagedParseIssue[] = [],
): ManagedNativeBoundaryInspection =>
managedNativeBoundaryInspectionSchema.parse({
schema_version: 1,
@@ -440,7 +68,14 @@ const unavailable = (
format: "pe",
},
module: null,
metadata: { status: "absent", version: null, table_row_counts: {} },
metadata: {
status:
classification === "malformed" || classification === "not-available"
? "malformed"
: "absent",
version: null,
table_row_counts: {},
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: target.sha256,
@@ -455,13 +90,9 @@ const unavailable = (
managed_native_header_rva: 0,
managed_native_header_size: 0,
},
module_refs: page([], limits.moduleRefOffset, limits.moduleRefLimit),
pinvoke_imports: page([], limits.importOffset, limits.importLimit),
native_implementations: page(
[],
limits.implementationOffset,
limits.implementationLimit,
),
module_refs: emptyPage(),
pinvoke_imports: emptyPage(),
native_implementations: emptyPage(),
summary: {
module_ref_count: 0,
pinvoke_import_count: 0,
@@ -469,132 +100,132 @@ const unavailable = (
ready_to_run: false,
mixed_mode_or_native_header: false,
},
coverage: {
state: "unavailable",
issues: issue === null ? [] : [issue],
},
coverage: { state: classification, issues },
limitations: [
"The PE has no admitted CLI metadata; managed/native boundary inspection is unavailable.",
"No CLI data was admitted; native boundary declarations are unavailable.",
"Static inspection does not load or execute target code, so native export resolution is not performed.",
],
});
/** Inspect PE/CLI managed/native boundary declarations without executing code. */
const readBoundaryInventory = (
bytes: Buffer,
pe: ManagedPeLayout,
limits: ManagedNativeBoundaryInspectionLimits,
): {
readonly layout: ManagedMetadataLayout;
readonly inventory: Inventory;
} => {
const cli = pe.cli!;
const metadataOffset = pe.rvaToOffset(
cli.metadata.rva,
cli.metadata.size,
"cli.metadata",
);
const layout = readManagedMetadataLayout(
bytes,
metadataOffset,
cli.metadata.size,
limits.maxTableRows,
);
const resourceDirectory: ManagedResourceDirectory = {
offset: pe.rvaToOffset(
cli.resources.rva,
cli.resources.size,
"cli.resources",
),
size: cli.resources.size,
};
const inventory = readManagedMetadataInventory(
bytes,
layout,
{
referenceOffset: 0,
referenceLimit: 0,
resourceOffset: 0,
resourceLimit: 0,
attributeOffset: 0,
attributeLimit: 0,
maxHeapItemBytes: limits.maxHeapItemBytes,
},
resourceDirectory,
);
return { layout, inventory };
};
const metadataLimitIssue = (
cli: NonNullable<ManagedPeLayout["cli"]>,
maxBytes: number,
): ManagedParseIssue => ({
code: "limit-exceeded",
scope: "cli.metadata",
offset: cli.headerOffset + 8,
detail: `CLI metadata size exceeds max_metadata_bytes ${String(maxBytes)}`,
});
/** Inspect managed/native boundary declarations from PE metadata without execution. */
export const inspectManagedNativeBoundariesBytes = (
bytes: Buffer,
target: BinaryTarget,
limits: ManagedNativeBoundaryInspectionLimits,
): ManagedNativeBoundaryInspection => {
const pe = readManagedPeLayout(bytes);
if (pe.cli === null) return unavailable(target, bytes, limits, pe.cliIssue);
const issues: ManagedParseIssue[] = [];
let pe: ManagedPeLayout;
try {
const rootOffset = pe.rvaToOffset(
pe.cli.metadata.rva,
pe.cli.metadata.size,
"cli.metadata",
);
if (pe.cli.metadata.size > limits.maxMetadataBytes)
throw managedFailure(
"limit-exceeded",
"metadata.root",
`CLI metadata size exceeds max_metadata_bytes ${String(limits.maxMetadataBytes)}`,
rootOffset,
);
const layout = readManagedMetadataLayout(
bytes,
rootOffset,
pe.cli.metadata.size,
limits.maxTableRows,
);
const inventory = readManagedMetadataInventory(
bytes,
layout,
{
referenceOffset: 0,
referenceLimit: 1,
resourceOffset: 0,
resourceLimit: 1,
attributeOffset: 0,
attributeLimit: 1,
maxHeapItemBytes: limits.maxHeapItemBytes,
},
null,
);
issues.push(...inventory.issues);
const moduleRefs = parseModuleRefs(bytes, layout, limits.maxHeapItemBytes);
const fields = parseFields(bytes, layout, limits.maxHeapItemBytes);
const methods = parseMethods(bytes, layout, limits.maxHeapItemBytes);
const members = new Map([...fields, ...methods]);
const imports = parseImplMaps(
bytes,
layout,
limits.maxHeapItemBytes,
moduleRefs,
members,
);
const implementations = nativeImplementations(
methods.values(),
new Set(
imports
.map(({ member_token: token }) => token)
.filter((token): token is string => token !== null),
),
);
const native = cliNative(pe);
return managedNativeBoundaryInspectionSchema.parse({
schema_version: 1,
artifact: {
path: target.path,
sha256: target.sha256,
byte_length: bytes.length,
format: "pe",
},
module: inventory.module,
metadata: {
status: issues.length === 0 ? "complete" : "partial",
version: layout.version,
table_row_counts: managedTableRowCounts(layout),
},
identity_scope: {
token_identity: "build-local",
requires_artifact_sha256: target.sha256,
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,
),
summary: {
module_ref_count: moduleRefs.length,
pinvoke_import_count: imports.length,
native_implementation_count: implementations.length,
ready_to_run: native.ready_to_run_signature,
mixed_mode_or_native_header:
native.managed_native_header_rva !== 0 ||
native.managed_native_header_size !== 0 ||
native.native_entry_point,
},
coverage: {
state: issues.length === 0 ? "complete" : "partial",
issues,
},
limitations: [
"P/Invoke rows prove managed import declarations only; this inspection does not verify that a native library, export, thunk, or provider-qualified function exists.",
"Managed metadata tokens are build-local coordinates and are only meaningful with the reported artifact SHA-256 and MVID.",
"ReadyToRun, NativeAOT, C++/CLI, and IL2CPP native semantics require separately selected native-provider evidence; this tool does not translate managed tokens into native addresses.",
],
});
pe = readManagedPeLayout(bytes);
} catch (cause: unknown) {
if (cause instanceof ManagedReaderFailure)
return unavailable(target, bytes, limits, cause.issue);
throw cause;
if (!(cause instanceof ManagedReaderFailure)) throw cause;
return emptyInspection(target, bytes, "malformed", [cause.issue]);
}
if (pe.cli === null)
return emptyInspection(
target,
bytes,
pe.cliDirectoryPresent ? "malformed" : "not-managed",
pe.cliIssue === null ? [] : [pe.cliIssue],
);
if (pe.cli.metadata.size > limits.maxMetadataBytes)
return emptyInspection(target, bytes, "malformed", [
metadataLimitIssue(pe.cli, limits.maxMetadataBytes),
]);
let layout: ManagedMetadataLayout;
let inventory: Inventory;
try {
({ layout, inventory } = readBoundaryInventory(bytes, pe, limits));
} catch (cause: unknown) {
if (!(cause instanceof ManagedReaderFailure)) throw cause;
return emptyInspection(target, bytes, "malformed", [cause.issue]);
}
const moduleRefs = parseModuleRefs(bytes, layout, limits.maxHeapItemBytes);
const members = new Map([
...parseFields(bytes, layout, limits.maxHeapItemBytes),
...parseMethods(bytes, layout, limits.maxHeapItemBytes),
]);
const imports = parseImplMaps({
bytes,
layout,
maxBytes: limits.maxHeapItemBytes,
modules: moduleRefs,
members,
});
const pinvokeTokens = new Set(
imports
.map(({ member_token }) => member_token)
.filter((token): token is string => token !== null),
);
const implementations = nativeImplementations(
members.values(),
pinvokeTokens,
);
return buildNativeBoundaryInspection({
target,
bytes,
limits,
pe,
layout,
inventory,
moduleRefs,
imports,
implementations,
native: cliNative(pe),
issues: [],
});
};
+104 -45
View File
@@ -43,6 +43,29 @@ export interface ManagedPeLayout {
rvaToOffset(rva: number, size: number, scope: string): number;
}
interface RvaMapping {
readonly bytes: Buffer;
readonly sections: readonly PeSection[];
readonly rva: number;
readonly size: number;
readonly scope: string;
}
interface CoffHeader {
readonly coff: number;
readonly machine: number;
readonly sectionCount: number;
readonly optionalSize: number;
readonly characteristics: number;
}
interface OptionalHeader {
readonly optionalOffset: number;
readonly optionalHeader: "pe32" | "pe32-plus";
readonly directoryCountOffset: number;
readonly directoryOffset: number;
}
const requireRange = (
bytes: Buffer,
offset: number,
@@ -95,13 +118,8 @@ const architectureFor = (machine: number): ManagedPeLayout["architecture"] => {
}
};
const mapRva = (
bytes: Buffer,
sections: readonly PeSection[],
rva: number,
size: number,
scope: string,
): number => {
const mapRva = (mapping: RvaMapping): number => {
const { bytes, sections, rva, size, scope } = mapping;
if (rva === 0 && size === 0) return 0;
for (const section of sections) {
const mappedSize = Math.max(section.virtualSize, section.rawSize);
@@ -144,7 +162,13 @@ const readCliHeader = (
"cli.header",
"CLI header is shorter than the required 72 bytes",
);
const offset = mapRva(bytes, sections, directory.rva, 72, "cli.header");
const offset = mapRva({
bytes,
sections,
rva: directory.rva,
size: 72,
scope: "cli.header",
});
const headerSize = bytes.readUInt32LE(offset);
if (headerSize < 72 || headerSize > directory.size)
throw managedFailure(
@@ -165,13 +189,13 @@ const readCliHeader = (
const managedNativeHeader = readDirectory(bytes, offset + 64);
let readyToRunSignature = false;
if (managedNativeHeader.rva !== 0 && managedNativeHeader.size >= 4) {
const nativeOffset = mapRva(
const nativeOffset = mapRva({
bytes,
sections,
managedNativeHeader.rva,
4,
"cli.managed-native-header",
);
rva: managedNativeHeader.rva,
size: 4,
scope: "cli.managed-native-header",
});
readyToRunSignature = bytes.readUInt32LE(nativeOffset) === 0x0052_5452;
}
return {
@@ -189,16 +213,7 @@ const readCliHeader = (
};
};
/** Parse the file-backed PE and CLI layout without loading target code. */
export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
requireRange(bytes, 0, 64, "pe.dos-header");
if (bytes[0] !== 0x4d || bytes[1] !== 0x5a)
throw managedFailure(
"invalid-directory",
"pe.dos-header",
"Artifact does not start with an MZ header",
0,
);
const readCoffHeader = (bytes: Buffer): CoffHeader => {
const peOffset = bytes.readUInt32LE(0x3c);
requireRange(bytes, peOffset, 24, "pe.coff-header");
if (bytes.readUInt32LE(peOffset) !== 0x0000_4550)
@@ -220,9 +235,13 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
);
const optionalSize = bytes.readUInt16LE(coff + 16);
const characteristics = bytes.readUInt16LE(coff + 18);
const optionalOffset = coff + 20;
requireRange(bytes, optionalOffset, optionalSize, "pe.optional-header");
if (optionalSize < 96)
return { coff, machine, sectionCount, optionalSize, characteristics };
};
const readOptionalHeader = (bytes: Buffer, coff: CoffHeader): OptionalHeader => {
const optionalOffset = coff.coff + 20;
requireRange(bytes, optionalOffset, coff.optionalSize, "pe.optional-header");
if (coff.optionalSize < 96)
throw managedFailure(
"invalid-directory",
"pe.optional-header",
@@ -239,16 +258,29 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
"PE optional header magic is unsupported",
optionalOffset,
);
const directoryCountOffset =
optionalOffset + (optionalHeader === "pe32" ? 92 : 108);
const directoryOffset =
optionalOffset + (optionalHeader === "pe32" ? 96 : 112);
requireRange(bytes, directoryCountOffset, 4, "pe.data-directories");
const directoryCount = bytes.readUInt32LE(directoryCountOffset);
const sectionOffset = add(optionalOffset, optionalSize, "pe.sections");
requireRange(bytes, sectionOffset, sectionCount * 40, "pe.sections");
return {
optionalOffset,
optionalHeader,
directoryCountOffset:
optionalOffset + (optionalHeader === "pe32" ? 92 : 108),
directoryOffset: optionalOffset + (optionalHeader === "pe32" ? 96 : 112),
};
};
const readSections = (
bytes: Buffer,
coff: CoffHeader,
optional: OptionalHeader,
): readonly PeSection[] => {
const sectionOffset = add(optional.optionalOffset, coff.optionalSize, "pe.sections");
requireRange(
bytes,
sectionOffset,
coff.sectionCount * 40,
"pe.sections",
);
const sections: PeSection[] = [];
for (let index = 0; index < sectionCount; index += 1) {
for (let index = 0; index < coff.sectionCount; index += 1) {
const offset = sectionOffset + index * 40;
const section = {
virtualSize: bytes.readUInt32LE(offset + 8),
@@ -265,11 +297,38 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
);
sections.push(section);
}
const cliDirectory =
return sections;
};
const readCliDirectory = (
bytes: Buffer,
coff: CoffHeader,
optional: OptionalHeader,
): PeDataDirectory => {
requireRange(bytes, optional.directoryCountOffset, 4, "pe.data-directories");
const directoryCount = bytes.readUInt32LE(optional.directoryCountOffset);
if (
directoryCount <= 14 ||
optionalSize < directoryOffset - optionalOffset + 120
? { rva: 0, size: 0 }
: readDirectory(bytes, directoryOffset + 14 * 8);
coff.optionalSize < optional.directoryOffset - optional.optionalOffset + 120
)
return { rva: 0, size: 0 };
return readDirectory(bytes, optional.directoryOffset + 14 * 8);
};
/** Parse the file-backed PE and CLI layout without loading target code. */
export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
requireRange(bytes, 0, 64, "pe.dos-header");
if (bytes[0] !== 0x4d || bytes[1] !== 0x5a)
throw managedFailure(
"invalid-directory",
"pe.dos-header",
"Artifact does not start with an MZ header",
0,
);
const coff = readCoffHeader(bytes);
const optional = readOptionalHeader(bytes, coff);
const sections = readSections(bytes, coff, optional);
const cliDirectory = readCliDirectory(bytes, coff, optional);
const cliDirectoryPresent = cliDirectory.rva !== 0 || cliDirectory.size !== 0;
let cli: ManagedCliHeader | null = null;
let cliIssue: ManagedParseIssue | null = null;
@@ -281,16 +340,16 @@ export const readManagedPeLayout = (bytes: Buffer): ManagedPeLayout => {
cliIssue = cause.issue;
}
return {
machine,
architecture: architectureFor(machine),
optionalHeader,
sectionCount,
characteristics,
machine: coff.machine,
architecture: architectureFor(coff.machine),
optionalHeader: optional.optionalHeader,
sectionCount: coff.sectionCount,
characteristics: coff.characteristics,
sections,
cli,
cliDirectoryPresent,
cliIssue,
rvaToOffset: (rva, size, scope) =>
mapRva(bytes, sections, rva, size, scope),
mapRva({ bytes, sections, rva, size, scope }),
};
};