Просмотр исходного кода

test(cocotb): fuzz 6400 BMC snapshot parser

root 3 месяцев назад
Родитель
Сommit
ed38a7964d

+ 38 - 4
src/acquisition/bmc_ascii_snapshot.v

@@ -3,7 +3,8 @@
 // Streaming ASCII-hex decoder for one 24 x two-byte BMC line. Writes always
 // target the inactive bank; only an exact, valid 48-byte line flips active.
 module bmc_ascii_snapshot #(
-    parameter integer STALE_SECONDS = 3
+    parameter integer STALE_SECONDS = 3,
+    parameter integer INTER_BYTE_TIMEOUT_CLKS = 2500000
 ) (
     input  wire        clk,
     input  wire        rst_n,
@@ -38,11 +39,18 @@ module bmc_ascii_snapshot #(
     reg have_high;
     reg line_active;
     reg line_bad;
+    reg line_format_bad;
     reg [7:0] integer_byte;
     reg echo_match;
+    localparam integer GAP_BITS = (INTER_BYTE_TIMEOUT_CLKS <= 1) ? 1 :
+        $clog2(INTER_BYTE_TIMEOUT_CLKS + 1);
+    reg [GAP_BITS-1:0] gap_counter;
     integer i;
     wire inactive_bank = ~active_bank;
     wire write_blocked = snapshot_lock && (inactive_bank == snapshot_lock_bank);
+    /* verilator lint_off WIDTH */
+    wire gap_expired = gap_counter >= INTER_BYTE_TIMEOUT_CLKS - 1;
+    /* verilator lint_on WIDTH */
 
     function is_hex;
         input [7:0] value;
@@ -113,8 +121,10 @@ module bmc_ascii_snapshot #(
             have_high <= 1'b0;
             line_active <= 1'b0;
             line_bad <= 1'b0;
+            line_format_bad <= 1'b0;
             integer_byte <= 8'd0;
             echo_match <= 1'b1;
+            gap_counter <= {GAP_BITS{1'b0}};
             for (i = 0; i < 48; i = i + 1) begin
                 bank0[i] <= 8'd0;
                 bank1[i] <= 8'd0;
@@ -126,9 +136,26 @@ module bmc_ascii_snapshot #(
                 age_seconds <= age_seconds + 1'b1;
             if (rx_framing_error) begin
                 line_bad <= 1'b1;
+                line_format_bad <= 1'b1;
                 line_active <= 1'b1;
             end
+            if (!rx_valid && line_active) begin
+                if (INTER_BYTE_TIMEOUT_CLKS <= 1 || gap_expired) begin
+                    byte_count <= 6'd0;
+                    have_high <= 1'b0;
+                    line_active <= 1'b0;
+                    line_bad <= 1'b0;
+                    line_format_bad <= 1'b0;
+                    integer_byte <= 8'd0;
+                    echo_match <= 1'b1;
+                    gap_counter <= {GAP_BITS{1'b0}};
+                    parser_error <= 1'b1;
+                end else begin
+                    gap_counter <= gap_counter + 1'b1;
+                end
+            end
             if (rx_valid) begin
+                gap_counter <= {GAP_BITS{1'b0}};
                 if (is_hex(rx_data)) begin
                     if (!line_active && !have_high) begin
                         if (write_blocked)
@@ -171,16 +198,20 @@ module bmc_ascii_snapshot #(
                             byte_count <= byte_count + 1'b1;
                         end else begin
                             line_bad <= 1'b1;
+                            line_format_bad <= 1'b1;
                         end
                     end
                 end else if ((rx_data == " ") || (rx_data == 8'h09)) begin
-                    if (have_high) line_bad <= 1'b1;
+                    if (have_high) begin
+                        line_bad <= 1'b1;
+                        line_format_bad <= 1'b1;
+                    end
                     have_high <= 1'b0;
                 end else if ((rx_data == 8'h0d) || (rx_data == 8'h0a)) begin
                     if (line_active) begin
-                        if ((byte_count == 6) && echo_match && !have_high && !line_bad) begin
+                        if ((byte_count == 6) && echo_match && !have_high && !line_format_bad) begin
                             // Optional six-byte command echo is a separate line.
-                        end else if ((byte_count == 48) && !have_high && !line_bad) begin
+                        end else if ((byte_count == 48) && !have_high && !line_bad && !line_format_bad) begin
                             active_bank <= ~active_bank;
                             epoch <= epoch + 1'b1;
                             age_seconds <= 16'd0;
@@ -193,10 +224,13 @@ module bmc_ascii_snapshot #(
                     have_high <= 1'b0;
                     line_active <= 1'b0;
                     line_bad <= 1'b0;
+                    line_format_bad <= 1'b0;
                     echo_match <= 1'b1;
+                    gap_counter <= {GAP_BITS{1'b0}};
                 end else begin
                     line_active <= 1'b1;
                     line_bad <= 1'b1;
+                    line_format_bad <= 1'b1;
                     have_high <= 1'b0;
                 end
             end

+ 79 - 0
tests/cocotb/bmc_ascii_snapshot_cocotb_top.v

@@ -0,0 +1,79 @@
+`timescale 1ns/1ps
+
+module bmc_ascii_snapshot_cocotb_top (
+    input  wire        tick_1s_test,
+    input  wire        rx_valid,
+    input  wire [7:0]  rx_data,
+    input  wire        rx_framing_error,
+    input  wire        snapshot_lock,
+    input  wire        snapshot_lock_bank,
+    input  wire [4:0]  rd_index,
+    output wire        sys_clk,
+    output reg         rst_n_mon = 1'b0,
+    output wire        snapshot_commit,
+    output wire        parser_error,
+    output wire [15:0] epoch,
+    output wire [15:0] age_seconds,
+    output wire        stale,
+    output wire        active_bank,
+    output wire [23:0] active_valid_mask,
+    output wire [15:0] rd_raw,
+    output wire        rd_valid,
+    output reg  [15:0] commit_count_mon = 0,
+    output reg  [15:0] error_count_mon = 0
+);
+    reg clk = 1'b0;
+    reg [3:0] reset_count = 0;
+    always #20 clk = ~clk;
+    assign sys_clk = clk;
+
+    always @(posedge clk) begin
+        if (reset_count < 8) begin
+            reset_count <= reset_count + 1'b1;
+            rst_n_mon <= 1'b0;
+        end else begin
+            rst_n_mon <= 1'b1;
+        end
+    end
+
+    bmc_ascii_snapshot #(
+        .STALE_SECONDS(2),
+        .INTER_BYTE_TIMEOUT_CLKS(64)
+    ) u_dut (
+        .clk(clk),
+        .rst_n(rst_n_mon),
+        .tick_1s(tick_1s_test),
+        .rx_valid(rx_valid),
+        .rx_data(rx_data),
+        .rx_framing_error(rx_framing_error),
+        .snapshot_lock(snapshot_lock),
+        .snapshot_lock_bank(snapshot_lock_bank),
+        .snapshot_commit(snapshot_commit),
+        .parser_error(parser_error),
+        .epoch(epoch),
+        .age_seconds(age_seconds),
+        .stale(stale),
+        .active_bank(active_bank),
+        .active_valid_mask(active_valid_mask),
+        .control_bank(active_bank),
+        .control_index(rd_index),
+        .control_raw(rd_raw),
+        .control_valid(rd_valid),
+        .snapshot_bank(active_bank),
+        .snapshot_index(5'd0),
+        .snapshot_raw(),
+        .snapshot_valid()
+    );
+
+    always @(posedge clk) begin
+        if (!rst_n_mon) begin
+            commit_count_mon <= 0;
+            error_count_mon <= 0;
+        end else begin
+            if (snapshot_commit)
+                commit_count_mon <= commit_count_mon + 1'b1;
+            if (parser_error)
+                error_count_mon <= error_count_mon + 1'b1;
+        end
+    end
+endmodule

+ 57 - 0
tests/cocotb/run_6400_bmc_fuzz.py

@@ -0,0 +1,57 @@
+#!/usr/bin/env python3
+"""Run fail-closed byte-level BMC parser replay/fuzz coverage."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+import tempfile
+import xml.etree.ElementTree as ET
+
+try:
+    from cocotb_tools.runner import get_runner
+except ModuleNotFoundError:
+    from cocotb.runner import get_runner
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TEST_DIR = Path(__file__).resolve().parent
+
+
+def main() -> int:
+    with tempfile.TemporaryDirectory(prefix="prod2u-6400-bmc-fuzz-") as directory:
+        build_dir = Path(directory)
+        os.environ["HYPOTHESIS_STORAGE_DIRECTORY"] = str(build_dir / "hypothesis")
+        runner = get_runner("icarus")
+        runner.build(
+            sources=[
+                ROOT / "src/acquisition/bmc_ascii_snapshot.v",
+                TEST_DIR / "bmc_ascii_snapshot_cocotb_top.v",
+            ],
+            hdl_toplevel="bmc_ascii_snapshot_cocotb_top",
+            build_dir=build_dir,
+            build_args=["-g2012"],
+            always=True,
+        )
+        result = Path(runner.test(
+            hdl_toplevel="bmc_ascii_snapshot_cocotb_top",
+            test_module="test_6400_bmc_parser_fuzz",
+            test_dir=TEST_DIR,
+            build_dir=build_dir,
+            results_xml=str(build_dir / "results.xml"),
+        ))
+        root = ET.parse(result).getroot()
+        cases = root.findall(".//testcase")
+        failures = root.findall(".//failure") + root.findall(".//error")
+        skipped = root.findall(".//skipped")
+        if not cases or failures or skipped:
+            raise RuntimeError(
+                f"BMC fuzz incomplete: cases={len(cases)} failures={len(failures)} "
+                f"skipped={len(skipped)} results={result}"
+            )
+    print("PASS: 6400 BMC parser replay/fuzz")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 223 - 0
tests/cocotb/test_6400_bmc_parser_fuzz.py

@@ -0,0 +1,223 @@
+"""Hypothesis replay/fuzz coverage for the production BMC ASCII bank parser."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+import warnings
+
+import cocotb
+from cocotb.triggers import FallingEdge, RisingEdge, Timer, with_timeout
+from hypothesis import HealthCheck, given, settings, strategies as st
+from hypothesis.errors import HypothesisSideeffectWarning
+
+
+@dataclass(frozen=True)
+class SnapshotCase:
+    channels: tuple[tuple[int, int] | None, ...]
+    lower: bool
+    separator: bytes
+
+    @property
+    def raw(self) -> bytes:
+        values = bytearray()
+        for channel in self.channels:
+            values.extend((0xFF, 0xFF) if channel is None else channel)
+        return bytes(values)
+
+    @property
+    def line(self) -> bytes:
+        words = [f"{value:02x}" if self.lower else f"{value:02X}" for value in self.raw]
+        return self.separator.join(value.encode("ascii") for value in words)
+
+
+@st.composite
+def snapshot_cases(draw) -> SnapshotCase:
+    channel = st.one_of(
+        st.none(),
+        st.tuples(st.integers(min_value=0, max_value=99), st.integers(min_value=0, max_value=99)),
+    )
+    channels = tuple(draw(st.lists(channel, min_size=24, max_size=24)))
+    return SnapshotCase(
+        channels=channels,
+        lower=draw(st.booleans()),
+        separator=draw(st.sampled_from((b"", b" ", b"\t"))),
+    )
+
+
+def generated_cases() -> list[SnapshotCase]:
+    values: list[SnapshotCase] = []
+
+    @settings(
+        max_examples=48,
+        derandomize=True,
+        database=None,
+        deadline=None,
+        suppress_health_check=(HealthCheck.too_slow,),
+    )
+    @given(snapshot_cases())
+    def collect(value: SnapshotCase) -> None:
+        values.append(value)
+
+    with warnings.catch_warnings():
+        warnings.simplefilter("ignore", HypothesisSideeffectWarning)
+        collect()
+    return values
+
+
+async def clock_cycles(dut, count: int) -> None:
+    for _ in range(count):
+        await RisingEdge(dut.sys_clk)
+
+
+async def send_char(dut, value: int) -> None:
+    await FallingEdge(dut.sys_clk)
+    dut.rx_data.value = value
+    dut.rx_valid.value = 1
+    await FallingEdge(dut.sys_clk)
+    dut.rx_valid.value = 0
+
+
+async def send_bytes(dut, values: bytes) -> None:
+    for value in values:
+        await send_char(dut, value)
+
+
+async def pulse_tick(dut, count: int = 1) -> None:
+    for _ in range(count):
+        await FallingEdge(dut.sys_clk)
+        dut.tick_1s_test.value = 1
+        await FallingEdge(dut.sys_clk)
+        dut.tick_1s_test.value = 0
+
+
+async def read_channels(dut) -> tuple[list[int], int]:
+    raw: list[int] = []
+    valid_mask = 0
+    for index in range(24):
+        dut.rd_index.value = index
+        await Timer(1, units="ns")
+        raw.append(int(dut.rd_raw.value))
+        valid_mask |= int(dut.rd_valid.value) << index
+    return raw, valid_mask
+
+
+async def expect_commit(dut, case: SnapshotCase, terminator: bytes) -> None:
+    commits = int(dut.commit_count_mon.value)
+    epoch = int(dut.epoch.value)
+    bank = int(dut.active_bank.value)
+    await send_bytes(dut, case.line + terminator)
+    await clock_cycles(dut, 3)
+    assert int(dut.commit_count_mon.value) == commits + 1
+    assert int(dut.epoch.value) == (epoch + 1) & 0xFFFF
+    assert int(dut.active_bank.value) == 1 - bank
+    assert int(dut.age_seconds.value) == 0
+    expected_raw = [int.from_bytes(case.raw[index : index + 2], "big") for index in range(0, 48, 2)]
+    expected_valid = sum(
+        (case.raw[index : index + 2] != b"\xFF\xFF") << (index // 2)
+        for index in range(0, 48, 2)
+    )
+    observed_raw, observed_valid = await read_channels(dut)
+    assert observed_raw == expected_raw
+    assert observed_valid == expected_valid
+    assert int(dut.active_valid_mask.value) == expected_valid
+
+
+async def expect_reject(dut, line: bytes, *, timeout: bool = False) -> None:
+    commits = int(dut.commit_count_mon.value)
+    errors = int(dut.error_count_mon.value)
+    epoch = int(dut.epoch.value)
+    bank = int(dut.active_bank.value)
+    raw_before, valid_before = await read_channels(dut)
+    await send_bytes(dut, line)
+    if timeout:
+        await clock_cycles(dut, 70)
+    else:
+        await clock_cycles(dut, 3)
+    assert int(dut.commit_count_mon.value) == commits
+    assert int(dut.error_count_mon.value) == errors + 1
+    assert int(dut.epoch.value) == epoch
+    assert int(dut.active_bank.value) == bank
+    raw_after, valid_after = await read_channels(dut)
+    assert (raw_after, valid_after) == (raw_before, valid_before)
+
+
+@cocotb.test()
+async def test_bmc_replay_fuzz_timeout_banks_epoch_and_freshness(dut):
+    dut.tick_1s_test.value = 0
+    dut.rx_valid.value = 0
+    dut.rx_data.value = 0
+    dut.rx_framing_error.value = 0
+    dut.snapshot_lock.value = 0
+    dut.snapshot_lock_bank.value = 0
+    dut.rd_index.value = 0
+    await with_timeout(RisingEdge(dut.rst_n_mon), 1, "ms")
+    await clock_cycles(dut, 3)
+    assert int(dut.age_seconds.value) == 0xFFFF
+    assert int(dut.stale.value) == 1
+
+    cases = generated_cases()
+    baseline = SnapshotCase(
+        channels=tuple((30, 0) for _ in range(24)),
+        lower=False,
+        separator=b" ",
+    )
+
+    # The optional six-byte command echo is a separate non-committing line.
+    await send_bytes(dut, b"36 6c DF dd 00 03\r\n")
+    await clock_cycles(dut, 3)
+    assert int(dut.commit_count_mon.value) == 0
+    assert int(dut.error_count_mon.value) == 0
+
+    # Mixed upper/lower hex, space/tab/no separators, CR, LF, CRLF, FF FF,
+    # consecutive snapshots, atomic bank flips, and exact epochs.
+    for index, case in enumerate(cases):
+        terminator = (b"\r", b"\n", b"\r\n")[index % 3]
+        await expect_commit(dut, case, terminator)
+
+        # Each valid replay also seeds a guaranteed-invalid-character mutation
+        # which must preserve the previously active bank byte-for-byte.
+        mutated = bytearray(case.line)
+        mutated[0] = ord("G")
+        await expect_reject(dut, bytes(mutated) + b"\r")
+
+    # Freshness is reset by a commit, ages on distinct one-second ticks, and
+    # becomes stale at the configured threshold.  A new snapshot clears it.
+    await pulse_tick(dut, 1)
+    assert int(dut.age_seconds.value) == 1 and int(dut.stale.value) == 0
+    await pulse_tick(dut, 1)
+    assert int(dut.age_seconds.value) == 2 and int(dut.stale.value) == 1
+    await expect_commit(dut, baseline, b"\r")
+    assert int(dut.age_seconds.value) == 0 and int(dut.stale.value) == 0
+
+    raw = baseline.raw
+    hex_line = b" ".join(f"{value:02X}".encode("ascii") for value in raw)
+    await expect_reject(dut, b" ".join(f"{value:02X}".encode("ascii") for value in raw[:-1]) + b"\r")
+    await expect_reject(dut, hex_line + b" 00\r")
+    await expect_reject(dut, b"FF" + hex_line[2:] + b"\r")
+    await expect_reject(dut, hex_line[:1] + b" " + hex_line[1:] + b"\r")
+
+    # A UART framing error taints the complete line even when all ASCII bytes
+    # that follow would otherwise be valid.
+    commits = int(dut.commit_count_mon.value)
+    errors = int(dut.error_count_mon.value)
+    await FallingEdge(dut.sys_clk)
+    dut.rx_framing_error.value = 1
+    await FallingEdge(dut.sys_clk)
+    dut.rx_framing_error.value = 0
+    await send_bytes(dut, hex_line + b"\r")
+    await clock_cycles(dut, 3)
+    assert int(dut.commit_count_mon.value) == commits
+    assert int(dut.error_count_mon.value) == errors + 1
+
+    # A half reply with no CR/LF is discarded by the inter-byte timeout.  The
+    # following complete reply starts from a clean nibble/count/echo state.
+    await expect_reject(dut, hex_line[:20], timeout=True)
+    await expect_commit(dut, baseline, b"\n")
+
+    # Snapshot ownership of the inactive bank blocks partial writes and bank
+    # flips until the lock is released.
+    dut.snapshot_lock.value = 1
+    dut.snapshot_lock_bank.value = 1 - int(dut.active_bank.value)
+    await expect_reject(dut, hex_line + b"\r")
+    dut.snapshot_lock.value = 0
+    await expect_commit(dut, baseline, b"\r")

+ 7 - 1
tools/run_6400_v1.py

@@ -87,9 +87,13 @@ def cocotb_integration() -> None:
     run(["python3", "tests/cocotb/run_6400_v1_integration.py"])
 
 
+def bmc_fuzz() -> None:
+    run(["python3", "tests/cocotb/run_6400_bmc_fuzz.py"])
+
+
 def main() -> int:
     parser = argparse.ArgumentParser()
-    parser.add_argument("action", choices=("generate", "lint", "sim", "cocotb", "unit", "all"))
+    parser.add_argument("action", choices=("generate", "lint", "sim", "cocotb", "bmc", "unit", "all"))
     args = parser.parse_args()
     if args.action in ("generate", "all"):
         generate()
@@ -99,6 +103,8 @@ def main() -> int:
         simulation()
     if args.action in ("cocotb", "all"):
         cocotb_integration()
+    if args.action in ("bmc", "all"):
+        bmc_fuzz()
     if args.action in ("unit", "all"):
         unit()
     return 0