# SPDX-License-Identifier: MIT """Disassembly in BK2's syntax, with the prefixes folded into the instruction they modify. ``ADC R3``, ``ADD #3``, ``MOVE R4,R5``, ``MOVES R4,R5``, ``LMS R1,(24h)``, ``IWT R15,#A103h``, ``BNE 8A64h`` (the target), ``STW (R3)``, ``LINK #2`` (handoff-brief decision 12). ALT1, ALT2 and ALT3 are folded into the form they select (``3D 50`` is ``ADC R0``); WITH followed by ``1n``/``Bn`` is MOVE/MOVES; the other TO/FROM/WITH prefixes stay in front of the opcode, joined by ``; `` (``WITH R1; ADD R0``). A prefix whose opcode is a branch (it applies to the opcode after the branch: U3) is printed alone, as is a prefix at the end of the input. """ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from gsu_python._decode import BRANCHES, MNEMONICS, decode #: Prefix-chain limit: a run of more prefixes than this is printed one at a time. _MAX_PREFIXES = 8 @dataclass(frozen=True, slots=True) class Instruction: """One decoded instruction: its first byte's address, every byte (prefixes included), the form key of the opcode that executes (``_decode``), and the text.""" address: int raw: bytes key: str text: str @property def length(self) -> int: return len(self.raw) def _operands(key: str, n: int, operands: list[int], address: int, sreg: int, dreg: int) -> str: mnemonic = MNEMONICS[key] if key == "branch": displacement = operands[0] - 0x100 if operands[0] & 0x80 else operands[0] return f"{BRANCHES[n]} {(address + 2 + displacement) & 0xFFFF:04X}h" if key in ("ibt",): return f"IBT R{n},#{operands[0]:02X}h" if key == "iwt": return f"IWT R{n},#{operands[1] << 8 | operands[0]:04X}h" if key == "lm": return f"LM R{n},({operands[1] << 8 | operands[0]:04X}h)" if key == "sm": return f"SM ({operands[1] << 8 | operands[0]:04X}h),R{n}" if key == "lms": return f"LMS R{n},({operands[0] << 1:03X}h)" if key == "sms": return f"SMS ({operands[0] << 1:03X}h),R{n}" if key == "move": return f"MOVE R{n},R{sreg}" if key == "moves": return f"MOVES R{dreg},R{n}" if key in ("stw", "stb", "ldw", "ldb"): return f"{mnemonic} (R{n})" if key in ("to", "from", "with", "jmp", "ljmp", "inc", "dec") or key.endswith("_r"): return f"{mnemonic} R{n}" if key.endswith("_i") or key == "link": return f"{mnemonic} #{n}" return mnemonic def disassemble( read: Callable[[int], int], address: int, *, alt: int = 0, b: bool = False, sreg: int = 0, dreg: int = 0, fold: bool = True, ) -> Instruction: """Decode the instruction at ``address`` (16-bit; ``read`` returns the byte at a 16-bit address in the program bank). ``alt``, ``b``, ``sreg`` and ``dreg`` are the prefix state already in effect (from SFR and the core) when disassembling at a live PC. With ``fold=False`` only the one opcode at ``address`` is decoded (a prefix prints alone): what one ``GSU.step`` executes.""" start = address & 0xFFFF pc = start raw: list[int] = [] text_prefixes: list[str] = [] first_prefix: tuple[int, int, int, bool, int, int] | None = None while True: opcode = read(pc) form = decode(opcode, alt, b) if fold and form.keeps_prefix and form.key != "branch" and len(raw) < _MAX_PREFIXES: if first_prefix is None: first_prefix = (pc, opcode, alt, b, sreg, dreg) raw.append(opcode) pc = (pc + 1) & 0xFFFF key = form.key if key == "alt1": alt, b = alt | 1, False elif key == "alt2": alt, b = alt | 2, False elif key == "alt3": alt, b = 3, False elif key == "to": dreg = form.n text_prefixes.append(f"TO R{dreg}") elif key == "from": sreg = form.n text_prefixes.append(f"FROM R{sreg}") else: # with sreg = dreg = form.n b = True text_prefixes.append(f"WITH R{sreg}") continue if not fold and form.keeps_prefix and form.key != "branch": return Instruction(start, bytes([opcode]), form.key, _operands(form.key, form.n, [], pc, sreg, dreg)) # fmt: skip if form.keeps_prefix and first_prefix is not None: # A prefix before a branch (or too long a chain): print the first prefix alone. prefix_pc, prefix_opcode, alt0, b0, _, _ = first_prefix lone = decode(prefix_opcode, alt0, b0) text = _operands(lone.key, lone.n, [], prefix_pc, sreg, dreg) return Instruction(start, bytes([prefix_opcode]), lone.key, text) operands = [read((pc + 1 + i) & 0xFFFF) for i in range(form.length - 1)] raw.extend([opcode, *operands]) if form.key in ("move", "moves"): text_prefixes = [t for t in text_prefixes if not t.startswith("WITH ")] body = _operands(form.key, form.n, operands, pc, sreg, dreg) text = "; ".join([*text_prefixes, body]) return Instruction(start, bytes(raw), form.key, text) def disassemble_bytes(code: bytes, address: int = 0) -> list[Instruction]: """Disassemble a byte string laid out from ``address``; reads past its end return 0.""" def read(at: int) -> int: offset = (at - address) & 0xFFFF return code[offset] if offset < len(code) else 0 out = [] pc = address end = address + len(code) while pc < end: instruction = disassemble(read, pc) out.append(instruction) pc += instruction.length return out __all__ = ["Instruction", "disassemble", "disassemble_bytes"]