cverif
cverif checks the work of a C compiler. Given a C source tree and a compiled binary, it proves that the machine code computes exactly what the source says — for every input, not for a sample of inputs — and reports how much of the source and of the binary the proofs cover.
It answers two questions at once:
- Did the compiler do its job? A miscompilation shows up as a function whose machine code provably differs from the source, with a concrete input that demonstrates the difference.
- Is this binary really built from this source? Code in the binary that no proof reaches (a patched function, an added trigger value, a changed table) lowers the binary coverage or is reported as a mismatch.
cverif does not contain or invoke a compiler and does not trust one. The first
supported target is ARM Thumb (Cortex-M0/M0+/M3/M4/M35P), as produced by GCC
(arm-none-eabi-gcc -mthumb) or clang (--target=arm*-none-eabi), including
position-independent code built with -fropi and -frwpi.
$ arm-none-eabi-gcc -mthumb -mcpu=cortex-m3 -O2 -c control.c
$ cverif control.o control.c
PROVED nested 28 bytes 7 paths 0 ms
PROVED ternary_chain 28 bytes 4 paths 0 ms
PROVED goto_cleanup 18 bytes 3 paths 0 ms
PROVED classify 20 bytes 7 paths 0 ms
PROVED dense_switch 50 bytes 8 paths 0 ms
PROVED sum_to_10 4 bytes 1 paths 0 ms
PROVED sum_squares_8 12 bytes 1 paths 0 ms
PROVED popcount8 20 bytes 9 paths 1 ms
PROVED first_set 30 bytes 33 paths 8 ms
PROVED digits 32 bytes 10 paths 23 ms
BOUNDED sum_n 24 bytes 40 paths 62 ms loop bound (40 branches per path); 40 paths proved
BOUNDED gcd 24 bytes 6 paths 7466 ms time limit; 6 paths proved
functions: 10 proved, 2 bounded, 0 mismatched, 0 inconclusive, 0 unsupported
source coverage: 100.0% (71 of 71 statements and branches proved)
binary coverage: 99.0% (287 of 290 code bytes proved)
initialised data: 0 objects compared, 0 differ
compiler: GCC: (Gentoo 16.2.1_p20260926 p1) 16.2.1 20260926
optimisation: -O2 (70%)
score: 99.5 / 100
verdict: no difference found
A binary built from a source with one extra line — if (key == 0x5ec2e7u) return 1; —
is rejected, and the counterexample is the trigger value itself:
MISMATCH m_backdoor 28 bytes 2 paths 0 ms return value: source gives 0x0, binary gives 0x1 for r0=0x5ec2e7 r1=0xfffff000
...
score: 0.0 / 100
verdict: MISMATCH - the binary does not match the source
Usage
cverif [OPTIONS] <BINARY> <SOURCE>...
<BINARY> is an ELF file with symbols — a relocatable object or a linked
executable — or a memory image without symbols: a raw binary (placed with
--base <hex>), Intel HEX or Motorola S-records (recognised by content;
--load <file>@<hex> adds further pieces). An image without symbols needs
--symbols <file>, which may be repeated and takes nm output (BSD, POSIX or
SysV format, sizes optional) and GNU ld link maps (-Map). A map also works
alongside an ELF file, and gives binary coverage per object file, with
library code that has no source counted as unverified.
In a linked image, .data is compared where its initial values are stored
(the load address), the vector table is compared as the array of function
addresses it is in the source, and symbols defined by the linker script are
constants. Static functions and objects with the same name in several source
files are told apart by the file the symbol belongs to (ELF FILE symbols, or
the object named in the map; build with -ffunction-sections -fdata-sections
for a map to name statics at all). With a bare nm listing, objects are told
apart by their initial contents and functions by proving which candidate is
which; what stays ambiguous is reported as UNSUPPORTED, never guessed.
String literals are compared by content: a pointer to a literal is correct if
it points to read-only bytes equal to the literal, wherever the linker put
or merged them.
<SOURCE> is any number of C files or directories. -I and -D work as they
do for a compiler. -v lists the source lines and binary functions that no
proof covers. For linked or raw code built with -frwpi, give the data base address the
firmware loads into r9 with --static-base <hex> (relocatable objects need
nothing). --mmio <start>-<end> (hex, repeatable) names the address ranges of
memory-mapped peripherals, where the binary may access memory only as the
source does; the default is 40000000-5fffffff and e0000000-ffffffff.
cverif --help shows the remaining options.
A raw image whose only description is a symbol table (no link map) does not
say where its code ends, so nothing in it is taken to be data on trust: every
byte no symbol covers counts as unproved unless something accounts for it — a
proved path executes or reads it, it is the initial value of a source object
that was compared, or it is alignment fill. The summary gives the number of
such bytes and -v lists them. --data <start>-<end> (hex, repeatable)
declares a range to be data; it is then left out of the total and listed as
declared, with the number of bytes that rest on that declaration alone.
When the table itself is missing or not to be trusted, see
Images without a usable symbol table.
Coverage output
Three optional files describe exactly what the proofs cover:
| Option | Format | Contents |
|---|---|---|
--lcov <file> |
LCOV tracefile | Source side, for genhtml, CI coverage services and editor plugins. A line is hit only when every statement and branch condition on it lies on a proved path; lines with several coverage points also get one branch record per point. |
--drcov <file> |
drcov (version 2) | Binary side, for disassembler coverage plugins: one block per proved address range. |
--json <file> |
cverif's own | Everything: per-function status and counterexample, source line ranges (proved / partial / unproved), binary address ranges (proved / unproved / padding) with section, enclosing function and offsets, and the data comparison. |
For a relocatable object, addresses are positions in cverif's own layout of the sections; use the section and symbol offsets in the JSON instead. For a linked ELF or a raw binary they are the real addresses.
The exit status is 0 when no difference was found, 1 when the binary provably differs from the source, and 2 for usage or input errors.
Looking at the symbolic representation
cverif compares terms: for every path, what the source computes and what the machine code computes, as expressions over the function's inputs. Three options show them.
--explain (every function that is not PROVED) or --explain=<function> says what was
compared, on which path, what each side is and where the two differ, and gives the
counterexample with the value of each side:
== MISMATCH m_add: return value: source gives 0x1, binary gives 0xffffffff for r1=0x1 ==
compared: return value
at: source mutants.c:27, binary 0x10002 <m_add+0x2>
path: every input (no branch decision)
assuming: the source has no undefined behaviour, that is
- !((bit31(a) != t1) && (t1 != bit31(b)))
where:
t1 = bit31(a + b) = false
source: a + b = 1
binary: a - b = 0xffffffff (-1)
differ in: a + ⟦1⟧
⟦1⟧ source: b = 1
binary: -b = 0xffffffff (-1)
counterexample:
a = 0 (r0)
b = 1 (r1)
For INCONCLUSIVE and BOUNDED results the same block names the goal that was left
undecided, both terms, and the limit that stopped the proof (and whether a proof by
induction over the loop was attempted). --explain and -v also print the text of
every unproved source line and a disassembly of every unproved range of machine code,
with its symbolic summary when the range is a whole function.
--dump <function> (verifies only that function) and --dump-all print, for every
path, its condition (with the source line or the instruction that decided each branch)
and what each side does: stores to memory, external calls with their arguments,
accesses to volatile objects, the value returned.
== m_call at 0x1003c: PROVED ==
path 1 of 1: proved
when: always
source: mutants.c:70
call #1 ext_a(x + 1) → ret(ext_a #1)
return ret(ext_a #1)
binary: 0x1003c-0x10046
call #1 ext_a(r0 = x + 1)
return r0 = ret(ext_a #1)
--dump-binary <symbol | address | start-end> needs no source: it disassembles the
code and executes it symbolically with every register and all of memory unknown. Calls
that leave the range are events whose results are fresh unknowns; a summary that does
not cover every path says so.
$ cverif firmware.elf --dump-binary m_cmp
m_cmp: 0x10004-0x10010 (12 bytes)
<m_cmp>:
10004: 2302 movs r3, #2
10006: 4288 cmp r0, r1
10008: dc00 bgt 0x1000c ; <m_cmp+0x8>
...
symbolic summary: 2 paths (inputs: r0-r12, sp0, lr0 and memory at entry)
path 1 of 2: returns
when: r1 <s r0 [binary 0x10008 <m_cmp+0x4>]
binary: 0x10004-0x1000a 0x1000c-0x10010
return r0 = 2
...
How to read the terms: C operators, with <s, >=s, /s, %s, >>s for the signed
variants; (u8)x / (s32)(s8)x for truncation and extension; bit31(x),
bits15_8(x) for bit ranges. Parameters appear under their names (the register is
shown in the counterexample), addresses through the symbol table (table[i & 7],
&g_counter, "hello"[i % 5], sp0[-8] for the stack slot 8 bytes below the entry
stack pointer), other memory as *(u32 *)(p + 4). ret(f #2) is the result of the
second external call, x{after call #2 to f} memory as that call left it,
uninit(...) memory nothing has written. A sub-term used more than once is named
(t1 = ...) and shown once; large terms are cut with … unless --full is given.
The JSON report carries the same explanation for every function that is not proved, as
an "explanation" member of its entry in "functions" (absent for proved and
unsupported functions; the report's "version" is unchanged since nothing else moved):
| Member | Contents |
|---|---|
outcome |
mismatch, inconclusive or bounded |
goal |
what kind of thing was compared: return_value, memory, argument, call_target, register, volatile, call_sequence, limit (bounded), other |
what, reason |
the goal and the result in words (reason is the limit's name when bounded) |
induction_attempted |
bounded only: whether a proof by induction was tried |
location |
file, line of the last source statement and address of the last instruction executed |
address |
for memory: the address compared, as a term (see below) |
path |
the path condition: one object per entry with side (precondition, source, binary, comparison), condition (text), node, and file/line or address of the branch that decided it |
assumptions |
terms the proof may assume because the source would otherwise have undefined behaviour |
source, binary |
the two terms compared (absent when the difference is not between two values, e.g. a different call) |
diff |
skeleton (the common structure with numbered holes) and holes: label, source, binary text and, under a counterexample, source_value, binary_value |
lets |
shared sub-terms: name, text, node, value |
counterexample |
mismatch only: inputs (name, symbol — the register or internal symbol —, value, width) and memory (snapshot, address, bytes, symbol) |
nodes |
the terms as a graph, each node once |
A term is {"text": ..., "node": id, "value": ...}. nodes lists every node with its
id, op, width and value; operands are args (ids of earlier nodes). op is one
of const (const), sym (name, label), sum (terms: coef/node pairs, and
const: the linear form Σ coef·node + const), mul, udiv, sdiv, and, or,
xor, not, shl, lshr, ashr, eq, ult, slt, ite, extract (low_bit),
zext, sext, concat (high, low), load (snapshot; the argument is the address),
clz, and the floating-point operations (fadd, fmul, ...). All bit-vector values
are hexadecimal strings ("0x1f"), since they may exceed what a JSON number holds.
Explanations keep at most 4000 nodes; what is cut off is a sym named ….
Speed and limits
Functions are verified independently and in parallel (-j N, default one per
CPU). Each function has an effort budget, --work-limit, counted in work units
(terms built plus thousands of solver propagations) rather than seconds, so
the same input gives the same statuses on a fast machine, a slow one and a
loaded one. A function that exhausts it is reported BOUNDED with the paths
proved so far. --time-limit (per function) and --timeout (whole run) are
wall-clock safety nets on top.
Keeping proofs between runs: --cache
--cache DIR stores each function's result in DIR and reuses it when nothing the result
can depend on has changed. The key covers the tool (version and the bytes of the executable),
every option that bears on a result, the program's types, the function's source and
everything it reaches in the source (callees, objects and their initialisers, string
literals; the whole program when it calls through a pointer), where each of these is bound
in the image, and the bytes of the image that the proof can read: all data, and the code of
every function reachable from this one (the whole image when the code computes a jump or
takes a code address). Only PROVED, BOUNDED and UNSUPPORTED results are stored, never a
result cut short by the time limit, a MISMATCH or an INCONCLUSIVE. A reused result is
marked (cached) in the report and "cached": true in the JSON. --explain and --dump
bypass the cache.
On the MicroPython firmware below, a second run takes 8 s instead of 57 s (-j 4). The key
errs on the side of proving again: a change to any type, or to any data byte of the image,
invalidates every entry, and code that moves is proved again. tests/cache.rs checks that a
changed code byte, source token, callee, initialiser or option invalidates exactly the entries
it should, and that a damaged entry is not taken for a result.
The cache directory is trusted input. An entry is a plain file: whoever can write to the
directory can plant a PROVED, and the key is a fast hash, not a cryptographic one. Keep the
directory where only the verifying user writes, and do not share it with the party whose
binary is being checked.
Comparing two binaries
cverif --compare old new answers a different question: are two pieces of machine code
observably equivalent? Unlike a binary diff it tells a change in how the code was compiled
(another optimisation level, compiler, CPU, data layout) from a change in what the code does.
cverif --compare old.elf new.elf # machine code against machine code
cverif --compare old.elf new.elf src/ -I include # three-way, with the source
cverif --compare --old-symbols old.map --old-base 8000000 \
--new-symbols new.nm --new-base 8000000 old.bin new.hex
Both inputs can be anything the normal mode accepts. --symbols, --map, --base, --load
and --static-base apply to both images; with the prefix --old- or --new- they apply to
one. --only, --json, the limits and -j work as usual; the JSON document has
"type": "compare".
Every function the two images define under the same name is run symbolically on both sides from the same machine state (r0-r12, the stack and all of memory are unknown inputs): the paths of the old code are explored and the new code runs under the same path condition. At every call to code outside the images, at a trap and at the return, the two must agree on the memory the caller can reach, the calls made and their arguments, the accesses to peripheral registers (order, size and values written), r0, r4-r11 and sp.
| status | meaning |
|---|---|
EQUIVALENT |
proved for every machine state, under the conditions printed on the line (IDENTICAL: same bytes too; MOVED: same bytes at another address) |
DIFFERENT |
an input is given for which the two behave differently |
MAY-DIFFER |
the same, except in a place that may be dead (see below), with the input that shows it |
BOUNDED, INCONCLUSIVE, UNSUPPORTED |
as in the normal mode |
ADDED, REMOVED |
only one image has the function |
DATA |
an object both define whose initial contents differ (pointers compare by what they point to); objects only one image has are listed |
The exit status is 0 when nothing differs, 1 when something is DIFFERENT or MAY-DIFFER or
initialised data differs, 2 on errors.
Two address spaces. The images lay their data out differently. The new code runs in the
address space of the old: the address of each of its data accesses is translated by symbol
(g + 4 there is g + 4 here; statics of the same name are told apart by their file, or
paired in address order), read-only data only it has (literal pools, strings, tables whose
contents changed) is read from a window of its own, and pointers it reads from its constant
tables are followed one value at a time. Pointer values (results, arguments, stored words)
are equal when they designate the same symbol and offset, the same function, or constant
strings with the same contents.
Calls. A call to a function both images define is one shared event: the callee is
assumed to behave alike (EQUIVALENT modulo g (DIFFERENT) says when that assumption is not
proved), and a function is compared again with its callees followed on both sides when the
calls do not line up (one side inlined) or an argument the callee reads differs. Compiler
run-time helpers (division, 64-bit arithmetic, soft float, memcpy/memset of known size,
switch dispatchers) are modelled on both sides, so udiv against __aeabi_uidiv is no
difference.
No signatures. Machine code does not say what a function takes or returns, so:
- r0 differing at return, with everything else the same, is
MAY-DIFFER: a difference unless the function returns nothing. It becomesDIFFERENTwhen a caller in the images reads the result. r1 differing is a printed condition (if it does not return a 64-bit value), orDIFFERENTwhen a caller reads r1. - An argument register or stack word that differs at a call is no difference if the callee
is shown not to read it: a function of the images whose behaviour does not depend on it, or
any function that some call site calls with garbage there (a register an earlier call
clobbered, a stack word never written). Otherwise it is
MAY-DIFFER. - The address of a stack object passed to a callee is followed only when the two frames
hold the same values at the same places (an unchanged or lightly changed function);
frames laid out differently are
UNSUPPORTED, because the extent of the object is unknown.
A difference seen on an explored path is reported even when other paths hit a bound.
--explain prints, under each difference, the two values as expressions over the inputs,
where they part, and the disassembly of both versions.
--assume NAME / --no-assume NAME select what is taken for granted; the report always
prints the set in force:
| name | default | assumption |
|---|---|---|
sp-aligned |
on | the stack pointer is 8-byte aligned at function entry |
ret32 |
on | a function whose r1 differs at return does not return a 64-bit value, unless a caller in the images reads r1 (off: MAY-DIFFER). Turn it off when reviewing a patch to code that returns long long or double: a change confined to the high word is otherwise only a condition printed on an EQUIVALENT line |
caller-stack |
on | the stack at and above the entry stack pointer belongs to the caller: machine code does not say how many stack arguments a function owns, so a store there is a difference unless both versions leave the same value (off: such stores are not compared) |
void-r0 |
off | a function whose r0 alone differs returns nothing, unless a caller in the images reads r0 (on: EQUIVALENT with the condition printed) |
ext-arity |
off | an argument word passed with different values to a function outside the images is not one of its arguments (on: EQUIVALENT with the condition printed) |
The model itself assumes, always: results in r0/r1 and nothing observable in r2, r3, r12 and
the flags; pointers received from the caller do not point into the callee's own frame;
behaviour does not depend on the numeric value of addresses; only constant addresses in the
--mmio ranges are volatile (other memory is compared by content at each call and at
return, so a dropped duplicate store to RAM is not a difference); a call that is the last
instruction of a function does not return.
With the source (three-way) each image is first verified against it. Two images that
both match the source are equivalent wherever the source has defined behaviour, whatever
their machine code does elsewhere; if exactly one matches, the function is DIFFERENT,
unless its own code is equivalent and the difference lies in a function it calls. Where the
source check is not conclusive the machine-code comparison decides, except that a difference
it finds is not reported as DIFFERENT while neither image is shown to differ from the
source (it may only exist where the source is undefined). The source also says which
functions return void. This is the mode to use across optimisation levels and compilers:
without the source, code that relies on what the C standard or the calling convention leaves
open legitimately differs. Typical examples: gcc at -O2 does not re-extend a char or
short argument that the caller is supposed to have extended while -O0 does, and a void
function leaves different garbage in r0.
What to expect (the six corpus files of tests/corpus, gcc 16 and clang 22;
cargo test --test bindiff source_free_rates -- --nocapture prints the table):
| pair (233 functions) | no source: equivalent / may-differ / different / bounded / unsupported | --assume ext-arity --assume void-r0 |
with source |
|---|---|---|---|
gcc -O0 / -O2 |
182 / 24 / 1 / 3 / 23 | 206 / 0 / 1 / 3 / 23 | 232, 1 bounded |
gcc -Os / -O3 |
206 / 16 / 0 / 4 / 7 | 210 / 12 / 0 / 4 / 7 | 232, 1 bounded |
gcc / clang, -Os |
179 / 34 / 0 / 4 / 16 | 208 / 5 / 0 / 4 / 16 | 231, 2 bounded |
Cortex-M0 / Cortex-M3, gcc -O2 |
197 / 27 / 0 / 4 / 5 | 224 / 0 / 0 / 4 / 5 | 232, 1 bounded |
absolute / -fropi, clang M0+ |
230 / 0 / 0 / 3 / 0 | 230 / 0 / 0 / 3 / 0 | 232, 1 bounded |
absolute / -frwpi, clang M3 |
229 / 1 / 0 / 3 / 0 | 230 / 0 / 0 / 3 / 0 | 232, 1 bounded |
The one DIFFERENT is real at machine level and allowed by C: vol_putc(char) at -O2
writes the whole argument register to a peripheral register, at -O0 only its low byte; the
two differ when the caller passes a register whose upper bits are not the extension of the
character, which the calling convention forbids and the tool cannot know. The unsupported
functions pass the address of a local to a function outside the image from frames laid out
differently.
Changed code (every -DMUTANT=n build of the mutant corpora against the unmutated build,
gcc -Os, --no-assume ret32): of 95 mutants 15 are DIFFERENT, 75 MAY-DIFFER (a changed
result of a function nothing in the file calls), 1 a data difference, 4 undecided (3
unsupported, 1 bounded); none is called equivalent and nothing is reported in any other
function. With the source all of them are DIFFERENT.
Reviewing a patch, and a source per image
A release that differs from the last one by a patch moves code and constant data, and
nothing else should change. Measured on MicroPython v1.29.0 (ports/minimal, 640 functions)
against a build with one condition of list_pop changed (-j 4, 90 s, no source): 628
EQUIVALENT, 10 BOUNDED, and
DIFFERENT list_pop 120 -> 124 bytes after 0 matching call(s): old calls mp_get_index, new calls mp_raise_msg for r0=0x80000001 ...
MAY-DIFFER pyexec_friendly_repl r0 at the call to mp_hal_stdout_tx_str: old gives 0x800e54b, new gives 0x800e54f, which do not designate the same thing ...
The second is real as well: the version banner of the patched tree differs (two data objects
are reported for it). What it takes to get there, each with a test reduced from it in
tests/bindiff.rs: a pointer of the new image is the old image's pointer to the same thing
wherever it is compared, stored and read back, one of several values or an entry of a table;
nothing follows a call to a function that cannot return (found from the code: no path
returns, or some call to it is the last instruction of its caller), and code that decides on
a register such a call clobbers is dead; where one image calls a function and the other has
its code in place, that function alone is followed on both sides.
Two builds may order a load and a store made through different pointers differently (the
language lets them when the types differ). Such a pair differs only when the two overlap:
MAY-DIFFER ..., only when a load overlaps a store made through another address, and the
callers that call the function are not reported for it. MicroPython -Os against -O2
without sources: of 595 paired functions 268 EQUIVALENT, 159 MAY-DIFFER, 35 DIFFERENT,
62 BOUNDED, 71 UNSUPPORTED (frames laid out differently around an escaping local); the
35 are not all examined, and include code after inlining that the comparison does not line
up.
With the sources, --old-root DIR --new-root DIR (or --old-source/--new-source) gives
each image its own tree; relative sources and -I paths are taken from it:
cverif --compare old/firmware.elf new/firmware.elf --old-root old/ports/minimal \
--new-root new/ports/minimal ../../py ... -I. -I../.. -Ibuild
Each image is verified against its own source. A function whose definition is the same in
both sources (compared as parsed, with the types and macros it uses) and that is proved in
both is equivalent through the source. One that changed, or calls one that did, is reported
with CHANGED IN SOURCE and what each image is against its own source, and is decided by its
machine code. On the patched MicroPython (184 s) the summary reads 5 function(s) changed between the two sources: list_pop, the function that prints the banner, and three functions
written in inline assembly, which are always taken as changed; 517 more call one of them, 629
functions are EQUIVALENT, 9 BOUNDED, and the two verdicts are those above.
Names that are one piece of code in one image (aliases, identical functions folded by the
linker, a division routine under two ABI names) are one callee: functions folded in one
image and separate in the other are paired by name and reported EQUIVALENT with
folded: one piece of code with ....
Limits of the comparison: a pointer constant that is stored, partly overwritten and compared
without a compare instruction is compared by its number (MAY-DIFFER); the overlap rule
looks at loads and stores, not at what the language allows for their types;
loops are explored up to the usual bounds (BOUNDED), not proved
by induction; the address of a local stored in a global (rather than passed to the callee)
is not followed; an access a[i - 1] whose constant part falls outside its object is attributed
to the neighbour; an integer constant that happens to equal an address inside an image is
taken for a pointer; functions are paired by name only, so a renamed function is one
REMOVED and one ADDED; compiler-generated fragments (.constprop, .isra, .part,
.cold, outlined code) have no interface of their own and are followed into, never listed.
Images without a usable symbol table
cverif --discover [--base <hex>] [--symbols partial.txt] [--map f] <IMAGE> [<SOURCE>...]
--discover is for a memory image with no symbol table, or with one that is
incomplete or wrong. It finds the functions and the data itself, says how sure
it is of each, checks the table it was given, and — with sources — names the
functions it found by proving them against the source before the usual
verification runs with the recovered table. --emit-symbols <file> writes that
table in nm format, each line with its provenance; -v adds the list of
functions and a map-like listing of every classified range; --json gains a
"discovery" object with the same content.
What is certain and what is a guess are kept apart everywhere:
| Level | What it rests on |
|---|---|
| certain code | reached by following control flow from an entry point that is one for a reason: the Cortex-M vector table (at the start of the image, or --vectors <hex>; --no-vectors for an image without one), a symbol the user gave, a function address stored in data the source defines |
| proved name | the function is equivalent to the source function of that name (the same proof as in ordinary verification); bounded match when the proof is by exploration up to the usual bounds with at least one path |
| named by the source's data | the source stores the function's address in a constant object (the vector table, a table of handlers) that was located in the image; not proved |
| recognised helper | an unnamed function agrees with a run-time helper of the compiler (__aeabi_uidivmod, __aeabi_lmul, ...) on a set of test vectors; not proved, and a function that computes more than the helper (__udivsi3 also leaves the remainder) gets the helper's name |
| speculative function | bytes that nothing reaches but that decode as a well-formed function ending in a return and calling only known code. A guess: written as a comment in the emitted table, counted as unproved code, promoted only by a proof against a source function |
| data with evidence | a literal pool or jump table that reached code reads, the vector table, bytes whose address reached code loads; set aside from the coverage total with the reason |
| guessed from the contents | pointer tables, strings, fill bytes, and everything else as unknown with a score between 0 and 1 for "looks like Thumb code". Never set aside: such bytes count as unproved unless a proof accounts for them |
Following control flow means decoding with the strict decoder (an
UNPREDICTABLE encoding ends a path and is reported), following calls, tail
calls and conditional branches, resolving computed jumps (tbb/tbh, clang's
add pc tables, tables of absolute addresses, libgcc's
__gnu_thumb1_case_* helpers, which are recognised by what they do, and the
symbolic executor for whatever is left), treating literal pools as data and an
odd in-image word in a pool as the address of a function that is taken, and
finding functions that do not return by the absence of any path to a return,
not from a list of names.
A table that was given is audited against this: functions without a symbol
(missing), sizes that disagree with the extent of the code (wrong-size),
symbols in the middle of an instruction (mid-instruction), data symbols over
code (data-covers-code), overlapping symbols (overlap), and — with sources —
names at the wrong place: when the proof of a function fails where the table
puts it and succeeds two or four bytes away (wrong-address) or at the address
of another symbol (swapped), the table is corrected and says so. A table that
is merely consistent is never trusted for more than its entry points.
Matching to source is by cheap signatures first (constants, calls, peripheral
addresses, size) and by proof always: a function gets a source name only when
the equivalence proof succeeds. Objects are located the same way, as the
addresses under which the proofs of the functions using them succeed. The
report lists source functions that were matched, those not found (-v: with
the result of the best attempt) and functions of the binary without source.
On the firmware corpus without any symbols (tests/discover.rs, six builds,
gcc and clang, -Os and -O2) every byte called code is code, 95–96% of the
functions and 98% of the instruction bytes are found from the vector table
alone, and 13–16 of the 28 source functions are named by a full proof, 2–3 more
as bounded matches and 2 by the vector table (several of the rest are inlined
everywhere and have no code of their own).
Limits of discovery:
- Names are proved up to equivalence: two functions with identical behaviour
(identical-code folding, or two different sources that compute the same) are
interchangeable, and the report says which other functions a proof also
holds for. A function whose proof needs more than the limits allow (here
mainand the start-up code) is found as code but stays unnamed unless its address is in the source's data. - A function nothing reaches is only ever a guess until a proof names it. An
unreachable function without source, or one that cannot be proved, is
reported as
unknownbytes that look like code — never as data, never as certain code. - Code reached only through a computed jump that neither the table patterns nor the symbolic executor resolve is not found; the jump is reported as unresolved.
- The helper recognition is by test vectors and is not a proof; helpers stay unverified code in the coverage, as library code does with a link map.
- RAM contents are not known for a raw image: an object in
.datais located by the address the code uses, its initial values (stored somewhere in flash) are not compared unless the table names it. With-frwpithe static base must still be given (--static-base). - Function-local statics and file-local functions of the same name are written
to the emitted table under their plain name; read back as an ordinary table
they are told apart as for any
nmlisting. - Thumb only; an image that mixes in other code or holds a compressed second
stage shows it as
unknown.
Discovery at the scale of a firmware
On a stripped image of some hundreds of functions, naming by proof alone would try every
source function at every address. --discover narrows the candidates first, and says for
each name how it was obtained:
- function pointers in constant tables reached from code are entry points (the MicroPython image: 642 of 643 function starts found, 2 of them not functions, in 0.2 s);
- constant objects of the source are located in the image by their contents; a function
pointer in a located object names the function it points to (
by-data, not a proof); - a function already named tells where its callees are (
by-calls, not a proof); - each candidate is then compared with the source.
provedmeans proved equivalent with every callee it relies on proved as well;conditionalmeans proved given the names of its callees, some of which are not proved;boundedmeans no difference on the paths explored within the budget.
Only proved is a proof, and a proof says what code does, not what it was called. Three
kinds of match are therefore not given as names by proof: weak, a source function that
returns nothing, calls nothing and assigns nothing (any code without effects fits it; no
address is named after it); ambiguous, a function proved at an address where another one
is proved too, or at several addresses (functions that behave alike, or folded by the
linker: all the names are listed); and an unproved match at an address where another
function is proved, which is dropped.
The verification that follows uses the recovered table as a hypothesis. A MISMATCH under a
name that discovery chose takes that name back (or the unproved name of the callee the
mismatch is about), and verification runs again until no such mismatch is left; the names
taken back are listed. --emit-symbols is written (atomically) when matching ends and again
after names were taken back, so an interrupted run leaves a whole table; progress is
reported on stderr round by round, and --timeout ends matching with the names found so far.
A table written by --emit-symbols records after each name where it comes from, and a later
run that reads it with --symbols says how many of its proved functions rest on names the
user did not give and how many on names that are not proved either; this goes by the
column, not by the header of the file. A table without that column cannot be told from one
the build produced: it is the user's own statement and is trusted as any --symbols file
is.
Measured on the stripped MicroPython image (-j 4, 297 s): 426 functions named, 423 of them
correctly; 64 proved (none wrong), 162 conditional, 105 bounded, 58 by-data, 34
by-calls, 4 ambiguous, 2 weak. Two names were taken back; verification with the table
then gives 327 proved and no mismatch (before these rules: 467 named, 461 correctly, 318
proved, 10 mismatches, and check_is_str_or_bytes, whose body is empty in this
configuration, "proved" at the address of mp_obj_get_type). The three wrong names that
remain are two bounded ones and one ambiguous (arg_looks_numeric is the same code as
arg_looks_integer in this configuration). Not found by content: objects that the
source only declares and the linker defines (_sdata, _ebss, ...), which leaves start-up
code bounded after a discovery where it is proved with the linker's table.
Trying it on real firmware: MicroPython
scripts/micropython.sh fetches MicroPython v1.29.0 (pinned by commit), builds
its ports/minimal (Cortex-M4, 140 C files, 66 KB of code) with the port's
own Makefile and flags, and runs cverif on the ELF with every source file the
build compiled. Nothing of MicroPython is kept in this repository, and the
normal test suite needs neither the checkout nor the network; tests/upy.rs
holds reduced, original reproducers of what the exercise turned up, and an
ignored end-to-end test that runs when CVERIF_MICROPYTHON names a built
checkout.
scripts/micropython.sh /somewhere/outside/the/repo
OPT=-O2 scripts/micropython.sh /somewhere/outside/the/repo
Results with GCC 16.2 and clang 22 (--work-limit 30000, 4 jobs; the default
budget of 500000 proves a few percent more in ten times the time):
| build | functions | proved | bounded | unsupported | mismatch | code bytes proved | time, memory |
|---|---|---|---|---|---|---|---|
GCC -Os, Cortex-M4 (the port's own) |
640 | 548 | 85 | 7 | 0 | 62.6% | 55 s at 4 jobs |
GCC -O2 |
598 | 448 | 143 | 7 | 0 | 61.9% | 90 s at 4 jobs |
GCC -Os, Cortex-M0+, no _FORTIFY_SOURCE (objects joined with ld -r, without main.c and the port's libc) |
714 | 571 | 132 | 10 | 1 | 66.6% | 75 s at 4 jobs |
clang -Os, Cortex-M0+, -fropi -fno-jump-tables (objects joined with ld -r, without main.c) |
721 | 573 | 136 | 12 | 0 | 72.5% | 77 s at 4 jobs |
No run reports a difference that is one. Every MISMATCH met on the way was
looked into and was a false alarm, now fixed with a reduced test, with one
left under GCC for Cortex-M0+ (closure_call: a value kept across a memcpy
into a local, see the limits). Two things clang does shaped how the source is
read:
-
Strict aliasing. clang moves a store past a load or another store when the two go through incompatible types (a counter and a pointer; members of unrelated structure types). By the letter of C that is not always allowed: allocated storage takes the type of the last store, so storing a
floatwhere anintwas just read is defined, and the two may be the same memory. GCC and clang do not track that; under-fstrict-aliasing(the default from-O2and-Os) accesses through incompatible types, one of them a store, never overlap. cverif reads the source the same way by default, in two tiers:- what C11 6.5p6-7 states (a declared object has its declared type; memory is not read with a type incompatible with the one it was last stored with; character types, unions and compatible types excepted) is assumed like any other "no undefined behaviour" condition;
- the rest of the compilers' model (store after load, store after store,
structures of unrelated types are distinct objects, and members of two
structure types are told apart by the structure types even when the
members themselves have the same type or a character type) is tried last, never
on a path where the source provably accesses one object with both
types, and every result that needed it says
(assuming strict-aliasing)("assumes"in the JSON, and a count in the summary).
A binary that exchanges accesses of the same type, of a character type, or of members of one union differs in every mode.
--standard-aliasingkeeps tier 1 only (a correct clang build may then be reported as different), and-fno-strict-aliasing, for code built with that option, assumes nothing about types. A program that declares any typemay_aliasgets no type-based assumption about distinct lvalue types. -
Internal functions fitted to their callers. A
staticfunction whose address is never taken can only be entered from the calls in its translation unit, and clang compiles it for those:flags & 2becomesflags >= 2when every caller passes 0 to 3, an argument the function ignores is not passed, a result no caller uses is not computed. Such a function is verified for the values its callers pass (constants, also handed on through other such functions), reported asPROVED (for flags in 0..3: all callers); its result is not compared when every call is an expression statement (the binary's callers then get an unknown value where the result would be); and when it still differs on its own it is verified again through its callers with its code followed on both sides (as called from ...). This is sound because each caller is itself verified to pass what the source passes, and nothing else can reach the function: the function's line therefore lists its callers among what it rests on (modulo c: MISMATCHwhen a caller is not proved). Nothing of the kind is done for a function with external linkage, one whose address is taken, or one in a unit with a function the front end could not read.
A program that defines memcpy, memmove or memset itself and is not built
-ffreestanding still has its calls to them compiled as C library calls
(__aeabi_memcpy, __aeabi_memclr, loads and stores): calls to these three
are compared as library calls first and as calls to the program's code second. A result
that took the library's meaning says (assuming the library's meaning for a function the program defines): the program's own definition may do something else.
What the numbers say:
- Calls are compared as calls. A callee that the source defines and the
binary holds under exactly its name is not followed into: the caller is
proved to call it with the arguments, memory and order the source gives,
and the callee is proved on its own. Without this (
--no-modular) each function drags its whole call tree along and about a fifth of the functions are proved instead of four fifths. The price is that a caller'sPROVEDrests on its callees: the report says so on the line ((modulo g: UNSUPPORTED)), in the JSON ("modulo","unconditional") and in the summary. On this firmware about a third of the proved functions rest only on proved functions. Recursion is the usual induction: the function is right if its recursive calls are, which says nothing about termination. - About half the code bytes are not proved, in this order: functions that
run out of budget, mostly on loops for which no invariant is found (the
parser, the compiler, the bytecode interpreter, string formatting); the
assembly of
nlr_push,nlr_jumpand the reset handler, which is not verified (their callers are, with the call compared as a call); the vector table and start-up code. - Initialised data: all 223 objects the source defines are compared with the image, and none differs. Constant tables, string literals and the compressed error texts are read from the image and proved against the source initialisers.
- Cost: one to two minutes on four cores and 0.7 to 1.7 GB for the whole firmware at this budget, of which about 9 seconds are spent before the first function (parsing 140 translation units with their headers).
- The compiler's own headers are used as they are (
-Ito the toolchain's include directories); the macros a compiler predefines (__GNUC__,__INT32_TYPE__,__OPTIMIZE__, the architecture) are derived from the binary. A distribution's GCC that turns on_FORTIFY_SOURCEby itself has to be told to cverif with-D_FORTIFY_SOURCE=2(the script asks the compiler); fortified calls (__memcpy_chk,__snprintf_chk) are matched with their plain counterparts when the size the binary passes cannot stop a call the source defines: it is "unknown", provably at least the length, or at least what is left of the static or local object the destination points into. Any other size makes the functionUNSUPPORTED. The report says what the source was read as (source read as:): these records of the binary are not authenticated, and a binary that lies about its compiler selects other#ifdefbranches of the source. - A source file the front end cannot parse is skipped with a warning and
listed (
SKIPPED,"skipped_sources"); the rest is verified. What the file defines is in no coverage figure on the source side; its code in the binary counts as unproved.
What the output means
Per function:
| Status | Meaning |
|---|---|
PROVED |
Every path through the function was explored on both sides and every effect was proved equal. |
BOUNDED |
No difference exists on the explored paths, but exploration stopped at a limit — typically a loop that could not be proved by induction. The proof covers the explored trip counts only. |
MISMATCH |
The machine code provably behaves differently. The message gives a concrete input. |
INCONCLUSIVE |
The prover ran out of budget on some obligation. Nothing is claimed either way. |
UNSUPPORTED |
The function uses something cverif does not model yet. |
Overall:
- Source coverage — the share of statements and branch conditions that lie on a proved path.
- Binary coverage — the share of code bytes (instructions and literal pools, excluding alignment padding) that lie on a proved path. Bytes that no proof reaches are exactly the bytes nothing vouches for.
- Initialised data — the initial contents of every object the source defines are compared with the image.
- Score — the mean of the two coverages, or 0 as soon as anything provably differs.
- Optimisation — a best guess at the
-Olevel from the shape of the code, with ties shown when levels produce indistinguishable code. Flags recorded in debug info are reported separately as declared, because they are a claim made by the binary, not evidence.
How it works
Both the C function and the machine code are executed symbolically over the same symbolic inputs: the argument registers and stack slots defined by the AAPCS, the initial contents of memory, and the results of calls to functions defined elsewhere. Every value either side computes is a term in one shared, hash-consed bit-vector language whose constructors normalise aggressively, so the two sides usually arrive at the same term. What normalisation cannot settle goes to a built-in prover: terms are bit-blasted into an incremental CDCL SAT solver.
For each path through the C function, the machine code is executed under that path's condition; where the machine code branches on something the condition does not determine, both directions are explored. At the end of every path — and at every call to an external function — cverif proves that:
- the return value is the same;
- every memory location either side wrote holds the same value;
- external calls happen in the same order with the same arguments;
- callee-saved registers and the stack pointer are restored;
- the machine code stores nothing outside what the source writes: not into its caller's frame and not into other objects. An access to the stack below the stack pointer is reported as a hazard (see "Hazards").
Memory is modelled with the guarantees a compiler may use and no others. A
local whose address has not been given away aliases nothing; once it has been
passed to an external function or stored where one can find it, any pointer
obtained afterwards may point into it. On top of that the source side assumes
what the C standard makes undefined otherwise: lvalues of incompatible types
do not overlap (the character types excepted), an object modified while a
restrict pointer to it is live is accessed only through that pointer, a
dereferenced pointer is not null, and an object with internal linkage that the
program never writes and whose address it never takes keeps its initial value.
The C side records the conditions under which the program has defined behaviour (no signed overflow, no division by zero, in-range shifts, in-bounds accesses to known objects). The machine code only has to match on inputs that satisfy them, which is precisely the freedom the C standard gives a compiler.
A proof never rests on sampled inputs or on running the code. A reported counterexample is a concrete input on which the two sides evaluate differently; for floating-point code the search for one also tries inputs near the solver's candidate, and each is checked with exact arithmetic before it is reported.
Some arithmetic that compilers produce is out of reach for a SAT solver. For those the normaliser carries rewrite rules that are theorems checked on each use — for example, division by a constant compiled into a multiplication by a reciprocal is recognised and turned back into a division only when the exact Granlund–Montgomery condition holds.
Floating point is supported for code built for software floating point (the
default for Cortex-M0/M3, -msoft-float elsewhere). Values are IEEE bit
patterns; comparisons, negation and fabs are exact bit-level formulas, while
addition, multiplication, division and conversions are functions the prover
knows nothing about except that equal operands give equal results. The
runtime routines the binary calls (__aeabi_fadd, __aeabi_dcmplt,
__aeabi_f2iz, … and their libgcc names) denote the same functions. A proof
therefore never relies on reassociation, on a reciprocal, or on any other
"fast-math" identity, and a counterexample is confirmed with exact IEEE
arithmetic before it is reported. Which NaN (sign, payload) an operation
returns is left open, as in C; whether a value is a NaN is exact. Converting an
out-of-range value to an integer is undefined behaviour.
Variable-length arrays and alloca
T a[n], alloca(n), __builtin_alloca(n) and
__builtin_alloca_with_align(n, a) create a stack object whose size is a
term. In the source it is a fresh private object: uninitialised, unknown to
every pointer that existed before it, private until its address is handed
out. A variable-length array lives until its scope is left (by falling out,
break, goto, or by reaching the declaration again); an alloca block
lives until the function returns. sizeof of a variable-length array is the
value computed at its declaration. A parameter declared int a[n],
int a[static n] or int a[*] is a pointer, as in C. Indexing inside the
array, a bound of at least one element and a size that fits the stack are
assumptions of defined behaviour, like any other.
In the binary the stack pointer moves by a computed amount and the function continues through a frame pointer. Nothing is assumed about that frame:
- every store and every load relative to the frame is proved to lie at or above the current stack pointer and below the caller's frame;
- at a call, the stack pointer is proved to be inside the megabyte below its value at entry, and what the binary keeps on the stack survives the call only where its address is proved to be at or above the stack pointer;
- the first time the binary passes the address of such an object, its block is proved to lie inside the function's own frame and not to overlap another local the callee can reach; from then on the source's object and that block are the same memory, and at every call the two sides must hold the same contents wherever either stored something (bytes the source never wrote are indeterminate and not compared). After the call the whole block is unknown, the same unknown on both sides;
- at return, the stack pointer and the callee-saved registers must be those of entry, whatever the size was.
When the path fixes the size (a bound the compiler folded, an inlined helper called with a constant) the object is an ordinary local.
Limits: an array or block is assumed to be at most 64 KiB (a program that
allocates more than its stack holds has no defined behaviour; the bound is
what keeps a frame inside the megabyte the model gives a function), and the
stack is assumed not to lie in the lowest or highest megabytes of the address
space. Only the outermost bound of a local array may be variable, and the
only type name that may have a variable bound is the operand of
sizeof(T[n]) (the bound is evaluated, the result is n * sizeof(T); this is
also how an assertion written (void)sizeof(char[1 - 2 * !(cond)]) on a
condition the compiler folds is read). Arrays of variable-length arrays,
pointers to and typedefs of variable-length array types and casts to them
make the function UNSUPPORTED with the construct named. A loop that creates such objects is explored to a bound
(eight per path) and reported BOUNDED; proofs by induction are not attempted
while one is live. Code that fills an array in a loop whose trip count is the
array's length is BOUNDED for the same reason as any such loop.
Hazards: accesses below the stack pointer
The procedure call standard gives a function nothing below its stack pointer,
and an exception taken at any instruction pushes its frame there. GCC
generating Thumb-1 code (Cortex-M0/M0+) at -Os/-O2 has been seen to
restore the stack pointer before its last access to a variable-length array
(mov sp, r7 followed by a load from the array).
Such code computes what the source says as long as no exception is taken between the two instructions, which is the model every other result here is stated in. So the function is verified as usual, with the access allowed, and keeps the status the proof gives it; the access is reported next to it:
PROVED vl_buf 32 bytes 1 paths (hazard: read below the stack pointer)
-v lists each instruction, the summary counts the functions, and the JSON
report gives "hazards": [{"kind": "below-sp read", "address": ..., "size": ...}]
per function. --strict-stack turns every such access into a MISMATCH
(and so into a failing exit status). Whatever the option, nothing below the
stack pointer survives a call, and an object whose address the function
passes to a callee must lie above it.
Endless loops and functions that do not return
A loop that never ends and does nothing (for (;;) {}, the usual body of a
default interrupt handler or a fatal-error routine) ends the path on both
sides: the binary must reach a branch to itself having made the same calls and
the same accesses to volatile objects. Plain stores on the way in can no
longer be observed by the program and are not compared (GCC removes them):
an interrupt handler or a debugger that reads such a variable after the hang
sees whatever the binary left there. A
call to a function declared noreturn ends the path in the same way.
Inline assembly
A function written in assembly — __attribute__((naked)), or a body that is
nothing but assembly statements the front end has no meaning for — has no C
semantics to compare with: it is UNSUPPORTED ("assembly: ..."), its code
counts as unverified, and its callers treat it like any external function. A
compiler that sees such a routine in the same translation unit may rely on the
registers its clobber lists leave out; cverif grants a caller exactly the
caller-saved registers the routine's code leaves unchanged on its single path
from entry to return, and none if the routine branches or calls out.
Instructions that only act on the system are events, ordered with calls and volatile accesses, that the binary must execute in the same order:
| statement | event |
|---|---|
cpsid i, cpsie i, cpsid f, cpsie f, cpsid if, cpsie if |
by name |
wfi, wfe, sev, yield |
by name |
dsb, dmb, isb (full system) |
by name |
bkpt #n, svc #n |
name and number |
mrs rX, PRIMASK | BASEPRI | BASEPRI_MAX | FAULTMASK | CONTROL | IPSR | MSP | PSP |
name; the value read is unknown, the same on both sides |
msr PRIMASK | BASEPRI | BASEPRI_MAX | FAULTMASK, rX |
name; the value written must be equal |
nop is no event (and nothing is said about timing). Operands are taken from
the statement: an "r" input for MSR, an "=r" output for MRS; a "memory"
clobber makes the event a point where all memory must agree, as at a call —
without it the compiler may move stores across the statement and so may the
binary. Several instructions in one statement are several events. Any other
instruction, an msr to MSP, PSP or CONTROL (which change the stack
under the running function), or operands in another shape make the containing
function UNSUPPORTED with the text of the statement.
Functions that return twice. A call to setjmp, _setjmp, sigsetjmp,
vfork, MicroPython's nlr_push, or any function declared
__attribute__((returns_twice)) is proved as an ordinary call, which covers
its first return. The second return resumes the same code with the same
callee-saved registers and stack pointer (the contract of the routine), with
memory that the proofs of the intervening code show to be equal on both sides,
and with non-volatile locals that C leaves indeterminate if they were modified
in between. What is not the same is the binary's stack frame, which the jump
back does not restore. The proof therefore carries over to the second return
only if no path of the function stores, after the call, to a frame slot that
the code following a possibly non-zero return reads before writing it, nor
releases that slot (raises the stack pointer above it) before a later call,
which may then use it; cverif checks that over all paths and reports the
function INCONCLUSIVE otherwise, with none of its paths counted as coverage
(typically a volatile local updated before the jump and read after it). Such
a call in an inlined callee or inside a loop proved by induction is
UNSUPPORTED.
Current limits
cverif is at an early stage. Known gaps are reported as UNSUPPORTED,
INCONCLUSIVE or BOUNDED rather than silently accepted, except where noted:
- Loops. A loop whose trip count depends on the input is proved by
induction when the binary loops the way the source does: cverif pairs a
point in the source loop with one in the machine loop, finds a relation
between the two states and proves that it holds on entry and is preserved by
every iteration. Peeled, rotated and plainly unrolled loops are handled,
as are loops around calls and loops the compiler tests at another point
than the source does. A loop during which a local is visible to the
functions it calls is not, and a loop whose memory accesses the prover
cannot tell apart within the budget is not either.
Loops unrolled with a remainder loop, vectorised, or replaced by a closed
form or a library call, loops in callees followed from their caller, and
recursion are explored to a bound and reported
BOUNDED. A proof by induction shows that the binary computes what the source computes whenever the source terminates; it does not show that the loop terminates. - A function proved with its calls compared as calls (the default) is right provided its callees behave as their source says; see the MicroPython section. Termination is not proved, for loops or for recursion.
- A
staticfunction fitted to its callers is only recognised when the arguments are constants in the source (also passed on unchanged by another such function, up to 16 values); a compiler that derives a range from computed arguments still gets aMISMATCH, orINCONCLUSIVEwhen the function could not be proved through its callers either. - Results marked
(assuming strict-aliasing)hold for the semantics GCC and clang implement, which is stricter on the program than ISO C for allocated storage;--standard-aliasingshows what remains without it. - Variadic function definitions and volatile bit-fields.
- Inline assembly other than the system instructions listed above; functions written in assembly are not verified, only called.
- Variable-length arrays with more than one variable bound, and pointers to variable-length array types (see above).
- A callee compared as a call that receives the address of a local is taken
to keep that address unless its own source shows that it only reads and
writes through it (a syntactic analysis that errs towards "kept"); a
compiler that proves more than that about a callee may release the local
earlier than the model allows, which shows as a false
MISMATCH. - A library
memcpy/memsetinto a local is taken to be able to change any global memory, so a value the compiler keeps across it instead of loading it again is a falseMISMATCH(seen once, GCC for Cortex-M0+). - Peripheral registers: every access the source makes to a volatile object
must be reproduced in order, and the binary may make no other access to a
constant address in a peripheral range (
--mmio). An extra read through a computed address that the source never treats as volatile is not detected. - A local whose address was given away stays reachable, as far as the binary side is concerned, until the next external call even if its scope has ended.
mallocand friends are ordinary external functions: the freshness of the memory they return is not known.- Some compiler arithmetic is beyond the prover, for example 64-bit division by a constant expanded inline.
- Targets other than Thumb (Cortex-M0, M3 and M4 are tested). Floating-point instructions (VFP) are not decoded, and functions passing floating-point values under the hard-float calling convention are unsupported.
<math.h>functions other thanfabsare ordinary external calls.- Whole firmware: link-time optimisation removes most of what identifies a
function (file symbols, names, boundaries), so little beyond exported entry
points is proved for LTO builds. Function-local statics of the same name in
several files (GCC's
name.N) cannot be told apart from annmlisting alone. Initialised data is compared object by object; code that reads constant data is proved against the image's bytes, so a changed table shows up as aDATAdifference, not in each function reading it. - The C front end is its own implementation and uses built-in versions of the common standard headers; unusual GNU extensions may not parse.
Building and testing
cargo build --release
cargo test --release
The crate has no dependencies. The end-to-end tests compile the corpus in
tests/corpus at every optimisation level, require every function to be
proved, and require deliberately altered builds to be rejected. They cover:
- GCC for Cortex-M3, M0 and M4 at
-O0 -O1 -O2 -O3 -Os -Og; - clang and GCC with a size-optimised Cortex-M0+ firmware command line
(
-mcpu=cortex-m0plus -fropi -fno-jump-tables -mno-unaligned-access ...), clang for-mcpu=cortex-m3 -frwpiand-mcpu=cortex-m35p+nodsp -msoft-float -frwpi, and GCC forcortex-m35p+nodsp, each at-Oz -Os -O0 -O1 -O2 -O3.
tests/vla_asm.rs covers variable-length arrays, alloca and inline
assembly with GCC and clang for Cortex-M0+ and M3 at -O0 -Os -O2, with
mutants of both and with hand-written frames that misplace the stack pointer.
tests/discover.rs strips the symbols from linked images and measures what
--discover finds against the ELF file (function starts and $t/$d bytes),
damages symbol tables (entries deleted, sizes removed, addresses shifted, names
swapped) and requires each defect to be flagged and the repaired table to give
the original result, and checks that appended or hidden code is reported and
that data blobs are not called code.
Tests skip themselves when the compiler they need is not installed.
tests/core_fuzz.rs checks the term normaliser and the prover against an
independent reference evaluator.
License
MIT