"""The board's command debugger: arm7tdmi-python's console over a whole GBA. ``python -m gba_python ROM --debug`` opens it. The CPU commands are the core's (``arm7tdmi_python.console.CommandDebugger``: registers, banks, stepping, breakpoints, bus watchpoints, listings, memory); this module gives it a board target, a side-effect-free peek over the board's memory, and the board's own commands through the core's ``commands`` hook: - one step is one CPU boundary on the board, and the instruction that halts the CPU runs the HALT up to its wake-up; every count is in system clocks, wait states and DMA included; - ``io`` shows the I/O registers by name (written values for the write-only ones); - ``video`` shows where the picture is (frame, VCOUNT, line cycle and dot, the flags, mode); - ``break irq|dma|halt|self|line N`` stop on an interrupt entry, a DMA transfer, a HALT, a branch to itself (where test ROMs end) or the start of a line, beside the core's address breakpoints; ``frame [N]`` runs N frames; - ``png FILE`` and ``layer N FILE`` write the last finished frame or one background's whole plane; ``state save|load FILE`` keep and restore the whole console (``gba_python.state``). The session tracks the bus where the core makes its cycles, before the board adds wait states (arm7tdmi-python docs/debugging.md "From a board"). """ from __future__ import annotations import sys from collections.abc import Callable, Sequence from pathlib import Path from typing import TextIO from arm7tdmi_python.console import ( CommandDebugger, CommandError, CommandResult, format_record, format_state, parse_number, ) from arm7tdmi_python.debug import DebugSession, next_instruction from gba_python import state from gba_python.board import GBA from gba_python.ppu.background import ( DIRECT, TEXT_BLOCKS, Latch, affine_line, bitmap_line, text_line, ) from gba_python.testrom import at_branch_to_self, rgb_png, screen_png HALT_LIMIT = 280896 # a HALT longer than a frame is stepped a frame at a time #: GBATEK's names for the I/O registers: name -> (offset, bits) IO_NAMES: dict[str, tuple[int, int]] = { "DISPCNT": (0x000, 16), "GREENSWAP": (0x002, 16), "DISPSTAT": (0x004, 16), "VCOUNT": (0x006, 16), **{f"BG{n}CNT": (0x008 + 2 * n, 16) for n in range(4)}, **{f"BG{n}HOFS": (0x010 + 4 * n, 16) for n in range(4)}, **{f"BG{n}VOFS": (0x012 + 4 * n, 16) for n in range(4)}, **{ f"BG{n}{name}": (base + offset, bits) for n, base in ((2, 0x020), (3, 0x030)) for name, offset, bits in ( ("PA", 0, 16), ("PB", 2, 16), ("PC", 4, 16), ("PD", 6, 16), ("X", 8, 32), ("Y", 12, 32), ) }, "WIN0H": (0x040, 16), "WIN1H": (0x042, 16), "WIN0V": (0x044, 16), "WIN1V": (0x046, 16), "WININ": (0x048, 16), "WINOUT": (0x04A, 16), "MOSAIC": (0x04C, 16), "BLDCNT": (0x050, 16), "BLDALPHA": (0x052, 16), "BLDY": (0x054, 16), "SOUND1CNT_L": (0x060, 16), "SOUND1CNT_H": (0x062, 16), "SOUND1CNT_X": (0x064, 16), "SOUND2CNT_L": (0x068, 16), "SOUND2CNT_H": (0x06C, 16), "SOUND3CNT_L": (0x070, 16), "SOUND3CNT_H": (0x072, 16), "SOUND3CNT_X": (0x074, 16), "SOUND4CNT_L": (0x078, 16), "SOUND4CNT_H": (0x07C, 16), "SOUNDCNT_L": (0x080, 16), "SOUNDCNT_H": (0x082, 16), "SOUNDCNT_X": (0x084, 16), "SOUNDBIAS": (0x088, 16), **{ f"DMA{n}{name}": (0x0B0 + 12 * n + offset, bits) for n in range(4) for name, offset, bits in (("SAD", 0, 32), ("DAD", 4, 32), ("CNT_L", 8, 16)) }, **{f"DMA{n}CNT_H": (0x0BA + 12 * n, 16) for n in range(4)}, **{f"TM{n}CNT_L": (0x100 + 4 * n, 16) for n in range(4)}, **{f"TM{n}CNT_H": (0x102 + 4 * n, 16) for n in range(4)}, "SIODATA32": (0x120, 32), "SIOCNT": (0x128, 16), "SIOMLT_SEND": (0x12A, 16), "KEYINPUT": (0x130, 16), "KEYCNT": (0x132, 16), "RCNT": (0x134, 16), "JOYCNT": (0x140, 16), "JOY_RECV": (0x150, 32), "JOY_TRANS": (0x154, 32), "JOYSTAT": (0x158, 16), "IE": (0x200, 16), "IF": (0x202, 16), "WAITCNT": (0x204, 16), "IME": (0x208, 16), "POSTFLG": (0x300, 8), } #: what ``io`` shows with no names: the registers most runs are about IO_SUMMARY = ( ("DISPCNT", "DISPSTAT", "VCOUNT", "BLDCNT"), ("BG0CNT", "BG1CNT", "BG2CNT", "BG3CNT"), ("IE", "IF", "IME", "WAITCNT"), ("KEYINPUT", "KEYCNT", "SOUNDCNT_H", "SOUNDCNT_X"), ) BREAK_KINDS = ("irq", "dma", "line", "halt", "self") _HELP = ( "io [NAME|ADDRESS ...] I/O registers by name (no names: a summary, DMA, timers)", "video Frame, VCOUNT, line cycle and dot, flags, mode, layers", "break irq|dma|halt|self|line N Also stop at an IRQ entry, after a DMA transfer, at a HALT,", " at a branch to itself, or when line N starts", "delete irq|dma|halt|self|line Remove a board breakpoint (delete ADDRESS as before)", "frame [COUNT] Run until COUNT frames end (breakpoints still stop it)", "png FILE Write the last finished frame as a PNG", "layer 0-3 FILE Write a background's whole plane as a PNG", "state save|load FILE Keep or restore the whole console", ) def peek_byte(gba: GBA, address: int) -> int: """A byte of the board's memory as the bus would map it, with no side effects: no clocks, no open bus, the BIOS readable everywhere, I/O through its read masks (0 if unreadable).""" address &= 0xFFFFFFFF page = address >> 24 if page == 0x00: return gba.bios_data[address] if address < len(gba.bios_data) else 0 if page == 0x02: return gba.ewram[address & 0x3FFFF] if page == 0x03: return gba.iwram[address & 0x7FFF] if page == 0x04: offset = address & 0xFFFFFF if offset < 0x400: half = gba.io._read_half(offset & 0x3FE) return 0 if half is None else half >> ((offset & 1) << 3) & 0xFF if offset & 0xFFFC == 0x800: return gba.memctl >> ((offset & 3) << 3) & 0xFF return 0 if page == 0x05: return gba.ppu.palette[address & 0x3FF] if page == 0x06: offset = address & 0x1FFFF return gba.ppu.vram[offset - 0x8000 if offset >= 0x18000 else offset] if page == 0x07: return gba.ppu.oam[address & 0x3FF] if 0x08 <= page <= 0x0D: offset = address & 0x01FFFFFF rom = gba.cartridge.rom return rom[offset] if offset < len(rom) else (offset >> 1 >> ((offset & 1) << 3)) & 0xFF if page in (0x0E, 0x0F): sram = getattr(gba.cartridge, "sram", None) data = getattr(sram, "data", None) return data[address & (len(data) - 1)] if data else 0xFF return 0 class BoardTarget: """One step is one CPU boundary on the board. The instruction that halts the CPU (the BIOS's write to HALTCNT) lasts until the wake-up: its step runs the HALT too, so a step never starts halted. A HALT longer than a frame is cut at the frame and goes on in the next steps, which run no instruction.""" def __init__(self, gba: GBA) -> None: self.gba, self.cpu = gba, gba.cpu self.halts = 0 # steps that halted the CPU (the debugger's ``break halt``) def step(self) -> int: gba = self.gba start = gba.scheduler.now if gba.halted: gba._run_halted(start + HALT_LIMIT) return gba.scheduler.now - start self.cpu.step() if gba.halted: self.halts += 1 gba._run_halted(gba.scheduler.now + HALT_LIMIT) return gba.scheduler.now - start def capture_state(self): return self.cpu.capture_state() class BoardDebugger: """The core's ``CommandDebugger`` with the board's target, peek and commands.""" def __init__(self, gba: GBA, *, history_limit: int = 256) -> None: self.gba = gba self.history_limit = history_limit self.watch: set[str] = set() # board breakpoints: irq, dma, halt self.lines: set[int] = set() # break at the start of these lines self._frame_target: int | None = None self._last_line: int | None = None self._last_dma = 0 self._last_halts = 0 self._fired = "" self.session = self._session(gba) commands: dict[tuple[str, ...], tuple[Callable[[list[str]], CommandResult], Sequence]] = { ("io",): (self._io, _HELP[0:1]), ("video", "v"): (self._video, _HELP[1:2]), ("break", "b"): (self._break, _HELP[2:4]), ("delete",): (self._delete, _HELP[4:5]), ("frame", "f"): (self._frame, _HELP[5:6]), ("png",): (self._png, _HELP[6:7]), ("layer",): (self._layer, _HELP[7:8]), ("state",): (self._state, _HELP[8:9]), ("breakpoints",): (self._breakpoints, ()), } self.debugger = CommandDebugger( self.session, stop_when=self._stop_when, stop_label=lambda: self._fired, commands=commands, ) def _session(self, gba: GBA) -> DebugSession: return DebugSession( BoardTarget(gba), peek_byte=lambda address: peek_byte(gba, address), history_limit=self.history_limit, track_accesses=True, ) def execute(self, line: str) -> CommandResult: self._arm() return self.debugger.execute(line) def interact(self, source: TextIO, sink: TextIO, prompt: str = "gba> ") -> 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) # ----- stop conditions ------------------------------------------------------------ def _arm(self) -> None: """Take the present as the baseline, so a run stops on changes from here on.""" self._last_line = self.gba.ppu.vcount self._last_dma = self.gba.dma.transfers self._last_halts = self.session.target.halts def _stop_when(self) -> bool: gba = self.gba fired = "" if self._frame_target is not None and gba.ppu.frame >= self._frame_target: fired = f"frame {gba.ppu.frame} ended" elif "irq" in self.watch and gba.cpu.pending_interrupt() == 0x12: fired = f"IRQ entry (IE {gba.irq.ie:04X} IF {gba.irq.if_:04X})" elif "halt" in self.watch and self.session.target.halts != self._last_halts: fired = "the last step halted the CPU until an interrupt" elif "self" in self.watch and at_branch_to_self(gba): fired = "a branch to itself" elif "dma" in self.watch and gba.dma.transfers != self._last_dma: fired = "a DMA transfer ran in the last step" line = gba.ppu.vcount if not fired and line != self._last_line and line in self.lines: fired = f"line {line} started" self._last_line = line self._last_dma = gba.dma.transfers self._last_halts = self.session.target.halts if fired: self._fired = fired return bool(fired) # ----- commands ------------------------------------------------------------------- def _io(self, args: list[str]) -> CommandResult: if not args: lines = [" ".join(self._io_value(name) for name in row) for row in IO_SUMMARY] lines += self._dma_lines() + self._timer_lines() return CommandResult(tuple(lines)) lines = [] for word in args: name = word.upper() if name not in IO_NAMES: offset = parse_number(word, "register") & 0x3FF found = [n for n, (o, _) in IO_NAMES.items() if o == offset] if not found: raise CommandError(f"no I/O register at {offset:03X}") name = found[0] lines.append(self._io_value(name)) return CommandResult(tuple(lines)) def _io_value(self, name: str) -> str: """``NAME=value``; write-only registers show what was written (``w``).""" offset, bits = IO_NAMES[name] gba = self.gba value = None if bits == 32: low, high = gba.io._read_half(offset), gba.io._read_half(offset + 2) if low is not None or high is not None: value = (low or 0) | (high or 0) << 16 else: value = gba.io._read_half(offset & ~1) if value is not None and bits == 8: value &= 0xFF if value is not None: return f"{name}={value:0{bits // 4}X}" written = self._written(offset, bits) if written is None: return f"{name}=----" return f"{name}={written:0{bits // 4}X}w" def _written(self, offset: int, bits: int) -> int | None: gba = self.gba if offset < 0x60: regs = gba.ppu.registers value = regs[offset >> 1] return value | regs[(offset >> 1) + 1] << 16 if bits == 32 else value if offset < 0xA8: return gba.apu.registers[offset >> 1] if 0xB0 <= offset < 0xE0: channel = gba.dma.channels[(offset - 0xB0) // 12] return (channel.src, channel.dst, channel.length)[((offset - 0xB0) % 12) // 4] if 0x100 <= offset < 0x110 and not offset & 2: return gba.timers.channels[(offset - 0x100) >> 2].reload return None def _dma_lines(self) -> list[str]: return [ f"DMA{channel.id} {'on ' if channel.enable else 'off'} CNT_H={channel.cnt_h:04X}" f" SAD={channel.src:08X} DAD={channel.dst:08X} CNT_L={channel.length:04X}" f" now src {channel.latch_src:08X} dst {channel.latch_dst:08X}" f" left {channel.latch_length:X}" for channel in self.gba.dma.channels ] def _timer_lines(self) -> list[str]: timers = self.gba.timers return [ f"TM{channel.id} {'on ' if channel.enable else 'off'}" f" counter={timers.read_counter(channel.id):04X} reload={channel.reload:04X}" f" CNT_H={channel.control:04X}" for channel in timers.channels ] def _video(self, args: list[str]) -> CommandResult: gba = self.gba ppu = gba.ppu cycle = gba.scheduler.now - ppu.line_start dispcnt = ppu.registers[0] layers = [f"BG{n}" for n in range(4) if dispcnt & (0x100 << n)] layers += ["OBJ"] * bool(dispcnt & 0x1000) flags = [ name for name, on in ( ("VBlank", ppu.vblank_flag), ("HBlank", ppu.hblank_flag), ("VCount", ppu.vcount_flag), ("forced blank", dispcnt & 0x80), ("halted", gba.halted), # only in a HALT longer than a frame ) if on ] return CommandResult( ( f"frame {ppu.frame} VCOUNT {ppu.vcount} line cycle {cycle} (dot {cycle >> 2})", f"cycles {gba.scheduler.now:,} mode {dispcnt & 7} layers {' '.join(layers)}", "flags " + (", ".join(flags) or "none"), ) ) def _break(self, args: list[str]) -> CommandResult: kind = args[0].lower() if args else "" if kind not in BREAK_KINDS: return self.debugger._break(args) if kind == "line": if len(args) != 2: raise CommandError("break line needs a line number") line = parse_number(args[1], "line") if line > 227: raise CommandError("lines are 0-227") self.lines.add(line) return CommandResult((f"break when line {line} starts",)) self.watch.add(kind) return CommandResult((f"break on {kind}",)) def _delete(self, args: list[str]) -> CommandResult: kind = args[0].lower() if args else "" if kind not in BREAK_KINDS: return self.debugger._delete(args) if kind == "line": if len(args) == 2: self.lines.discard(parse_number(args[1], "line")) else: self.lines.clear() else: self.watch.discard(kind) return CommandResult((f"deleted {' '.join(args)}",)) def _breakpoints(self, args: list[str]) -> CommandResult: lines = list(self.debugger._breakpoints(args).lines) lines += [f"break {kind}" for kind in sorted(self.watch)] lines += [f"break line {line}" for line in sorted(self.lines)] if len(lines) > 1 and lines[0] == "none": lines.pop(0) return CommandResult(tuple(lines)) def _frame(self, args: list[str]) -> CommandResult: count = parse_number(args[0], "count") if args else 1 if count < 1: raise CommandError("frame needs a positive count") session = self.session lines: list[str] = [] if next_instruction(session.target.capture_state()).address in session.breakpoints: lines.append(format_record(session.step())) # off the breakpoint, as continue does self._frame_target = self.gba.ppu.frame + count try: result = session.run(max_steps=2_000_000 * count, stop_when=self._stop_when) finally: self._frame_target = None described = self.debugger._describe(result) return CommandResult((*lines, described, *format_state(result.state))) def _png(self, args: list[str]) -> CommandResult: if len(args) != 1: raise CommandError("png needs a file") Path(args[0]).write_bytes(screen_png(self.gba)) frames = self.gba.ppu.frame return CommandResult((f"wrote the last finished frame ({frames} so far) to {args[0]}",)) def _layer(self, args: list[str]) -> CommandResult: if len(args) != 2: raise CommandError("layer needs a background (0-3) and a file") bg = parse_number(args[0], "background") if bg > 3: raise CommandError("the backgrounds are 0-3") width, height, rgb, kind = layer_rgb(self.gba, bg) Path(args[1]).write_bytes(rgb_png(width, height, rgb)) return CommandResult((f"wrote BG{bg} ({kind}, {width}x{height}) to {args[1]}",)) def _state(self, args: list[str]) -> CommandResult: if len(args) != 2 or args[0] not in ("save", "load"): raise CommandError("state needs save or load and a file") path = Path(args[1]) if args[0] == "save": self.session.close() # the tracking wrappers are not part of the console try: path.write_bytes(state.save(self.gba)) finally: self.session._wrap_bus() return CommandResult((f"saved the console to {path}",)) gba = state.load(path.read_bytes()) old = self.session old.close() self.gba = gba self.session = self._session(gba) self.session.breakpoints = old.breakpoints self.session.watchpoints = old.watchpoints self.debugger.session = self.session self._arm() lines = (f"loaded {path}: frame {gba.ppu.frame}, VCOUNT {gba.ppu.vcount}",) return CommandResult(lines + self.debugger.execute("registers").lines) def layer_rgb(gba: GBA, bg: int) -> tuple[int, int, bytes, str]: """A background's whole plane (its map, or its bitmap page) as RGB bytes, as the current DISPCNT and BGxCNT describe it, with the backdrop where it is transparent.""" ppu = gba.ppu vram, palette = ppu.vram, ppu.palette dispcnt = ppu.registers[0] mode = dispcnt & 7 bgcnt = ppu.registers[4 + bg] rows: list[list[int]] = [] if mode >= 3: if bg != 2: raise CommandError(f"mode {mode} has only BG2") width, height = (160, 128) if mode == 5 else (240, 160) page = bool(dispcnt & 0x10) rows = [bitmap_line(vram, mode, page, 0, y << 8, 256, 0)[:width] for y in range(height)] kind = f"mode {mode} bitmap" elif mode == 0 or (mode == 1 and bg < 2): wide, tall = TEXT_BLOCKS[bgcnt >> 14] width, height = 512 if wide else 256, 512 if tall else 256 for y in range(height): row: list[int] = [] for x in range(0, width, 240): row += text_line(vram, bgcnt, x, y, 0x10000, Latch())[: width - x] rows.append(row) kind = "text" elif (mode == 1 and bg == 2) or (mode == 2 and bg >= 2): width = height = 128 << (bgcnt >> 14) for y in range(height): row = [] for x in range(0, width, 240): row += affine_line(vram, bgcnt, x << 8, y << 8, 256, 0, Latch())[: width - x] rows.append(row) kind = "affine" else: raise CommandError(f"mode {mode} has no BG{bg}") widen = [c << 3 | c >> 2 for c in range(32)] out = bytearray() for row in rows: for pixel in row: if pixel & DIRECT: color = pixel & 0x7FFF else: index = pixel & 0xFF color = palette[2 * index] | palette[2 * index + 1] << 8 out += bytes((widen[color & 31], widen[color >> 5 & 31], widen[color >> 10 & 31])) return width, height, bytes(out), kind def run(gba: GBA, commands: list[str], batch: bool) -> int: """The command line's ``--debug``: run ``commands``, then read stdin unless ``batch``.""" debugger = BoardDebugger(gba) for command in ["registers", "video", *commands]: print(f"gba> {command}") try: result = debugger.execute(command) except CommandError as exc: print(f"error: {exc}") continue for line in result.lines: print(line) if result.quit: return 0 if not batch: debugger.interact(sys.stdin, sys.stdout) return 0