Skip to main content

Crate thumb_asm

Crate thumb_asm 

Source
Expand description

Generic, platform-neutral toolkit for reading, patching and generating ARM-Thumb code inside a flat binary image.

Whatever the image is — a drive firmware dump, a boot ROM, a stripped .bin carved out of an update package — the work reduces to four verbs:

  • find — locate something (a byte pattern, a word, a run of free space, a call site). ONE primitive, find, expressed over a Needle; every named finder (find_free_space, …) is a thin overload of it. Because find takes a start and returns the match offset, finds compose by nesting: find(y, find(x, find(a, 0))).
  • read — read a value at a found location: read_u32, read_u16, read_u8 for offsets already known to be in bounds, and the Option-returning try_read_u32, try_read_u16, try_read_u8 for scans that walk to the end of the image. Instruction-level reads are decode_bl, decode_b_wide and decode_b_cond.
  • modify / insert — write() bytes at an offset (repoint a record, patch a field) or insert a code blob into free space, returning its address. install_branch does the whole detour-installation pattern — encode, write, decode back to confirm — in one call.
  • create — Asm, a small position-independent Thumb assembler with a literal pool and data blobs, plus the standalone encoders encode_bl, encode_b_wide and encode_b_cond.

The crate deliberately knows nothing about any particular firmware, vendor or tool. The knowledge — which needle to look for, where it lives, what to assemble in its place — belongs to the caller; this crate supplies only the verbs, so supporting a new platform never means new toolkit logic.

Every encoding claim in this file cites its section in Arm’s architecture reference manuals (A5.*/A7.* = ARM DDI 0403E.e, Armv7-M; A6.* = ARM DDI 0406B, Armv7-A/R).

Re-exports§

pub use isa::Insn;
pub use isa::Operand;
pub use isa::Reg;
pub use isa::Width;

Modules§

analysis
Image analysis — the questions a Thumb patching session actually asks.
detour
Installing a detour over live code: decode what is there, move it into a stub, and branch.
flags
Which condition flags an instruction reads and writes, and which are live at a point in an image.
isa
Instruction-accurate Thumb decoding.
relocate
Re-siting one decoded instruction so that it still means the same thing at a new address.

Structs§

