From c2ed07fdc063a1e5cfc11c04326ecf0e3631fa36 Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Sun, 6 Dec 2026 16:16:33 +0800 Subject: [PATCH] feat(dotnet): inventory a managed assembly's enums, enum arguments and GUID literals (#17366) Add inventory_managed_features across CLI and MCP to report enum definitions, direct constant enum arguments, and GUID literals with CIL sites and retained summary views. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --- .../skills/reverse-engineer-anything/SKILL.md | 5 +- .../references/native-and-artifacts.md | 10 + .../skills/reverse-engineer-anything/SKILL.md | 5 +- .../references/native-and-artifacts.md | 10 + docs/.vitepress/documentation.ts | 5 + docs/README.md | 1 + docs/getting-started/cli.md | 9 + docs/guides/managed/feature-inventory.md | 65 ++ docs/reference/limits-and-recovery.md | 2 + docs/reference/supported-targets.md | 1 + scripts/ci/scopes.mjs | 5 + scripts/fixtures/managed/pe.mjs | 181 ++++- scripts/lib/module-layers.mjs | 2 + .../tools/inventory_managed_features.json | 10 + .../ManagedFeatureInventoryService.test.ts | 99 +++ .../managed/ManagedFeatureInventoryService.ts | 52 ++ src/cli.ts | 2 + src/cli/cliCommandRegistrations.ts | 5 + src/cli/managedFeatureInventoryCommands.ts | 35 + src/composition/capabilityDeclarations.ts | 8 + src/composition/capabilityServices.ts | 7 + src/composition/managedFeatureInventory.ts | 7 + .../managedFeatureInventoryToolContracts.ts | 37 ++ src/contracts/toolContracts.ts | 2 + src/contracts/toolFamilies.ts | 1 + src/domain/agentBudgetOperations.ts | 1 + src/domain/analysisView/analysisView.ts | 2 + src/domain/analysisView/analysisViewResult.ts | 4 + .../managedFeatureInventoryView.test.ts | 93 +++ .../managedFeatureInventoryView.ts | 176 +++++ .../managedFeatureInventorySummarySchema.ts | 8 + .../managed/managedDecodeBudget.test.ts | 25 + src/domain/managed/managedDecodeBudget.ts | 15 + src/domain/managed/managedFeatureInventory.ts | 128 ++++ .../managed/managedMemberInspectorCore.ts | 152 +++-- src/dotnet/ManagedMethodBodyReader.ts | 45 ++ .../features/ManagedFeatureInventory.test.ts | 206 ++++++ .../features/ManagedFeatureInventory.ts | 623 ++++++++++++++++++ .../ManagedFeatureInventoryProvider.ts | 154 +++++ ...ManagedFeatureInventoryProviderIdentity.ts | 6 + .../managed/ManagedFeatureInventoryPort.ts | 20 + src/server/createServer.ts | 2 + src/server/offlineInspectionToolBindings.ts | 4 + .../managedFeatureInventoryCli.test.ts | 61 ++ .../tools/localToolContracts.test.ts | 1 + .../mcp/managedFeatureInventoryMcp.test.ts | 68 ++ tests/boundary/mcp/servedSchemaParity.test.ts | 1 + tests/conformance/providerCapabilityCases.ts | 3 + tests/fixtures/featureAssembly.ts | 183 +++++ tests/support/providerLifecycleCoverage.ts | 14 + 50 files changed, 2487 insertions(+), 74 deletions(-) create mode 100644 docs/guides/managed/feature-inventory.md create mode 100644 scripts/verify/advertised-schemas/tools/inventory_managed_features.json create mode 100644 src/application/managed/ManagedFeatureInventoryService.test.ts create mode 100644 src/application/managed/ManagedFeatureInventoryService.ts create mode 100644 src/cli/managedFeatureInventoryCommands.ts create mode 100644 src/composition/managedFeatureInventory.ts create mode 100644 src/contracts/managed/managedFeatureInventoryToolContracts.ts create mode 100644 src/domain/analysisView/managedFeatureInventoryView.test.ts create mode 100644 src/domain/analysisView/managedFeatureInventoryView.ts create mode 100644 src/domain/analysisView/summarySchemas/managedFeatureInventorySummarySchema.ts create mode 100644 src/domain/managed/managedFeatureInventory.ts create mode 100644 src/dotnet/features/ManagedFeatureInventory.test.ts create mode 100644 src/dotnet/features/ManagedFeatureInventory.ts create mode 100644 src/dotnet/features/ManagedFeatureInventoryProvider.ts create mode 100644 src/dotnet/features/ManagedFeatureInventoryProviderIdentity.ts create mode 100644 src/ports/managed/ManagedFeatureInventoryPort.ts create mode 100644 tests/acceptance/managedFeatureInventoryCli.test.ts create mode 100644 tests/boundary/mcp/managedFeatureInventoryMcp.test.ts create mode 100644 tests/fixtures/featureAssembly.ts diff --git a/.agents/skills/reverse-engineer-anything/SKILL.md b/.agents/skills/reverse-engineer-anything/SKILL.md index 471ffae9294..8fd0d573d3a 100644 --- a/.agents/skills/reverse-engineer-anything/SKILL.md +++ b/.agents/skills/reverse-engineer-anything/SKILL.md @@ -121,7 +121,10 @@ explicit path or endpoint and do not need it. `dotnet-assembly`; extract a `.g.resources` member and inspect it as a resource set; decode its `.baml` views with `inspect_baml`. An assembly that references Google.Protobuf: `recover_protobuf_descriptors` returns its - `.proto` files and a FileDescriptorSet for capture decoding. + `.proto` files and a FileDescriptorSet for capture decoding. To map an + application's features, `inventory_managed_features` lists its enums, + the enum constants its calls pass (such as localization keys) and its + GUID literals, with CIL sites. - .NET resource set (`.resources`, such as a WPF assembly's `.g.resources` holding BAML): `inspect_artifact` without a provider, then `extract_artifact` for selected members. Serialized objects are listed by diff --git a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md index c51b5deade9..286e07f9eb7 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -903,6 +903,16 @@ run-time strings are out of reach; an empty result is not proof that no protobuf is used. See [protobuf descriptors](https://github.com/morluto/rea/blob/main/docs/guides/managed/protobuf-descriptors.md) and [.NET resource sets](https://github.com/morluto/rea/blob/main/docs/guides/managed/dotnet-resources.md). +`inventory_managed_features` maps an application's feature surface: the enums +it defines (names ending in Type, Kind, Mode or Category are marked), each +constant pushed directly before a call for an enum parameter, with the member +it names when the enum is defined in the same assembly, and GUID string +literals, each with its method token and IL offset. Obfuscation renames types +and methods but keeps enum values and literals, so these sites lead to the +code behind a feature. Run it on a separate localization or contracts +assembly to name the values of enums defined there. It identifies and lists +only. See +[feature inventory](https://github.com/morluto/rea/blob/main/docs/guides/managed/feature-inventory.md). ### .NET NativeAOT diff --git a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md index 471ffae9294..8fd0d573d3a 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/SKILL.md @@ -121,7 +121,10 @@ explicit path or endpoint and do not need it. `dotnet-assembly`; extract a `.g.resources` member and inspect it as a resource set; decode its `.baml` views with `inspect_baml`. An assembly that references Google.Protobuf: `recover_protobuf_descriptors` returns its - `.proto` files and a FileDescriptorSet for capture decoding. + `.proto` files and a FileDescriptorSet for capture decoding. To map an + application's features, `inventory_managed_features` lists its enums, + the enum constants its calls pass (such as localization keys) and its + GUID literals, with CIL sites. - .NET resource set (`.resources`, such as a WPF assembly's `.g.resources` holding BAML): `inspect_artifact` without a provider, then `extract_artifact` for selected members. Serialized objects are listed by diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md index c51b5deade9..286e07f9eb7 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -903,6 +903,16 @@ run-time strings are out of reach; an empty result is not proof that no protobuf is used. See [protobuf descriptors](https://github.com/morluto/rea/blob/main/docs/guides/managed/protobuf-descriptors.md) and [.NET resource sets](https://github.com/morluto/rea/blob/main/docs/guides/managed/dotnet-resources.md). +`inventory_managed_features` maps an application's feature surface: the enums +it defines (names ending in Type, Kind, Mode or Category are marked), each +constant pushed directly before a call for an enum parameter, with the member +it names when the enum is defined in the same assembly, and GUID string +literals, each with its method token and IL offset. Obfuscation renames types +and methods but keeps enum values and literals, so these sites lead to the +code behind a feature. Run it on a separate localization or contracts +assembly to name the values of enums defined there. It identifies and lists +only. See +[feature inventory](https://github.com/morluto/rea/blob/main/docs/guides/managed/feature-inventory.md). ### .NET NativeAOT diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index a4fdb67e543..902bc211a62 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -343,6 +343,11 @@ export const documentationSections = [ source: "guides/managed/protobuf-descriptors.md", route: "/protobuf-descriptors", }, + { + text: "Feature inventory of .NET assemblies", + source: "guides/managed/feature-inventory.md", + route: "/managed-feature-inventory", + }, guideAtRoute("IL2CPP metadata", "/il2cpp-metadata"), ], }, diff --git a/docs/README.md b/docs/README.md index 4e1a1bcaf2c..31d736daf72 100644 --- a/docs/README.md +++ b/docs/README.md @@ -108,6 +108,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages. - [.NET resource sets](guides/managed/dotnet-resources.md) - [WPF BAML documents](guides/managed/baml.md) - [Protobuf descriptors in .NET assemblies](guides/managed/protobuf-descriptors.md) +- [Feature inventory of .NET assemblies](guides/managed/feature-inventory.md) - [.NET single-file bundles](dotnet-bundles.md) - [IL2CPP metadata](il2cpp-metadata.md) diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 9a519907eb4..eb0de4b3aa1 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -306,6 +306,15 @@ rea recover-protobuf-descriptors /absolute/path/App.Client.dll --json See [protobuf descriptors](../guides/managed/protobuf-descriptors.md). +List a managed assembly's enums, the enum constants its calls pass, and its +GUID literals: + +```bash +rea inventory-managed-features /absolute/path/App.exe --json +``` + +See [feature inventory](../guides/managed/feature-inventory.md). + ## SQLite snapshots For a local database snapshot, use `rea inspect-sqlite-database PATH --json`. diff --git a/docs/guides/managed/feature-inventory.md b/docs/guides/managed/feature-inventory.md new file mode 100644 index 00000000000..36bc43bd6d9 --- /dev/null +++ b/docs/guides/managed/feature-inventory.md @@ -0,0 +1,65 @@ +# Feature inventory of .NET assemblies + +An application's feature surface often shows in a few places in its +metadata and CIL, even when type and member names are obfuscated: + +- enums of kinds, such as a `MenuType`, `BuiltinCommandType` or + `SearchBarType`, list a subsystem's features in a few lines; +- localization keys, often an enum such as `LocKey`, lead to the code that + owns each piece of text; +- hard-coded GUIDs identify default items, COM classes and interfaces. + +Use `rea inventory-managed-features App.exe --json` or MCP +`inventory_managed_features` to list them without loading or running the +assembly. The inventory identifies and lists for orientation; it offers no +way to modify, patch or enable anything. + +The report has three lists: + +- `enums`: every enum the assembly defines, with its `underlying_type` and + its members' names and values (decimal text). `kind_name` marks names that + end in Type, Kind, Mode or Category. `argument_sites` counts the + `enum_arguments` rows that pass one of its values. +- `enum_arguments`: each constant pushed directly before a call for a + value-type parameter. In verifiable CIL only an enum value is pushed that + way, so each row names: + - the parameter's `enum` and its position (`parameter`); + - the `callee`; + - the `value`, and the `member` it names when the enum is defined in the + same assembly (`defined_here`); + - the calling `method`, its `method_token` and the constant's `il_offset`. +- `guid_literals`: `ldstr` literals in GUID form, with or without braces, + normalised to lower case, with their method and IL offset. + +For example, on a WPF application whose localization keys live in a +separate assembly, `enum_arguments` lists each `Loc.Get(LocKey, …)` call +with the key's value. Running the inventory on the localization assembly +gives the `LocKey` members to name those values. + +The scan reads every method body once and keeps only the rows it reports. +What it does not attribute is listed in `limitations`: + +- a value that is computed, loaded from a field or local, or merged from two + branches: a branch target between the constant and the call stops + attribution; +- members of an enum defined in another assembly: the row keeps the enum's + name, and `member` is null; +- GUIDs built from integers or byte arrays. + +A method whose CIL cannot be decoded completely is counted in +`undecoded_methods`, and coverage is then `partial`. + +The per-call budgets are: + +- `max_entries`: enum members, enum argument sites and GUID literals + together, 65,536 by default, up to 1,048,576; +- `max_text_bytes`: the reported names and literals, 16 MiB by default, up to + 256 MiB; +- `max_snapshot_bytes` and `max_metadata_representation_bytes`, as for + `inspect_managed_artifact`. + +An exhausted budget fails without partial success and names the parameter to +raise. A large result returns its summary: kind-named enums first, enum +arguments grouped by enum with the most sites first, and a sample of the +GUID literals. Page the complete record with `inspect_analysis_view` kind +`evidence-json`. diff --git a/docs/reference/limits-and-recovery.md b/docs/reference/limits-and-recovery.md index b8c79fa0b21..090ecffeeaf 100644 --- a/docs/reference/limits-and-recovery.md +++ b/docs/reference/limits-and-recovery.md @@ -142,6 +142,8 @@ import and lambda rows combined; default 65,536, at most 1,048,576). `recover_protobuf_descriptors` reports `details.limit` for `max_descriptor_bytes`, `max_descriptor_depth`, `max_snapshot_bytes` and `max_metadata_representation_bytes`. +`inventory_managed_features` reports `details.limit` for `max_entries`, `max_text_bytes`, `max_snapshot_bytes` and `max_metadata_representation_bytes`. + `inspect_uniffi_library` reports `details.limit` for its per-call budgets (`max_file_bytes`, `max_entries`, `max_text_bytes` and `max_structure_bytes`). `inspect_baml` reports `details.limit` for its per-call budgets (`max_file_bytes`, `max_records`, `max_elements` and `max_text_bytes`). diff --git a/docs/reference/supported-targets.md b/docs/reference/supported-targets.md index 2910f6a284b..dcb7b38b1bd 100644 --- a/docs/reference/supported-targets.md +++ b/docs/reference/supported-targets.md @@ -18,6 +18,7 @@ For worked examples by target type, see the [guides on rea.tools](https://rea.to | Unix ar archives | GNU and BSD member inventory, thin references, and stored-member extraction | Built-in static reader; [Unix ar archives](../guides/artifacts/ar-archives.md) | | .NET resource sets | Named strings, byte arrays, streams and primitives with decoded values; serialized objects listed by type | Built-in static reader; [.NET resource sets](../guides/managed/dotnet-resources.md) | | Protobuf descriptors | FileDescriptorProtos from Google.Protobuf Reflection classes in .NET assemblies, as a FileDescriptorSet | Built-in static CIL reading; [protobuf descriptors](../guides/managed/protobuf-descriptors.md) | +| .NET feature inventory | Enums, constant enum arguments and GUID literals in .NET assemblies, with CIL sites | Built-in static CIL reading; [feature inventory](../guides/managed/feature-inventory.md) | | WPF BAML documents | Element tree, names, keys, connection IDs, property values, bindings and resource references of compiled XAML | Built-in static reader; [WPF BAML documents](../guides/managed/baml.md) | | .NET assembly resources | Manifest resources embedded in a managed assembly, listed and extracted as stored bytes | Built-in static reader; [.NET resource sets](../guides/managed/dotnet-resources.md) | | Switch NSO/NRO | Module id, segment layout and hashes, NRO icon/NACP/RomFS ranges; LZ4 segments decompressed | Built-in static header parsing; [Switch executables](../guides/firmware/switch-executables.md) | diff --git a/scripts/ci/scopes.mjs b/scripts/ci/scopes.mjs index 49bc175b277..59c9375b7a5 100644 --- a/scripts/ci/scopes.mjs +++ b/scripts/ci/scopes.mjs @@ -181,6 +181,11 @@ const PATH_SCOPES = { "src/application/managed/ProtobufDescriptorsService*.ts", "src/domain/analysisView/protobufDescriptorsView.ts", "docs/guides/managed/protobuf-descriptors.md", + "src/domain/managed/managedFeatureInventory.ts", + "src/dotnet/features/**", + "src/application/managed/ManagedFeatureInventoryService*.ts", + "src/domain/analysisView/managedFeatureInventoryView.ts", + "docs/guides/managed/feature-inventory.md", "src/domain/native/uniffiLibrary*.ts", "src/native/uniffi/**", "src/application/binaryDiagnostics/UniffiLibraryService*.ts", diff --git a/scripts/fixtures/managed/pe.mjs b/scripts/fixtures/managed/pe.mjs index b3477a3950c..05490eaeae3 100644 --- a/scripts/fixtures/managed/pe.mjs +++ b/scripts/fixtures/managed/pe.mjs @@ -7,6 +7,7 @@ import { Buffer } from "node:buffer"; * readonly implFlags?: number; * readonly name: string; * readonly rva?: number; + * readonly signature?: Buffer; * }} ManagedPeFixtureMethod */ /** @@ -45,6 +46,22 @@ import { Buffer } from "node:buffer"; * readonly secondType?: { readonly name: string; readonly firstField: number }; * readonly typeName?: string; * readonly typeNamespace?: string; + * readonly typeRefs?: readonly { readonly name: string; readonly namespace: string }[]; + * readonly types?: readonly { + * readonly name: string; + * readonly namespace?: string; + * readonly extendsRaw?: number; + * readonly flags?: number; + * readonly fieldList: number; + * readonly methodList: number; + * }[]; + * readonly memberRefs?: readonly { + * readonly parentRaw: number; + * readonly name: string; + * readonly signature: Buffer; + * }[]; + * readonly userStrings?: readonly string[]; + * readonly nestedClasses?: readonly (readonly [number, number])[]; * }} ManagedPeFixtureOptions */ /** A method whose metadata row has an RVA. @typedef {ManagedPeFixtureMethod & { readonly rva: number }} PlacedFixtureMethod */ @@ -140,12 +157,19 @@ const typeRefRow = (name, namespace) => * @param {number} fieldList * @param {number} methodList */ -const typeDefRow = (name, namespace, fieldList, methodList) => +const typeDefRow = ( + name, + namespace, + fieldList, + methodList, + extendsRaw = (1 << 2) | 1, + flags = 0x0010_0001, +) => Buffer.concat([ - u32(0x0010_0001), + u32(flags), u16(name), u16(namespace), - u16((1 << 2) | 1), + u16(extendsRaw), u16(fieldList), u16(methodList), ]); @@ -187,8 +211,8 @@ const methodDefRow = ({ * @param {number} name * @param {number} signature */ -const memberRefRow = (name, signature) => - Buffer.concat([u16((1 << 3) | 1), u16(name), u16(signature)]); +const memberRefRow = (name, signature, parentRaw = (1 << 3) | 1) => + Buffer.concat([u16(parentRaw), u16(name), u16(signature)]); /** @param {number} name */ const moduleRefRow = (name) => Buffer.concat([u16(name)]); @@ -271,8 +295,9 @@ const metadataStreamHeader = (relativeOffset, size, name) => { * @param {Buffer} strings * @param {Buffer} guid * @param {Buffer} blob + * @param {Buffer} [userStrings] A #US heap; omitted, the root has four streams. */ -const metadataRoot = (tables, strings, guid, blob) => { +const metadataRoot = (tables, strings, guid, blob, userStrings) => { const version = Buffer.from("v4.0.30319\0\0", "utf8"); const header = Buffer.concat([ u32(0x424a_5342), @@ -282,13 +307,14 @@ const metadataRoot = (tables, strings, guid, blob) => { u32(version.length), version, u16(0), - u16(4), + u16(userStrings === undefined ? 4 : 5), ]); const streamHeaderSize = metadataStreamHeader(0, 0, "#~").length + metadataStreamHeader(0, 0, "#Strings").length + metadataStreamHeader(0, 0, "#GUID").length + - metadataStreamHeader(0, 0, "#Blob").length; + metadataStreamHeader(0, 0, "#Blob").length + + (userStrings === undefined ? 0 : metadataStreamHeader(0, 0, "#US").length); let offset = align4(header.length + streamHeaderSize); const tablesOffset = offset; offset = align4(offset + tables.length); @@ -297,13 +323,23 @@ const metadataRoot = (tables, strings, guid, blob) => { const guidOffset = offset; offset = align4(offset + guid.length); const blobOffset = offset; + offset = align4(offset + blob.length); + const userStringsOffset = offset; const headers = Buffer.concat([ metadataStreamHeader(tablesOffset, tables.length, "#~"), metadataStreamHeader(stringsOffset, strings.length, "#Strings"), metadataStreamHeader(guidOffset, guid.length, "#GUID"), metadataStreamHeader(blobOffset, blob.length, "#Blob"), + ...(userStrings === undefined + ? [] + : [metadataStreamHeader(userStringsOffset, userStrings.length, "#US")]), ]); - const root = Buffer.alloc(align4(blobOffset + blob.length)); + const root = Buffer.alloc( + userStrings === undefined + ? align4(blobOffset + blob.length) + : align4(userStringsOffset + userStrings.length), + ); + userStrings?.copy(root, userStringsOffset); header.copy(root, 0); headers.copy(root, header.length); tables.copy(root, tablesOffset); @@ -425,7 +461,10 @@ const buildManagedMetadata = (options, methods) => { const methodRows = namedMethods.map(({ method, name }) => methodDefRow({ name, - signature: methodSignature, + signature: + method.signature === undefined + ? methodSignature + : blobs.add(method.signature), rva: method.rva, flags: method.flags ?? 0x0016, implFlags: method.implFlags ?? 0, @@ -435,32 +474,74 @@ const buildManagedMetadata = (options, methods) => { /** @type {Map} */ const rows = new Map([ [0, [moduleRow(moduleName)]], - [1, [typeRefRow(attributeName, attributeNamespace)]], + [ + 1, + [ + typeRefRow(attributeName, attributeNamespace), + ...(options.typeRefs ?? []).map((reference) => + typeRefRow( + strings.add(reference.name), + strings.add(reference.namespace), + ), + ), + ], + ], [ 2, - [ - typeDefRow(typeName, typeNamespace, 1, 1), - ...(secondType === undefined - ? [] - : [ - typeDefRow( - strings.add(secondType.name), - typeNamespace, - secondType.firstField, - methods.length + 1, - ), - ]), - ], + options.types !== undefined + ? options.types.map((type) => + typeDefRow( + strings.add(type.name), + strings.add(type.namespace ?? ""), + type.fieldList, + type.methodList, + type.extendsRaw ?? 0, + type.flags ?? 0x0010_0001, + ), + ) + : [ + typeDefRow(typeName, typeNamespace, 1, 1), + ...(secondType === undefined + ? [] + : [ + typeDefRow( + strings.add(secondType.name), + typeNamespace, + secondType.firstField, + methods.length + 1, + ), + ]), + ], ], [4, fieldRows], [6, methodRows], - [10, [memberRefRow(constructorName, constructorSignature)]], + [ + 10, + [ + memberRefRow(constructorName, constructorSignature), + ...(options.memberRefs ?? []).map((reference) => + memberRefRow( + strings.add(reference.name), + blobs.add(reference.signature), + reference.parentRaw, + ), + ), + ], + ], [12, [customAttributeRow(attributeBlob)]], [32, [assemblyRow(assemblyName)]], [35, referenceStringIndexes.map((name) => assemblyRefRow(name, tokenBlob))], [40, [manifestResourceRow(resourceName)]], ]); if (constantRows.length > 0) rows.set(11, constantRows); + // NestedClass rows: [nested TypeDef row, enclosing TypeDef row]. + if (options.nestedClasses !== undefined) + rows.set( + 41, + options.nestedClasses.map(([nested, enclosing]) => + Buffer.concat([u16(nested), u16(enclosing)]), + ), + ); if (pinvokeModuleName !== null) rows.set(26, [moduleRefRow(pinvokeModuleName)]); if (pinvokeImportName !== null) @@ -477,11 +558,61 @@ const buildManagedMetadata = (options, methods) => { strings.toBuffer(), guidHeap(options.mvid), blobs.toBuffer(), + options.userStrings === undefined + ? undefined + : managedUserStringHeap(options.userStrings).heap, ); if (options.corruptMetadataSignature === true) metadata.writeUInt32LE(0, 0); return metadata; }; +/** + * ECMA-335 II.24.2.4: the terminal byte is 1 when a UTF-16 unit has a + * non-zero high byte or a low byte in 0x01-0x08, 0x0E-0x1F, 0x27, 0x2D or 0x7F. + * @param {string} value + */ +const userStringTerminal = (value) => { + for (let index = 0; index < value.length; index += 1) { + const unit = value.charCodeAt(index); + if ( + unit > 0xff || + (unit >= 0x01 && unit <= 0x08) || + (unit >= 0x0e && unit <= 0x1f) || + unit === 0x27 || + unit === 0x2d || + unit === 0x7f + ) + return 1; + } + return 0; +}; + +/** + * A #US heap holding `values` in order, with each literal's heap offset: an + * `ldstr` operand is `0x70000000 | offset`. + * @param {readonly string[]} values + */ +export const managedUserStringHeap = (values) => { + /** @type {Buffer[]} */ + const chunks = [Buffer.from([0])]; + /** @type {number[]} */ + const offsets = []; + let size = 1; + for (const value of values) { + const text = Buffer.from(value, "utf16le"); + if (text.length + 1 > 0x7f) + throw new RangeError("Managed PE fixture user string is too long"); + offsets.push(size); + chunks.push( + Buffer.from([text.length + 1]), + text, + Buffer.from([userStringTerminal(value)]), + ); + size += text.length + 2; + } + return { heap: Buffer.concat(chunks), offsets }; +}; + /** * @param {number} value * @param {number} boundary diff --git a/scripts/lib/module-layers.mjs b/scripts/lib/module-layers.mjs index df606ca5868..e4b185dd914 100644 --- a/scripts/lib/module-layers.mjs +++ b/scripts/lib/module-layers.mjs @@ -310,6 +310,8 @@ export const ENTRY_FILES = Object.freeze( "baml/BamlProviderIdentity.ts", "protobuf/ProtobufDescriptorsProvider.ts", "protobuf/ProtobufDescriptorsProviderIdentity.ts", + "features/ManagedFeatureInventoryProvider.ts", + "features/ManagedFeatureInventoryProviderIdentity.ts", ], electron: ["ElectronFuseProvider.ts", "ElectronFuseProviderIdentity.ts"], erlang: ["BeamProvider.ts", "ErlangBeamProviderIdentity.ts"], diff --git a/scripts/verify/advertised-schemas/tools/inventory_managed_features.json b/scripts/verify/advertised-schemas/tools/inventory_managed_features.json new file mode 100644 index 00000000000..8b971500eed --- /dev/null +++ b/scripts/verify/advertised-schemas/tools/inventory_managed_features.json @@ -0,0 +1,10 @@ +{ + "schemas": { + "input compact": "3f5f5bbab4ccb1b0", + "output compact": "e345f0377ecbe795" + }, + "patterns": { + "input": ["^(?:[\\x2f\\\\]|[A-Za-z]:[\\x2f\\\\])[^\\x00]*$"], + "output": ["^[^\\x00]*$", "^ev_[0-9a-f]{64}$"] + } +} diff --git a/src/application/managed/ManagedFeatureInventoryService.test.ts b/src/application/managed/ManagedFeatureInventoryService.test.ts new file mode 100644 index 00000000000..634c5bc9125 --- /dev/null +++ b/src/application/managed/ManagedFeatureInventoryService.test.ts @@ -0,0 +1,99 @@ +import { expectInvalidInspectionInputs } from "../../../tests/support/expectInvalidInspectionInputs.js"; +import { lateCancellationEvidence } from "../../../tests/support/lateCancellationEvidence.js"; +import { expect, it } from "vitest"; +import { ManagedFeatureInventoryService } from "./ManagedFeatureInventoryService.js"; +import type { ManagedFeatureInventory } from "../../domain/managed/managedFeatureInventory.js"; + +const identity = { + id: "fixture-managed-feature-inventory", + name: "Source-owned feature inventory seam", + version: "1", +}; + +const site = { + method: "Demo.Program.Main", + method_token: "0x06000002", + il_offset: 0, +}; + +const report: ManagedFeatureInventory = { + artifact: { path: "/artifacts/App.dll", sha256: "a".repeat(64), bytes: 4096 }, + enums: [ + { + type: "Demo.Mode", + token: "0x02000001", + underlying_type: "i4", + kind_name: true, + members: [{ name: "Advanced", value: "5" }], + argument_sites: 1, + }, + ], + enum_arguments: [ + { + enum: "Demo.Mode", + defined_here: true, + value: "5", + member: "Advanced", + callee: "Demo.Program.Use", + parameter: 0, + ...site, + }, + ], + guid_literals: [ + { value: "44eca225-98f6-489c-b97a-03163e83ce7e", ...site, il_offset: 13 }, + ], + coverage: { status: "complete", methods: 2, undecoded_methods: 0 }, + limitations: [], +}; + +const serviceReturning = (value: ManagedFeatureInventory) => + new ManagedFeatureInventoryService({ + close: async () => {}, + identity, + inspect: async () => ({ ok: true, value }), + }); + +it("rejects relative paths, extra arguments, and NUL paths before reading", async () => { + await expectInvalidInspectionInputs( + report, + "App.dll", + (inspect) => + new ManagedFeatureInventoryService({ + close: async () => {}, + identity, + inspect, + }), + "/artifacts/App\0.dll", + ); +}); + +it("retains completed Evidence and caller selections on late cancellation", async () => { + const evidence = await lateCancellationEvidence( + report, + { source: "caller-request", operation: "cancel" }, + (inspect) => + new ManagedFeatureInventoryService({ + close: async () => {}, + identity, + inspect, + }), + ); + expect(evidence).toMatchObject({ + operation: "inventory_managed_features", + parameters: { path: report.artifact.path }, + normalized_result: report, + }); +}); + +it("refuses a report with more rows than the caller allowed", async () => { + const result = await serviceReturning(report).inspect({ + path: report.artifact.path, + max_entries: 2, + }); + expect(result.ok).toBe(false); + const admitted = await serviceReturning(report).inspect({ + path: report.artifact.path, + max_entries: 3, + }); + expect(admitted.ok).toBe(true); +}); diff --git a/src/application/managed/ManagedFeatureInventoryService.ts b/src/application/managed/ManagedFeatureInventoryService.ts new file mode 100644 index 00000000000..8d3bf3822a0 --- /dev/null +++ b/src/application/managed/ManagedFeatureInventoryService.ts @@ -0,0 +1,52 @@ +import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; +import type { ManagedFeatureInventoryPort } from "../../ports/managed/ManagedFeatureInventoryPort.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import type { Evidence } from "../../domain/evidence.js"; +import { + inventoryManagedFeaturesInputSchema, + managedFeatureInventorySchema, +} from "../../domain/managed/managedFeatureInventory.js"; +import type { Result } from "../../domain/result.js"; +import { observedFileEvidence } from "../observedFileEvidence.js"; +import { executeArtifactInspection } from "../ArtifactInspectionExecution.js"; + +const OPERATION = "inventory_managed_features"; + +/** Shared caller validation, output parsing and Evidence provenance for CLI and MCP. */ +export class ManagedFeatureInventoryService { + constructor(readonly provider: ManagedFeatureInventoryPort) {} + + close(): Promise { + return this.provider.close(); + } + + inspect( + rawInput: unknown, + options?: ExecutionOptions, + ): Promise> { + return executeArtifactInspection( + { + operation: OPERATION, + inputSchema: inventoryManagedFeaturesInputSchema, + outputSchema: managedFeatureInventorySchema, + provider: this.provider, + invalidOutputMessage: + "Managed feature inventory provider returned malformed output or changed artifact identity.", + toParameters: (input) => input, + validateReport: (report, parameters) => + report.artifact.path === parameters.path && + report.enums.reduce( + (total, { members }) => total + members.length, + 0, + ) + + report.enum_arguments.length + + report.guid_literals.length <= + parameters.max_entries, + buildEvidence: (value, identity, parameters) => + observedFileEvidence(value, identity, OPERATION, parameters), + }, + rawInput, + options, + ); + } +} diff --git a/src/cli.ts b/src/cli.ts index f47d3a66e5c..a07bd3851a4 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -36,6 +36,7 @@ import * as rustModule from "./cli/rustCommands.js"; import * as pythonPycModule from "./cli/pythonPycCommands.js"; import * as bamlModule from "./cli/bamlCommands.js"; import * as protobufDescriptorsModule from "./cli/protobufDescriptorCommands.js"; +import * as managedFeatureInventoryModule from "./cli/managedFeatureInventoryCommands.js"; import * as debPackageModule from "./cli/debPackageCommands.js"; import * as nugetNupkgModule from "./cli/nugetNupkgCommands.js"; import * as vsixPackageModule from "./cli/vsixPackageCommands.js"; @@ -106,6 +107,7 @@ const CLI_COMMAND_MODULES: CliCommandModules = { pythonPyc: pythonPycModule, baml: bamlModule, protobufDescriptors: protobufDescriptorsModule, + managedFeatureInventory: managedFeatureInventoryModule, debPackage: debPackageModule, nugetNupkg: nugetNupkgModule, vsixPackage: vsixPackageModule, diff --git a/src/cli/cliCommandRegistrations.ts b/src/cli/cliCommandRegistrations.ts index 8170eb9a55c..0d7d76214eb 100644 --- a/src/cli/cliCommandRegistrations.ts +++ b/src/cli/cliCommandRegistrations.ts @@ -110,6 +110,10 @@ export const CLI_COMMAND_REGISTRATIONS = { () => import("./protobufDescriptorCommands.js"), "registerProtobufDescriptorCommands", ), + managedFeatureInventory: cliRegistrar( + () => import("./managedFeatureInventoryCommands.js"), + "registerManagedFeatureInventoryCommands", + ), debPackage: cliRegistrar( () => import("./debPackageCommands.js"), "registerDebPackageCommands", @@ -347,6 +351,7 @@ const CLI_FAMILY_REGISTRATIONS: { "pythonPyc", "baml", "protobufDescriptors", + "managedFeatureInventory", "debPackage", "nugetNupkg", "vsixPackage", diff --git a/src/cli/managedFeatureInventoryCommands.ts b/src/cli/managedFeatureInventoryCommands.ts new file mode 100644 index 00000000000..580839ec6f6 --- /dev/null +++ b/src/cli/managedFeatureInventoryCommands.ts @@ -0,0 +1,35 @@ +import type { Logger } from "pino"; + +import { createManagedFeatureInventoryService } from "../composition/managedFeatureInventory.js"; +import { MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS } from "../contracts/managed/managedFeatureInventoryToolContracts.js"; +import { contractNamed } from "./contractCliDescription.js"; +import { registerContractCommand } from "./contractCommand.js"; +import { deliverWithService } from "./contractCommandRunners.js"; +import type { CliInstance } from "./types.js"; + +/** Inventory operator-selected assemblies through the same workflow as MCP. */ +export const registerManagedFeatureInventoryCommands = ( + cli: CliInstance, + logger: Logger, +): void => { + registerContractCommand( + cli, + logger, + contractNamed( + MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS, + "inventory_managed_features", + ), + { + description: + "List a managed assembly's enums, enum arguments and GUID literals without loading it", + positionals: ["path"], + callerPaths: ["path"], + evidenceDelivery: true, + fields: { path: { description: "Local managed PE assembly" } }, + }, + deliverWithService( + createManagedFeatureInventoryService, + "rea-managed-feature-inventory", + ), + ); +}; diff --git a/src/composition/capabilityDeclarations.ts b/src/composition/capabilityDeclarations.ts index 1433566bac7..4303fda503d 100644 --- a/src/composition/capabilityDeclarations.ts +++ b/src/composition/capabilityDeclarations.ts @@ -116,6 +116,7 @@ import { YARA_PROVIDER_IDENTITY } from "../yara/YaraProviderIdentity.js"; import { PYTHON_PYC_PROVIDER_IDENTITY } from "../python/PythonPycProviderIdentity.js"; import { BAML_PROVIDER_IDENTITY } from "../dotnet/baml/BamlProviderIdentity.js"; import { PROTOBUF_DESCRIPTORS_PROVIDER_IDENTITY } from "../dotnet/protobuf/ProtobufDescriptorsProviderIdentity.js"; +import { MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY } from "../dotnet/features/ManagedFeatureInventoryProviderIdentity.js"; import { DEB_PACKAGE_PROVIDER_IDENTITY } from "../deb/DebPackageProviderIdentity.js"; import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "../rizin/RizinDebuggerProviderIdentity.js"; import { RIZIN_PROVIDER_IDENTITY } from "../rizin/RizinProviderIdentity.js"; @@ -518,6 +519,13 @@ export const CAPABILITY_DECLARATIONS = { }), ], }, + managedFeatureInventory: { + providers: [ + providerBinding(MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY, { + group: "MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS", + }), + ], + }, debPackage: { providers: [ providerBinding(DEB_PACKAGE_PROVIDER_IDENTITY, { diff --git a/src/composition/capabilityServices.ts b/src/composition/capabilityServices.ts index 4c817ce4c16..40d8c3a9673 100644 --- a/src/composition/capabilityServices.ts +++ b/src/composition/capabilityServices.ts @@ -51,6 +51,7 @@ import { createReleaseExposureService } from "./releaseExposure.js"; import { createPythonPycService } from "./pythonPyc.js"; import { createBamlService } from "./baml.js"; import { createProtobufDescriptorsService } from "./protobufDescriptors.js"; +import { createManagedFeatureInventoryService } from "./managedFeatureInventory.js"; import { createDebPackageService } from "./debPackage.js"; import { createNugetNupkgService } from "./nugetNupkg.js"; import { createVsixPackageService } from "./vsixPackage.js"; @@ -128,6 +129,7 @@ import type { RustBinaryService } from "../application/rust/RustBinaryService.js import type { PythonPycService } from "../application/python/PythonPycService.js"; import type { BamlService } from "../application/managed/BamlService.js"; import type { ProtobufDescriptorsService } from "../application/managed/ProtobufDescriptorsService.js"; +import type { ManagedFeatureInventoryService } from "../application/managed/ManagedFeatureInventoryService.js"; import type { DebPackageService } from "../application/deb/DebPackageService.js"; import type { NugetNupkgService } from "../application/nuget/NugetNupkgService.js"; import type { VsixPackageService } from "../application/vsix/VsixPackageService.js"; @@ -171,6 +173,7 @@ export interface CapabilityServiceOptions { readonly pythonPyc?: PythonPycService; readonly baml?: BamlService; readonly protobufDescriptors?: ProtobufDescriptorsService; + readonly managedFeatureInventory?: ManagedFeatureInventoryService; readonly debPackage?: DebPackageService; readonly nugetNupkg?: NugetNupkgService; readonly vsixPackage?: VsixPackageService; @@ -465,6 +468,10 @@ const modules = { ({ options }) => options.protobufDescriptors ?? createProtobufDescriptorsService(), ), + managedFeatureInventory: service( + ({ options }) => + options.managedFeatureInventory ?? createManagedFeatureInventoryService(), + ), debPackage: service( ({ options }) => options.debPackage ?? createDebPackageService(), ), diff --git a/src/composition/managedFeatureInventory.ts b/src/composition/managedFeatureInventory.ts new file mode 100644 index 00000000000..5f2f97535d6 --- /dev/null +++ b/src/composition/managedFeatureInventory.ts @@ -0,0 +1,7 @@ +import { ManagedFeatureInventoryService } from "../application/managed/ManagedFeatureInventoryService.js"; +import { ManagedFeatureInventoryProvider } from "../dotnet/features/ManagedFeatureInventoryProvider.js"; + +/** Compose a read-only feature inventory without loading or running the assembly. */ +export const createManagedFeatureInventoryService = + (): ManagedFeatureInventoryService => + new ManagedFeatureInventoryService(new ManagedFeatureInventoryProvider()); diff --git a/src/contracts/managed/managedFeatureInventoryToolContracts.ts b/src/contracts/managed/managedFeatureInventoryToolContracts.ts new file mode 100644 index 00000000000..ebb59b805d8 --- /dev/null +++ b/src/contracts/managed/managedFeatureInventoryToolContracts.ts @@ -0,0 +1,37 @@ +import { + inventoryManagedFeaturesInputSchema, + managedFeatureInventorySchema, +} from "../../domain/managed/managedFeatureInventory.js"; +import { managedFeatureInventorySummaryViewResultSchema } from "../../domain/analysisView/summarySchemas/managedFeatureInventorySummarySchema.js"; +import { + analysisDetailOutputSchemaOf, + analysisDetailSchema, +} from "../analysisDetail.js"; +import type { ToolContract } from "../toolContractTypes.js"; +import { evidenceEffects, toolContractMetadata } from "../toolEffects.js"; + +/** A static feature-surface inventory, independent of .NET. */ +export const MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS = [ + { + name: "inventory_managed_features", + availability: "standalone", + cli: true, + ...toolContractMetadata("inventory_managed_features", evidenceEffects), + kind: "artifact-provider", + description: + "List a managed assembly's feature surface from its metadata and CIL, without loading or running it: the enums it defines with their member values, marking names that end in Type, Kind or Mode (enums of kinds often name every feature of a subsystem); each constant passed directly to an enum-typed parameter, such as a localization key or command kind, with its callee, the member it names when the enum is defined in the same assembly, and its method token and IL offset; and string literals in GUID form, such as default-item or COM identifiers, with their sites. This is an inventory for orientation; it identifies and lists, and offers no way to modify, patch or enable anything. Values computed at run time, merged across branches or loaded from fields are not attributed. Exhausted budgets fail without partial success. Omitted detail returns complete Evidence within the agent result budget and otherwise the retained summary; inspect_analysis_view kind evidence-json pages the complete record.", + inputSchema: inventoryManagedFeaturesInputSchema.extend({ + detail: analysisDetailSchema, + }), + outputSchema: analysisDetailOutputSchemaOf( + managedFeatureInventorySchema, + managedFeatureInventorySummaryViewResultSchema, + ), + examples: [ + { + title: "Inventory an application assembly's enums and feature keys", + input: { path: "/artifacts/App.exe" }, + }, + ], + }, +] as const satisfies readonly ToolContract[]; diff --git a/src/contracts/toolContracts.ts b/src/contracts/toolContracts.ts index f2720ada733..0a7aabc6b3b 100644 --- a/src/contracts/toolContracts.ts +++ b/src/contracts/toolContracts.ts @@ -16,6 +16,7 @@ import { LABVIEW_TOOL_CONTRACTS } from "./labview/labviewToolContracts.js"; import { PYTHON_PYC_TOOL_CONTRACTS } from "./python/pythonPycToolContracts.js"; import { BAML_TOOL_CONTRACTS } from "./managed/bamlToolContracts.js"; import { PROTOBUF_DESCRIPTOR_TOOL_CONTRACTS } from "./managed/protobufDescriptorToolContracts.js"; +import { MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS } from "./managed/managedFeatureInventoryToolContracts.js"; import { DEB_PACKAGE_TOOL_CONTRACTS } from "./deb/debPackageToolContracts.js"; import { NUGET_NUPKG_TOOL_CONTRACTS } from "./nuget/nupkgToolContracts.js"; import { VSIX_PACKAGE_TOOL_CONTRACTS } from "./vsix/vsixPackageToolContracts.js"; @@ -97,6 +98,7 @@ const CATALOG_CONTRACT_GROUPS = { SIGNAL_TOOL_CONTRACTS, MANAGED_TOOL_CONTRACTS, PROTOBUF_DESCRIPTOR_TOOL_CONTRACTS, + MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS, ANDROID_TOOL_CONTRACTS, APKTOOL_TOOL_CONTRACTS, PCAP_TOOL_CONTRACTS, diff --git a/src/contracts/toolFamilies.ts b/src/contracts/toolFamilies.ts index 5a36e70455f..2316dc5af90 100644 --- a/src/contracts/toolFamilies.ts +++ b/src/contracts/toolFamilies.ts @@ -73,6 +73,7 @@ export const TOOL_FAMILY_DEFINITIONS = [ contracts: [ ...TOOL_CONTRACT_GROUPS.MANAGED_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.PROTOBUF_DESCRIPTOR_TOOL_CONTRACTS, + ...TOOL_CONTRACT_GROUPS.MANAGED_FEATURE_INVENTORY_TOOL_CONTRACTS, ...TOOL_CONTRACT_GROUPS.MANAGED_WORKFLOW_TOOL_CONTRACTS, ], }, diff --git a/src/domain/agentBudgetOperations.ts b/src/domain/agentBudgetOperations.ts index 854aa622005..bb21a5408f4 100644 --- a/src/domain/agentBudgetOperations.ts +++ b/src/domain/agentBudgetOperations.ts @@ -48,6 +48,7 @@ export const AGENT_BUDGET_OPERATIONS = [ "inspect_baml", "inspect_uniffi_library", "recover_protobuf_descriptors", + "inventory_managed_features", "inspect_wasm_artifact", "inspect_web_network_capture", "inspect_web_page", diff --git a/src/domain/analysisView/analysisView.ts b/src/domain/analysisView/analysisView.ts index 22914409b75..b29c03b9bd8 100644 --- a/src/domain/analysisView/analysisView.ts +++ b/src/domain/analysisView/analysisView.ts @@ -34,6 +34,7 @@ import { projectVsixPackageView } from "./vsixPackageView.js"; import { projectBamlDocumentView } from "./bamlDocumentView.js"; import { projectUniffiLibraryView } from "./uniffiLibraryView.js"; import { projectProtobufDescriptorsView } from "./protobufDescriptorsView.js"; +import { projectManagedFeatureInventoryView } from "./managedFeatureInventoryView.js"; import { projectOciImageLayoutView } from "./ociImageLayoutView.js"; import { projectNativeExportsView } from "./nativeExportsView.js"; import { projectPeImportsView } from "./peImportsView.js"; @@ -230,6 +231,7 @@ const retainedViewProjectors = new Map([ retain("inspect_baml", projectBamlDocumentView), retain("inspect_uniffi_library", projectUniffiLibraryView), retain("recover_protobuf_descriptors", projectProtobufDescriptorsView), + retain("inventory_managed_features", projectManagedFeatureInventoryView), retain("inspect_oci_image_layout", projectOciImageLayoutView), retain("frida_session_status", projectFridaSessionStatusView), retain("gdb_console", projectCommandObservationView), diff --git a/src/domain/analysisView/analysisViewResult.ts b/src/domain/analysisView/analysisViewResult.ts index 6f50b4353d0..2b994a552f5 100644 --- a/src/domain/analysisView/analysisViewResult.ts +++ b/src/domain/analysisView/analysisViewResult.ts @@ -331,6 +331,7 @@ import { vsixPackageSummaryViewResultSchema } from "./summarySchemas/vsixPackage import { bamlDocumentSummaryViewResultSchema } from "./summarySchemas/bamlDocumentSummarySchema.js"; import { uniffiLibrarySummaryViewResultSchema } from "./summarySchemas/uniffiLibrarySummarySchema.js"; import { protobufDescriptorsSummaryViewResultSchema } from "./summarySchemas/protobufDescriptorsSummarySchema.js"; +import { managedFeatureInventorySummaryViewResultSchema } from "./summarySchemas/managedFeatureInventorySummarySchema.js"; import { wasmArtifactSummaryViewResultSchema } from "./summarySchemas/wasmArtifactSummarySchema.js"; import { webBundlePageViewResultSchema, @@ -446,6 +447,7 @@ export { bamlDocumentSummaryViewResultSchema, uniffiLibrarySummaryViewResultSchema, protobufDescriptorsSummaryViewResultSchema, + managedFeatureInventorySummaryViewResultSchema, wasmArtifactSummaryViewResultSchema, webBundlePageViewResultSchema, webBundleSummaryViewResultSchema, @@ -474,6 +476,7 @@ const viewResultBase = { "inspect_baml", "inspect_uniffi_library", "recover_protobuf_descriptors", + "inventory_managed_features", "inspect_oci_image_layout", "inspect_erlang_beam", "inspect_devicetree", @@ -908,6 +911,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [ bamlDocumentSummaryViewResultSchema, uniffiLibrarySummaryViewResultSchema, protobufDescriptorsSummaryViewResultSchema, + managedFeatureInventorySummaryViewResultSchema, ociImageLayoutSummaryViewResultSchema, ]), z.strictObject({ diff --git a/src/domain/analysisView/managedFeatureInventoryView.test.ts b/src/domain/analysisView/managedFeatureInventoryView.test.ts new file mode 100644 index 00000000000..045ec9f1596 --- /dev/null +++ b/src/domain/analysisView/managedFeatureInventoryView.test.ts @@ -0,0 +1,93 @@ +import { expect, it } from "vitest"; +import { createEvidence } from "../evidence.js"; +import type { ManagedFeatureInventory } from "../managed/managedFeatureInventory.js"; +import { projectAnalysisView } from "./analysisView.js"; +import type { AnalysisViewParent } from "./analysisViewParent.js"; + +const SHA = "a".repeat(64); +const site = { method: "App.Main", method_token: "0x06000001", il_offset: 0 }; + +const parentFor = (report: ManagedFeatureInventory): AnalysisViewParent => { + const evidence = createEvidence( + { + path: report.artifact.path, + sha256: SHA, + format: "pe", + architecture: "x86", + }, + { id: "feature-view-test", name: "Feature view test", version: "1" }, + { + operation: "inventory_managed_features", + parameters: { path: report.artifact.path }, + result: report, + confidence: "observed", + }, + ); + return { + evidenceId: evidence.evidence_id, + operation: evidence.operation, + predicateType: evidence.predicate_type, + subject: evidence.subject, + normalizedResult: structuredClone(report), + limitations: evidence.limitations, + provider: evidence.provider, + }; +}; + +const enumNamed = ( + type: string, + kind_name: boolean, + argument_sites: number, +) => ({ + type, + token: "0x02000001", + underlying_type: "i4", + kind_name, + members: [{ name: "A", value: "0" }], + argument_sites, +}); + +it("summarizes kind-named enums first and groups enum arguments by enum", () => { + const argument = (type: string, value: string) => ({ + enum: type, + defined_here: false, + value, + member: null, + callee: "Loc.Get", + parameter: 0, + ...site, + }); + const report: ManagedFeatureInventory = { + artifact: { path: "/artifacts/App.exe", sha256: SHA, bytes: 4096 }, + enums: [ + enumNamed("App.Colors", false, 9), + enumNamed("App.MenuType", true, 1), + ], + enum_arguments: [ + argument("Loc.LocKey", "1"), + argument("Loc.LocKey", "2"), + argument("Loc.LocKey", "2"), + argument("App.MenuType", "0"), + ], + guid_literals: [{ value: "44eca225-98f6-489c-b97a-03163e83ce7e", ...site }], + coverage: { status: "complete", methods: 1, undecoded_methods: 0 }, + limitations: [], + }; + const result = projectAnalysisView(parentFor(report), { kind: "summary" }); + if (!result.ok) throw result.error; + expect(result.value).toMatchObject({ + summary: { + enums: [ + { type: "App.MenuType", kind_name: true, member_count: 1 }, + { type: "App.Colors", kind_name: false, argument_sites: 9 }, + ], + enum_count: 2, + enum_argument_groups: [ + { enum: "Loc.LocKey", sites: 3, distinct_values: 2 }, + { enum: "App.MenuType", sites: 1, distinct_values: 1 }, + ], + enum_argument_count: 4, + guid_literal_count: 1, + }, + }); +}); diff --git a/src/domain/analysisView/managedFeatureInventoryView.ts b/src/domain/analysisView/managedFeatureInventoryView.ts new file mode 100644 index 00000000000..ca47b191fdd --- /dev/null +++ b/src/domain/analysisView/managedFeatureInventoryView.ts @@ -0,0 +1,176 @@ +import { artifactSummaryViewFields } from "./analysisViewBase.js"; +import { viewParentIdentity } from "./viewParentIdentity.js"; +import { z } from "zod"; +import { managedFeatureInventorySchema } from "../managed/managedFeatureInventory.js"; +import { ok } from "../result.js"; +import type { AnalysisViewParent } from "./analysisViewParent.js"; +import { + ownedView, + type AdmittedView, + type SummaryAnalysisView, +} from "./analysisViewShape.js"; +import { invalidAnalysisView } from "./analysisViewErrors.js"; +import { createAnalysisViewResultReader } from "./analysisViewParent.js"; +import { boundedViewLimitations } from "./analysisViewCoverage.js"; +import { boundedList } from "../boundedList.js"; + +/** Enums listed in the summary, kind-named first; the rest stay in the complete parent. */ +const SUMMARY_ENUMS = 48; +/** Enum argument groups listed, most sites first. */ +const SUMMARY_ARGUMENT_GROUPS = 32; +/** GUID literals listed. */ +const SUMMARY_GUIDS = 16; +/** UTF-16 code-unit cap for summary names so summaries stay within the agent budget. */ +const SUMMARY_TEXT_UNITS = 200; + +const count = z.int().nonnegative(); + +/** Per-enum and per-group counts; members and sites stay in the complete parent. */ +export const managedFeatureInventorySummarySchema = + managedFeatureInventorySchema + .pick({ artifact: true, coverage: true }) + .extend({ + enums: z.array( + z.strictObject({ + type: z.string(), + kind_name: z.boolean(), + member_count: count, + argument_sites: count, + }), + ), + enum_count: count, + /** Enum arguments grouped by the parameter's enum type. */ + enum_argument_groups: z.array( + z.strictObject({ + enum: z.string(), + defined_here: z.boolean(), + sites: count, + distinct_values: count, + }), + ), + enum_argument_group_count: count, + enum_argument_count: count, + guid_literals: z.array( + z.strictObject({ value: z.string(), method: z.string() }), + ), + guid_literal_count: count, + text_truncated: z.boolean(), + limitation_count: count, + }); + +const readReport = createAnalysisViewResultReader( + managedFeatureInventorySchema, +); + +/** Summarize a retained feature inventory without reading the assembly again. */ +export const projectManagedFeatureInventoryView = ( + parent: AnalysisViewParent, + admitted: AdmittedView, +) => { + const view = ownedView(admitted, "summary"); + if (view === undefined) + return invalidAnalysisView( + "Managed feature inventory Evidence supports the summary view.", + ); + const parsed = readReport(parent); + if (!parsed.ok) return parsed; + const report = parsed.value; + let textTruncated = false; + const bound = (value: string): string => { + if (value.length <= SUMMARY_TEXT_UNITS) return value; + textTruncated = true; + const last = value.charCodeAt(SUMMARY_TEXT_UNITS - 1); + return value.slice( + 0, + last >= 0xd800 && last <= 0xdbff + ? SUMMARY_TEXT_UNITS - 1 + : SUMMARY_TEXT_UNITS, + ); + }; + // Kind-named enums first, then by argument sites; the sort is stable. + const enums = boundedList( + [...report.enums].sort( + (left, right) => + Number(right.kind_name) - Number(left.kind_name) || + right.argument_sites - left.argument_sites, + ), + SUMMARY_ENUMS, + ); + const groups = new Map< + string, + { defined_here: boolean; sites: number; values: Set } + >(); + for (const argument of report.enum_arguments) { + const group = groups.get(argument.enum) ?? { + defined_here: argument.defined_here, + sites: 0, + values: new Set(), + }; + group.sites += 1; + group.values.add(argument.value); + groups.set(argument.enum, group); + } + const ranked = boundedList( + [...groups].sort(([, left], [, right]) => right.sites - left.sites), + SUMMARY_ARGUMENT_GROUPS, + ); + const guids = boundedList(report.guid_literals, SUMMARY_GUIDS); + const summary = { + artifact: report.artifact, + coverage: report.coverage, + enums: enums.items.map((entry) => ({ + type: bound(entry.type), + kind_name: entry.kind_name, + member_count: entry.members.length, + argument_sites: entry.argument_sites, + })), + enum_count: report.enums.length, + enum_argument_groups: ranked.items.map(([name, group]) => ({ + enum: bound(name), + defined_here: group.defined_here, + sites: group.sites, + distinct_values: group.values.size, + })), + enum_argument_group_count: groups.size, + enum_argument_count: report.enum_arguments.length, + guid_literals: guids.items.map(({ value, method }) => ({ + value, + method: bound(method), + })), + guid_literal_count: report.guid_literals.length, + text_truncated: textTruncated, + limitation_count: report.limitations.length, + }; + const { artifact, ...fields } = artifactSummaryViewFields( + view, + summary, + summary.enum_count, + ); + const omitted = (listed: number, total: number, what: string) => + listed < total + ? [ + `The summary lists ${String(listed)} of ${String(total)} ${what}; inspect parent Evidence ${parent.evidenceId} for the rest.`, + ] + : []; + const required = [ + ...omitted(enums.items.length, report.enums.length, "enums"), + ...omitted(ranked.items.length, groups.size, "enum argument groups"), + ...omitted( + guids.items.length, + report.guid_literals.length, + "GUID literals", + ), + ...(textTruncated + ? [ + `A name was truncated to fit the summary view; inspect parent Evidence ${parent.evidenceId} for the complete value.`, + ] + : []), + ]; + return ok({ + ...viewParentIdentity(parent, "inventory_managed_features"), + artifact, + limitations: boundedViewLimitations(parent, report.limitations, required), + unknowns: [], + ...fields, + }); +}; diff --git a/src/domain/analysisView/summarySchemas/managedFeatureInventorySummarySchema.ts b/src/domain/analysisView/summarySchemas/managedFeatureInventorySummarySchema.ts new file mode 100644 index 00000000000..dfcb0d03f94 --- /dev/null +++ b/src/domain/analysisView/summarySchemas/managedFeatureInventorySummarySchema.ts @@ -0,0 +1,8 @@ +import { producerSummarySchema } from "../analysisViewBase.js"; +import { managedFeatureInventorySummarySchema } from "../managedFeatureInventoryView.js"; + +export const managedFeatureInventorySummaryViewResultSchema = + producerSummarySchema( + "inventory_managed_features", + managedFeatureInventorySummarySchema, + ); diff --git a/src/domain/managed/managedDecodeBudget.test.ts b/src/domain/managed/managedDecodeBudget.test.ts index 944f6a588ef..e5b8f6c847b 100644 --- a/src/domain/managed/managedDecodeBudget.test.ts +++ b/src/domain/managed/managedDecodeBudget.test.ts @@ -73,6 +73,31 @@ describe("managed decoding bounds", () => { budget.releaseTransient(); expect(() => budget.admitTransient(bound, null)).not.toThrow(); }); + + it("keeps an outer transient charge live across a nested transient scope", () => { + const budget = new ManagedDecodeBudget(1000); + + budget.admitTransient(600, null); + budget.withTransientScope(() => { + budget.admitTransient(300, null); + // Outer (600) + inner (300) leaves only 100 bytes. + expect(() => budget.admitTransient(200, null)).toThrow( + ManagedReaderFailure, + ); + budget.reserve(100, null); + }); + + // Inner transient (300) was refunded, but outer (600) and retained (100) stay charged. + expect(() => budget.admitTransient(400, null)).toThrow( + ManagedReaderFailure, + ); + expect(() => budget.admitTransient(300, null)).not.toThrow(); + + budget.releaseTransient(); + // Only the 100 retained bytes remain charged. + expect(() => budget.reserve(900, null)).not.toThrow(); + expect(() => budget.reserve(1, null)).toThrow(ManagedReaderFailure); + }); }); // Callers admit these allowances through their input schemas, so a value diff --git a/src/domain/managed/managedDecodeBudget.ts b/src/domain/managed/managedDecodeBudget.ts index 9f371860faf..2d31a59e933 100644 --- a/src/domain/managed/managedDecodeBudget.ts +++ b/src/domain/managed/managedDecodeBudget.ts @@ -73,6 +73,21 @@ export class ManagedDecodeBudget { this.#transient = 0; } + /** + * Run a nested transient decode in its own refund scope so releasing it does + * not refund transient allocations still live in the caller. + */ + withTransientScope(run: () => Value): Value { + const outer = this.#transient; + this.#transient = 0; + try { + return run(); + } finally { + this.releaseTransient(); + this.#transient = outer; + } + } + /** UTF-8 cannot decode to more UTF-16 units than bytes; JSON uses at most six bytes per unit. */ reserveString(encodedBytes: number, offset: number | null): void { this.reserve(encodedBytes * 6 + 2, offset); diff --git a/src/domain/managed/managedFeatureInventory.ts b/src/domain/managed/managedFeatureInventory.ts new file mode 100644 index 00000000000..b1665ab1293 --- /dev/null +++ b/src/domain/managed/managedFeatureInventory.ts @@ -0,0 +1,128 @@ +import { z } from "zod"; + +import type { AnalysisParameterLimit } from "../analysisSettings.js"; +import { coverageStatusSchema } from "../coverage.js"; +import { digestSchema } from "../digests.js"; +import { absoluteLocalPathStringSchema } from "../localPath.js"; +import { managedInspectionBudgetShape } from "./managedInspectionLimits.js"; + +/** Format identity for typed feature inventory failures. */ +export const MANAGED_FEATURE_INVENTORY_FORMAT = "managed-feature-inventory"; + +/** Each per-call budget's schema bounds and omitted value. */ +export const MANAGED_FEATURE_INVENTORY_BUDGETS = { + max_entries: { minimum: 1, maximum: 1_048_576, default_value: 65_536 }, + max_text_bytes: { + minimum: 1, + maximum: 256 * 1024 * 1024, + default_value: 16 * 1024 * 1024, + }, +} as const; +export type ManagedFeatureInventoryBudget = + keyof typeof MANAGED_FEATURE_INVENTORY_BUDGETS; + +/** The per-call control that stopped the inventory, with the bounds the next call accepts. */ +export const managedFeatureInventoryBudgetLimit = ( + parameter: ManagedFeatureInventoryBudget, + effectiveValue: number, +): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter, + effective_value: effectiveValue, + unit: parameter === "max_entries" ? "count" : "bytes", + ...MANAGED_FEATURE_INVENTORY_BUDGETS[parameter], + applies_at: "next_call", +}); + +const budget = (name: ManagedFeatureInventoryBudget) => { + const bounds = MANAGED_FEATURE_INVENTORY_BUDGETS[name]; + return z + .int() + .min(bounds.minimum) + .max(bounds.maximum) + .default(bounds.default_value); +}; + +export const inventoryManagedFeaturesInputSchema = z.strictObject({ + path: absoluteLocalPathStringSchema.describe( + "Absolute filesystem path to a managed PE assembly", + ), + ...managedInspectionBudgetShape, + max_entries: budget("max_entries").describe( + "Maximum reported rows: enum members, enum argument sites and GUID literals together; exceeding it fails without partial success", + ), + max_text_bytes: budget("max_text_bytes").describe( + "Maximum reported name and literal text in bytes; exceeding it fails without partial success", + ), +}); +export type InventoryManagedFeaturesInput = z.infer< + typeof inventoryManagedFeaturesInputSchema +>; + +const count = z.int().nonnegative(); +const token = z.string().regex(/^0x[0-9a-f]{8}$/u); +/** An enum constant as decimal text; 64-bit values exceed a JSON number. */ +const value = z.string().regex(/^-?\d+$/u); + +const site = { + /** The method whose CIL holds the site, as `Namespace.Type.Method`. */ + method: z.string(), + method_token: token, + il_offset: count, +}; + +const enumSchema = z.strictObject({ + type: z.string(), + token, + /** The `value__` field's element type, such as `i4`; null when unreadable. */ + underlying_type: z.string().nullable(), + /** The name ends in Type, Kind, Mode or Category: an enum of kinds. */ + kind_name: z.boolean(), + members: z.array(z.strictObject({ name: z.string(), value })), + /** Sites in `enum_arguments` that pass one of this enum's values. */ + argument_sites: count, +}); + +const enumArgumentSchema = z.strictObject({ + /** The parameter's enum type, as the callee's signature names it. */ + enum: z.string(), + /** Whether the enum is defined in this assembly, so `member` can resolve. */ + defined_here: z.boolean(), + value, + /** The first member with this value, when the enum is defined here. */ + member: z.string().nullable(), + /** The called method, as `Type.Method`. */ + callee: z.string(), + /** Zero-based position among the callee's declared parameters. */ + parameter: count, + ...site, +}); + +const guidLiteralSchema = z.strictObject({ + /** Lower-case, without braces. */ + value: z.string().regex(/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/u), + ...site, +}); + +export const managedFeatureInventorySchema = z.strictObject({ + artifact: z.strictObject({ + path: z.string().min(1), + sha256: digestSchema, + bytes: count, + }), + enums: z.array(enumSchema), + enum_arguments: z.array(enumArgumentSchema), + guid_literals: z.array(guidLiteralSchema), + coverage: z.strictObject({ + status: coverageStatusSchema, + methods: count, + /** Methods whose CIL could not be decoded completely and were not searched in full. */ + undecoded_methods: count, + }), + limitations: z.array(z.string().min(1)), +}); +export type ManagedFeatureInventory = z.infer< + typeof managedFeatureInventorySchema +>; +export type ManagedFeatureEnum = z.infer; +export type ManagedEnumArgument = z.infer; diff --git a/src/domain/managed/managedMemberInspectorCore.ts b/src/domain/managed/managedMemberInspectorCore.ts index 0a743e6f45b..f923ae44b76 100644 --- a/src/domain/managed/managedMemberInspectorCore.ts +++ b/src/domain/managed/managedMemberInspectorCore.ts @@ -961,49 +961,52 @@ export const specSignatureFacts = ( readonly nominalGenericType: NominalGenericType | null; } => { const budget = managedDecodeBudget(layout); - // Rendering is transient, so charge it as member signatures are charged. - budget.admitTransient(blob.length * 256, owner.offset); - try { - let cursor = 0; - let count = 1; - if (owner.form === "instantiation") { - if (blob[0] !== 0x0a) - malformedSignature("MethodSpec instantiation is not GENERICINST", 0); - const header = readCompressed(blob, 1); - if (header.value === 0) - malformedSignature("MethodSpec instantiation has no type arguments", 1); - count = header.value; - cursor = header.next; + return budget.withTransientScope(() => { + // Rendering is transient, so charge it as member signatures are charged. + budget.admitTransient(blob.length * 256, owner.offset); + try { + let cursor = 0; + let count = 1; + if (owner.form === "instantiation") { + if (blob[0] !== 0x0a) + malformedSignature("MethodSpec instantiation is not GENERICINST", 0); + const header = readCompressed(blob, 1); + if (header.value === 0) + malformedSignature( + "MethodSpec instantiation has no type arguments", + 1, + ); + count = header.value; + cursor = header.next; + } + const types: string[] = []; + const operands: TypeOperand[] = []; + let nominalGenericType: NominalGenericType | null = null; + // Each Type consumes at least one byte, so a false count fails on truncation. + for (let index = 0; index < count; index += 1) { + const type = readTypeSignature(blob, cursor, "type", { + layout, + operands, + }); + types.push(type.value); + if (owner.form === "type") nominalGenericType = type.nominalGenericType; + cursor = type.next; + } + if (cursor !== blob.length) + malformedSignature("Trailing signature data", cursor); + return { + types, + resolvedSha256: + typeName === undefined + ? null + : resolvedSha256(blob, operands, typeName), + nominalGenericType, + }; + } catch (cause: unknown) { + const issue = signatureDecodeIssue(cause); + throw managedFailure(issue.code, owner.scope, issue.detail, owner.offset); } - const types: string[] = []; - const operands: TypeOperand[] = []; - let nominalGenericType: NominalGenericType | null = null; - // Each Type consumes at least one byte, so a false count fails on truncation. - for (let index = 0; index < count; index += 1) { - const type = readTypeSignature(blob, cursor, "type", { - layout, - operands, - }); - types.push(type.value); - if (owner.form === "type") nominalGenericType = type.nominalGenericType; - cursor = type.next; - } - if (cursor !== blob.length) - malformedSignature("Trailing signature data", cursor); - return { - types, - resolvedSha256: - typeName === undefined - ? null - : resolvedSha256(blob, operands, typeName), - nominalGenericType, - }; - } catch (cause: unknown) { - const issue = signatureDecodeIssue(cause); - throw managedFailure(issue.code, owner.scope, issue.detail, owner.offset); - } finally { - budget.releaseTransient(); - } + }); }; type DecodedSignature = Omit< @@ -1103,6 +1106,63 @@ const decodeSignature = ( } }; +/** A value-type parameter's TypeDef or TypeRef operand. */ +export type ValueTypeParameter = Pick; + +/** + * Each parameter of a method signature: its type operand when the parameter + * is exactly a value type, custom modifiers aside, otherwise null. Returns + * the parse issue when the blob is not a complete decodable method signature. + */ +export const methodValueTypeParameters = ( + blob: Buffer, + layout: ManagedMetadataLayout, +): Result => { + try { + const header = readMethodSignatureHeader(blob, 0, "member"); + let offset = readTypeSignature(blob, header.next, "return", { + layout, + }).next; + const parameters: (ValueTypeParameter | null)[] = []; + let sentinelSeen = false; + for (let index = 0; index < header.parameterCount; index += 1) { + // A VARARG sentinel separates the fixed parameters from the rest. + if (blob[offset] === 0x41 && (header.first & 0x0f) === 5) { + if (sentinelSeen) + malformedSignature( + "VARARG signature has an invalid sentinel position", + offset, + ); + sentinelSeen = true; + offset += 1; + if (blob[offset] === undefined || blob[offset] === 0x41) + malformedSignature("VARARG signature has adjacent sentinels", offset); + } + const operands: TypeOperand[] = []; + const kinds: number[] = []; + const parameter = readTypeSignature(blob, offset, "parameter", { + layout, + operands, + onElement: (kind) => kinds.push(kind), + }); + // Custom modifiers precede the type, so its operand is the last one. + const type = kinds.filter((kind) => kind !== 0x1f && kind !== 0x20); + const operand = operands.at(-1); + parameters.push( + type.length === 1 && type[0] === 0x11 && operand !== undefined + ? { value: operand.value, coordinate: operand.coordinate } + : null, + ); + offset = parameter.next; + } + if (offset !== blob.length) + malformedSignature("Trailing signature data", offset); + return ok(parameters); + } catch (cause: unknown) { + return err(signatureDecodeIssue(cause)); + } +}; + /** * Generic parameter count of a method signature that decodes completely, 0 * when it is not generic, or null when the blob is not a decodable method @@ -1113,12 +1173,10 @@ export const methodGenericArity = ( blob: Buffer, ): number | null => { const budget = managedDecodeBudget(layout); - budget.admitTransient(blob.length * 256, metadataBlobOffset(layout)); - try { + return budget.withTransientScope(() => { + budget.admitTransient(blob.length * 256, metadataBlobOffset(layout)); return signatureGenericArity(decodeSignature(blob)); - } finally { - budget.releaseTransient(); - } + }); }; /** diff --git a/src/dotnet/ManagedMethodBodyReader.ts b/src/dotnet/ManagedMethodBodyReader.ts index bb21589eeef..b818874d78b 100644 --- a/src/dotnet/ManagedMethodBodyReader.ts +++ b/src/dotnet/ManagedMethodBodyReader.ts @@ -12,6 +12,7 @@ import { import type { ManagedPeLayout } from "../domain/managed/managedPeReader.js"; import type { ManagedMethodBody, + ParsedInstruction, ParsedTokenInstruction, } from "../domain/managed/managedMemberInspectorCore.js"; import { @@ -104,6 +105,50 @@ const readMethodBodyHeader = (reader: BinaryReader): MethodBodyHeader => { }; }; +/** + * A method's decoded CIL, for scans that keep only what they report. Records + * are admitted as transient against the budget, not retained. + */ +export const methodInstructions = ( + bytes: Buffer, + pe: ManagedPeLayout, + rva: number, + implementation: ManagedMethodImplementationFlags, + budget: ManagedDecodeBudget, +): { + readonly instructions: readonly ParsedInstruction[]; + /** The IL bytes, for operands the records summarise, such as switch tables. */ + readonly il: Buffer; + /** Whether every instruction decoded; a method without CIL has none left. */ + readonly scanned: boolean; +} => { + const none = { instructions: [], il: Buffer.alloc(0), scanned: true }; + if ( + rva === 0 || + implementation.codeType !== "il" || + implementation.managedKind !== "managed" || + implementation.pinvokeFlag || + implementation.internalCall + ) + return none; + const { offset, available } = pe.rvaFileRange(rva, "method.body"); + const methodBytes = bytes.subarray(offset, offset + available); + const header = readMethodBodyHeader( + new BinaryReader(methodBytes, true, "cil-method-body"), + ); + requireMethodBodyBytes(available, header.size + header.ilSize); + const il = methodBytes.subarray(header.size, header.size + header.ilSize); + const ilOffset = offset + header.size; + const decoded = decodeInstructions(il, (start) => + budget.admitTransient(256, ilOffset + start), + ); + return { + instructions: decoded.parsed, + il, + scanned: decoded.issue === null && decoded.truncated === 0, + }; +}; + export interface MethodBodyContext { readonly implementation: ManagedMethodImplementationFlags; readonly budget: ManagedDecodeBudget; diff --git a/src/dotnet/features/ManagedFeatureInventory.test.ts b/src/dotnet/features/ManagedFeatureInventory.test.ts new file mode 100644 index 00000000000..bcba364f516 --- /dev/null +++ b/src/dotnet/features/ManagedFeatureInventory.test.ts @@ -0,0 +1,206 @@ +import { expect, it } from "vitest"; +import { ParseFailureError } from "../../domain/parseFailure.js"; +import { buildNativePeFixture } from "../ManagedPe.fixture.js"; +import { + FIXTURE_GUID, + featureAssembly, +} from "../../../tests/fixtures/featureAssembly.js"; +import { inventoryManagedFeatures } from "./ManagedFeatureInventory.js"; + +const inventory = ( + bytes: Buffer, + maxEntries = 1024, + maxTextBytes = 1 << 20, + maxMetadataRepresentationBytes?: number, +) => + inventoryManagedFeatures( + bytes, + { path: "/x/Demo.dll", sha256: "0".repeat(64), bytes: bytes.length }, + { + max_entries: maxEntries, + max_text_bytes: maxTextBytes, + max_metadata_representation_bytes: maxMetadataRepresentationBytes, + }, + ); + +const site = { method: "Demo.Program.Main", method_token: "0x06000002" }; + +it("lists enums, constant enum arguments and GUID literals with their CIL sites", () => { + const result = inventory(featureAssembly()); + expect(result.enums).toEqual([ + { + type: "Demo.Mode", + token: "0x02000001", + underlying_type: expect.any(String), + kind_name: true, + members: [ + { name: "Simple", value: "0" }, + { name: "Advanced", value: "5" }, + ], + argument_sites: 2, + }, + ]); + expect(result.enum_arguments).toEqual([ + { + enum: "Demo.Mode", + defined_here: true, + value: "5", + member: "Advanced", + callee: "Demo.Program.Use", + parameter: 0, + ...site, + il_offset: 0, + }, + { + enum: "External.Shade", + defined_here: false, + value: "2", + member: null, + callee: "External.Painter.Paint", + parameter: 0, + ...site, + il_offset: 6, + }, + { + enum: "Demo.Mode", + defined_here: true, + value: "0", + member: "Simple", + callee: "External.Painter.Paint", + parameter: 1, + ...site, + il_offset: 7, + }, + ]); + expect(result.guid_literals).toEqual([ + { value: "44eca225-98f6-489c-b97a-03163e83ce7e", ...site, il_offset: 13 }, + ]); + expect(result.coverage).toEqual({ + status: "complete", + methods: 2, + undecoded_methods: 0, + }); +}); + +it("refuses an inventory above max_entries or max_text_bytes by name", () => { + for (const [entries, text, name] of [ + [3, 1 << 20, "max_entries"], + [1024, 16, "max_text_bytes"], + ] as const) { + const thrown = (() => { + try { + inventory(featureAssembly(), entries, text); + } catch (cause) { + return cause; + } + return undefined; + })(); + expect(thrown).toBeInstanceOf(ParseFailureError); + expect((thrown as ParseFailureError).failure).toMatchObject({ + kind: "limit", + limit: { name }, + }); + } +}); + +it("refuses a file without a CLI header", () => { + expect(() => inventory(buildNativePeFixture())).toThrow(ParseFailureError); +}); + +it("names an unsigned enum's member from the bit pattern its constant pushes", () => { + const result = inventory(featureAssembly({ unsigned: true })); + expect(result.enums[0]).toMatchObject({ + underlying_type: "u4", + members: [ + { name: "Simple", value: "0" }, + { name: "Advanced", value: "4294967295" }, + ], + }); + expect(result.enum_arguments[0]).toMatchObject({ + value: "4294967295", + member: "Advanced", + }); +}); + +it("reads a modified enum parameter's type from the signature, not its rendering", () => { + const result = inventory(featureAssembly({ modifier: true })); + expect(result.enum_arguments[0]).toMatchObject({ + enum: "Demo.Mode", + member: "Advanced", + callee: "Demo.Program.Use", + }); +}); + +it("counts a malformed method body and keeps the rest of the inventory", () => { + const result = inventory(featureAssembly({ brokenUse: true })); + expect(result.coverage).toEqual({ + status: "partial", + methods: 2, + undecoded_methods: 1, + }); + expect(result.enums).toHaveLength(1); + expect(result.enum_arguments).toHaveLength(3); +}); + +it("keeps a literal's metadata issue in coverage", () => { + const bytes = featureAssembly(); + // Clear the GUID literal's required terminal flag. + const text = Buffer.from(FIXTURE_GUID, "utf16le"); + const at = bytes.indexOf(text) + text.length; + expect(bytes[at]).toBe(1); + bytes[at] = 0; + const result = inventory(bytes); + expect(result.guid_literals).toHaveLength(1); + expect(result.coverage.status).toBe("partial"); +}); + +it("names a nested enum the same way in its definition and at its call sites", () => { + const result = inventory(featureAssembly({ nested: true })); + const name = result.enums[0]?.type; + expect(name).toBe("Demo.Program/Mode"); + expect(result.enum_arguments[0]).toMatchObject({ + enum: name, + member: "Advanced", + }); +}); + +it("marks coverage partial when a callee signature references a missing TypeDef", () => { + const result = inventory(featureAssembly({ brokenUseSignature: true })); + expect(result.coverage).toEqual({ + status: "partial", + methods: 2, + undecoded_methods: 0, + }); + expect(result.enum_arguments.map((site) => site.callee)).toEqual([ + "External.Painter.Paint", + "External.Painter.Paint", + ]); + expect( + result.limitations.some((line) => line.includes("metadata issue")), + ).toBe(true); +}); + +it("charges retained callee parameter caches against max_metadata_representation_bytes", () => { + // 80 distinct callees x 50 i4 parameters = 4000 cached slots (64 KiB retained) + // while each individual signature is small (~13 KiB transient) and emits no extra rows. + const wide = featureAssembly({ wideCallees: { count: 80, params: 50 } }); + const narrow = featureAssembly({ wideCallees: { count: 80, params: 1 } }); + // A budget that fits the narrow callees must reject the wide parameter cache. + const budget = 95_000; + expect(inventory(narrow, 1024, 1 << 20, budget).coverage.status).toBe( + "complete", + ); + const thrown = (() => { + try { + inventory(wide, 1024, 1 << 20, budget); + } catch (cause) { + return cause; + } + return undefined; + })(); + expect(thrown).toBeInstanceOf(ParseFailureError); + expect((thrown as ParseFailureError).failure).toMatchObject({ + kind: "limit", + limit: { name: "max_metadata_representation_bytes" }, + }); +}); diff --git a/src/dotnet/features/ManagedFeatureInventory.ts b/src/dotnet/features/ManagedFeatureInventory.ts new file mode 100644 index 00000000000..7d7d89b2df9 --- /dev/null +++ b/src/dotnet/features/ManagedFeatureInventory.ts @@ -0,0 +1,623 @@ +import { BinaryReader } from "../../domain/binaryContainer.js"; +import { CoverageAccumulator } from "../../domain/coverageAccumulator.js"; +import { jsonStringByteLength } from "../../domain/jsonStringByteLength.js"; +import { + managedDecodeBudget, + ManagedRepresentationFailure, +} from "../../domain/managed/managedDecodeBudget.js"; +import { + MANAGED_FEATURE_INVENTORY_FORMAT, + type InventoryManagedFeaturesInput, + type ManagedEnumArgument, + type ManagedFeatureEnum, + type ManagedFeatureInventory, +} from "../../domain/managed/managedFeatureInventory.js"; +import { DEFAULT_MANAGED_REPRESENTATION_BYTES } from "../../domain/managed/managedInspectionLimits.js"; +import { + methodValueTypeParameters, + parseTypes, + readTypeDefinitions, + type ParsedInstruction, +} from "../../domain/managed/managedMemberInspectorCore.js"; +import { memberDeclaringTypeRowLookup } from "../../domain/managed/managedMemberOwnership.js"; +import { readMemberReferenceRowFacts } from "../../domain/managed/managedMemberReferenceRows.js"; +import { + decodeMetadataCodedIndex, + type MetadataTokenFact, + metadataRowCursor, + metadataToken, + readMetadataBlob, + readMetadataString, + readMetadataUserString, +} from "../../domain/managed/managedMetadataHeaps.js"; +import { + MANAGED_CODED_INDEXES, + readManagedMetadataLayout, +} from "../../domain/managed/managedMetadataLayout.js"; +import { readManagedPeLayout } from "../../domain/managed/managedPeReader.js"; +import { + appendManagedParseIssues, + ManagedReaderFailure, + managedIssueTargetFailure, +} from "../../domain/managed/managedReaderFailure.js"; +import { managedSignatureTypeNames } from "../../domain/managed/managedSignatureTypeNames.js"; +import { managedTypeReferences } from "../../domain/managed/managedTypeReferences.js"; +import { readTypeMemberListFacts } from "../../domain/managed/managedTypeMemberLists.js"; +import type { ManagedParseIssue } from "../../domain/managed/managedArtifact.js"; +import { + decodeLimit, + malformedInput, + ParseFailureError, + unsupportedInput, +} from "../../domain/parseFailure.js"; +import { methodInstructions } from "../ManagedMethodBodyReader.js"; +import { + readMethodDefinitionName, + readMethodDefinitionRow, +} from "../ManagedMethodDefinitionRows.js"; +import { parseFields } from "../ManagedMemberRows.js"; +import { typeNameLookup } from "../ManagedTypeNames.js"; + +/** ECMA-335 tables this reader resolves. */ +const TYPE_REF_TABLE = 0x01; +const TYPE_DEF_TABLE = 0x02; +const METHOD_DEF_TABLE = 0x06; +const MEMBER_REF_TABLE = 0x0a; +const METHOD_SPEC_TABLE = 0x2b; +const USER_STRING_TABLE = 0x70; +/** FieldAttributes.Static: an enum's members; `value__` is the instance field. */ +const STATIC_FIELD = 0x0010; +/** Names that announce an enum of kinds. */ +const KIND_NAME = /(?:Type|Kind|Mode|Category)$/u; +const GUID_TEXT = + "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"; +const GUID = new RegExp(`^(?:\\{(${GUID_TEXT})\\}|(${GUID_TEXT}))$`, "iu"); +/** Bits an unsigned underlying type keeps of a pushed constant. */ +const UNSIGNED_BITS = new Map([ + ["u1", 8], + ["u2", 16], + ["u4", 32], + ["u8", 64], +]); +/** Accounted bytes of one retained row beside its text. */ +const ROW_BYTES = 128; +/** Accounted bytes of one cached non-value-type parameter slot in `callees`. */ +const PARAMETER_SLOT_BYTES = 16; +/** Accounted bytes of one cached value-type parameter entry beside its name. */ +const PARAMETER_OBJECT_BYTES = 64; +const CALLS = new Set(["call", "callvirt", "newobj"]); +/** Instructions that push one value and pop none. */ +const SINGLE_PUSH = + /^(?:ld(?:arg|arga|loc|loca)(?:\.[0-3s])?|ldnull|ldstr|ldsfld|ldsflda|ldtoken|ldftn|ldc\..+)$/u; + +type CalleeParameter = { + readonly name: string; + /** TypeDef row when the type is defined here, else null. */ + readonly definition: number | null; +} | null; + +interface Callee { + readonly name: string; + readonly parameters: readonly CalleeParameter[]; +} + +/** The constant an `ldc` pushes, as decimal text; null for other instructions. */ +const constantOf = ({ opcode, operand }: ParsedInstruction): string | null => { + const implicit = /^ldc\.i4\.(m1|[0-8])$/u.exec(opcode); + if (implicit !== null) return implicit[1] === "m1" ? "-1" : implicit[1]!; + if ( + (opcode === "ldc.i4.s" || opcode === "ldc.i4" || opcode === "ldc.i8") && + operand !== null + ) + return operand; + return null; +}; + +/** Absolute targets of every branch and switch, so joins stop argument matching. */ +const branchTargets = ( + instructions: readonly ParsedInstruction[], + il: Buffer, +): ReadonlySet => { + const targets = new Set(); + const reader = new BinaryReader(il, true, "cil"); + for (const instruction of instructions) { + if (instruction.operandKind === "branch" && instruction.operand !== null) + targets.add(Number(instruction.operand)); + else if (instruction.operandKind === "switch") { + // switch N, then N 32-bit targets relative to the next instruction. + const count = reader.u32(instruction.offset + 1); + const next = instruction.offset + 5 + count * 4; + for (let index = 0; index < count; index += 1) + targets.add(next + reader.i32(instruction.offset + 5 + index * 4)); + } + } + return targets; +}; + +/** A constant pushed for one of a call's parameters. */ +interface PushedConstant { + readonly parameter: number; + readonly value: string; + readonly offset: number; +} + +/** The fields `recordArguments` derives for each site. */ +type EnumArgumentFacts = Pick< + ManagedEnumArgument, + "enum" | "defined_here" | "value" | "member" | "callee" | "parameter" +>; + +/** + * The constants pushed for a call's parameters, in IL order. Walking back from + * the call, each instruction that pushes one value and pops none supplies the + * next parameter from the end; a branch target, where the stack is a join, or + * any other instruction stops the walk. + */ +const pushedConstants = ( + instructions: readonly ParsedInstruction[], + call: number, + targets: ReadonlySet, + parameterCount: number, +): PushedConstant[] => { + const pushed: PushedConstant[] = []; + let previous = call - 1; + for ( + let parameter = parameterCount - 1; + parameter >= 0 && previous >= 0; + parameter -= 1, previous -= 1 + ) { + if (targets.has(instructions[previous + 1]!.offset)) break; + const pusher = instructions[previous]!; + if (!SINGLE_PUSH.test(pusher.opcode)) break; + const value = constantOf(pusher); + if (value !== null) + pushed.push({ parameter, value, offset: pusher.offset }); + } + return pushed.reverse(); +}; + +const recover = ( + bytes: Buffer, + artifact: ManagedFeatureInventory["artifact"], + input: Pick< + InventoryManagedFeaturesInput, + "max_entries" | "max_text_bytes" | "max_metadata_representation_bytes" + >, +): ManagedFeatureInventory => { + const pe = readManagedPeLayout(bytes); + if (pe.cli === null) + throw unsupportedInput( + MANAGED_FEATURE_INVENTORY_FORMAT, + "The file is not a managed assembly with a CLI header", + { field: "cli-header" }, + ); + const layout = readManagedMetadataLayout( + bytes, + pe.rvaToOffset(pe.cli.metadata.rva, pe.cli.metadata.size, "cli.metadata"), + pe.cli.metadata.size, + input.max_metadata_representation_bytes, + ); + const budget = managedDecodeBudget(layout); + const issues: ManagedParseIssue[] = []; + const memberLists = readTypeMemberListFacts(bytes, layout); + const ranges = readTypeDefinitions(bytes, layout, issues, memberLists); + const parsedTypes = parseTypes(bytes, layout, ranges); + const references = managedTypeReferences(bytes, layout, issues); + appendManagedParseIssues(issues, parsedTypes.issues); + const { operand: signatureTypeName, displayName: displayTypeName } = + managedSignatureTypeNames(layout, issues, parsedTypes, references); + /** One spelling, nesting included, for definitions and signature operands. */ + const nameOf = (table: number, row: number): string | null => + table === TYPE_DEF_TABLE || table === TYPE_REF_TABLE + ? displayTypeName({ + value: (row << 2) | (table === TYPE_REF_TABLE ? 1 : 0), + coordinate: { table, row }, + }) + : typeName({ table, row, token: metadataToken(table, row) }); + const { name: typeName } = typeNameLookup( + bytes, + layout, + ranges, + issues, + references, + signatureTypeName, + ); + + let entries = 0; + let textBytes = 0; + /** Charge one retained row, or a type's header when `rows` is 0, before it is kept. */ + const report = (rows: number, ...texts: readonly string[]): void => { + entries += rows; + if (entries > input.max_entries) + throw decodeLimit( + MANAGED_FEATURE_INVENTORY_FORMAT, + `The inventory has more than max_entries=${String(input.max_entries)} rows`, + { name: "max_entries", maximum: input.max_entries }, + ); + let rowText = 0; + for (const text of texts) rowText += jsonStringByteLength(text); + textBytes += rowText; + if (textBytes > input.max_text_bytes) + throw decodeLimit( + MANAGED_FEATURE_INVENTORY_FORMAT, + `The inventory's names and literals exceed max_text_bytes=${String(input.max_text_bytes)}`, + { name: "max_text_bytes", maximum: input.max_text_bytes }, + ); + budget.reserve(ROW_BYTES + rowText, null); + }; + + // Enums: TypeDefs that extend System.Enum, with their constant members. + const typeNames = new Map(); + const enumRows = new Map(); + const enumTokens = new Set(); + for (const { row, type } of parsedTypes.types) { + typeNames.set(row, nameOf(TYPE_DEF_TABLE, row) ?? type.full_name); + const base = type.extends_token; + if ( + base === null || + Number.parseInt(base.slice(2, 4), 16) !== TYPE_REF_TABLE + ) + continue; + const reference = references(Number.parseInt(base.slice(4), 16)); + if (reference?.namespace !== "System" || reference.name !== "Enum") + continue; + enumTokens.add(type.token); + } + const fields = parseFields(bytes, layout, ranges, memberLists, { + signatureTypeName, + displayTypeName, + declarationTypeName: () => null, + selected: enumTokens, + }); + appendManagedParseIssues(issues, fields.issues); + const membersByType = new Map< + string, + ManagedFeatureEnum["members"][number][] + >(); + const underlying = new Map(); + for (const field of fields.fields) { + const owner = field.declaring_type_token; + if (owner === null) continue; + if ((field.flags & STATIC_FIELD) === 0) { + underlying.set(owner, field.signature.field_type); + continue; + } + if (field.constant?.state !== "decoded") continue; + const { value } = field.constant; + if (typeof value !== "number" && typeof value !== "string") continue; + const list = membersByType.get(owner) ?? []; + list.push({ name: field.name, value: String(value) }); + membersByType.set(owner, list); + } + const memberNames = new Map>(); + for (const { row, type } of parsedTypes.types) { + if (!enumTokens.has(type.token)) continue; + const members = membersByType.get(type.token) ?? []; + const name = typeNames.get(row) ?? type.full_name; + report(0, name); + const byValue = new Map(); + for (const member of members) { + report(1, member.name, member.value); + if (!byValue.has(member.value)) byValue.set(member.value, member.name); + } + memberNames.set(row, byValue); + enumRows.set(row, { + type: name, + token: type.token, + underlying_type: underlying.get(type.token) ?? null, + kind_name: KIND_NAME.test(type.name), + members, + argument_sites: 0, + }); + } + + // Callees: their names and which parameters take a value type. + const callees = new Map(); + const methodName = ( + row: number, + definition: ReturnType, + ): string => + `${typeNames.get(methodOwner(row)) ?? "(no declaring type)"}.${readMethodDefinitionName(bytes, layout, definition)}`; + const methodOwner = memberDeclaringTypeRowLookup( + bytes, + layout, + 6, + memberLists, + ); + const parametersOf = (blob: Buffer, scope: string): CalleeParameter[] => + budget.withTransientScope(() => { + budget.admitTransient(blob.length * 256, null); + const parsed = methodValueTypeParameters(blob, layout); + if (!parsed.ok) { + budget.reserve(ROW_BYTES, parsed.error.offset); + issues.push({ ...parsed.error, scope }); + return []; + } + const parameters: CalleeParameter[] = []; + for (const parameter of parsed.value) { + const table = parameter?.coordinate.table; + if (parameter === null || table === undefined) { + budget.reserve(PARAMETER_SLOT_BYTES, null); + parameters.push(null); + continue; + } + const { row } = parameter.coordinate; + const name = + nameOf(table, row) ?? `valuetype:${String(parameter.value)}`; + budget.reserve( + PARAMETER_OBJECT_BYTES + jsonStringByteLength(name), + null, + ); + parameters.push({ + name, + definition: table === TYPE_DEF_TABLE ? row : null, + }); + } + return parameters; + }); + const calleeOf = (table: number, row: number): Callee | null => { + const token = metadataToken(table, row); + const cached = callees.get(token); + if (cached !== undefined) return cached; + let callee: Callee | null = null; + if (table === METHOD_DEF_TABLE) { + const definition = readMethodDefinitionRow(bytes, layout, row); + const signature = readMetadataBlob( + bytes, + layout, + definition.signatureIndex, + ); + const name = methodName(row, definition); + const parameters = parametersOf( + signature, + `metadata.MethodDef:${token}.Signature`, + ); + budget.reserve(ROW_BYTES + jsonStringByteLength(name), null); + callee = { name, parameters }; + } else if (table === MEMBER_REF_TABLE) { + const member = readMemberReferenceRowFacts(bytes, layout, row); + const memberName = readMetadataString(bytes, layout, member.nameIndex); + const signature = readMetadataBlob(bytes, layout, member.signatureIndex); + const parent = + member.parent.kind === "valid" + ? nameOf(member.parent.table, member.parent.row) + : null; + if (member.parent.kind !== "valid") { + budget.reserve(ROW_BYTES, member.rowOffset); + issues.push({ + code: "invalid-row", + scope: `metadata.MemberRef:${token}.Class`, + detail: `MemberRef ${token} has an invalid parent reference`, + offset: member.rowOffset, + }); + } + const name = `${parent ?? "(unresolved type)"}.${memberName}`; + const parameters = parametersOf( + signature, + `metadata.MemberRef:${token}.Signature`, + ); + budget.reserve(ROW_BYTES + jsonStringByteLength(name), null); + callee = { name, parameters }; + } else if (table === METHOD_SPEC_TABLE) { + // A generic method instantiation calls its MethodDef or MemberRef. + const cursor = metadataRowCursor(bytes, layout, METHOD_SPEC_TABLE, row); + const method = decodeMetadataCodedIndex( + cursor.readIndex(layout.codedIndexSize("MethodDefOrRef")), + MANAGED_CODED_INDEXES.MethodDefOrRef.bits, + MANAGED_CODED_INDEXES.MethodDefOrRef.tables, + layout.rowCounts, + ); + if (method.kind === "valid" && method.table !== METHOD_SPEC_TABLE) + callee = calleeOf(method.table, method.row); + else { + budget.reserve(ROW_BYTES, cursor.start); + issues.push({ + code: "invalid-row", + scope: `metadata.MethodSpec:${token}.Method`, + detail: `MethodSpec ${token} references an invalid MethodDefOrRef target`, + offset: cursor.start, + }); + } + budget.reserve(ROW_BYTES, null); + } else { + budget.reserve(ROW_BYTES, null); + } + callees.set(token, callee); + return callee; + }; + + const enumArguments: ManagedEnumArgument[] = []; + /** Each #US literal's GUID form, or null, decided once. */ + const guids = new Map(); + const guidLiterals: ManagedFeatureInventory["guid_literals"] = []; + const guidOf = (reference: MetadataTokenFact): string | null => { + const known = guids.get(reference.row); + if (known !== undefined) return known; + const literal = readMetadataUserString(bytes, layout, reference); + appendManagedParseIssues(issues, literal.issues); + const guid = GUID.exec(literal.value); + const value = guid === null ? null : (guid[1] ?? guid[2]!).toLowerCase(); + budget.reserve( + 64 + (value === null ? 0 : jsonStringByteLength(value)), + null, + ); + guids.set(reference.row, value); + return value; + }; + /** Record each constant a call passes for an enum parameter, in IL order. */ + const recordArguments = ( + callee: Callee, + pushed: readonly PushedConstant[], + site: Omit, + ): void => { + for (const { parameter, value: raw, offset } of pushed) { + const type = callee.parameters[parameter]; + if (type === null || type === undefined) continue; + const local = + type.definition === null ? undefined : enumRows.get(type.definition); + // An unsigned enum's constant is pushed as its signed bit pattern. + const bits = UNSIGNED_BITS.get(local?.underlying_type ?? ""); + const value = + bits === undefined ? raw : BigInt.asUintN(bits, BigInt(raw)).toString(); + const member = + type.definition === null + ? null + : (memberNames.get(type.definition)?.get(value) ?? null); + report( + 1, + type.name, + value, + site.method, + callee.name, + ...(member === null ? [] : [member]), + ); + if (local !== undefined) + enumRows.set(type.definition!, { + ...local, + argument_sites: local.argument_sites + 1, + }); + enumArguments.push({ + enum: type.name, + defined_here: local !== undefined, + value, + member, + callee: callee.name, + parameter, + ...site, + il_offset: offset, + }); + } + }; + const scanMethod = ( + definition: ReturnType, + method: string, + ): boolean => { + const { instructions, il, scanned } = methodInstructions( + bytes, + pe, + definition.rva, + definition.implementation, + budget, + ); + const targets = branchTargets(instructions, il); + const site = { method, method_token: definition.token }; + for (const [ + index, + { opcode, reference, offset }, + ] of instructions.entries()) { + if (reference === null) continue; + if (opcode === "ldstr" && reference.table === USER_STRING_TABLE) { + const value = guidOf(reference); + if (value === null) continue; + report(1, value, method); + guidLiterals.push({ value, ...site, il_offset: offset }); + } else if (CALLS.has(opcode)) { + const callee = calleeOf(reference.table, reference.row); + if (callee?.parameters.some((type) => type !== null) === true) + recordArguments( + callee, + pushedConstants( + instructions, + index, + targets, + callee.parameters.length, + ), + site, + ); + } + } + return scanned; + }; + + const methodRows = layout.table(METHOD_DEF_TABLE)?.rowCount ?? 0; + let undecoded = 0; + for (let row = 1; row <= methodRows; row += 1) { + const definition = readMethodDefinitionRow(bytes, layout, row); + budget.withTransientScope(() => { + try { + if (!scanMethod(definition, methodName(row, definition))) + undecoded += 1; + } catch (cause: unknown) { + // A budget stops the whole call; a malformed body is one omission. + const malformed = + (cause instanceof ManagedReaderFailure && + !(cause instanceof ManagedRepresentationFailure)) || + (cause instanceof ParseFailureError && + cause.failure.kind !== "limit"); + if (!malformed) throw cause; + undecoded += 1; + } + }); + } + + const coverage = new CoverageAccumulator().recordComplete(); + const limitations = [ + "Enum arguments are constants pushed directly before a call for a value-type parameter; values computed, loaded from fields or locals, or merged across branches are not attributed.", + "Enums referenced from other assemblies keep their names but not their member names; inventory the defining assembly to resolve them.", + "GUID literals are ldstr strings in GUID form; GUIDs built from integers or byte arrays are not reported.", + ]; + if (undecoded > 0) { + limitations.push( + `${String(undecoded)} method(s) could not be decoded completely and were not searched in full.`, + ); + coverage.recordOmission("undecoded methods"); + } + // readTypeDefinitions already carries the member-list issues. + if (issues.length > 0) { + limitations.push( + `${String(issues.length)} metadata issue(s) leave some names, signatures, members or literals uncertain.`, + ); + coverage.recordOmission("metadata issues"); + } + return { + artifact, + enums: [...enumRows.values()], + enum_arguments: enumArguments, + guid_literals: guidLiterals, + coverage: { + status: coverage.finalizeKnown(), + methods: methodRows, + undecoded_methods: undecoded, + }, + limitations, + }; +}; + +/** + * {@link recover}, with the managed reader's refusals as parse failures: a + * representation budget is a named limit, other issues malformed or + * unsupported input. + */ +export const inventoryManagedFeatures = ( + ...args: Parameters +): ManagedFeatureInventory => { + try { + return recover(...args); + } catch (cause: unknown) { + if (cause instanceof ManagedRepresentationFailure) + throw decodeLimit( + MANAGED_FEATURE_INVENTORY_FORMAT, + cause.message, + { + name: "max_metadata_representation_bytes", + maximum: + args[2].max_metadata_representation_bytes ?? + DEFAULT_MANAGED_REPRESENTATION_BYTES, + }, + { cause }, + ); + if (!(cause instanceof ManagedReaderFailure)) throw cause; + const failure = managedIssueTargetFailure(cause.issue); + const site = { + cause, + field: cause.issue.scope, + ...(cause.issue.offset === null ? {} : { offset: cause.issue.offset }), + }; + if (failure?.kind === "unsupported") + throw unsupportedInput(MANAGED_FEATURE_INVENTORY_FORMAT, cause.message, { + ...site, + undecodedContent: true, + }); + throw malformedInput(MANAGED_FEATURE_INVENTORY_FORMAT, cause.message, site); + } +}; diff --git a/src/dotnet/features/ManagedFeatureInventoryProvider.ts b/src/dotnet/features/ManagedFeatureInventoryProvider.ts new file mode 100644 index 00000000000..88a767c9cee --- /dev/null +++ b/src/dotnet/features/ManagedFeatureInventoryProvider.ts @@ -0,0 +1,154 @@ +import { MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY } from "./ManagedFeatureInventoryProviderIdentity.js"; +import { + artifactFilePrimaryFacts, + closeArtifactResources, + projectStableArtifactFailure, + selectedFileRequirement, + type StableArtifactSnapshot, + readStableArtifact, + ArtifactResourceScope, +} from "../../resources/index.js"; +import type { ManagedFeatureInventoryPort } from "../../ports/managed/ManagedFeatureInventoryPort.js"; +import type { ExecutionOptions } from "../../ports/AnalysisProvider.js"; +import type { AnalysisParameterLimit } from "../../domain/analysisSettings.js"; +import { + DEFAULT_MANAGED_REPRESENTATION_BYTES, + DEFAULT_MANAGED_SNAPSHOT_BYTES, + managedRepresentationLimit, +} from "../../domain/managed/managedInspectionLimits.js"; +import { + MANAGED_FEATURE_INVENTORY_FORMAT, + managedFeatureInventoryBudgetLimit, + type InventoryManagedFeaturesInput, +} from "../../domain/managed/managedFeatureInventory.js"; +import { decodeLimit } from "../../domain/parseFailure.js"; +import { err, ok } from "../../domain/result.js"; +import { + isParseLimit, + parseLimitConstraint, +} from "../../domain/parseFailureAnalysisError.js"; +import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js"; +import { offlineArtifactFailureDialect } from "../../providers/offlineArtifactFailure.js"; +import { inventoryManagedFeatures } from "./ManagedFeatureInventory.js"; + +const OPERATION = "inventory_managed_features"; + +/** The selected snapshot ceiling, as the managed tools report it. */ +const snapshotLimit = (effectiveValue: number): AnalysisParameterLimit => ({ + control_kind: "parameter", + parameter: "max_snapshot_bytes", + effective_value: effectiveValue, + unit: "bytes", + minimum: 1, + maximum: Number.MAX_SAFE_INTEGER, + default_value: DEFAULT_MANAGED_SNAPSHOT_BYTES, + applies_at: "next_call", +}); + +const failureFor = ( + cause: unknown, + input: InventoryManagedFeaturesInput, + snapshot?: StableArtifactSnapshot, +) => { + const facts = artifactFilePrimaryFacts(cause); + const snapshotBytes = + input.max_snapshot_bytes ?? DEFAULT_MANAGED_SNAPSHOT_BYTES; + return projectStableArtifactFailure( + cause, + classifyProviderFailure( + facts.cause, + offlineArtifactFailureDialect(facts, { + operation: OPERATION, + providerId: MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY.id, + path: input.path, + description: "managed assembly", + recognise: (failure) => { + if (!isParseLimit(failure, MANAGED_FEATURE_INVENTORY_FORMAT)) + return undefined; + const { name } = failure.failure.limit; + const limit = + name === "max_entries" || name === "max_text_bytes" + ? managedFeatureInventoryBudgetLimit(name, input[name]) + : name === "max_metadata_representation_bytes" + ? managedRepresentationLimit( + input.max_metadata_representation_bytes ?? + DEFAULT_MANAGED_REPRESENTATION_BYTES, + ) + : undefined; + if (limit === undefined) return undefined; + return parseLimitConstraint(OPERATION, "memory", failure, { + retryable: false, + limit, + }); + }, + fileSize: (failure) => + parseLimitConstraint( + OPERATION, + "file-size", + decodeLimit( + MANAGED_FEATURE_INVENTORY_FORMAT, + failure.message, + { name: "max_snapshot_bytes", maximum: snapshotBytes }, + { cause: failure }, + ), + { + retryable: false, + limit: { + ...snapshotLimit(snapshotBytes), + ...selectedFileRequirement(failure), + }, + }, + ), + }), + ), + input.path, + MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY.id, + OPERATION, + snapshot, + ); +}; + +/** Feature inventory over one bounded, identity-checked managed assembly. */ +export class ManagedFeatureInventoryProvider implements ManagedFeatureInventoryPort { + readonly identity = MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY; + readonly #resources = new ArtifactResourceScope(); + + close(): Promise { + return closeArtifactResources( + () => this.#resources.close(), + MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY, + OPERATION, + ); + } + + async inspect( + input: InventoryManagedFeaturesInput, + options?: ExecutionOptions, + ) { + let snapshot: StableArtifactSnapshot | undefined; + try { + snapshot = await this.#resources.run(() => + readStableArtifact( + input.path, + input.max_snapshot_bytes ?? DEFAULT_MANAGED_SNAPSHOT_BYTES, + options?.signal, + undefined, + this.#resources, + ), + ); + return ok( + inventoryManagedFeatures( + snapshot.bytes, + { + path: input.path, + sha256: snapshot.sha256, + bytes: snapshot.bytes.length, + }, + input, + ), + ); + } catch (cause) { + return err(failureFor(cause, input, snapshot)); + } + } +} diff --git a/src/dotnet/features/ManagedFeatureInventoryProviderIdentity.ts b/src/dotnet/features/ManagedFeatureInventoryProviderIdentity.ts new file mode 100644 index 00000000000..a129ae61b62 --- /dev/null +++ b/src/dotnet/features/ManagedFeatureInventoryProviderIdentity.ts @@ -0,0 +1,6 @@ +/** Bundled reader identity; the inventory comes from the assembly's own metadata and CIL. */ +export const MANAGED_FEATURE_INVENTORY_PROVIDER_IDENTITY = { + id: "rea-managed-feature-inventory", + name: "REA managed feature inventory", + version: "1", +} as const; diff --git a/src/ports/managed/ManagedFeatureInventoryPort.ts b/src/ports/managed/ManagedFeatureInventoryPort.ts new file mode 100644 index 00000000000..ab7616e301e --- /dev/null +++ b/src/ports/managed/ManagedFeatureInventoryPort.ts @@ -0,0 +1,20 @@ +import type { + ExecutionOptions, + ProviderIdentity, +} from "../AnalysisProvider.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import type { + InventoryManagedFeaturesInput, + ManagedFeatureInventory, +} from "../../domain/managed/managedFeatureInventory.js"; +import type { Result } from "../../domain/result.js"; + +/** Stable read and feature inventory, without loading or running the assembly. */ +export interface ManagedFeatureInventoryPort { + readonly identity: ProviderIdentity; + close(): Promise; + inspect( + input: InventoryManagedFeaturesInput, + options?: ExecutionOptions, + ): Promise>; +} diff --git a/src/server/createServer.ts b/src/server/createServer.ts index 871c8d0b654..0d0fa254f2a 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -243,6 +243,7 @@ export const createServer = ( pythonPyc, baml, protobufDescriptors, + managedFeatureInventory, debPackage, mavenGradleMetadata, dwarfUnits, @@ -478,6 +479,7 @@ export const createServer = ( pythonPyc, baml, protobufDescriptors, + managedFeatureInventory, debPackage, erlangBeam, v8CodeCache, diff --git a/src/server/offlineInspectionToolBindings.ts b/src/server/offlineInspectionToolBindings.ts index 16867274db8..364ad4483e8 100644 --- a/src/server/offlineInspectionToolBindings.ts +++ b/src/server/offlineInspectionToolBindings.ts @@ -44,6 +44,7 @@ import type { OciImageLayoutService } from "../application/oci/OciImageLayoutSer import type { PythonPycService } from "../application/python/PythonPycService.js"; import type { BamlService } from "../application/managed/BamlService.js"; import type { ProtobufDescriptorsService } from "../application/managed/ProtobufDescriptorsService.js"; +import type { ManagedFeatureInventoryService } from "../application/managed/ManagedFeatureInventoryService.js"; import type { ReleaseExposureService } from "../application/releaseExposure/ReleaseExposureService.js"; import type { RustBinaryService } from "../application/rust/RustBinaryService.js"; import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js"; @@ -270,6 +271,9 @@ export const OFFLINE_INSPECTION_TOOL_BINDINGS = { protobufDescriptors: ((service) => ({ recover_protobuf_descriptors: applicationSummary(service), })) satisfies Bind, + managedFeatureInventory: ((service) => ({ + inventory_managed_features: applicationSummary(service), + })) satisfies Bind, erlangBeam: ((service) => ({ inspect_erlang_beam: applicationSummary(service), })) satisfies Bind, diff --git a/tests/acceptance/managedFeatureInventoryCli.test.ts b/tests/acceptance/managedFeatureInventoryCli.test.ts new file mode 100644 index 00000000000..d9d42f508d4 --- /dev/null +++ b/tests/acceptance/managedFeatureInventoryCli.test.ts @@ -0,0 +1,61 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; +import { toolContract } from "../../src/contracts/toolContracts.js"; +import { managedFeatureInventorySchema } from "../../src/domain/managed/managedFeatureInventory.js"; +import { featureAssembly } from "../fixtures/featureAssembly.js"; +import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; +import { cliTest } from "../support/cli/cliFixture.js"; + +const completeEvidenceSchema = toolContract( + "inventory_managed_features", +).outputSchema.safeExtend({ normalized_result: managedFeatureInventorySchema }); + +const write = async () => { + const path = join( + await createTestTempDirectory("rea-features-cli-"), + "Demo.dll", + ); + await writeFile(path, featureAssembly()); + return path; +}; + +cliTest( + "inventory-managed-features lists enums, enum arguments and GUID literals", + async ({ cli }) => { + const result = await cli.run({ + arguments: ["inventory-managed-features", await write(), "--json"], + }); + expect(result.exitCode, result.stderr).toBe(0); + const report = completeEvidenceSchema.parse(result.json).normalized_result; + expect(report.enums[0]).toMatchObject({ + type: "Demo.Mode", + kind_name: true, + argument_sites: 2, + }); + expect(report.enum_arguments).toHaveLength(3); + expect(report.guid_literals[0]?.value).toBe( + "44eca225-98f6-489c-b97a-03163e83ce7e", + ); + expect(report.coverage.status).toBe("complete"); + }, +); + +cliTest( + "inventory-managed-features names the row budget it exhausted", + async ({ cli }) => { + const result = await cli.run({ + arguments: [ + "inventory-managed-features", + await write(), + "--max-entries", + "2", + "--json", + ], + }); + expect(result.exitCode).toBe(1); + expect(result.json).toMatchObject({ + details: { limit: { parameter: "max_entries", effective_value: 2 } }, + }); + }, +); diff --git a/tests/acceptance/tools/localToolContracts.test.ts b/tests/acceptance/tools/localToolContracts.test.ts index 366a9a82fbd..473fdf7edd9 100644 --- a/tests/acceptance/tools/localToolContracts.test.ts +++ b/tests/acceptance/tools/localToolContracts.test.ts @@ -282,6 +282,7 @@ const pathRequests: readonly [string, Record][] = [ ["inspect_baml", { path: nul }], ["inspect_uniffi_library", { path: nul }], ["recover_protobuf_descriptors", { path: nul }], + ["inventory_managed_features", { path: nul }], ["inspect_oci_image_layout", { path: nul }], ["inspect_yara_matches", { path: nul, rule_paths: ["/tmp/rules.yar"] }], ["inspect_yara_matches", { path: "/tmp/sample.bin", rule_paths: [nul] }], diff --git a/tests/boundary/mcp/managedFeatureInventoryMcp.test.ts b/tests/boundary/mcp/managedFeatureInventoryMcp.test.ts new file mode 100644 index 00000000000..56c74344072 --- /dev/null +++ b/tests/boundary/mcp/managedFeatureInventoryMcp.test.ts @@ -0,0 +1,68 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { expect } from "vitest"; +import { toolContract } from "../../../src/contracts/toolContracts.js"; +import { managedFeatureInventorySchema } from "../../../src/domain/managed/managedFeatureInventory.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { featureAssembly } from "../../fixtures/featureAssembly.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { mcpTest } from "../../support/mcp/mcpFixture.js"; +import { testDeliveryEnvironment } from "../../support/completeEvidenceByDefault.js"; + +const completeEvidenceSchema = toolContract( + "inventory_managed_features", +).outputSchema.safeExtend({ normalized_result: managedFeatureInventorySchema }); + +mcpTest( + "advertises inventory_managed_features and inventories the assembly", + async ({ mcp }) => { + const session = createTestBinarySession(() => { + throw new Error("A feature inventory must not start a deep provider"); + }); + const client = await mcp.connect( + createServer( + { kind: "session", session }, + { + environment: testDeliveryEnvironment( + process.env, + "completeEvidenceByDefault", + ), + }, + ), + ); + try { + const advertised = (await client.listTools()).tools.find( + (tool) => tool.name === "inventory_managed_features", + ); + expect(advertised?.annotations).toMatchObject({ + readOnlyHint: false, + idempotentHint: true, + }); + const path = join( + await createTestTempDirectory("rea-features-mcp-"), + "Demo.dll", + ); + await writeFile(path, featureAssembly()); + const response = await client.callTool({ + name: "inventory_managed_features", + arguments: { path }, + }); + expect(response.isError, JSON.stringify(response.content)).not.toBe(true); + const report = completeEvidenceSchema.parse( + response.structuredContent, + ).normalized_result; + expect(report.enums.map(({ type }) => type)).toEqual(["Demo.Mode"]); + expect( + report.enum_arguments.map(({ enum: type, member }) => [type, member]), + ).toEqual([ + ["Demo.Mode", "Advanced"], + ["External.Shade", null], + ["Demo.Mode", "Simple"], + ]); + expect(report.guid_literals).toHaveLength(1); + } finally { + await session.close(); + } + }, +); diff --git a/tests/boundary/mcp/servedSchemaParity.test.ts b/tests/boundary/mcp/servedSchemaParity.test.ts index 0e13930d58c..a053bcc39df 100644 --- a/tests/boundary/mcp/servedSchemaParity.test.ts +++ b/tests/boundary/mcp/servedSchemaParity.test.ts @@ -745,6 +745,7 @@ const ABSOLUTE_PATH_FIELDS = [ "inspect_vsix_package path", "inspect_yara_matches path", "inspect_yara_matches rule_paths.[]", + "inventory_managed_features path", "open_binary path", "open_binary snapshot_path", "recover_javascript_sources additional_paths.[]", diff --git a/tests/conformance/providerCapabilityCases.ts b/tests/conformance/providerCapabilityCases.ts index 821e707278e..a0657bfc628 100644 --- a/tests/conformance/providerCapabilityCases.ts +++ b/tests/conformance/providerCapabilityCases.ts @@ -176,6 +176,9 @@ export const PROVIDER_CAPABILITY_CONFORMANCE: Readonly< protobufDescriptors: { cases: ["tests/acceptance/protobufDescriptorsCli.test.ts"], }, + managedFeatureInventory: { + cases: ["tests/acceptance/managedFeatureInventoryCli.test.ts"], + }, uniffiLibrary: { cases: ["tests/acceptance/uniffiLibraryCli.test.ts"] }, recordedCrash: { cases: ["tests/boundary/mcp/recordedCrashMcp.test.ts"] }, releaseExposure: { cases: ["tests/acceptance/releaseExposureCli.test.ts"] }, diff --git a/tests/fixtures/featureAssembly.ts b/tests/fixtures/featureAssembly.ts new file mode 100644 index 00000000000..1137d4b1d83 --- /dev/null +++ b/tests/fixtures/featureAssembly.ts @@ -0,0 +1,183 @@ +import { + buildManagedPeFixture, + managedUserStringHeap, +} from "../../scripts/fixtures/managed/pe.mjs"; + +/** The GUID literal the fixture's Main loads, as written. */ +export const FIXTURE_GUID = "{44ECA225-98F6-489C-B97A-03163E83CE7E}"; +const USER_STRINGS = [FIXTURE_GUID, "not a guid"]; + +const tiny = (il: readonly number[]): Buffer => + Buffer.from([(il.length << 2) | 2, ...il]); +const token = (value: number): number[] => [ + value & 0xff, + (value >>> 8) & 0xff, + (value >>> 16) & 0xff, + value >>> 24, +]; + +/** + * Demo.Mode (an enum: Simple = 0, Advanced = 5) and Demo.Program, whose Main + * passes Mode.Advanced to Use(Mode), passes 2 and Mode.Simple to the external + * External.Painter.Paint(External.Shade, Demo.Mode), loads a GUID literal and + * another string, and calls Use with a value merged from two branches. + */ +export interface FeatureAssemblyOptions { + /** Mode is `: uint` with Advanced = 0xffffffff, pushed as ldc.i4.m1. */ + readonly unsigned?: boolean; + /** Use(Mode)'s parameter carries a modopt before its type. */ + readonly modifier?: boolean; + /** Use's body header is malformed. */ + readonly brokenUse?: boolean; + /** Mode is nested in Program. */ + readonly nested?: boolean; + /** Use's signature names a missing TypeDef row. */ + readonly brokenUseSignature?: boolean; + /** Extra distinct non-enum callees with many parameters called from Main. */ + readonly wideCallees?: { readonly count: number; readonly params: number }; +} + +export const featureAssembly = ( + options: FeatureAssemblyOptions = {}, +): Buffer => { + const { offsets } = managedUserStringHeap(USER_STRINGS); + const literal = (index: number) => token(0x7000_0000 | offsets[index]!); + const use = token(0x0600_0001); + const extraCallees = options.wideCallees; + const wideCalls = + extraCallees === undefined + ? [] + : Array.from({ length: extraCallees.count }, (_, index) => [ + 0x28, + ...token(0x0600_0003 + index), + ]); + // One instruction per row, with its IL offset. + const main = [ + [options.unsigned === true ? 0x15 : 0x1b], // 0: ldc.i4.5, or ldc.i4.m1 + [0x28, ...use], // 1: call Use(Mode) + [0x18], // 6: ldc.i4.2 + [0x16], // 7: ldc.i4.0 + [0x28, ...token(0x0a00_0002)], // 8: call Painter.Paint(Shade, Mode) + [0x72, ...literal(0)], // 13: ldstr GUID + [0x26], // 18: pop + [0x72, ...literal(1)], // 19: ldstr "not a guid" + [0x26], // 24: pop + [0x17], // 25: ldc.i4.1 + [0x2d, 0x03], // 26: brtrue.s 31 + [0x16], // 28: ldc.i4.0 + [0x2b, 0x01], // 29: br.s 32 + [0x1b], // 31: ldc.i4.5 + [0x28, ...use], // 32: call Use(Mode), a join: not attributed + ...wideCalls, + [0x2a], // 37: ret + ].flat(); + const bodyOf = (il: readonly number[]): Buffer => { + if (il.length < 64) return tiny(il); + const header = Buffer.alloc(12); + // Fat header: CorILMethod_FatFormat (3) | size=3 dwords (3 << 12). + header.writeUInt16LE(0x3003, 0); + header.writeUInt16LE(8, 2); + header.writeUInt32LE(il.length, 4); + header.writeUInt32LE(0, 8); + return Buffer.concat([header, Buffer.from(il)]); + }; + // TypeDefOrRef coded indexes: TypeDef row n is n << 2, TypeRef row n is (n << 2) | 1. + const mode = 1 << 2; + const shade = (4 << 2) | 1; + return buildManagedPeFixture({ + typeRefs: [ + { name: "Enum", namespace: "System" }, + { name: "Object", namespace: "System" }, + { name: "Shade", namespace: "External" }, + { name: "Painter", namespace: "External" }, + ], + types: [ + { + name: "Mode", + // A nested type has no namespace of its own. + namespace: options.nested === true ? "" : "Demo", + extendsRaw: (2 << 2) | 1, + // Sealed; public, or nested public. + flags: options.nested === true ? 0x0000_0102 : 0x0000_0101, + fieldList: 1, + methodList: 1, + }, + { + name: "Program", + namespace: "Demo", + extendsRaw: (3 << 2) | 1, + fieldList: 4, + methodList: 1, + }, + ], + fields: [ + { + name: "value__", + flags: 0x0606, + signature: Buffer.from([0x06, options.unsigned === true ? 0x09 : 0x08]), + }, + { + name: "Simple", + flags: 0x8056, + signature: Buffer.from([0x06, 0x11, mode]), + }, + { + name: "Advanced", + flags: 0x8056, + signature: Buffer.from([0x06, 0x11, mode]), + }, + ], + // HasConstant coded indexes: Field row n is n << 2. + constants: [ + { + typeCode: options.unsigned === true ? 0x09 : 0x08, + parentRaw: 2 << 2, + value: Buffer.alloc(4), + }, + { + typeCode: options.unsigned === true ? 0x09 : 0x08, + parentRaw: 3 << 2, + value: Buffer.from( + options.unsigned === true ? [255, 255, 255, 255] : [5, 0, 0, 0], + ), + }, + ], + methods: [ + { + name: "Use", + // modopt(System.Object) is TypeRef row 3; TypeDef row 99 does not exist. + signature: Buffer.from( + options.brokenUseSignature === true + ? [0x00, 0x01, 0x01, 0x11, 0x81, 0x8c] + : options.modifier === true + ? [0x00, 0x01, 0x01, 0x20, (3 << 2) | 1, 0x11, mode] + : [0x00, 0x01, 0x01, 0x11, mode], + ), + body: options.brokenUse === true ? Buffer.from([0x00]) : tiny([0x2a]), + }, + { name: "Main", body: bodyOf(main) }, + ...(extraCallees === undefined + ? [] + : Array.from({ length: extraCallees.count }, (_, index) => ({ + name: `W${String(index)}`, + signature: Buffer.from([ + 0x00, + extraCallees.params, + 0x01, + ...Array.from({ length: extraCallees.params }, () => 0x08), + ]), + body: tiny([0x2a]), + }))), + ], + // MemberRefParent coded index: TypeRef row n is (n << 3) | 1. + memberRefs: [ + { + parentRaw: (5 << 3) | 1, + name: "Paint", + signature: Buffer.from([0x00, 0x02, 0x01, 0x11, shade, 0x11, mode]), + }, + ], + userStrings: USER_STRINGS, + ...(options.nested === true ? { nestedClasses: [[1, 2] as const] } : {}), + }); +}; diff --git a/tests/support/providerLifecycleCoverage.ts b/tests/support/providerLifecycleCoverage.ts index d672a5b7555..7d3b9c7d231 100644 --- a/tests/support/providerLifecycleCoverage.ts +++ b/tests/support/providerLifecycleCoverage.ts @@ -1803,6 +1803,20 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly< ), ), ), + "rea-managed-feature-inventory": inProcess( + covered( + test( + "tests/boundary/mcp/managedFeatureInventoryMcp.test.ts", + "advertises inventory_managed_features and inventories the assembly", + ), + ), + covered( + test( + "src/application/managed/ManagedFeatureInventoryService.test.ts", + "retains completed Evidence and caller selections on late cancellation", + ), + ), + ), "rea-baml": inProcess( covered( test(