test_6400_bmc_parser_fuzz.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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 Timer(1, units="ns")
  76. raw.append(int(dut.rd_raw.value))
  77. valid_mask |= int(dut.rd_valid.value) << index
  78. return raw, valid_mask
  79. async def expect_commit(dut, case: SnapshotCase, terminator: bytes) -> None:
  80. commits = int(dut.commit_count_mon.value)
  81. epoch = int(dut.epoch.value)
  82. bank = int(dut.active_bank.value)
  83. await send_bytes(dut, case.line + terminator)
  84. await clock_cycles(dut, 3)
  85. assert int(dut.commit_count_mon.value) == commits + 1
  86. assert int(dut.epoch.value) == (epoch + 1) & 0xFFFF
  87. assert int(dut.active_bank.value) == 1 - bank
  88. assert int(dut.age_seconds.value) == 0
  89. expected_raw = [int.from_bytes(case.raw[index : index + 2], "big") for index in range(0, 48, 2)]
  90. expected_valid = sum(
  91. (case.raw[index : index + 2] != b"\xFF\xFF") << (index // 2)
  92. for index in range(0, 48, 2)
  93. )
  94. observed_raw, observed_valid = await read_channels(dut)
  95. assert observed_raw == expected_raw
  96. assert observed_valid == expected_valid
  97. assert int(dut.active_valid_mask.value) == expected_valid
  98. async def expect_reject(dut, line: bytes, *, timeout: bool = False) -> None:
  99. commits = int(dut.commit_count_mon.value)
  100. errors = int(dut.error_count_mon.value)
  101. epoch = int(dut.epoch.value)
  102. bank = int(dut.active_bank.value)
  103. raw_before, valid_before = await read_channels(dut)
  104. await send_bytes(dut, line)
  105. if timeout:
  106. await clock_cycles(dut, 70)
  107. else:
  108. await clock_cycles(dut, 3)
  109. assert int(dut.commit_count_mon.value) == commits
  110. assert int(dut.error_count_mon.value) == errors + 1
  111. assert int(dut.epoch.value) == epoch
  112. assert int(dut.active_bank.value) == bank
  113. raw_after, valid_after = await read_channels(dut)
  114. assert (raw_after, valid_after) == (raw_before, valid_before)
  115. @cocotb.test()
  116. async def test_bmc_replay_fuzz_timeout_banks_epoch_and_freshness(dut):
  117. dut.tick_1s_test.value = 0
  118. dut.rx_valid.value = 0
  119. dut.rx_data.value = 0
  120. dut.rx_framing_error.value = 0
  121. dut.snapshot_lock.value = 0
  122. dut.snapshot_lock_bank.value = 0
  123. dut.rd_index.value = 0
  124. await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
  125. await clock_cycles(dut, 3)
  126. assert int(dut.age_seconds.value) == 0xFFFF
  127. assert int(dut.stale.value) == 1
  128. cases = generated_cases()
  129. baseline = SnapshotCase(
  130. channels=tuple((30, 0) for _ in range(24)),
  131. lower=False,
  132. separator=b" ",
  133. )
  134. # The optional six-byte command echo is a separate non-committing line.
  135. await send_bytes(dut, b"36 6c DF dd 00 03\r\n")
  136. await clock_cycles(dut, 3)
  137. assert int(dut.commit_count_mon.value) == 0
  138. assert int(dut.error_count_mon.value) == 0
  139. # Mixed upper/lower hex, space/tab/no separators, CR, LF, CRLF, FF FF,
  140. # consecutive snapshots, atomic bank flips, and exact epochs.
  141. for index, case in enumerate(cases):
  142. terminator = (b"\r", b"\n", b"\r\n")[index % 3]
  143. await expect_commit(dut, case, terminator)
  144. # Each valid replay also seeds a guaranteed-invalid-character mutation
  145. # which must preserve the previously active bank byte-for-byte.
  146. mutated = bytearray(case.line)
  147. mutated[0] = ord("G")
  148. await expect_reject(dut, bytes(mutated) + b"\r")
  149. # Freshness is reset by a commit, ages on distinct one-second ticks, and
  150. # becomes stale at the configured threshold. A new snapshot clears it.
  151. await pulse_tick(dut, 1)
  152. assert int(dut.age_seconds.value) == 1 and int(dut.stale.value) == 0
  153. await pulse_tick(dut, 1)
  154. assert int(dut.age_seconds.value) == 2 and int(dut.stale.value) == 1
  155. await expect_commit(dut, baseline, b"\r")
  156. assert int(dut.age_seconds.value) == 0 and int(dut.stale.value) == 0
  157. raw = baseline.raw
  158. hex_line = b" ".join(f"{value:02X}".encode("ascii") for value in raw)
  159. await expect_reject(dut, b" ".join(f"{value:02X}".encode("ascii") for value in raw[:-1]) + b"\r")
  160. await expect_reject(dut, hex_line + b" 00\r")
  161. await expect_reject(dut, b"FF" + hex_line[2:] + b"\r")
  162. await expect_reject(dut, hex_line[:1] + b" " + hex_line[1:] + b"\r")
  163. # A UART framing error taints the complete line even when all ASCII bytes
  164. # that follow would otherwise be valid.
  165. commits = int(dut.commit_count_mon.value)
  166. errors = int(dut.error_count_mon.value)
  167. await FallingEdge(dut.sys_clk)
  168. dut.rx_framing_error.value = 1
  169. await FallingEdge(dut.sys_clk)
  170. dut.rx_framing_error.value = 0
  171. await send_bytes(dut, hex_line + b"\r")
  172. await clock_cycles(dut, 3)
  173. assert int(dut.commit_count_mon.value) == commits
  174. assert int(dut.error_count_mon.value) == errors + 1
  175. # A half reply with no CR/LF is discarded by the inter-byte timeout. The
  176. # following complete reply starts from a clean nibble/count/echo state.
  177. await expect_reject(dut, hex_line[:20], timeout=True)
  178. await expect_commit(dut, baseline, b"\n")
  179. # Snapshot ownership of the inactive bank blocks partial writes and bank
  180. # flips until the lock is released.
  181. dut.snapshot_lock.value = 1
  182. dut.snapshot_lock_bank.value = 1 - int(dut.active_bank.value)
  183. await expect_reject(dut, hex_line + b"\r")
  184. dut.snapshot_lock.value = 0
  185. await expect_commit(dut, baseline, b"\r")