From 7bdf3741c91f76bfff3f3e054a5cf41b7f476d0b Mon Sep 17 00:00:00 2001 From: blasty Date: Sun, 26 Jul 2026 14:51:07 +0200 Subject: arm: switch ARM/Thumb decoding with `t` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `c` could not carve Thumb code. Thumb isn't a property of the bytes — it's a mode the CPU is in — so a raw image gives IDA nothing to detect: at a Thumb entry point it decodes 16-bit instructions as 32-bit ARM and produces confident nonsense. experiments/fibonacci.bin starts with `08 b5` = push {r3,lr}, which IDA reads as SVCLT 0xBF00. `t` on the listing switches the mode at the cursor and disassembles in it: Thumb @ 0x0 (segment set to 32-bit; Thumb needs ARM32) — 10 instructions 0x0 PUSH {R3,LR} 0x2 MOVS R1, #0 0x4 MOV R4, R0 0x6 BL unk_E3C Setting the T segment register is only half of it. Thumb does not exist in AArch64, and a headerless blob loaded with -parm comes up 64-bit, so T alone changes nothing and looks broken — I watched exactly that happen while probing the API. Asking for Thumb IS asking for ARM32, so set_thumb forces the segment to 32-bit and says so rather than doing it silently. It also has to del_items over the range first: the bytes are currently decoded in the old mode, and leaving that item defined pins the wrong instruction length so the new mode has nothing to apply to. Implemented as a `thumb` kind in the existing edit-item flow, so it inherits the shared reload — same cache bump, same ViewAnchor restore, same status flash. It switches AND disassembles, because flipping T and leaving the bytes undefined shows you nothing and reading the code was the point. tests: new tests/test_thumb_ui.py (8) driving the real Thumb binary — `c` alone does NOT produce the prologue, `t` does, the instructions are 16-bit wide (in ARM mode those three rows would be one 4-byte instruction), the run continues, the status explains the 32-bit forcing, and `t` toggles back. Deletes the .i64 first, because T and the segment's addressing mode are saved in it and a stale database would answer the question for us. 209/0 scenarios, 26/0 blob, 8/0 thumb. --- README.md | 4 ++ docs/PROJECTS.md | 20 ++++++++ idatui/app.py | 23 ++++++++- idatui/domain.py | 8 ++++ server/patch_server.py | 57 ++++++++++++++++++++++ tests/test_thumb_ui.py | 126 +++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 237 insertions(+), 1 deletion(-) create mode 100644 tests/test_thumb_ui.py diff --git a/README.md b/README.md index 8fc59fd..6ccd65a 100644 --- a/README.md +++ b/README.md @@ -98,6 +98,10 @@ nothing: ./ida-tui fw.bin --processor arm --base 0x8000000 ``` +ARM images that use Thumb need one more thing: press `t` on the listing to switch +ARM/Thumb decoding at the cursor (it sets IDA's `T` register, and the segment to +32-bit, since Thumb doesn't exist in AArch64). + `--base` is a real address (IDA's own `-b` is in paragraphs; the conversion is done for you). In a project the options are recorded per binary, which is what a multi-image firmware wants. They apply to the first open only — after that the diff --git a/docs/PROJECTS.md b/docs/PROJECTS.md index 10274ab..38d3262 100644 --- a/docs/PROJECTS.md +++ b/docs/PROJECTS.md @@ -297,6 +297,26 @@ conversion happens in `BinaryRef.load_args`, and a base that isn't 16-byte aligned is rejected rather than silently landing somewhere else. `ida_args` passes anything else through untouched. +### ARM/Thumb + +Thumb is not a property of the bytes — it's a mode the CPU is in — so a raw image +gives IDA nothing to detect. At a Thumb entry point it decodes 16-bit +instructions as 32-bit ARM and produces confident nonsense: `push {r3,lr}` +(`08 b5`) reads as `SVCLT 0xBF00`, and `c` either refuses or carves garbage. + +`t` on the listing switches the mode at the cursor and disassembles in it: + + Thumb @ 0x0 (segment set to 32-bit; Thumb needs ARM32) — 10 instructions + +It sets IDA's `T` segment register, and forces the segment to 32-bit when +turning Thumb on. That second part isn't optional: Thumb doesn't exist in +AArch64, and a headerless blob loaded with `-parm` comes up 64-bit, so setting +`T` alone changes nothing and looks broken. Asking for Thumb *is* asking for +ARM32. + +`t` again toggles back — the mode is a guess, and guesses get revised. Both +states are saved in the `.i64`. + ### When analysis finds nothing Zero functions is what a raw image described wrongly looks like — right file, diff --git a/idatui/app.py b/idatui/app.py index 2190643..ff67eef 100644 --- a/idatui/app.py +++ b/idatui/app.py @@ -738,6 +738,7 @@ class ListingView(SearchMixin, NavMixin, ColumnCursor, ScrollView, can_focus=Tru Binding("a", "make_string", "Str", show=False), Binding("p", "define_func", "Func", show=False), Binding("u", "undefine", "Undef", show=False), + Binding("t", "toggle_thumb", "ARM/Thumb", show=False), *SearchMixin.SEARCH_BINDINGS, *NavMixin.NAV_BINDINGS, *ColumnCursor.COL_BINDINGS, @@ -1126,6 +1127,9 @@ class ListingView(SearchMixin, NavMixin, ColumnCursor, ScrollView, can_focus=Tru def action_undefine(self) -> None: self.post_message(EditItemRequested(self, "undef")) + def action_toggle_thumb(self) -> None: + self.post_message(EditItemRequested(self, "thumb")) + def action_make_data(self) -> None: self.post_message(MakeDataRequested(self)) @@ -5150,7 +5154,8 @@ class IdaTui(App): anchor: ViewAnchor | None = None) -> None: # worker context assert self.program is not None verb = {"code": "defined code", "func": "created function", - "undef": "undefined", "string": "made string"}[kind] + "undef": "undefined", "string": "made string", + "thumb": "switched decoding"}[kind] try: if kind == "code": # Keep going until something stops it: one instruction is rarely @@ -5175,6 +5180,22 @@ class IdaTui(App): "limit": "instruction limit"}.get(why, why) verb = (f"defined {n} instruction{'s' if n != 1 else ''} " f"({ea:#x}\u2013{end:#x}) \u2014 {reason}") + elif kind == "thumb": + # Switch the mode, then disassemble in it: flipping T and + # leaving the bytes undefined shows nothing, and the reason you + # flipped it was to read the code. + r = self.program.set_thumb(ea) + run = self.program.define_code_run(ea) + n = int(run.get("count", 0)) + mode = "Thumb" if r.get("thumb") else "ARM" + verb = f"{mode} @ {ea:#x}" + if r.get("forced_32bit"): + verb += " (segment set to 32-bit; Thumb needs ARM32)" + verb += (f" \u2014 {n} instruction{'s' if n != 1 else ''}" + if n else " \u2014 still doesn't decode") + # falls through to the shared reload: same cache bump, same + # anchor restore, same flash. That is the whole point of having + # one path. elif kind == "func": self.program.define_func(ea) elif kind == "string": diff --git a/idatui/domain.py b/idatui/domain.py index 606cf42..8787431 100644 --- a/idatui/domain.py +++ b/idatui/domain.py @@ -1373,6 +1373,14 @@ class Program: if res.get("error"): raise IDAToolError("define_code", f"@ {ea:#x}: {res['error']}") + def set_thumb(self, ea: int, mode: str = "toggle") -> dict: + """Switch ARM/Thumb decoding at ``ea``. Returns the resulting state.""" + r = self.client.call("set_thumb", addr=hex(ea), mode=mode) + if not isinstance(r, dict) or r.get("error"): + raise IDAToolError("set_thumb", + f"@ {ea:#x}: {(r or {}).get('error', 'failed')}") + return r + def define_code_run(self, ea: int, limit: int = 20000) -> dict: """Disassemble consecutively from ``ea`` until something stops it. diff --git a/server/patch_server.py b/server/patch_server.py index 6601a0f..e40310a 100644 --- a/server/patch_server.py +++ b/server/patch_server.py @@ -967,6 +967,63 @@ def define_code_run( return {"start": hex(start), "end": hex(ea), "count": count, "stopped": stopped} + +@tool +@idasync +def set_thumb( + addr: Annotated[str, "Address to change the ARM decoding mode at"], + mode: Annotated[str, "'toggle', 'on' (Thumb) or 'off' (ARM)"] = "toggle", + end: Annotated[str, "Optional exclusive end address (default: this item)"] = "", +) -> dict: + """Switch ARM/Thumb decoding at ``addr`` (IDA's T segment register). + + Thumb is not a property of the bytes, it's a mode the CPU is in, so a raw + image gives IDA no way to know: at a Thumb entry point it decodes 16-bit + instructions as 32-bit ARM and produces confident nonsense + (``push {r3,lr}`` reads as ``SVCLT 0xBF00``). + + Also forces the segment to 32-bit when turning Thumb ON. Thumb does not + exist in AArch64, and a headerless blob loaded with -parm defaults to + 64-bit — so setting T alone changes nothing and looks broken. Asking for + Thumb IS asking for ARM32.""" + import ida_bytes + import ida_idp + import ida_segment + import ida_segregs + + try: + ea = parse_address(addr) + except Exception as e: + return {"addr": str(addr), "error": str(e)} + treg = ida_idp.str2reg("T") + if treg is None or treg < 0: + return {"addr": hex(ea), "error": "no T register (not an ARM database)"} + seg = ida_segment.getseg(ea) + if not seg: + return {"addr": hex(ea), "error": "no segment"} + + cur = ida_segregs.get_sreg(ea, treg) + cur = 0 if cur in (None, 0xFFFFFFFF, -1) else int(cur) + want = {"on": 1, "off": 0}.get(str(mode).lower(), 0 if cur else 1) + + changed_bits = False + if want and seg.bitness != 1: + ida_segment.set_segm_addressing(seg, 1) + changed_bits = True + + try: + stop = parse_address(end) if end else 0 + except Exception: + stop = 0 + size = max(int(stop) - ea, 0) or max(ida_bytes.get_item_size(ea), 2) + # The bytes are currently decoded in the OLD mode; leaving that item defined + # pins the wrong instruction length and the new mode has nothing to apply to. + ida_bytes.del_items(ea, 0, size) + ok = bool(ida_segregs.split_sreg_range(ea, treg, want, ida_segregs.SR_user)) + now = ida_segregs.get_sreg(ea, treg) + return {"addr": hex(ea), "thumb": bool(now), "was": bool(cur), "ok": ok, + "bitness": ida_segment.getseg(ea).bitness, + "forced_32bit": changed_bits} ''' SNIPPET = f"{BEGIN}\n{BODY.strip()}\n{END}\n" diff --git a/tests/test_thumb_ui.py b/tests/test_thumb_ui.py new file mode 100644 index 0000000..dce1635 --- /dev/null +++ b/tests/test_thumb_ui.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""ARM/Thumb decoding switch, against real Thumb code. + +Thumb isn't a property of the bytes — it's a mode the CPU is in — so a raw image +gives IDA no way to know. At a Thumb entry point it decodes 16-bit instructions +as 32-bit ARM and produces confident nonsense, and `c` either fails or carves +garbage. `t` switches the mode. + +Uses experiments/fibonacci.bin (real Thumb), so the encodings are not a guess. +Needs IDA. ~40s. +""" +import asyncio +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from textual.widgets import Static # noqa: E402 + +from idatui.app import IdaTui, ListingView # noqa: E402 + +PASS = FAIL = 0 +BIN = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), + "experiments", "fibonacci.bin") + + +def check(name, ok, detail=""): + global PASS, FAIL + if ok: + PASS += 1 + print(f" ok {name}") + else: + FAIL += 1 + print(f" FAIL {name} {detail}") + + +async def wait(pred, pilot, t=240.0): + for _ in range(int(t / 0.05)): + await pilot.pause(0.05) + try: + if pred(): + return True + except Exception: # noqa: BLE001 + pass + return False + + +async def run() -> int: + # A fresh database every time: the T flag and the segment's addressing mode + # are SAVED in the .i64, so a previous run would answer the question for us. + for ext in (".i64", ".id0", ".id1", ".id2", ".nam", ".til"): + try: + os.remove(BIN + ext) + except OSError: + pass + + app = IdaTui(open_path=BIN, keepalive=False, load_args="-parm") + async with app.run_test(size=(140, 44)) as pilot: + await wait(lambda: app._func_index is not None + and app._func_index.complete, pilot) + await wait(lambda: app._cur is not None, pilot, 60) + lst = app.query_one(ListingView) + lst.focus() + lst.cursor = lst.model.index_of_ea(0) + lst._scroll_cursor_into_view() + await pilot.pause(0.3) + check("starts undefined at the entry", lst.model.get(lst.cursor).kind == "unknown", + f"{lst.model.get(lst.cursor).text!r}") + + # `c` in the wrong mode: this is the failure being fixed. It must NOT + # quietly carve garbage — either it refuses, or whatever it makes is not + # the Thumb prologue. + m0 = lst.model + await pilot.press("c") + await pilot.pause(2.5) + h = lst.model.get(lst.model.index_of_ea(0)) + check("`c` alone does not produce the Thumb prologue", + h is None or h.kind != "code" or "PUSH" not in h.text.upper(), + f"{h.text if h else None!r}") + + m1 = lst.model + await pilot.press("t") + await wait(lambda: lst.model is not m1 and lst.model is not None, pilot, 60) + await pilot.pause(0.5) + + status = str(app.query_one("#status", Static).render()) + check("the status says it switched to Thumb", "Thumb" in status, status[:90]) + # Thumb doesn't exist in AArch64, and -parm on a headerless blob gives a + # 64-bit segment, so setting T alone would change nothing and look broken. + check("and says it forced the segment to 32-bit", + "32-bit" in status, status[:90]) + + m = lst.model + rows = [m.get(m.index_of_ea(ea)) for ea in (0x0, 0x2, 0x4)] + check("the entry decodes as Thumb", + rows[0] is not None and rows[0].kind == "code" + and "PUSH" in rows[0].text.upper(), + f"{rows[0].text if rows[0] else None!r}") + # 16-bit instructions: the addresses are 2 apart, which is the whole + # point — in ARM mode these would be one 4-byte instruction. + check("instructions are 16-bit wide", + all(r is not None and r.kind == "code" and r.size == 2 for r in rows), + f"{[(hex(r.ea), r.size, r.text) for r in rows if r]}") + check("and it kept disassembling past the first one", + sum(1 for i in range(20) if (m.get(i) or h).kind == "code") > 5, + "expected a run of instructions, not one") + + # Toggling back must be possible — the mode is a guess and guesses get + # revised. + m2 = lst.model + lst.cursor = lst.model.index_of_ea(0) + await pilot.press("t") + await wait(lambda: lst.model is not m2 and lst.model is not None, pilot, 60) + await pilot.pause(0.5) + status = str(app.query_one("#status", Static).render()) + check("`t` toggles back to ARM", "ARM @" in status, status[:80]) + + print(f"\n{PASS} passed, {FAIL} failed") + return 1 if FAIL else 0 + + +if __name__ == "__main__": + if not os.path.isfile(BIN): + print(f"no such binary: {BIN}") + raise SystemExit(2) + raise SystemExit(asyncio.run(run())) -- cgit v1.3.1-sl0p