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
fim/utils/config.py ADDED
@@ -0,0 +1,1714 @@
1
+ # SPDX-FileCopyrightText: 2026 HI-REST and the HFIM contributors
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """
5
+ Campaign configuration validation and loading utilities.
6
+
7
+ This module provides utilities for loading and validating YAML campaign
8
+ configurations. It ensures all required fields are present and validates
9
+ field values against constraints.
10
+ """
11
+
12
+ import json
13
+ import os
14
+ import warnings
15
+ from typing import Any, Dict, List, Mapping, Optional, Set, Tuple
16
+ import yaml
17
+
18
+ from fim.core.configuration import schema as _schema
19
+
20
+
21
+ class ConfigError(Exception):
22
+ """Base exception for configuration errors."""
23
+ pass
24
+
25
+
26
+ class ConfigValidationError(ConfigError):
27
+ """Raised when configuration validation fails."""
28
+ pass
29
+
30
+
31
+ class ConfigFileNotFoundError(ConfigError):
32
+ """Raised when configuration file doesn't exist."""
33
+ pass
34
+
35
+
36
+ # Required fields for all campaigns
37
+ REQUIRED_FIELDS: Set[str] = set(_schema.REQUIRED_KEYS)
38
+
39
+ # Valid values for enumerated fields
40
+ #
41
+ # Schema: two keys name the fault target.
42
+ # - target_types: List[str] - the list form; only "register"/"memory"
43
+ # - fault_target: str - the canonical key, read by _run_gem5_campaign
44
+ # with values like "cache_l1d", "memory", "dram"
45
+ # `fault_target` is the ONE canonical key, accepted by the validator with the
46
+ # full target taxonomy. `target_types` stays as a compatibility alias - if
47
+ # only it is present we derive `fault_target = target_types[0]` at load time.
48
+ #
49
+ # Keep this set aligned with FIMController's C++ validTypes set in
50
+ # hfim-sim-gem5/integration/simobjects-fim/fim/fim_controller.cc (the C++ uses
51
+ # the un-suffixed "cache" because cache level is implicit via the wired
52
+ # target_cache SimObject; the campaign layer uses level-suffixed forms
53
+ # because that's how _run_gem5_campaign dispatches via prefix match).
54
+ VALID_FAULT_TARGETS: Set[str] = set(_schema.FAULT_TARGETS)
55
+
56
+ # Backward-compat: target_types list accepts the same taxonomy.
57
+ VALID_TARGET_TYPES: Set[str] = VALID_FAULT_TARGETS
58
+
59
+ VALID_FAULT_MODELS: Set[str] = set(_schema.choices("fault_model"))
60
+ VALID_LOG_LEVELS: Set[str] = set(_schema.choices("log_level"))
61
+ VALID_BIT_WIDTHS: Set[int] = set(_schema.choices("bit_width"))
62
+ VALID_MEMORY_SIZES: Set[int] = set(_schema.choices("memory_access_size"))
63
+
64
+ # A memory injection on the simulator backends (QEMU, gem5) is a one-byte
65
+ # read-modify-write, and faultlist replay rejects any bit outside [0,7] for
66
+ # memory targets. Defaulting wider promised a bit width those injectors cannot
67
+ # deliver: the mask ANDed to zero and the fault silently flipped nothing. The
68
+ # hardware backend reads and writes the whole memory_access_size word.
69
+ DEFAULT_MEMORY_ACCESS_SIZE: int = _schema.setting("memory_access_size").default
70
+
71
+
72
+ def memory_word_bytes(config: Dict[str, Any]) -> int:
73
+ """The memory word a campaign draws faults in: the drawn address is
74
+ aligned to it, the faultlist draws bits below its width, and a backend
75
+ that writes whole words (hardware) reads and writes exactly it."""
76
+ return int(config.get("memory_access_size", DEFAULT_MEMORY_ACCESS_SIZE))
77
+
78
+
79
+ def derived_bit_width(config: Dict[str, Any]) -> int:
80
+ """The bit width a campaign can actually
81
+ flip. Explicit bit_width wins; otherwise it is derived from the target
82
+ (memory -> access size in bits, registers -> 64)."""
83
+ explicit = config.get("bit_width")
84
+ if explicit is not None:
85
+ return int(explicit)
86
+ targets = config.get("target_types") or []
87
+ if "memory" in targets or config.get("fault") == "memory":
88
+ return memory_word_bytes(config) * 8
89
+ return 64
90
+
91
+
92
+ VALID_COMPARISON_MODES: Set[str] = set(_schema.OBSERVABLE_COMPARISONS)
93
+ VALID_INJECTION_MODES: Set[str] = set(_schema.choices("injection_mode"))
94
+
95
+ # One definition, so a config that omits the key cannot mean one thing to
96
+ # the golden run and another to the campaign. They disagreed: the golden
97
+ # defaulted to icount and every campaign path to timer, so the plugin was
98
+ # loaded for the reference run and not for the injected ones.
99
+ #
100
+ # The value is timer even though icount is the clock a reproducible
101
+ # campaign wants. icount needs the instruction counts the golden run
102
+ # writes to trace.json, and raises rather than quietly changing clock
103
+ # when they are absent. That is right for a config that ASKED for icount
104
+ # and wrong as the answer for one that said nothing, so as a default it
105
+ # turns every campaign with a countless golden into a hard failure.
106
+ # Documentation steers a reproducible campaign to set icount explicitly.
107
+ INJECTION_MODE_DEFAULT: str = _schema.setting("injection_mode").default
108
+
109
+ # Default values for optional fields
110
+ # The Built-in Defaults, projected from the Key Schema.
111
+ DEFAULTS: Dict[str, Any] = _schema.defaults()
112
+
113
+
114
+
115
+ # A key may be renamed for clarity without breaking the campaigns already
116
+ # written against the old name: both are accepted, the canonical one wins
117
+ # if a config somehow carries both, and everything downstream reads one
118
+ # name only.
119
+ KEY_ALIASES: Dict[str, str] = dict(_schema.KEY_ALIASES)
120
+
121
+
122
+ # Keys that are still accepted but have never done anything. A config that
123
+ # sets one to something other than the value that changes nothing gets a
124
+ # warning saying so (and what to use), and the key is dropped.
125
+ # The Retired Keys: key -> (matters, message).
126
+ INERT_KEYS = {r.key: (r.matters, r.message) for r in _schema.RETIRED}
127
+
128
+
129
+ def _apply_key_aliases(config: Dict[str, Any]) -> Dict[str, Any]:
130
+ """Resolve accepted spellings to the canonical key, and drop inert ones."""
131
+ out = dict(config)
132
+ for key, (matters, message) in INERT_KEYS.items():
133
+ if key in out:
134
+ if matters(out.pop(key)):
135
+ warnings.warn(message, stacklevel=3)
136
+ # injection_timeout is the exact per-injection cap: it replaces timeout
137
+ # (which may be "auto", derived from the golden) rather than defaulting it.
138
+ if "injection_timeout" in out:
139
+ out["timeout"] = out.pop("injection_timeout")
140
+ for alias, canonical in KEY_ALIASES.items():
141
+ if alias in out:
142
+ value = out.pop(alias)
143
+ out.setdefault(canonical, value)
144
+ return out
145
+
146
+
147
+ # The Build Settings. A campaign may set them (or a file it includes); the
148
+ # Build Invocation (fim.core.artifacts.adapters.sdk) hands them to the SDK's
149
+ # build.sh.
150
+ BUILD_SETTING_KEYS = _schema.BUILD_SETTING_KEYS
151
+
152
+ def check_template_data(data: Dict[str, Any], manifest: str) -> None:
153
+ """Refuse every key of the template's hfim.yaml that no schema entry
154
+ declares; `x_` keys are notes."""
155
+ from fim.core.artifacts.classification import TEMPLATE_CLASSIFICATION
156
+ if isinstance(data, dict):
157
+ for key in data:
158
+ if (key not in TEMPLATE_CLASSIFICATION
159
+ and not str(key).startswith(_schema.ANNOTATION_PREFIX)):
160
+ raise _unknown_key_error(str(key), f" in {manifest}",
161
+ TEMPLATE_CLASSIFICATION)
162
+
163
+
164
+ def check_template_manifest(config_path: str) -> None:
165
+ """check_template_data on the hfim.yaml of the campaign's repository."""
166
+ from fim.core.configuration.sources import read_template
167
+ template = read_template(config_path)
168
+ if template is not None:
169
+ check_template_data(template.data, template.path)
170
+
171
+
172
+ # A batch file describes several campaigns that share a configuration, as
173
+ # `defaults` plus one entry per campaign. A Server runs these through its
174
+ # own dispatcher; these two functions let hfim read the same file here, so
175
+ # a sweep written once runs in either place.
176
+ BATCH_KEYS = ("defaults", "campaigns")
177
+
178
+ # The batch vocabulary is the one the Server's dispatcher uses, which is
179
+ # not quite the campaign one. `fault:` and `section:` already normalise in
180
+ # apply_defaults; this is the rest.
181
+ _BATCH_ALIASES = dict(_schema.BATCH_ALIASES)
182
+
183
+
184
+ def pick_benchmark_elf(benchmark: str, candidates: List[str],
185
+ arch: Optional[str] = None,
186
+ backend: Optional[str] = None) -> Optional[str]:
187
+ """Choose among hfim-sdk's benchmarks/<b>/build/<b>_<arch>[_gem5].elf.
188
+
189
+ sorted(...)[0] ignored both the arch and the backend: with an aarch64
190
+ and a riscv64 build side by side a riscv64 campaign got the aarch64 ELF,
191
+ and a QEMU campaign could get the gem5-SE build. Prefer the exact name
192
+ for this arch/backend; fall back to the first-in-order pick only when
193
+ nothing matches.
194
+
195
+ A gem5 backend runs the gem5-se build target, which hfim-sdk writes as
196
+ <b>_<arch>_gem5.elf: that name, or another gem5-se build, never the
197
+ first in order (a stray <b>_riscv64.elf sorts first and is a
198
+ bare-metal program gem5's SE mode cannot run). None when there is
199
+ no gem5-se build."""
200
+ if not candidates:
201
+ return None
202
+ if str(backend or "qemu").startswith("gem5"):
203
+ exact = f"{benchmark}_{arch or 'riscv64'}_gem5.elf"
204
+ se_builds = [c for c in sorted(candidates) if c.endswith("_gem5.elf")]
205
+ return next((c for c in se_builds if os.path.basename(c) == exact),
206
+ se_builds[0] if se_builds else None)
207
+ exact = f"{benchmark}_{arch or 'riscv64'}.elf"
208
+ for c in sorted(candidates):
209
+ if os.path.basename(c) == exact:
210
+ return c
211
+ not_gem5 = [c for c in sorted(candidates) if not c.endswith("_gem5.elf")]
212
+ return (not_gem5 or sorted(candidates))[0]
213
+
214
+
215
+ def make_campaign_id(benchmark: str, label: Optional[str] = None, now=None) -> str:
216
+ """The name of a campaign's result directory: `<benchmark>_<timestamp>`,
217
+ or `<benchmark>_<label>_<timestamp>` when campaign_label is set, with a
218
+ timestamp to the microsecond (`%Y%m%d_%H%M%S_%f`).
219
+
220
+ One rule for every Campaign Machine: a local campaign names itself with
221
+ it, and `hfim run --on` names each Server Campaign with it before the
222
+ Submission leaves the Local Machine.
223
+ """
224
+ from datetime import datetime
225
+ timestamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S_%f")
226
+ if label:
227
+ return f"{benchmark}_{label}_{timestamp}"
228
+ return f"{benchmark}_{timestamp}"
229
+
230
+
231
+ def is_batch_config(config: Dict[str, Any]) -> bool:
232
+ """True when this file describes several campaigns rather than one."""
233
+ return isinstance(config, dict) and "campaigns" in config
234
+
235
+
236
+ def name_batch_entries(entries: List[Dict[str, Any]], stem: str) -> None:
237
+ """Give each batch entry a campaign_name of its own, `<name>-<i>`
238
+ (the entry's own name, else the batch file's stem): the local batch and
239
+ the Submission name entries the same way."""
240
+ for i, entry in enumerate(entries, 1):
241
+ name = entry.get("campaign_name") or stem
242
+ entry.setdefault("campaign_name", f"{name}-{i}")
243
+
244
+
245
+ def batch_entry_label(entry: Mapping[str, Any]) -> Tuple[str, str]:
246
+ """(benchmark, target) of a batch entry as written, for a progress line."""
247
+ return (str(entry.get("benchmark", "?")),
248
+ str(entry.get("fault") or entry.get("section") or ""))
249
+
250
+
251
+ def stated_output_dir(raw: Mapping[str, Any]) -> Any:
252
+ """The output_dir a campaign or batch file states, before resolution
253
+ (a batch states it under defaults:)."""
254
+ return raw.get("output_dir") or (raw.get("defaults") or {}).get("output_dir")
255
+
256
+
257
+ def stated_benchmark(raw: Mapping[str, Any]) -> Any:
258
+ """The benchmark a campaign file states, before resolution."""
259
+ return raw.get("benchmark") if isinstance(raw, Mapping) else None
260
+
261
+
262
+ def expand_batch(config: Dict[str, Any], base: Optional[str] = None) -> List[Dict[str, Any]]:
263
+ """One campaign config per entry, defaults merged in.
264
+
265
+ Keys outside `defaults` and `campaigns` (campaign_name, simulator, and
266
+ anything else stated once for the whole file) apply to every entry, so
267
+ a batch does not have to repeat them inside defaults. An entry's own
268
+ keys win over both.
269
+
270
+ `include:` may appear in each of the three layers; an entry
271
+ includes its own files first, then those of `defaults:`, then those at
272
+ the top, so the closer layer wins here too. With `base`, the batch
273
+ file's directory, every include path is made absolute against it, so
274
+ the entry's campaign file resolves wherever it is written.
275
+
276
+ Raises ConfigValidationError when the file is not a usable batch, since
277
+ the alternative is validating it as a single campaign and reporting a
278
+ pile of missing fields that are in fact present, one level down.
279
+ """
280
+ campaigns = config.get("campaigns")
281
+ if not isinstance(campaigns, list) or not campaigns:
282
+ raise ConfigValidationError(
283
+ "a batch file needs a non-empty `campaigns:` list, one entry per "
284
+ "campaign")
285
+
286
+ defaults = config.get("defaults") or {}
287
+ if not isinstance(defaults, dict):
288
+ raise ConfigValidationError("`defaults:` must be a mapping")
289
+
290
+ shared = {k: v for k, v in config.items() if k not in BATCH_KEYS}
291
+
292
+ out: List[Dict[str, Any]] = []
293
+ for i, entry in enumerate(campaigns):
294
+ if not isinstance(entry, dict):
295
+ raise ConfigValidationError(
296
+ f"campaigns[{i}] must be a mapping, got {type(entry).__name__}")
297
+ # Aliases resolve inside each layer BEFORE the layers merge. Merging
298
+ # first let `defaults: {num_injections: 100}` beat an entry's own
299
+ # `injections: 10` (and a defaults target_variable beat an entry's
300
+ # target_symbol), the opposite of "an entry's own keys win".
301
+ layers = [_canonical_layer(shared), _canonical_layer(defaults),
302
+ _canonical_layer(entry)]
303
+ merged = {**layers[0], **layers[1], **layers[2]}
304
+ from fim.core.configuration.includes import include_list
305
+ included: List[str] = []
306
+ for layer, where in ((entry, f"campaigns[{i}]"), (defaults, "defaults"),
307
+ (shared, "the batch file")):
308
+ for item in include_list(layer, where):
309
+ if base is not None and not os.path.isabs(os.path.expanduser(item)):
310
+ item = os.path.normpath(os.path.join(base, item))
311
+ if item not in included:
312
+ included.append(item)
313
+ merged.pop(_schema.INCLUDE_KEY, None)
314
+ if included:
315
+ merged[_schema.INCLUDE_KEY] = included
316
+ try:
317
+ _check_key_spelling(merged, f" in campaigns[{i}]")
318
+ except ConfigValidationError as e:
319
+ raise ConfigValidationError(f"campaigns[{i}]: {e}") from e
320
+ out.append(merged)
321
+ return out
322
+
323
+
324
+ def _canonical_layer(layer: Dict[str, Any]) -> Dict[str, Any]:
325
+ """One batch layer with every accepted spelling mapped to its canonical
326
+ key. Within a layer the canonical spelling wins if both appear."""
327
+ out = dict(layer)
328
+ for alias, canonical in {**_BATCH_ALIASES, **KEY_ALIASES}.items():
329
+ if alias in out:
330
+ value = out.pop(alias)
331
+ out.setdefault(canonical, value)
332
+ return out
333
+
334
+
335
+ def load_config(config_path: str, options: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
336
+ """
337
+ Load and validate a campaign configuration from a YAML file.
338
+
339
+ Args:
340
+ config_path: Path to the YAML configuration file.
341
+ options: Command Options of this invocation (`--workers N` is
342
+ {"num_workers": N}); each wins over the files for its Setting.
343
+
344
+ Returns:
345
+ The validated configuration, read-only.
346
+
347
+ Raises:
348
+ ConfigFileNotFoundError: If config file doesn't exist.
349
+ ConfigValidationError: If config validation fails.
350
+ ConfigError: If YAML parsing fails.
351
+ """
352
+ # One resolution of every Source, read once, with the Origin of each
353
+ # value (fim/core/configuration/resolver.py).
354
+ # A run that resolved its campaign already pinned that resolution:
355
+ # every process of the run uses it, and an edit of the file
356
+ # after the run started reaches none of them.
357
+ from fim.core.configuration.resolver import pinned, resolve
358
+ fixed = pinned(config_path, options)
359
+ if fixed is not None:
360
+ return fixed
361
+ return resolve(config_path, options)
362
+
363
+
364
+ def apply_defaults(config: Dict[str, Any]) -> Dict[str, Any]:
365
+ """
366
+ Apply default values for missing optional fields.
367
+
368
+ Args:
369
+ config: Configuration dictionary.
370
+
371
+ Returns:
372
+ Configuration with defaults applied.
373
+ """
374
+ result = config.copy()
375
+
376
+ # Friendly aliases: the per-benchmark fim.yaml and the batch campaign
377
+ # file share one vocabulary. `fault:` is the canonical user-facing key
378
+ # for "what to inject"; `section:` is sugar for a whole-section memory
379
+ # window. Both normalise to the internal keys (`fault_target`,
380
+ # `memory_start`/`memory_end`) before any other logic runs. Conflicts
381
+ # (alias AND internal key both set to different values) are rejected by
382
+ # the validator, not silently reconciled here.
383
+ if result.get("fault") not in (None, "") and not result.get("fault_target"):
384
+ result["fault_target"] = result["fault"]
385
+ if result.get("section") not in (None, ""):
386
+ # A section name fills both ends of the window; _resolve_section_end
387
+ # turns the end into section_start + section_size.
388
+ if "memory_start" not in result or result["memory_start"] is None:
389
+ result["memory_start"] = result["section"]
390
+ if "memory_end" not in result or result["memory_end"] is None:
391
+ result["memory_end"] = result["section"]
392
+
393
+ # The injection clock of a backend without an icount clock is timer
394
+ # (gem5 counts instructions itself; a hardware board has no plugin).
395
+ # It is a Derivation, made before the Records hash the configuration,
396
+ # and a stated icount on such a backend is refused by validate_config.
397
+ backend = str(result.get("simulator_backend") or "qemu")
398
+ if result.get("injection_mode") is None and backend not in _schema.ICOUNT_BACKENDS:
399
+ result["injection_mode"] = "timer"
400
+
401
+ for key, default_value in DEFAULTS.items():
402
+ if key not in result or result[key] is None:
403
+ result[key] = default_value
404
+ elif key == "results" and isinstance(default_value, dict):
405
+ # Merge results config with defaults
406
+ if isinstance(result[key], dict):
407
+ merged_results = default_value.copy()
408
+ merged_results.update(result[key])
409
+ result[key] = merged_results
410
+
411
+ # Schema: derive the canonical `fault_target` from the list form
412
+ # `target_types` when only the latter is present, and
413
+ # reconcile both when both are present.
414
+ #
415
+ # Precedence (matches _run_gem5_campaign at base_campaign.py:1077):
416
+ # 1. explicit fault_target wins (already canonical)
417
+ # 2. else target_types[0] is promoted to fault_target
418
+ # 3. else default "register"
419
+ #
420
+ # When fault_target IS set but target_types isn't, mirror it back to
421
+ # target_types as a single-element list so downstream code that
422
+ # iterates target_types (validator, register/memory-specific
423
+ # validation blocks) still sees the right value.
424
+ has_ft = result.get("fault_target") not in (None, "")
425
+ has_tt = isinstance(result.get("target_types"), list) and result["target_types"]
426
+ if has_ft and not has_tt:
427
+ result["target_types"] = [result["fault_target"]]
428
+ elif has_tt and not has_ft:
429
+ result["fault_target"] = result["target_types"][0]
430
+ elif has_ft and has_tt:
431
+ # Both present - fault_target wins. Override target_types[0]
432
+ # silently (logged at debug level only; this is a YAML-author
433
+ # mistake, not a runtime bug).
434
+ if result["target_types"][0] != result["fault_target"]:
435
+ result["target_types"] = [result["fault_target"]]
436
+ # else: both missing - let the validator raise REQUIRED_FIELDS error
437
+
438
+ # target_types as a list of cache levels IS the level sweep (a
439
+ # Derivation).
440
+ tt = result.get("target_types")
441
+ cache_levels = ("cache_l1d", "cache_l1i", "cache_l2")
442
+ if (isinstance(tt, list) and len(tt) > 1 and all(t in cache_levels for t in tt)
443
+ and result.get("cache_level_sweep") is None):
444
+ result["cache_level_sweep"] = [t.replace("cache_", "") for t in tt]
445
+
446
+ # gem5 builds caches only for a non-Atomic CPU, and a Ruby run needs a
447
+ # timing CPU too, so a cache, coherence or Ruby target runs
448
+ # TimingSimpleCPU. It is a Derivation, made before the Golden Record
449
+ # hashes the CPU, and a stated AtomicSimpleCPU on such a target is
450
+ # refused by validate_config.
451
+ if _gem5_needs_timing_cpu(result) and result.get("cpu_model") is None:
452
+ from fim.core.gem5_launch import TIMING_CPU_MODEL
453
+ result["cpu_model"] = TIMING_CPU_MODEL
454
+
455
+ return result
456
+
457
+
458
+ def _gem5_needs_timing_cpu(config: Dict[str, Any]) -> bool:
459
+ """A gem5 campaign whose target lives in a cache or in Ruby state, by
460
+ what the configuration says (the binary name is a Machine Binding
461
+ signal the launch still checks)."""
462
+ backend = str(config.get("simulator_backend") or "qemu")
463
+ if not backend.startswith("gem5"):
464
+ return False
465
+ from fim.core.gem5_launch import needs_cache_hierarchy
466
+ ft = str(config.get("fault_target") or "")
467
+ return needs_cache_hierarchy(ft, backend == "gem5-ruby" or ft.lower().startswith("ruby_"))
468
+
469
+
470
+ def validate_results_config(results: Dict[str, Any]) -> None:
471
+ """
472
+ Validate results configuration section.
473
+
474
+ Args:
475
+ results: Results configuration dictionary.
476
+
477
+ Raises:
478
+ ConfigValidationError: If validation fails.
479
+ """
480
+ if not isinstance(results, dict):
481
+ raise ConfigValidationError("results must be a dictionary")
482
+
483
+ # Validate save_per_injection (boolean)
484
+ save_per_injection = results.get("save_per_injection")
485
+ if save_per_injection is not None:
486
+ if not isinstance(save_per_injection, bool):
487
+ raise ConfigValidationError("results.save_per_injection must be a boolean")
488
+
489
+ # Validate save_uart_output (boolean)
490
+ save_uart_output = results.get("save_uart_output")
491
+ if save_uart_output is not None:
492
+ if not isinstance(save_uart_output, bool):
493
+ raise ConfigValidationError("results.save_uart_output must be a boolean")
494
+
495
+ # Validate save_register_dump (boolean)
496
+ save_register_dump = results.get("save_register_dump")
497
+ if save_register_dump is not None:
498
+ if not isinstance(save_register_dump, bool):
499
+ raise ConfigValidationError("results.save_register_dump must be a boolean")
500
+
501
+ # Validate save_observable_state (boolean)
502
+ save_observable_state = results.get("save_observable_state")
503
+ if save_observable_state is not None:
504
+ if not isinstance(save_observable_state, bool):
505
+ raise ConfigValidationError("results.save_observable_state must be a boolean")
506
+
507
+
508
+ def _validate_type_string(var_type: str, where: str) -> None:
509
+ """
510
+ Validate that a fim.yaml `type:` string parses to a known base type.
511
+
512
+ Called from `validate_observable_outputs` for each variable. Catches
513
+ typos, unsupported C constructs (structs, unions, bitfields), and
514
+ unsupported qualifiers BEFORE the campaign starts running - instead
515
+ of letting them surface as corrupted verdicts post-campaign.
516
+
517
+ Args:
518
+ var_type: The raw type string from fim.yaml (e.g. 'double[8]',
519
+ 'volatile unsigned long', 'frobnicator_t').
520
+ where: A YAML path used in the error message
521
+ (e.g. 'observable_outputs.variables[2].type').
522
+
523
+ Raises:
524
+ ConfigValidationError: If `var_type` is empty, parses to an
525
+ unknown base type, or contains a construct we don't support
526
+ (struct/union/bitfield).
527
+ """
528
+ # Lazy import to keep observable_state out of the YAML-load hot path.
529
+ from fim.analysis.observable_state import ObservableState, ObservableStateError
530
+
531
+ if not var_type.strip():
532
+ raise ConfigValidationError(
533
+ f"{where} must be a non-empty type string "
534
+ f"(e.g. 'int', 'double[8]', 'unsigned long')"
535
+ )
536
+
537
+ # Reject constructs we explicitly don't support yet - better to be
538
+ # honest about the gap than to fall through.
539
+ lowered = var_type.lower()
540
+ for unsupported, hint in (
541
+ ('struct', 'unpack the struct into individual scalar observables'),
542
+ ('union', 'unions are not supported - observe a specific member'),
543
+ (':', 'bitfields are not supported (the colon syntax `unsigned x : 3`)'),
544
+ ):
545
+ if unsupported in lowered:
546
+ raise ConfigValidationError(
547
+ f"{where}={var_type!r} uses an unsupported C construct "
548
+ f"({unsupported!r}). {hint}."
549
+ )
550
+
551
+ # Try to parse a zero-buffer of the implied size to surface unknown
552
+ # base types. We don't care about the resulting value - we just want
553
+ # the parser's "unknown type" check to fire here, where the user can
554
+ # fix the YAML, instead of after the campaign has burned an hour.
555
+ normalised = ObservableState._normalise_type(var_type)
556
+ if '*' in normalised:
557
+ # Pointer types are always valid (parser handles them generically).
558
+ return
559
+
560
+ if '[' in normalised and ']' in normalised:
561
+ base_type, _dims = ObservableState._split_array_type(normalised)
562
+ else:
563
+ base_type = normalised
564
+
565
+ if base_type not in ObservableState._BASE_TYPE_TABLE:
566
+ # Surface the same message the parser would, but earlier and with
567
+ # the YAML path.
568
+ valid = sorted(ObservableState._BASE_TYPE_TABLE.keys())
569
+ raise ConfigValidationError(
570
+ f"{where}={var_type!r}: unknown base type {base_type!r}. "
571
+ f"Add it to ObservableState._BASE_TYPE_TABLE or pick from "
572
+ f"the allowed list. Allowed scalars: {valid}"
573
+ )
574
+
575
+
576
+ def validate_observable_outputs(observable_outputs: Dict[str, Any]) -> None:
577
+ """
578
+ Validate observable_outputs configuration section.
579
+
580
+ Args:
581
+ observable_outputs: Observable outputs configuration dictionary.
582
+
583
+ Raises:
584
+ ConfigValidationError: If validation fails.
585
+ """
586
+ if not isinstance(observable_outputs, dict):
587
+ raise ConfigValidationError("observable_outputs must be a dictionary")
588
+
589
+ # Validate comparison mode (optional, defaults to "exact")
590
+ comparison = observable_outputs.get("comparison", "exact")
591
+ if not isinstance(comparison, str):
592
+ raise ConfigValidationError("observable_outputs.comparison must be a string")
593
+ if comparison not in VALID_COMPARISON_MODES:
594
+ raise ConfigValidationError(
595
+ f"Invalid comparison mode '{comparison}'. "
596
+ f"Valid values: {', '.join(sorted(VALID_COMPARISON_MODES))}"
597
+ )
598
+
599
+ # At least one of 'variables' or 'memory_regions' must be present
600
+ variables = observable_outputs.get("variables")
601
+ memory_regions = observable_outputs.get("memory_regions")
602
+
603
+ if variables is None and memory_regions is None:
604
+ raise ConfigValidationError(
605
+ "observable_outputs must contain at least one of 'variables' or 'memory_regions'"
606
+ )
607
+
608
+ # Validate variables section (if present)
609
+ if variables is not None:
610
+ if not isinstance(variables, list):
611
+ raise ConfigValidationError("observable_outputs.variables must be a list")
612
+
613
+ if len(variables) == 0:
614
+ raise ConfigValidationError("observable_outputs.variables must not be empty")
615
+
616
+ for i, var in enumerate(variables):
617
+ if not isinstance(var, dict):
618
+ raise ConfigValidationError(
619
+ f"observable_outputs.variables[{i}] must be a dictionary"
620
+ )
621
+
622
+ # Name is required
623
+ name = var.get("name")
624
+ if name is None:
625
+ raise ConfigValidationError(
626
+ f"observable_outputs.variables[{i}] must have 'name' field"
627
+ )
628
+ if not isinstance(name, str) or not name.strip():
629
+ raise ConfigValidationError(
630
+ f"observable_outputs.variables[{i}].name must be a non-empty string"
631
+ )
632
+
633
+ # Type is optional (string). When present, it must parse to a
634
+ # base type our ObservableState parser recognises - otherwise
635
+ # we'd silently fall through to the int fallback and report
636
+ # corrupted verdicts.
637
+ var_type = var.get("type")
638
+ if var_type is not None:
639
+ if not isinstance(var_type, str):
640
+ raise ConfigValidationError(
641
+ f"observable_outputs.variables[{i}].type must be a string"
642
+ )
643
+ _validate_type_string(
644
+ var_type,
645
+ where=f"observable_outputs.variables[{i}].type"
646
+ )
647
+
648
+ # Tolerance is optional (for floating point comparison)
649
+ tolerance = var.get("tolerance")
650
+ if tolerance is not None:
651
+ if not isinstance(tolerance, (int, float)):
652
+ raise ConfigValidationError(
653
+ f"observable_outputs.variables[{i}].tolerance must be a number"
654
+ )
655
+ if tolerance < 0:
656
+ raise ConfigValidationError(
657
+ f"observable_outputs.variables[{i}].tolerance must be non-negative"
658
+ )
659
+
660
+ # Validate memory_regions section (if present)
661
+ if memory_regions is not None:
662
+ if not isinstance(memory_regions, list):
663
+ raise ConfigValidationError("observable_outputs.memory_regions must be a list")
664
+
665
+ if len(memory_regions) == 0:
666
+ raise ConfigValidationError("observable_outputs.memory_regions must not be empty")
667
+
668
+ for i, region in enumerate(memory_regions):
669
+ if not isinstance(region, dict):
670
+ raise ConfigValidationError(
671
+ f"observable_outputs.memory_regions[{i}] must be a dictionary"
672
+ )
673
+
674
+ # Address is required
675
+ address = region.get("address")
676
+ if address is None:
677
+ raise ConfigValidationError(
678
+ f"observable_outputs.memory_regions[{i}] must have 'address' field"
679
+ )
680
+
681
+ # Validate address format (int, hex string)
682
+ if isinstance(address, str):
683
+ try:
684
+ int(address, 0) # Supports 0x prefix for hex
685
+ except ValueError:
686
+ raise ConfigValidationError(
687
+ f"observable_outputs.memory_regions[{i}].address '{address}' "
688
+ "is not a valid integer or hex string"
689
+ )
690
+ elif not isinstance(address, int):
691
+ raise ConfigValidationError(
692
+ f"observable_outputs.memory_regions[{i}].address must be an integer or hex string"
693
+ )
694
+
695
+ # Size is required
696
+ size = region.get("size")
697
+ if size is None:
698
+ raise ConfigValidationError(
699
+ f"observable_outputs.memory_regions[{i}] must have 'size' field"
700
+ )
701
+ if not isinstance(size, int) or size <= 0:
702
+ raise ConfigValidationError(
703
+ f"observable_outputs.memory_regions[{i}].size must be a positive integer"
704
+ )
705
+
706
+ # Name is required
707
+ name = region.get("name")
708
+ if name is None:
709
+ raise ConfigValidationError(
710
+ f"observable_outputs.memory_regions[{i}] must have 'name' field"
711
+ )
712
+ if not isinstance(name, str) or not name.strip():
713
+ raise ConfigValidationError(
714
+ f"observable_outputs.memory_regions[{i}].name must be a non-empty string"
715
+ )
716
+
717
+
718
+ # Which optional keys belong to which fault family. A key set while a
719
+ # different family is active is almost always a copy/paste leftover, so the
720
+ # validator names it instead of ignoring it. Keys common to every campaign
721
+ # (n, seed, timeout, observable_outputs, bit_width, fault_model, ...) are
722
+ # never family-specific and are not listed here.
723
+ _REGISTER_KEYS = set(_schema.family_keys("register"))
724
+ # memory_access_size is intentionally omitted: it carries a default, so it is
725
+ # present on every config and is not a reliable signal of "memory" intent.
726
+ _MEMORY_KEYS = set(_schema.family_keys("memory"))
727
+ _CACHE_KEYS = set(_schema.family_keys("cache"))
728
+
729
+
730
+ def _family_of(fault_target: str) -> str:
731
+ """Group a fault_target into a family for key-isolation checks."""
732
+ if fault_target == "register":
733
+ return "register"
734
+ if fault_target == "memory":
735
+ return "memory"
736
+ if fault_target.startswith("cache_") or fault_target.startswith("ecc_parity_"):
737
+ return "cache"
738
+ # dram, phys_reg, rob, lsq, rename_map, branch_pred, tlb, ruby_*:
739
+ # no per-family extra keys to police today.
740
+ return "other"
741
+
742
+
743
+ def _check_target_key_isolation(config: Dict[str, Any], target_type) -> None:
744
+ """
745
+ Reject keys that belong to a fault family other than the active one.
746
+
747
+ One campaign injects one kind of fault. Mixing register/memory/cache
748
+ keys in a single config is a mistake; for several fault types use a
749
+ batch campaign file (one entry per fault), which a Server runs.
750
+ """
751
+ if not isinstance(target_type, str) or not target_type:
752
+ return
753
+ family = _family_of(target_type)
754
+ allowed = {
755
+ "register": _REGISTER_KEYS,
756
+ "memory": _MEMORY_KEYS,
757
+ "cache": _CACHE_KEYS,
758
+ "other": set(),
759
+ }[family]
760
+
761
+ foreign = (_REGISTER_KEYS | _MEMORY_KEYS | _CACHE_KEYS) - allowed
762
+ present = [k for k in foreign if config.get(k) not in (None, "")]
763
+ if present:
764
+ raise ConfigValidationError(
765
+ f"fault: {target_type} does not use these keys: "
766
+ f"{', '.join(sorted(present))}. One campaign = one fault type; "
767
+ f"for several, use a batch campaign file with one entry each, submitted to a Server."
768
+ )
769
+
770
+
771
+ # Keys the framework reads somewhere (core, server, the SDK build through
772
+ # the Build Invocation). A near-miss spelling of one is refused, since it
773
+ # would silently run the campaign with the default (`injection_mod:
774
+ # breakpoint` would run as icount). Any other key outside this list is
775
+ # read by nothing, so the loader warns that it is ignored.
776
+ # tests/artifacts/test_config_key_contract.py holds every key here to a
777
+ # consumer, or to INERT_KEYS / KEY_ALIASES.
778
+ KNOWN_CONFIG_KEYS = _schema.ACCEPTED_KEYS
779
+
780
+ # Keys whose value must be a real YAML boolean. A quoted 'false' is a
781
+ # non-empty string, which every `if config.get(...)` reads as True.
782
+ _BOOL_KEYS = _schema.BOOL_KEYS
783
+
784
+ # Keys whose value must be an integer when present (not a bool, float or
785
+ # numeric string: several readers use the raw value without int()).
786
+ _INT_KEYS = _schema.INT_KEYS
787
+
788
+
789
+ def _unknown_key_error(key: str, where: str, candidates) -> ConfigValidationError:
790
+ import difflib
791
+ from fim import __version__
792
+ close = difflib.get_close_matches(key, candidates, n=1, cutoff=0.85)
793
+ hint = f" Did you mean '{close[0]}'?" if close else ""
794
+ return ConfigValidationError(
795
+ f"unknown key '{key}'{where}: hfim {__version__} has no setting of "
796
+ f"that name, so the campaign would not do what the file asks.{hint} "
797
+ f"A note for people goes under a key that starts with "
798
+ f"'{_schema.ANNOTATION_PREFIX}'.")
799
+
800
+
801
+ def _check_key_spelling(config: Dict[str, Any], where: str = "") -> None:
802
+ """Refuse every key that is no Setting, alias or Retired Key (a campaign
803
+ that names a key this core does not know asks for behaviour this core
804
+ will not give). Keys starting with `_` are Run Facts; keys starting with
805
+ `x_` are annotations and are kept."""
806
+ for key in config:
807
+ if (not isinstance(key, str) or key in KNOWN_CONFIG_KEYS or key.startswith("_")
808
+ or key.startswith(_schema.ANNOTATION_PREFIX) or key == _schema.INCLUDE_KEY):
809
+ continue
810
+ raise _unknown_key_error(key, where, KNOWN_CONFIG_KEYS)
811
+
812
+
813
+ def _check_backend(config: Dict[str, Any], origin: Optional[Dict[str, str]] = None) -> None:
814
+ """A Setting stated for a backend that will not act on it
815
+ is refused when it changes results, and dropped with a warning when it is
816
+ Neutral. Applied to the keys the files state, before defaults."""
817
+ backend = str(config.get("simulator_backend") or "qemu")
818
+ for key in list(config):
819
+ s = _schema.BY_KEY.get(key) if isinstance(key, str) else None
820
+ if s is None or s.backends is None or backend in s.backends:
821
+ continue
822
+ value = config.get(key)
823
+ # A value that asks for nothing (empty, false, or the default) does
824
+ # nothing on any backend: `serial_pty: false` on gem5 is not refused.
825
+ if value in (None, "", [], {}) or value is False or (
826
+ s.has_default and value == s.default):
827
+ continue
828
+ where = f" (from {origin[key]})" if origin and key in origin else ""
829
+ msg = (f"{key}{where} applies to the {', '.join(sorted(s.backends))} backend, "
830
+ f"and this campaign runs on {backend}, which would ignore it.")
831
+ if s.group is _schema.Group.NEUTRAL:
832
+ warnings.warn(msg + " It is dropped.", stacklevel=3)
833
+ config.pop(key)
834
+ else:
835
+ raise ConfigValidationError(
836
+ msg + " Remove it, or for several backends use a batch file with "
837
+ "the backend's keys in its own entry.")
838
+
839
+
840
+ def _check_operator_overrides(config: Dict[str, Any],
841
+ origin: Optional[Dict[str, str]] = None) -> None:
842
+ """An Operator Override that disagrees with a value the
843
+ campaign (or a file it includes) states for a result-changing Setting
844
+ is a conflict, refused with both named. When none states one, the
845
+ override applies (build.sh reads it). `origin` names the included file
846
+ a value came from."""
847
+ for var in _schema.VARIABLES:
848
+ if var.kind != "override" or not var.setting:
849
+ continue
850
+ s = _schema.BY_KEY[var.setting]
851
+ if s.group is _schema.Group.NEUTRAL:
852
+ continue
853
+ env = os.environ.get(var.name)
854
+ value = config.get(s.key)
855
+ if not env or value in (None, ""):
856
+ continue
857
+ norm = (lambda v: str(v).strip().lstrip("-")) if s.key == "build_optflag" else str
858
+ if norm(value) != norm(env):
859
+ source = (origin or {}).get(s.key) or "the campaign"
860
+ raise ConfigValidationError(
861
+ f"{var.name}={env} in the environment disagrees with "
862
+ f"{s.key}: {value} in {source}. One run has one value: unset "
863
+ f"{var.name}, or change {s.key}.")
864
+
865
+
866
+ def _check_scalar_types(config: Dict[str, Any]) -> None:
867
+ for key in _BOOL_KEYS:
868
+ if key in config and config[key] is not None and not isinstance(config[key], bool):
869
+ raise ConfigValidationError(
870
+ f"{key} must be true or false, got {config[key]!r} "
871
+ f"(a quoted string is always read as true)")
872
+ for key in _INT_KEYS:
873
+ v = config.get(key)
874
+ if v is not None and (isinstance(v, bool) or not isinstance(v, int)):
875
+ raise ConfigValidationError(
876
+ f"{key} must be an integer, got {v!r}")
877
+
878
+
879
+ # Keys that only shape a firmware boot (firmware_path set: the board's own
880
+ # firmware boots the program). Without one, QEMU loads the ELF with -kernel
881
+ # and never reads them.
882
+ FIRMWARE_BOOT_KEYS = _schema.FIRMWARE_BOOT_KEYS
883
+
884
+
885
+ def _check_boot_mode(config: Dict[str, Any]) -> None:
886
+ """Refuse a QEMU key the chosen boot never reads, instead of running
887
+ the campaign as if it had been honoured."""
888
+ def given(key):
889
+ return config.get(key) not in (None, "")
890
+ if not given("firmware_path"):
891
+ stray = [k for k in FIRMWARE_BOOT_KEYS if given(k)]
892
+ if stray:
893
+ raise ConfigValidationError(
894
+ f"{', '.join(stray)} only apply to a firmware boot, and this "
895
+ f"campaign sets no firmware_path: QEMU loads the ELF with "
896
+ f"-kernel and would ignore {'it' if len(stray) == 1 else 'them'}.")
897
+ elif given("qemu_cpu"):
898
+ raise ConfigValidationError(
899
+ "qemu_cpu has no effect on a firmware boot (firmware_path): the "
900
+ "machine (qemu_machine) defines its own cores and QEMU is started "
901
+ "without -cpu. Remove qemu_cpu.")
902
+
903
+
904
+ def validate_config(config: Dict[str, Any]) -> None:
905
+ """
906
+ Validate campaign configuration.
907
+
908
+ Args:
909
+ config: Configuration dictionary to validate.
910
+
911
+ Raises:
912
+ ConfigValidationError: If validation fails.
913
+ """
914
+ # Check required fields
915
+ missing_fields = REQUIRED_FIELDS - set(config.keys())
916
+ if missing_fields:
917
+ raise ConfigValidationError(
918
+ f"Missing required fields: {', '.join(sorted(missing_fields))}"
919
+ )
920
+
921
+ # Validate benchmark
922
+ benchmark = config.get("benchmark")
923
+ if not isinstance(benchmark, str) or not benchmark.strip():
924
+ raise ConfigValidationError("benchmark must be a non-empty string")
925
+
926
+ _check_scalar_types(config)
927
+ _check_boot_mode(config)
928
+
929
+ backend = str(config.get("simulator_backend") or "qemu")
930
+ if config.get("injection_mode") == "icount" and backend not in _schema.ICOUNT_BACKENDS:
931
+ raise ConfigValidationError(
932
+ f"injection_mode: icount needs the QEMU icount plugin; the {backend} "
933
+ f"backend has no instruction-count clock. Use timer (the default here) "
934
+ f"or breakpoint.")
935
+ if backend == "ovp":
936
+ # The whole OVP plan is checked here, before anything is built or run.
937
+ from fim.core.ovp_plan import PlanRefused, check_config
938
+ try:
939
+ check_config(config)
940
+ except PlanRefused as e:
941
+ raise ConfigValidationError(str(e)) from None
942
+
943
+ # A campaign names a simulator package or a binary path, not both: the
944
+ # campaign, the golden and the Records could each pick a different one
945
+ # of the two.
946
+ if config.get("simulator"):
947
+ both = [k for k in ("qemu_path", "gem5_binary") if config.get(k)]
948
+ if both:
949
+ raise ConfigValidationError(
950
+ f"simulator: {config.get('simulator')!r} and {both[0]}: name the same "
951
+ f"simulator twice. Keep the package, or replace it with {both[0]} "
952
+ f"for a simulator built by hand.")
953
+
954
+ if config.get("cpu_model") == "AtomicSimpleCPU" and _gem5_needs_timing_cpu(config):
955
+ raise ConfigValidationError(
956
+ f"cpu_model: AtomicSimpleCPU cannot reach target {config.get('fault_target')!r}: "
957
+ f"gem5 builds no caches for an Atomic CPU and Atomic never touches Ruby "
958
+ f"state. Leave cpu_model unstated (TimingSimpleCPU) or name a timing CPU.")
959
+
960
+ # comparison_mode: its value domain is declared, so a value other than
961
+ # `strict` or `normalized` is refused rather than run as normalized.
962
+ mode = config.get("comparison_mode")
963
+ if mode is not None and mode not in _schema.choices("comparison_mode"):
964
+ raise ConfigValidationError(
965
+ f"comparison_mode must be one of "
966
+ f"{', '.join(sorted(_schema.choices('comparison_mode')))}, got {mode!r}")
967
+
968
+ # Validate seed (bool is an int subclass: `seed: true` is not a seed)
969
+ seed = config.get("seed")
970
+ if isinstance(seed, bool) or not isinstance(seed, int) or seed < 0:
971
+ raise ConfigValidationError("seed must be a non-negative integer")
972
+
973
+ # Validate num_injections
974
+ num_injections = config.get("num_injections")
975
+ if (isinstance(num_injections, bool) or not isinstance(num_injections, int)
976
+ or num_injections <= 0):
977
+ raise ConfigValidationError("num_injections must be a positive integer")
978
+
979
+ # Validate the canonical fault_target FIRST so any
980
+ # error message names the canonical key. apply_defaults() may
981
+ # have synthesised it from target_types[0]; we validate against
982
+ # the unified taxonomy regardless of how it got here.
983
+ fault_target = config.get("fault_target")
984
+ if fault_target is not None:
985
+ if not isinstance(fault_target, str) or not fault_target.strip():
986
+ raise ConfigValidationError(
987
+ "fault_target must be a non-empty string"
988
+ )
989
+ if fault_target in _schema.REFUSED_TARGETS:
990
+ raise ConfigValidationError(_schema.REFUSED_TARGETS[fault_target])
991
+ if fault_target not in VALID_FAULT_TARGETS:
992
+ raise ConfigValidationError(
993
+ f"Invalid fault_target '{fault_target}'. "
994
+ f"Valid values: {', '.join(sorted(VALID_FAULT_TARGETS))}"
995
+ )
996
+
997
+ # Reject conflicting aliases up front: the friendly `fault:` / `section:`
998
+ # keys are sugar, so setting them to a value that disagrees with the
999
+ # internal key they map to is a mistake, not something to silently
1000
+ # reconcile. (apply_defaults only fills the internal key when it was
1001
+ # empty, so a disagreement here means the author set both by hand.)
1002
+ if config.get("fault") not in (None, "") and fault_target is not None:
1003
+ if config["fault"] != fault_target:
1004
+ raise ConfigValidationError(
1005
+ f"'fault: {config['fault']}' conflicts with "
1006
+ f"'fault_target: {fault_target}'. Use one (prefer 'fault')."
1007
+ )
1008
+ if config.get("section") not in (None, ""):
1009
+ sec = config["section"]
1010
+ ms = config.get("memory_start")
1011
+ me = config.get("memory_end")
1012
+ if (ms is not None and ms != sec) or (me is not None and me != sec):
1013
+ raise ConfigValidationError(
1014
+ f"'section: {sec}' conflicts with explicit memory_start/"
1015
+ f"memory_end. Use 'section' for a whole section, or "
1016
+ f"memory_start/memory_end for an address range, not both."
1017
+ )
1018
+
1019
+ # Validate target_types (the list form - apply_defaults() has
1020
+ # already synthesised it from fault_target if needed). Kept for
1021
+ # compatibility; YAML should use fault_target.
1022
+ target_types = config.get("target_types")
1023
+ if not isinstance(target_types, list) or len(target_types) == 0:
1024
+ raise ConfigValidationError("target_types must be a non-empty list")
1025
+
1026
+ for target_type in target_types:
1027
+ if target_type in _schema.REFUSED_TARGETS:
1028
+ raise ConfigValidationError(_schema.REFUSED_TARGETS[target_type])
1029
+ if target_type not in VALID_TARGET_TYPES:
1030
+ raise ConfigValidationError(
1031
+ f"Invalid target_type '{target_type}'. "
1032
+ f"Valid values: {', '.join(sorted(VALID_TARGET_TYPES))}"
1033
+ )
1034
+
1035
+ # Cross-target guard: keys that belong to a fault family other than the
1036
+ # active one are almost always copy/paste leftovers. Rather than ignore
1037
+ # them silently (which hides config mistakes), name the offender. One
1038
+ # campaign injects one kind of fault; for several, use a batch file
1039
+ # (a Server runs those).
1040
+ # target_types[0] is authoritative here (it is what the per-target
1041
+ # blocks below key off and what apply_defaults keeps in sync with
1042
+ # fault_target).
1043
+ _check_target_key_isolation(config, target_type=target_types[0])
1044
+
1045
+ # Validate register-specific fields
1046
+ if "register" in target_types:
1047
+ target_registers = config.get("target_registers")
1048
+ auto_flag = config.get("auto_registers", False)
1049
+ if not isinstance(auto_flag, bool):
1050
+ raise ConfigValidationError("auto_registers must be a boolean")
1051
+
1052
+ # auto_registers: true selects the ELF-autodetected GPR pool.
1053
+ # target_registers is then optional -- if given (a list) it is unioned
1054
+ # in as extras; if absent, the pool alone is used. include_int/
1055
+ # include_floats tune the pool. Without auto_registers, target_registers
1056
+ # is required (string 'auto' is an accepted alias, or a non-empty
1057
+ # list).
1058
+ if auto_flag:
1059
+ include_int = config.get("include_int", True)
1060
+ include_floats = config.get("include_floats", False)
1061
+ if not isinstance(include_int, bool):
1062
+ raise ConfigValidationError("include_int must be a boolean")
1063
+ if not isinstance(include_floats, bool):
1064
+ raise ConfigValidationError("include_floats must be a boolean")
1065
+ if not include_int and not include_floats:
1066
+ raise ConfigValidationError(
1067
+ "auto_registers: true with include_int=false and "
1068
+ "include_floats=false selects no registers; enable at least one"
1069
+ )
1070
+ if target_registers is not None:
1071
+ if not isinstance(target_registers, list):
1072
+ raise ConfigValidationError(
1073
+ "with auto_registers: true, target_registers (if given) "
1074
+ "must be a list of extra register names"
1075
+ )
1076
+ if len(target_registers) == 0:
1077
+ raise ConfigValidationError(
1078
+ "target_registers must be a non-empty list (or omit it "
1079
+ "to use the auto pool alone)"
1080
+ )
1081
+ elif target_registers is None:
1082
+ raise ConfigValidationError(
1083
+ "target_registers is required when target_types includes "
1084
+ "'register' (or set auto_registers: true)"
1085
+ )
1086
+ # `auto` (string) is the autodetect sentinel. The explicit
1087
+ # form is a non-empty list of register names.
1088
+ elif isinstance(target_registers, str):
1089
+ if target_registers.lower() != "auto":
1090
+ raise ConfigValidationError(
1091
+ "target_registers string form must be 'auto'; "
1092
+ "otherwise give a non-empty list of register names"
1093
+ )
1094
+ include_int = config.get("include_int", True)
1095
+ include_floats = config.get("include_floats", False)
1096
+ if not isinstance(include_int, bool):
1097
+ raise ConfigValidationError("include_int must be a boolean")
1098
+ if not isinstance(include_floats, bool):
1099
+ raise ConfigValidationError("include_floats must be a boolean")
1100
+ if not include_int and not include_floats:
1101
+ raise ConfigValidationError(
1102
+ "target_registers: auto with include_int=false and "
1103
+ "include_floats=false selects no registers; enable at least one"
1104
+ )
1105
+ elif isinstance(target_registers, list):
1106
+ if len(target_registers) == 0:
1107
+ raise ConfigValidationError("target_registers must be a non-empty list")
1108
+ else:
1109
+ raise ConfigValidationError(
1110
+ "target_registers must be 'auto' or a non-empty list of register names"
1111
+ )
1112
+
1113
+ # Validate memory-specific fields
1114
+ if "memory" in target_types:
1115
+ memory_start = config.get("memory_start")
1116
+ memory_end = config.get("memory_end")
1117
+ target_variable = config.get("target_variable")
1118
+
1119
+ # target_variable names a data symbol whose [addr, addr+st_size) range
1120
+ # is resolved from the ELF at setup(): it supplies the range itself,
1121
+ # so memory_start/memory_end are not required when it is set.
1122
+ if target_variable is not None:
1123
+ if not isinstance(target_variable, str) or not target_variable:
1124
+ raise ConfigValidationError(
1125
+ "target_variable must be a non-empty symbol name string"
1126
+ )
1127
+ else:
1128
+ if memory_start is None:
1129
+ raise ConfigValidationError(
1130
+ "memory_start is required when target_types includes 'memory' "
1131
+ "(or set target_variable to a data symbol name)"
1132
+ )
1133
+ if memory_end is None:
1134
+ raise ConfigValidationError(
1135
+ "memory_end is required when target_types includes 'memory' "
1136
+ "(or set target_variable to a data symbol name)"
1137
+ )
1138
+
1139
+ # When target_variable supplies the range, skip the start/end checks.
1140
+ if target_variable is not None:
1141
+ memory_start = None
1142
+ memory_end = None
1143
+
1144
+ # Validate memory addresses (can be int, hex string, or section name).
1145
+ # Skipped when target_variable supplies the range (start/end are None).
1146
+ if target_variable is None:
1147
+ if isinstance(memory_start, str) and not memory_start.startswith("."):
1148
+ # Hex string
1149
+ try:
1150
+ memory_start_int = int(memory_start, 0)
1151
+ except ValueError:
1152
+ raise ConfigValidationError(
1153
+ f"memory_start '{memory_start}' is not a valid integer or hex string"
1154
+ )
1155
+ elif isinstance(memory_start, int):
1156
+ memory_start_int = memory_start
1157
+ elif isinstance(memory_start, str):
1158
+ # Section name - will be resolved later
1159
+ memory_start_int = None
1160
+ else:
1161
+ raise ConfigValidationError(
1162
+ "memory_start must be an integer, hex string, or section name"
1163
+ )
1164
+
1165
+ if isinstance(memory_end, str) and not memory_end.startswith("."):
1166
+ try:
1167
+ memory_end_int = int(memory_end, 0)
1168
+ except ValueError:
1169
+ raise ConfigValidationError(
1170
+ f"memory_end '{memory_end}' is not a valid integer or hex string"
1171
+ )
1172
+ elif isinstance(memory_end, int):
1173
+ memory_end_int = memory_end
1174
+ elif isinstance(memory_end, str):
1175
+ memory_end_int = None
1176
+ else:
1177
+ raise ConfigValidationError(
1178
+ "memory_end must be an integer, hex string, or section name"
1179
+ )
1180
+
1181
+ # Validate range if both are integers
1182
+ if memory_start_int is not None and memory_end_int is not None:
1183
+ if memory_end_int <= memory_start_int:
1184
+ raise ConfigValidationError(
1185
+ f"memory_end ({memory_end_int:#x}) must be greater than "
1186
+ f"memory_start ({memory_start_int:#x})"
1187
+ )
1188
+
1189
+ # Validate memory_access_size
1190
+ memory_access_size = config.get("memory_access_size", DEFAULT_MEMORY_ACCESS_SIZE)
1191
+ if memory_access_size not in VALID_MEMORY_SIZES:
1192
+ raise ConfigValidationError(
1193
+ f"memory_access_size must be one of {sorted(VALID_MEMORY_SIZES)}"
1194
+ )
1195
+
1196
+ # A bit_width above 8 lets the draw pick
1197
+ # bit positions the injector will not apply, because injection is a
1198
+ # one-byte read-modify-write on every backend. That is worth saying
1199
+ # out loud, but it is NOT a reason to refuse the campaign: DRAM
1200
+ # physics models describe an upset in the device (a row, a retention
1201
+ # failure) rather than a bit inside one CPU access, and older configs
1202
+ # carry a 64-bit default. Warn, do not abort.
1203
+ explicit_bw = config.get("bit_width")
1204
+ if explicit_bw is not None and int(explicit_bw) > 8:
1205
+ warnings.warn(
1206
+ f"bit_width={explicit_bw} exceeds what a memory injection can "
1207
+ f"flip. The injection is a one-byte read-modify-write, so only "
1208
+ f"bits 0-7 apply however memory_access_size is set; wider draws "
1209
+ f"are dropped from the faultlist. Lower bit_width to 8.",
1210
+ stacklevel=2,
1211
+ )
1212
+
1213
+ # Validate fault_model
1214
+ fault_model = config.get("fault_model")
1215
+ if fault_model not in VALID_FAULT_MODELS:
1216
+ raise ConfigValidationError(
1217
+ f"Invalid fault_model '{fault_model}'. "
1218
+ f"Valid values: {', '.join(sorted(VALID_FAULT_MODELS))}"
1219
+ )
1220
+
1221
+ # Cache richness: optional per-set/way/bit targeting.
1222
+ # When provided, the values must be non-negative integers. Range
1223
+ # validation against the active board's cache geometry happens in
1224
+ # CacheCampaign.__init__ where the board YAML has been loaded.
1225
+ fault_target = config.get("fault_target", "")
1226
+ cache_set = config.get("cache_set")
1227
+ cache_way = config.get("cache_way")
1228
+ cache_level_sweep = config.get("cache_level_sweep")
1229
+ if cache_set is not None:
1230
+ if not isinstance(cache_set, int) or cache_set < 0:
1231
+ raise ConfigValidationError(
1232
+ f"cache_set must be a non-negative integer, got {cache_set!r}"
1233
+ )
1234
+ # Family isolation (cache_set only with cache_*/ecc_parity_*) is
1235
+ # enforced uniformly by _check_target_key_isolation() above.
1236
+ if cache_way is not None:
1237
+ if not isinstance(cache_way, int) or cache_way < 0:
1238
+ raise ConfigValidationError(
1239
+ f"cache_way must be a non-negative integer, got {cache_way!r}"
1240
+ )
1241
+ if cache_level_sweep is not None:
1242
+ if not isinstance(cache_level_sweep, list) or not cache_level_sweep:
1243
+ raise ConfigValidationError(
1244
+ f"cache_level_sweep must be a non-empty list, got "
1245
+ f"{cache_level_sweep!r}"
1246
+ )
1247
+ for lvl in cache_level_sweep:
1248
+ if lvl not in ("l1d", "l1i", "l2"):
1249
+ raise ConfigValidationError(
1250
+ f"cache_level_sweep entries must be l1d/l1i/l2, got {lvl!r}"
1251
+ )
1252
+
1253
+ # Multi-bit fault model. multi_bit_count > 1 instructs
1254
+ # the faultlist generator to pick N distinct bit positions per
1255
+ # injection and OR them into the fault_mask. Architecture-agnostic;
1256
+ # works on register, memory, and cache_* targets.
1257
+ multi_bit_count = config.get("multi_bit_count")
1258
+ if multi_bit_count is not None:
1259
+ if not isinstance(multi_bit_count, int) or multi_bit_count < 1:
1260
+ raise ConfigValidationError(
1261
+ f"multi_bit_count must be a positive integer, got "
1262
+ f"{multi_bit_count!r}"
1263
+ )
1264
+ bw = derived_bit_width(config)
1265
+ if multi_bit_count > bw:
1266
+ raise ConfigValidationError(
1267
+ f"multi_bit_count={multi_bit_count} exceeds "
1268
+ f"bit_width={bw}"
1269
+ )
1270
+
1271
+ # DRAM physics fault model. Enum is the same as the
1272
+ # FIMController.dram_error_model Param enum.
1273
+ dram_error_model = config.get("dram_error_model")
1274
+ if dram_error_model is not None:
1275
+ valid_dram_models = {
1276
+ "none", "single_bit", "multi_bit", "row", "retention",
1277
+ }
1278
+ if dram_error_model not in valid_dram_models:
1279
+ raise ConfigValidationError(
1280
+ f"dram_error_model must be one of {sorted(valid_dram_models)}, "
1281
+ f"got {dram_error_model!r}"
1282
+ )
1283
+
1284
+ # Cross-Setting Rules: the gem5 injector reads these only with a DRAM
1285
+ # error model (and the count and row size only with their own model);
1286
+ # stated without it they would be accepted and ignored, so they are
1287
+ # refused.
1288
+ model = dram_error_model if dram_error_model not in (None, "none") else None
1289
+ for key, needs in (("dram_ecc_enabled", None), ("dram_multi_bit_count", "multi_bit"),
1290
+ ("dram_row_size", "row")):
1291
+ value = config.get(key)
1292
+ if value in (None, False):
1293
+ continue
1294
+ if model is None or (needs and model != needs):
1295
+ want = f"dram_error_model: {needs}" if needs else "a dram_error_model"
1296
+ raise ConfigValidationError(
1297
+ f"{key} acts only with {want}; this campaign "
1298
+ f"{'sets none' if model is None else 'uses ' + model}, so gem5 would ignore it.")
1299
+
1300
+ # Fault persistence. Enum on FIMController.
1301
+ fault_persistence = config.get("fault_persistence")
1302
+ if fault_persistence is not None:
1303
+ if fault_persistence not in {"transient", "permanent"}:
1304
+ raise ConfigValidationError(
1305
+ f"fault_persistence must be 'transient' or 'permanent', "
1306
+ f"got {fault_persistence!r}"
1307
+ )
1308
+ # Only the gem5 and OVP injectors re-apply a fault (OVP: stuck-at).
1309
+ # On QEMU the bit is written once and
1310
+ # the program's next store erases it, so a "permanent" campaign
1311
+ # would silently measure a transient one.
1312
+ backend = str(config.get("simulator_backend") or "qemu")
1313
+ if fault_persistence == "permanent" and not (backend.startswith("gem5")
1314
+ or backend == "ovp"):
1315
+ raise ConfigValidationError(
1316
+ "fault_persistence: permanent is only implemented on gem5 and OVP; "
1317
+ "the QEMU backend writes the fault once (transient)")
1318
+
1319
+ # An OVP-native permanent model.
1320
+ if config.get("ovp_permanent_model") not in (None, ""):
1321
+ if str(config.get("simulator_backend") or "qemu") != "ovp":
1322
+ raise ConfigValidationError(
1323
+ "ovp_permanent_model is an OVP-native permanent model (inverted_cell); "
1324
+ "it is read only with simulator_backend: ovp.")
1325
+ if config.get("ovp_permanent_model") != "inverted_cell":
1326
+ raise ConfigValidationError(
1327
+ f"ovp_permanent_model: {config.get('ovp_permanent_model')!r} (inverted_cell)")
1328
+
1329
+ # A CSR fault target exists on OVP only.
1330
+ targets = set(config.get("target_types") or []) | {config.get("fault_target")}
1331
+ if "csr" in targets and str(config.get("simulator_backend") or "qemu") != "ovp":
1332
+ raise ConfigValidationError(
1333
+ "target_types: csr (a control and status register) is injected only by the "
1334
+ "OVP backend (simulator_backend: ovp); QEMU and gem5 have no CSR fault target")
1335
+
1336
+ # Cache ECC opt-in. Mirrors the DRAM ECC oracle shape on the cache
1337
+ # injection path. Default off keeps campaigns without ECC
1338
+ # reproducible; ECC-on campaigns produce a measurable SDC delta on
1339
+ # cache_l1d/l1i/l2 targets.
1340
+ cache_ecc_enabled = config.get("cache_ecc_enabled")
1341
+ if cache_ecc_enabled is not None:
1342
+ if not isinstance(cache_ecc_enabled, bool):
1343
+ raise ConfigValidationError(
1344
+ f"cache_ecc_enabled must be a boolean, "
1345
+ f"got {cache_ecc_enabled!r}"
1346
+ )
1347
+ cache_ecc_scope = config.get("cache_ecc_scope")
1348
+ if cache_ecc_scope is not None:
1349
+ valid_scopes = {"data", "tag", "both"}
1350
+ if cache_ecc_scope not in valid_scopes:
1351
+ raise ConfigValidationError(
1352
+ f"cache_ecc_scope must be one of {sorted(valid_scopes)}, "
1353
+ f"got {cache_ecc_scope!r}"
1354
+ )
1355
+
1356
+ # Per-level cache ECC policy. The C906 TRM and Cortex-
1357
+ # A53 TRM both ship per-array policy (L1 = parity-only, L2 =
1358
+ # SECDED). Default (None) = inherit cache_ecc_enabled global.
1359
+ valid_policies = {"parity", "secded", "none"}
1360
+ for policy_key in ("cache_ecc_policy_l1d", "cache_ecc_policy_l1i",
1361
+ "cache_ecc_policy_l2"):
1362
+ policy_val = config.get(policy_key)
1363
+ if policy_val is not None:
1364
+ if policy_val not in valid_policies:
1365
+ raise ConfigValidationError(
1366
+ f"{policy_key} must be one of "
1367
+ f"{sorted(valid_policies)}, got {policy_val!r}"
1368
+ )
1369
+ # Reject inconsistent combination: ECC globally off + per-
1370
+ # level policy demanding ECC. Silent confusion otherwise.
1371
+ if (cache_ecc_enabled is False and policy_val != "none"):
1372
+ raise ConfigValidationError(
1373
+ f"{policy_key}={policy_val!r} requires "
1374
+ f"cache_ecc_enabled=true. Per-level policy is "
1375
+ f"meaningless without the ECC oracle engaged."
1376
+ )
1377
+
1378
+ # Cache ECC modelling is single-core only. The snoop / coherent-response paths in
1379
+ # hfim-sim-gem5/gem5/src/mem/cache/cache.cc (lines 1009 / 1216 / 1222)
1380
+ # ship blk->data raw to upper caches without going through
1381
+ # applyFimEccDecode. For a single-core C906 with no L2 sharers
1382
+ # that path never fires; for any multi-core configuration the
1383
+ # decode is bypassed and ECC-on campaigns produce silent SDCs
1384
+ # that the model claims to mask. Reject the dangerous combination
1385
+ # outright.
1386
+ num_cores = config.get("num_cores")
1387
+ if num_cores is not None and cache_ecc_enabled:
1388
+ if not isinstance(num_cores, int) or num_cores < 1:
1389
+ raise ConfigValidationError(
1390
+ f"num_cores must be a positive integer when "
1391
+ f"cache_ecc_enabled is set, got {num_cores!r}"
1392
+ )
1393
+ if num_cores > 1:
1394
+ raise ConfigValidationError(
1395
+ f"cache_ecc_enabled=true is single-core only "
1396
+ f"(num_cores={num_cores}). The snoop / coherent-response "
1397
+ f"paths do not apply the ECC decode, so multi-core ECC "
1398
+ f"campaigns produce silent SDCs that the model "
1399
+ f"claims to mask. Either set num_cores=1 or disable "
1400
+ f"cache_ecc_enabled."
1401
+ )
1402
+
1403
+ # Multicore injection knobs. num_cores + target_core are
1404
+ # backend-agnostic campaign params. The rules differ by backend
1405
+ # because the backends' multicore control models differ:
1406
+ # - qemu: per-hart register/memory injection is feasible via
1407
+ # -smp N + GDB thread-select, but icount is a GLOBAL budget
1408
+ # under SMP round-robin (not a per-hart coordinate) and
1409
+ # bit-exact replay is single-vCPU only. So multicore QEMU must
1410
+ # use breakpoint timing; icount+multicore is rejected here.
1411
+ # - gem5 (classic): multicore is blocked entirely - the
1412
+ # cache-ECC snoop/coherent-response decode is unwired.
1413
+ # The ECC gate above already rejects
1414
+ # cache_ecc_enabled+multicore; a plain classic multicore run
1415
+ # has no coherence model, so cross-core injection is
1416
+ # meaningless. Steer users to gem5-ruby.
1417
+ # - gem5-ruby: multicore coherence injection is the intended
1418
+ # path, validated there, not here.
1419
+ # This block validates shape + the qemu icount rule. The
1420
+ # non-reproducibility WARNING for qemu num_cores>1 is emitted at
1421
+ # the campaign layer (base_campaign.setup), where the logger lives.
1422
+ num_cores = config.get("num_cores")
1423
+ if num_cores is not None:
1424
+ if not isinstance(num_cores, int) or num_cores < 1:
1425
+ raise ConfigValidationError(
1426
+ f"num_cores must be a positive integer, got "
1427
+ f"{num_cores!r}"
1428
+ )
1429
+
1430
+ # target_core: a hart (2), a list of harts ([0, 2]) the injections are
1431
+ # drawn from, or "random" (every hart of target_cluster, the default
1432
+ # with num_cores > 1). Harts are numbered within their cluster.
1433
+ target_core = config.get("target_core")
1434
+ if target_core is not None:
1435
+ if isinstance(target_core, str):
1436
+ if target_core != "random":
1437
+ raise ConfigValidationError(
1438
+ f"target_core must be a hart number, a list of them or "
1439
+ f"'random', got {target_core!r}")
1440
+ harts = []
1441
+ elif isinstance(target_core, list):
1442
+ if not target_core:
1443
+ raise ConfigValidationError("target_core is an empty list")
1444
+ harts = target_core
1445
+ else:
1446
+ harts = [target_core]
1447
+ for hart in harts:
1448
+ if isinstance(hart, bool) or not isinstance(hart, int) or hart < 0:
1449
+ raise ConfigValidationError(
1450
+ f"target_core must be a non-negative integer, a list of "
1451
+ f"them or 'random', got {target_core!r}")
1452
+ if len(set(harts)) != len(harts):
1453
+ raise ConfigValidationError(
1454
+ f"target_core lists a hart twice: {target_core!r}")
1455
+ # Harts index into [0, num_cores). num_cores defaults to 1 when
1456
+ # unset, so a hart > 0 without num_cores is an error too.
1457
+ effective_cores = num_cores if num_cores is not None else 1
1458
+ for hart in harts:
1459
+ if hart >= effective_cores:
1460
+ raise ConfigValidationError(
1461
+ f"target_core={hart} is out of range for "
1462
+ f"num_cores={effective_cores}; valid range is "
1463
+ f"[0, {effective_cores}).")
1464
+
1465
+ # target_cluster selects a cpu-cluster on a heterogeneous SoC
1466
+ # (e.g. PolarFire: E51 e-cluster=0, U54 u-cluster=1). Each cluster is a
1467
+ # separate GDB inferior; select_hart binds it. 0 (the default) is the
1468
+ # single-cluster path. Only meaningful with num_cores>1.
1469
+ # memory_per_core splits a memory target into one slice per hart; it
1470
+ # needs several harts and a memory fault to make sense.
1471
+ if config.get("memory_per_core"):
1472
+ if (num_cores or 1) <= 1:
1473
+ raise ConfigValidationError(
1474
+ "memory_per_core needs num_cores > 1: it splits the memory "
1475
+ "target into one slice per hart")
1476
+ kinds = config.get("target_types") or [config.get("fault")]
1477
+ if "memory" not in [str(k) for k in kinds if k]:
1478
+ raise ConfigValidationError(
1479
+ "memory_per_core applies to memory faults; this campaign "
1480
+ "injects no memory fault")
1481
+
1482
+ target_cluster = config.get("target_cluster")
1483
+ if target_cluster is not None:
1484
+ if not isinstance(target_cluster, int) or target_cluster < 0:
1485
+ raise ConfigValidationError(
1486
+ f"target_cluster must be a non-negative integer, got "
1487
+ f"{target_cluster!r}"
1488
+ )
1489
+ if target_cluster > 0:
1490
+ effective_cores = num_cores if num_cores is not None else 1
1491
+ if effective_cores <= 1:
1492
+ raise ConfigValidationError(
1493
+ f"target_cluster={target_cluster} needs num_cores>1 "
1494
+ f"(a multi-cluster SoC); got num_cores={effective_cores}."
1495
+ )
1496
+ # The board says how many clusters it has (board.yaml
1497
+ # cpu.clusters); QEMU virt and any board that declares none
1498
+ # has one.
1499
+ from fim.utils.board import clusters
1500
+ declared = clusters(config)
1501
+ if target_cluster >= declared:
1502
+ raise ConfigValidationError(
1503
+ f"target_cluster={target_cluster} but the board has "
1504
+ f"{declared} cluster{'s' if declared != 1 else ''} "
1505
+ f"(board.yaml cpu.clusters); use a board that declares "
1506
+ f"more clusters (e.g. microchip-icicle-kit, clusters: 2) "
1507
+ f"or a lower target_cluster."
1508
+ )
1509
+
1510
+ if num_cores is not None and num_cores > 1:
1511
+ backend = config.get("simulator_backend", "qemu")
1512
+ if backend == "qemu":
1513
+ # Multicore QEMU cannot use icount as a per-hart timing
1514
+ # coordinate (see block comment). Force the user onto
1515
+ # breakpoint mode explicitly rather than silently
1516
+ # mistiming injections.
1517
+ injection_mode = config.get("injection_mode", INJECTION_MODE_DEFAULT)
1518
+ if injection_mode == "icount":
1519
+ raise ConfigValidationError(
1520
+ "injection_mode=icount is incompatible with "
1521
+ "num_cores>1 on the QEMU backend. Under SMP, QEMU "
1522
+ "runs single-threaded round-robin TCG and icount "
1523
+ "is a GLOBAL instruction budget, not a per-hart "
1524
+ "retirement count - so an icount value cannot "
1525
+ "target a specific hart's timeline. Use "
1526
+ "injection_mode=breakpoint for multicore QEMU "
1527
+ "campaigns. (Bit-exact seed replay is also "
1528
+ "unavailable under QEMU SMP; the campaign will "
1529
+ "warn.)"
1530
+ )
1531
+ elif backend == "gem5":
1532
+ raise ConfigValidationError(
1533
+ f"num_cores={num_cores} (>1) is not supported on the "
1534
+ f"classic gem5 backend: it has no correct multicore "
1535
+ f"coherence path (the cache snoop/coherent-response "
1536
+ f"ECC decode is unwired). For "
1537
+ f"multicore coherence injection use "
1538
+ f"simulator_backend: gem5-ruby."
1539
+ )
1540
+
1541
+ # Opt-in random-DRAM fallback for memory targets.
1542
+ # When true, the framework lets the C++ side pick a random DRAM
1543
+ # address per injection instead of using the Python-resolved
1544
+ # memory_start/end window. Closer to silicon SEU physics; user
1545
+ # explicitly opts in because it makes per-row reasoning impossible.
1546
+ memory_random_fallback = config.get("memory_random_fallback")
1547
+ if memory_random_fallback is not None:
1548
+ if not isinstance(memory_random_fallback, bool):
1549
+ raise ConfigValidationError(
1550
+ f"memory_random_fallback must be a boolean, "
1551
+ f"got {memory_random_fallback!r}"
1552
+ )
1553
+
1554
+ # Validate bit_width
1555
+ bit_width = derived_bit_width(config)
1556
+ if bit_width not in VALID_BIT_WIDTHS:
1557
+ raise ConfigValidationError(
1558
+ f"bit_width must be one of {sorted(VALID_BIT_WIDTHS)}"
1559
+ )
1560
+
1561
+ # Optional effective-XLEN declaration. When present it
1562
+ # must be a real RISC-V width; the register injection path caps the
1563
+ # fault-model draw at this width (register_campaign) and the GDB
1564
+ # controller treats every width decision accordingly.
1565
+ xlen = config.get("xlen")
1566
+ if xlen is not None:
1567
+ if not isinstance(xlen, int) or isinstance(xlen, bool) \
1568
+ or xlen not in (32, 64):
1569
+ raise ConfigValidationError(
1570
+ f"xlen must be 32 or 64, got {xlen!r}"
1571
+ )
1572
+
1573
+ # Validate timeout. Either a positive number (explicit wall-clock cap) or
1574
+ # the string "auto", which defers to a golden-derived value (1.5x the golden
1575
+ # run's execution time by default) resolved in base_campaign.setup() once the
1576
+ # golden trace.json is loaded. "auto" keeps the cap tied to the actual
1577
+ # workload instead of a hardcoded literal that has no provenance.
1578
+ timeout = config.get("timeout")
1579
+ if isinstance(timeout, str):
1580
+ if timeout.strip().lower() != "auto":
1581
+ raise ConfigValidationError(
1582
+ "timeout must be a positive number or the string \"auto\""
1583
+ )
1584
+ elif not isinstance(timeout, (int, float)) or timeout <= 0:
1585
+ raise ConfigValidationError(
1586
+ "timeout must be a positive number or the string \"auto\""
1587
+ )
1588
+
1589
+ # Validate timeout_factor (only consulted when timeout == "auto")
1590
+ timeout_factor = config.get("timeout_factor", 1.5)
1591
+ if not isinstance(timeout_factor, (int, float)) or timeout_factor <= 0:
1592
+ raise ConfigValidationError("timeout_factor must be a positive number")
1593
+
1594
+ # Validate timeout_floor (only consulted when timeout == "auto")
1595
+ timeout_floor = config.get("timeout_floor")
1596
+ if timeout_floor is not None:
1597
+ if not isinstance(timeout_floor, (int, float)) or timeout_floor <= 0:
1598
+ raise ConfigValidationError("timeout_floor must be a positive number")
1599
+
1600
+ # Validate precise_stop_margin (only consulted in icount mode)
1601
+ margin = config.get("precise_stop_margin")
1602
+ if margin is not None:
1603
+ if isinstance(margin, bool) or not isinstance(margin, int) or margin < 0:
1604
+ raise ConfigValidationError(
1605
+ "precise_stop_margin must be a non-negative integer number of "
1606
+ "instructions (0 disables it)")
1607
+ if config.get("injection_mode", INJECTION_MODE_DEFAULT) != "icount":
1608
+ warnings.warn(
1609
+ "precise_stop_margin only applies to injection_mode: icount, "
1610
+ "where a stop is placed by instruction count. The other modes "
1611
+ "name an address or a moment and do not use it.",
1612
+ stacklevel=2,
1613
+ )
1614
+
1615
+ # Validate injection_mode
1616
+ injection_mode = config.get("injection_mode", INJECTION_MODE_DEFAULT)
1617
+ if injection_mode not in VALID_INJECTION_MODES:
1618
+ raise ConfigValidationError(
1619
+ f"Invalid injection_mode '{injection_mode}'. "
1620
+ f"Valid values: {', '.join(sorted(VALID_INJECTION_MODES))}"
1621
+ )
1622
+
1623
+ # Validate timer_scale_factor (only used in timer mode)
1624
+ timer_scale_factor = config.get("timer_scale_factor", 0.00001)
1625
+ if not isinstance(timer_scale_factor, (int, float)) or timer_scale_factor <= 0:
1626
+ raise ConfigValidationError("timer_scale_factor must be a positive number")
1627
+
1628
+ # Validate min_instructions
1629
+ min_instructions = config.get("min_instructions", 0)
1630
+ if not isinstance(min_instructions, int) or min_instructions < 0:
1631
+ raise ConfigValidationError("min_instructions must be a non-negative integer")
1632
+
1633
+ # Validate max_instructions
1634
+ max_instructions = config.get("max_instructions")
1635
+ if max_instructions is not None:
1636
+ if not isinstance(max_instructions, int) or max_instructions <= 0:
1637
+ raise ConfigValidationError("max_instructions must be a positive integer or null")
1638
+ if max_instructions <= min_instructions:
1639
+ raise ConfigValidationError(
1640
+ f"max_instructions ({max_instructions}) must be greater than "
1641
+ f"min_instructions ({min_instructions})"
1642
+ )
1643
+
1644
+ # Validate hang_icount_factor. Backend-agnostic semantic: "post-injection,
1645
+ # cut the run once it executes more than factor x the golden instruction
1646
+ # count and call it a hang." This mirrors SOFIA's FIM_HANG_THRESHOLD=0.5
1647
+ # (1.5x golden_icount). It is distinct from `timeout` (wall-clock seconds):
1648
+ # hang_icount_factor cuts by INSTRUCTIONS so the cutoff is deterministic and
1649
+ # comparable across simulators, where wall-clock is not.
1650
+ #
1651
+ # Resolution is per-backend (validation is identical):
1652
+ # - QEMU : armed as a second icount-plugin target at factor x golden_icount;
1653
+ # requires injection_mode == "icount" (the plugin is only loaded
1654
+ # there). A hit is classified TIMEOUT (the SOFIA-Hang equivalent).
1655
+ # - gem5 : resolved to --max-insts = factor x golden_icount (native).
1656
+ # Unset => no icount cutoff; the run is bounded only by `timeout` seconds,
1657
+ # i.e. behaviour is byte-identical to today (rollback path).
1658
+ hang_icount_factor = config.get("hang_icount_factor")
1659
+ if hang_icount_factor is not None:
1660
+ if not isinstance(hang_icount_factor, (int, float)) or hang_icount_factor <= 0:
1661
+ raise ConfigValidationError(
1662
+ "hang_icount_factor must be a positive number or null"
1663
+ )
1664
+ backend = config.get("simulator_backend", "qemu")
1665
+ if backend == "qemu" and injection_mode != "icount":
1666
+ raise ConfigValidationError(
1667
+ "hang_icount_factor on the QEMU backend requires "
1668
+ "injection_mode: icount (the icount plugin is only loaded in "
1669
+ "icount mode). Set injection_mode: icount or remove "
1670
+ "hang_icount_factor."
1671
+ )
1672
+
1673
+ # Validate log_level
1674
+ log_level = config.get("log_level", "INFO")
1675
+ if log_level not in VALID_LOG_LEVELS:
1676
+ raise ConfigValidationError(
1677
+ f"Invalid log_level '{log_level}'. "
1678
+ f"Valid values: {', '.join(sorted(VALID_LOG_LEVELS))}"
1679
+ )
1680
+
1681
+ # Validate ports
1682
+ gdb_port = config.get("gdb_port", 1234)
1683
+ if not isinstance(gdb_port, int) or not (1 <= gdb_port <= 65535):
1684
+ raise ConfigValidationError("gdb_port must be an integer between 1 and 65535")
1685
+
1686
+ qmp_port = config.get("qmp_port", 4444)
1687
+ if not isinstance(qmp_port, int) or not (1 <= qmp_port <= 65535):
1688
+ raise ConfigValidationError("qmp_port must be an integer between 1 and 65535")
1689
+
1690
+ if gdb_port == qmp_port:
1691
+ raise ConfigValidationError("gdb_port and qmp_port must be different")
1692
+
1693
+ # Validate completion_patterns (optional)
1694
+ completion_patterns = config.get("completion_patterns")
1695
+ if completion_patterns is not None:
1696
+ if not isinstance(completion_patterns, list):
1697
+ raise ConfigValidationError("completion_patterns must be a list")
1698
+ if len(completion_patterns) == 0:
1699
+ raise ConfigValidationError("completion_patterns must not be empty")
1700
+ for i, pattern in enumerate(completion_patterns):
1701
+ if not isinstance(pattern, str) or not pattern.strip():
1702
+ raise ConfigValidationError(
1703
+ f"completion_patterns[{i}] must be a non-empty string"
1704
+ )
1705
+
1706
+ # Validate observable_outputs (optional)
1707
+ observable_outputs = config.get("observable_outputs")
1708
+ if observable_outputs is not None:
1709
+ validate_observable_outputs(observable_outputs)
1710
+
1711
+ # Validate results configuration (optional)
1712
+ results = config.get("results")
1713
+ if results is not None:
1714
+ validate_results_config(results)