From bf7646b0c7ae641f5abbc3a04e353da5b36bd655 Mon Sep 17 00:00:00 2001 From: CyberSprout Date: Thu, 3 Dec 2026 03:36:28 -0500 Subject: [PATCH] feat(firmware): classify privileged system-register, CSR, and port-I/O instructions (#14422) * feat(firmware): classify privileged system-register, CSR, and port-I/O instructions Add `inspect_procedure_hardware_instructions` (`rea inspect-procedure-hardware-instructions`) to extract and classify architectural non-MMIO hardware instructions from `read_function_instructions` across `arm`, `arm64`, `riscv`, `xtensa`, `mips`, `x86`, and `x86_64`. - Parse provider `: ` lines through the shared native address grammar (`OBSERVED_NATIVE_ADDRESS_PATTERN` / `nativeAddressInputSchema`) without stripping 2-hex-letter mnemonics (`dc`) or discarding address spaces (`rom:0x1000`, `overlay%3Aspace:0x1000`). - Normalize conditional A32/T32 system, coprocessor, barrier, wait, and trap mnemonics (`mrcne`, `mcrgt`, `mrsne`, `msreq`, `cpsie.w`, `wfene`, `wfine`, `sevne`, `svcne`) while preserving original disassembled mnemonics, and cover AArch64 `dc`/`ic`/`at`/`tlbi` maintenance operations. - Parse complete 8-bit immediate x86 port tokens (`0x00..0xff` across `0x`, Intel `h`, `$`/`#`, and decimal syntax), keep register-selected `DX` ports as `unresolved_register`, and separate symbolic or unparsed port tokens as `unresolved_operand`. - Classify zero-source RISC-V CSR set/clear pseudo-instructions (`csrsi csr, 0`, `csrci csr, 0`, `csrs csr, zero`, `csrc csr, x0`) as `read` consistently with their canonical `csrrs`/`csrrc`/`csrrsi`/`csrrci` encodings. Refs #7955 * chore(firmware): refresh the hardware-instruction advertised schema summary The shared Evidence output schema on main now advertises its string patterns, so the summary recorded on the older base was stale. Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --------- Co-authored-by: gensokyo-dev Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --- .../references/native-and-artifacts.md | 6 + .../references/native-and-artifacts.md | 6 + docs/.vitepress/documentation.ts | 5 + docs/README.md | 1 + docs/guides/firmware/firmware-analysis.md | 6 +- .../firmware/hardware-instruction-channels.md | 66 ++ ...spect_procedure_hardware_instructions.json | 9 + src/application/CapabilityInventory.ts | 1 + src/application/DirectAnalysis.ts | 1 + src/application/EnhancedTools.ts | 27 + ...HardwareInstructionChannelsService.test.ts | 70 +++ .../HardwareInstructionChannelsService.ts | 61 ++ src/application/oneShotOperationInput.ts | 1 + src/cli/coreNativeCommands.ts | 31 + src/contracts/enhancedInputs.ts | 3 + .../functionWorkflowToolContracts.ts | 13 +- src/contracts/toolContractExamples.ts | 4 + src/contracts/toolOutputSchemaGroups.ts | 4 + .../hardwareInstructionChannels.test.ts | 440 ++++++++++++++ .../firmware/hardwareInstructionChannels.ts | 105 ++++ .../hardwareInstructionClassifiers.ts | 573 ++++++++++++++++++ .../firmware/hardwareInstructionRiscv.ts | 212 +++++++ src/domain/firmware/hardwareInstructionX86.ts | 362 +++++++++++ src/domain/inputArgumentGuidance.ts | 1 + src/server/sessionToolBindings.ts | 10 + .../hardwareInstructionChannelsMcpCli.test.ts | 163 +++++ 26 files changed, 2179 insertions(+), 2 deletions(-) create mode 100644 docs/guides/firmware/hardware-instruction-channels.md create mode 100644 scripts/verify/advertised-schemas/tools/inspect_procedure_hardware_instructions.json create mode 100644 src/application/firmware/HardwareInstructionChannelsService.test.ts create mode 100644 src/application/firmware/HardwareInstructionChannelsService.ts create mode 100644 src/domain/firmware/hardwareInstructionChannels.test.ts create mode 100644 src/domain/firmware/hardwareInstructionChannels.ts create mode 100644 src/domain/firmware/hardwareInstructionClassifiers.ts create mode 100644 src/domain/firmware/hardwareInstructionRiscv.ts create mode 100644 src/domain/firmware/hardwareInstructionX86.ts create mode 100644 tests/boundary/mcp/hardwareInstructionChannelsMcpCli.test.ts 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 dda6dffc399..a0700de8bbe 100644 --- a/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md +++ b/.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md @@ -965,6 +965,12 @@ For ESP32/ESP8266 flash dumps or carved `partitions/nvs.bin` files (`esp-nvs`), to decode ESP-IDF v1/v2 Non-Volatile Storage pages, CRC32 checksums, namespaces, strings, integers, floats, and multi-chunk v2 blobs, marking older copies of a key `superseded`; encrypted NVS entries are not decrypted. See [ESP-IDF NVS partitions](https://github.com/morluto/rea/blob/main/docs/guides/firmware/esp-nvs.md). +When analyzing disassembled bootloaders, RTOS handlers, kernels, or BIOS/UEFI +functions in an open target, use `inspect_procedure_hardware_instructions` +(`rea inspect-procedure-hardware-instructions TARGET PROCEDURE --hardware-architecture ARCH`) +to extract non-MMIO hardware channels (`MRS`/`MSR`, `CPSID`, `MCR`/`MRC`, +RISC-V `csrr*`, Xtensa `rsr`/`wsr`, MIPS `mfc0`/`mtc0`, x86 `in`/`out` and +`rdmsr`/`wrmsr`/`cr*`). See [hardware instruction channels](https://github.com/morluto/rea/blob/main/docs/guides/firmware/hardware-instruction-channels.md). For other headerless images (embedded firmware without ELF/Mach-O/PE/MZ headers), open with `format: "raw-binary"`, `architecture` (`x86`, `x86_64`, 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 dda6dffc399..a0700de8bbe 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 @@ -965,6 +965,12 @@ For ESP32/ESP8266 flash dumps or carved `partitions/nvs.bin` files (`esp-nvs`), to decode ESP-IDF v1/v2 Non-Volatile Storage pages, CRC32 checksums, namespaces, strings, integers, floats, and multi-chunk v2 blobs, marking older copies of a key `superseded`; encrypted NVS entries are not decrypted. See [ESP-IDF NVS partitions](https://github.com/morluto/rea/blob/main/docs/guides/firmware/esp-nvs.md). +When analyzing disassembled bootloaders, RTOS handlers, kernels, or BIOS/UEFI +functions in an open target, use `inspect_procedure_hardware_instructions` +(`rea inspect-procedure-hardware-instructions TARGET PROCEDURE --hardware-architecture ARCH`) +to extract non-MMIO hardware channels (`MRS`/`MSR`, `CPSID`, `MCR`/`MRC`, +RISC-V `csrr*`, Xtensa `rsr`/`wsr`, MIPS `mfc0`/`mtc0`, x86 `in`/`out` and +`rdmsr`/`wrmsr`/`cr*`). See [hardware instruction channels](https://github.com/morluto/rea/blob/main/docs/guides/firmware/hardware-instruction-channels.md). For other headerless images (embedded firmware without ELF/Mach-O/PE/MZ headers), open with `format: "raw-binary"`, `architecture` (`x86`, `x86_64`, diff --git a/docs/.vitepress/documentation.ts b/docs/.vitepress/documentation.ts index 4afc1803fad..ce5b89636ac 100644 --- a/docs/.vitepress/documentation.ts +++ b/docs/.vitepress/documentation.ts @@ -343,6 +343,11 @@ export const documentationSections = [ source: "guides/firmware/firmware-architecture-candidates.md", route: "/firmware-architecture-candidates", }, + { + text: "Non-MMIO hardware instruction channels", + source: "guides/firmware/hardware-instruction-channels.md", + route: "/hardware-instruction-channels", + }, { text: "Android OTA update payloads", source: "guides/firmware/android-ota-payload.md", diff --git a/docs/README.md b/docs/README.md index 69e57f1bfe5..63d57a28609 100644 --- a/docs/README.md +++ b/docs/README.md @@ -111,6 +111,7 @@ The [REA website](https://rea.tools/) has worked examples and product pages. - [Firmware analysis](guides/firmware/firmware-analysis.md) - [Firmware interrupt and trap vector tables](guides/firmware/firmware-vector-tables.md) - [Firmware CPU and load-base candidates](guides/firmware/firmware-architecture-candidates.md) +- [Non-MMIO hardware instruction channels](guides/firmware/hardware-instruction-channels.md) - [Android OTA update payloads](guides/firmware/android-ota-payload.md) - [Android Verified Boot vbmeta images](guides/firmware/android-vbmeta.md) - [Android sparse images](guides/firmware/android-sparse-image.md) diff --git a/docs/guides/firmware/firmware-analysis.md b/docs/guides/firmware/firmware-analysis.md index 701e32cac5c..a035c80d887 100644 --- a/docs/guides/firmware/firmware-analysis.md +++ b/docs/guides/firmware/firmware-analysis.md @@ -16,7 +16,11 @@ bases, and instruction-signature margins before choosing `open_binary` inputs. For bare-metal ARM M-profile and RISC-V images with a known load base, use [`inspect_firmware_vector_table`](firmware-vector-tables.md) to decode system exception vectors, external IRQ handler addresses, and optional CMSIS-SVD -interrupt bindings without opening a session. +interrupt bindings without opening a session. Once a firmware +or kernel target is open in a native provider, use +[`inspect_procedure_hardware_instructions`](hardware-instruction-channels.md) to +extract privileged system-register, CSR, special-register, barrier, and x86 port +I/O instructions from disassembled procedures. On Linux, Binwalk and Unblob run as REA-owned processes and require a procps-compatible system `ps`; see the shared diff --git a/docs/guides/firmware/hardware-instruction-channels.md b/docs/guides/firmware/hardware-instruction-channels.md new file mode 100644 index 00000000000..95467303fc7 --- /dev/null +++ b/docs/guides/firmware/hardware-instruction-channels.md @@ -0,0 +1,66 @@ +# Non-MMIO hardware instruction channels + +`inspect_procedure_hardware_instructions` (`rea inspect-procedure-hardware-instructions`) +is a provider-neutral disassembly workflow that extracts architectural hardware +instructions outside memory-mapped I/O from one analyzed procedure via +`read_function_instructions`. + +## When to use it + +Reset handlers, bootloaders, RTOS context switches, hypervisors, and x86 BIOS or +SMM routines control core hardware state through privileged ISA instructions +rather than load/store MMIO accesses—operations that decompilers frequently +collapse into opaque intrinsics. + +Supported `hardware_architecture` families: + +- `arm`: Cortex-M and A-profile `MRS`/`MSR` (`MSP`, `PSP`, `MSPLIM`, `PSPLIM`, + `PRIMASK`, `BASEPRI`, `FAULTMASK`, `CONTROL`, `CPSR`, `SPSR`, including field + masks such as `CPSR_c` and conditional/Thumb width forms such as `mrsne`, + `msreq`, `mrcne`, `cpsie.w`), `CPSID`/`CPSIE`, `MCR`/`MRC`/`MCRR`/`MRRC` + coprocessor transfers (`CP15`/`CP14`), `DSB`/`DMB`/`ISB`, and + `WFI`/`WFE`/`SEV`/`SVC`/`BKPT`. +- `arm64`: `MRS`/`MSR` (`SCTLR_EL*`, `VBAR_EL*`, `TTBR*`, `MAIR_EL*`, `ESR_EL*`, + `ELR_EL*`, `DAIF`, `CurrentEL`, numeric `S3_*` encodings), `TLBI`/`IC`/`DC`/`AT`, + `DSB`/`ISB`, and `SVC`/`HVC`/`SMC`/`ERET`. +- `riscv`: `csrrw`/`csrrs`/`csrrc` and pseudo-ops (`csrr`, `csrw`, `csrs`, + `csrc`, `csrsi`, `csrci`) across standard CSRs (`mstatus`, `mie`, `mtvec`, + `mepc`, `mcause`, `mtval`, `satp`, `pmpcfg*`, `pmpaddr*`), distinguishing + zero-source non-mutating reads (`csrsi csr, 0`, `csrs csr, zero`) from + writes, plus `mret`/`sret`/`ecall`/`wfi` and `fence`/`fence.i`/`sfence.vma`. +- `xtensa`: `rsr`/`wsr`/`xsr` special registers (`PS`, `INTENABLE`, `VECBASE`, + `CCOUNT`, `EXCCAUSE`), `rsil`, `waiti`, and `memw`/`isync`/`dsync`. +- `mips`: `mfc0`/`mtc0` CP0 transfers, `ei`/`di`, `eret`, `sync`/`ehb`, and + `cache`/`tlbwi`/`tlbwr`. +- `x86` and `x86_64`: `in`/`out`/`ins*`/`outs*` port I/O (attributing 8-bit + immediate ports `0x00..0xff` such as `0x70`/`0x71` CMOS/RTC, `0x60`/`0x64` + 8042/EC, `0x80` POST, and `0xb2`/`0xb3` APM/SMI across `0x`, Intel `h`, `$`, + and decimal syntax, while 16-bit ports such as `0xcf8`/`0xcfc` PCI or `0x3f8` + UART accessed through `DX` report `target: null` with + `target_basis: "unresolved_register"`), `rdmsr`/`wrmsr`, `mov cr*`/`dr*`, + `lgdt`/`lidt`, `cli`/`sti`, `wbinvd`/`invlpg`, `cpuid`, and `rsm`/`vmcall`. + +## CLI and MCP usage + +```bash +rea inspect-procedure-hardware-instructions firmware.elf Reset_Handler \ + --hardware-architecture arm +``` + +In MCP, open a target with `open_binary`, then call +`inspect_procedure_hardware_instructions` with `procedure` and +`hardware_architecture`. + +## Provenance and limitations + +- Register-indirect port or MSR indices (`in al, dx`, `out dx, eax`, + `rdmsr`/`wrmsr` via `ECX`) report `target: null` and + `target_basis: "unresolved_register"` rather than guessing register values; + pair with `trace_native_values` or `analyze_function` when constant + propagation is needed. Symbolic or unparsed operand tokens report + `target_basis: "unresolved_operand"` without counting as register-dynamic. +- Space-qualified native coordinates from multi-space providers (such as + `rom:0x1000` or `overlay%3Aspace:0x1000`) are preserved verbatim on + `instruction_address`. +- Body coverage reflects the selected provider's `read_function_instructions` + extent and inherits any provider terminal-call caveats in `limitations`. diff --git a/scripts/verify/advertised-schemas/tools/inspect_procedure_hardware_instructions.json b/scripts/verify/advertised-schemas/tools/inspect_procedure_hardware_instructions.json new file mode 100644 index 00000000000..4471b6b5dba --- /dev/null +++ b/scripts/verify/advertised-schemas/tools/inspect_procedure_hardware_instructions.json @@ -0,0 +1,9 @@ +{ + "schemas": { + "input compact": "22bb60d84c84a937", + "output compact": "4babf3ed292a48aa" + }, + "patterns": { + "output": ["^[^\\x00]*$", "^ev_[0-9a-f]{64}$"] + } +} diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts index eb85dd5be27..81e58a9c57b 100644 --- a/src/application/CapabilityInventory.ts +++ b/src/application/CapabilityInventory.ts @@ -265,6 +265,7 @@ const ENHANCED_REQUIREMENTS: ReadonlyMap = new Map( ], analyze_function: ["analyze_function"], inspect_native_api: ["analyze_function"], + inspect_procedure_hardware_instructions: ["read_function_instructions"], trace_feature: [ "search_strings", "search_procedures", diff --git a/src/application/DirectAnalysis.ts b/src/application/DirectAnalysis.ts index 7daa7fed42e..00cc5973185 100644 --- a/src/application/DirectAnalysis.ts +++ b/src/application/DirectAnalysis.ts @@ -1014,6 +1014,7 @@ const isWorkflowEvidenceTool = ( ): tool is DirectEnhancedToolName => tool === "binary_overview" || tool === "inspect_native_api" || + tool === "inspect_procedure_hardware_instructions" || tool === "inspect_native_dispatch_metadata" || tool === "trace_feature" || tool === "trace_native_values" || diff --git a/src/application/EnhancedTools.ts b/src/application/EnhancedTools.ts index f7f848a3751..4dc8c479ef0 100644 --- a/src/application/EnhancedTools.ts +++ b/src/application/EnhancedTools.ts @@ -87,6 +87,7 @@ import { import { traceLiteralFeature } from "./EnhancedLiteralTracing.js"; import type { ProgressReporter } from "../ports/ProgressReporter.js"; import { projectNativeApiInspection } from "./native/NativeApiInspection.js"; +import { inspectProcedureHardwareInstructions } from "./firmware/HardwareInstructionChannelsService.js"; type BatchResolution = { readonly address: string; @@ -147,6 +148,15 @@ export class EnhancedTools { ? this.executeValidated({ name, input: parsed.data }, signal) : invalidEnhancedInput(name, parsed.error, input); } + case "inspect_procedure_hardware_instructions": { + const parsed = + enhancedInputSchemas.inspect_procedure_hardware_instructions.safeParse( + input, + ); + return parsed.success + ? this.executeValidated({ name, input: parsed.data }, signal) + : invalidEnhancedInput(name, parsed.error, input); + } case "inspect_native_dispatch_metadata": { const parsed = enhancedInputSchemas.inspect_native_dispatch_metadata.safeParse( @@ -224,6 +234,8 @@ export class EnhancedTools { return this.#analyzeFunction(call.input, signal); case "inspect_native_api": return this.#inspectNativeApi(call.input, signal); + case "inspect_procedure_hardware_instructions": + return this.#inspectHardwareInstructions(call.input, signal); case "trace_feature": return traceLiteralFeature(this.#observed, call.input, signal); case "trace_call_path": @@ -264,6 +276,21 @@ export class EnhancedTools { ); } + async #inspectHardwareInstructions( + input: z.output< + typeof enhancedInputSchemas.inspect_procedure_hardware_instructions + >, + signal?: AbortSignal, + ): EnhancedResult { + const inspected = await inspectProcedureHardwareInstructions( + this.analysis, + input, + signal === undefined ? undefined : { signal }, + ); + if (!inspected.ok) return inspected; + return ok(ownedJsonValueSchema.parse(inspected.value)); + } + async #objcClasses(pattern: string, signal?: AbortSignal): EnhancedResult { const inventory = await executeFact( this.#observed, diff --git a/src/application/firmware/HardwareInstructionChannelsService.test.ts b/src/application/firmware/HardwareInstructionChannelsService.test.ts new file mode 100644 index 00000000000..874dccc1149 --- /dev/null +++ b/src/application/firmware/HardwareInstructionChannelsService.test.ts @@ -0,0 +1,70 @@ +import { describe, expect, it } from "vitest"; +import { inspectProcedureHardwareInstructions } from "./HardwareInstructionChannelsService.js"; +import { ok } from "../../domain/result.js"; +import { + createAnalysisExecution, + type AnalysisOperationPort, +} from "../../ports/AnalysisProvider.js"; + +const MOCK_PROVIDER = { + id: "mock", + name: "Mock Provider", + version: "1", +} as const; + +describe("inspectProcedureHardwareInstructions service", () => { + it("composes read_function_instructions and preserves provider limitations", async () => { + const port: AnalysisOperationPort = { + execute: async (operation, args) => { + expect(operation).toBe("read_function_instructions"); + expect(args).toEqual({ procedure: "Reset_Handler" }); + return ok( + createAnalysisExecution( + { + procedure: { + name: "Reset_Handler", + address: "0x08000100", + classification: null, + body: { available: false, reason: "fixture" }, + }, + instructions: [ + "0x08000100: cpsid i", + "0x08000102: msr msp, r0", + "0x08000106: isb", + ], + limitations: ["Ghidra terminal-call truncation possible."], + }, + MOCK_PROVIDER, + ), + ); + }, + }; + + const res = await inspectProcedureHardwareInstructions(port, { + procedure: "Reset_Handler", + hardware_architecture: "arm", + }); + expect(res.ok).toBe(true); + if (!res.ok) return; + expect(res.value.matched_instruction_count).toBe(3); + expect(res.value.summary.distinct_targets).toEqual(["CPS:I", "MSP"]); + expect(res.value.limitations).toContain( + "Ghidra terminal-call truncation possible.", + ); + }); + + it("returns AnalysisOutputError when provider output violates functionInstructionWindowSchema", async () => { + const port: AnalysisOperationPort = { + execute: async () => + ok(createAnalysisExecution({ unexpected: true }, MOCK_PROVIDER)), + }; + + const res = await inspectProcedureHardwareInstructions(port, { + procedure: "bad_fn", + hardware_architecture: "riscv", + }); + expect(res.ok).toBe(false); + if (res.ok) return; + expect(res.error._tag).toBe("AnalysisOutputError"); + }); +}); diff --git a/src/application/firmware/HardwareInstructionChannelsService.ts b/src/application/firmware/HardwareInstructionChannelsService.ts new file mode 100644 index 00000000000..afd2d0f8839 --- /dev/null +++ b/src/application/firmware/HardwareInstructionChannelsService.ts @@ -0,0 +1,61 @@ +import type { + AnalysisOperationPort, + ExecutionOptions, +} from "../../ports/AnalysisProvider.js"; +import { + AnalysisOutputError, + cancelledBy, + isAborted, +} from "../../domain/analysisErrorCore.js"; +import type { AnalysisError } from "../../domain/analysisErrorBase.js"; +import { analyzeProcedureHardwareInstructions } from "../../domain/firmware/hardwareInstructionClassifiers.js"; +import type { + HardwareInstructionChannelsResult, + InspectProcedureHardwareInstructionsInput, +} from "../../domain/firmware/hardwareInstructionChannels.js"; +import { functionInstructionWindowSchema } from "../../domain/native/functionDossier.js"; +import { err, ok, type Result } from "../../domain/result.js"; + +const OPERATION = "inspect_procedure_hardware_instructions"; + +/** Compose `read_function_instructions` with ISA-specific hardware channel extraction. */ +export const inspectProcedureHardwareInstructions = async ( + analysis: AnalysisOperationPort, + input: InspectProcedureHardwareInstructionsInput, + options?: ExecutionOptions, +): Promise> => { + if (isAborted(options?.signal)) { + return err(cancelledBy(OPERATION, options?.signal)); + } + const executed = await analysis.execute( + "read_function_instructions", + { procedure: input.procedure }, + { ...options, retainEvidence: true }, + ); + if (!executed.ok) return executed; + if (isAborted(options?.signal)) { + return err(cancelledBy(OPERATION, options?.signal)); + } + + const parsed = functionInstructionWindowSchema.safeParse( + executed.value.result, + ); + if (!parsed.success) { + return err( + new AnalysisOutputError( + "read_function_instructions", + "Provider output did not match functionInstructionWindowSchema.", + { cause: parsed.error }, + ), + ); + } + + return ok( + analyzeProcedureHardwareInstructions({ + procedure: parsed.data.procedure, + architecture: input.hardware_architecture, + instructions: parsed.data.instructions, + upstreamLimitations: parsed.data.limitations, + }), + ); +}; diff --git a/src/application/oneShotOperationInput.ts b/src/application/oneShotOperationInput.ts index c26533dbc11..9bc2737a808 100644 --- a/src/application/oneShotOperationInput.ts +++ b/src/application/oneShotOperationInput.ts @@ -37,6 +37,7 @@ export type DirectAnalysisTool = | "resolve_native_call_targets" | "analyze_function" | "inspect_native_api" + | "inspect_procedure_hardware_instructions" | "inspect_native_dispatch_metadata" | "search_strings" | "search_procedures" diff --git a/src/cli/coreNativeCommands.ts b/src/cli/coreNativeCommands.ts index bcbc2bb825c..74a06ec8541 100644 --- a/src/cli/coreNativeCommands.ts +++ b/src/cli/coreNativeCommands.ts @@ -327,4 +327,35 @@ const registerProcedureSelectorCommands = ( }, run, ); + registerContractCommand( + cli, + logger, + contractNamed( + ENHANCED_TOOL_CONTRACTS, + "inspect_procedure_hardware_instructions", + ), + { + description: `Extract non-MMIO hardware instructions (system registers, CSRs, port I/O, barriers) from one procedure. ${addressOrProcedureGuidance} ${equalSelectorGuidance}`, + sessionTarget: nativeTarget("Local executable or firmware path", true), + positionals: ["procedure"], + selectorOptions: { + procedure: { + name: "procedure", + description: `Procedure selector; use this option for symbols beginning with a dash. ${addressOrProcedureGuidance}`, + kind: "native", + }, + }, + fields: { + procedure: { + name: "address", + description: `Procedure name or address. ${addressOrProcedureGuidance}`, + }, + hardware_architecture: { + description: + "Explicit ISA family (arm, arm64, riscv, xtensa, mips, x86, or x86_64)", + }, + }, + }, + run, + ); }; diff --git a/src/contracts/enhancedInputs.ts b/src/contracts/enhancedInputs.ts index d0e1565cce7..9905e4f39b8 100644 --- a/src/contracts/enhancedInputs.ts +++ b/src/contracts/enhancedInputs.ts @@ -1,6 +1,7 @@ import { z } from "zod"; import { nativeDispatchMetadataInputSchema } from "../domain/native/objcSwiftMetadata.js"; import { nativeProcedureInputSchema } from "../domain/native/nativeProcedureInput.js"; +import { inspectProcedureHardwareInstructionsInputSchema } from "../domain/firmware/hardwareInstructionChannels.js"; import { decompileDirectoryInputSchema } from "./decompileDirectory.js"; import { nativeValueTraceInputSchema } from "../domain/native/nativeValueTrace.js"; import { nativeInvestigationTraceLimitsSchema } from "../domain/native/nativeInvestigationGraph.js"; @@ -96,6 +97,8 @@ export const enhancedInputSchemas = { // Provider input excludes delivery detail, which belongs to the MCP tool contract. analyze_function: nativeProcedureInputSchema, inspect_native_api: nativeProcedureInputSchema, + inspect_procedure_hardware_instructions: + inspectProcedureHardwareInstructionsInputSchema, trace_feature: traceLiteralInputSchema, trace_call_path: z.strictObject({ start: z.string().min(1).describe("A starting procedure symbol or address"), diff --git a/src/contracts/functionWorkflowToolContracts.ts b/src/contracts/functionWorkflowToolContracts.ts index 5f0c4a94f46..81f04a758ca 100644 --- a/src/contracts/functionWorkflowToolContracts.ts +++ b/src/contracts/functionWorkflowToolContracts.ts @@ -14,7 +14,10 @@ import { } from "./toolEffects.js"; import { enhancedOutputSchemas } from "./toolOutputSchemaGroups.js"; -type FunctionWorkflowName = "analyze_function" | "inspect_native_api"; +type FunctionWorkflowName = + | "analyze_function" + | "inspect_native_api" + | "inspect_procedure_hardware_instructions"; /** * MCP inputs: the provider input plus analyze_function's delivery detail, which @@ -26,11 +29,14 @@ export const functionWorkflowInputSchemas = { detail: analysisDetailSummaryDefaultSchema, }), inspect_native_api: enhancedInputSchemas.inspect_native_api, + inspect_procedure_hardware_instructions: + enhancedInputSchemas.inspect_procedure_hardware_instructions, } as const; /** The contracts below that the CLI exposes as commands. */ const FUNCTION_WORKFLOW_CLI_CONTRACTS: ReadonlySet = new Set([ "inspect_native_api", + "inspect_procedure_hardware_instructions", ]); const functionWorkflow = ( @@ -77,4 +83,9 @@ export const FUNCTION_WORKFLOW_TOOL_CONTRACTS = [ }), "Inspect recovered parameter/return boundary types and jump-table dispatch for one native function selected by symbol or address. Returns confidence, supporting Evidence, case/data/target mappings, unsupported facets and residual unknowns. Null case values are unresolved, never known defaults. Use analyze_function for the broader function dossier.", ), + functionWorkflow( + "inspect_procedure_hardware_instructions", + providerUiNetworkEvidenceEffects, + "Extract and classify non-MMIO architectural hardware instructions from one disassembled procedure using an explicit hardware_architecture (arm, arm64, riscv, xtensa, mips, x86, or x86_64). Reports system/special registers (MRS/MSR, MCR/MRC, RDMSR/WRMSR, CR0..CR8), RISC-V CSRs (csrr*), Xtensa RSR/WSR/XSR, MIPS CP0, x86 port I/O (in/out), interrupt masks (CPSID/CPSIE, CLI/STI), memory barriers, and privilege/sleep transitions. Register-indirect ports or MSRs (such as DX or ECX) keep target: null with target_basis: unresolved_register.", + ), ] as const satisfies readonly ToolContract[]; diff --git a/src/contracts/toolContractExamples.ts b/src/contracts/toolContractExamples.ts index d98f5c3802b..00298fff596 100644 --- a/src/contracts/toolContractExamples.ts +++ b/src/contracts/toolContractExamples.ts @@ -53,6 +53,10 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly< }, analyze_swift_types: { category: "classes", pattern: "Account" }, inspect_native_api: { procedure: "main" }, + inspect_procedure_hardware_instructions: { + procedure: "Reset_Handler", + hardware_architecture: "arm", + }, trace_feature: { query: "license" }, trace_call_path: { start: "0x1000", goal: "0x1100" }, trace_native_ui_action: { action: "buildTapped:" }, diff --git a/src/contracts/toolOutputSchemaGroups.ts b/src/contracts/toolOutputSchemaGroups.ts index c0831552f48..d2b7a7db3f7 100644 --- a/src/contracts/toolOutputSchemaGroups.ts +++ b/src/contracts/toolOutputSchemaGroups.ts @@ -70,6 +70,7 @@ import { evidenceBundleSchema } from "../domain/evidenceBundle.js"; import { processCaptureComparisonSchema } from "../domain/process/processComparison.js"; import { nativeApiInspectionResultSchema } from "../domain/native/nativeApiBoundary.js"; +import { hardwareInstructionChannelsResultSchema } from "../domain/firmware/hardwareInstructionChannels.js"; import { demangleSwiftSchema, inspectMachoSchema, @@ -426,6 +427,9 @@ export const enhancedOutputSchemas = { nativeFunctionSummaryViewResultSchema, ), inspect_native_api: evidenceResultOf(nativeApiInspectionResultSchema), + inspect_procedure_hardware_instructions: evidenceResultOf( + hardwareInstructionChannelsResultSchema, + ), trace_feature: literalTraceOutput, trace_call_path: callPathTraceOutput, } as const satisfies Readonly>; diff --git a/src/domain/firmware/hardwareInstructionChannels.test.ts b/src/domain/firmware/hardwareInstructionChannels.test.ts new file mode 100644 index 00000000000..2d2f1f9134b --- /dev/null +++ b/src/domain/firmware/hardwareInstructionChannels.test.ts @@ -0,0 +1,440 @@ +import { describe, expect, it } from "vitest"; +import { hardwareInstructionChannelsResultSchema } from "./hardwareInstructionChannels.js"; +import { analyzeProcedureHardwareInstructions } from "./hardwareInstructionClassifiers.js"; + +const procId = (name: string, address: string) => ({ + name, + address, + classification: null, + body: { available: false as const, reason: "fixture" }, +}); + +describe("analyzeProcedureHardwareInstructions ARM, AArch64, and RISC-V", () => { + it("classifies ARM Cortex-M and CP15 system registers, interrupt masks, barriers, and sleep instructions", () => { + const res = analyzeProcedureHardwareInstructions({ + procedure: procId("Reset_Handler", "0x08000100"), + architecture: "arm", + instructions: [ + "0x08000100: cpsid i", + "0x08000102: mrs r0, primask", + "0x08000106: msr msp_ns, r1", + "0x0800010a: mcr p15, #0, r0, c12, c0, #0", + "0x0800010e: dsb.w sy", + "0x08000112: isb", + "0x08000116: wfi", + "0x08000118: bx lr", + ], + }); + expect(hardwareInstructionChannelsResultSchema.safeParse(res).success).toBe( + true, + ); + expect(res.matched_instruction_count).toBe(7); + expect(res.channels[0]).toMatchObject({ + instruction_address: "0x08000100", + mnemonic: "cpsid", + category: "interrupt_mask", + direction: "write", + target: "CPS:I", + }); + expect(res.channels[1]).toMatchObject({ + mnemonic: "mrs", + category: "system_register", + direction: "read", + target: "PRIMASK", + }); + expect(res.channels[2]).toMatchObject({ + mnemonic: "msr", + direction: "write", + target: "MSP_NS", + target_description: "Main Stack Pointer (Non-secure)", + }); + expect(res.channels[3]).toMatchObject({ + mnemonic: "mcr", + category: "coprocessor", + direction: "write", + target: "P15:0,c12,c0,0", + target_description: "Vector Base Address Register (VBAR)", + }); + }); + + it("classifies conditional A32/T32 hardware instructions while retaining original mnemonics", () => { + const condArm = analyzeProcedureHardwareInstructions({ + procedure: procId("cond_sys_init", "0x8000"), + architecture: "arm", + instructions: [ + "0x8000: mrcne p15, #0, r0, c12, c0, #0", + "0x8004: mcrgt p15, #0, r0, c1, c0, #0", + "0x8008: mrsne r0, cpsr", + "0x800c: msreq cpsr_c, r1", + "0x8010: cpsie.w i", + "0x8014: wfene", + "0x8018: wfine", + "0x801c: sevne", + "0x8020: svcne #0", + "0x8024: addeq r0, r0, #1", + "0x8028: moveq r1, r2", + "0x802c: ldrne r3, [r0]", + "0x8030: bne 0x8000", + ], + }); + expect( + hardwareInstructionChannelsResultSchema.safeParse(condArm).success, + ).toBe(true); + expect(condArm.matched_instruction_count).toBe(9); + expect(condArm.channels[0]).toMatchObject({ + mnemonic: "mrcne", + category: "coprocessor", + direction: "read", + target: "P15:0,c12,c0,0", + target_description: "Vector Base Address Register (VBAR)", + }); + expect(condArm.channels[1]).toMatchObject({ + mnemonic: "mcrgt", + category: "coprocessor", + direction: "write", + target: "P15:0,c1,c0,0", + target_description: "System Control Register (SCTLR)", + }); + expect(condArm.channels[2]).toMatchObject({ + mnemonic: "mrsne", + category: "system_register", + direction: "read", + target: "CPSR", + }); + expect(condArm.channels[3]).toMatchObject({ + mnemonic: "msreq", + category: "system_register", + direction: "write", + target: "CPSR_C", + target_description: "Current Program Status Register (CPSR_C)", + }); + expect(condArm.channels[4]).toMatchObject({ + mnemonic: "cpsie.w", + category: "interrupt_mask", + direction: "write", + target: "CPS:I", + }); + expect(condArm.channels.slice(5).map((c) => c.mnemonic)).toEqual([ + "wfene", + "wfine", + "sevne", + "svcne", + ]); + }); + + it("classifies AArch64 EL system registers and DC/IC/AT/TLBI maintenance without stripping hex-like mnemonics", () => { + const arm64 = analyzeProcedureHardwareInstructions({ + procedure: procId("el3_init", "0x4000"), + architecture: "arm64", + instructions: [ + "0x4000 mrs x0, CurrentEL", + "0x4004 msr vbar_el1, x1", + "0x4008 msr s3_0_c15_c2_0, x2", + "0x400c: dc civac, x0", + "0x4010: dc zva, x1", + "0x4014: ic iallu", + "0x4018: at s1e1r, x0", + "0x401c: tlbi vmalle1", + "0x4020 eret", + ], + }); + expect( + hardwareInstructionChannelsResultSchema.safeParse(arm64).success, + ).toBe(true); + expect(arm64.matched_instruction_count).toBe(9); + expect(arm64.channels[1]).toMatchObject({ + target: "VBAR_EL1", + direction: "write", + target_basis: "architecture_manual", + }); + expect(arm64.channels[2]).toMatchObject({ + target: "S3_0_C15_C2_0", + target_basis: "numeric_encoding", + }); + expect(arm64.channels[3]).toMatchObject({ + instruction_address: "0x400c", + mnemonic: "dc", + category: "cache_or_tlb", + direction: "control", + target: "CIVAC", + target_basis: "architecture_manual", + }); + expect(arm64.channels[4]).toMatchObject({ + mnemonic: "dc", + category: "cache_or_tlb", + target: "ZVA", + }); + expect(arm64.channels[5]).toMatchObject({ + mnemonic: "ic", + category: "cache_or_tlb", + target: "IALLU", + }); + expect(arm64.channels[6]).toMatchObject({ + mnemonic: "at", + category: "cache_or_tlb", + target: "S1E1R", + }); + expect(arm64.channels[7]).toMatchObject({ + mnemonic: "tlbi", + category: "cache_or_tlb", + target: "VMALLE1", + }); + }); + + it("classifies RISC-V CSR pseudo and explicit operations, keeping zero-source set/clear forms as reads", () => { + const rv = analyzeProcedureHardwareInstructions({ + procedure: procId("trap_init", "0x80000000"), + architecture: "riscv", + instructions: [ + "0x80000000: csrrw x0, mtvec, a0", + "0x80000004: csrrs a1, mcause, x0", + "0x80000008: csrsi mstatus, 8", + "0x8000000c: csrsi mstatus, 0", + "0x80000010: csrci mstatus, 0x0", + "0x80000014: csrs mstatus, zero", + "0x80000018: csrc mie, x0", + "0x8000001c: csrs mie, a0", + "0x80000020: csrw pmpcfg0, zero", + "0x80000024: sfence.vma", + "0x80000028: mret", + ], + }); + expect(hardwareInstructionChannelsResultSchema.safeParse(rv).success).toBe( + true, + ); + expect(rv.matched_instruction_count).toBe(11); + expect(rv.channels[0]).toMatchObject({ + category: "csr", + direction: "write", + target: "mtvec", + }); + expect(rv.channels[1]).toMatchObject({ + category: "csr", + direction: "read", + target: "mcause", + }); + expect(rv.channels[2]).toMatchObject({ + mnemonic: "csrsi", + direction: "read_modify_write", + target: "mstatus", + }); + expect(rv.channels[3]).toMatchObject({ + mnemonic: "csrsi", + direction: "read", + target: "mstatus", + }); + expect(rv.channels[4]).toMatchObject({ + mnemonic: "csrci", + direction: "read", + target: "mstatus", + }); + expect(rv.channels[5]).toMatchObject({ + mnemonic: "csrs", + direction: "read", + target: "mstatus", + }); + expect(rv.channels[6]).toMatchObject({ + mnemonic: "csrc", + direction: "read", + target: "mie", + }); + expect(rv.channels[7]).toMatchObject({ + mnemonic: "csrs", + direction: "read_modify_write", + target: "mie", + }); + expect(rv.channels[8]).toMatchObject({ + mnemonic: "csrw", + direction: "write", + target: "pmpcfg0", + }); + }); +}); + +describe("analyzeProcedureHardwareInstructions Xtensa, MIPS, x86, address spaces, and controls", () => { + it("classifies Xtensa special registers, MIPS CP0, and x86 encodable imm8 vs DX-selected port I/O", () => { + const xtensa = analyzeProcedureHardwareInstructions({ + procedure: procId("xt_ints_off", "0x40080100"), + architecture: "xtensa", + instructions: ["rsil a2, 3", "rsr.ccount a3", "wsr a4, vecbase", "memw"], + }); + expect(xtensa.matched_instruction_count).toBe(4); + expect(xtensa.channels[1]).toMatchObject({ + category: "special_register", + direction: "read", + target: "CCOUNT", + }); + expect(xtensa.channels[2]).toMatchObject({ + direction: "write", + target: "VECBASE", + }); + + const mips = analyzeProcedureHardwareInstructions({ + procedure: procId("mips_exc", "0xbfc00380"), + architecture: "mips", + instructions: ["di", "mfc0 $k0, $13", "mtc0 $k0, $12, 0", "eret"], + }); + expect(mips.matched_instruction_count).toBe(4); + expect(mips.channels[1]).toMatchObject({ + category: "coprocessor", + direction: "read", + target: "CP0:$13", + }); + + const x86 = analyzeProcedureHardwareInstructions({ + procedure: procId("early_io_and_pci", "0xfff00100"), + architecture: "x86_64", + instructions: [ + "0xfff00100: cli", + "0xfff00101: out 0x70, al", + "0xfff00103: in al, 0x60", + "0xfff00105: out 80h, al", + "0xfff00107: in al, 0EDh", + "0xfff00109: outb %al, $0x80", + "0xfff0010b: out #0x80, al", + "0xfff0010d: out 128, al", + "0xfff0010f: mov dx, 0xcf8", + "0xfff00113: out dx, eax", + "0xfff00114: mov dx, 0xcfc", + "0xfff00118: in eax, dx", + "0xfff00119: rdmsr", + "0xfff0011b: mov cr3, rax", + "0xfff0011e: movq %cr0, %rbx", + "0xfff00121: out PORT_DIAG, al", + ], + }); + expect(hardwareInstructionChannelsResultSchema.safeParse(x86).success).toBe( + true, + ); + expect(x86.matched_instruction_count).toBe(14); + expect(x86.channels[1]).toMatchObject({ + category: "port_io", + direction: "write", + target: "0x70", + target_description: "CMOS RAM / RTC Index (NMI Mask)", + target_basis: "architecture_manual", + }); + expect(x86.channels[2]).toMatchObject({ + category: "port_io", + direction: "read", + target: "0x60", + target_description: "8042 KBC / Embedded Controller Data", + target_basis: "architecture_manual", + }); + expect(x86.channels[3]).toMatchObject({ + category: "port_io", + direction: "write", + target: "0x80", + target_description: "BIOS POST Diagnostic Code Port", + target_basis: "architecture_manual", + }); + expect(x86.channels[4]).toMatchObject({ + category: "port_io", + direction: "read", + target: "0xed", + target_description: null, + target_basis: "immediate_constant", + }); + expect(x86.channels[5]).toMatchObject({ + target: "0x80", + target_basis: "architecture_manual", + }); + expect(x86.channels[6]).toMatchObject({ + target: "0x80", + target_basis: "architecture_manual", + }); + expect(x86.channels[7]).toMatchObject({ + target: "0x80", + target_basis: "architecture_manual", + }); + expect(x86.channels[8]).toMatchObject({ + raw_instruction: "0xfff00113: out dx, eax", + category: "port_io", + direction: "write", + target: null, + target_basis: "unresolved_register", + }); + expect(x86.channels[9]).toMatchObject({ + raw_instruction: "0xfff00118: in eax, dx", + category: "port_io", + direction: "read", + target: null, + target_basis: "unresolved_register", + }); + expect(x86.channels[11]).toMatchObject({ + category: "system_register", + direction: "write", + target: "CR3", + }); + expect(x86.channels[12]).toMatchObject({ + category: "system_register", + direction: "read", + target: "CR0", + }); + expect(x86.channels[13]).toMatchObject({ + raw_instruction: "0xfff00121: out PORT_DIAG, al", + category: "port_io", + direction: "write", + target: null, + target_basis: "unresolved_operand", + }); + // Only out dx, in dx, and rdmsr are register-selected; symbolic PORT_DIAG is unresolved_operand. + expect(x86.summary.unresolved_dynamic_count).toBe(3); + expect( + x86.limitations.some((l) => l.includes("general-purpose register")), + ).toBe(true); + expect( + x86.limitations.some((l) => + l.includes("symbolic or unparsed target operands"), + ), + ).toBe(true); + }); + + it("preserves space-qualified and percent-escaped native instruction addresses", () => { + const romX86 = analyzeProcedureHardwareInstructions({ + procedure: procId("rom_entry", "rom:0x1000"), + architecture: "x86", + instructions: ["rom:0x1000: cli", "rom:0x1001: hlt"], + }); + expect( + hardwareInstructionChannelsResultSchema.safeParse(romX86).success, + ).toBe(true); + expect(romX86.channels.map((c) => c.instruction_address)).toEqual([ + "rom:0x1000", + "rom:0x1001", + ]); + + const overlayArm = analyzeProcedureHardwareInstructions({ + procedure: procId("overlay_sleep", "overlay%3Aspace:0x1000"), + architecture: "arm", + instructions: [ + "overlay%3Aspace:0x1000: wfi", + "overlay%3aspace:0x1004: isb", + ], + }); + expect( + hardwareInstructionChannelsResultSchema.safeParse(overlayArm).success, + ).toBe(true); + expect(overlayArm.channels.map((c) => c.instruction_address)).toEqual([ + "overlay%3Aspace:0x1000", + "overlay%3Aspace:0x1004", + ]); + }); + + it("returns zero channels for pure ALU and memory load/store instructions", () => { + const pureAlu = analyzeProcedureHardwareInstructions({ + procedure: procId("memcpy_words", "0x1000"), + architecture: "arm", + instructions: [ + "0x1000: push {r4, lr}", + "0x1002: ldr r3, [r1], #4", + "0x1006: str r3, [r0], #4", + "0x100a: subs r2, r2, #1", + "0x100c: bne 0x1002", + "0x100e: pop {r4, pc}", + ], + }); + expect(pureAlu.matched_instruction_count).toBe(0); + expect(pureAlu.channels).toEqual([]); + }); +}); diff --git a/src/domain/firmware/hardwareInstructionChannels.ts b/src/domain/firmware/hardwareInstructionChannels.ts new file mode 100644 index 00000000000..2773e7beb22 --- /dev/null +++ b/src/domain/firmware/hardwareInstructionChannels.ts @@ -0,0 +1,105 @@ +import { z } from "zod"; +import { nativeAddressObservationSchema } from "../native/nativeAddress.js"; +import { nativeProcedureInputSchema } from "../native/nativeProcedureInput.js"; +import { procedureIdentitySchema } from "../native/procedureInfo.js"; + +export const HARDWARE_INSTRUCTION_ARCHITECTURES = [ + "arm", + "arm64", + "riscv", + "xtensa", + "mips", + "x86", + "x86_64", +] as const; + +export const hardwareInstructionArchitectureSchema = z.enum( + HARDWARE_INSTRUCTION_ARCHITECTURES, +); +export type HardwareInstructionArchitecture = z.infer< + typeof hardwareInstructionArchitectureSchema +>; + +export const inspectProcedureHardwareInstructionsInputSchema = + nativeProcedureInputSchema.extend({ + hardware_architecture: hardwareInstructionArchitectureSchema.describe( + "Explicit instruction-set family used to classify non-MMIO hardware instructions in the disassembled procedure.", + ), + }); + +export type InspectProcedureHardwareInstructionsInput = z.output< + typeof inspectProcedureHardwareInstructionsInputSchema +>; + +export const HARDWARE_CHANNEL_CATEGORIES = [ + "system_register", + "coprocessor", + "csr", + "special_register", + "port_io", + "interrupt_mask", + "memory_barrier", + "privilege_or_trap", + "power_or_wait", + "cache_or_tlb", +] as const; + +export const hardwareChannelCategorySchema = z.enum( + HARDWARE_CHANNEL_CATEGORIES, +); +export type HardwareChannelCategory = z.infer< + typeof hardwareChannelCategorySchema +>; + +export const hardwareChannelDirectionSchema = z.enum([ + "read", + "write", + "read_modify_write", + "control", +]); +export type HardwareChannelDirection = z.infer< + typeof hardwareChannelDirectionSchema +>; + +export const hardwareTargetBasisSchema = z.enum([ + "architecture_manual", + "immediate_constant", + "numeric_encoding", + "unresolved_register", + "unresolved_operand", + "not_applicable", +]); +export type HardwareTargetBasis = z.infer; + +export const hardwareInstructionChannelSchema = z.strictObject({ + instruction_index: z.number().int().min(0), + instruction_address: nativeAddressObservationSchema.nullable(), + raw_instruction: z.string(), + mnemonic: z.string(), + category: hardwareChannelCategorySchema, + direction: hardwareChannelDirectionSchema, + target: z.string().nullable(), + target_description: z.string().nullable(), + target_basis: hardwareTargetBasisSchema, +}); +export type HardwareInstructionChannel = z.infer< + typeof hardwareInstructionChannelSchema +>; + +export const hardwareInstructionChannelsResultSchema = z.strictObject({ + procedure: procedureIdentitySchema, + hardware_architecture: hardwareInstructionArchitectureSchema, + examined_instruction_count: z.number().int().min(0), + matched_instruction_count: z.number().int().min(0), + channels: z.array(hardwareInstructionChannelSchema), + summary: z.strictObject({ + by_category: z.record(z.string(), z.number().int().min(0)), + distinct_targets: z.array(z.string()), + unresolved_dynamic_count: z.number().int().min(0), + }), + limitations: z.array(z.string()), +}); + +export type HardwareInstructionChannelsResult = z.infer< + typeof hardwareInstructionChannelsResultSchema +>; diff --git a/src/domain/firmware/hardwareInstructionClassifiers.ts b/src/domain/firmware/hardwareInstructionClassifiers.ts new file mode 100644 index 00000000000..7fa97463d22 --- /dev/null +++ b/src/domain/firmware/hardwareInstructionClassifiers.ts @@ -0,0 +1,573 @@ +import { + OBSERVED_NATIVE_ADDRESS_PATTERN, + nativeAddressInputSchema, +} from "../native/nativeAddress.js"; +import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js"; +import type { + HardwareChannelCategory, + HardwareInstructionArchitecture, + HardwareInstructionChannel, + HardwareInstructionChannelsResult, +} from "./hardwareInstructionChannels.js"; +import { + classifyRiscvInstruction, + type ClassifiedInstruction, +} from "./hardwareInstructionRiscv.js"; +import { classifyX86Instruction } from "./hardwareInstructionX86.js"; + +const ARM_SYSREG_DESCRIPTIONS: Readonly> = { + MSP: "Main Stack Pointer", + PSP: "Process Stack Pointer", + MSPLIM: "Main Stack Pointer Limit Register", + PSPLIM: "Process Stack Pointer Limit Register", + PRIMASK: "Exception Priority Mask Register", + BASEPRI: "Base Priority Mask Register", + BASEPRI_MAX: "Base Priority Mask Conditional Write", + FAULTMASK: "Fault Mask Register", + CONTROL: "Special-Purpose Control Register", + IPSR: "Interrupt Program Status Register", + EPSR: "Execution Program Status Register", + APSR: "Application Program Status Register", + IAPSR: "Interrupt and Application Program Status Register", + EAPSR: "Execution and Application Program Status Register", + XPSR: "Combined Program Status Register", + CPSR: "Current Program Status Register", + SPSR: "Saved Program Status Register", + CURRENTEL: "Current Exception Level", + DAIF: "Interrupt Mask Bits (Debug, SError, IRQ, FIQ)", + DAIFSET: "Set DAIF Interrupt Mask Bits", + DAIFCLR: "Clear DAIF Interrupt Mask Bits", + NZCV: "Condition Flags", +}; + +const describeArmSystemReg = ( + raw: string, +): { + readonly target: string; + readonly description: string | null; + readonly basis: ClassifiedInstruction["target_basis"]; +} => { + const fullUpper = raw.toUpperCase(); + const upper = fullUpper.replace(/_NS$/u, ""); + const exact = ARM_SYSREG_DESCRIPTIONS[upper]; + if (exact !== undefined) { + return { + target: fullUpper, + description: fullUpper.endsWith("_NS") ? `${exact} (Non-secure)` : exact, + basis: "architecture_manual", + }; + } + const psrMaskMatch = /^(CPSR|SPSR|APSR|XPSR)_[CFXSNZQVGE]+$/u.exec(upper); + if (psrMaskMatch !== null) { + const baseDesc = ARM_SYSREG_DESCRIPTIONS[psrMaskMatch[1]!]!; + return { + target: fullUpper, + description: `${baseDesc} (${fullUpper})`, + basis: "architecture_manual", + }; + } + if ( + /^(?:SCTLR|VBAR|TTBR0|TTBR1|TCR|MAIR|ESR|FAR|ELR|SPSR|SCR|HCR|CPACR|SP|TPIDR)_EL[0-3]$/u.test( + fullUpper, + ) + ) { + return { + target: fullUpper, + description: `AArch64 System Register ${fullUpper}`, + basis: "architecture_manual", + }; + } + if (/^S[0-3]_[0-7]_C[0-9]+_C[0-9]+_[0-7]$/u.test(fullUpper)) { + return { target: fullUpper, description: null, basis: "numeric_encoding" }; + } + return { target: fullUpper, description: null, basis: "architecture_manual" }; +}; + +const ARM_SHARED_CONTROL_OPS: Readonly< + Record< + string, + { readonly category: HardwareChannelCategory; readonly description: string } + > +> = { + dsb: { + category: "memory_barrier", + description: "Data Synchronization Barrier", + }, + dmb: { category: "memory_barrier", description: "Data Memory Barrier" }, + isb: { + category: "memory_barrier", + description: "Instruction Synchronization Barrier", + }, + wfi: { category: "power_or_wait", description: "Wait For Interrupt" }, + wfe: { category: "power_or_wait", description: "Wait For Event" }, + sev: { category: "power_or_wait", description: "Send Event" }, + sevl: { category: "power_or_wait", description: "Send Event Local" }, + svc: { category: "privilege_or_trap", description: "Supervisor Call" }, + hvc: { category: "privilege_or_trap", description: "Hypervisor Call" }, + smc: { category: "privilege_or_trap", description: "Secure Monitor Call" }, + eret: { category: "privilege_or_trap", description: "Exception Return" }, +}; + +const ARM32_ONLY_CONTROL_OPS: Readonly< + Record< + string, + { readonly category: HardwareChannelCategory; readonly description: string } + > +> = { + swi: { category: "privilege_or_trap", description: "Supervisor Call" }, + bkpt: { category: "privilege_or_trap", description: "Software Breakpoint" }, +}; + +const ARM32_ROOT_PATTERN = + /^(dsb|dmb|isb|wfi|wfe|sevl|sev|svc|swi|hvc|smc|eret|bkpt|mrs|msr|cpsid|cpsie|mcrr2|mcrr|mrrc2|mrrc|mcr2|mcr|mrc2|mrc)(?:eq|ne|cs|hs|cc|lo|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al)?(?:\.[nw])?$/u; + +const ARM_COPROC_32_MNEMONICS: ReadonlySet = new Set([ + "mcr", + "mcr2", + "mrc", + "mrc2", +]); + +const ARM_COPROC_64_MNEMONICS: ReadonlySet = new Set([ + "mcrr", + "mcrr2", + "mrrc", + "mrrc2", +]); + +const ARM64_MAINT_MNEMONICS: ReadonlySet = new Set([ + "tlbi", + "ic", + "dc", + "at", +]); + +const normalizeCoprocOpcode = (raw: string): string => { + const stripped = raw.replace(/^#/u, "").trim(); + if (/^0x[0-9a-f]+$/iu.test(stripped)) { + return String(Number.parseInt(stripped.slice(2), 16)); + } + return stripped; +}; + +const normalizeCoprocReg = (raw: string): string => + raw + .trim() + .toLowerCase() + .replace(/^cr([0-9]+)$/u, "c$1"); + +const classifyArmCoprocessor = ( + mnemonic: string, + baseMnem: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + if (ARM_COPROC_32_MNEMONICS.has(baseMnem) && operands.length >= 5) { + const coproc = operands[0]!.toUpperCase(); + const opc1 = normalizeCoprocOpcode(operands[1]!); + const crn = normalizeCoprocReg(operands[3]!); + const crm = normalizeCoprocReg(operands[4]!); + const opc2 = normalizeCoprocOpcode(operands[5] ?? "0"); + const target = `${coproc}:${opc1},${crn},${crm},${opc2}`; + const description = + target === "P15:0,c1,c0,0" + ? "System Control Register (SCTLR)" + : target === "P15:0,c12,c0,0" + ? "Vector Base Address Register (VBAR)" + : `ARM Coprocessor ${target}`; + return { + mnemonic, + category: "coprocessor", + direction: baseMnem.startsWith("mrc") ? "read" : "write", + target, + target_description: description, + target_basis: "architecture_manual", + }; + } + if (ARM_COPROC_64_MNEMONICS.has(baseMnem) && operands.length >= 5) { + const coproc = operands[0]!.toUpperCase(); + const opc1 = normalizeCoprocOpcode(operands[1]!); + const crm = normalizeCoprocReg(operands[4]!); + const target = `${coproc}:${opc1},${crm}`; + return { + mnemonic, + category: "coprocessor", + direction: baseMnem.startsWith("mrrc") ? "read" : "write", + target, + target_description: `ARM 64-bit Coprocessor ${target}`, + target_basis: "architecture_manual", + }; + } + return null; +}; + +const classifyArmOrArm64 = ( + mnemonic: string, + operands: readonly string[], + isArm64: boolean, +): ClassifiedInstruction | null => { + let baseMnem = mnemonic; + if (!isArm64) { + const rootMatch = ARM32_ROOT_PATTERN.exec(mnemonic); + if (rootMatch === null) return null; + baseMnem = rootMatch[1]!; + } + + const fixed = isArm64 + ? baseMnem === "brk" + ? { + category: "privilege_or_trap" as const, + description: "AArch64 Breakpoint", + } + : ARM_SHARED_CONTROL_OPS[baseMnem] + : (ARM_SHARED_CONTROL_OPS[baseMnem] ?? ARM32_ONLY_CONTROL_OPS[baseMnem]); + if (fixed !== undefined) { + return { + mnemonic, + category: fixed.category, + direction: "control", + target: null, + target_description: fixed.description, + target_basis: "not_applicable", + }; + } + + if ((baseMnem === "mrs" || baseMnem === "msr") && operands.length >= 2) { + const isRead = baseMnem === "mrs"; + const reg = describeArmSystemReg(isRead ? operands[1]! : operands[0]!); + return { + mnemonic, + category: "system_register", + direction: isRead ? "read" : "write", + target: reg.target, + target_description: reg.description, + target_basis: reg.basis, + }; + } + + if (!isArm64 && (baseMnem === "cpsid" || baseMnem === "cpsie")) { + const flags = (operands[0] ?? "").toUpperCase() || "I"; + return { + mnemonic, + category: "interrupt_mask", + direction: "write", + target: `CPS:${flags}`, + target_description: + baseMnem === "cpsid" + ? `Disable interrupt mask (${flags})` + : `Enable interrupt mask (${flags})`, + target_basis: "architecture_manual", + }; + } + + if (!isArm64) return classifyArmCoprocessor(mnemonic, baseMnem, operands); + + if (ARM64_MAINT_MNEMONICS.has(baseMnem)) { + const op0 = operands[0]; + return { + mnemonic, + category: "cache_or_tlb", + direction: "control", + target: op0 !== undefined ? op0.toUpperCase() : null, + target_description: + baseMnem === "at" + ? "AArch64 AT address translation" + : `AArch64 ${baseMnem.toUpperCase()} maintenance`, + target_basis: + op0 !== undefined ? "architecture_manual" : "not_applicable", + }; + } + + return null; +}; + +const XTENSA_SR_BASES: Readonly< + Record +> = { + rsr: "read", + wsr: "write", + xsr: "read_modify_write", +}; + +const XTENSA_BARRIERS: ReadonlySet = new Set([ + "memw", + "extw", + "isync", + "dsync", + "esync", + "rsync", +]); + +const XTENSA_TRAPS: ReadonlySet = new Set([ + "rfe", + "rfi", + "syscall", + "break", +]); + +const classifyXtensa = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + const dotParts = mnemonic.split("."); + const srDir = XTENSA_SR_BASES[dotParts[0]!]; + if (srDir !== undefined) { + const srRaw = dotParts[1] ?? operands[1] ?? operands[0]; + if (srRaw === undefined || srRaw.length === 0) return null; + const sr = srRaw.toUpperCase(); + return { + mnemonic, + category: "special_register", + direction: srDir, + target: sr, + target_description: `Xtensa Special Register ${sr}`, + target_basis: /^[0-9]+$/u.test(sr) + ? "numeric_encoding" + : "architecture_manual", + }; + } + if (mnemonic === "rsil" || mnemonic === "waiti") { + return { + mnemonic, + category: mnemonic === "rsil" ? "interrupt_mask" : "power_or_wait", + direction: mnemonic === "rsil" ? "read_modify_write" : "control", + target: "PS.INTLEVEL", + target_description: + mnemonic === "rsil" + ? "Read and Set Xtensa Interrupt Level" + : "Wait for Interrupt at specified level", + target_basis: "architecture_manual", + }; + } + if (XTENSA_BARRIERS.has(mnemonic) || XTENSA_TRAPS.has(mnemonic)) { + return { + mnemonic, + category: XTENSA_BARRIERS.has(mnemonic) + ? "memory_barrier" + : "privilege_or_trap", + direction: "control", + target: null, + target_description: `Xtensa ${mnemonic.toUpperCase()}`, + target_basis: "not_applicable", + }; + } + return null; +}; + +const MIPS_CP0_MOVES: ReadonlySet = new Set([ + "mfc0", + "dmfc0", + "mtc0", + "dmtc0", +]); + +const MIPS_FIXED_OPS: Readonly< + Record< + string, + { readonly category: HardwareChannelCategory; readonly description: string } + > +> = { + eret: { category: "privilege_or_trap", description: "MIPS ERET" }, + deret: { category: "privilege_or_trap", description: "MIPS DERET" }, + syscall: { category: "privilege_or_trap", description: "MIPS SYSCALL" }, + sync: { category: "memory_barrier", description: "MIPS SYNC barrier" }, + ehb: { category: "memory_barrier", description: "MIPS EHB barrier" }, + wait: { category: "power_or_wait", description: "MIPS Wait for Interrupt" }, + cache: { category: "cache_or_tlb", description: "MIPS CACHE maintenance" }, + tlbwi: { category: "cache_or_tlb", description: "MIPS TLBWI maintenance" }, + tlbwr: { category: "cache_or_tlb", description: "MIPS TLBWR maintenance" }, + tlbr: { category: "cache_or_tlb", description: "MIPS TLBR maintenance" }, + tlbp: { category: "cache_or_tlb", description: "MIPS TLBP maintenance" }, +}; + +const classifyMips = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + if (MIPS_CP0_MOVES.has(mnemonic) && operands.length >= 2) { + const cp0Reg = operands[1]!.toUpperCase(); + const sel = operands[2] !== undefined ? `,${operands[2]}` : ""; + const target = `CP0:${cp0Reg}${sel}`; + return { + mnemonic, + category: "coprocessor", + direction: mnemonic.includes("mf") ? "read" : "write", + target, + target_description: `MIPS System Control Coprocessor (${target})`, + target_basis: "architecture_manual", + }; + } + if (mnemonic === "ei" || mnemonic === "di") { + return { + mnemonic, + category: "interrupt_mask", + direction: "read_modify_write", + target: "CP0:Status.IE", + target_description: + mnemonic === "di" + ? "Disable MIPS Global Interrupts" + : "Enable MIPS Global Interrupts", + target_basis: "architecture_manual", + }; + } + const fixed = MIPS_FIXED_OPS[mnemonic]; + if (fixed !== undefined) { + return { + mnemonic, + category: fixed.category, + direction: "control", + target: null, + target_description: fixed.description, + target_basis: "not_applicable", + }; + } + return null; +}; + +const parseLeadingNativeAddress = (token: string): string | null => { + if (OBSERVED_NATIVE_ADDRESS_PATTERN.test(token)) return token; + const parsed = nativeAddressInputSchema.safeParse(token); + return parsed.success ? parsed.data : null; +}; + +const parseInstructionLine = ( + rawLine: string, + arch: HardwareInstructionArchitecture, +): { + readonly address: string | null; + readonly mnemonic: string; + readonly operands: readonly string[]; +} | null => { + const withoutComment = rawLine + .replace(/(?:;|\/\/|#(?![0-9a-fxA-FX+-])).*$/u, "") + .trim(); + if (withoutComment.length === 0) return null; + + let address: string | null = null; + let body = withoutComment; + const firstSpace = withoutComment.search(/\s/u); + if (firstSpace === -1) { + if (withoutComment.endsWith(":")) return null; + } else { + const firstToken = withoutComment.slice(0, firstSpace); + const candidate = firstToken.endsWith(":") + ? firstToken.slice(0, -1) + : firstToken; + const parsedAddr = parseLeadingNativeAddress(candidate); + if (parsedAddr !== null) { + address = parsedAddr; + body = withoutComment.slice(firstSpace + 1).trim(); + } else if (firstToken.endsWith(":")) { + body = withoutComment.slice(firstSpace + 1).trim(); + } + } + if (body.length === 0) return null; + + if (arch === "x86" || arch === "x86_64") { + body = body.replace( + /^(?:(?:lock|rep|repe|repz|repne|repnz|data16)\s+)+/iu, + "", + ); + } + const spaceIdx = body.search(/\s/u); + const mnemonic = ( + spaceIdx === -1 ? body : body.slice(0, spaceIdx) + ).toLowerCase(); + if (mnemonic.length === 0) return null; + const operandStr = spaceIdx === -1 ? "" : body.slice(spaceIdx + 1).trim(); + const operands = + operandStr.length === 0 + ? [] + : operandStr + .split(",") + .map((tok) => tok.trim()) + .filter((tok) => tok.length > 0); + return { address, mnemonic, operands }; +}; + +const classifyByArch = ( + arch: HardwareInstructionArchitecture, + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + switch (arch) { + case "arm": + return classifyArmOrArm64(mnemonic, operands, false); + case "arm64": + return classifyArmOrArm64(mnemonic, operands, true); + case "riscv": + return classifyRiscvInstruction(mnemonic, operands); + case "xtensa": + return classifyXtensa(mnemonic, operands); + case "mips": + return classifyMips(mnemonic, operands); + case "x86": + case "x86_64": + return classifyX86Instruction(mnemonic, operands); + } +}; + +/** Extract non-MMIO architectural hardware channels from disassembled instructions. */ +export const analyzeProcedureHardwareInstructions = (options: { + readonly procedure: HardwareInstructionChannelsResult["procedure"]; + readonly architecture: HardwareInstructionArchitecture; + readonly instructions: readonly string[]; + readonly upstreamLimitations?: readonly string[] | undefined; +}): HardwareInstructionChannelsResult => { + const { procedure, architecture, instructions, upstreamLimitations } = + options; + const channels: HardwareInstructionChannel[] = []; + const byCategory: Record = {}; + const distinctTargets = new Set(); + // not-an-allowance: counts of register-indirect and symbolic/unparsed operand sites + let unresolvedDynamicCount = 0; + let unresolvedOperandCount = 0; + + for (let i = 0; i < instructions.length; i += 1) { + const raw = instructions[i]!; + const parsed = parseInstructionLine(raw, architecture); + if (parsed === null) continue; + const hit = classifyByArch(architecture, parsed.mnemonic, parsed.operands); + if (hit === null) continue; + byCategory[hit.category] = (byCategory[hit.category] ?? 0) + 1; + if (hit.target !== null) distinctTargets.add(hit.target); + if (hit.target_basis === "unresolved_register") unresolvedDynamicCount += 1; + if (hit.target_basis === "unresolved_operand") unresolvedOperandCount += 1; + channels.push({ + instruction_index: i, + instruction_address: parsed.address, + raw_instruction: raw, + mnemonic: hit.mnemonic, + category: hit.category, + direction: hit.direction, + target: hit.target, + target_description: hit.target_description, + target_basis: hit.target_basis, + }); + } + + const limitations = [...(upstreamLimitations ?? [])]; + if (unresolvedDynamicCount > 0) { + limitations.push( + `${String(unresolvedDynamicCount)} hardware instruction(s) select their port or register index dynamically through a general-purpose register (such as DX or ECX); use trace_native_values or analyze_function to inspect constant propagation.`, + ); + } + if (unresolvedOperandCount > 0) { + limitations.push( + `${String(unresolvedOperandCount)} hardware instruction(s) use symbolic or unparsed target operands that could not be normalized to an architectural constant or register; inspect raw_instruction for the provider's operand text.`, + ); + } + + return { + procedure, + hardware_architecture: architecture, + examined_instruction_count: instructions.length, + matched_instruction_count: channels.length, + channels, + summary: { + by_category: byCategory, + distinct_targets: [...distinctTargets].sort(compareUnicodeCodePoints), + unresolved_dynamic_count: unresolvedDynamicCount, + }, + limitations, + }; +}; diff --git a/src/domain/firmware/hardwareInstructionRiscv.ts b/src/domain/firmware/hardwareInstructionRiscv.ts new file mode 100644 index 00000000000..a855749fb27 --- /dev/null +++ b/src/domain/firmware/hardwareInstructionRiscv.ts @@ -0,0 +1,212 @@ +import type { + HardwareChannelCategory, + HardwareChannelDirection, + HardwareTargetBasis, +} from "./hardwareInstructionChannels.js"; + +export interface ClassifiedInstruction { + readonly mnemonic: string; + readonly category: HardwareChannelCategory; + readonly direction: HardwareChannelDirection; + readonly target: string | null; + readonly target_description: string | null; + readonly target_basis: HardwareTargetBasis; +} + +const RISCV_CSR_DESCRIPTIONS: Readonly> = { + mstatus: "Machine Status Register", + misa: "Machine ISA Register", + medeleg: "Machine Exception Delegation Register", + mideleg: "Machine Interrupt Delegation Register", + mie: "Machine Interrupt-Enable Register", + mtvec: "Machine Trap-Vector Base-Address Register", + mcounteren: "Machine Counter-Enable Register", + mscratch: "Machine Scratch Register", + mepc: "Machine Exception Program Counter", + mcause: "Machine Trap Cause Register", + mtval: "Machine Bad Address or Instruction", + mip: "Machine Interrupt-Pending Register", + mcycle: "Machine Cycle Counter", + minstret: "Machine Instructions-Retired Counter", + mhartid: "Hardware Thread ID", + sstatus: "Supervisor Status Register", + sie: "Supervisor Interrupt-Enable Register", + stvec: "Supervisor Trap-Vector Base-Address Register", + sscratch: "Supervisor Scratch Register", + sepc: "Supervisor Exception Program Counter", + scause: "Supervisor Trap Cause Register", + stval: "Supervisor Trap Value", + sip: "Supervisor Interrupt-Pending Register", + satp: "Supervisor Address Translation and Protection Register", + fcsr: "Floating-Point Control and Status Register", +}; + +const describeRiscvCsr = ( + rawCsr: string, +): { + readonly target: string; + readonly description: string | null; + readonly basis: HardwareTargetBasis; +} => { + const lower = rawCsr.toLowerCase(); + const known = RISCV_CSR_DESCRIPTIONS[lower]; + if (known !== undefined) { + return { target: lower, description: known, basis: "architecture_manual" }; + } + if (/^pmpcfg[0-9]+$/u.test(lower)) { + return { + target: lower, + description: "Physical Memory Protection Configuration", + basis: "architecture_manual", + }; + } + if (/^pmpaddr[0-9]+$/u.test(lower)) { + return { + target: lower, + description: "Physical Memory Protection Address", + basis: "architecture_manual", + }; + } + if (/^(?:0x[0-9a-f]+|[0-9]+)$/u.test(lower)) { + return { target: lower, description: null, basis: "numeric_encoding" }; + } + return { target: lower, description: null, basis: "architecture_manual" }; +}; + +const isZeroRegister = (operand: string | undefined): boolean => + operand !== undefined && /^(?:x0|zero)$/iu.test(operand.trim()); + +const isZeroImmediate = (operand: string | undefined): boolean => + operand !== undefined && /^[#$]?(?:0x0+|0+)$/iu.test(operand.trim()); + +const RISCV_EXPLICIT_CSR_OPS: ReadonlySet = new Set([ + "csrrw", + "csrrwi", + "csrrs", + "csrrsi", + "csrrc", + "csrrci", +]); + +const RISCV_PSEUDO_WRITE_SET_OPS: ReadonlySet = new Set([ + "csrw", + "csrwi", + "csrs", + "csrsi", + "csrc", + "csrci", +]); + +const RISCV_CONTROL_OPS: Readonly< + Record< + string, + { + readonly category: HardwareChannelCategory; + readonly description: string; + } + > +> = { + mret: { + category: "privilege_or_trap", + description: "Machine-mode Trap Return", + }, + sret: { + category: "privilege_or_trap", + description: "Supervisor-mode Trap Return", + }, + uret: { category: "privilege_or_trap", description: "User-mode Trap Return" }, + dret: { category: "privilege_or_trap", description: "Debug-mode Return" }, + ecall: { category: "privilege_or_trap", description: "Environment Call" }, + ebreak: { + category: "privilege_or_trap", + description: "Environment Breakpoint", + }, + "c.ebreak": { + category: "privilege_or_trap", + description: "Compressed Environment Breakpoint", + }, + wfi: { category: "power_or_wait", description: "Wait for Interrupt" }, + fence: { category: "memory_barrier", description: "Memory Ordering Fence" }, + "fence.i": { + category: "cache_or_tlb", + description: "Instruction-Stream Synchronization Fence", + }, + "sfence.vma": { + category: "cache_or_tlb", + description: "Supervisor Virtual-Memory Fence", + }, +}; + +export const classifyRiscvInstruction = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + const fixed = RISCV_CONTROL_OPS[mnemonic]; + if (fixed !== undefined) { + return { + mnemonic, + category: fixed.category, + direction: "control", + target: null, + target_description: fixed.description, + target_basis: "not_applicable", + }; + } + + if (RISCV_EXPLICIT_CSR_OPS.has(mnemonic) && operands.length >= 3) { + const csr = describeRiscvCsr(operands[1]!); + const isWriteSwap = mnemonic.startsWith("csrrw"); + const isImmediate = mnemonic.endsWith("i"); + let direction: HardwareChannelDirection = "read_modify_write"; + if (isWriteSwap && isZeroRegister(operands[0])) direction = "write"; + else if ( + !isWriteSwap && + (isImmediate ? isZeroImmediate(operands[2]) : isZeroRegister(operands[2])) + ) { + direction = "read"; + } + return { + mnemonic, + category: "csr", + direction, + target: csr.target, + target_description: csr.description, + target_basis: csr.basis, + }; + } + + if (mnemonic === "csrr" && operands[1] !== undefined) { + const csr = describeRiscvCsr(operands[1]); + return { + mnemonic, + category: "csr", + direction: "read", + target: csr.target, + target_description: csr.description, + target_basis: csr.basis, + }; + } + + if (RISCV_PSEUDO_WRITE_SET_OPS.has(mnemonic) && operands.length >= 2) { + const csr = describeRiscvCsr(operands[0]!); + let direction: HardwareChannelDirection = "read_modify_write"; + if (mnemonic.startsWith("csrw")) { + direction = "write"; + } else { + const zeroSource = mnemonic.endsWith("i") + ? isZeroImmediate(operands[1]) + : isZeroRegister(operands[1]); + if (zeroSource) direction = "read"; + } + return { + mnemonic, + category: "csr", + direction, + target: csr.target, + target_description: csr.description, + target_basis: csr.basis, + }; + } + + return null; +}; diff --git a/src/domain/firmware/hardwareInstructionX86.ts b/src/domain/firmware/hardwareInstructionX86.ts new file mode 100644 index 00000000000..e45057122de --- /dev/null +++ b/src/domain/firmware/hardwareInstructionX86.ts @@ -0,0 +1,362 @@ +import type { + HardwareChannelCategory, + HardwareChannelDirection, + HardwareTargetBasis, +} from "./hardwareInstructionChannels.js"; +import type { ClassifiedInstruction } from "./hardwareInstructionRiscv.js"; + +/** + * Architectural 8-bit x86 I/O ports reachable through immediate `IN`/`OUT` + * (`imm8`, `0x00..0xff`). 16-bit ports above `0xff` (such as `0x3f8` UART or + * `0xcf8`/`0xcfc` PCI configuration space) must be selected through `DX`. + */ +const X86_KNOWN_IMM8_PORTS: Readonly> = { + 0x20: "8259A Master PIC Command", + 0x21: "8259A Master PIC Data / IMR", + 0x40: "8254 PIT Channel 0", + 0x43: "8254 PIT Mode/Command", + 0x60: "8042 KBC / Embedded Controller Data", + 0x61: "PC Speaker / NMI Status and Control", + 0x64: "8042 KBC / Embedded Controller Command-Status", + 0x70: "CMOS RAM / RTC Index (NMI Mask)", + 0x71: "CMOS RAM / RTC Data", + 0x80: "BIOS POST Diagnostic Code Port", + 0x92: "System Control Port A (Fast A20 / Init)", + 0xa0: "8259A Slave PIC Command", + 0xa1: "8259A Slave PIC Data / IMR", + 0xb2: "APM / SMI Command Port (APM_CNT)", + 0xb3: "APM / SMI Status Port (APM_STS)", +}; + +const parseImmediatePortValue = (token: string): number | null => { + const literal = token.replace(/^[$#]\s*/u, ""); + const hexPrefix = /^0x([0-9a-f]+)$/iu.exec(literal); + if (hexPrefix !== null) return Number.parseInt(hexPrefix[1]!, 16); + const hexSuffix = /^([0-9][0-9a-f]*)h$/iu.exec(literal); + if (hexSuffix !== null) return Number.parseInt(hexSuffix[1]!, 16); + if (/^[0-9]+$/u.test(literal)) return Number.parseInt(literal, 10); + return null; +}; + +const parseX86PortOperand = ( + raw: string, +): { + readonly target: string | null; + readonly description: string | null; + readonly basis: HardwareTargetBasis; +} => { + const trimmed = raw.trim(); + if (/^(?:\(\s*%?dx\s*\)|%?dx)$/iu.test(trimmed)) { + return { + target: null, + description: "Dynamic 16-bit I/O port in DX", + basis: "unresolved_register", + }; + } + const num = parseImmediatePortValue(trimmed); + if (num !== null && Number.isSafeInteger(num) && num >= 0 && num <= 0xff) { + const hex = `0x${num.toString(16)}`; + const known = X86_KNOWN_IMM8_PORTS[num] ?? null; + return { + target: hex, + description: known, + basis: known !== null ? "architecture_manual" : "immediate_constant", + }; + } + return { target: null, description: null, basis: "unresolved_operand" }; +}; + +const X86_SIMPLE_OPS: Readonly< + Record< + string, + { + readonly category: HardwareChannelCategory; + readonly direction: HardwareChannelDirection; + readonly target: string | null; + readonly description: string; + readonly basis: HardwareTargetBasis; + } + > +> = { + cli: { + category: "interrupt_mask", + direction: "write", + target: "IF", + description: "Clear Interrupt Flag (disable maskable interrupts)", + basis: "architecture_manual", + }, + sti: { + category: "interrupt_mask", + direction: "write", + target: "IF", + description: "Set Interrupt Flag (enable maskable interrupts)", + basis: "architecture_manual", + }, + rdmsr: { + category: "system_register", + direction: "read", + target: null, + description: "Read Model-Specific Register indexed by ECX", + basis: "unresolved_register", + }, + wrmsr: { + category: "system_register", + direction: "write", + target: null, + description: "Write Model-Specific Register indexed by ECX", + basis: "unresolved_register", + }, + rdtsc: { + category: "system_register", + direction: "read", + target: "TSC", + description: "Read Time-Stamp Counter", + basis: "architecture_manual", + }, + rdtscp: { + category: "system_register", + direction: "read", + target: "TSC", + description: "Read Time-Stamp Counter and Processor ID", + basis: "architecture_manual", + }, + xgetbv: { + category: "system_register", + direction: "read", + target: "XCR", + description: "Read Extended Control Register indexed by ECX", + basis: "unresolved_register", + }, + xsetbv: { + category: "system_register", + direction: "write", + target: "XCR", + description: "Write Extended Control Register indexed by ECX", + basis: "unresolved_register", + }, + cpuid: { + category: "privilege_or_trap", + direction: "read", + target: "CPUID", + description: "CPU Identification leaf query", + basis: "architecture_manual", + }, + wbinvd: { + category: "cache_or_tlb", + direction: "control", + target: null, + description: "Write Back and Invalidate Cache", + basis: "not_applicable", + }, + invd: { + category: "cache_or_tlb", + direction: "control", + target: null, + description: "Invalidate Internal Caches", + basis: "not_applicable", + }, + invlpg: { + category: "cache_or_tlb", + direction: "control", + target: null, + description: "Invalidate TLB Entry", + basis: "not_applicable", + }, + mfence: { + category: "memory_barrier", + direction: "control", + target: null, + description: "Memory Fence", + basis: "not_applicable", + }, + lfence: { + category: "memory_barrier", + direction: "control", + target: null, + description: "Load Fence", + basis: "not_applicable", + }, + sfence: { + category: "memory_barrier", + direction: "control", + target: null, + description: "Store Fence", + basis: "not_applicable", + }, + hlt: { + category: "power_or_wait", + direction: "control", + target: null, + description: "Halt until next external interrupt", + basis: "not_applicable", + }, + rsm: { + category: "privilege_or_trap", + direction: "control", + target: "SMM", + description: "Resume from System Management Mode", + basis: "architecture_manual", + }, + syscall: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Fast System Call", + basis: "not_applicable", + }, + sysret: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Return from Fast System Call", + basis: "not_applicable", + }, + iret: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Interrupt Return", + basis: "not_applicable", + }, + iretd: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Interrupt Return (32-bit)", + basis: "not_applicable", + }, + iretq: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Interrupt Return (64-bit)", + basis: "not_applicable", + }, + vmcall: { + category: "privilege_or_trap", + direction: "control", + target: null, + description: "Call to VM Monitor (Hypercall)", + basis: "not_applicable", + }, +}; + +const classifyX86ControlRegMove = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + if (!/^mov[lq]?$/u.test(mnemonic) || operands.length < 2) return null; + const op0 = operands[0]!.replace(/^%/u, "").toLowerCase(); + const op1 = operands[1]!.replace(/^%/u, "").toLowerCase(); + const isAtt = operands[0]!.startsWith("%") || operands[1]!.startsWith("%"); + const regPattern = /^(?:cr[02348]|dr[0-7])$/u; + if (regPattern.test(op0)) { + return { + mnemonic, + category: "system_register", + direction: isAtt ? "read" : "write", + target: op0.toUpperCase(), + target_description: op0.startsWith("cr") + ? `x86 Control Register ${op0.toUpperCase()}` + : `x86 Debug Register ${op0.toUpperCase()}`, + target_basis: "architecture_manual", + }; + } + if (regPattern.test(op1)) { + return { + mnemonic, + category: "system_register", + direction: isAtt ? "write" : "read", + target: op1.toUpperCase(), + target_description: op1.startsWith("cr") + ? `x86 Control Register ${op1.toUpperCase()}` + : `x86 Debug Register ${op1.toUpperCase()}`, + target_basis: "architecture_manual", + }; + } + return null; +}; + +const classifyX86PortIo = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + if (/^(?:in|in[bwl])$/u.test(mnemonic) && operands.length >= 2) { + const isAtt = + operands[0]!.startsWith("$") || + operands[0]!.startsWith("(") || + operands[1]!.startsWith("%"); + const port = parseX86PortOperand(isAtt ? operands[0]! : operands[1]!); + return { + mnemonic, + category: "port_io", + direction: "read", + target: port.target, + target_description: port.description, + target_basis: port.basis, + }; + } + if (/^(?:out|out[bwl])$/u.test(mnemonic) && operands.length >= 2) { + const isAtt = + operands[1]!.startsWith("$") || + operands[1]!.startsWith("(") || + operands[0]!.startsWith("%"); + const port = parseX86PortOperand(isAtt ? operands[1]! : operands[0]!); + return { + mnemonic, + category: "port_io", + direction: "write", + target: port.target, + target_description: port.description, + target_basis: port.basis, + }; + } + if (/^(?:ins|outs)[bwdl]?$/u.test(mnemonic)) { + return { + mnemonic, + category: "port_io", + direction: mnemonic.startsWith("ins") ? "read" : "write", + target: null, + target_description: "String I/O port indexed by DX", + target_basis: "unresolved_register", + }; + } + return null; +}; + +export const classifyX86Instruction = ( + mnemonic: string, + operands: readonly string[], +): ClassifiedInstruction | null => { + const simple = X86_SIMPLE_OPS[mnemonic]; + if (simple !== undefined) { + return { + mnemonic, + category: simple.category, + direction: simple.direction, + target: simple.target, + target_description: simple.description, + target_basis: simple.basis, + }; + } + + const crMove = classifyX86ControlRegMove(mnemonic, operands); + if (crMove !== null) return crMove; + + const portIo = classifyX86PortIo(mnemonic, operands); + if (portIo !== null) return portIo; + + if (/^(?:lgdt|lidt|sgdt|sidt|ltr|lldt)$/u.test(mnemonic)) { + const table = mnemonic.slice(1).toUpperCase(); + return { + mnemonic, + category: "system_register", + direction: mnemonic.startsWith("l") ? "write" : "read", + target: table, + target_description: `Descriptor Table Register (${table})`, + target_basis: "architecture_manual", + }; + } + + return null; +}; diff --git a/src/domain/inputArgumentGuidance.ts b/src/domain/inputArgumentGuidance.ts index b5958f887e5..2e855282b6f 100644 --- a/src/domain/inputArgumentGuidance.ts +++ b/src/domain/inputArgumentGuidance.ts @@ -11,6 +11,7 @@ const PROCEDURE_OPERATIONS: ReadonlySet = new Set([ "analyze_function", "annotate_native_function", "inspect_native_api", + "inspect_procedure_hardware_instructions", "procedure_address", "procedure_assembly", "procedure_callees", diff --git a/src/server/sessionToolBindings.ts b/src/server/sessionToolBindings.ts index d90ff0d43d1..fe99e91a24f 100644 --- a/src/server/sessionToolBindings.ts +++ b/src/server/sessionToolBindings.ts @@ -570,6 +570,16 @@ export const bindEnhancedWorkflowTools = ({ request, ), }, + inspect_procedure_hardware_instructions: { + admission: "sdk", + analyze: (input, analysis, request) => + executeSessionWorkflowEvidence( + { name: "inspect_procedure_hardware_instructions", input }, + analysis, + session, + request, + ), + }, trace_feature: { admission: "sdk", detail: "delivery", diff --git a/tests/boundary/mcp/hardwareInstructionChannelsMcpCli.test.ts b/tests/boundary/mcp/hardwareInstructionChannelsMcpCli.test.ts new file mode 100644 index 00000000000..229a00f39c4 --- /dev/null +++ b/tests/boundary/mcp/hardwareInstructionChannelsMcpCli.test.ts @@ -0,0 +1,163 @@ +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { describe, expect, it, onTestFinished } from "vitest"; +import { runDirectAnalysis } from "../../../src/application/DirectAnalysis.js"; +import type { DirectAnalysisDependencies } from "../../../src/application/DirectAnalysisDependencies.js"; +import { CLI_COMMAND_REGISTRATIONS } from "../../../src/cli/cliCommandRegistrations.js"; +import { createCliShell } from "../../../src/cli/cliShell.js"; +import * as coreAnalysisModule from "../../../src/cli/coreAnalysisCommands.js"; +import { parseConfig } from "../../../src/config/parseConfig.js"; +import { ok } from "../../../src/domain/result.js"; +import { silentLogger } from "../../../src/logger.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { observed } from "../../fixtures/analysisExecution.js"; +import { + createBinarySessionTargets, + createTestBinarySession, +} from "../../fixtures/binarySession.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; + +describe("inspect_procedure_hardware_instructions CLI and MCP parity", () => { + it("executes over advertised MCP session and public CLI with Evidence linkage", async () => { + const [targetPath] = await createBinarySessionTargets(); + const clientFactory = () => ({ + execute: async (operation: string) => { + if (operation === "health") return observed({ ok: true }); + if (operation === "read_function_instructions") { + return observed({ + procedure: { + name: "SystemInit", + address: "0x08000200", + classification: null, + body: { available: false, reason: "fixture" }, + }, + instructions: [ + "0x08000200: cpsid i", + "0x08000202: mrs r0, control", + "0x08000206: msr basepri, r1", + "0x0800020a: dsb sy", + "0x0800020e: isb", + ], + limitations: [], + }); + } + throw new Error(`Unexpected provider operation: ${operation}`); + }, + close: async () => ok(null), + }); + + const session = createTestBinarySession(clientFactory); + const opened = await session.open(targetPath); + expect(opened.ok).toBe(true); + + const server = createServer( + { kind: "session", session }, + { environment: {}, logger: silentLogger }, + ); + const client = new Client( + { name: "hw-insn-test", version: "1" }, + { jsonSchemaValidator: createMcpSchemaValidation() }, + ); + onTestFinished(async () => { + await client.close(); + await server.close(); + await session.close(); + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + + const mcpRes = await client.callTool({ + name: "inspect_procedure_hardware_instructions", + arguments: { + procedure: "SystemInit", + hardware_architecture: "arm", + }, + }); + expect(mcpRes.isError).not.toBe(true); + const mcpStructured = mcpRes.structuredContent as { + parameters: Record; + normalized_result: { + matched_instruction_count: number; + summary: { distinct_targets: string[] }; + }; + evidence_links: string[]; + }; + expect(mcpStructured.parameters).toEqual({ + procedure: "SystemInit", + hardware_architecture: "arm", + }); + expect(mcpStructured.normalized_result.matched_instruction_count).toBe(5); + expect(mcpStructured.normalized_result.summary.distinct_targets).toEqual([ + "BASEPRI", + "CONTROL", + "CPS:I", + ]); + expect(mcpStructured.evidence_links.length).toBeGreaterThanOrEqual(1); + + const deps: DirectAnalysisDependencies = { + readConfiguration: () => parseConfig({}), + createBinarySession: () => createTestBinarySession(clientFactory), + createNativeDispatchBinarySession: () => + createTestBinarySession(clientFactory), + createArtifactBinarySession: () => createTestBinarySession(clientFactory), + createNativeBinarySession: () => createTestBinarySession(clientFactory), + createManagedBinarySession: () => { + throw new Error("Unexpected managed session"); + }, + }; + + const cli = createCliShell({ + selectedEnvironment: {}, + registrations: [ + { + registration: CLI_COMMAND_REGISTRATIONS.coreAnalysis, + module: coreAnalysisModule, + }, + ], + createAnalysis: () => ({ + runDirectAnalysis: (p, tool, args, opts) => + runDirectAnalysis(deps, p, tool, args, opts), + runProviderAnalysis: () => { + throw new Error("Unexpected provider analysis"); + }, + runManagedProviderEvidence: () => { + throw new Error("Unexpected managed provider evidence"); + }, + runSessionStatus: () => { + throw new Error("Unexpected session status"); + }, + }), + }); + + let cliStdout = ""; + let cliExitCode = 0; + await cli.serve( + [ + "inspect-procedure-hardware-instructions", + targetPath, + "SystemInit", + "--hardware-architecture", + "arm", + "--format", + "json", + ], + { + env: {}, + exit: (code) => { + cliExitCode = code; + }, + stdout: (chunk) => { + cliStdout += chunk; + }, + }, + ); + expect(cliExitCode).toBe(0); + const cliParsed = JSON.parse(cliStdout) as { + normalized_result: typeof mcpStructured.normalized_result; + }; + expect(cliParsed.normalized_result).toEqual( + mcpStructured.normalized_result, + ); + }); +});