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 aNeedle; every named finder (find_free_space, …) is a thin overload of it. Becausefindtakes astartand 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_u8for offsets already known to be in bounds, and theOption-returningtry_read_u32,try_read_u16,try_read_u8for scans that walk to the end of the image. Instruction-level reads aredecode_bl,decode_b_wideanddecode_b_cond. - modify / insert —
write()bytes at an offset (repoint a record, patch a field) orinserta code blob into free space, returning its address.install_branchdoes 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 encodersencode_bl,encode_b_wideandencode_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§
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. - Command
Record - One resolved dispatch record.
- Command
Table - 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::walkandCommandTable::replaceare generic over them. - Cond
Branch - A decoded conditional branch: which condition, where it goes, and how wide the instruction was.
- Free
Space - An allocator over the erased space in an image.
- Install
Mismatch - The four bytes at a detour site do not branch where they were meant to.
Enums§
- AsmError
- Error returned by
Asm::finishwhen an encoded branch,ldrliteral, oradrfalls outside what its Thumb encoding can represent, or when a label was referenced but never bound. - Branch
At - What is already at a patch site. Returned by
classify_branch. - Branch
Kind - Which 4-byte branch a detour site is patched with.
- Cond
- An ARM condition code.
- Find
Error - Why
find_onedid not return an offset. - Fit
- Which free run to choose when more than one will do. See
find_free_space_in. - Install
Hazard - Why
can_installsays a site cannot take a branch. - Needle
- A thing
findcan 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_installbut for a caller who knows the image’s ISAisa::Target. This is the load-bearing surface for the 0.14.0 detour path: underTarget::Unionan Armv8-MSGat the hook site decodes as a plainLDRD(the whole reasonisa::Targetexists — 0.12.0), socan_installsilently green-lights overwriting the Security Gateway. A caller who passesTarget::V8Mgets the honest answer, which is stillOk(())today becauseSGis 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_branchbut for a caller who knows the image’s ISAisa::Target. UnderTarget::V8Mthis is what lets a hook-site check see a CMSE gateway (SG) asNotABranch— sinceSGis not a branch — rather than as a fake pc-relativeLDRDwhose displacement then gets followed as a “branch target that carries a literal address”. Seecan_install_withfor the parallel argument on the install side. - decode_
b_ cond - Decode the conditional branch at
at, in either encoding, orNoneif the bytes there are not one. - decode_
b_ wide - Decode a Thumb-2
B.W(T4) atoffand return its absolute target (Thumb bit cleared), orNoneif the two halfwords there are not aB.W. Mirror ofdecode_blbut discriminates on thehw2bit-12=1 && bit-14=0 pattern (B.W) vs bit-12=1 && bit-14=1 (BL). - decode_
bl - Decode a Thumb
BLat file offsetoff→ its absolute target VA (Thumb bit cleared).Noneif the 4 bytes atoffare not aBL. - encode_
b_ cond - Encode a conditional branch at file offset
siteto absolutetarget, choosing the narrowest encoding that reaches: 2 bytes (T1, ±254) if it fits, else 4 bytes (T3, ±1 MB), elseNone. - encode_
b_ wide - Encode a Thumb-2 wide unconditional branch (
B.W, T4 encoding) at file offsetsitethat jumps to absolute targettarget(Thumb bit implicit; pass the even entry address). Same 4-byte width and same imm packing asencode_bl— the only difference ishw2’s base (0x9000forB.Winstead of0xD000forBL, i.e. bit 14 cleared). Same ±16 MiB range. - encode_
bl - Encode a Thumb
BLat file offsetsitethat calls absolute targettarget(Thumb bit is implicit; pass the even entry address). Returns the 4 bytes, orNoneiftargetis out ofBLrange (±16 MiB). - find
- The one search primitive. Find
needleat or after byte offsetstart; return the offset of the match, orNone. Every named finder below is a thin overload of this call. - find_
bl_ sites - Every file offset holding a Thumb
BLwhose target istarget(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
>= lenfree (0xFF) bytes at or afterstartwhose start offset is a multiple ofalign.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
needleand require that it occurs exactly once. - find_
one_ in find_one, confined to a window of the image.- insert
- Insert: copy
codeinto free space atfree_off, returning the image address it now lives at (offset == load address on this flat mapping). - install_
branch - Encode a
kindbranch fromsitetotarget, write it intoimage, 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
offbegins with apush {..., lr}(0xB5xx, A5.2.5) within the firstwindowhalfwords — 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_u8without the panic:Nonewhenatis past the end.- try_
read_ u16 read_u16without the panic:Noneunless all 2 bytes are in bounds.- try_
read_ u32 read_u32without the panic:Noneunless all 4 bytes are in bounds.- verify_
branch - Confirm that the four bytes at
siteare akindbranch toexpected. - write
- Modify: overwrite
image[at..at+bytes.len()]withbytes.