# SPDX-License-Identifier: MIT """Side-effect-free ARM and Thumb disassembly, driven by the core's own decode tables. Every opcode is classified by the handler ``ARM_HANDLERS`` / ``THUMB_HANDLERS`` names for it, the same lookup :meth:`ARM7TDMI.step` makes, so the text always describes what the core executes. Encodings ARMv4T leaves undefined or reserved print as what the ARM7TDMI does with them, with a comment naming the docs item. The syntax is ARM's own, pre-UAL, as in the data sheet (ARM DDI 0029E chapters 4 and 5) and the ARMv4T Architecture Reference Manual: upper case, the condition before ``S`` (``ADDEQS``) and before the size (``LDREQB``, ``LDRSH``), ``LDMIA``/``STMDB`` addressing modes, MSR field masks (``CPSR_fc``), ``R13``-``R15`` written ``SP``, ``LR``, ``PC``. Thumb uses the same names; a data-processing Thumb instruction sets the flags without an ``S``, as in DS chapter 5. Immediates are hexadecimal (``#0x1F``) except shift amounts; branch targets are absolute; a PC-relative load or ``ADD Rd, PC, #n`` gets the address it uses as a comment. >>> disassemble_arm(0xE0912003, 0x08000000).text 'ADDS R2, R1, R3' >>> disassemble_thumb(0xF000, 0x08000000, 0xF810).text 'BL 0x08000024' """ from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from arm7tdmi_python._tables import ARM_HANDLERS, THUMB_HANDLERS ByteReader = Callable[[int], int] MASK32 = 0xFFFFFFFF CONDITIONS = ("EQ", "NE", "CS", "CC", "MI", "PL", "VS", "VC") CONDITIONS += ("HI", "LS", "GE", "LT", "GT", "LE", "", "NV") REGISTERS = (*tuple(f"R{n}" for n in range(13)), "SP", "LR", "PC") SHIFTS = ("LSL", "LSR", "ASR", "ROR") DATA_OPS = ("AND", "EOR", "SUB", "RSB", "ADD", "ADC", "SBC", "RSC") DATA_OPS += ("TST", "TEQ", "CMP", "CMN", "ORR", "MOV", "BIC", "MVN") COMPARES = frozenset(("TST", "TEQ", "CMP", "CMN")) NONSTANDARD = "nonstandard encoding: should-be-zero/one bits differ" NO_COPROCESSOR = "no coprocessor answers on the GBA: undefined trap (TRM 4.6)" @dataclass(frozen=True, slots=True) class Instruction: """One decoded instruction: where it is, its bytes, its text and what it refers to.""" address: int data: bytes mnemonic: str operands: tuple[str, ...] = () #: A note for the reader: the address a PC-relative operand means, or the docs item #: behind an undefined or reserved encoding. Empty when there is nothing to add. comment: str = "" thumb: bool = False #: The branch target, for B, BL and Bcc (absolute); ``None`` otherwise. target: int | None = None def __post_init__(self) -> None: if type(self.address) is not int or not 0 <= self.address <= MASK32: raise ValueError("address must be a 32-bit unsigned integer") if type(self.data) is not bytes or len(self.data) not in (2, 4): raise ValueError("data must be 2 or 4 bytes") if type(self.mnemonic) is not str or not self.mnemonic: raise ValueError("mnemonic must not be empty") if type(self.operands) is not tuple or not all(type(o) is str for o in self.operands): raise ValueError("operands must be a tuple of strings") @property def size(self) -> int: """Bytes consumed: 4 in ARM state and for a combined Thumb BL pair, otherwise 2.""" return len(self.data) @property def next_address(self) -> int: return (self.address + self.size) & MASK32 @property def text(self) -> str: """Assembly text without the comment.""" return self.mnemonic if not self.operands else f"{self.mnemonic} {', '.join(self.operands)}" @property def listing(self) -> str: """Assembly text with the comment, if any, after ``;``.""" return f"{self.text:<32} ; {self.comment}" if self.comment else self.text # ---------------------------------------------------------------------- helpers def _hex(value: int) -> str: return f"0x{value:X}" def _imm(value: int) -> str: return f"#0x{value:X}" def _signed_imm(value: int, up: bool) -> str: return f"#0x{value:X}" if up else f"#-0x{value:X}" def _address(value: int) -> str: return f"0x{value & MASK32:08X}" def _sign_extend(value: int, bits: int) -> int: return value - (1 << bits) if value & (1 << (bits - 1)) else value def _ror(value: int, amount: int) -> int: amount &= 31 return ((value >> amount) | (value << (32 - amount))) & MASK32 if amount else value def _register_list(mask: int) -> str: """``{R0-R3, R5, LR}``: runs of three or more low registers as ranges.""" parts: list[str] = [] n = 0 while n < 16: if not mask & (1 << n): n += 1 continue end = n while end + 1 < 13 and mask & (1 << (end + 1)): end += 1 if n < 13 and end - n >= 2: parts.append(f"{REGISTERS[n]}-{REGISTERS[end]}") else: parts.extend(REGISTERS[k] for k in range(n, end + 1)) n = end + 1 return "{" + ", ".join(parts) + "}" def _join(*comments: str) -> str: return "; ".join(c for c in comments if c) # ---------------------------------------------------------------------- ARM def _arm_shift(op: int) -> str: """The shifted-register form of an operand: ``Rm``, ``Rm, LSL #3``, ``Rm, ROR Rs``, ``Rm, RRX``. Immediate ``LSR #0`` and ``ASR #0`` mean 32 (DS 4.5.2, U10).""" rm = REGISTERS[op & 0xF] kind = (op >> 5) & 3 if op & 0x10: return f"{rm}, {SHIFTS[kind]} {REGISTERS[(op >> 8) & 0xF]}" amount = (op >> 7) & 31 if amount == 0: if kind == 0: return rm if kind == 3: return f"{rm}, RRX" amount = 32 return f"{rm}, {SHIFTS[kind]} #{amount}" def _arm_rotated_immediate(op: int) -> tuple[str, int]: """``#value``; or ``#imm8, rot`` when the encoding is not the one with the smallest rotation, since the rotation decides the shifter's carry (DS 4.5.3).""" imm8, rotate = op & 0xFF, (op >> 8) & 0xF value = _ror(imm8, 2 * rotate) canonical = next(r for r in range(16) if _ror(value, 32 - 2 * r) < 0x100) if rotate != canonical: return f"#0x{imm8:X}, {2 * rotate}", value return _imm(value), value def _arm_data(op: int, name: str, address: int) -> tuple[str, tuple[str, ...], str]: cond = CONDITIONS[op >> 28] opcode = DATA_OPS.index(name) s = bool(op & (1 << 20)) rn, rd = (op >> 16) & 0xF, (op >> 12) & 0xF comment = "" if op & (1 << 25): operand2, value = _arm_rotated_immediate(op) if rn == 15 and name in ("ADD", "SUB"): base = address + 8 comment = f"={_address(base + value if name == 'ADD' else base - value)}" else: operand2 = _arm_shift(op) if name in COMPARES: mnemonic = f"{name}{cond}" if rd == 15: mnemonic += "P" comment = "Rd = R15: also CPSR <- SPSR (U13)" elif rd: comment = NONSTANDARD return mnemonic, (REGISTERS[rn], operand2), comment mnemonic = f"{name}{cond}{'S' if s else ''}" if s and rd == 15: comment = _join(comment, "S with Rd = PC: also CPSR <- SPSR (U13)") if opcode in (13, 15): # MOV, MVN: no first operand if rn: comment = _join(comment, NONSTANDARD) return mnemonic, (REGISTERS[rd], operand2), comment return mnemonic, (REGISTERS[rd], REGISTERS[rn], operand2), comment def _psr_fields(mask: int) -> str: return "".join(letter for bit, letter in ((8, "f"), (4, "s"), (2, "x"), (1, "c")) if mask & bit) def _arm_mrs(op: int) -> tuple[str, tuple[str, ...], str]: psr = "SPSR" if op & (1 << 22) else "CPSR" standard = (op >> 16) & 0xF == 0xF and op & 0xFFF == 0 and not op & (1 << 25) comment = "" if standard else NONSTANDARD return f"MRS{CONDITIONS[op >> 28]}", (REGISTERS[(op >> 12) & 0xF], psr), comment def _arm_msr(op: int) -> tuple[str, tuple[str, ...], str]: psr = "SPSR" if op & (1 << 22) else "CPSR" fields = _psr_fields((op >> 16) & 0xF) target = f"{psr}_{fields}" if fields else psr comment = "" if fields else "no fields: writes nothing" if op & (1 << 25): source, _ = _arm_rotated_immediate(op) standard = (op >> 12) & 0xF == 0xF else: source = REGISTERS[op & 0xF] standard = (op >> 12) & 0xF == 0xF and (op >> 4) & 0xFF == 0 if not standard: comment = _join(comment, NONSTANDARD) return f"MSR{CONDITIONS[op >> 28]}", (target, source), comment def _arm_bx(op: int) -> tuple[str, tuple[str, ...], str]: comment = "" if (op >> 8) & 0xFFF == 0xFFF else NONSTANDARD return f"BX{CONDITIONS[op >> 28]}", (REGISTERS[op & 0xF],), comment def _arm_multiply(op: int, name: str) -> tuple[str, tuple[str, ...], str]: """MUL Rd, Rm, Rs / MLA Rd, Rm, Rs, Rn / xMULL and xMLAL RdLo, RdHi, Rm, Rs (DS 4.7, 4.8). Bit 22 of a short multiply and Rn of MUL should be zero.""" cond = CONDITIONS[op >> 28] s = "S" if op & (1 << 20) else "" rd, rn = (op >> 16) & 0xF, (op >> 12) & 0xF rs, rm = (op >> 8) & 0xF, op & 0xF mnemonic = f"{name}{cond}{s}" if name in ("MUL", "MLA"): standard = not op & (1 << 22) and (name == "MLA" or rn == 0) operands = (REGISTERS[rd], REGISTERS[rm], REGISTERS[rs]) if name == "MLA": operands += (REGISTERS[rn],) return mnemonic, operands, "" if standard else NONSTANDARD return mnemonic, (REGISTERS[rn], REGISTERS[rd], REGISTERS[rm], REGISTERS[rs]), "" def _arm_swp(op: int) -> tuple[str, tuple[str, ...], str]: """SWP{B} Rd, Rm, [Rn] (DS 4.12); bits 23, 21:20 and 11:8 should be zero.""" byte = "B" if op & (1 << 22) else "" standard = not op & 0x00B00F00 rd, rm, rn = (op >> 12) & 0xF, op & 0xF, (op >> 16) & 0xF operands = (REGISTERS[rd], REGISTERS[rm], f"[{REGISTERS[rn]}]") return f"SWP{CONDITIONS[op >> 28]}{byte}", operands, "" if standard else NONSTANDARD def _indexed(rn: int, offset: str | None, pre: bool, write_back: bool) -> str: """``[Rn, off]{!}`` (pre-indexed) or ``[Rn], off`` (post-indexed).""" base = REGISTERS[rn] if pre: inner = f"[{base}, {offset}]" if offset else f"[{base}]" return inner + ("!" if write_back else "") # A post-indexed zero offset stays visible: ``[Rn]`` alone is the pre-indexed encoding. return f"[{base}], {offset or '#0x0'}" def _arm_single(op: int, name: str, address: int) -> tuple[str, tuple[str, ...], str]: """LDR/STR/LDRB/STRB, including the T forms (DS 4.9).""" pre, up, write_back = bool(op & (1 << 24)), bool(op & (1 << 23)), bool(op & (1 << 21)) rn, rd = (op >> 16) & 0xF, (op >> 12) & 0xF comment = "" if op & (1 << 25): offset: str | None = ("" if up else "-") + _arm_shift(op) else: imm = op & 0xFFF offset = None if imm == 0 and up else _signed_imm(imm, up) if rn == 15 and pre: comment = f"=[{_address(address + 8 + (imm if up else -imm))}]" t = "T" if not pre and write_back else "" mnemonic = f"{name[:3]}{CONDITIONS[op >> 28]}{name[3:]}{t}" return mnemonic, (REGISTERS[rd], _indexed(rn, offset, pre, write_back and pre)), comment _HALFWORD_SUFFIX = {"LDRH": "H", "STRH": "H", "LDRSB": "SB", "LDRSH": "SH", "LDRD": "D"} _HALFWORD_SUFFIX["STRD"] = "D" def _arm_halfword(op: int, name: str, address: int) -> tuple[str, tuple[str, ...], str]: """LDRH/STRH/LDRSB/LDRSH, and the ARMv5 LDRD/STRD encodings (DS 4.10, U21).""" pre, up, write_back = bool(op & (1 << 24)), bool(op & (1 << 23)), bool(op & (1 << 21)) rn, rd = (op >> 16) & 0xF, (op >> 12) & 0xF comment = "" if op & (1 << 22): imm = (op & 0xF) | ((op >> 4) & 0xF0) offset = None if imm == 0 and up else _signed_imm(imm, up) if rn == 15 and pre: comment = f"=[{_address(address + 8 + (imm if up else -imm))}]" else: offset = ("" if up else "-") + REGISTERS[op & 0xF] if (op >> 8) & 0xF: comment = NONSTANDARD if write_back and not pre: comment = _join(comment, NONSTANDARD) # W must be 0 when post-indexed (DS 4.10) if name in ("LDRD", "STRD"): comment = _join(comment, "ARMv5 only: no transfer on the ARM7TDMI, base write-back (U21)") mnemonic = f"{name[:3]}{CONDITIONS[op >> 28]}{_HALFWORD_SUFFIX[name]}" return mnemonic, (REGISTERS[rd], _indexed(rn, offset, pre, write_back and pre)), comment def _arm_block(op: int, name: str) -> tuple[str, tuple[str, ...], str]: pre, up = bool(op & (1 << 24)), bool(op & (1 << 23)) mode = ("DA", "IA", "DB", "IB")[pre << 1 | up] rn = (op >> 16) & 0xF base = REGISTERS[rn] + ("!" if op & (1 << 21) else "") registers = _register_list(op & 0xFFFF) + ("^" if op & (1 << 22) else "") comment = "empty list: transfers R15, base moves by 0x40 (U4)" if op & 0xFFFF == 0 else "" return f"{name}{CONDITIONS[op >> 28]}{mode}", (base, registers), comment def _arm_coprocessor(op: int, name: str) -> tuple[str, tuple[str, ...], str]: cond = CONDITIONS[op >> 28] cp = (op >> 8) & 0xF crn, crd, crm = (op >> 16) & 0xF, (op >> 12) & 0xF, op & 0xF if name in ("MRC", "MCR"): operands = (f"p{cp}", str((op >> 21) & 7), REGISTERS[crd], f"c{crn}", f"c{crm}") if (op >> 5) & 7: operands += (str((op >> 5) & 7),) if cp == 14: effect = "Rd = the opcode at +8" if name == "MRC" else "no visible effect" return f"{name}{cond}", operands, f"CP14 (U17): {effect}" return f"{name}{cond}", operands, NO_COPROCESSOR if name == "CDP": operands = (f"p{cp}", str((op >> 20) & 0xF), f"c{crd}", f"c{crn}", f"c{crm}") return f"CDP{cond}", (*operands, str((op >> 5) & 7)), NO_COPROCESSOR # LDC / STC pre, up, write_back = bool(op & (1 << 24)), bool(op & (1 << 23)), bool(op & (1 << 21)) imm = (op & 0xFF) << 2 # P = 0 is post-indexed, as DS 4.15 defines it for ARMv4T if pre: where = _indexed(crn, None if imm == 0 and up else _signed_imm(imm, up), pre, write_back) else: # Unlike LDR/STR, a post-indexed LDC/STC writes back only with W = 1, which DS 4.15 # writes as a trailing ``!``: ``[Rn], #off{!}``. where = f"[{REGISTERS[crn]}], {_signed_imm(imm, up)}" + ("!" if write_back else "") long = "L" if op & (1 << 22) else "" return f"{name}{cond}{long}", (f"p{cp}", f"c{crd}", where), NO_COPROCESSOR _DATA_HANDLERS = {f"_arm_{name.lower()}": name for name in DATA_OPS} _MULTIPLY = {"_arm_mul": "MUL", "_arm_mla": "MLA", "_arm_umull": "UMULL"} _MULTIPLY |= {"_arm_umlal": "UMLAL", "_arm_smull": "SMULL", "_arm_smlal": "SMLAL"} _SINGLE = {"_arm_ldr": "LDR", "_arm_ldrb": "LDRB", "_arm_str": "STR", "_arm_strb": "STRB"} _HALFWORD = {f"_arm_{name.lower()}": name for name in _HALFWORD_SUFFIX} _COPROCESSOR = {"_arm_mrc": "MRC", "_arm_mcr": "MCR", "_arm_cdp": "CDP"} _COPROCESSOR |= {"_arm_ldc": "LDC", "_arm_stc": "STC"} def disassemble_arm(word: int, address: int) -> Instruction: """The ARM instruction ``word`` at ``address``, classified by the core's decode table.""" op = word & MASK32 address &= MASK32 handler = ARM_HANDLERS[(op >> 16) & 0xFF0 | (op >> 4) & 0xF] cond = CONDITIONS[op >> 28] comment = "" target = None operands: tuple[str, ...] = () if handler in _DATA_HANDLERS: mnemonic, operands, comment = _arm_data(op, _DATA_HANDLERS[handler], address) elif handler == "_arm_mrs": mnemonic, operands, comment = _arm_mrs(op) elif handler == "_arm_msr": mnemonic, operands, comment = _arm_msr(op) elif handler == "_arm_bx": mnemonic, operands, comment = _arm_bx(op) elif handler in _MULTIPLY: mnemonic, operands, comment = _arm_multiply(op, _MULTIPLY[handler]) elif handler == "_arm_swp": mnemonic, operands, comment = _arm_swp(op) elif handler in _SINGLE: mnemonic, operands, comment = _arm_single(op, _SINGLE[handler], address) elif handler in _HALFWORD: mnemonic, operands, comment = _arm_halfword(op, _HALFWORD[handler], address) elif handler in ("_arm_ldm", "_arm_stm"): mnemonic, operands, comment = _arm_block(op, handler[5:].upper()) elif handler in ("_arm_b", "_arm_bl"): target = (address + 8 + (_sign_extend(op & 0xFFFFFF, 24) << 2)) & MASK32 mnemonic, operands = f"{handler[5:].upper()}{cond}", (_address(target),) elif handler == "_arm_swi": mnemonic, operands = f"SWI{cond}", (_hex(op & 0xFFFFFF),) elif handler == "_arm_undefined": mnemonic, comment = f"UND{cond}", "undefined instruction: the undefined trap (C5)" elif handler in _COPROCESSOR: mnemonic, operands, comment = _arm_coprocessor(op, _COPROCESSOR[handler]) else: # pragma: no cover - the tables name no other handler raise AssertionError(f"no disassembly for {handler}") if op >> 28 == 0xF: comment = _join(comment, "condition NV: never executes (U19)") data = op.to_bytes(4, "little") return Instruction(address, data, mnemonic, operands, comment, False, target) # ---------------------------------------------------------------------- Thumb _LOW = REGISTERS[:8] _THUMB_ALU_NAMES = ("and", "eor", "lsl", "lsr", "asr", "adc", "sbc", "ror") _THUMB_ALU_NAMES += ("tst", "neg", "cmp", "cmn", "orr", "mul", "bic", "mvn") _THUMB_ALU = {name: name.upper() for name in _THUMB_ALU_NAMES} _THUMB_REG = {"str_reg": "STR", "strb_reg": "STRB", "ldr_reg": "LDR", "ldrb_reg": "LDRB"} _THUMB_REG |= {"strh_reg": "STRH", "ldsb_reg": "LDRSB", "ldrh_reg": "LDRH", "ldsh_reg": "LDRSH"} _THUMB_IMM = {"str_imm": ("STR", 2), "ldr_imm": ("LDR", 2), "strb_imm": ("STRB", 0)} _THUMB_IMM |= {"ldrb_imm": ("LDRB", 0), "strh_imm": ("STRH", 1), "ldrh_imm": ("LDRH", 1)} def _thumb_hi(op: int, name: str) -> tuple[str, tuple[str, ...], str]: """Format 5: ADD/CMP/MOV with a high register, and BX (DS 5.5). H1 = H2 = 0 (ADD, CMP, MOV) and BX with H1 set are reserved but execute (U19).""" h1, h2 = op & 0x80, op & 0x40 rd = REGISTERS[(op & 7) | (8 if h1 else 0)] rs = REGISTERS[(op >> 3) & 0xF] if name == "bx": comment = "H1 set: still BX, no link (U19)" if h1 else "" if op & 7: comment = _join(comment, NONSTANDARD) return "BX", (rs,), comment comment = "" if h1 or h2 else "both registers low: reserved, executes (U19)" return name.upper(), (rd, rs), comment def disassemble_thumb(halfword: int, address: int, next_halfword: int | None = None) -> Instruction: """The Thumb instruction ``halfword`` at ``address``. A BL first half followed by a second half (``next_halfword``) disassembles as one 4-byte ``BL target``, as assemblers write it. Either half alone prints as ``BL.HI`` / ``BL.LO`` with its offset: the core runs them as two instructions (U18). """ op = halfword & 0xFFFF address &= MASK32 handler = THUMB_HANDLERS[op >> 6][len("_thumb_") :] data = op.to_bytes(2, "little") rd, rs = _LOW[op & 7], _LOW[(op >> 3) & 7] comment = "" target = None operands: tuple[str, ...] if handler in ("lsl_imm", "lsr_imm", "asr_imm"): amount = (op >> 6) & 31 if amount == 0 and handler != "lsl_imm": amount = 32 mnemonic, operands = handler[:3].upper(), (rd, rs, f"#{amount}") elif handler in ("add3", "sub3"): operand = f"#{(op >> 6) & 7}" if op & 0x400 else _LOW[(op >> 6) & 7] mnemonic, operands = handler[:3].upper(), (rd, rs, operand) elif handler in ("mov_imm", "cmp_imm", "add_imm", "sub_imm"): mnemonic, operands = handler[:3].upper(), (_LOW[(op >> 8) & 7], _imm(op & 0xFF)) elif handler in _THUMB_ALU: mnemonic, operands = _THUMB_ALU[handler], (rd, rs) elif handler in ("add_hi", "cmp_hi", "mov_hi", "bx"): mnemonic, operands, comment = _thumb_hi(op, handler[:3] if handler != "bx" else "bx") elif handler == "ldr_pc": offset = (op & 0xFF) << 2 mnemonic = "LDR" operands = (_LOW[(op >> 8) & 7], f"[PC, {_imm(offset)}]" if offset else "[PC]") comment = f"=[{_address(((address + 4) & ~3) + offset)}]" elif handler in _THUMB_REG: mnemonic = _THUMB_REG[handler] operands = (rd, f"[{rs}, {_LOW[(op >> 6) & 7]}]") elif handler in _THUMB_IMM: mnemonic, scale = _THUMB_IMM[handler] offset = ((op >> 6) & 31) << scale operands = (rd, f"[{rs}, {_imm(offset)}]" if offset else f"[{rs}]") elif handler in ("str_sp", "ldr_sp"): offset = (op & 0xFF) << 2 mnemonic = handler[:3].upper() operands = (_LOW[(op >> 8) & 7], f"[SP, {_imm(offset)}]" if offset else "[SP]") elif handler in ("add_pc_rel", "add_sp_rel"): offset = (op & 0xFF) << 2 base = "PC" if handler == "add_pc_rel" else "SP" mnemonic, operands = "ADD", (_LOW[(op >> 8) & 7], base, _imm(offset)) if base == "PC": comment = f"={_address(((address + 4) & ~3) + offset)}" elif handler == "add_sp": mnemonic, operands = "ADD", ("SP", _signed_imm((op & 0x7F) << 2, not op & 0x80)) elif handler in ("push", "pop"): mask = op & 0xFF if op & 0x100: mask |= 1 << (14 if handler == "push" else 15) mnemonic, operands = handler.upper(), (_register_list(mask),) if mask == 0: comment = "empty list: transfers R15, SP moves by 0x40 (U4)" elif handler in ("stmia", "ldmia"): mnemonic = handler.upper() operands = (f"{_LOW[(op >> 8) & 7]}!", _register_list(op & 0xFF)) if op & 0xFF == 0: comment = "empty list: transfers R15, base moves by 0x40 (U4)" elif handler == "bcc": target = (address + 4 + (_sign_extend(op & 0xFF, 8) << 1)) & MASK32 mnemonic, operands = f"B{CONDITIONS[(op >> 8) & 0xF]}", (_address(target),) elif handler == "swi": mnemonic, operands = "SWI", (_hex(op & 0xFF),) elif handler == "b": target = (address + 4 + (_sign_extend(op & 0x7FF, 11) << 1)) & MASK32 mnemonic, operands = "B", (_address(target),) elif handler == "bl_prefix": high = _sign_extend(op & 0x7FF, 11) << 12 if next_halfword is not None and THUMB_HANDLERS[(next_halfword & 0xFFFF) >> 6] == ( "_thumb_bl_suffix" ): target = (address + 4 + high + ((next_halfword & 0x7FF) << 1)) & MASK32 data += (next_halfword & 0xFFFF).to_bytes(2, "little") mnemonic, operands = "BL", (_address(target),) else: mnemonic, operands = "BL.HI", (_imm(op & 0x7FF),) comment = f"first half: LR = {_address(address + 4 + high)}" elif handler == "bl_suffix": mnemonic, operands = "BL.LO", (_imm(op & 0x7FF),) comment = ( f"second half: PC = LR + {_hex((op & 0x7FF) << 1)}, LR = {_address(address + 2)} | 1" ) elif handler == "undefined": mnemonic, operands, comment = _thumb_undefined(op) else: # pragma: no cover - the tables name no other handler raise AssertionError(f"no disassembly for _thumb_{handler}") return Instruction(address, data, mnemonic, operands, comment, True, target) def _thumb_undefined(op: int) -> tuple[str, tuple[str, ...], str]: """An encoding Thumb leaves undefined: 0xDExx (C7), 0xE8xx (C8) and the unused formats; each takes the undefined trap (DS 5.0, C5).""" if op & 0xFF00 == 0xDE00: return "UND", (_imm(op & 0xFF),), "B with condition 1110: undefined trap (C7)" if op & 0xF800 == 0xE800: return "UND", (_imm(op & 0x7FF),), "BLX suffix (ARMv5): undefined trap (C8)" return "UND", (), "undefined encoding: undefined trap (C5)" # ---------------------------------------------------------------------- from memory def _read(reader: ByteReader, address: int, count: int) -> int: value = 0 for i in range(count): byte = reader((address + i) & MASK32) if type(byte) is not int or not 0 <= byte <= 0xFF: raise ValueError(f"byte reader returned a non-byte value at 0x{address + i:08X}") value |= byte << (8 * i) return value def disassemble(reader: ByteReader, address: int, thumb: bool) -> Instruction: """The instruction at ``address`` read through ``reader`` (a side-effect-free byte peek), in Thumb state if ``thumb``. The address is aligned as the fetch would align it; a Thumb BL first half reads the next halfword to combine the pair.""" if thumb: address &= ~1 & MASK32 first = _read(reader, address, 2) second = None if THUMB_HANDLERS[first >> 6] == "_thumb_bl_prefix": second = _read(reader, address + 2, 2) return disassemble_thumb(first, address, second) address &= ~3 & MASK32 return disassemble_arm(_read(reader, address, 4), address) __all__ = [ "ByteReader", "Instruction", "disassemble", "disassemble_arm", "disassemble_thumb", ]