summaryrefslogtreecommitdiffstats
path: root/debug/risc-v-gsp-rm-vm/tests/test_discovery.py
blob: 66b2a845c59ccee386c29ecadd72832d16416e78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
"""Integration tests for unknown-call discovery and reachability (docs/19).

The integration tests drive the two harness CLIs as subprocesses against the
bundled demo firmware and skip cleanly when qemu-system-riscv64 or the demo
ELF is absent. The pure-function tests need neither.
"""
from __future__ import annotations

import json
import os
import subprocess
import sys
import tempfile
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
TOOL_ROOT = os.path.abspath(os.path.join(HERE, ".."))
DEMO_ELF = os.path.join(TOOL_ROOT, "firmware", "uproc_demo", "build", "uproc_demo.elf")
DISCOVERY = os.path.join(TOOL_ROOT, "harness", "control_discovery.py")
REACH = os.path.join(TOOL_ROOT, "harness", "reach.py")
if TOOL_ROOT not in sys.path:
    sys.path.insert(0, TOOL_ROOT)

from harness.common import qemu_available  # noqa: E402
from harness.control_discovery import (  # noqa: E402
    DEMO_CASE_HANDLERS,
    classify_outcome,
    generate_probes,
    pattern_args,
)

MASK64 = (1 << 64) - 1


def _run(args: list[str], timeout: float = 120.0) -> subprocess.CompletedProcess:
    return subprocess.run(
        [sys.executable] + args,
        capture_output=True,
        text=True,
        cwd=TOOL_ROOT,
        timeout=timeout,
    )


def _read_findings(out: str) -> list[dict]:
    with open(os.path.join(out, "findings.jsonl"), encoding="utf-8") as fh:
        return [json.loads(line) for line in fh if line.strip()]


class DiscoveryUnitTests(unittest.TestCase):
    def test_pattern_args_deterministic(self):
        self.assertEqual(pattern_args("zero", 1, 3), (0, 0, 0))
        self.assertEqual(pattern_args("boundary", 1, 3), (MASK64, 1, 0x7FFF_FFFF_FFFF_FFFF))
        self.assertEqual(pattern_args("sentinel", 5, 3), pattern_args("sentinel", 5, 3))
        self.assertNotEqual(pattern_args("sentinel", 5, 3), pattern_args("sentinel", 5, 4))
        self.assertTrue(all(0 <= value <= MASK64 for value in pattern_args("sentinel", 9, 1)))

    def test_generate_probes_order_and_cap(self):
        probes = generate_probes(4, ["zero", "sentinel"], seed=1)
        self.assertEqual([probe.cmd for probe in probes], [1, 1, 2, 2, 3, 3, 4, 4])
        self.assertEqual([probe.pattern for probe in probes[0:2]], ["zero", "sentinel"])
        self.assertEqual(len(generate_probes(64, ["zero", "sentinel", "boundary"], seed=1, iterations=5)), 5)

    def test_classify_outcome_priority(self):
        base = dict(cmd=6, is_injected=False, handler="rpc_fault", dispatch_seen=True, call_retval=None)
        self.assertEqual(classify_outcome(faults=[{"cause": 3}], signals=[], settle_ok=True, **base), "trap")
        self.assertEqual(classify_outcome(faults=[{"cause": 5}], signals=[], settle_ok=True, **base), "fault")
        self.assertEqual(classify_outcome(faults=[], signals=[], settle_ok=True, **base), "known-handler")
        self.assertEqual(
            classify_outcome(
                cmd=16, is_injected=True, handler="rpc_ping", dispatch_seen=True, call_retval=None,
                faults=[], signals=[], settle_ok=True,
            ),
            "injected-slot",
        )
        self.assertEqual(
            classify_outcome(
                cmd=7, is_injected=False, handler=None, dispatch_seen=True, call_retval=None,
                faults=[], signals=[], settle_ok=True,
            ),
            "default-path",
        )
        self.assertEqual(
            classify_outcome(
                cmd=7, is_injected=False, handler=None, dispatch_seen=False, call_retval=None,
                faults=[], signals=[], settle_ok=True,
            ),
            "no-progress",
        )
        self.assertEqual(classify_outcome(faults=[], signals=[], settle_ok=False, **base), "settle-failed")


