Repository navigation
Releases
v0.14.1
Mutation-coverage patch. No API changes, no behaviour changes. Adds tests
that close the remaining tractable gaps in the pre-0.14.0 code, and
introduces a durable convention for documenting mutants that are provably
equivalent-by-construction so future sweeps can stop chasing them.
Test coverage
Flags::contains— added three per-flagother=set, self=emptycases
(one each for N, Z, C), which pin the!other.x || self.xclauses that
the existingNZC.contains(ALL)case only exercised for V. Kills three
delete !mutants insrc/flags.rs:121.encode_stm_ldmT1 (stmia/ldmianarrow encoder insrc/isa/t16_branch.rs)
— added a hand-built-Insncase withRninr8..=r15for both
mnemonics. Ther.is_low()guard on the base register was previously
only exercised by the exhaustive-halfword round-trip loop, whose inputs
never see a non-low base; a mutant that replaced the guard withtrue
would silently flipstmia(base0xC000) toldmia(base0xC800)
throughrn << 8overflow. The new test assertsencodereturnsNone
for every non-low base for both mnemonics.
Documentation
Introduces a // mutant-equivalent: line-marker convention for mutants
that are provably equivalent-by-construction — the mutation produces the
same observable behaviour as the original across every input the function
can receive, so no test can distinguish them. Comments are one line,
positioned on or immediately above the mutated line, and state the
equivalence argument in one sentence.
Sites documented in this release:
src/isa/mod.rs:317,:331— the two 32-bit dispatch arms whose
mutation is subsumed by the_ =>catch-all'st32_coproc::decode(...) .or_else(t32_simd::decode), or by that catch-all'sNone. The existing
block comments already argued the equivalence; themutant-equivalent
markers make them greppable.src/lib.rs:904—Asm::imm'sstep > 1fast-path: withstep == 1,
v % 1is identically0, so the second conjunct is unreachable under
either> 1or>= 1.src/analysis.rs:687—reachable_with'simage[at + 1]for
it_state_fromreads only the low byte's cond/mask nibbles; the high
byte the second index would name (the IT opcode's0xBF) is never
looked at, soat + 1→at * 1is observably identical.src/isa/t32_coproc.rs:1464..1472— the pre-existing block comment on
the four hand-writtenr.num() < 16guards has grown a
mutant-equivalent (nine mutants — ...)header so the grep sweep
recognises the whole family in one place.Reg::numisself.0 & 0xF,
so the predicate is unconditionally true and every weakening of it
yields an identical program.
Not addressed
The 597 replace | with ^ misses on encoders that OR together
mask-disjoint bit-fields remain provably equivalent-by-construction, as
cargo-mutants' own runbook (skill §7b) calls out. The hw = a | b | c
family is left as-is: annotating each one line-by-line would be six
hundred lines of noise. A future release may add a per-encoder-file
header once the semantics of "these fields are disjoint" is stated once
in isa::insn and pointed to from the emitters.
v0.14.0
The encoder learns to say "not on this chip". isa::Target — decoder-only
through 0.13 — now runs through the assembler and the install/verify/analysis
surfaces, so a caller who knows their image's profile gets refusal at the
emitter that would produce an instruction the target does not define, and a
detour that would misread a CMSE Security Gateway as a spurious pc-relative
LDRD gets the honest answer.
The mechanism is a per-emitter legality table (see
src/isa/legality.rs), not decode-back: spec/THUMB-ISA.md §988–991 makes
the decoder a union by design, so "does it decode under V7A?" is not the
question. "Does this mnemonic + encoding form appear on V7A?" is, and that is
what the table answers.
The 0.14.0 table is deliberately minimal: only sdiv and udiv (Thumb-2
T1) are restricted, on Armv7-A and on the strict V7AR intersection.
Every other current Asm emitter is baseline T1 that is defined across
Armv6-M / V7-M / V7-A / V7-R / V7E-M / V8-M identically, so the gate is a
no-op for the pre-existing emitter surface today. The follow-on rows —
sg/bxns/blxns under V8M, enterx/leavex under ThumbEE, blx label
T2, DSP, and the operand-discriminated mrs/msr/cps/dsb/dmb
mnemonics — land in 0.14.x / 0.15.0 alongside their emitters.
Emitted bytes changed
Nothing changes for an existing caller under Target::Union — the crate's
default. Bytes for sdiv/udiv are unchanged (they weren't emittable
before 0.14). The 16-bit digest across the baseline emitter corpus is
unchanged.
Added
-
Asm::with_target(isa::Target)andAsm::target()— construct
a chip-specific assembler that refuses at the emit site any instruction
the target does not define. UnderTarget::Unionthe behaviour is
byte-for-byte identical toAsm::new(). -
Every
Asmemitter is now fluent:-> &mut Self, so
Asm::with_target(V8M).sdiv(0, 1, 2).finish().unwrap()reads as a
single expression.label(),data_blob(),pos(),target()and
finish()do not chain (they return values other than the builder). -
Asm::finish(&mut self)replaces the by-valuefinish(self).
Every path (OkorErr) leavesselfa fresh empty assembler with
the same target — the reuse contract Fable's audit named. Twofinish()
calls in a row: the second returnsOk(vec![]). A label from the
previous buffer used afterfinishis refused as
AsmError::Layout { .. }by the nextfinish, never silently bound to
an offset in the new buffer. -
Asm::sdiv(rd, rn, rm)andAsm::udiv(rd, rn, rm)— the
demonstration restricted emitters. Both emit the Thumb-2 T1 wide
encoding (ARM ARM A8.8.165 / A8.8.267); both refuse SP (r13) and PC
(r15) in any argument asAsmError::Operand. Under
Target::V7A/V7ARthey refuse asAsmError::Unsupported; under
V7R/V7M/V7EM/V8M/Unionthey emit. -
Asm::raw16_unchecked(hw)— the explicit "these bytes, no gate"
escape hatch.raw16(hw)under a non-Union target now decodeshwunder
self.target, refuses a wide-instruction prefix (points atraw32),
and consults the legality table on the recovered mnemonic; use the
_uncheckedform to bypass every check. -
Asm::raw32(hw1, hw2)— first-class emitter for wide (Thumb-2)
patterns. Same non-Union rule asraw16— decode underself.target,
legality-check the recovered mnemonic — the load-bearing correctness for
hand-encoding CMSE (SG) sequences on V8M. -
isa::Target::V7A,isa::Target::V7R,isa::Target::V7EM
— the sub-profile split V7AR needed.Targetis#[non_exhaustive]so
the additions are additive.V7ARis retained as the strict
intersection — legal iff legal on both V7A and V7R — which makes it
strictly stricter than V7R alone (the answer for images of unknown
sub-profile). V7M/V7A/V7R/V7EM are legality-discriminated only; the
decoder treats them identically toUnion. V8M and ThumbEE remain
decoder-discriminated. -
can_install_with(target, ...),classify_branch_with(target, ...),analysis::xrefs_with(target, ...),
analysis::reachable_with(target, ...),
analysis::function_start_with(target, ...),
analysis::literal_value_with(target, ...)— target-aware overloads
of every install / analysis surface that previously hardcoded
Target::Union. The old signatures are retained and delegate to Union. -
DetourOptions::target: isa::Targetand
DetourOptions::with_target(...)— threads the caller's profile
through the detour path (displaced-instruction sweep, flag-liveness
analysis, stub verifier). Consequence: on an Armv8-M image a Security
Gateway (SG) at the hook site is now decoded assg, not as a
phantom pc-relativeLDRDwhose "literal target" the detour follows
into whatever bytes sit at that offset.
Changed (breaking, pre-1.0)
-
AsmErrorbecomes an enum with three variants:
Operand { at, msg },Unsupported { at, mnemonic, target },
Layout { at, msg }.reason()accordingly returns"operand",
"unsupported"or"layout".message()is removed — use
format!("{err}")or theDisplayimpl. Every variant carriesat,
the byte position in the code buffer the error refers to.AsmError::at()
exposes it. -
Asm::finishtakes&mut selfrather thanself. Callers doing
asm.finish()?on amutbinding are unaffected; a caller passing
Asmby value into a function that then called.finish()will need
to pass&mut Asminstead. -
Every
Asmemitter returns&mut Selfrather than(). Callers
who wrote closures like|a| a.push(0)in aFnOnce(&mut Asm)context
will need to add a discard:|a| { a.push(0); }.
v0.13.0
Know what the registers and flags are doing. The crate stops refusing
instructions it can prove are safe to rewrite.
Emitted bytes changed
Nothing changes for an existing caller. The one rewrite this release adds is
off by default: DetourOptions::rewrite_compare_branches is false, so a
displaced CBZ/CBNZ that cannot reach its target is still refused exactly
as in 0.12.0. Turn it on and a CBZ at a site where every condition flag is
dead becomes CMP + B<cond>.W — different bytes, deliberately, and only
where they mean the same thing.
The 16-bit digest is unchanged: 0x0e06fda25d6b89e8.
Added
-
flags— which condition flags an instruction reads and writes, and
which are live at a point in an image.This is per-flag rather than a bool, and that is the whole point.
Insn::sets_flagssays that flags are written; the mnemonic says which.
Logical and shift operations withS—ANDS,ORRS,EORS,BICS,
MVNS,LSLS,LSRS,ASRS— write N, Z and C and leave V untouched,
with DDI 0403E.e A7.7.9 and its siblings saying// APSR.V unchanged
outright. Arithmetic and the comparisons write all four. A model that reads
sets_flagsas "all four die here" therefore reports V dead after an
ANDS, which would licence a rewrite that destroys a V the next branch
tests.Reads are asymmetric in the same way:
ADC,SBC,RSCandRRXconsume
the carry flag withcond: None, so a rule built oninsn.cond.is_some()
misses every one of them.live_afterfollows both the fall-through and the taken path. That is
not a refinement — the motivating caller is rewriting aCBZ, which is
itself a conditional branch, so half of what happens after it is at its
target. Anything it cannot follow (an unresolvable target, a target outside
the image, undecodable bytes, the walk budget running out) resolves to every
flag live. The approximation is one-directional by design: a flag reported
live may be dead, but a flag reported dead is dead on every path it saw. -
relocate::widen_compare_branch— rewritescbz rn, tascmp rn, #0beq.w t.relocaterefuses these outright, because the offset is
unsigned and forward-only (0 to 126 bytes, no backward form), so a stub in
free space essentially never reaches.
It takes the liveness as an argument rather than computing it, because it
receives anInsnand liveness is a property of the image around it. It
refuses unless every flag is dead. -
RelocateError::FlagsLive— names which flags are live, not just that
some are. Worth reading rather than treating as a yes/no: "only V" is the
common answer, because a nearbyANDSkills three of the four and looks as
though it killed all of them. -
DetourOptions::rewrite_compare_branches— opt in, and it does not make
the rewrite unconditional. Liveness is computed from the image at each
displaced instruction's original address, and a site where any flag survives
is still refused.
Hardened
-
A ten-lens audit of the new liveness code and the modules around it,
looped to convergence over six rounds. It confirmed 27 defects, all fixed
here. The four high-severity ones were all in this release's ownflags
code and all erred toward reporting a flag dead — the direction that turns
a refusal into a silent clobber:live_afterfollowing a literal load's
Targetinto the pool and decoding data as code;live_fromwalking with
the stateless decoder and so missing anITblock's flag reads and its
setflags = !InITBlock()suppression;readsmissingRRXused as a shift
operand; andwritesclaimingMSR APSR_gtouches the condition flags when
it writes only the GE bits. -
An integer-overflow class, fixed in six places. Arithmetic on a
caller-suppliedu32/usizeaddress done before the bounds check meant to
reject an extreme value — a panic in debug, a wrapped and wrong result in
release — inCommandTable::find,widen_compare_branch,build_stub,
disassemble,function_startandreachable. A crate that must never
crash on caller input now refuses these rather than overflowing. -
Every ARMv8-M / VFP citation in
docs/CONFORMANCE.mdcorrected (twelve
section numbers that named the wrong instruction), and the document is now
pinned totests/support/divergences.rsby a test, so the two cannot drift
again.Asm::finishalso stopped indexing its label table with an
unvalidated caller id, and several stale comment fragments were removed.
Deferred
- The
UNPREDICTABLEchannel onInsn, again. It needs
#[non_exhaustive]onInsn, which removes literal construction from a
struct whose hand-construction is a documented use case, so it needs a
builder designed first — and then every group module has to classify its own
encodings, which is a pass over nineteen files rather than an afternoon.
Shipping half of it would mean a second breaking release to finish it.
v0.12.0
Say what you are patching. The crate stops inferring the instruction set from
the instruction and starts being told.
Emitted bytes changed
Nothing moves for existing callers. [Target::Union] is the default and
reproduces 0.11.1 exactly, including where an Armv8-M encoding collides with
an Armv7 one: under the union SG still decodes as the LDRD Armv7 reads
there. The pinned 16-bit digest is unchanged — 58,233 decoded halfwords,
0x0e06fda25d6b89e8.
Bytes do change if you opt in to Target::V8M, which is the point of
opting in.
Fixed
-
Armv8-M images were decoded wrongly, silently. Not refused — answered,
confidently and incorrectly:halfwords was is, under Target::V8M0xE97F 0xE97Fldrd lr, r9, [pc, #-508]!, 0xe08sg0xE841 0xF000strex r0, pc, [r1]tt r0, r10x4774None, andDecoderstopsbxns lrSGis the mandatory first instruction of every secure-gateway veneer, so
every TrustZone-M image contains one; read asLDRDit carries a resolved
pc-relative target andanalysis::literal_valuewill read a pool word that
is not there.BXNSends every secure entry function, soreachable
reported a function with a truncated body and no exit.
Breaking changes
-
decode_at_with,decode_halfwordsandDecoder::thumbeetake a
Targetinstead of athumbee: bool.Decoder::thumbee(true)becomes
Decoder::target(Target::ThumbEE);falsebecomesTarget::Union.
decode_atandDecoder::neware unchanged. -
Operand,XrefKind,Widen,Reach,Xref,DetourErrorand
InstallMismatchare now#[non_exhaustive], so amatchover them
needs a wildcard arm. This is the same budget 0.11.0 spent onNeedleand
friends, finishing the job it started — every one of these has to grow as
the ISA and the refusal vocabulary do.WidthandCondare deliberately not marked. Thumb has two
instruction lengths and a four-bit condition field, so those sets are closed
by the architecture; marking them would cost callers exhaustive matching for
a flexibility that can never be used.Insnis not marked either, and that is a deferral rather than a decision:
it is a struct with public fields, so#[non_exhaustive]would remove
literal construction — which is a documented use case here. It needs a
builder first, and that is 0.13.0's.
Added
-
isa::Target—Union,V7M,V7AR,V8M,ThumbEE. Most of the
crate still decodes the union deliberately: for most of the map the profiles
disagree only about which patterns are UNDEFINED, and a union decoder is
more useful on an image of unknown provenance.Targetis for where that
stops being a coherent answer, because the patterns collide. -
The Armv8-M Security Extension —
SG,BXNS,BLXNS,TT,TTT,
TTA,TTAT, decoded and encoded underTarget::V8M. Implemented as a
profile-owned slice in the shapethumbeeestablished, consulted before
dispatch, so none of the nineteen group modules changed. It has to run
before them rather than as a fallback: these are reassignments of
allocated patterns, so once an Armv7 group has answered, the wrong answer
has been chosen.CLRMis not included despite usually being listed with CMSE. LLVM
rejects it forarmv8-m.mainwith "instruction requires: armv8.1m.main", so
it belongs with the Armv8.1-M work. -
RelocateError::SecureGateway— moving anSGis refused. It is the
only refusal here that is not about range, alignment or encodability:SG
re-encodes perfectly at any address and is still wrong to move, because the
Security Attribution Unit identifies a gateway by the address the
instruction sits at. Moved, it stops being a gateway and the address it
vacated stops being guarded — so a detour over one would silently close the
entry point it was patching. -
detour::detour_in— place the stub only in regions the caller declares
writable. The built-in search knows about runs of0xff, which is a guess
about what is erased and says nothing about what is safe to write: a run
inside a checksummed block, or one the bootloader rewrites, looks identical
to a spare one.FreeSpaceandfind_free_space_inshipped in 0.11.1 and
detourreached neither.It is a function rather than a
DetourOptionsfield because the option
struct would need a lifetime parameter to hold a borrowed slice, and because
the regions describe the call rather than a default. It is not equivalent to
allocating and passingstub_at: that is one attempt with no retry, and
whether a stub is usable is not knowable until the patch is laid out. -
reason()on every error type.RelocateErrorwas the only one with
both#[non_exhaustive]and a machine-readable reason;FindErrorand
InstallHazardhad the first,DetourErrorthe second,AsmErrorand
InstallMismatchneither. All six now have both.AsmErroralso gains
message().
Testing
-
Mutation score holds at 91.1% across 7,738 mutants (up from 7,624), so
the new code is covered in the same proportion as the old rather than
diluting it. 593 of the 666 survivors are the|to^family over
disjoint bit-fields and 4 arer.num() < 16, both equivalent by
construction.The run found one real gap in this release's own code: nothing distinguished
hook & !1fromhook,hook | !1orhook ^ !1indetour_in, because
every test passed an already-even hook. A Thumb function pointer
conventionally has bit 0 set — that is how the architecture marks a Thumb
entry point — so a caller reading one out of a vector table passes an odd
address, and the masking is on the path every such call takes.
Documentation
-
Which "regions" this crate means: the caller's, always. Raised by a
consumer againstStraddle, whoseRejectrationale cites erase
granularity and so reads as though the crate consults an erase-block map. It
does not and cannot — it is handed a&[u8]with no device geometry. A
region is whatever you meant it to be, and erase granularity is a reason you
might chooseReject, not something that can be detected here. Stated on
Straddleand applied to every region-taking API. -
Labelling a
FindErroris shown rather than supported. Acontext(&str)
was requested; a&'static strwould not take a label built at run time and
aStringwould make a currently-Copyerror allocate on a path that is
often in a loop.countandfirstare public, so the wrapper it would
replace is onematcharm, now the documented example.
v0.11.1
Emitted bytes changed
No instruction encoding changed: the digest is unchanged from 0.11.0 —
58,233 decoded 16-bit halfwords, 0x0e06fda25d6b89e8.
But placement did. The find_free_space_in fix below changes the address
returned for callers who pass more than one region, so an image built through
it can differ byte-for-byte from one built with 0.11.0 even though every
instruction in it encodes identically. If you pin a whole image or a digest
over one, expect a diff and check it is only the stub addresses moving.
That is not an instruction-encoding change and the digest cannot see it, which
is worth being explicit about rather than letting "digest unchanged" be read as
"your image is unchanged".
This section is now a fixed heading that appears in every release, empty or
not, so a consumer with a byte-exact golden test can grep for it rather than
read for it. See docs/ENCODING-STABILITY.md, which exists because 0.10.0's
mov_reg fix moved 21 bytes in a consumer's image and they discovered it when
their known-answer test failed rather than from the release notes. The fix was
correct; announcing it only in prose was not.
Fixed
find_free_space_inreturned a different address depending on the order
the regions were passed.Fit::Firstreturned whichever region was listed
first rather than the lowest address, despite the name, andFit::Largest
broke ties the same way. Two callers with identical intent got different stub
addresses, which for anyone producing byte-reproducible images is
nondeterminism with nothing to show for it. Both policies now resolve to an
address:Firstis the lowest offset,Largestbreaks ties on the lowest
offset. Reported by a consumer; it shipped in 0.11.0 through a green gate,
because nothing tested the same regions in two orders.
Added
-
find_inandfind_one_in— search confined to a window. Scoping is not
ergonomics, it is how an otherwise-ambiguous signature becomes usable: a
pattern matching three places across an image may match once inside the
region you care about, andfind_onewithout a bound was usable only where
the pattern was globally unique — the case that never needed checking. The
range is in image coordinates and matches must lie entirely inside it;
taking a window rather than letting callers slice is what keeps
Needle::Masked's halfword boundaries andNeedle::FreeRun's alignment
measured from the image origin. -
FreeSpaceandStraddle— an allocator over erased space. Placing
several stubs is a different question from placing one, and repeating a
search does not answer it: nothing has been written yet, so every call
returns the same offset. This tracks what it has handed out, so allocations
pack contiguously without writing first. Regions are normalised to a sorted,
merged set, so the sequence of offsets depends on the region set and not
the order they were listed.Straddle::Rejectrefuses a free run that
continues past the regions it was found in — for callers whose erase
granularity is coarser than their integrity regions, where clipping does not
help because the hazard is the write, not the placement. -
can_installandInstallHazard— a pre-flight check for a patch site.
classify_branchreports width; this answers the question width was being
consulted for, so the caller is not left doing the reasoning that goes wrong.
The hazard is more general than "the site holds a 16-bit branch": any 2-byte
instruction followed by a 4-byte one spans six, and a 4-byte branch leaves
two bytes to be executed as whatever they encode. -
docs/ENCODING-STABILITY.mdand a pinned encoding digest in the test
suite, so a change to emitted bytes fails the build before it reaches a
consumer's known-answer test.
Documentation
- The half-open range convention is stated on every range-taking function.
a..=bis deliberately not accepted: a&[Range]whose elements were built
under two conventions cannot be told apart by reading it, so refusing the
inclusive form makes a porting error a compile error rather than an
off-by-one.
v0.11.0
Four additions requested by a consumer patching firmware with this crate, each
a case where the crate was close but an assumption blocked them. Two of the
four cannot be made without breaking changes, which is what makes this 0.11.0
rather than 0.10.2 — cargo-semver-checks runs in the qa gate and would have
refused a patch bump.
Breaking changes
-
Needle,BranchKind,ConventionandDetourOptionsare now
#[non_exhaustive]. This is the last time an addition to any of them costs
a version. A downstreammatchon one of the enums now needs a_arm, and
DetourOptionsmust be built throughDetourOptions::new()and thewith_*
chain rather than a struct literal — which is what the examples already did. -
DetourOptionsgained astylefield. Defaults to
DetourStyle::ResumeAfter, which is the existing behaviour, so a caller
using the builder is unaffected.
Added
-
Needle::Masked(&[(u16, u16)])— instruction search with don't-care
bits. A signature is(value, mask)halfword pairs: "anyBL" is
(0xF000, 0xF800), the five bits that identify the encoding fixed and the
eleven displacement bits ignored.Needle::Bytescannot express that at all,
because the bytes differ at every call site, so every consumer was
hand-rolling the scan. Matches are halfword-aligned: Thumb instructions
are 2-aligned, and a byte-granular scan reports hits straddling two real
instructions that look plausible and are not instructions. An empty pattern
matches nothing rather than everything. -
find_one— search that refuses to guess.findreturns the first
match, which is right when scanning and wrong when identifying: a signature
matching three places has not found the function, it has said the signature
is too weak, and patching the first one is how a tool reports success and
bricks a device.Err(FindError::Ambiguous { count, first })carries both
numbers so a caller can say what happened without repeating the search. -
find_free_space_inandFit— free space restricted to regions the
caller says are writable, with a first-fit or largest-fit policy.
find_free_spacescans the whole image, which assumes every erased byte is
fair game; in a real image it is not — a region may be integrity-covered,
vendor-reserved, or outside the erase block being rewritten. Only the caller
knows. Slicing the image and searching that is not a workaround: slicing
at an unaligned offset moves the alignment origin, so a result that is
4-aligned within the slice is not 4-aligned within the image — the same
failure thealignparameter exists to prevent, reintroduced one layer up.
Fit::Largestexists because first-fit takes the first hole big enough and
leaves the large one fragmented. -
classify_branchandBranchAt— ask what is at a site before
overwriting it.verify_branchchecks an assertion: you say which kind and
target you expect and it agrees or disagrees. It cannot catch the
expectation itself being wrong, which is the interesting failure. The field
that matters most is width: a 16-bitbat the site comes back as
Direct { kind: None, width: 2 }, andinstall_branchonly writes 4-byte
branches, so patching over it consumes the two bytes of whatever follows.
Checkingwidthfirst turns a field-reported brick into a refusal. -
DetourStyle::DiscardAndJumpTo(u32)— the tail-call detour shape:
replace the site's instructions and branch to a computed address rather than
relocating them and resuming. The variant is named for what it does because
the displaced instructions do not run; an arm calledJumpToreads like
a destination choice and hides that. This is the only operation in the crate
that discards instructions, and the crate cannot check that you meant it.
v0.10.1
No code changes: the library is byte-identical in behaviour to 0.10.0. This
release exists so that the project's governance, security and assurance
documentation is published alongside the crate rather than only in the
repository, and so that there is a release carrying signatures.
Added
-
SECURITY.md— how to report a vulnerability (privately, through GitHub
private vulnerability reporting or by email), what response to expect, and
how reporters are credited. It also states scope: the realistic reports are a
panic reachable from untrusted input through an API not documented as
panicking, a mis-encoded or mis-decoded instruction, or an unbounded loop or
allocation driven by input. Explicitly out of scope:read_u8/read_u16/
read_u32panicking past the end of the image, which they are documented to
do —try_read_*returningOptionis the form for untrusted input. -
docs/ASSURANCE_CASE.md— the argument that the crate is adequately
secure for what it does, with the evidence for each claim and the limits of
the argument stated rather than left implied. The realistic harm here is not
a memory-safety exploit in aforbid(unsafe_code)crate with no dependencies
and no I/O; it is a wrong instruction written into firmware. -
GOVERNANCE.md,CODE_OF_CONDUCT.md,ROADMAP.md— who decides what,
what happens to the project if the maintainer becomes unavailable, the
Contributor Covenant, and where the project is going.GOVERNANCE.mdis
honest that this is a single-maintainer project rather than describing a
committee that does not exist. -
CONTRIBUTING.mdgained coding standards, a testing policy and a DCO
section. The standards were already enforced by CI; they were not written
down anywhere a contributor would find them. The testing policy states
red-before-green as a requirement and says why a test that cannot fail is
worse than no test — both failure modes happened in this project and are in
the 0.10.0 entry below. -
Signed releases. Every release now carries a SLSA build-provenance
attestation and a keyless cosign signature over the exact.cratepublished
to crates.io, attached as release assets and verified inside the workflow
that produces them. crates.io holds the bytes but publishes no signature over
them; consumers of this crate write its output into firmware, so "are these
the bytes the maintainer built?" is a question with a device on the end of
it. Verify withgh attestation verify thumb-asm-0.10.1.crate --repo MattJackson/thumb-asm, orcosign verify-blob --bundleagainst the bundle
asset. -
A
yankdispatch input on the release workflow. Trusted Publishing mints
a token scoped to publishing, and crates.io refuses it for a yank, so that
path takes a separately scoped token and says so rather than failing with an
authentication error that looks like a misconfiguration.
Fixed
CODE_OF_CONDUCT.mdis declared CC BY 4.0, not MIT. It is the
Contributor Covenant reproduced verbatim — someone else's text, under its own
licence. Labelling it MIT with this project's copyright would have been the
same mistakeLICENSES/LicenseRef-Arm-Documentation.txtexists to avoid for
the Arm manuals.
v0.10.0
0.1.0 was a 676-line position-independent assembler and patch-site finder with
26 instruction encodings. 0.10.0 is roughly twenty thousand lines: a decoder
and encoder for essentially the whole Thumb and Thumb-2 instruction set, an
instruction relocator built on it, and a trampoline installer built on that.
The crate went from emitting Thumb to reading it, which is what makes
patching over live code possible rather than only over a known prologue.
Three things that shipped in 0.1.0 break. They are listed first, because they
are the only reason this is not a drop-in upgrade.
Breaking changes
-
DetourError::Installhas been removed. The variant named a failure whose
precondition set is empty:detour's planning phase already proves the site is
in bounds, that the hook branch encodes, and — viaStubOverlapsSite— that
writing the stub cannot touch the site's four bytes. What remained was
install_branch's read-back, and a write to a&mut [u8]followed by a read
cannot disagree under Rust's memory model. The commit is now two infallible
stores and the read-back survives as adebug_assert_eq!post-condition, which
makes the code match what the module's Atomicity section already claimed. -
find_free_spacetakes a requiredalignparameter. The signature is now
find_free_space(image, len, align, start). Alignment has to be accounted for
during the scan, not by rounding up a run that was already found: rounding
the start up moves the start without moving the end, so a run that was exactly
long enough stops being long enough and the caller gets an offset whose tail
overlaps live bytes. Pass4for anything destined forAsm::finish, whose
literal-pool offsets are computed againstAlign(PC, 4); pass1for raw
data, which is the pre-0.10 behaviour. Panics ifalignis 0. -
Needle::FreeRunis a struct variant.Needle::FreeRun(len)is now
Needle::FreeRun { len, align }, for the same reason. Anymatchover
Needlehas to be updated. -
Asm::mov_regno longer writes the condition flags. See Fixed below for
what it used to emit and why that was wrong. Callers that wanted the old
flag-setting behaviour must switch to the newAsm::movs_reg; callers that
wanted a register move need no change and were previously getting a silently
different instruction.
One further shape change affects nobody on crates.io but does affect anyone
tracking dev: isa::Mem stores its offset as an unsigned magnitude plus a
separate add: bool — the architecture's U bit — rather than as a signed
i32, and gained an align: u16 field for Advanced SIMD's [rn:64]
qualifier. AddrMode gained a fourth variant, PostIncrement, for the
[rn]! form of the element and structure transfers. Mem::displacement()
returns the signed byte count for consumers that only want the effective
address.
Added
isa — the decoder, the encoder and the instruction vocabulary
isa::Decoder— anIterator<Item = Insn>that walks a Thumb stream from
a known start and tracksITSTATE. The 1–4 instructions after anIT
carry no condition in their own encoding, so a decoder that ignoresIT
reports them as unconditional — silently, and in the one place where being
wrong changes control flow. Instructions decoded inside an IT block come back
withInsn::condalready filled in.Decoder::atdecodes from an offset that
is not the address;.thumbee(true)selects ThumbEE state;pos,it_state
andskipare there to resynchronise past an undefined encoding.isa::decode_at,decode_at_with,decode_halfwords— decode one
instruction, from an image or straight from a halfword pair.
isa::insn_lenis the whole of Thumb's length rule:hw1[15:11]decides
and nothing else is consulted (ARM DDI 0403E.e A5.1).isa::encode/isa::encode_bytes— the inverse. Dispatch is verified,
not trusted: a mnemonic does not identify an encoding group —addlives in
five of them — soencodeoffers the instruction to each group in turn and
decodes every candidate again, comparing it against the instruction asked
for, before returning it. A mismatch is discarded and the next group gets a
turn. With a bare fallback chain the whole thing would only be as correct as
its least strict member, and a group accepting a neighbour's instruction would
emit the wrong encoding while every module's own tests stayed green.isa::disassemble—countinstructions from an offset as UAL text.isa::insn— the shared vocabulary every group module speaks:Insn
(mnemonic,encoding,addr,width,cond,sets_flags,
explicit_width,operands) withis_branch,is_call,writes_pc,
branch_targetandlen;Operand,Operands(a fixed inline array,
MAX_OPERANDS == 6, so decoding allocates nothing),Mem,AddrMode,Reg,
FpReg,Shift,ShiftKind,ShiftAmountandWidth.Insn,Operand,
RegandWidthare re-exported at the crate root.- Nineteen group modules, one per numbered sub-table of Arm's architecture
reference manual, so a review is one section ofspec/THUMB-ISA.mdbeside one
table of Arm's beside one file of the crate's: the six 16-bit groups of A5.2,
the twelve 32-bit groups of A5.3 (including the coprocessor, floating-point
and Advanced SIMD space), and ThumbEE's re-assigned 16-bit map from
DDI 0406 A9.2.1. - Coverage, counted rather than asserted. Thumb's length rule partitions
every bit pattern a Thumb stream can present into 59,392 single halfwords and
402,653,184(hw1, hw2)pairs, and both are small enough to enumerate, so
spec/THUMB-ISA.md§4 states coverage as an exhaustive count of all
402,712,576 of them rather than as an adjective. 58,233 of the 59,392
16-bit halfwords decode — 98.05% — with the 1,159 exceptions named one at a
time rather than left as a remainder, and 3,840 of ThumbEE's 4,096
re-assigned halfwords. Over half of the wide space decodes; §4.2 has the
module-by-module table, whose rows partition the whole space so the total is
a sum rather than an estimate, together with the distinct-mnemonic and
(mnemonic, encoding)counts. §4.3 explains why the wide-space ratio is not
a coverage grade: most of the 32-bit space is UNDEFINED by construction —
Table A5-9 leaves wholeop2rows unallocated,t32_dp_regrejects fifteen
sixteenths of its space before decoding anything — and a decoder scoring
higher there would be wrong. - One refusal policy, stated once (§4.4):
decodereturnsNoneonly for
an encoding the table does not allocate, for a should-be-zero or should-be-one
bit holding the wrong value —Insnhas nowhere to put it, so decoding would
discard information and re-encode to a different pattern — and for an
UNPREDICTABLE encoding with no representable UAL. The converse is applied just
as uniformly: an UNPREDICTABLE choice of operands is decoded, because
pop.w {lr, pc}is exactly the malformed code a reverse-engineer is hunting
for and refusing it would hide it.
relocate — moving one instruction to a new address
relocate(insn, to),relocate_with(insn, to, widen)and
relocate_bytes— re-site a decoded instruction so it still means the
same thing somewhere else. Thumb has three ways for behaviour to depend on an
instruction's own address: a direct branch's displacement, a pc-relative
literal access based onAlign(PC, 4), and the handful of instructions that
readpcas a value. The decoder has already done the hard half, because an
Operand::Targetis the resolved absolute address, so relocation never
redoes pc arithmetic — it holds the target still and asks whether the new
displacement fits.- The case worth knowing:
Align(PC, 4)does not move linearly. Moving an
instruction two bytes changes a literal displacement by either zero or four,
never by two, so the temptingnew = old - (to - from)is wrong at every
second halfword and wrong in a way that still assembles. Widen::{Never, IfNeeded}— whether a narrow direct branch may be
re-encoded wide when the narrow displacement no longer reaches.relocate
never widens, because widening changes the instruction's length and a caller
laying out a fixed buffer has to be told; the widening form is asked for by
name. Only direct branches widen: a narrowADRorLDR (literal)is refused
rather than widened, because ±4095 is the same "cannot reach a pool from free
space" class as ±1020.RelocateError— eight variants, each naming the instruction and both
addresses, with a stablereason()string, plusmnemonic(),from(),
to()andis_address_dependent(), which is what tells a caller whether
retrying at a different address could possibly help.
detour — the headline verb
tramp(image, site, hook)anddetour(image, site, hook, opts)—
decode the instructions a four-byte hook branch would displace, relocate them
into a stub, branch back, and install the hook. This is the thing that cannot
be written without a decoder, because patching four bytes over an arbitrary
address is four ways wrong and every one of them is silent: it cuts an
instruction in half; it moves an instruction out from under itsIT, so a
conditional instruction runs unconditionally in the stub; it relocates a
pc-relative instruction as a byte copy; and it half-applies.- Refusals are specific and atomic.
DetourErrorhas fifteen variants, each
with a stablereason()—"splits-it-block","site-not-aligned",
"site-in-it-block","no-free-space","site-unreachable",
"hook-unreachable","resume-unreachable","relocate"(wrapping the
RelocateErrorthat says which instruction could not be moved), and the rest.
On any error the image is byte-for...