# SPDX-License-Identifier: MIT """A portable command debugger over :class:`~hg51b_python.debug.DebugSession`. ``CommandDebugger.execute(line)`` runs one command and returns printable lines; ``interact(input, output)`` is a line loop with no terminal dependencies. Besides the family's commands it acts as the S-CPU (``host read``/``host write`` on $6000-$7FFF, ``call PB:PC`` = the games' start sequence) so a program can be driven by hand. Numbers are decimal, ``0x1F`` or ``$1F``; program addresses are ``PB:PC`` (hex) or one number ``PB << 8 | PC``. """ from __future__ import annotations import shlex from dataclasses import dataclass from typing import TextIO from hg51b_python.debug import DebugSession, StepRecord from hg51b_python.disasm import disassemble, format_instruction from hg51b_python.state import CPUState class CommandError(ValueError): """A malformed or unsupported command.""" @dataclass(frozen=True, slots=True) class CommandResult: lines: tuple[str, ...] = () quit: bool = False _HELP = ( "help | ? This summary", "registers | regs | r Registers, flags, stack, cache, DMA and bus state", "step [COUNT] | s Execute instructions (ignores breakpoints)", "run STEPS Run with a step limit, stopping at breakpoints/watchpoints", "continue | c Run up to 1,000,000 steps", "break PB:PC | b Add a breakpoint", "delete PB:PC Remove a breakpoint", "watch BYTE [r|w|rw] Stop after a step that reads/writes data RAM BYTE", "unwatch BYTE Remove a data RAM watchpoint", "hostwatch ADDRESS [R|W|RW] Report S-CPU accesses to ADDRESS ($6000-$7FFF)", "buswatch ADDRESS Stop after the chip reads bus ADDRESS", "breakpoints List breakpoints and watchpoints", "disassemble [PB:PC] [COUNT] | d Decode cached words (default: at PB:PC)", "ram BYTE [COUNT] | m Show data RAM bytes", "history [COUNT] Show retained step records", "set REGISTER VALUE Set a register (a p mar mdr dpr r0..r15 pb pc ...)", "host read ADDRESS | host write ADDRESS VALUE Act as the S-CPU", "call PB:PC [PAGE] Start PB:PC as the games do (preload into PAGE, start)", "quit | exit | q Leave the command loop", ) _SETTABLE = {"a", "p", "mar", "mdr", "dpr", "rom", "ram", "pb", "pc", "mul"} def parse_number(text: str, name: str = "value") -> int: try: value = int(text[1:], 16) if text.startswith("$") else int(text, 0) except ValueError as exc: raise CommandError(f"{name} must be an integer") from exc if value < 0: raise CommandError(f"{name} must be non-negative") return value def parse_address(text: str) -> int: """``PB:PC`` in hex, or a number = PB << 8 | PC.""" if ":" in text: pb, _, pc = text.partition(":") try: return int(pb, 16) << 8 | int(pc, 16) & 0xFF except ValueError as exc: raise CommandError("an address is PB:PC in hex") from exc return parse_number(text, "address") def _flags(state: CPUState) -> str: return " ".join(n if getattr(state, n.lower()) else n.lower() for n in ("N", "Z", "C", "V")) def format_state(state: CPUState) -> tuple[str, ...]: """Registers, flags, the stack, and the cache/DMA/bus/control state.""" low = " ".join(f"R{i}={value:06X}" for i, value in enumerate(state.r[:8])) high = " ".join(f"R{i}={value:06X}" for i, value in enumerate(state.r[8:], start=8)) pages = " ".join("-" if address < 0 else f"{address:06X}" for address in state.cache_address) control = [name for name in ("halted", "lock", "suspend_enabled") if getattr(state, name)] return ( f"PB:PC={state.pb:04X}:{state.pc:02X} A={state.a:06X} P={state.p:04X} [{_flags(state)}]" f" MH={state.mh:06X} ML={state.ml:06X}", f"MDR={state.mdr:06X} MAR={state.mar:06X} DPR={state.dpr:06X} ROM={state.rom:06X}" f" RAM={state.ram:06X}", low, high, "stack " + " ".join(f"{entry:06X}" for entry in state.stack), f"cache page {state.cache_page} holds [{pages}] base {state.cache_base:06X}" f" locks {int(state.cache_lock[0])}{int(state.cache_lock[1])}" + (" loading" if state.cache_enabled else ""), f"dma {state.dma_source:06X}->{state.dma_target:06X} x{state.dma_length}" + (" running" if state.dma_enabled else "") + f" bus {'pending ' + str(state.bus_pending) if state.bus_pending else 'idle'}" + f" {' '.join(control) or 'running'} clock {state.clock}", ) def _format_record(record: StepRecord) -> str: ram = " ".join(f"{kind}[{index:03X}]={value:02X}" for kind, index, value in record.ram_accesses) after = record.after return ( f"#{record.sequence:<7} {record.before.pb:04X}:{record.before.pc:02X}" f" {record.instruction.text:<24} -> A={after.a:06X} [{_flags(after)}] {ram}" ).rstrip() class CommandDebugger: def __init__(self, session: DebugSession, harness=None) -> None: if not isinstance(session, DebugSession): raise TypeError("session must be a DebugSession") self.session = session self.harness = harness def execute(self, line: str) -> CommandResult: try: words = shlex.split(line) except ValueError as exc: raise CommandError(str(exc)) from exc if not words: return CommandResult() command, args = words[0].lower(), words[1:] session, cx = self.session, self.session.cx if command in ("help", "?"): return CommandResult(_HELP) if command in ("quit", "exit", "q"): return CommandResult(quit=True) if command in ("registers", "regs", "r"): return CommandResult(format_state(cx.capture_state(memory=False))) if command in ("step", "s"): count = parse_number(args[0], "count") if args else 1 lines = [] for _ in range(count): record = session.step() if record is None: lines.append("(idle)") break lines.append(_format_record(record)) return CommandResult(tuple(lines)) if command in ("run", "continue", "c"): steps = parse_number(args[0], "steps") if command == "run" and args else 1_000_000 result = session.run(max_steps=max(steps, 1)) lines = [f"stopped: {result.reason.value} after {result.steps} steps"] lines += [f" {hit}" for hit in result.hits] return CommandResult((*lines, *format_state(result.state))) if command in ("break", "b"): session.add_breakpoint(parse_address(args[0])) return CommandResult() if command == "delete": session.remove_breakpoint(parse_address(args[0])) return CommandResult() if command == "watch": session.add_watchpoint(parse_number(args[0], "byte"), args[1] if args[1:] else "rw") return CommandResult() if command == "unwatch": session.remove_watchpoint(parse_number(args[0], "byte")) return CommandResult() if command == "hostwatch": kind = args[1].upper() if args[1:] else "RW" session.add_host_watchpoint(parse_number(args[0], "address"), kind) return CommandResult() if command == "buswatch": session.add_bus_watchpoint(parse_number(args[0], "address")) return CommandResult() if command == "breakpoints": lines = [f"break {a >> 8:04X}:{a & 0xFF:02X}" for a in sorted(session.breakpoints)] lines += [f"watch {i:03X} {k}" for i, k in sorted(session.watchpoints.items())] lines += [f"hostwatch {a:04X} {k}" for a, k in sorted(session.host_watchpoints.items())] lines += [f"buswatch {a:06X}" for a in sorted(session.bus_watchpoints)] return CommandResult(tuple(lines)) if command in ("disassemble", "d"): where = parse_address(args[0]) if args else cx.pb << 8 | cx.pc count = parse_number(args[1], "count") if args[1:] else 12 pb = where >> 8 address = (cx.cache_base + (pb << 9)) & 0xFFFFFF if address not in cx.cache_address: return CommandResult((f"PB {pb:04X} is not in the cache",)) words = cx.program_ram[cx.cache_address.index(address)] lines = [ format_instruction(disassemble(words[pc & 0xFF], pb << 8 | (pc & 0xFF))) for pc in range(where & 0xFF, (where & 0xFF) + count) ] return CommandResult(tuple(lines)) if command in ("ram", "m"): start = parse_number(args[0], "byte") if args else 0 count = min(parse_number(args[1], "count") if args[1:] else 64, 3072) lines = [] for row in range(start, start + count, 16): cells = [ f"{cx.data_ram[i % 3072]:02X}" for i in range(row, min(row + 16, start + count)) ] lines.append(f"{row % 3072:03X}: {' '.join(cells)}") return CommandResult(tuple(lines)) if command == "history": count = parse_number(args[0], "count") if args else 16 records = session.history[-count:] if count else () return CommandResult(tuple(_format_record(record) for record in records)) if command == "set": if len(args) != 2: raise CommandError("set REGISTER VALUE") name, value = args[0].lower(), parse_number(args[1]) if name.startswith("r") and name[1:].isdigit() and int(name[1:]) < 16: cx.r[int(name[1:])] = value & 0xFFFFFF elif name in _SETTABLE: setattr(cx, name, value) else: raise CommandError(f"unknown register {name!r}") return CommandResult() if command == "host": if len(args) >= 2 and args[0].lower() == "read": address = parse_number(args[1], "address") return CommandResult((f"host read {address:04X}: {cx.read(address):02X}",)) if len(args) == 3 and args[0].lower() == "write": address, value = parse_number(args[1], "address"), parse_number(args[2]) & 0xFF cx.write(address, value) return CommandResult((f"host write {address:04X} = {value:02X}",)) raise CommandError("host read ADDRESS | host write ADDRESS VALUE") if command == "call": if not args: raise CommandError("call PB:PC [PAGE]") where = parse_address(args[0]) page = parse_number(args[1], "page") & 1 if args[1:] else 0 cx.write(0x7F4D, where >> 8 & 0xFF) cx.write(0x7F4E, where >> 16) cx.write(0x7F48, page) cx.write(0x7F4F, where & 0xFF) return CommandResult((f"started {where >> 8:04X}:{where & 0xFF:02X}",)) raise CommandError(f"unknown command {command!r} (help lists them)") def interact(self, stream_in: TextIO, stream_out: TextIO) -> None: while True: stream_out.write("hg51b> ") stream_out.flush() line = stream_in.readline() if not line: return try: result = self.execute(line) except (CommandError, ValueError) as exc: stream_out.write(f"error: {exc}\n") continue for text in result.lines: stream_out.write(text + "\n") if result.quit: return __all__ = [ "CommandDebugger", "CommandError", "CommandResult", "format_state", "parse_address", "parse_number", ]