@unittest.skipUnless(qemu_available(), "qemu-system-riscv64 not installed")
@unittest.skipUnless(os.path.exists(DEMO_ELF), "demo firmware not built (make demo)")
class DiscoveryIntegrationTests(unittest.TestCase):
    def test_sweep_classifies_known_and_unknown(self):
        with tempfile.TemporaryDirectory(prefix="discovery-sweep-") as out:
            result = _run(
                [
                    DISCOVERY,
                    "--out", out,
                    "--max-id", "32",
                    "--patterns", "zero",
                    "--seed", "5",
                    "--timeout", "0.25",
                    "--settle", "1.0",
                ]
            )
            self.assertEqual(result.returncode, 0, result.stderr[-2000:])
            findings = _read_findings(out)
            self.assertEqual(len(findings), 32)
            by_cmd: dict[int, dict] = {finding["cmd"]: finding for finding in findings}

            # Known commands 1..6 are attributed to their handlers; zero args
            # make ECHO fault (NULL string) and FAULT trap (ebreak).
            for cmd, name in DEMO_CASE_HANDLERS.items():
                self.assertEqual(by_cmd[cmd]["handler"], name, f"cmd {cmd} handler")
            for cmd in (1, 3, 4, 5):
                self.assertEqual(by_cmd[cmd]["outcome"], "known-handler")
            self.assertEqual(by_cmd[2]["outcome"], "fault")
            self.assertEqual(by_cmd[6]["outcome"], "trap")

            # At least one default/unused id reaches the catch-all with ~id.
            self.assertEqual(by_cmd[7]["outcome"], "default-path")
            self.assertEqual(by_cmd[7]["effects"]["after"]["result"], (~7) & MASK64)
            self.assertEqual(by_cmd[32]["outcome"], "default-path")

            # Injected-service dispatch: 16..21 alias handler slots 0..5.
            self.assertEqual(by_cmd[16]["outcome"], "injected-slot")
            self.assertEqual(by_cmd[16]["handler"], "rpc_ping")
            self.assertEqual(by_cmd[21]["outcome"], "trap")

            report_path = os.path.join(out, "control-discovery.md")
            self.assertTrue(os.path.exists(report_path))
            with open(report_path, encoding="utf-8") as fh:
                report = fh.read()
            self.assertIn("Status: implemented, documented and tested", report)
            self.assertIn("Unknown / undiscovered ids", report)
            self.assertIn("Injected-slot dispatch ids", report)
            self.assertIn("rpc_fault", report)
            self.assertTrue(os.path.isdir(os.path.join(out, "sessions")))

    def test_sweep_deterministic(self):
        base = [
            DISCOVERY,
            "--max-id", "8",
            "--patterns", "zero",
            "--seed", "11",
            "--timeout", "0.25",
            "--settle", "1.0",
        ]
        with tempfile.TemporaryDirectory(prefix="discovery-det-a-") as out_a, tempfile.TemporaryDirectory(
            prefix="discovery-det-b-"
        ) as out_b:
            first = _run(base + ["--out", out_a])
            second = _run(base + ["--out", out_b])
            self.assertEqual(first.returncode, 0, first.stderr[-2000:])
            self.assertEqual(second.returncode, 0, second.stderr[-2000:])
            with open(os.path.join(out_a, "findings.jsonl"), encoding="utf-8") as fa, open(
                os.path.join(out_b, "findings.jsonl"), encoding="utf-8"
            ) as fb:
                self.assertEqual(fa.read(), fb.read(), "same seed/params must replay byte-for-byte")

    def test_rm_surface_exits_cleanly(self):
        with tempfile.TemporaryDirectory(prefix="discovery-rm-") as out:
            result = _run([DISCOVERY, "--surface", "rm", "--out", out])
            self.assertEqual(result.returncode, 0, result.stderr[-2000:])
            self.assertIn("skipped", result.stdout)
            self.assertFalse(os.path.exists(os.path.join(out, "findings.jsonl")))

    def test_reach_rpc_ping_via_call(self):
        with tempfile.TemporaryDirectory(prefix="reach-ping-") as out:
            result = _run([REACH, "--target", "rpc_ping", "--method", "call", "--args", "0x41", "--out", out])
            self.assertEqual(result.returncode, 0, result.stderr[-2000:])
            with open(os.path.join(out, "reach-report.json"), encoding="utf-8") as fh:
                report = json.load(fh)
            self.assertTrue(report["reachable"])
            self.assertEqual(report["method"], "call")
            self.assertEqual(report["entry"]["symbol"], "rpc_ping")
            self.assertEqual(report["effects"]["retval"], 0x41 ^ 0xBEEF)
            self.assertTrue(os.path.exists(os.path.join(out, "probe.json")))
            with open(os.path.join(out, "probe.json"), encoding="utf-8") as fh:
                probe = json.load(fh)
            self.assertEqual(probe["method"], "call")
            self.assertEqual(probe["args"], [0x41])

    def test_reach_rpc_sum_via_run(self):
        with tempfile.TemporaryDirectory(prefix="reach-sum-") as out:
            result = _run([REACH, "--target", "rpc_sum", "--method", "run", "--out", out])
            self.assertEqual(result.returncode, 0, result.stderr[-2000:])
            with open(os.path.join(out, "reach-report.json"), encoding="utf-8") as fh:
                report = json.load(fh)
            self.assertTrue(report["reachable"])
            self.assertEqual(report["method"], "run")
            self.assertEqual(report["entry"]["symbol"], "rpc_sum")
            self.assertTrue(report["prior_events"], "the self-test hook history must be recorded")

    def test_reach_rpc_fault_via_trigger(self):
        with tempfile.TemporaryDirectory(prefix="reach-fault-") as out:
            result = _run([REACH, "--target", "rpc_fault", "--method", "trigger", "--out", out])
            self.assertEqual(result.returncode, 0, result.stderr[-2000:])
            with open(os.path.join(out, "reach-report.json"), encoding="utf-8") as fh:
                report = json.load(fh)
            self.assertTrue(report["reachable"])
            self.assertEqual(report["method"], "trigger")
            self.assertEqual(report["trigger"]["id"], 6)
            self.assertEqual(report["trigger"]["handler"], "rpc_fault")
            self.assertEqual(report["required_args"]["cmd"], 6)
            self.assertTrue(report["effects"]["trap"], "rpc_fault must show the ebreak trap")
            self.assertTrue(os.path.exists(os.path.join(out, "probe.json")))


if __name__ == "__main__":
    unittest.main()