Files
rea/src/domain/managed/managedArtifact.ts
T
91830f1e0e feat(managed): name the declaring type of call and field targets (#2163)
* feat(managed): name the declaring type of call and field targets

Call edges named external targets by member name alone (Join, ToJson,
WriteAllText), and method-spec edges had no name at all, so an analyst could
not tell which library a method calls or find every use of a type without a
decompiler. Field accesses through MemberRefs had no name either.

Name each TypeDef, TypeRef, and generic-instantiation TypeSpec once, in the
namespace-qualified form TypeDef full_name uses, and add member_refs
parent_name, call_edges target_declaring_type, and field_accesses
field_declaring_type. A method-spec target reports the generic method it
instantiates. Fields, member references, methods, and method specs now
resolve through one token-keyed MemberCore lookup instead of three maps.
Evidence recorded before these fields reads them as null.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): validate spec blobs and member kinds before naming targets

Address review findings on declaring-type naming:

- A generic instantiation must name a TypeDef or TypeRef, so a TypeSpec
  base is reported as malformed instead of followed. Naming no longer
  recurses.
- TypeSpec and MethodSpec instantiation blobs are decoded with the
  member-signature grammar. Malformed blobs and out-of-range TypeDef rows
  are reported against their owning row and make coverage partial.
- A MethodSpec reads both columns. An invalid Method coded index is
  reported; a readable Method keeps its name beside a malformed
  instantiation.
- MemberCore carries its signature kind, so a field operand is named only
  by a field or field-signature MemberRef. This replaces the token-table
  guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): validate MethodSpec arity and report unsupported spec blobs

- A MethodSpec now checks that its method signature is generic and that
  the instantiation supplies as many type arguments as it declares. A
  non-generic target, a field reference, or a count mismatch is reported
  as invalid-row; the readable method keeps its name.
- Unsupported TypeSpec and MethodSpec forms raise an owner-scoped
  unsupported-signature issue instead of reading as an intentional
  unknown.
- MethodSpec reading moves to ManagedMethodSpecs.ts, and its tests get
  their own describe block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): reject non-method signature headers and invalid TypeRef scopes

The method signature header reader now owns the calling-convention rule
that only FNPTR applied: FIELD, LOCAL_SIG, PROPERTY, and GENERICINST
headers, the reserved bit, and EXPLICITTHIS without HASTHIS are malformed.
A MethodSpec whose method has a PROPERTY header is no longer accepted as a
generic method, and member signatures with such headers no longer decode
as methods.

The type-name lookup validates a TypeRef's ResolutionScope coded index and
reports an out-of-range scope as invalid-row, keeping the readable name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): hold member rows to MethodDefSig and FieldSig headers

Method signature headers are now checked in context. MethodDef and
MemberRef rows accept only the MethodDefSig/MethodRefSig headers: DEFAULT,
VARARG, or GENERIC with DEFAULT. FNPTR keeps the unmanaged conventions
compilers emit for function pointers. A field signature must be exactly
FIELD, so a flagged FIELD header is malformed and never names a field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): accept MethodSpec arity only from a fully decoded signature

The arity check read only the target's signature header, so a truncated
generic method signature passed. Under type selection a MethodDef target
outside the selection is never decoded elsewhere, so coverage stayed
complete. The arity now comes from a transient full decode, and only a
decoded method signature supplies it. signature() keeps its raw length
and digest around the shared decodeSignature.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf(managed): decode each MethodSpec target signature once

edgeTargets caches the generic arity, including a failed decode, by
target method token, so many instantiations of one generic method share
a single signature decode. Unity.InputSystem has 472 distinct MethodSpecs
over about 133 target methods.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): validate spec type operands and transitive reference scopes

* fix(managed): retain readable names when a scope row is unreadable

* test(managed): pin owner-scoped spec operand and scope-chain checks

