hfim-cli 1.15.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (288) hide show
  1. fim/__init__.py +42 -0
  2. fim/analysis/__init__.py +53 -0
  3. fim/analysis/burst_sdc.py +160 -0
  4. fim/analysis/classifier.py +924 -0
  5. fim/analysis/comparator.py +738 -0
  6. fim/analysis/consolidate.py +625 -0
  7. fim/analysis/csv_io.py +28 -0
  8. fim/analysis/ecc_quartet.py +167 -0
  9. fim/analysis/nvm_endurance_matrix.py +170 -0
  10. fim/analysis/observable_state.py +945 -0
  11. fim/analysis/reporter.py +712 -0
  12. fim/analysis/results_txt.py +229 -0
  13. fim/campaigns/__init__.py +28 -0
  14. fim/campaigns/base_campaign.py +5151 -0
  15. fim/campaigns/cache_campaign.py +233 -0
  16. fim/campaigns/campaign_view.py +135 -0
  17. fim/campaigns/csr_campaign.py +31 -0
  18. fim/campaigns/fault_plan.py +105 -0
  19. fim/campaigns/faultlist_builder.py +503 -0
  20. fim/campaigns/gem5_parallel_runner.py +210 -0
  21. fim/campaigns/golden_gate.py +158 -0
  22. fim/campaigns/injection_point_selector.py +473 -0
  23. fim/campaigns/memory_campaign.py +686 -0
  24. fim/campaigns/parallel_runner.py +510 -0
  25. fim/campaigns/register_campaign.py +617 -0
  26. fim/campaigns/serial_feeder.py +169 -0
  27. fim/cli.py +2652 -0
  28. fim/configs/benchmarks/bitcount.yaml +11 -0
  29. fim/configs/benchmarks/checksum.yaml +11 -0
  30. fim/configs/benchmarks/dotprod_f64.yaml +12 -0
  31. fim/configs/benchmarks/fibonacci.yaml +10 -0
  32. fim/configs/boards/board_spec_schema.yaml +216 -0
  33. fim/configs/boards/raspberry_pi_5.yaml +122 -0
  34. fim/configs/boards/xuantie_c906.yaml +127 -0
  35. fim/configs/boards/xuantie_c906_ruby_nvmain.yaml +85 -0
  36. fim/configs/dramsim3/DDR3_1Gb_x8_1333.ini +69 -0
  37. fim/configs/dramsim3/DDR3_4Gb_x16_1600.ini +67 -0
  38. fim/configs/dramsim3/DDR3_4Gb_x16_1866.ini +67 -0
  39. fim/configs/dramsim3/DDR3_4Gb_x4_1600.ini +67 -0
  40. fim/configs/dramsim3/DDR3_4Gb_x4_1866.ini +67 -0
  41. fim/configs/dramsim3/DDR3_4Gb_x8_1600.ini +67 -0
  42. fim/configs/dramsim3/DDR3_4Gb_x8_1866.ini +67 -0
  43. fim/configs/dramsim3/DDR3_8Gb_x16_1600.ini +67 -0
  44. fim/configs/dramsim3/DDR3_8Gb_x16_1866.ini +67 -0
  45. fim/configs/dramsim3/DDR3_8Gb_x4_1600.ini +67 -0
  46. fim/configs/dramsim3/DDR3_8Gb_x4_1866.ini +67 -0
  47. fim/configs/dramsim3/DDR3_8Gb_x8_1600.ini +67 -0
  48. fim/configs/dramsim3/DDR3_8Gb_x8_1866.ini +67 -0
  49. fim/configs/dramsim3/DDR4_4Gb_x16_1866.ini +67 -0
  50. fim/configs/dramsim3/DDR4_4Gb_x16_2133.ini +67 -0
  51. fim/configs/dramsim3/DDR4_4Gb_x16_2133_2.ini +67 -0
  52. fim/configs/dramsim3/DDR4_4Gb_x16_2400.ini +67 -0
  53. fim/configs/dramsim3/DDR4_4Gb_x16_2400_2.ini +67 -0
  54. fim/configs/dramsim3/DDR4_4Gb_x16_2666.ini +67 -0
  55. fim/configs/dramsim3/DDR4_4Gb_x16_2666_2.ini +67 -0
  56. fim/configs/dramsim3/DDR4_4Gb_x4_1866.ini +67 -0
  57. fim/configs/dramsim3/DDR4_4Gb_x4_2133.ini +67 -0
  58. fim/configs/dramsim3/DDR4_4Gb_x4_2133_2.ini +67 -0
  59. fim/configs/dramsim3/DDR4_4Gb_x4_2400.ini +67 -0
  60. fim/configs/dramsim3/DDR4_4Gb_x4_2400_2.ini +67 -0
  61. fim/configs/dramsim3/DDR4_4Gb_x4_2666.ini +67 -0
  62. fim/configs/dramsim3/DDR4_4Gb_x4_2666_2.ini +67 -0
  63. fim/configs/dramsim3/DDR4_4Gb_x8_1866.ini +67 -0
  64. fim/configs/dramsim3/DDR4_4Gb_x8_2133.ini +67 -0
  65. fim/configs/dramsim3/DDR4_4Gb_x8_2133_2.ini +67 -0
  66. fim/configs/dramsim3/DDR4_4Gb_x8_2400.ini +67 -0
  67. fim/configs/dramsim3/DDR4_4Gb_x8_2400_2.ini +67 -0
  68. fim/configs/dramsim3/DDR4_4Gb_x8_2666.ini +67 -0
  69. fim/configs/dramsim3/DDR4_4Gb_x8_2666_2.ini +67 -0
  70. fim/configs/dramsim3/DDR4_8Gb_x16_1866.ini +67 -0
  71. fim/configs/dramsim3/DDR4_8Gb_x16_2133.ini +67 -0
  72. fim/configs/dramsim3/DDR4_8Gb_x16_2133_2.ini +67 -0
  73. fim/configs/dramsim3/DDR4_8Gb_x16_2400.ini +67 -0
  74. fim/configs/dramsim3/DDR4_8Gb_x16_2400_2.ini +67 -0
  75. fim/configs/dramsim3/DDR4_8Gb_x16_2666.ini +67 -0
  76. fim/configs/dramsim3/DDR4_8Gb_x16_2666_2.ini +67 -0
  77. fim/configs/dramsim3/DDR4_8Gb_x16_2933.ini +67 -0
  78. fim/configs/dramsim3/DDR4_8Gb_x16_2933_2.ini +67 -0
  79. fim/configs/dramsim3/DDR4_8Gb_x16_3200.ini +67 -0
  80. fim/configs/dramsim3/DDR4_8Gb_x4_1866.ini +67 -0
  81. fim/configs/dramsim3/DDR4_8Gb_x4_2133.ini +67 -0
  82. fim/configs/dramsim3/DDR4_8Gb_x4_2133_2.ini +67 -0
  83. fim/configs/dramsim3/DDR4_8Gb_x4_2400.ini +67 -0
  84. fim/configs/dramsim3/DDR4_8Gb_x4_2400_2.ini +67 -0
  85. fim/configs/dramsim3/DDR4_8Gb_x4_2666.ini +67 -0
  86. fim/configs/dramsim3/DDR4_8Gb_x4_2666_2.ini +67 -0
  87. fim/configs/dramsim3/DDR4_8Gb_x4_2933.ini +67 -0
  88. fim/configs/dramsim3/DDR4_8Gb_x4_2933_2.ini +67 -0
  89. fim/configs/dramsim3/DDR4_8Gb_x4_3200.ini +67 -0
  90. fim/configs/dramsim3/DDR4_8Gb_x8_1866.ini +67 -0
  91. fim/configs/dramsim3/DDR4_8Gb_x8_2133.ini +67 -0
  92. fim/configs/dramsim3/DDR4_8Gb_x8_2133_2.ini +67 -0
  93. fim/configs/dramsim3/DDR4_8Gb_x8_2400.ini +77 -0
  94. fim/configs/dramsim3/DDR4_8Gb_x8_2400_2.ini +67 -0
  95. fim/configs/dramsim3/DDR4_8Gb_x8_2666.ini +67 -0
  96. fim/configs/dramsim3/DDR4_8Gb_x8_2666_2.ini +67 -0
  97. fim/configs/dramsim3/DDR4_8Gb_x8_2933.ini +67 -0
  98. fim/configs/dramsim3/DDR4_8Gb_x8_2933_2.ini +67 -0
  99. fim/configs/dramsim3/DDR4_8Gb_x8_3200.ini +67 -0
  100. fim/configs/ecc_policies/c906.yaml +26 -0
  101. fim/configs/matmul_aarch64.yaml +62 -0
  102. fim/configs/mcpat/c906.xml +481 -0
  103. fim/configs/mcpat/raspberry_pi_5.xml +405 -0
  104. fim/configs/mcpat/sTemplate.xml +444 -0
  105. fim/configs/mcpat/template.xml +405 -0
  106. fim/configs/mmult.yaml +140 -0
  107. fim/configs/mmult_memory_gem5.yaml +23 -0
  108. fim/configs/nvmain/2D_DRAM_example.config +249 -0
  109. fim/configs/nvmain/3D_DRAMCache_OffChipMemory_example.config +154 -0
  110. fim/configs/nvmain/3D_DRAMCache_example.config +275 -0
  111. fim/configs/nvmain/3D_DRAM_example.config +237 -0
  112. fim/configs/nvmain/3D_PredictorDRC_example.config +277 -0
  113. fim/configs/nvmain/3D_VariableDRC_example.config +278 -0
  114. fim/configs/nvmain/Hybrid_DRAM_channel.config +249 -0
  115. fim/configs/nvmain/Hybrid_NVM_channel.config +208 -0
  116. fim/configs/nvmain/Hybrid_NVM_channel_BitModel.config +208 -0
  117. fim/configs/nvmain/Hybrid_example.config +72 -0
  118. fim/configs/nvmain/Hybrid_example_BitModel.config +72 -0
  119. fim/configs/nvmain/PCM_ISSCC_2012_4GB.config +217 -0
  120. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel.config +217 -0
  121. fim/configs/nvmain/PCM_ISSCC_2012_4GB_BitModel_ECP.config +222 -0
  122. fim/configs/nvmain/PCM_ISSCC_2012_4GB_ByteModel.config +217 -0
  123. fim/configs/nvmain/PCM_ISSCC_2012_4GB_RowModel.config +217 -0
  124. fim/configs/nvmain/PCM_ISSCC_2012_4GB_WordModel.config +217 -0
  125. fim/configs/nvmain/PCM_MLC_estimated.config +233 -0
  126. fim/configs/nvmain/PCM_MLC_example.config +232 -0
  127. fim/configs/nvmain/PCM_MLC_example_BitModel.config +232 -0
  128. fim/configs/nvmain/PerfectMemory.config +229 -0
  129. fim/configs/nvmain/RRAM_ISSCC_2012_4GB.config +218 -0
  130. fim/configs/nvmain/STTRAM_Everspin_4GB.config +217 -0
  131. fim/configs/nvmain/STTRAM_Everspin_4GB_BitModel.config +217 -0
  132. fim/configs/nvmain/printtrace.config +145 -0
  133. fim/configs/nvmain/printtrace_bitflip.config +146 -0
  134. fim/configs/quicksort_dmr.yaml +225 -0
  135. fim/configs/rust_sort_array.yaml +28 -0
  136. fim/configs/rust_sort_bss.yaml +38 -0
  137. fim/configs/sum.yaml +149 -0
  138. fim/configs/template.yaml +418 -0
  139. fim/configs/toolchains.remote.json +14 -0
  140. fim/core/__init__.py +161 -0
  141. fim/core/artifacts/__init__.py +25 -0
  142. fim/core/artifacts/adapters/__init__.py +146 -0
  143. fim/core/artifacts/adapters/board.py +38 -0
  144. fim/core/artifacts/adapters/config.py +115 -0
  145. fim/core/artifacts/adapters/sdk.py +435 -0
  146. fim/core/artifacts/adapters/simulator.py +139 -0
  147. fim/core/artifacts/adapters/template.py +107 -0
  148. fim/core/artifacts/classification.py +95 -0
  149. fim/core/artifacts/hashing.py +265 -0
  150. fim/core/artifacts/inputs.py +179 -0
  151. fim/core/artifacts/records.py +238 -0
  152. fim/core/artifacts/retention.py +504 -0
  153. fim/core/artifacts/staleness.py +486 -0
  154. fim/core/artifacts/store.py +202 -0
  155. fim/core/artifacts/workspace.py +108 -0
  156. fim/core/checkpoint.py +338 -0
  157. fim/core/checkpoint_policy.py +171 -0
  158. fim/core/classifier_view.py +96 -0
  159. fim/core/clock_view.py +99 -0
  160. fim/core/configuration/__init__.py +13 -0
  161. fim/core/configuration/frozen.py +85 -0
  162. fim/core/configuration/groups.py +41 -0
  163. fim/core/configuration/includes.py +249 -0
  164. fim/core/configuration/lifecycle_rules.py +83 -0
  165. fim/core/configuration/reference.py +200 -0
  166. fim/core/configuration/reference_docs.py +344 -0
  167. fim/core/configuration/resolver.py +495 -0
  168. fim/core/configuration/run_context.py +51 -0
  169. fim/core/configuration/schema.py +784 -0
  170. fim/core/configuration/sources.py +121 -0
  171. fim/core/configuration/template_pins.py +79 -0
  172. fim/core/fault_models.py +261 -0
  173. fim/core/fim.py +452 -0
  174. fim/core/gdb_controller.py +2053 -0
  175. fim/core/gem5_controller.py +1226 -0
  176. fim/core/gem5_launch.py +489 -0
  177. fim/core/gem5_observable.py +202 -0
  178. fim/core/gem5_producers.py +684 -0
  179. fim/core/gem5_simulator.py +724 -0
  180. fim/core/golden_view.py +94 -0
  181. fim/core/hardware_cluster.py +236 -0
  182. fim/core/hardware_simulator.py +992 -0
  183. fim/core/hardware_spec.py +352 -0
  184. fim/core/hardware_station.py +374 -0
  185. fim/core/hardware_view.py +64 -0
  186. fim/core/hardware_window.py +102 -0
  187. fim/core/hook_view.py +52 -0
  188. fim/core/lifecycle.py +433 -0
  189. fim/core/machine_binding.py +317 -0
  190. fim/core/ovp_plan.py +419 -0
  191. fim/core/ovp_protocol.py +647 -0
  192. fim/core/ovp_simulator.py +1201 -0
  193. fim/core/ovp_view.py +99 -0
  194. fim/core/qemu_controller.py +1396 -0
  195. fim/core/qemu_launch.py +179 -0
  196. fim/core/qemu_simulator.py +329 -0
  197. fim/core/results_store.py +218 -0
  198. fim/core/results_view.py +94 -0
  199. fim/core/simulator_controller.py +298 -0
  200. fim/core/simulator_manifest.py +739 -0
  201. fim/core/station_host.py +277 -0
  202. fim/install/__init__.py +16 -0
  203. fim/install/ensure.py +182 -0
  204. fim/install/home.py +126 -0
  205. fim/install/index.py +122 -0
  206. fim/install/index.yaml +59 -0
  207. fim/install/prebuilt.py +120 -0
  208. fim/install/probes.py +182 -0
  209. fim/install/remote.py +165 -0
  210. fim/install/sdk.py +178 -0
  211. fim/install/setup.py +184 -0
  212. fim/install/simulators.py +323 -0
  213. fim/install/template.py +147 -0
  214. fim/install/uninstall.py +149 -0
  215. fim/provision/__init__.py +48 -0
  216. fim/provision/catalog.py +278 -0
  217. fim/provision/commands.py +1051 -0
  218. fim/provision/doctor.py +291 -0
  219. fim/provision/drain.py +117 -0
  220. fim/provision/forms/__init__.py +4 -0
  221. fim/provision/forms/docker.py +469 -0
  222. fim/provision/forms/fake.py +281 -0
  223. fim/provision/forms/native.py +438 -0
  224. fim/provision/fresh_layout.py +66 -0
  225. fim/provision/hostdeps.py +229 -0
  226. fim/provision/layout_units.py +148 -0
  227. fim/provision/lock.py +100 -0
  228. fim/provision/package.py +110 -0
  229. fim/provision/plan.py +356 -0
  230. fim/provision/privilege.py +259 -0
  231. fim/provision/probe.py +117 -0
  232. fim/provision/release.py +188 -0
  233. fim/provision/sdk.py +102 -0
  234. fim/provision/steps.py +324 -0
  235. fim/provision/switch.py +80 -0
  236. fim/provision/switch_recovery.py +165 -0
  237. fim/remote/__init__.py +15 -0
  238. fim/remote/access/__init__.py +203 -0
  239. fim/remote/access/credential.py +46 -0
  240. fim/remote/access/credentials/__init__.py +4 -0
  241. fim/remote/access/credentials/command.py +50 -0
  242. fim/remote/access/credentials/keychain.py +50 -0
  243. fim/remote/access/credentials/none.py +16 -0
  244. fim/remote/access/credentials/peer.py +25 -0
  245. fim/remote/access/credentials/token.py +50 -0
  246. fim/remote/access/spec.py +34 -0
  247. fim/remote/access/transport.py +66 -0
  248. fim/remote/access/transports/__init__.py +4 -0
  249. fim/remote/access/transports/command.py +222 -0
  250. fim/remote/access/transports/direct.py +39 -0
  251. fim/remote/access/transports/ssh_tunnel.py +74 -0
  252. fim/remote/api.py +245 -0
  253. fim/remote/commands.py +625 -0
  254. fim/remote/fetch.py +155 -0
  255. fim/remote/follow.py +157 -0
  256. fim/remote/journal.py +150 -0
  257. fim/remote/location.py +108 -0
  258. fim/remote/preflight.py +350 -0
  259. fim/remote/servers.py +159 -0
  260. fim/remote/snapshot.py +249 -0
  261. fim/remote/submit.py +302 -0
  262. fim/scripts/__init__.py +2 -0
  263. fim/scripts/generate_report.py +108 -0
  264. fim/scripts/run_campaign.py +1447 -0
  265. fim/scripts/run_ecc_quartet.py +94 -0
  266. fim/scripts/run_golden.py +2256 -0
  267. fim/scripts/verify_provenance.py +61 -0
  268. fim/utils/__init__.py +74 -0
  269. fim/utils/board.py +378 -0
  270. fim/utils/board_view.py +39 -0
  271. fim/utils/config.py +1714 -0
  272. fim/utils/coredump.py +28 -0
  273. fim/utils/elf_parser.py +1118 -0
  274. fim/utils/elf_provenance.py +140 -0
  275. fim/utils/injection_file_writer.py +309 -0
  276. fim/utils/logger.py +362 -0
  277. fim/utils/picker.py +195 -0
  278. fim/utils/prng.py +207 -0
  279. fim/utils/provenance.py +873 -0
  280. fim/utils/register_width.py +52 -0
  281. hfim_cli-1.15.6.data/data/share/hfim/gem5_to_mcpat.py +508 -0
  282. hfim_cli-1.15.6.dist-info/METADATA +131 -0
  283. hfim_cli-1.15.6.dist-info/RECORD +288 -0
  284. hfim_cli-1.15.6.dist-info/WHEEL +5 -0
  285. hfim_cli-1.15.6.dist-info/entry_points.txt +2 -0
  286. hfim_cli-1.15.6.dist-info/licenses/LICENSE +21 -0
  287. hfim_cli-1.15.6.dist-info/licenses/THIRD_PARTY_NOTICES +166 -0
  288. hfim_cli-1.15.6.dist-info/top_level.txt +1 -0
