"""Portable command debugger built as a thin frontend over DebugSession. ``CommandDebugger.execute(line)`` runs one command and returns printable lines; ``interact(input, output)`` is a line-oriented loop with no terminal dependencies. ``python -m arm7tdmi_python ROM --debug`` starts one on a program in the minimal harness. The command set matches the family's (z80-python, sm83-python) with ARM's registers, banks and PSRs, a bus-cycle view typed N/S/I/C, and watchpoints that see internal cycles. """ from __future__ import annotations import shlex from collections.abc import Callable, Mapping, Sequence from dataclasses import dataclass from pathlib import Path from typing import TextIO from arm7tdmi_python._modes import BANK_FIQ, BANK_USER, MODE_BITS, bank_of from arm7tdmi_python.debug import ( BoundaryKind, DebugSession, RunResult, StepRecord, next_instruction, ) from arm7tdmi_python.disasm import REGISTERS as NAMES from arm7tdmi_python.disasm import ByteReader, Instruction, disassemble from arm7tdmi_python.state import CPUState class CommandError(ValueError): """A malformed or unsupported debugger command.""" @dataclass(frozen=True, slots=True) class CommandResult: """Rendered lines and control state returned by one debugger command.""" lines: tuple[str, ...] = () quit: bool = False _HELP = ( "help | ? Show this command summary", "registers | regs | r Registers, CPSR, the current SPSR and the next instruction", "banks Every mode's banked registers and SPSR", "step [COUNT] | s Run one or more boundaries (ignores breakpoints)", "over | o Step, running a BL, Thumb BL pair or SWI through to its return", "until ADDRESS | u Run until the instruction at ADDRESS", "run STEPS [CYCLES] Run with a finite step and optional cycle limit", "continue | c Run up to 1,000,000 steps, off a breakpoint if on one", "break ADDRESS | b Add an execute breakpoint", "delete ADDRESS Remove an execute breakpoint", "breakpoints List breakpoints and watchpoints", "watch ADDRESS [r|w|i...] [LEN] Stop after a step with a read, write or internal cycle there", "unwatch ADDRESS Remove a watchpoint", "cycles [STEPS] The bus cycles of the last steps, typed N, S, I, C", "disassemble [ADDR] [N] [arm|thumb] | d Decode from memory (default: PC, current state)", "memory ADDRESS [LENGTH] [b|h|w] | m Show up to 256 bytes as bytes, halfwords or words", "history [COUNT] Show retained step records", "set REGISTER VALUE R0-R15 SP LR PC CPSR SPSR; PC refills the pipeline,", " CPSR swaps banks (set PC after changing T)", "irq on|off, fiq on|off Drive the interrupt lines", "load FILE [ADDRESS] Copy a raw binary (or an ELF's segments) into memory", "quit | exit | q Leave the command loop", "Numbers are decimal; 0x1234 or $1234 is hexadecimal.", ) MODES = {0x10: "USR", 0x11: "FIQ", 0x12: "IRQ", 0x13: "SVC", 0x17: "ABT", 0x1B: "UND"} MODES[0x1F] = "SYS" BANK_NAMES = ("USR/SYS", "FIQ", "SVC", "ABT", "IRQ", "UND") ALIASES = {**{f"R{n}": n for n in range(16)}, "SP": 13, "LR": 14, "PC": 15} def parse_number(text: str, name: str = "value", *, maximum: int = 0xFFFFFFFF) -> int: """Parse a debugger number: decimal, or hexadecimal written ``0x1234`` or ``$1234``.""" 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 not 0 <= value <= maximum: raise CommandError(f"{name} must be in range 0..{maximum:#x}") return value def _positive(text: str, name: str) -> int: value = parse_number(text, name) if value == 0: raise CommandError(f"{name} must be positive") return value def format_psr(value: int) -> str: """``nZCv IFt SYS``: flags in capitals when set, the mask and state bits, the mode.""" flags = "".join(c if value & (1 << (31 - i)) else c.lower() for i, c in enumerate("NZCV")) bits = "".join(c if value & bit else c.lower() for c, bit in (("I", 0x80), ("F", 0x40))) state = "T" if value & 0x20 else "t" return f"{value:08X} {flags} {bits}{state} {MODES.get(value & MODE_BITS, '???')}" def format_instruction(instruction: Instruction) -> str: """``address encoding text ; comment``; a Thumb BL pair shows both halfwords.""" data = instruction.data if instruction.thumb: raw = " ".join( f"{int.from_bytes(data[i : i + 2], 'little'):04X}" for i in (0, 2)[: len(data) // 2] ) else: raw = f"{int.from_bytes(data, 'little'):08X}" return f"{instruction.address:08X} {raw:<9} {instruction.listing}" def format_state(state: CPUState) -> tuple[str, ...]: """Four rows of registers, the PSRs, and the instruction the next step runs.""" r = state.registers rows = [ " ".join(f"{NAMES[n]:>3}={r[n]:08X}" for n in range(row, row + 4)) for row in (0, 4, 8, 12) ] bank = bank_of(state.cpsr) spsr = "--------" if bank in (BANK_USER, 6) else format_psr(state.spsr[bank]) rows.append(f"CPSR={format_psr(state.cpsr)} SPSR={spsr}") rows.append(f"next {format_instruction(next_instruction(state))}") return tuple(rows) def format_banks(state: CPUState) -> tuple[str, ...]: """Every bank: R8-R14 for User/System and FIQ, R13-R14 and the SPSR for the others.""" lines = [] for bank, name in enumerate(BANK_NAMES): values = state.banks[bank] if bank in (BANK_USER, BANK_FIQ): registers = " ".join(f"{NAMES[8 + i]}={v:08X}" for i, v in enumerate(values)) else: registers = f"SP={values[5]:08X} LR={values[6]:08X}" spsr = "" if bank == BANK_USER else f" SPSR={format_psr(state.spsr[bank])}" lines.append(f"{name:<7} {registers}{spsr}") return tuple(lines) def format_record(record: StepRecord) -> str: if record.instruction is not None: what = record.instruction.text else: what = f"<{record.kind.value} entry>" after = record.after.registers[15] - (4 if record.after.cpsr & 0x20 else 8) return ( f"#{record.sequence:<6} {record.address:08X} {what:<32} {record.cycles:>2} cycles" f" -> {after & 0xFFFFFFFF:08X}" ) class CommandDebugger: """A line-oriented command frontend for one :class:`DebugSession`. ``stop_when``, if given, ends ``continue`` and ``run`` when it becomes true (the command-line front end passes the harness's branch-to-itself check); ``stop_label`` names it in the stop line, as a string or a function called when it fires. ``loader`` copies an image into the host's memory for ``load`` (``loader(address, data)``). A board adds its own commands with ``commands``: a mapping from a tuple of names to ``(handler, help_lines)``, where ``handler(args)`` returns a :class:`CommandResult` (or raises :class:`CommandError`) and ``help_lines`` join the ``help`` listing. A board name that matches a built-in one replaces it. """ def __init__( self, session: DebugSession, *, stop_when: Callable[[], bool] | None = None, stop_label: str | Callable[[], str] = "the host's stop condition (branch to itself)", loader: Callable[[int, bytes], None] | None = None, commands: Mapping[ tuple[str, ...], tuple[Callable[[list[str]], CommandResult], Sequence[str]] ] | None = None, ) -> None: if not isinstance(session, DebugSession): raise TypeError("session must be a DebugSession") self.session = session self.stop_when = stop_when self.stop_label = stop_label self.loader = loader self.commands = dict(commands or {}) def execute(self, line: str) -> CommandResult: """Run one command line; raises :class:`CommandError` if it is malformed. An error the host raises while running (the minimal harness's ``EnteredBIOS``) comes back as lines; the instruction it interrupted may be half done.""" try: words = shlex.split(line) except ValueError as exc: raise CommandError(str(exc)) from exc if not words: return CommandResult() name, args = words[0].lower(), words[1:] handlers = { ("help", "?"): self._help, ("registers", "regs", "r"): self._registers, ("banks",): self._banks, ("step", "s"): self._step, ("over", "o"): self._over, ("until", "u"): self._until, ("run",): self._run, ("continue", "c"): self._continue, ("break", "b"): self._break, ("delete",): self._delete, ("breakpoints",): self._breakpoints, ("watch",): self._watch, ("unwatch",): self._unwatch, ("cycles",): self._cycles, ("disassemble", "d"): self._disassemble, ("memory", "m"): self._memory, ("history",): self._history, ("set",): self._set, ("irq",): lambda args: self._line("irq", args), ("fiq",): lambda args: self._line("fiq", args), ("load",): self._load, ("quit", "exit", "q"): lambda args: CommandResult(quit=True), } if self.commands: claimed = {n for names in self.commands for n in names} handlers = { names: handler for names, handler in handlers.items() if not claimed.intersection(names) } handlers.update({names: entry[0] for names, entry in self.commands.items()}) for names, handler in handlers.items(): if name in names: try: return handler(args) except RuntimeError as exc: lines = (f"stopped by the host: {exc}", *format_state(self._state())) return CommandResult(lines) raise CommandError(f"unknown command {name!r}; try 'help'") def interact(self, source: TextIO, sink: TextIO, prompt: str = "arm7> ") -> None: """Read commands from ``source`` until ``quit`` or end of input.""" print(prompt, end="", file=sink, flush=True) for line in source: try: result = self.execute(line) except CommandError as exc: print(f"error: {exc}", file=sink) else: for out in result.lines: print(out, file=sink) if result.quit: return print(prompt, end="", file=sink, flush=True) # ----- commands ------------------------------------------------------ def _help(self, args: list[str]) -> CommandResult: extra = tuple(line for _, lines in self.commands.values() for line in lines) return CommandResult(_HELP[:-1] + extra + _HELP[-1:]) def _state(self) -> CPUState: return self.session.target.capture_state() def _registers(self, args: list[str]) -> CommandResult: return CommandResult(format_state(self._state())) def _banks(self, args: list[str]) -> CommandResult: return CommandResult(format_banks(self._state())) def _step(self, args: list[str]) -> CommandResult: count = _positive(args[0], "count") if args else 1 lines = [format_record(self.session.step()) for _ in range(min(count, 1000))] return CommandResult((*lines, *format_state(self._state()))) def _over(self, args: list[str]) -> CommandResult: result = self.session.step_over() return CommandResult((self._describe(result), *format_state(result.state))) def _until(self, args: list[str]) -> CommandResult: if len(args) != 1: raise CommandError("until needs one address") address = parse_number(args[0], "address") result = self.session.run(max_steps=1_000_000, until=address, stop_when=self.stop_when) return CommandResult((self._describe(result), *format_state(result.state))) def _describe(self, result: RunResult) -> str: reason = result.reason.value if reason == "condition": label = self.stop_label if isinstance(self.stop_label, str) else self.stop_label() reason = f"stopped: {label}" text = f"{reason}: {result.steps} steps, {result.cycles} cycles" if result.hits: text += f"; {result.hits[0].text}" return text def _run(self, args: list[str]) -> CommandResult: if not args: raise CommandError("run needs a step count") steps = _positive(args[0], "steps") cycles = _positive(args[1], "cycles") if len(args) > 1 else None result = self.session.run(max_steps=steps, max_cycles=cycles, stop_when=self.stop_when) return CommandResult((self._describe(result), *format_state(result.state))) def _continue(self, args: list[str]) -> CommandResult: session = self.session lines: list[str] = [] state = self._state() if next_instruction(state).address in session.breakpoints: lines.append(format_record(session.step())) result = session.run(max_steps=1_000_000, stop_when=self.stop_when) return CommandResult((*lines, self._describe(result), *format_state(result.state))) def _break(self, args: list[str]) -> CommandResult: if len(args) != 1: raise CommandError("break needs one address") address = parse_number(args[0], "address") self.session.add_breakpoint(address) return CommandResult((f"breakpoint at {address:08X}",)) def _delete(self, args: list[str]) -> CommandResult: if len(args) != 1: raise CommandError("delete needs one address") self.session.remove_breakpoint(parse_number(args[0], "address")) return CommandResult() def _breakpoints(self, args: list[str]) -> CommandResult: session = self.session lines = [f"break {a:08X}" for a in sorted(session.breakpoints)] for address, (kind, length) in sorted(session.watchpoints.items()): lines.append(f"watch {address:08X} {kind} {length}") return CommandResult(tuple(lines) or ("none",)) def _watch(self, args: list[str]) -> CommandResult: if not 1 <= len(args) <= 3: raise CommandError("watch needs an address, optional r/w/i letters and a length") address = parse_number(args[0], "address") kind = args[1] if len(args) > 1 else "rw" length = _positive(args[2], "length") if len(args) > 2 else 1 try: self.session.add_watchpoint(address, kind, length) except ValueError as exc: raise CommandError(str(exc)) from exc return CommandResult((f"watchpoint at {address:08X} ({kind}, {length} bytes)",)) def _unwatch(self, args: list[str]) -> CommandResult: if len(args) != 1: raise CommandError("unwatch needs one address") self.session.remove_watchpoint(parse_number(args[0], "address")) return CommandResult() def _cycles(self, args: list[str]) -> CommandResult: if not self.session.tracking: raise CommandError("this session does not track the bus") count = _positive(args[0], "steps") if args else 1 lines = [] for record in self.session.history[-count:]: lines.append(format_record(record)) lines += [f" {cycle.text}" for cycle in record.accesses or ()] return CommandResult(tuple(lines) or ("no history",)) def _peek(self) -> ByteReader: peek = self.session.peek_byte if peek is None: raise CommandError("this session has no peek_byte") return peek def _disassemble(self, args: list[str]) -> CommandResult: peek = self._peek() state = self._state() thumb = bool(state.cpsr & 0x20) words = list(args) if words and words[-1].lower() in ("arm", "thumb"): thumb = words.pop().lower() == "thumb" address = parse_number(words[0], "address") if words else next_instruction(state).address count = _positive(words[1], "count") if len(words) > 1 else 8 lines = [] for _ in range(min(count, 256)): instruction = disassemble(peek, address, thumb) lines.append(format_instruction(instruction)) address = instruction.next_address return CommandResult(tuple(lines)) def _memory(self, args: list[str]) -> CommandResult: peek = self._peek() if not args: raise CommandError("memory needs an address") address = parse_number(args[0], "address") length = _positive(args[1], "length") if len(args) > 1 else 64 unit = {"b": 1, "h": 2, "w": 4}.get(args[2].lower() if len(args) > 2 else "b") if unit is None: raise CommandError("the unit is b, h or w") address &= ~(unit - 1) length = min(length, 256) lines = [] for start in range(address, address + length, 16): cells = [] for offset in range(0, min(16, address + length - start), unit): value = 0 for i in range(unit): value |= peek((start + offset + i) & 0xFFFFFFFF) << (8 * i) cells.append(f"{value:0{2 * unit}X}") lines.append(f"{start & 0xFFFFFFFF:08X} " + " ".join(cells)) return CommandResult(tuple(lines)) def _history(self, args: list[str]) -> CommandResult: count = _positive(args[0], "count") if args else 10 records = self.session.history[-count:] return CommandResult(tuple(format_record(r) for r in records) or ("no history",)) def _set(self, args: list[str]) -> CommandResult: if len(args) != 2: raise CommandError("set needs a register and a value") register = args[0].upper() value = parse_number(args[1], "value") cpu = self.session.cpu if register == "PC": cpu.start_at(value) # a write to R15 refills the pipeline: two fetches elif register in ALIASES: cpu.r[ALIASES[register]] = value elif register == "CPSR": cpu._switch_mode(value & MODE_BITS) # swap banks as an MSR would cpu.cpsr = value elif register == "SPSR": bank = bank_of(cpu.cpsr) if bank in (BANK_USER, 6): raise CommandError("this mode has no SPSR") cpu.spsr[bank] = value else: raise CommandError(f"unknown register {args[0]!r}") return CommandResult(format_state(self._state())) def _line(self, name: str, args: list[str]) -> CommandResult: if len(args) != 1 or args[0].lower() not in ("on", "off"): raise CommandError(f"{name} needs on or off") setattr(self.session.cpu, name, args[0].lower() == "on") pending = self.session.cpu.pending_interrupt() note = {0x11: "FIQ", 0x12: "IRQ"}.get(pending, "nothing") return CommandResult((f"{name} line {args[0].lower()}; the next step takes {note}",)) def _load(self, args: list[str]) -> CommandResult: if self.loader is None: raise CommandError("this host cannot load images") if not 1 <= len(args) <= 2: raise CommandError("load needs a file and, for a raw binary, an address") from arm7tdmi_python.harness import elf_image data = Path(args[0]).read_bytes() if data[:4] == b"\x7fELF": segments, entry = elf_image(data) for address, chunk in segments: self.loader(address, chunk) return CommandResult( (f"loaded {len(segments)} ELF segments; entry {entry:08X} (set PC to start)",) ) if len(args) != 2: raise CommandError("a raw binary needs a load address") address = parse_number(args[1], "address") self.loader(address, data) return CommandResult((f"loaded {len(data)} bytes at {address:08X}",)) __all__ = [ "BoundaryKind", "CommandDebugger", "CommandError", "CommandResult", "format_banks", "format_instruction", "format_psr", "format_record", "format_state", "parse_number", ]