e59217c83 validates spec type operands inside specSignature, so a
malformed generic TypeSpec base is now invalid-row under its owning
TypeSpec row; the three stale expectations follow that. New cases cover
a TypeSpec argument and a MethodSpec argument that name a missing TypeRef,
and a TypeRef whose ResolutionScope names itself. The scope cases move to
their own describe block.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): keep field targets from naming MethodSpecs

A MethodSpec over a field-signature MemberRef inherited kind "field", so
an ldsfld on that MethodSpec published a field name and declaring type
for malformed IL. A MethodSpec now borrows its target's name only when
the target is not a field; the arity check still reports it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(managed): reuse owner-decoded signatures for MethodSpec arity

MemberRef signatures, and MethodDef signatures in the type selection, are
already fully decoded, but the MethodSpec arity check decoded them again
and admitted a second transient allocation, which could exhaust the
budget. MemberCore now carries the owner's genericArity, and only a target
nothing decoded, such as an unselected MethodDef, falls back to the raw
signature. signatureGenericArity is the one rule for both paths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-10-13 21:12:15 +08:00

535 lines
17 KiB
TypeScript

import { z } from "zod";
import { digestSchema } from "../digests.js";
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const offsetSchema = z.number().int().min(0);
/** A 16-byte CLI metadata GUID without RFC 4122 version/variant restrictions. */
export const cliMetadataGuidSchema = z
.string()
.regex(/^[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$/u);
const publicKeyIdentitySchema = z.object({
kind: z.enum(["none", "public-key", "public-key-token"]),
byte_length: z.number().int().min(0),
sha256: digestSchema.nullable(),
token: z
.string()
.regex(/^[a-f0-9]{16}$/u)
.nullable(),
});
const assemblyIdentitySchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
hash_algorithm: z.number().int().min(0).max(0xffff_ffff),
public_key: publicKeyIdentitySchema,
token: tokenSchema,
row_offset: offsetSchema,
});
const moduleIdentitySchema = z.object({
name: z.string(),
generation: z.number().int().min(0).max(0xffff),
mvid: cliMetadataGuidSchema.nullable(),
enc_id: cliMetadataGuidSchema.nullable(),
enc_base_id: cliMetadataGuidSchema.nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const assemblyReferenceSchema = z.object({
name: z.string(),
version: z.string().regex(/^\d+\.\d+\.\d+\.\d+$/u),
culture: z.string().nullable(),
flags: z.number().int().min(0).max(0xffff_ffff),
public_key_or_token: publicKeyIdentitySchema,
hash_value_sha256: digestSchema.nullable(),
hash_value_length: z.number().int().min(0),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedResourceSchema = z.object({
name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
visibility: z.enum(["public", "private", "unknown"]),
implementation_token: tokenSchema.nullable(),
embedded: z.boolean(),
declared_offset: z.number().int().min(0).max(0xffff_ffff),
data_length: z.number().int().min(0).nullable(),
data_sha256: digestSchema.nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const customAttributeSchema = z.object({
parent_token: tokenSchema,
constructor_token: tokenSchema.nullable(),
type_name: z.string().nullable(),
value_length: z.number().int().min(0),
value_sha256: digestSchema,
decoded_fixed_string: z.string().nullable(),
token: tokenSchema,
row_offset: offsetSchema,
});
const managedSignatureSchema = z.object({
raw_length: z.number().int().min(0),
raw_sha256: digestSchema,
kind: z.enum(["method", "field", "unknown"]),
parse_status: z.enum(["decoded", "partial", "unsupported", "malformed"]),
calling_convention: z.string().nullable(),
generic_parameter_count: z.number().int().min(0).nullable(),
parameter_count: z.number().int().min(0).nullable(),
return_type: z.string().nullable(),
parameter_types: z.array(z.string()),
field_type: z.string().nullable(),
issue: z.string().nullable(),
});
const managedTypeSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
namespace: z.string(),
name: z.string(),
full_name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
extends_token: tokenSchema.nullable(),
field_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
method_list: z.object({
first_row: z.number().int().min(1).nullable(),
last_row: z.number().int().min(0).nullable(),
count: z.number().int().min(0),
}),
});
/** One ExportedType row: a type this assembly exports from another module or forwards. */
const managedExportedTypeSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
namespace: z.string(),
name: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
forwarder: z.boolean(),
type_def_id: z.number().int().min(0).max(0xffff_ffff),
implementation_token: tokenSchema.nullable(),
});
const managedFieldSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
});
const managedExceptionRegionSchema = z.object({
flags: z.number().int().min(0).max(0xffff_ffff),
try_offset: z.number().int().min(0),
try_length: z.number().int().min(0),
handler_offset: z.number().int().min(0),
handler_length: z.number().int().min(0),
class_token: tokenSchema.nullable(),
filter_offset: z.number().int().min(0).nullable(),
});
const managedInstructionAnchorSchema = z.object({
il_offset: z.number().int().min(0),
opcode: z.string().min(1),
operand_kind: z.enum([
"none",
"branch",
"constant",
"field",
"method",
"signature",
"string",
"switch",
"token",
"type",
"variable",
"unknown",
]),
operand: z.string().nullable(),
});
const managedMethodBodySchema = z.object({
status: z.enum(["present", "partial", "absent", "malformed"]),
header_format: z.enum(["tiny", "fat", "none", "unknown"]),
rva: z.number().int().min(0).max(0xffff_ffff),
file_offset: offsetSchema.nullable(),
max_stack: z.number().int().min(0).nullable(),
init_locals: z.boolean().nullable(),
local_var_sig_token: tokenSchema.nullable(),
il_size: z.number().int().min(0),
il_sha256: digestSchema
.nullable()
.describe(
"SHA-256 of exactly the raw il_size CIL bytes; excludes the method header, locals signature, alignment, and extra sections",
),
normalized_il_sha256: digestSchema
.nullable()
.describe(
"Member-result-v1 SHA-256 of UTF-8 JSON [opcode, operand_kind, operand] tuples for a complete decode; retains build-local tokens, omits switch targets, and excludes headers, locals, and exception regions",
),
instruction_count: z.number().int().min(0),
decoded_instruction_count: z.number().int().min(0),
truncated_instructions: z.number().int().min(0),
opcode_counts: z.record(z.string(), z.number().int().min(1)),
anchors: z.array(managedInstructionAnchorSchema),
exception_regions: z.array(managedExceptionRegionSchema),
issue: z.string().nullable(),
});
const managedMethodSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
declaring_type_token: tokenSchema.nullable(),
declaring_type: z.string().nullable(),
name: z.string(),
rva: z.number().int().min(0).max(0xffff_ffff),
impl_flags: z.number().int().min(0).max(0xffff),
flags: z.number().int().min(0).max(0xffff),
signature: managedSignatureSchema,
body: managedMethodBodySchema,
});
// Declaring types are namespace-qualified like TypeDef `full_name`, nested
// types keep bare names, and a generic instantiation names its generic type.
// Evidence recorded before declaring types were named reads them as null.
const declaringTypeNameSchema = z.string().nullable().default(null);
const managedMemberReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
parent_token: tokenSchema.nullable(),
parent_name: declaringTypeNameSchema.describe(
"Name of a TypeDef, TypeRef, or generic-instantiation TypeSpec parent; null for other parents or when unknown",
),
name: z.string(),
signature: managedSignatureSchema,
});
const managedModuleReferenceSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
name: z.string(),
});
const managedNativeImportSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
mapping_flags: z.number().int().min(0).max(0xffff),
mapping_flags_hex: z.string().regex(/^0x[0-9a-f]{4}$/u),
member_token: tokenSchema.nullable(),
member_kind: z.enum(["method", "field", "unknown"]),
member_name: z.string().nullable(),
import_name: z.string(),
import_scope_token: tokenSchema.nullable(),
import_scope_name: z.string().nullable(),
no_mangle: z.boolean(),
char_set: z.enum(["not-specified", "ansi", "unicode", "auto", "unknown"]),
call_convention: z.enum([
"not-specified",
"winapi",
"cdecl",
"stdcall",
"thiscall",
"fastcall",
"unknown",
]),
supports_last_error: z.boolean(),
best_fit: z.enum(["assembly-default", "enabled", "disabled", "unknown"]),
throw_on_unmappable_char: z.enum([
"assembly-default",
"enabled",
"disabled",
"unknown",
]),
verification: z.literal("managed-declaration-only"),
});
const managedNativeImplementationSchema = z.object({
token: tokenSchema,
row_offset: offsetSchema,
name: z.string(),
rva: z.number().int().min(0).max(0xffff_ffff),
flags: z.number().int().min(0).max(0xffff),
impl_flags: z.number().int().min(0).max(0xffff),
code_type: z.enum(["il", "native", "optil", "runtime", "unknown"]),
managed_kind: z.enum(["managed", "unmanaged", "unknown"]),
pinvoke_declared: z.boolean(),
boundary_kind: z.enum([
"pinvoke",
"native-body",
"runtime-provided",
"unmanaged-method",
"mixed-or-unknown",
]),
body_interpretation: z.enum([
"managed-cil",
"native-or-runtime",
"not-file-backed",
"unknown",
]),
});
const managedCallEdgeSchema = z.object({
caller_token: tokenSchema,
caller: z.string().nullable(),
opcode: z.string(),
target_token: tokenSchema,
target_kind: z.enum(["method-def", "member-ref", "method-spec", "unknown"]),
target_name: z
.string()
.nullable()
.describe("Method name; a method-spec target reports its generic method"),
target_declaring_type: declaringTypeNameSchema.describe(
"Declaring type of the called method; null when unknown",
),
});
const managedFieldAccessSchema = z.object({
method_token: tokenSchema,
method: z.string().nullable(),
opcode: z.string(),
field_token: tokenSchema,
field_name: z.string().nullable(),
field_declaring_type: declaringTypeNameSchema.describe(
"Declaring type of the accessed field; null when unknown",
),
});
const managedParseIssueSchema = z.object({
code: z.enum([
"resource-limit",
"invalid-cli-header",
"invalid-directory",
"invalid-metadata-root",
"invalid-stream",
"missing-stream",
"invalid-tables",
"invalid-row",
"invalid-heap-index",
"invalid-string",
"invalid-blob",
"unsupported-signature",
"invalid-guid",
"invalid-resource",
]),
scope: z.string().min(1),
offset: offsetSchema.nullable(),
detail: z.string().min(1),
});
/** Provider-neutral, execution-free PE/CLI triage and identity result. */
export const managedArtifactInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
pe: z.object({
machine: z.number().int().min(0).max(0xffff),
machine_hex: z.string().regex(/^0x[0-9a-f]{4}$/u),
architecture: z.enum(["x86", "x86_64", "arm", "arm64"]),
optional_header: z.enum(["pe32", "pe32-plus"]),
section_count: z.number().int().min(1).max(0xffff),
characteristics: z.number().int().min(0).max(0xffff),
cli: z
.object({
header_offset: offsetSchema,
header_size: z.number().int().min(72),
runtime_version: z.string(),
flags: z.number().int().min(0).max(0xffff_ffff),
flag_names: z.array(z.string()),
entry_point: z.object({
kind: z.enum(["metadata-token", "native-rva", "none"]),
value: z.string().nullable(),
}),
metadata_rva: z.number().int().min(1).max(0xffff_ffff),
metadata_size: z.number().int().min(1).max(0xffff_ffff),
resources_rva: z.number().int().min(0).max(0xffff_ffff),
resources_size: z.number().int().min(0).max(0xffff_ffff),
strong_name_rva: z.number().int().min(0).max(0xffff_ffff),
strong_name_size: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
ready_to_run_signature: z.boolean(),
})
.nullable(),
}),
classification: z.object({
status: z.enum(["managed", "not-managed", "malformed"]),
container: z.literal("pe"),
runtime_family: z.enum([
"dotnet-framework",
"modern-dotnet",
"unity-mono",
"mixed-clr-native",
"unknown",
]),
implementation: z.enum([
"cil",
"cil-and-ready-to-run",
"cpp-cli-mixed",
"metadata-only",
"not-managed",
"unknown",
]),
managed_architecture: z.enum([
"anycpu",
"anycpu-prefer-32",
"x86",
"x86_64",
"arm",
"arm64",
"unknown",
]),
evidence: z.array(
z.object({
code: z.string().min(1),
detail: z.string().min(1),
file_offset: offsetSchema.nullable(),
}),
),
}),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
stream_names: z.array(z.string()),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
module: moduleIdentitySchema.nullable(),
assembly: assemblyIdentitySchema.nullable(),
target_frameworks: z.array(z.string()),
references: z.array(assemblyReferenceSchema),
resources: z.array(managedResourceSchema),
attributes: z.array(customAttributeSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
/** Provider-neutral, execution-free metadata/signature/IL member inspection. */
export const managedMemberInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
module: moduleIdentitySchema.nullable(),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
identity_scope: z.object({
token_identity: z.literal("build-local"),
requires_artifact_sha256: digestSchema,
requires_mvid: cliMetadataGuidSchema.nullable(),
}),
types: z.array(managedTypeSchema),
// Member Evidence recorded before ExportedType rows were read omits this
// field; null means the table was not examined, not that it was empty.
exported_types: z.array(managedExportedTypeSchema).nullable().default(null),
fields: z.array(managedFieldSchema),
methods: z.array(managedMethodSchema),
member_refs: z.array(managedMemberReferenceSchema),
call_edges: z.array(managedCallEdgeSchema),
field_accesses: z.array(managedFieldAccessSchema),
/** Caller-selected declaring types; null when every type was inspected. */
selection: z
.object({
type_names: z.array(z.string().min(1)).min(1),
unmatched_type_names: z.array(z.string().min(1)),
})
.nullable()
.default(null),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
/** Provider-neutral managed/native boundary observations from PE/CLI metadata. */
export const managedNativeBoundaryInspectionSchema = z.object({
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
byte_length: z.number().int().min(0),
format: z.literal("pe"),
}),
module: moduleIdentitySchema.nullable(),
metadata: z.object({
status: z.enum(["absent", "complete", "partial", "malformed"]),
version: z.string().nullable(),
table_row_counts: z.record(
z.string(),
z.number().int().min(0).max(0xffff_ffff),
),
}),
identity_scope: z.object({
token_identity: z.literal("build-local"),
requires_artifact_sha256: digestSchema,
requires_mvid: cliMetadataGuidSchema.nullable(),
}),
cli_native: z
.object({
il_only: z.boolean(),
requires_32bit: z.boolean(),
strong_name_signed: z.boolean(),
native_entry_point: z.boolean(),
ready_to_run_signature: z.boolean(),
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
})
.nullable(),
module_refs: z.array(managedModuleReferenceSchema),
pinvoke_imports: z.array(managedNativeImportSchema),
native_implementations: z.array(managedNativeImplementationSchema),
summary: z.object({
module_ref_count: z.number().int().min(0),
pinvoke_import_count: z.number().int().min(0),
native_implementation_count: z.number().int().min(0),
ready_to_run: z.boolean().nullable(),
mixed_mode_or_native_header: z.boolean().nullable(),
}),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
}),
limitations: z.array(z.string()),
});
export type ManagedArtifactInspection = z.infer<
typeof managedArtifactInspectionSchema
>;
export type ManagedMemberInspection = z.infer<
typeof managedMemberInspectionSchema
>;
export type ManagedNativeBoundaryInspection = z.infer<
typeof managedNativeBoundaryInspectionSchema
>;
export type ManagedParseIssue = z.infer<typeof managedParseIssueSchema>;