@@ -0,0 +1,179 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """The QEMU View.
5
+
6
+ Everything a QEMU launch takes from configuration, for the golden run and
7
+ every injection alike: the machine, the CPU, RAM, cores, how it boots, the
8
+ serial line and the extra arguments. The CPU and machine follow one chain:
9
+ the ELF's arch (a Build Output), then what the simulator package says its
10
+ build implements (Machine Binding), then a stated qemu_cpu / qemu_machine.
11
+ The campaign and the golden each wrote that chain out; qemu_launch() is
12
+ now its only copy.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass
18
+ from typing import Any, Dict, Mapping, Optional, Tuple
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class QemuLaunch:
23
+ machine: str
24
+ cpu: str
25
+ memory: str
26
+ serial_pty: bool
27
+ num_cores: int
28
+ firmware_path: Optional[str]
29
+ firmware_entry: Any
30
+ sd_image_path: Optional[str]
31
+ guest_uart_serial: Optional[str]
32
+ extra_args: Tuple[str, ...]
33
+ # One instruction per translation block for a run that stops at an
34
+ # instruction count (off with HFIM_NO_ONE_INSN_PER_TB=1, an Execution
35
+ # Setup Input of the Golden Record).
36
+ precise_stops: bool = True
37
+
38
+ def controller_kwargs(self) -> Dict[str, Any]:
39
+ """Keyword arguments for QEMUController(...)."""
40
+ return {
41
+ "machine": self.machine,
42
+ "cpu": self.cpu,
43
+ "memory": self.memory,
44
+ "serial_pty": self.serial_pty,
45
+ "num_cores": self.num_cores,
46
+ "firmware_path": self.firmware_path,
47
+ "firmware_entry": self.firmware_entry,
48
+ "sd_image_path": self.sd_image_path,
49
+ "guest_uart_serial": self.guest_uart_serial,
50
+ "extra_args": list(self.extra_args),
51
+ "precise_stops": self.precise_stops,
52
+ }
53
+
54
+
55
+ @dataclass(frozen=True)
56
+ class QemuSession:
57
+ """What QEMUSimulatorController.setup is given: its own keyword set
58
+ (qemu_binary, gdb_binary, benchmark_name, checkpoint_base_dir, snapshot
59
+ and plugin options) besides the Settings it shares with a campaign."""
60
+ elf_path: Optional[str]
61
+ qemu_binary: str
62
+ gdb_binary: str
63
+ gdb_port: int
64
+ qmp_port: int
65
+ machine: str
66
+ cpu: str
67
+ memory: str
68
+ working_dir: Optional[str]
69
+ snapshot_file: Optional[str]
70
+ snapshot_mode: bool
71
+ plugin_path: Optional[str]
72
+ plugin_args: Optional[str]
73
+ serial_pty: bool
74
+ arch: str
75
+ benchmark_name: Optional[str]
76
+ checkpoint_base_dir: str
77
+
78
+
79
+ def qemu_session(params: Mapping[str, Any]) -> QemuSession:
80
+ g = params.get
81
+ return QemuSession(
82
+ # Required, as setup has always required them (KeyError).
83
+ elf_path=params["elf_path"], qemu_binary=params["qemu_binary"],
84
+ gdb_binary=params["gdb_binary"],
85
+ gdb_port=g("gdb_port", 1234), qmp_port=g("qmp_port", 4444),
86
+ machine=g("machine", "virt"), cpu=g("cpu", "c906fdv"), memory=g("memory", "256M"),
87
+ working_dir=g("working_dir"), snapshot_file=g("snapshot_file"),
88
+ snapshot_mode=g("snapshot_mode", False), plugin_path=g("plugin_path"),
89
+ plugin_args=g("plugin_args"), serial_pty=g("serial_pty", False),
90
+ arch=g("arch", "riscv64"), benchmark_name=g("benchmark_name"),
91
+ checkpoint_base_dir=g("checkpoint_base_dir", "golden"))
92
+
93
+
94
+ def qmp_retries() -> int:
95
+ """HFIM_QMP_RETRIES, else 150: how many times to try the QMP socket of a
96
+ QEMU that is still starting (process wiring, changes no result)."""
97
+ import os
98
+ return int(os.environ.get("HFIM_QMP_RETRIES", "150"))
99
+
100
+
101
+ def precise_stops_on(environ: Optional[Mapping[str, str]] = None) -> bool:
102
+ """HFIM_NO_ONE_INSN_PER_TB=1 turns the precise stops off: the escape
103
+ hatch for measuring what they cost."""
104
+ import os
105
+ environ = os.environ if environ is None else environ
106
+ return environ.get("HFIM_NO_ONE_INSN_PER_TB") != "1"
107
+
108
+
109
+ def default_machine_cpu(elf_arch: Optional[Mapping[str, Any]],
110
+ package_archs: Optional[Mapping[str, Mapping[str, Any]]] = None
111
+ ) -> Tuple[str, str, str]:
112
+ """(arch name, machine, cpu) before the campaign states either: the
113
+ ELF's arch, with the package's own machine and cpu for that arch over
114
+ the toolchain table's guess."""
115
+ elf_arch = elf_arch or {}
116
+ name = elf_arch.get("name", "riscv64")
117
+ machine = elf_arch.get("machine", "virt")
118
+ cpu = elf_arch.get("cpu", "rv64")
119
+ spec = (package_archs or {}).get(name) or {}
120
+ return name, spec.get("machine") or machine, spec.get("cpu") or cpu
121
+
122
+
123
+ def cpu_origin(config: Mapping[str, Any]) -> str:
124
+ """Who asked for the CPU a run boots: the campaign's qemu_cpu, else
125
+ the board's emulation.qemu_cpu, else the simulator package's default."""
126
+ from fim.core.configuration.resolver import origin_of
127
+ from fim.utils.board import machine_shape
128
+ origin = origin_of(config, "qemu_cpu")
129
+ if origin is not None and origin.source == "derived":
130
+ return "board.yaml (emulation.qemu_cpu)" # the resolver took it from the board
131
+ if config.get("qemu_cpu") not in (None, ""):
132
+ return "the campaign's qemu_cpu"
133
+ if "qemu_cpu" in machine_shape(dict(config)):
134
+ return "board.yaml (emulation.qemu_cpu)"
135
+ return "the simulator package's default"
136
+
137
+
138
+ def _extra_args(config: Mapping[str, Any]) -> Tuple[str, ...]:
139
+ """The board's own clock arguments (board.yaml emulation.timing), then
140
+ the config's qemu_args; a config that passes its own -icount wins."""
141
+ from fim.utils.board import icount_args
142
+ extra = [str(a) for a in (config.get("qemu_args") or [])]
143
+ if "-icount" in extra:
144
+ return tuple(extra)
145
+ return tuple(icount_args(config) + extra)
146
+
147
+
148
+ def qemu_launch(config: Mapping[str, Any], default_machine: str,
149
+ default_cpu: str) -> QemuLaunch:
150
+ """The QEMU View of a configuration, given the machine and CPU the
151
+ configuration falls back to (default_machine_cpu). The machine, CPU,
152
+ memory and hart count come from the campaign when it states them, else
153
+ from the board (board.yaml emulation:, cpu.harts), else the default."""
154
+ from fim.utils.board import machine_shape
155
+ g = config.get
156
+ board = machine_shape(dict(config))
157
+
158
+ def stated(key: str, default: Any) -> Any:
159
+ value = g(key)
160
+ return value if value not in (None, "") else board.get(key, default)
161
+
162
+ return QemuLaunch(
163
+ machine=stated("qemu_machine", default_machine),
164
+ cpu=stated("qemu_cpu", default_cpu),
165
+ # microchip-icicle-kit rejects less than 1.5G; the PolarFire board
166
+ # states qemu_memory: 2G.
167
+ memory=stated("qemu_memory", "256M"),
168
+ serial_pty=bool(g("serial_pty", False)),
169
+ # An SMP guest hangs at boot under fewer harts than it was built for.
170
+ num_cores=int(stated("num_cores", 1)),
171
+ firmware_path=g("firmware_path"),
172
+ firmware_entry=g("firmware_entry"),
173
+ sd_image_path=g("sd_image_path"),
174
+ guest_uart_serial=g("guest_uart_serial"),
175
+ # On the golden as on each injection: a timing flag such as -icount
176
+ # changes what the guest does.
177
+ extra_args=_extra_args(config),
178
+ precise_stops=precise_stops_on(),
179
+ )
@@ -0,0 +1,329 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ QEMUSimulatorController - wraps QEMUController + GDBController + CheckpointManager
6
+ behind the SimulatorController interface.
7
+
8
+ This is a pure refactor: no behavior changes. Existing QEMU campaign logic
9
+ can use this controller interchangeably with the raw QEMUController/GDB pair.
10
+ """
11
+
12
+ import os
13
+ import time
14
+ from typing import Dict, List, Optional, Tuple
15
+
16
+ from fim.core.simulator_controller import SimulatorController, GoldenResult, InjectionRun
17
+ from fim.core.qemu_controller import QEMUController
18
+ from fim.core.gdb_controller import GDBController, GDBError
19
+ from fim.core.checkpoint import CheckpointManager
20
+ from fim.utils.logger import get_logger
21
+
22
+ logger = get_logger("fim.core.qemu_simulator")
23
+
24
+
25
+ class QEMUSimulatorController(SimulatorController):
26
+ """SimulatorController implementation backed by QEMU + GDB.
27
+
28
+ Wraps QEMUController, GDBController, and CheckpointManager so that
29
+ campaign logic can use the SimulatorController ABC without knowing
30
+ which backend is active.
31
+ """
32
+
33
+ # Default timeout for continue_and_wait (seconds)
34
+ DEFAULT_TIMEOUT = 60.0
35
+
36
+ def __init__(self) -> None:
37
+ self._qemu: Optional[QEMUController] = None
38
+ self._gdb: Optional[GDBController] = None
39
+ self._checkpoint_mgr: Optional[CheckpointManager] = None
40
+ self._session = None
41
+
42
+ # -- SimulatorController interface ----------------------------------------
43
+
44
+ def setup(self, config: Dict) -> None:
45
+ """Initialize QEMU, GDB, and CheckpointManager from *config*.
46
+
47
+ Expected config keys:
48
+ elf_path (str): Path to the benchmark ELF binary.
49
+ qemu_binary (str): Path to qemu-system-riscv64.
50
+ gdb_binary (str): Path to GDB executable.
51
+ gdb_port (int): TCP port for GDB server (default 1234).
52
+ qmp_port (int): TCP port for QMP socket (default 4444).
53
+ machine (str): QEMU machine type (default "virt").
54
+ cpu (str): QEMU CPU model (default "c906fdv").
55
+ memory (str): RAM size (default "256M").
56
+ working_dir (str): QEMU working directory.
57
+ snapshot_file (str): Path to qcow2 for snapshots.
58
+ snapshot_mode (bool): If True, open qcow2 read-only.
59
+ plugin_path (str): Path to TCG plugin .so.
60
+ plugin_args (str): Plugin argument string.
61
+ serial_pty (bool): Use PTY for UART.
62
+ benchmark_name (str): Benchmark name for checkpoint directory.
63
+ checkpoint_base_dir (str): Base dir for checkpoints (default "golden").
64
+ arch (str): Architecture for GDB register set (default "riscv64").
65
+ """
66
+ from fim.core.qemu_launch import qemu_session
67
+ s = self._session = qemu_session(config)
68
+
69
+ elf_path = s.elf_path
70
+ qemu_binary = s.qemu_binary
71
+ gdb_binary = s.gdb_binary
72
+
73
+ gdb_port = s.gdb_port
74
+ qmp_port = s.qmp_port
75
+
76
+ # Create QEMUController
77
+ self._qemu = QEMUController(
78
+ elf_path=elf_path,
79
+ qemu_binary=qemu_binary,
80
+ gdb_port=gdb_port,
81
+ qmp_port=qmp_port,
82
+ machine=s.machine,
83
+ cpu=s.cpu,
84
+ memory=s.memory,
85
+ working_dir=s.working_dir,
86
+ snapshot_file=s.snapshot_file,
87
+ snapshot_mode=s.snapshot_mode,
88
+ plugin_path=s.plugin_path,
89
+ plugin_args=s.plugin_args,
90
+ serial_pty=s.serial_pty,
91
+ )
92
+ self._qemu.start()
93
+ logger.info("QEMU started")
94
+
95
+ # Create GDBController and connect
96
+ arch = s.arch
97
+ self._gdb = GDBController(
98
+ gdb_binary=gdb_binary,
99
+ host="127.0.0.1",
100
+ port=gdb_port,
101
+ arch=arch,
102
+ )
103
+ try:
104
+ self._gdb.connect(elf_path=elf_path)
105
+ except Exception:
106
+ # QEMU is already running; a failed attach must not leave it
107
+ # behind (each leak holds a port and counts against nproc).
108
+ try:
109
+ self._qemu.stop()
110
+ finally:
111
+ self._qemu = None
112
+ raise
113
+ self._gdb.set_qemu_controller(self._qemu)
114
+ logger.info("GDB connected")
115
+
116
+ # Create CheckpointManager (optional - requires benchmark_name)
117
+ benchmark_name = s.benchmark_name
118
+ if benchmark_name:
119
+ checkpoint_base = s.checkpoint_base_dir
120
+ self._checkpoint_mgr = CheckpointManager(
121
+ qemu=self._qemu,
122
+ benchmark_name=benchmark_name,
123
+ base_dir=checkpoint_base,
124
+ )
125
+ logger.info("CheckpointManager initialised")
126
+
127
+ def run_golden(
128
+ self,
129
+ benchmark_elf: str,
130
+ timeout: int,
131
+ checkpoint_locations: List[str],
132
+ ) -> GoldenResult:
133
+ """Delegate to the existing GoldenRunner.
134
+
135
+ The GoldenRunner already orchestrates QEMU + GDB + CheckpointManager
136
+ for golden runs. This method creates a GoldenRunner configured with
137
+ the same paths/ports and returns a GoldenResult.
138
+ """
139
+ from fim.scripts.run_golden import GoldenRunner
140
+
141
+ s = self._session
142
+ runner = GoldenRunner(
143
+ benchmark=s.benchmark_name or "unknown",
144
+ elf_path=benchmark_elf,
145
+ output_dir=s.checkpoint_base_dir,
146
+ qemu_binary=s.qemu_binary,
147
+ gdb_binary=s.gdb_binary,
148
+ gdb_port=s.gdb_port,
149
+ qmp_port=s.qmp_port,
150
+ timeout=timeout,
151
+ checkpoint_locations=checkpoint_locations,
152
+ )
153
+
154
+ # GoldenRunner manages its own QEMU/GDB lifecycle, so tear down
155
+ # the instances created in setup() first to free ports.
156
+ self.cleanup()
157
+
158
+ summary = runner.run()
159
+
160
+ # Re-establish controllers for subsequent injection calls
161
+ # (caller is expected to call setup() again if they need the
162
+ # controllers, or use a fresh config with snapshot_mode=True).
163
+
164
+ checkpoint_dir = str(
165
+ runner.golden_dir / "checkpoints"
166
+ )
167
+
168
+ # QEMU's icount plugin doesn't surface a separate
169
+ # kernel-exit count distinct from total instruction count. Set
170
+ # fim_exit_icount = total_instructions so the field is populated
171
+ # honestly (same value, no probe-fired distinction) rather than
172
+ # left None (which would falsely suggest the workload didn't
173
+ # exit through fim_exit).
174
+ total_insts = summary.get("instruction_count", 0)
175
+ return GoldenResult(
176
+ output=runner.qemu.get_uart_output() if runner.qemu else "",
177
+ total_instructions=total_insts,
178
+ fim_init_icount=runner.fim_init_icount,
179
+ checkpoint_dir=checkpoint_dir,
180
+ trace=runner.trace if runner.trace else {},
181
+ observable_state=None,
182
+ fim_exit_icount=total_insts if total_insts > 0 else None,
183
+ )
184
+
185
+ def restore_checkpoint(self, checkpoint_name: str) -> None:
186
+ """Restore a QEMU snapshot and reconnect GDB."""
187
+ if self._checkpoint_mgr is None:
188
+ raise RuntimeError("CheckpointManager not initialised (missing benchmark_name in config)")
189
+ if self._gdb is None:
190
+ raise RuntimeError("GDB not initialised")
191
+
192
+ self._checkpoint_mgr.restore_checkpoint(checkpoint_name)
193
+
194
+ # After loadvm, GDB's register cache is stale.
195
+ # Disconnect without detaching (keeps CPU stopped) then reconnect.
196
+ self._gdb.disconnect_without_detach()
197
+ time.sleep(0.2)
198
+ self._gdb.connect(elf_path=self._session.elf_path)
199
+ self._gdb.set_qemu_controller(self._qemu)
200
+ logger.info("Checkpoint restored and GDB reconnected")
201
+
202
+ def inject_register_fault(
203
+ self, reg_name: str, faulty_value: int,
204
+ instruction_count: int = 0,
205
+ ) -> Tuple[int, int]:
206
+ """Read original value, write faulty value, return both."""
207
+ if self._gdb is None:
208
+ raise RuntimeError("GDB not initialised")
209
+
210
+ original = self._gdb.read_register(reg_name)
211
+ self._gdb.write_register(reg_name, faulty_value)
212
+ return (original, faulty_value)
213
+
214
+ def inject_memory_fault(
215
+ self, address: int, faulty_value: int, size: int
216
+ ) -> Tuple[int, int]:
217
+ """Read original memory, write faulty value, return both."""
218
+ if self._gdb is None:
219
+ raise RuntimeError("GDB not initialised")
220
+
221
+ original_bytes = self._gdb.read_memory(address, size)
222
+ original_value = int.from_bytes(original_bytes, byteorder="little")
223
+ self._gdb.write_memory(address, faulty_value, size)
224
+ return (original_value, faulty_value)
225
+
226
+ # inject_cache_fault - inherited default raises NotImplementedError
227
+
228
+ def continue_and_wait(self, timeout: float) -> InjectionRun:
229
+ """Continue execution, wait for completion, capture output."""
230
+ if self._gdb is None or self._qemu is None:
231
+ raise RuntimeError("Controllers not initialised")
232
+
233
+ start = time.time()
234
+ error_msg: Optional[str] = None
235
+ timed_out = False
236
+ crashed = False
237
+ exit_code: Optional[int] = None
238
+
239
+ try:
240
+ stop_reason = self._gdb.continue_execution(timeout=timeout)
241
+ except GDBError as exc:
242
+ stop_reason = "error"
243
+ error_msg = str(exc)
244
+
245
+ elapsed = time.time() - start
246
+
247
+ if stop_reason == "qemu-exited" or stop_reason == "target-disconnected":
248
+ _, exit_code = self._qemu.get_exit_status()
249
+ elif "exited" in stop_reason:
250
+ _, exit_code = self._qemu.get_exit_status()
251
+ elif stop_reason == "error":
252
+ timed_out = "timeout" in (error_msg or "").lower()
253
+
254
+ # One crash rule for every backend (classifier owns it).
255
+ from fim.analysis.classifier import decide_crash
256
+ crashed = decide_crash(exit_code=exit_code, completed=None,
257
+ error_message=error_msg, timed_out=timed_out)
258
+
259
+ output = self._qemu.get_uart_output(wait_time=0.5)
260
+
261
+ return InjectionRun(
262
+ output=output,
263
+ exit_code=exit_code,
264
+ timed_out=timed_out,
265
+ crashed=crashed,
266
+ execution_time=elapsed,
267
+ error_message=error_msg,
268
+ )
269
+
270
+ def get_output(self) -> str:
271
+ if self._qemu is None:
272
+ raise RuntimeError("QEMU not initialised")
273
+ return self._qemu.get_uart_output()
274
+
275
+ def read_register(self, reg_name: str) -> int:
276
+ if self._gdb is None:
277
+ raise RuntimeError("GDB not initialised")
278
+ return self._gdb.read_register(reg_name)
279
+
280
+ def dump_registers(self) -> Dict[str, int]:
281
+ if self._gdb is None:
282
+ raise RuntimeError("GDB not initialised")
283
+ raw = self._gdb.dump_all_registers()
284
+ # dump_all_registers returns hex-string values; convert to int
285
+ result: Dict[str, int] = {}
286
+ for key, val in raw.items():
287
+ if key in ("timestamp", "capture_point"):
288
+ continue
289
+ if isinstance(val, str) and val.startswith("0x"):
290
+ result[key] = int(val, 16)
291
+ elif isinstance(val, int):
292
+ result[key] = val
293
+ return result
294
+
295
+ def cleanup(self) -> None:
296
+ if self._gdb is not None:
297
+ try:
298
+ self._gdb.disconnect()
299
+ except Exception:
300
+ pass
301
+ self._gdb = None
302
+
303
+ if self._qemu is not None:
304
+ try:
305
+ self._qemu.stop()
306
+ except Exception:
307
+ pass
308
+ self._qemu = None
309
+
310
+ self._checkpoint_mgr = None
311
+
312
+ def is_available(self) -> bool:
313
+ """Check if the configured QEMU binary exists."""
314
+ session = self._session
315
+ return bool(session and session.qemu_binary) and os.path.isfile(session.qemu_binary)
316
+
317
+ # -- Accessors for internal controllers (testing / advanced use) ----------
318
+
319
+ @property
320
+ def qemu(self) -> Optional[QEMUController]:
321
+ return self._qemu
322
+
323
+ @property
324
+ def gdb(self) -> Optional[GDBController]:
325
+ return self._gdb
326
+
327
+ @property
328
+ def checkpoint_mgr(self) -> Optional[CheckpointManager]:
329
+ return self._checkpoint_mgr