# SPDX-License-Identifier: MIT """A portable command debugger over :class:`~upd7725_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 can act as the host (``host`` reads SR, reads or writes a DR byte), so a program's command protocol can be stepped by hand. Numbers are decimal, ``0x1F`` or ``$1F``. """ from __future__ import annotations import shlex from dataclasses import dataclass from typing import TextIO from upd7725_python.debug import DebugSession, StepRecord from upd7725_python.disasm import disassemble, format_instruction from upd7725_python.state import REGISTER_NAMES, 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 and the stack", "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 (off a breakpoint if on one)", "break ADDRESS | b Add a PC breakpoint", "delete ADDRESS Remove a PC breakpoint", "watch INDEX [r|w|rw] Stop after a step that reads/writes data RAM word INDEX", "unwatch INDEX Remove a RAM watchpoint", "hostwatch R|W DR|SR Report host accesses of that kind (see 'host')", "breakpoints List breakpoints and watchpoints", "disassemble [ADDRESS] [COUNT] | d Decode program words", "ram INDEX [COUNT] | m Show data RAM words", "history [COUNT] Show retained step records", "set REGISTER VALUE Set a register (pc rp dp sp k l m n a b flaga flagb ...)", "host sr | host read | host write VALUE Act as the host on the parallel port", "quit | exit | q Leave the command loop", ) _FLAGS = ["S1", "S0", "C", "Z", "OV1", "OV0"] 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 _flags(value: int) -> str: return " ".join(name if value & (0x20 >> i) else name.lower() for i, name in enumerate(_FLAGS)) def format_state(state: CPUState) -> tuple[str, ...]: """Registers, both flag sets, SR and the stack.""" return ( f"PC={state.pc:04X} RP={state.rp:03X} DP={state.dp:03X} SP={state.sp} " f"K={state.k:04X} L={state.l:04X} M={state.m:04X} N={state.n:04X}", f"A={state.a:04X} [{_flags(state.flaga)}] B={state.b:04X} [{_flags(state.flagb)}]", f"TR={state.tr:04X} TRB={state.trb:04X} DR={state.dr:04X} SR={state.sr:04X} " f"SI={state.si:04X} SO={state.so:04X} RQM={int(state.rqm)} DRS={int(state.drs)} " f"DRC={int(state.drc)}", "stack " + " ".join(f"{value:04X}" for value in state.stack), ) def _format_record(record: StepRecord) -> str: ram = " ".join(f"{kind}[{index:03X}]={value:04X}" for kind, index, value in record.ram_accesses) return ( f"#{record.sequence:<7} {record.before.pc:04X} {record.instruction.text:<44} " f"-> PC={record.after.pc:04X} {ram}" ).rstrip() class CommandDebugger: def __init__(self, session: DebugSession) -> None: if not isinstance(session, DebugSession): raise TypeError("session must be a DebugSession") self.session = session 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, dsp = self.session, self.session.dsp 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(dsp.capture_state(ram=False))) if command in ("step", "s"): count = parse_number(args[0], "count") if args else 1 return CommandResult(tuple(_format_record(session.step()) for _ in range(count))) if command in ("run", "continue", "c"): steps = parse_number(args[0], "steps") if command == "run" and args else 1_000_000 if command != "run" and dsp.pc in session.breakpoints: session.step() steps -= 1 result = session.run(max_steps=max(steps, 1)) lines = [f"stopped: {result.reason.value} after {result.steps} steps"] lines += [f" {kind}[{index:03X}] = {value:04X}" for kind, index, value in result.hits] return CommandResult((*lines, *format_state(result.state))) if command in ("break", "b"): session.add_breakpoint(parse_number(args[0], "address")) return CommandResult() if command == "delete": session.remove_breakpoint(parse_number(args[0], "address")) return CommandResult() if command == "watch": session.add_watchpoint( parse_number(args[0], "index"), args[1] if len(args) > 1 else "rw" ) return CommandResult() if command == "unwatch": session.remove_watchpoint(parse_number(args[0], "index")) return CommandResult() if command == "hostwatch": if len(args) != 2: raise CommandError("hostwatch R|W DR|SR") session.add_host_watchpoint(args[0].upper(), args[1].upper()) return CommandResult() if command == "breakpoints": lines = [f"break {address:04X}" for address in sorted(session.breakpoints)] lines += [f"watch {i:03X} {k}" for i, k in sorted(session.watchpoints.items())] lines += [f"hostwatch {d} {p}" for d, p in sorted(session.host_watchpoints)] return CommandResult(tuple(lines)) if command in ("disassemble", "d"): address = parse_number(args[0], "address") if args else dsp.pc count = parse_number(args[1], "count") if len(args) > 1 else 12 lines = [] for offset in range(count): where = (address + offset) & dsp.model.pc_mask lines.append(format_instruction(disassemble(dsp.program[where], where))) return CommandResult(tuple(lines)) if command in ("ram", "m"): index = parse_number(args[0], "index") if args else 0 count = min(parse_number(args[1], "count") if len(args) > 1 else 16, 256) lines = [] for row in range(index, index + count, 8): cells = [ f"{dsp.ram[i % len(dsp.ram)]:04X}" for i in range(row, min(row + 8, index + count)) ] lines.append(f"{row % len(dsp.ram):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 or args[0].lower() not in REGISTER_NAMES: raise CommandError("set REGISTER VALUE") setattr(dsp, args[0].lower(), parse_number(args[1]) & 0xFFFF) return CommandResult() if command == "host": if not args: raise CommandError("host sr | host read | host write VALUE") action = args[0].lower() if action == "sr": value = dsp.read_sr() elif action == "read": value = dsp.read_dr() elif action == "write" and len(args) == 2: value = parse_number(args[1]) & 0xFF dsp.write_dr(value) else: raise CommandError("host sr | host read | host write VALUE") lines = [f"host {action}: {value:02X}"] lines += [ f" watched: {a.direction} {a.port} {a.value:02X}" for a in session.take_host_hits() ] return CommandResult(tuple(lines)) 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("upd7725> ") 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_number"]