# SPDX-License-Identifier: MIT """DebugSession and the command debugger on small programs in the minimal harness. The programs are hand-encoded; each test first checks the disassembly of what it runs, so an encoding mistake shows up as text rather than as a puzzling run. """ from __future__ import annotations import io import struct from pathlib import Path import pytest from arm7tdmi_python.__main__ import main from arm7tdmi_python.console import ( CommandDebugger, CommandError, CommandResult, format_psr, parse_number, ) from arm7tdmi_python.debug import ( BoundaryKind, BusCycle, DebugSession, StepRecord, StopReason, instruction_address, ) from arm7tdmi_python.harness import Harness, elf_image ROM = 0x08000000 # ARM: MOV R0, #5; BL sub; MUL R1, R1, R0; B .; (pad); sub: ADD R0, R0, #1; BX LR ARM_PROGRAM = [0xE3A00005, 0xEB000002, 0xE0010091, 0xEAFFFFFE, 0, 0xE2800001, 0xE12FFF1E] ARM_TEXT = ["MOV R0, #0x5", "BL 0x08000014", "MUL R1, R1, R0", "B 0x0800000C", "ANDEQ R0, R0, R0"] ARM_TEXT += ["ADD R0, R0, #0x1", "BX LR"] # Thumb at 0x100: BL 0x108 (pair); MOV R0, #1; B .; sub: ADD R0, #1; BX LR THUMB_PROGRAM = [0xF000, 0xF802, 0x2001, 0xE7FE, 0x3001, 0x4770] def arm_harness() -> Harness: return Harness(b"".join(struct.pack(" Harness: harness = Harness(b"") harness.load(ROM + 0x100, b"".join(struct.pack(" DebugSession: return DebugSession(harness.cpu, peek_byte=harness.peek, track_accesses=True, **options) def test_the_programs_are_what_the_tests_say(): session = session_for(arm_harness()) from arm7tdmi_python.disasm import disassemble texts = [disassemble(session.peek_byte, ROM + 4 * i, False).text for i in range(7)] assert texts == ARM_TEXT thumb = session_for(thumb_harness()) texts = [disassemble(thumb.peek_byte, ROM + 0x100 + a, True).text for a in (0, 4, 6, 8, 10)] assert texts == ["BL 0x08000108", "MOV R0, #0x1", "B 0x08000106", "ADD R0, #0x1", "BX LR"] def test_step_records_carry_the_pipeline_instruction_and_typed_bus_cycles(): session = session_for(arm_harness()) record = session.step() assert record.kind is BoundaryKind.INSTRUCTION and record.address == ROM assert record.instruction.text == "MOV R0, #0x5" assert record.cycles == len(record.accesses) == 1 assert record.accesses[0] == BusCycle("read", ROM + 8, 32, 3, 0xE0010091) assert record.accesses[0].type == "S" call = session.step() # BL: one prefetch then the refill, N then S assert [c.type for c in call.accesses] == ["S", "N", "S"] assert call.after.registers[14] == ROM + 8 session.step() # ADD session.step() # BX LR multiply = session.step() # MUL R1, R1, R0 with R0 = 6: one I cycle (m = 1) assert multiply.instruction.text == "MUL R1, R1, R0" assert [c.type for c in multiply.accesses] == ["S", "I"] assert multiply.accesses[1].kind == "internal" and multiply.accesses[1].value is None assert session.total_steps == 5 and session.total_cycles == sum( r.cycles for r in session.history ) def test_coprocessor_cycles_are_reported_as_c(): harness = Harness(struct.pack(" None: self.memory = bytearray(0x10000) for address, word in words.items(): self.memory[address : address + 4] = word.to_bytes(4, "little") def read(self, address: int, width: int, access: int) -> int: address &= 0xFFFF & ~(width // 8 - 1) return int.from_bytes(self.memory[address : address + width // 8], "little") def write(self, address: int, width: int, value: int, access: int) -> None: address &= 0xFFFF & ~(width // 8 - 1) self.memory[address : address + width // 8] = value.to_bytes(width // 8, "little") def test_interrupt_entry_is_its_own_boundary(): from arm7tdmi_python import ARM7TDMI bus = FlatBus({0x18: 0xEAFFFFFE, 0x100: 0xE3A00001}) # IRQ vector: B .; MOV R0, #1 cpu = ARM7TDMI(bus.read, bus.write) state = cpu.capture_state() state.cpsr = 0x1F # System, I clear cpu.restore_state(state) cpu.start_at(0x100) cpu.irq = True session = DebugSession(cpu, track_accesses=True) session.add_breakpoint(0x100) # an entry is not an instruction: no stop before it record = session.step() assert record.kind is BoundaryKind.IRQ and record.instruction is None assert record.address == 0x100 and record.after.cpsr & 0x1F == 0x12 assert instruction_address(record.after) == 0x18 assert record.after.registers[14] == 0x104 # the instruction not run, + 4 def test_close_restores_the_hosts_callbacks(): harness = arm_harness() original = harness.cpu._bus_read session = session_for(harness) assert harness.cpu._bus_read is not original session.close() assert harness.cpu._bus_read is original and not session.tracking def test_a_board_shaped_target_is_driven_through_its_own_step(): """A board (gba-python) passes itself: ``cpu`` is the processor, ``step()`` is the board's, which may do more than run the CPU (a HALT, a DMA).""" class Board: def __init__(self) -> None: self.harness = arm_harness() self.cpu = self.harness.cpu self.ticks = 0 def step(self) -> int: self.ticks += 1 return self.cpu.step() def capture_state(self): return self.cpu.capture_state() board = Board() session = DebugSession(board, track_accesses=True) assert session.cpu is board.cpu record = session.step() assert board.ticks == 1 and len(record.accesses) == 1 def test_validation(): with pytest.raises(TypeError): DebugSession(object()) session = session_for(arm_harness()) with pytest.raises(ValueError): session.run(max_steps=0) with pytest.raises(ValueError): session.add_breakpoint(-1) with pytest.raises(ValueError): BusCycle("fetch", 0) with pytest.raises(ValueError): StepRecord(0, BoundaryKind.IRQ, 0, None, None, 1, ARM_TEXT) # type: ignore[arg-type] # ---------------------------------------------------------------------- the console def debugger_for(harness: Harness) -> CommandDebugger: return CommandDebugger( session_for(harness), stop_when=harness.at_branch_to_self, loader=harness.load ) def run(debugger: CommandDebugger, line: str) -> list[str]: return list(debugger.execute(line).lines) def test_console_registers_banks_and_psr(): debugger = debugger_for(arm_harness()) lines = run(debugger, "r") assert lines[3].startswith("R12=00000000") and "SP=03007F00" in lines[3] assert lines[4].startswith("CPSR=0000001F nzcv ift SYS") assert lines[5] == "next 08000000 E3A00005 MOV R0, #0x5" banks = run(debugger, "banks") assert banks[2].startswith("SVC SP=03007FE0") and banks[4].startswith("IRQ SP=03007FA0") assert format_psr(0xF00000D3) == "F00000D3 NZCV IFt SVC" def test_console_step_over_until_break_continue(): debugger = debugger_for(arm_harness()) assert run(debugger, "s")[0].startswith("#0 08000000 MOV R0, #0x5") assert run(debugger, "o")[0].startswith("returned: 3 steps") assert run(debugger, "break 0x0800000C") == ["breakpoint at 0800000C"] assert run(debugger, "c")[0].startswith("breakpoint:") assert run(debugger, "breakpoints") == ["break 0800000C"] lines = run(debugger, "c") # steps off the breakpoint: B . comes straight back to it assert lines[0].startswith("#5 0800000C B 0x0800000C") assert lines[1].startswith("breakpoint: 0 steps") assert run(debugger, "delete 0x0800000C") == [] assert run(debugger, "c")[0].startswith("stopped: the host's stop condition") debugger = debugger_for(arm_harness()) assert run(debugger, "u 0x08000014")[0].startswith("until: 2 steps") assert run(debugger, "run 1")[0].startswith("step_limit: 1 steps") def test_console_cycles_watch_memory_disassemble(): debugger = debugger_for(arm_harness()) run(debugger, "s 2") cycles = run(debugger, "cycles 1") assert cycles[1:] == [ " S read 0800000C 32-bit EAFFFFFE code", " N read 08000014 32-bit E2800001 code", " S read 08000018 32-bit E12FFF1E code", ] assert run(debugger, "watch 0x08000010 i") == ["watchpoint at 08000010 (i, 1 bytes)"] run(debugger, "unwatch 0x08000010") run(debugger, "watch 0x08000014 i") assert "I internal 08000014" in run(debugger, "c")[0] assert run(debugger, "m 0x08000000 8 w") == ["08000000 E3A00005 EB000002"] assert run(debugger, "m 0x08000000 4") == ["08000000 05 00 A0 E3"] listing = run(debugger, "d 0x08000000 2") assert listing == ["08000000 E3A00005 MOV R0, #0x5", "08000004 EB000002 BL 0x08000014"] thumb = debugger_for(thumb_harness()) assert run(thumb, "d")[0] == "08000100 F000 F802 BL 0x08000108" assert run(thumb, "d 0x08000100 1 arm")[0].startswith("08000100 F802F000") def test_console_set_irq_load_history_and_errors(tmp_path): harness = arm_harness() debugger = debugger_for(harness) run(debugger, "set R3 0x1234") assert harness.cpu.r[3] == 0x1234 run(debugger, "set PC 0x08000014") assert run(debugger, "r")[5].startswith("next 08000014") run(debugger, "set CPSR 0xD3") assert harness.cpu.r[13] == 0x03007FE0 # the Supervisor bank run(debugger, "set SPSR 0x1F") assert harness.cpu.capture_state().spsr[2] == 0x1F run(debugger, "set CPSR 0x1F") with pytest.raises(CommandError): run(debugger, "set SPSR 0") # System mode has none assert run(debugger, "irq on") == ["irq line on; the next step takes IRQ"] # I is clear assert run(debugger, "irq off") == ["irq line off; the next step takes nothing"] binary = tmp_path / "code.bin" binary.write_bytes(struct.pack(" bytes: header_size, entry_size = 52, 32 offset = header_size + entry_size * len(segments) header = b"\x7fELF" + bytes([1, 1, 1]) + bytes(9) header += struct.pack("