test_6400_bmc_parser_fuzz.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. """Hypothesis replay/fuzz coverage for the production BMC ASCII bank parser."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. import warnings
  5. import cocotb
  6. from cocotb.triggers import FallingEdge, RisingEdge, Timer, with_timeout
  7. from hypothesis import HealthCheck, given, settings, strategies as st
  8. from hypothesis.errors import HypothesisSideeffectWarning
  9. @dataclass(frozen=True)
  10. class SnapshotCase:
  11. channels: tuple[tuple[int, int] | None, ...]
  12. lower: bool
  13. separator: bytes
  14. @property
  15. def raw(self) -> bytes:
  16. values = bytearray()
  17. for channel in self.channels:
  18. values.extend((0xFF, 0xFF) if channel is None else channel)
  19. return bytes(values)
  20. @property
  21. def line(self) -> bytes:
  22. words = [f"{value:02x}" if self.lower else f"{value:02X}" for value in self.raw]
  23. return self.separator.join(value.encode("ascii") for value in words)
  24. @st.composite
  25. def snapshot_cases(draw) -> SnapshotCase:
  26. channel = st.one_of(
  27. st.none(),
  28. st.tuples(st.integers(min_value=0, max_value=99), st.integers(min_value=0, max_value=99)),
  29. )
  30. channels = tuple(draw(st.lists(channel, min_size=24, max_size=24)))
  31. return SnapshotCase(
  32. channels=channels,
  33. lower=draw(st.booleans()),
  34. separator=draw(st.sampled_from((b"", b" ", b"\t"))),
  35. )
  36. def generated_cases() -> list[SnapshotCase]:
  37. values: list[SnapshotCase] = []
  38. @settings(
  39. max_examples=48,
  40. derandomize=True,
  41. database=None,
  42. deadline=None,
  43. suppress_health_check=(HealthCheck.too_slow,),
  44. )
  45. @given(snapshot_cases())
  46. def collect(value: SnapshotCase) -> None:
  47. values.append(value)
  48. with warnings.catch_warnings():
  49. warnings.simplefilter("ignore", HypothesisSideeffectWarning)
  50. collect()
  51. return values
  52. async def clock_cycles(dut, count: int) -> None:
  53. for _ in range(count):
  54. await RisingEdge(dut.sys_clk)
  55. async def send_char(dut, value: int) -> None:
  56. await FallingEdge(dut.sys_clk)
  57. dut.rx_data.value = value
  58. dut.rx_valid.value = 1
  59. await FallingEdge(dut.sys_clk)
  60. dut.rx_valid.value = 0
  61. async def send_bytes(dut, values: bytes) -> None:
  62. for value in values:
  63. await send_char(dut, value)
  64. async def pulse_tick(dut, count: int = 1) -> None:
  65. for _ in range(count):
  66. await FallingEdge(dut.sys_clk)
  67. dut.tick_1s_test.value = 1
  68. await FallingEdge(dut.sys_clk)
  69. dut.tick_1s_test.value = 0
  70. async def read_channels(dut) -> tuple[list[int], int]:
  71. raw: list[int] = []
  72. valid_mask = 0
  73. for index in range(24):
  74. dut.rd_index.value = index
  75. await RisingEdge(dut.sys_clk)
  76. await Timer(1, units="ns")
  77. raw.append(int(dut.rd_raw.value))
  78. valid_mask |= int(dut.rd_valid.value) << index
  79. return raw, valid_mask
  80. async def expect_commit(dut, case: SnapshotCase, terminator: bytes) -> None:
  81. commits = int(dut.commit_count_mon.value)
  82. epoch = int(dut.epoch.value)
  83. bank = int(dut.active_bank.value)
  84. await send_bytes(dut, case.line + terminator)
  85. await clock_cycles(dut, 3)
  86. assert int(dut.commit_count_mon.value) == commits + 1
  87. assert int(dut.epoch.value) == (epoch + 1) & 0xFFFF
  88. assert int(dut.active_bank.value) == 1 - bank
  89. assert int(dut.age_seconds.value) == 0
  90. expected_raw = [int.from_bytes(case.raw[index : index + 2], "big") for index in range(0, 48, 2)]
  91. expected_valid = sum(
  92. (case.raw[index : index + 2] != b"\xFF\xFF") << (index // 2)
  93. for index in range(0, 48, 2)
  94. )
  95. observed_raw, observed_valid = await read_channels(dut)
  96. assert observed_raw == expected_raw
  97. assert observed_valid == expected_valid
  98. assert int(dut.active_valid_mask.value) == expected_valid
  99. async def expect_reject(dut, line: bytes, *, timeout: bool = False) -> None:
  100. commits = int(dut.commit_count_mon.value)
  101. errors = int(dut.error_count_mon.value)
  102. epoch = int(dut.epoch.value)
  103. bank = int(dut.active_bank.value)
  104. raw_before, valid_before = await read_channels(dut)
  105. await send_bytes(dut, line)
  106. if timeout:
  107. await clock_cycles(dut, 70)
  108. else:
  109. await clock_cycles(dut, 3)
  110. assert int(dut.commit_count_mon.value) == commits
  111. assert int(dut.error_count_mon.value) == errors + 1
  112. assert int(dut.epoch.value) == epoch
  113. assert int(dut.active_bank.value) == bank
  114. raw_after, valid_after = await read_channels(dut)
  115. assert (raw_after, valid_after) == (raw_before, valid_before)
  116. @cocotb.test()
  117. async def test_bmc_replay_fuzz_timeout_banks_epoch_and_freshness(dut):
  118. dut.tick_1s_test.value = 0
  119. dut.rx_valid.value = 0
  120. dut.rx_data.value = 0
  121. dut.rx_framing_error.value = 0
  122. dut.snapshot_lock.value = 0
  123. dut.snapshot_lock_bank.value = 0
  124. dut.rd_index.value = 0
  125. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  126. await clock_cycles(dut, 27)
  127. assert int(dut.age_seconds.value) == 0xFFFF
  128. assert int(dut.stale.value) == 1
  129. cases = generated_cases()
  130. baseline = SnapshotCase(
  131. channels=tuple((30, 0) for _ in range(24)),
  132. lower=False,
  133. separator=b" ",
  134. )
  135. # The optional six-byte command echo is a separate non-committing line.
  136. await send_bytes(dut, b"36 6c DF dd 00 03\r\n")
  137. await clock_cycles(dut, 3)
  138. assert int(dut.commit_count_mon.value) == 0
  139. assert int(dut.error_count_mon.value) == 0
  140. # Mixed upper/lower hex, space/tab/no separators, CR, LF, CRLF, FF FF,
  141. # consecutive snapshots, atomic bank flips, and exact epochs.
  142. for index, case in enumerate(cases):
  143. terminator = (b"\r", b"\n", b"\r\n")[index % 3]
  144. await expect_commit(dut, case, terminator)
  145. # Each valid replay also seeds a guaranteed-invalid-character mutation
  146. # which must preserve the previously active bank byte-for-byte.
  147. mutated = bytearray(case.line)
  148. mutated[0] = ord("G")
  149. await expect_reject(dut, bytes(mutated) + b"\r")
  150. # Freshness is reset by a commit, ages on distinct one-second ticks, and
  151. # becomes stale at the configured threshold. A new snapshot clears it.
  152. await pulse_tick(dut, 1)
  153. assert int(dut.age_seconds.value) == 1 and int(dut.stale.value) == 0
  154. await pulse_tick(dut, 1)
  155. assert int(dut.age_seconds.value) == 2 and int(dut.stale.value) == 1
  156. await expect_commit(dut, baseline, b"\r")
  157. assert int(dut.age_seconds.value) == 0 and int(dut.stale.value) == 0
  158. raw = baseline.raw
  159. hex_line = b" ".join(f"{value:02X}".encode("ascii") for value in raw)
  160. await expect_reject(dut, b" ".join(f"{value:02X}".encode("ascii") for value in raw[:-1]) + b"\r")
  161. await expect_reject(dut, hex_line + b" 00\r")
  162. await expect_reject(dut, b"FF" + hex_line[2:] + b"\r")
  163. await expect_reject(dut, hex_line[:1] + b" " + hex_line[1:] + b"\r")
  164. # A UART framing error taints the complete line even when all ASCII bytes
  165. # that follow would otherwise be valid.
  166. commits = int(dut.commit_count_mon.value)
  167. errors = int(dut.error_count_mon.value)
  168. await FallingEdge(dut.sys_clk)
  169. dut.rx_framing_error.value = 1
  170. await FallingEdge(dut.sys_clk)
  171. dut.rx_framing_error.value = 0
  172. await send_bytes(dut, hex_line + b"\r")
  173. await clock_cycles(dut, 3)
  174. assert int(dut.commit_count_mon.value) == commits
  175. assert int(dut.error_count_mon.value) == errors + 1
  176. # A half reply with no CR/LF is discarded by the inter-byte timeout. The
  177. # following complete reply starts from a clean nibble/count/echo state.
  178. await expect_reject(dut, hex_line[:20], timeout=True)
  179. await expect_commit(dut, baseline, b"\n")
  180. # Snapshot ownership of the inactive bank blocks partial writes and bank
  181. # flips until the lock is released.
  182. dut.snapshot_lock.value = 1
  183. dut.snapshot_lock_bank.value = 1 - int(dut.active_bank.value)
  184. await expect_reject(dut, hex_line + b"\r")
  185. dut.snapshot_lock.value = 0
  186. await expect_commit(dut, baseline, b"\r")