"""Bus traces as JSON Lines: every access the bus serves, with the clocks it took. One object per access, in order, for the CPU's callbacks and the DMA's own accesses alike:: {"cycle": 1204, "clocks": 3, "kind": "read", "address": 134217736, "width": 32, "access": 3, "value": 3818127360, "dma": false} {"cycle": 1207, "clocks": 1, "kind": "internal", "address": 134217740} ``cycle`` is the system clock when the access starts, ``clocks`` how many it took (wait states, a prefetch hit's single cycle, a DMA run that the CPU waited for, an internal cycle hidden under a DMA: 0). ``access`` is the bit set the bus saw: SEQ=1, CODE=2, the DMA's 4, LOCK=8, after the GBA's merged-IS rule (``arm7tdmi_python.gba_access``). """ from __future__ import annotations import json from typing import TextIO from gba_python.board import GBA from gba_python.dma import DMA_ACCESS def attach(gba: GBA, stream: TextIO) -> None: """Trace every bus access of ``gba`` from now on into ``stream``.""" scheduler = gba.scheduler read, write = gba.bus_read, gba.bus_write idle = gba.cpu._bus_idle def emit(record: dict) -> None: stream.write(json.dumps(record) + "\n") def traced_read(address: int, width: int, access: int) -> int: start = scheduler.now value = read(address, width, access) emit( { "cycle": start, "clocks": scheduler.now - start, "kind": "read", "address": address, "width": width, "access": access, "value": value, "dma": bool(access & DMA_ACCESS), } ) return value def traced_write(address: int, width: int, value: int, access: int) -> None: start = scheduler.now write(address, width, value, access) emit( { "cycle": start, "clocks": scheduler.now - start, "kind": "write", "address": address, "width": width, "access": access, "value": value, "dma": bool(access & DMA_ACCESS), } ) def traced_idle(address: int) -> None: start = scheduler.now idle(address) emit( { "cycle": start, "clocks": scheduler.now - start, "kind": "internal", "address": address, } ) gba.bus_read = traced_read # type: ignore[method-assign] gba.bus_write = traced_write # type: ignore[method-assign] gba.cpu._bus_idle = traced_idle