Asm
A tiny position-independent Thumb assembler with a trailing 4-byte-aligned literal pool — the “create” verb. It is dumb: it emits exactly the instructions asked for and lays out ldr rt, [pc, #imm] literals in first-reference order. An engine composes it; the toolkit never decides what to assemble.
CommandRecord
One resolved dispatch record.
CommandTable
An opcode-dispatch table: an array of fixed-size records that firmware scans by key until it finds a handler pointer to call. The shape recurs across unrelated devices (SCSI/ATA command tables, vendor-command tables, ioctl and AT-command jump tables), so this type stores only the geometry — where the records start, how wide they are, and which byte of a record holds the opcode, the flags and the handler pointer. The caller supplies those numbers; CommandTable::find, CommandTable::walk and CommandTable::replace are generic over them.
CondBranch
A decoded conditional branch: which condition, where it goes, and how wide the instruction was.
FreeSpace
An allocator over the erased space in an image.
InstallMismatch
The four bytes at a detour site do not branch where they were meant to.

Enums§

AsmError
Error returned by Asm::finish when an encoded branch, ldr literal, or adr falls outside what its Thumb encoding can represent, or when a label was referenced but never bound.
BranchAt
What is already at a patch site. Returned by classify_branch.
BranchKind
Which 4-byte branch a detour site is patched with.
Cond
An ARM condition code.
FindError
Why find_one did not return an offset.
Fit
Which free run to choose when more than one will do. See find_free_space_in.
InstallHazard
Why can_install says a site cannot take a branch.
Needle
A thing find can search for. Add a variant here to teach every caller a new kind of search without touching caller code.
Straddle
What to do with a free run that crosses out of the regions it was found in.

Functions§

can_install
Would installing a 4-byte branch here overwrite whole instructions?
can_install_with
Same as can_install but for a caller who knows the image’s ISA isa::Target. This is the load-bearing surface for the 0.14.0 detour path: under Target::Union an Armv8-M SG at the hook site decodes as a plain LDRD (the whole reason isa::Target exists — 0.12.0), so can_install silently green-lights overwriting the Security Gateway. A caller who passes Target::V8M gets the honest answer, which is still Ok(()) today because SG is a legal instruction on that target, but sets the stage for follow-on hazards (InstallHazard::SecureGateway, planned for 0.14.x) to fire from this path.
classify_branch
Ask what branch is already at at, before overwriting it.
classify_branch_with
Same as classify_branch but for a caller who knows the image’s ISA isa::Target. Under Target::V8M this is what lets a hook-site check see a CMSE gateway (SG) as NotABranch — since SG is not a branch — rather than as a fake pc-relative LDRD whose displacement then gets followed as a “branch target that carries a literal address”. See can_install_with for the parallel argument on the install side.
decode_b_cond
Decode the conditional branch at at, in either encoding, or None if the bytes there are not one.
decode_b_wide
Decode a Thumb-2 B.W (T4) at off and return its absolute target (Thumb bit cleared), or None if the two halfwords there are not a B.W. Mirror of decode_bl but discriminates on the hw2 bit-12=1 && bit-14=0 pattern (B.W) vs bit-12=1 && bit-14=1 (BL).
decode_bl
Decode a Thumb BL at file offset off → its absolute target VA (Thumb bit cleared). None if the 4 bytes at off are not a BL.
encode_b_cond
Encode a conditional branch at file offset site to absolute target, choosing the narrowest encoding that reaches: 2 bytes (T1, ±254) if it fits, else 4 bytes (T3, ±1 MB), else None.
encode_b_wide
Encode a Thumb-2 wide unconditional branch (B.W, T4 encoding) at file offset site that jumps to absolute target target (Thumb bit implicit; pass the even entry address). Same 4-byte width and same imm packing as encode_bl — the only difference is hw2’s base (0x9000 for B.W instead of 0xD000 for BL, i.e. bit 14 cleared). Same ±16 MiB range.
encode_bl
Encode a Thumb BL at file offset site that calls absolute target target (Thumb bit is implicit; pass the even entry address). Returns the 4 bytes, or None if target is out of BL range (±16 MiB).
find
The one search primitive. Find needle at or after byte offset start; return the offset of the match, or None. Every named finder below is a thin overload of this call.
find_bl_sites
Every file offset holding a Thumb BL whose target is target (Thumb bit ignored). These are the direct call sites that reach a handler — the thing to redirect when a firmware dispatches by hardcoded call rather than a table.
find_free_space
Overload: the first run of >= len free (0xFF) bytes at or after start whose start offset is a multiple of align. find_free_space(image, len, align, start) == find(image, Needle::FreeRun { len, align }, start).
find_free_space_in
Free space, restricted to regions the caller says are writable.
find_in
find, confined to a window of the image.
find_one
Find needle and require that it occurs exactly once.
find_one_in
find_one, confined to a window of the image.
insert
Insert: copy code into free space at free_off, returning the image address it now lives at (offset == load address on this flat mapping).
install_branch
Encode a kind branch from site to target, write it into image, and verify by decoding it back — the whole install-a-detour pattern in one call.
prologue_is_push_lr
Whether the Thumb code at file offset off begins with a push {..., lr} (0xB5xx, A5.2.5) within the first window halfwords — a cheap “this is a real function entry” cross-check. Used to reject a coincidental byte match when resolving a handler pointer: a scan over every even offset can land mid-instruction, and a plausible-looking hit that is not preceded by a prologue usually is one of those.
read_u8
Read the byte at at.
read_u16
Read the little-endian u16 at at.
read_u32
Read the little-endian u32 at at (e.g. a record’s handler pointer).
try_read_u8
read_u8 without the panic: None when at is past the end.
try_read_u16
read_u16 without the panic: None unless all 2 bytes are in bounds.
try_read_u32
read_u32 without the panic: None unless all 4 bytes are in bounds.
verify_branch
Confirm that the four bytes at site are a kind branch to expected.
write
Modify: overwrite image[at..at+bytes.len()] with bytes.

Type Aliases§

Result
The crate’s Result, defaulted to AsmError so downstream code can write -> thumb_asm::Result<Vec<u8>> and mean “or an assembler error”.