Files
reverse-engineering-anything/src/composition/capabilityServices.ts
T
0af842ad26 feat(firmware): disassemble RISC-V, MIPS32, PowerPC, and ARM64 split-immediate MMIO accesses (#15413)
* feat(firmware): disassemble RISC-V, MIPS32, PowerPC, and ARM64 split-immediate MMIO accesses

* fix(firmware): tighten SVD interval inheritance and split-immediate register tracking

* fix(firmware): bound inherited SVD block expansion and decode exact destination GPRs

* fix(firmware): clear Rs across acquire-ordered ARM64 CAS and CASP variants

* chore(mcp): sync advertised schema summary and budget projection with main

* fix(firmware): bound CMSIS-SVD numeric widths before BigInt and index expansion

* fix(firmware): keep rejected SVD addressBlocks distinct from omitted spans

* fix(firmware): bound MMIO representation growth and preserve SVD ambiguity

* perf(firmware): memoize SVD address lookups and pre-rank peripheral names

* fix(firmware): scan a whole application image by default for MMIO syntheses

On the 1.36 MB IROM segment of the MicroPython 1.24.1 ESP32-C3 image, a
default call scanned 256 KiB and kept 512 of 713 matching accesses. The
omitted rows were not in the retained Evidence, so the agent had to repeat
the call with larger controls or page by scan_offset. Defaults now scan
4 MiB and keep up to 32,768 syntheses within a 16 MiB representation
allowance, matching the literal-pool tool. Retained summary delivery still
sizes what reaches the agent. The image completes in about 1 s with 4,073
syntheses.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* refactor(firmware): use MMIO synthesis maximums as their defaults directly

The default scan, synthesis and representation constants only repeated
their maximums, which Knip reports as duplicate exports. The budgets and
the parser fallback now name the maximums.

Co-Authored-By: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>

* fix(firmware): bound SVD match cache weight, exclude RISC-V flash, and report scan-limit stops

---------

Co-authored-by: gensokyo-dev <gensokyo-dev@users.noreply.github.com>
Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
2026-12-03 17:22:49 +08:00

855 lines
35 KiB
TypeScript

import type { RequestAnalysisPort } from "../ports/AnalysisProvider.js";
import type { ApktoolRequest } from "../domain/apktool/apktoolResourceAnalysis.js";
import type { FlutterRequest } from "../domain/flutter/flutterBuildAnalysis.js";
import type { PcapRequest } from "../domain/pcap/pcapAnalysis.js";
import type { AdbRequest } from "../domain/adb/adbDeviceAnalysis.js";
import { createUefiAnalysisService } from "../application/ProviderOperationServices.js";
import type { UefiAnalysisPort } from "../ports/uefi/UefiAnalysisPort.js";
import { createUefiAnalysisProvider } from "./uefi.js";
import type { OptionalProviderLoadFailures } from "../ports/OptionalObservationProviders.js";
import {
locateWiresharkTool,
selectWiresharkTool,
} from "../pcap/PcapConfiguration.js";
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
import { CapabilityScope } from "../application/CapabilityScope.js";
import type {
CapabilityAvailabilityFacts,
OptionalAvailabilityFeatures,
} from "../application/CapabilityAvailability.js";
import {
CAPABILITY_DECLARATIONS,
type CapabilityDeclarationId,
} from "./capabilityDeclarations.js";
import { isAbsolute } from "node:path";
import { createGpuCodeObjectsService } from "./gpu.js";
import { createPacketCaptureService } from "./captures.js";
import { tsharkHostSupported } from "../captures/TsharkCaptureProvider.js";
import { createSignalRecordingService } from "./signals.js";
import { sigrokHostSupported } from "../signals/SigrokRecordingProvider.js";
import { wasmArtifactModule } from "./wasm.js";
import { apkSignatureModule } from "./apkSignature.js";
import { evmInterfaceModule } from "./evm.js";
import {
evmHostSupported,
evmLimiterAvailability,
} from "../evm/EvmoleInterfaceProvider.js";
import { createSqliteDatabaseService } from "./sqlite.js";
import { createDesktopApplicationService } from "./desktop.js";
import { DesktopBuildComputers } from "../application/desktop/DesktopBuildComputers.js";
import { readHostFile } from "../desktop/HostFileRead.js";
import { createGoBinaryService } from "./go.js";
import { createRustBinaryService } from "./rust.js";
import { createBeamService } from "./erlang.js";
import { createV8CodeCacheService } from "./v8CodeCache.js";
import { createMavenGradleMetadataService } from "./mavenGradleMetadata.js";
import { createModelArtifactService } from "./model.js";
import { createIl2cppMetadataService } from "./il2cpp.js";
import { createLabviewArtifactService } from "./labview.js";
import { createElectronFuseService } from "./electronFuses.js";
import { createReleaseExposureService } from "./releaseExposure.js";
import { createPythonPycService } from "./pythonPyc.js";
import { createDebPackageService } from "./debPackage.js";
import { createNugetNupkgService } from "./nugetNupkg.js";
import { createVsixPackageService } from "./vsixPackage.js";
import { createOciImageLayoutService } from "./ociImageLayout.js";
import { createYaraMatchesService } from "./yara.js";
import { createWebNetworkCaptureService } from "./webNetworkCaptures.js";
import { createWebSourceLocationService } from "./webSourceLocations.js";
import { createWebModuleTraceService } from "./webModules.js";
import { createWebRuntimeService } from "./webRuntime.js";
import { createJavaScriptRecoveryProvider } from "./javascriptRecovery.js";
import { wakaruHostSupported } from "../javascript/recovery/WakaruCommand.js";
import { ArtifactResourceScope } from "../resources/index.js";
import { createReverseEngineeringService } from "./reverseEngineering.js";
import type {
ReverseEngineeringService,
CommandProviderLaunchFailures,
} from "../application/reverse/ReverseEngineeringService.js";
import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysisService.js";
import { createFirmwareAnalysisProvider } from "./firmware.js";
import { firmwareHostSupported } from "../firmware/FirmwareCommand.js";
import { createAndroidAnalysisProvider } from "./android.js";
import { createPcapAnalysisProvider } from "./pcap.js";
import { createFlutterBuildAnalysisProvider } from "./flutter.js";
import { createApktoolResourceAnalysisProvider } from "./apktool.js";
import { createJebAnalysisProvider } from "./jeb.js";
import { createAdbDeviceAnalysisProvider } from "./adb.js";
import { createFridaInstrumentationProvider } from "./frida.js";
import { createCutterBridgeService } from "./cutter.js";
import {
createGdbSessionManager,
createRizinDebugSessionManager,
} from "./debuggerSessions.js";
import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js";
import { pcapCaptureHostSupported } from "../domain/pcap/pcapAnalysis.js";
import { createPeLoadConfigService } from "./binaryDiagnostics/peLoadConfig.js";
import { createPeUnwindRangesService } from "./binaryDiagnostics/peUnwindRanges.js";
import { createMachoFunctionStartsService } from "./binaryDiagnostics/machoFunctionStarts.js";
import { createPeOverlayService } from "./binaryDiagnostics/peOverlay.js";
import { createBinaryHardeningService } from "./binaryDiagnostics/binaryHardening.js";
import { createPeCertificatesService } from "./binaryDiagnostics/peCertificates.js";
import { createPeImportsService } from "./binaryDiagnostics/peImports.js";
import { createNativeExportsService } from "./binaryDiagnostics/nativeExports.js";
import { createPeResourcesService } from "./binaryDiagnostics/peResources.js";
import { createWindowsShortcutService } from "./binaryDiagnostics/windowsShortcut.js";
import { createFirmwareArchitectureCandidatesService } from "./binaryDiagnostics/firmwareArchitectureCandidates.js";
import { createRecordedCrashService } from "./binaryDiagnostics/recordedCrash.js";
import { createBinaryLayoutService } from "./binaryDiagnostics/binaryLayout.js";
import { createDevicetreeService } from "./binaryDiagnostics/devicetree.js";
import { createEspNvsService } from "./binaryDiagnostics/espNvs.js";
import { createFirmwareLiteralPoolsService } from "./binaryDiagnostics/firmwareLiteralPools.js";
import { createFirmwareMmioSynthesisService } from "./binaryDiagnostics/firmwareMmioSynthesis.js";
import { createFirmwareVectorTableService } from "./binaryDiagnostics/firmwareVectorTable.js";
import { createElfNotesService } from "./binaryDiagnostics/elfNotes.js";
import { createDwarfUnitsService } from "./binaryDiagnostics/dwarfUnits.js";
import { createElfDebugLinkService } from "./binaryDiagnostics/elfDebugLink.js";
import { createNativeInitializersService } from "./binaryDiagnostics/nativeInitializers.js";
import { createElfUnwindRangesService } from "./binaryDiagnostics/elfUnwindRanges.js";
import { createAppleIpsService } from "./binaryDiagnostics/appleIps.js";
import { createKernelModuleService } from "./binaryDiagnostics/kernelModule.js";
import { createElfDependenciesService } from "./binaryDiagnostics/elfDependencies.js";
import { createKernelBuildConfigService } from "./binaryDiagnostics/kernelBuildConfig.js";
import { pwntoolsHostSupported } from "../native/pwntools/PwntoolsDecoder.js";
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
import type { ApkSignatureService } from "../application/apkSignature/ApkSignatureService.js";
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js";
import type { Il2cppMetadataService } from "../application/il2cpp/Il2cppMetadataService.js";
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
import type { ElectronFuseService } from "../application/electron/ElectronFuseService.js";
import type { RustBinaryService } from "../application/rust/RustBinaryService.js";
import type { PythonPycService } from "../application/python/PythonPycService.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";
import type { OciImageLayoutService } from "../application/oci/OciImageLayoutService.js";
import type { YaraMatchesService } from "../application/yara/YaraMatchesService.js";
import type { BeamService } from "../application/erlang/BeamService.js";
import type { V8CodeCacheService } from "../application/v8CodeCache/V8CodeCacheService.js";
import type { MavenGradleMetadataService } from "../application/java/MavenGradleMetadataService.js";
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import type { BrowserObservationPort } from "../ports/BrowserObservationPort.js";
import type { BrowserScenarioCapturePort } from "../ports/BrowserScenarioCapturePort.js";
import type { ElectronActiveObservationPort } from "../ports/javascript/ElectronActiveObservationPort.js";
import type { ElectronObservationPort } from "../ports/javascript/ElectronObservationPort.js";
import type { JavaScriptRuntimeObservationPort } from "../ports/javascript/JavaScriptRuntimeObservationPort.js";
import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js";
import type { WebModuleTraceService } from "../application/WebModuleTraceService.js";
import type { WebSourceLocationService } from "../application/WebSourceLocationService.js";
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
import type { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
import type { JavaScriptRecoveryPort } from "../ports/javascript/JavaScriptRecoveryPort.js";
import type { FirmwareAnalysisPort } from "../ports/firmware/FirmwareAnalysisPort.js";
import type { AndroidAnalysisPort } from "../ports/android/AndroidAnalysisPort.js";
import type { JebAnalysisPort } from "../ports/jeb/JebAnalysisPort.js";
import type { BuildSettle } from "../application/desktop/DesktopBuildSettle.js";
import type { BuildComputerDefaults } from "../desktop/BuildComputerEnvironment.js";
import type { ComputerStartTiming } from "../desktop/AgentEnvComputer.js";
/** Typed injection inputs shared by a capability host, independent of transport. */
export interface CapabilityServiceOptions {
readonly packetCapture?: PacketCaptureService;
readonly signalRecording?: SignalRecordingService;
readonly wasmArtifact?: WasmArtifactService;
readonly apkSignature?: ApkSignatureService;
readonly evmInterface?: EvmInterfaceService;
readonly sqliteDatabase?: SqliteDatabaseService;
readonly binaryLayout?: BinaryLayoutService;
readonly goBinary?: GoBinaryService;
readonly il2cppMetadata?: Il2cppMetadataService;
readonly rustBinary?: RustBinaryService;
readonly pythonPyc?: PythonPycService;
readonly debPackage?: DebPackageService;
readonly nugetNupkg?: NugetNupkgService;
readonly vsixPackage?: VsixPackageService;
readonly ociImageLayout?: OciImageLayoutService;
readonly yaraMatches?: YaraMatchesService;
readonly erlangBeam?: BeamService;
readonly v8CodeCache?: V8CodeCacheService;
readonly mavenGradleMetadata?: MavenGradleMetadataService;
readonly electronFuses?: ElectronFuseService;
readonly recordedCrash?: RecordedCrashService;
readonly uefiAnalysis?: UefiAnalysisPort;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
readonly javascriptRecovery?: JavaScriptRecoveryPort;
readonly webModuleTrace?: WebModuleTraceService;
readonly webSourceLocation?: WebSourceLocationService;
readonly webRuntime?: WebRuntimeService;
readonly webNetworkCapture?: WebNetworkCaptureService;
readonly androidAnalysis?: AndroidAnalysisPort;
readonly apktoolAnalysis?: RequestAnalysisPort<ApktoolRequest>;
readonly pcapAnalysis?: RequestAnalysisPort<PcapRequest>;
readonly flutterAnalysis?: RequestAnalysisPort<FlutterRequest>;
readonly jebAnalysis?: JebAnalysisPort;
readonly adbDeviceAnalysis?: RequestAnalysisPort<AdbRequest>;
readonly browserObservation?: BrowserObservationPort;
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
readonly electronObservation?: ElectronObservationPort;
readonly optionalObservationProviderOwner?: "server" | "caller";
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
readonly electronActiveObservation?: ElectronActiveObservationPort;
readonly javascriptRuntimeObservation?: JavaScriptRuntimeObservationPort;
readonly fridaInstrumentation?: FridaInstrumentationPort;
/** How build computers read an app until its files settle; the shipped timing on real time unless a test shortens or clocks it. */
readonly desktopBuildSettle?: BuildSettle;
/** Where build computers look for unset settings; the host's PATH and REA cache unless a test isolates them. */
readonly desktopBuildDefaults?: BuildComputerDefaults;
/** How long a build computer waits for its desktop to draw and how often its start reports progress; the shipped timing unless a test shortens it. */
readonly desktopBuildStartTiming?: ComputerStartTiming;
readonly reverseEngineering?: ReverseEngineeringService;
}
// Reuse a PATH probe for bursts of status calls and recheck installs/removals.
const TSHARK_AVAILABILITY_CACHE_MS = 1_000;
const tsharkLocatable = (environment: Readonly<NodeJS.ProcessEnv>): boolean => {
try {
return (
locateWiresharkTool(
selectWiresharkTool(environment, "tshark"),
environment,
) !== undefined
);
} catch {
// A relative REA_TSHARK_COMMAND is configuration the tool reports at execution.
return false;
}
};
export interface CapabilityHostContext {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly providerEnvironment: Readonly<NodeJS.ProcessEnv>;
readonly settings: AnalysisSettingsReader;
readonly options: CapabilityServiceOptions;
readonly platform: NodeJS.Platform;
readonly arch: NodeJS.Architecture;
}
interface CapabilityInstance<Value> {
readonly value: Value;
readonly close: () => Promise<void>;
readonly ownership: "host" | "caller";
readonly availability?: CapabilityAvailabilityFacts;
}
const capability =
<Value>(
create: (context: CapabilityHostContext) => Value,
close: (value: Value) => Promise<void>,
observe?: (
context: CapabilityHostContext,
value: Value,
) => CapabilityAvailabilityFacts,
ownership: (context: CapabilityHostContext) => "host" | "caller" = () =>
"host",
) =>
(context: CapabilityHostContext): CapabilityInstance<Value> => {
const value = create(context);
return {
value,
close: () => close(value),
ownership: ownership(context),
...(observe === undefined
? {}
: { availability: observe(context, value) }),
};
};
const service = <Value extends { close(): Promise<void> }>(
create: (context: CapabilityHostContext) => Value,
observe?: (
context: CapabilityHostContext,
value: Value,
) => CapabilityAvailabilityFacts,
) => capability(create, (value) => value.close(), observe);
const outsideHost = (injected: unknown, supported: boolean): boolean =>
injected === undefined && !supported;
const configuredPwntools = (context: CapabilityHostContext): boolean =>
pwntoolsHostSupported(context.platform, context.arch) &&
isAbsolute(context.environment.REA_PWNTOOLS_PYTHON ?? "");
const sharedObservationOwnership = (context: CapabilityHostContext) =>
context.options.optionalObservationProviderOwner === "caller"
? "caller"
: "host";
const closeObservation = (value: { close?: () => Promise<void> } | undefined) =>
value?.close?.() ?? Promise.resolve();
/** Each entry binds construction, ownership and observed availability once. */
const modules = {
wasmArtifact: service(
({ environment, options, settings }) =>
wasmArtifactModule.create(environment, options.wasmArtifact, settings),
({ environment, options }) => ({
optionalFeatures: {
wasmArtifactEnabled:
options.wasmArtifact !== undefined ||
isAbsolute(environment.REA_WABT_BIN_DIRECTORY ?? ""),
},
}),
),
apkSignature: service(({ environment, options }) =>
apkSignatureModule.create(environment, options.apkSignature),
),
evmInterface: service(
({ environment, options, platform, arch }) =>
options.evmInterface ??
evmInterfaceModule.create(environment, { platform, architecture: arch }),
({ environment, options, platform, arch }) => ({
hostUnsupported: {
evmInterface: outsideHost(
options.evmInterface,
evmHostSupported(platform, arch),
),
},
optionalFeatures: {
evmInterfaceEnabled:
options.evmInterface !== undefined ||
evmHostSupported(platform, arch),
},
...(options.evmInterface !== undefined ||
!evmHostSupported(platform, arch)
? {}
: {
probes: {
evmLimiterAvailability: (signal: AbortSignal) =>
evmLimiterAvailability(environment, { platform, arch, signal }),
},
}),
}),
),
sqliteDatabase: service(
({ environment, options }) =>
options.sqliteDatabase ?? createSqliteDatabaseService(environment),
),
binaryLayout: service(
({ environment, options, platform, arch }) =>
options.binaryLayout ??
createBinaryLayoutService(environment, { platform, architecture: arch }),
(context) => ({
hostUnsupported: {
binaryLayout: outsideHost(
context.options.binaryLayout,
pwntoolsHostSupported(context.platform, context.arch),
),
},
optionalFeatures: {
binaryLayoutEnabled:
context.options.binaryLayout !== undefined ||
configuredPwntools(context),
},
}),
),
recordedCrash: service(
({ environment, options, platform, arch }) =>
options.recordedCrash ??
createRecordedCrashService(environment, {
platform,
architecture: arch,
}),
(context) => ({
hostUnsupported: {
recordedCrash: outsideHost(
context.options.recordedCrash,
pwntoolsHostSupported(context.platform, context.arch),
),
},
optionalFeatures: {
recordedCrashEnabled:
context.options.recordedCrash !== undefined ||
configuredPwntools(context),
},
}),
),
webSourceLocation: service(
({ environment, options }) =>
options.webSourceLocation ??
createWebSourceLocationService(environment, true),
),
webModuleTrace: service(
({ environment, options }) =>
options.webModuleTrace ?? createWebModuleTraceService(environment),
({ environment, options }) => ({
optionalFeatures: {
webModuleResolutionEnabled:
options.webModuleTrace !== undefined ||
isAbsolute(environment.REA_BROWSER_EXECUTABLE ?? ""),
},
}),
),
desktopApplication: service(() => createDesktopApplicationService()),
desktopBuildComputers: capability(
({ providerEnvironment, options }) =>
new DesktopBuildComputers(
providerEnvironment,
readHostFile,
options.desktopBuildSettle,
options.desktopBuildDefaults,
options.desktopBuildStartTiming,
),
(value) => value.closeAll(),
),
goBinary: service(
({ options }) => options.goBinary ?? createGoBinaryService(),
),
rustBinary: service(
({ options }) => options.rustBinary ?? createRustBinaryService(),
),
erlangBeam: service(
({ options }) => options.erlangBeam ?? createBeamService(),
),
v8CodeCache: service(
({ options }) => options.v8CodeCache ?? createV8CodeCacheService(),
),
mavenGradleMetadata: service(
({ options }) =>
options.mavenGradleMetadata ?? createMavenGradleMetadataService(),
),
modelArtifact: service(() => createModelArtifactService()),
gpuCodeObjects: service(() => createGpuCodeObjectsService()),
il2cppMetadata: service(
({ options }) => options.il2cppMetadata ?? createIl2cppMetadataService(),
),
peResources: service(() => createPeResourcesService()),
labviewArtifact: service(() => createLabviewArtifactService()),
nativeExports: service(() => createNativeExportsService()),
devicetree: service(() => createDevicetreeService()),
espNvs: service(() => createEspNvsService()),
firmwareLiteralPools: service(() => createFirmwareLiteralPoolsService()),
firmwareMmioSynthesis: service(() => createFirmwareMmioSynthesisService()),
firmwareVectorTable: service(() => createFirmwareVectorTableService()),
elfNotes: service(() => createElfNotesService()),
dwarfUnits: service(() => createDwarfUnitsService()),
elfDebugLink: service(() => createElfDebugLinkService()),
nativeInitializers: service(() => createNativeInitializersService()),
elfUnwindRanges: service(() => createElfUnwindRangesService()),
appleIps: service(() => createAppleIpsService()),
kernelModule: service(() => createKernelModuleService()),
elfDependencies: service(() => createElfDependenciesService()),
kernelBuildConfig: service(() => createKernelBuildConfigService()),
peLoadConfig: service(() => createPeLoadConfigService()),
peOverlay: service(() => createPeOverlayService()),
peUnwindRanges: service(() => createPeUnwindRangesService()),
machoFunctionStarts: service(() => createMachoFunctionStartsService()),
binaryHardening: service(() => createBinaryHardeningService()),
peCertificates: service(() => createPeCertificatesService()),
peImports: service(() => createPeImportsService()),
windowsShortcut: service(() => createWindowsShortcutService()),
firmwareArchitectureCandidates: service(() =>
createFirmwareArchitectureCandidatesService(),
),
electronFuses: service(
({ options }) => options.electronFuses ?? createElectronFuseService(),
),
releaseExposure: service(({ environment, settings }) =>
createReleaseExposureService(environment, settings),
),
pythonPyc: service(
({ options }) => options.pythonPyc ?? createPythonPycService(),
),
debPackage: service(
({ options }) => options.debPackage ?? createDebPackageService(),
),
nugetNupkg: service(
({ options }) => options.nugetNupkg ?? createNugetNupkgService(),
),
vsixPackage: service(
({ options }) => options.vsixPackage ?? createVsixPackageService(),
),
ociImageLayout: service(
({ options }) => options.ociImageLayout ?? createOciImageLayoutService(),
),
yaraMatches: service(
({ environment, options, platform, settings }) =>
options.yaraMatches ??
createYaraMatchesService(environment, settings, platform),
),
webNetworkCapture: service(
({ environment, options, settings }) =>
options.webNetworkCapture ??
createWebNetworkCaptureService(environment, settings),
),
javascriptRecovery: capability(
({ environment, options, platform, arch }) =>
options.javascriptRecovery ??
createJavaScriptRecoveryProvider(environment, undefined, {
platform,
architecture: arch,
}),
(value) => value.close?.() ?? Promise.resolve(),
({ environment, options, platform, arch }) => ({
hostUnsupported: {
javascriptRecovery: outsideHost(
options.javascriptRecovery,
wakaruHostSupported(platform, arch),
),
},
optionalFeatures: {
javascriptRecoveryEnabled:
options.javascriptRecovery !== undefined ||
(wakaruHostSupported(platform, arch) &&
isAbsolute(environment.REA_WAKARU_COMMAND ?? "")),
},
}),
),
artifactResources: service(() => new ArtifactResourceScope()),
reverseEngineering: service(
({ providerEnvironment, options }) =>
options.reverseEngineering ??
createReverseEngineeringService(providerEnvironment),
(_context, value) => ({
observeCommandProviderFailures: () => value.observedLaunchFailures(),
}),
),
firmwareAnalysis: service(
({ environment, options, platform, arch }) =>
new FirmwareAnalysisService(
options.firmwareAnalysis ??
createFirmwareAnalysisProvider(environment, undefined, {
platform,
architecture: arch,
}),
),
({ environment, options, platform }) => ({
hostUnsupported: {
firmwareInspection: outsideHost(
options.firmwareAnalysis,
firmwareHostSupported(platform),
),
firmwareExtraction: outsideHost(
options.firmwareAnalysis,
firmwareHostSupported(platform),
),
},
optionalFeatures: {
firmwareInspectionEnabled:
options.firmwareAnalysis !== undefined ||
(firmwareHostSupported(platform) &&
isAbsolute(environment.REA_BINWALK_COMMAND ?? "")),
firmwareExtractionEnabled:
options.firmwareAnalysis !== undefined ||
(firmwareHostSupported(platform) &&
isAbsolute(environment.REA_UNBLOB_COMMAND ?? "")),
},
}),
),
uefiAnalysis: service(({ options }) =>
createUefiAnalysisService(
options.uefiAnalysis ?? createUefiAnalysisProvider(),
),
),
gdbSessions: capability(
({ providerEnvironment, platform }) =>
createGdbSessionManager(providerEnvironment, { platform }),
(value) => value.closeAll(),
({ platform }) => ({
hostUnsupported: {
persistentDebugger: !persistentDebuggerHostSupported(platform),
},
}),
),
rizinDebugSessions: capability(
({ providerEnvironment, platform }) =>
createRizinDebugSessionManager(providerEnvironment, { platform }),
(value) => value.closeAll(),
),
android: service(
({ environment, options, settings }) =>
options.androidAnalysis ??
createAndroidAnalysisProvider(environment, undefined, settings),
(_context, value) => ({
probes: {
androidAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
pcap: service(
({ environment, options, platform }) =>
options.pcapAnalysis ?? createPcapAnalysisProvider(environment, platform),
({ options, platform }) => ({
hostUnsupported: {
pcapCapture: outsideHost(
options.pcapAnalysis,
pcapCaptureHostSupported(platform),
),
},
}),
),
flutter: service(
({ environment, options, settings }) =>
options.flutterAnalysis ??
createFlutterBuildAnalysisProvider(environment, settings),
),
fridaInstrumentation: capability(
({ options }) =>
options.fridaInstrumentation ?? createFridaInstrumentationProvider(),
(value) => value.closeAll(),
({ options }, value) => ({
observeProviderLoadFailures: () => {
const failure =
options.optionalProviderLoadFailures?.fridaInstrumentation ??
value.availabilityFailure?.();
return failure === undefined ? {} : { fridaInstrumentation: failure };
},
}),
),
packetCapture: service(
({ environment, options, platform }) =>
options.packetCapture ??
createPacketCaptureService(environment, platform),
({ environment, options, platform }) => {
let cached:
| {
readonly command: string | undefined;
readonly path: string | undefined;
readonly pathExt: string | undefined;
readonly locatable: boolean;
readonly expiresAt: number;
}
| undefined;
const locatable = (): boolean => {
const command = environment.REA_TSHARK_COMMAND;
const path = environment.PATH;
const pathExt = environment.PATHEXT;
const now = performance.now();
if (
cached === undefined ||
cached.command !== command ||
cached.path !== path ||
cached.pathExt !== pathExt ||
now >= cached.expiresAt
) {
cached = {
command,
path,
pathExt,
locatable: tsharkLocatable(environment),
expiresAt: now + TSHARK_AVAILABILITY_CACHE_MS,
};
}
return cached.locatable;
};
return {
hostUnsupported: {
packetCapture: outsideHost(
options.packetCapture,
tsharkHostSupported(platform),
),
},
// Probe PATH only when `binary_session` queries default availability.
observeOptionalFeatures: () => ({
packetCaptureEnabled:
options.packetCapture !== undefined ||
(tsharkHostSupported(platform) && locatable()),
}),
};
},
),
signalRecording: service(
({ environment, options, platform }) =>
options.signalRecording ??
createSignalRecordingService(environment, platform),
({ environment, options, platform }) => ({
hostUnsupported: {
signalRecording: outsideHost(
options.signalRecording,
sigrokHostSupported(platform),
),
},
optionalFeatures: {
signalRecordingEnabled:
options.signalRecording !== undefined ||
(sigrokHostSupported(platform) &&
isAbsolute(environment.REA_SIGROK_COMMAND ?? "")),
},
}),
),
webRuntime: capability(
({ options }) => options.webRuntime ?? createWebRuntimeService(),
(value) => value.provider.close?.() ?? Promise.resolve(),
),
apktool: service(
({ environment, options, platform }) =>
options.apktoolAnalysis ??
createApktoolResourceAnalysisProvider(environment, platform),
(_context, value) => ({
probes: {
apktoolAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
jeb: service(
({ environment, options }) =>
options.jebAnalysis ?? createJebAnalysisProvider(environment),
(_context, value) => ({
probes: {
jebAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
adbDevice: service(
({ environment, options, platform }) =>
options.adbDeviceAnalysis ??
createAdbDeviceAnalysisProvider(environment, platform),
(_context, value) => ({
probes: {
adbAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
cutter: service(({ providerEnvironment, settings }) =>
createCutterBridgeService(providerEnvironment, { read: settings }),
),
browserObservation: capability(
({ options }) => options.browserObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
browserObservationEnabled: options.browserObservation !== undefined,
},
}),
sharedObservationOwnership,
),
browserScenarioCapture: capability(
({ options }) => options.browserScenarioCapture,
closeObservation,
({ options }) => ({
optionalFeatures: {
browserScenarioEnabled: options.browserScenarioCapture !== undefined,
},
}),
sharedObservationOwnership,
),
electronObservation: capability(
({ options }) => options.electronObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
electronObservationEnabled: options.electronObservation !== undefined,
},
}),
sharedObservationOwnership,
),
electronActiveObservation: capability(
({ options }) => options.electronActiveObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
electronAutomationEnabled:
options.electronActiveObservation !== undefined,
},
}),
sharedObservationOwnership,
),
javascriptRuntimeObservation: capability(
({ options }) => options.javascriptRuntimeObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
v8InspectorObservationEnabled:
options.javascriptRuntimeObservation !== undefined,
},
}),
sharedObservationOwnership,
),
} satisfies Partial<
Record<
CapabilityDeclarationId,
(context: CapabilityHostContext) => CapabilityInstance<unknown>
>
>;
export type CapabilityServices = {
readonly [Key in keyof typeof modules]: ReturnType<
(typeof modules)[Key]
>["value"];
};
/** Compose every service and its cleanup together, retaining precise typed ports. */
export const createCapabilityServices = (context: CapabilityHostContext) => {
const scope = new CapabilityScope();
const hostUnsupported: NonNullable<
CapabilityAvailabilityFacts["hostUnsupported"]
> = {};
const optionalFeatures: NonNullable<
CapabilityAvailabilityFacts["optionalFeatures"]
> = {};
const probes: NonNullable<CapabilityAvailabilityFacts["probes"]> = {};
const failureObservers: (() => OptionalProviderLoadFailures)[] = [];
const commandFailureObservers: (() => CommandProviderLaunchFailures)[] = [];
const optionalFeatureObservers: (() => Partial<OptionalAvailabilityFeatures>)[] =
[];
const availability = { hostUnsupported, optionalFeatures };
// This is a key-preserving map of a source-owned typed declaration, not an
// external value parser or a generic operation dispatcher.
const services = Object.fromEntries(
Object.entries(modules).map(([id, create]) => {
const instance = create(context);
const declaration = CAPABILITY_DECLARATIONS[id as keyof typeof modules];
if (declaration === undefined)
throw new Error(`Undeclared capability ${id}`);
Object.assign(
availability.hostUnsupported,
instance.availability?.hostUnsupported,
);
Object.assign(
availability.optionalFeatures,
instance.availability?.optionalFeatures,
);
Object.assign(probes, instance.availability?.probes);
const observeFailure = instance.availability?.observeProviderLoadFailures;
if (observeFailure !== undefined) failureObservers.push(observeFailure);
const observeCommandFailure =
instance.availability?.observeCommandProviderFailures;
if (observeCommandFailure !== undefined)
commandFailureObservers.push(observeCommandFailure);
const observeOptional = instance.availability?.observeOptionalFeatures;
if (observeOptional !== undefined)
optionalFeatureObservers.push(observeOptional);
return [
id,
instance.ownership === "host"
? scope.own(id, instance.value, instance.close)
: instance.value,
];
}),
) as CapabilityServices;
return {
services,
availability,
probes,
observeProviderLoadFailures: (): OptionalProviderLoadFailures =>
Object.assign({}, ...failureObservers.map((observe) => observe())),
observeCommandProviderFailures: (): CommandProviderLaunchFailures =>
Object.assign({}, ...commandFailureObservers.map((observe) => observe())),
observeOptionalFeatures: (): Partial<OptionalAvailabilityFeatures> =>
Object.assign(
{},
...optionalFeatureObservers.map((observe) => observe()),
),
createManagedBinarySession: async () => {
const { createManagedBinarySession } = await import("./binary.js");
return createManagedBinarySession();
},
createArtifactPathInspection: async () => {
const { createArtifactPathInspection } =
await import("./artifactSession.js");
return createArtifactPathInspection(
context.providerEnvironment,
context.platform,
context.settings,
);
},
close: () => scope.close(),
};
};