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
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.
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.
Source coverage is the share of statements and branch conditions that lie on
a proved path, with each definition counted once: a static inline
function in a header is one function, however many translation units include
it, and is proved where any copy of it is. A definition is in the total when
it has code in the image: under its own symbol, or inlined into a function
that has (found through the calls in the source, also across several inlined
levels; its statements are then proved through its callers). Left out, and
listed instead:
- functions with no code in the image (no symbol, nothing with code calls
them: unused header helpers, functions the linker discarded). The summary
gives their number and their statements (
not in binary:),-vand the JSON ("source_functions_not_in_binary","source_points_not_in_binary") the names; - statements that a constant condition rules out inside functions that do
have code (
if (FEATURE) ...with the feature configured to 0, the other arm ofif (1)): no code exists for them. The summary counts them,-vand"source_no_code"list them. A statement that is unreachable for any other reason stays in the total as unproved.
Binary coverage is the share of the bytes of the executable sections that
are accounted for: instructions on a proved path, literal pools and tables a
proved path reads, and constants among the code that equal what the source
says (the initial value of a const object or a string literal, where the
linker script puts read-only data in the text section; the summary says how
many, "constants" in the JSON). Not counted at all: fill between functions,
the halfword of fill that aligns a literal pool inside a proved function (any
other fill inside a function is code, proved or not), a lone zero byte that aligns a constant, and
ranges set aside as data on somebody's word. Everything else is unproved and
appears in the JSON with its section, function and offset. 100% on both sides
therefore means: every statement that has code is on a proved path, and every
byte of the code sections is proved code, a proved constant, or padding.
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.
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, with the obstacle it met). --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 |
induction, induction_detail |
bounded only: why no proof by induction was found. induction is one of not-attempted, no-source-loop (the loop is in a callee followed from this function, or there is none), no-looping-path, no-cut-pair, base-failed, step-failed, no-relation, body-too-large, budget, exposed-local, dynamic-object, events (the two sides do not reach the loop head with the same calls made), unsupported-shape; the detail names the phase and the cut address of the attempt that got furthest |
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 ….
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.
--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.
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.
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, 16 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.
Each pair is decided by the cheapest means that decides it, and the summary says how many by
each (decided by:). A pair that consists of the same instructions, with call targets and
address constants that designate the same things, is equivalent without being explored: 614
of the 640 here. Such a pair is analysed only when a function that differs needs to know
what it does (which argument words it reads, whether its callers read its result); the other
26 are compared path by path. That is where the time went: 90 s before, 16 s now, the same
verdicts. CVERIF_COMPARE_FULL=1 explores every pair.
A DIFFERENT verdict comes with an input, and that input is run: both functions are
executed on it by an interpreter that shares nothing with the symbolic executor (the
reference of the red-team tests), calls returning what the counterexample says they return.
If the two runs do not show the difference, the verdict is INCONCLUSIVE and says so: the
prover's model and the machine disagree, and nothing is established. CVERIF_REPLAY=1 prints
what each run did ({run on that input: after 0 matching call(s) the old code calls ...}), or
why an input was not run (the replay gives up after 50000 instructions, and does not model
what a followed callee does to a peripheral).
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 (159 s): of 595 paired functions 274 EQUIVALENT, 155 MAY-DIFFER, 21
DIFFERENT, 63 BOUNDED, 10 INCONCLUSIVE, 72 UNSUPPORTED (frames laid out differently
around an escaping local). The prover gave 31 counterexamples. Run on the two functions, 14
show the difference, 10 do not (these are the INCONCLUSIVE ones: strictly_equal, the two
emit_write_bytecode_byte functions, five string methods and two more; the prover's model
and the machine disagree on them, which is a defect of the comparison and not a difference
of the images), and 7 are not run to their end by the replay (they stay DIFFERENT,
unconfirmed). Of the 14 that are confirmed, 8 are a difference in which calls are made: the
old code calls plat_print_strn (in seven printing functions) or
instance_count_native_bases where the new code does not make that call. That is what a
callee copied into its caller looks like, and the comparison, which follows such a callee
only where it can tell which one it is, still reports it as DIFFERENT. With the sources
none of the 31 is a difference:
The same pair with the sources (three-way, 343 s) has no difference: 451 EQUIVALENT (360
through the source, both images proved against it; 54 the same instructions; the rest by
machine code), 137 BOUNDED, 4 INCONCLUSIVE, 3 UNSUPPORTED, no DIFFERENT and no
MAY-DIFFER. Equivalence through the source is transitive (old = source = new) and holds
under what both proofs assume: the inputs for which the source is defined, the aliasing
rules it was held to, and for a function fitted to its callers the argument values they
pass; a function that is BOUNDED against the source on either side is BOUNDED here.
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
What the instructions do not settle is verified against the source, each image against its
own. Definitions are compared exactly, as parsed after preprocessing with the types and
macros they use: white space, comments and the place of a definition in its file are no
change; a function written in assembly is compared as text; a definition whose only change
is a line number or file name that __LINE__ or __FILE__ put there is
CHANGED IN SOURCE (line numbers and file names only). A function that is the same in both
sources and proved in both images is equivalent through the source, and so is one that
calls a changed function, when both proofs compared that call as a call: a caller depends
on its callee through the interface only (signature, noreturn, parameters that are only
borrowed or returned unchanged, the argument values its callers pass, a result nobody uses),
and the verdict lists the callee (EQUIVALENT ... modulo list_pop (DIFFERENT)). A function
that has changed code in place (an inlined callee, with or without a symbol of its own), uses
an object whose definition changed, or calls a function whose interface changed is decided by
its machine code and says why. On the patched MicroPython (62 s, 184 s before) the summary
reads 2 function(s) changed between the two sources: list_pop, pyexec_friendly_repl; one
more (mp_execute_bytecode) depends on the changed version object; 614 pairs are the same
instructions, 6 are equivalent through the source and 20 are compared as machine code (11
that are not proved against the source, 9 for what a differing function needs to know of
them); 630 are EQUIVALENT, 8 BOUNDED, and the two verdicts are those above. Pairs with
the same instructions are not verified against the source in this mode (--cache keeps the
proofs of each image between runs, as it does for plain verification).
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.
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.
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. The same run counts the binary coverage a second time without the code that is proved
under a name that is not (Binary coverage without the code under such names: ...).
A name that is conditional is proved given the names of the functions it calls; when those
become proved, it is proved, and this is repeated until nothing changes. What remains is
listed with the reason: conditional on: mp_map_lookup (bounded; 18), ... gives each name
that conditional ones rest on, how that name stands, and how many rest on it.
A symbol that the source only declares and the linker script defines (_estack, _sdata)
has no content to find it by. It is reported as inferred _estack = 0x20002000 (...), and
written to the table with that provenance, when the image holds an address where the
initialised data of the source holds the symbol (the first word of a vector table), or
when a function that uses it is proved with that address among the constants of its code.
The second needs the proof: start-up code that is only bounded (see below) gives none.
Measured on the stripped MicroPython image (-j 4, about 280 s): 412 functions named, 408
of them correctly; about 60 proved (none wrong), 150 conditional, 100 bounded, 65
by-data, 30 by-calls, 5 ambiguous. Two names were taken back; verification with the
table then gives 311 proved and no mismatch. The conditional names rest on 109 others, most
often mp_map_lookup (bounded; 18 rest on it) and mp_printf (conditional; 13). The wrong
names that remain are bounded or ambiguous ones (arg_looks_numeric is the same code as
arg_looks_integer in this configuration). No linker symbol is inferred on this image: its
start-up code is assembly. On the small firmware of the tests _estack is inferred from the
vector table; _sdata, _edata, _sbss, _ebss and _sidata are not, because the
start-up function that uses them is only bounded on a raw image ("path limit; 0 paths
proved"), also when the five are given with --symbols, while it is proved with the ELF
file. That difference is not understood yet.
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 | source proved | time |
|---|---|---|---|---|---|---|---|---|
GCC -Os, Cortex-M4 (the port's own) |
643 | 568 | 75 | 0 | 0 | 82.3% | 79.4% | 63 s at 4 jobs |
GCC -O2 |
602 | 467 | 135 | 0 | 0 | 78.1% | 77.6% | 163 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% (not measured again since) | 75 s at 4 jobs | |
clang -Os, Cortex-M0+, -fropi -fno-jump-tables (objects joined with ld -r, without main.c) |
721 | 611 | 110 | 0 | 0 | 78.3% | 79.5% | 92 s at 4 jobs |
The two coverage columns count what the coverage section says. In the linked GCC images about 12 KB of the proved bytes are constants in the text section (the parser's tables, the qstr pool, module dictionaries, string literals) that equal the source's; an object file keeps those in sections of their own, which is why the clang row has none. Counted the way earlier versions did (every copy of a header's inline functions, functions without code, and data in the text section as unproved code) the first row read 16.5% of the source and 62.6% of the bytes for the same proofs.
Merging conditionals (see "Conditionals that join again") is on in these runs,
except in the Cortex-M0+ GCC row, which was measured before it. It is tried on
the few functions the exploration path by path leaves open and that are mostly
small conditionals, and proves two more functions in the first row and one in
the last, for 3 to 8% more time (--no-merge: 564, 465 and 603 proved in 61,
158 and 85 s): what stays BOUNDED in MicroPython is conditionals a side of
which returns or calls, loops and one very large switch, none of which it
reaches.
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; a load and a
store of two members of one structure type that share no byte, one of
them of a character type, are apart too, since two
structures of a type coincide or do not overlap, which is why
g.b = p->v; g.c = p->v;readsp->vonce) 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); where the values are too many to list but every call passes a constant or a value of a narrower unsigned type (auint8_tmember, abool), for the bound that gives,PROVED (for n < 256: all callers): GCC tests such a parameter withn != 0where the source saysn > 0; 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.
Library functions a hosted compiler computes itself. Without
-ffreestanding the compiler knows what some C library functions return and
emits code for it, or calls another function: isdigit, isascii and
toascii become a comparison or a mask, ffs a bit count, memcmp of one
byte the difference of the two bytes, strchr in a string constant with a
known character its result, and strchr(s, c) for a string constant s
becomes memchr(s, c, strlen(s) + 1). The source is read with the same
meaning, for a hosted program only and only where the program does not define
the function itself; a binary that calls the function is compared with that
value, and the result then says what it rests on (the library's isdigit
among the assumptions). An expansion that computes something else (x - '0' < 9, the wrong byte, a memchr over less than the whole string) is a
MISMATCH.
Orders of evaluation the language leaves open. The operands of a binary
operator, the two sides of an assignment, the old value and the right-hand
side of a op= b, and the arguments of a call are evaluated in no order C
fixes; GCC and clang choose differently (MMIO |= f() reads the register
before the call with one and after it with the other). The source is run in
one order first; if the binary differs from that and the order could have been
observed (a call or volatile access on one side, anything the other side reads
or does), the other orders are tried, and the function is a MISMATCH only if
it differs in every one of them (and not proved, but not a difference either,
if one of them could not be decided). What is sequenced stays sequenced:
statements, &&, ||, ?:, the comma operator, and a call's arguments
before the call. Initialiser lists and the operands of subscripts are run
left to right only.
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.
Whether the program's definition is the library function is settled once per
program: each of the three is verified, like any function against its code,
against a plain implementation of the library function that cverif carries
(a byte loop; for memcpy a forward copy or a memmove).
- Proved: the calls rest on nothing more.
- Neither proved nor refuted (a word-at-a-time implementation whose loops do
not pair with the byte loop): a result that took the library's meaning
says
(assuming the library's meaning for a function the program defines). - Refuted (
memsetormemmovereturn or store something else for some arguments): the summary sayslibrary: the program's memset differs from the library's (...), and every result that relied on it carries the same sentence. No difference is ever claimed formemcpy, which may do what it likes with overlapping blocks.
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. - What is not proved, for the port's own build (12.5 KB of 66 KB, and
1884 of 8617 statements): 12.0 KB in the 87 functions that run out of
budget (the bytecode interpreter alone 3.5 KB, then the lexer's entry
point, string formatting, the parser, the compiler's entry point); 0.3 KB
in a function that stops at the path limit; and under 200 bytes of code
without source, unread jump-table entries and code inside proved functions
that no path of the source reaches. No function is
UNSUPPORTEDorINCONCLUSIVE:nlr_push,nlr_jumpand the reset handler are compared with their assembly (see "Assembly"), and the clones GCC made (.isra,.constprop) are verified on their own. On the source side the rest is statements of functions inlined into the unproved ones. 237 definitions (948 statements) have no code in this image and 13 statements sit under a constant-false condition; both are listed, not counted. - 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 flag of the fortifiedprintffunctions (__snprintf_chk(s, n, flag, size, ...),__sprintf_chk,__vsnprintf_chk,__vsprintf_chk) is part of the call: it must be a constant the source passes to the fortified form of that function, any other value is aMISMATCH, and a binary with fortifiedprintfcalls whose source was read without them isUNSUPPORTED(pass the same-D_FORTIFY_SOURCE). 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.
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.
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.
Exploring one path per way through a function makes the number of paths the
product of its conditionals: eight independent if (flags & X) n += …; are
256 paths of a few instructions each. Where a conditional is small, has no
calls and its sides meet again, both executors run the two sides once from the
same state and continue with one state in which every value the sides left
different is an if-then-else term on the condition:
- in the source,
&&,||and?:whose operands have no side effects other than plain reads and writes, andif/elseregions of up to 12 basic blocks without calls, loops,switch, variable-length arrays or inline assembly (nested conditionals inside are merged the same way); - in the machine code, the instructions under an
ITblock and forward conditional branches (B<cond>,CBZ/CBNZ) over at most 40 instructions that come back together, without calls or changes of the stack pointer.
Registers, flags and the memory either side wrote (at most 24 stores) are joined; a store made on one side only keeps the old value on the other. What the source must not do on one side (a division by zero, an out-of-range shift, an access outside an object) is assumed only where that side is taken: the condition recorded is "not taken, or defined". A side that is undefined outright leaves the other side and the assumption that it is the one taken. A merged value that ends up in an address is decided by an ordinary branch at that point, and a later branch on the same condition removes the choice from what is still to be proved.
Nothing is assumed about a merged region that would not hold on each path through it; the two executors need not merge the same regions. Coverage stays per side taken: the statements and instructions of a side count only if the merged path was proved and some defined execution of that path takes the side (a side nothing can take is reported as not covered, as before).
Merging trades paths for larger terms, and one large question can be harder
for the prover than many small ones; some things are also only recognised on a
path that pins a value down. So every function is first explored path by path
with its whole budget, and that verdict stands whenever it is one. Only where
that exploration runs out of budget, and at least two thirds of the paths it
opened were opened at conditionals of the kinds above, is the function explored
once more with those merged, with a quarter of the budget on top. That second
result counts if it is a proof, or if neither is complete and it covers more; a
difference is only ever reported from the exploration path by path, whose
counterexample names one way through the function. (Trying the merged
exploration first, or on every function left open, cost a fifth of the run
time on MicroPython for the same proofs.) --no-merge turns merging off, and
so does --dump, which shows what each path computes; --merge-only explores
with merging alone, for measurements. A length or a fill value that a merged
region chose is settled by a branch where memcpy, memset or memmove is
modelled, which copies one length at a time.
What it does not reach, counted on the 78 functions of the gcc -Os build that
stay BOUNDED (paths opened at a source conditional, by the reason it is not
joined): 62% at conditionals whose sides do not meet again within a dozen
blocks (a side returns or leaves a loop, the test is a loop's own, a switch
or a loop lies inside), 22% at ones merging does join, 15% at ones that would
join but for a call on a side (the test-then-call shape), under 1% at another
construct. A call on a side is not
merged: calls are compared one by one in the order each side makes them, and
a call that happens on one side only would have to be a call under a condition
on both, with what it may have changed in memory under that condition too. A
side that ends in a call that does not return (if (bad) raise();) costs one
short path per check, not a doubling: the path that takes it ends there.
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.
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.
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 made on the way in to
memory other code can see (globals, statics, anything reached through a
pointer the function was given) are compared as well: what the binary stores
there must be what the source stores. The program itself never reads that
memory again, so a compiler may drop such a store, and GCC does: a binary
that stores nothing where the source stores is accepted, and the result
says (assuming nothing reads what the source stores before a loop that never ends), since an interrupt handler or a debugger would see the old value.
Stores to the function's own local objects are not compared, even when their
address was given away earlier. A
call to a function declared noreturn ends the path in the same way.
Function symbols that share an address are one piece of code and a call is
compared by the code it reaches, whatever the name at the call site. The
opposite also happens: one name at several addresses. The image may hold the
code of a function more than once (a copy per translation unit, a copy the
linker did not fold), and a symbol table written for a stripped image may call
several addresses by the one name. Within one function the source's
foo(); bar(); foo(); can then be bl 0xAAAA; bl bar; bl 0xBBBB, and no
single address for foo fits both calls. Nothing has to be chosen:
- The source defines
foo. Every address namedfoothat a short trial does not refute as the function is verified against the source on its own. The first is listed asfoo, the others asfoo @ 0xBBBB, each with its own verdict and its bytes in the binary coverage. A call the binary makes to any of them is the call the source makes tofoo, compared as a call (arguments, memory, result). The caller's proof then rests on the copy its call reaches, exactly as it rests on any callee compared as a call: the report saysmodulo foo @ 0xBBBB: MISMATCHfor the callers whose calls go to a copy that is wrong, and not for those that only reach the others. - An address named
foothat is notfoofor every argument (code specialised for some callers, or simply wrong code) is refuted by the trial and is no copy. It gets no verdict of its own; a call to it is followed, on both sides, like a call to an inlined function, and the caller is proved or not with the code that is really there. A version that only fits the constant 5 is fine for the caller that passes 5 and aMISMATCHfor one that reaches it with 3. - The source only declares
foo. Calls are compared by name, so several addresses under the name are taken for one function. Where they hold the same instructions (equal bytes, branches to the same places, literals within the code) they are one function, and nothing is assumed. Otherwise the names are the only evidence, and every result that compares a call under the name says(assuming the 2 addresses named foo are one function), also as"assumes"in the JSON. - Pointers. The source's
&foois one value; the binary may hold the address of any copy. Where a comparison comes down to exactly that (the source gives one address offoo, the binary another), the function isUNSUPPORTEDwith that reason: neither proved, since the program could compare the two pointers, nor a difference.
Symbol tables (--symbols, a link map, an ELF symbol table, the table
--discover writes) may list a name any number of times; the sizes are per
address. Limits: a wrong copy whose own verification is refuted by the trial is
not listed as such (its callers are); the copies of a function are verified for
every argument unless the function is fitted to its callers, in which case the
callers of all copies together are what it is fitted to; and a linker veneer
(__foo_veneer) is still another name, not another address of foo.
Assembly sources. A .s or .S file on the command line (GNU as
syntax, Thumb; preprocessor directives are not interpreted, so a .S file
that uses them must be preprocessed first), and an __attribute__((naked))
C function whose body is nothing but assembly statements, is verified without
semantics:
no assembler runs and nothing is executed, the binary is decoded and compared
with what the source says, instruction by instruction. Every instruction of
the binary must be the source's (the same operation on the same operands,
whatever encoding the assembler chose), every branch must go where the
source's label is, every ldr rX, =value must load that value, data
directives must be the bytes of the image, and the routine must end where the
source ends (bytes after an instruction that never falls through are neither
compared nor counted). The result is PROVED with (assembly: every instruction is the source's) and "assembly": true in the JSON; a
difference is a MISMATCH at the address; an instruction or directive the
front end does not know is UNSUPPORTED, never equal. Callers treat the
routine as an external function, as before.
Supported: labels, numeric local labels, .equ/.set, the data directives
(.word .long .4byte .short .hword .2byte .byte .space .skip .ascii .asciz .string), .align .balign .p2align, .pool .ltorg, the directives that
emit nothing, and the instructions of the Thumb decoder: data processing with
immediate, register and shifted-register operands, movw movt mul mla mls udiv sdiv, loads and stores in every addressing mode, push pop ldm stm,
branches, cbz cbnz, it blocks, adr, extends, rev*, clz, rbit, and
the system instructions of the table below. In the older divided syntax
(.syntax divided, GCC's default for ARMv6-M) a 16-bit instruction written
without s is the flag-setting one. Not supported: macros, conditional
assembly, expressions beyond symbol ± constant, ARM state, floating point.
Assembly statements inside a C function are compared as a block in two
cases. A statement that never falls through (it ends in b, bx or
pop {..., pc}: MicroPython's nlr_jump restores the registers from a buffer
and returns through the saved link register) ends the path like a call to a
function that does not return: the binary must reach these instructions, with
the statement's input operand in a register and with the memory the source
has at that point. ldr sp, =symbol as the first statement of a naked
function (a reset handler) is a stack switch, after which the C body is
verified for any stack. In both cases the instructions must be in the
function's code exactly once, nothing may jump into their middle, and such a
function is never followed into from a caller. A naked function whose C body
runs off its end stops there, with everything it did compared.
A body made of assembly statements in a function that is not naked (the
compiler adds a frame around it) remains 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).
The same verdict is given from the source's side, whatever the binary does:
a function that reads a volatile local after such a call and stores to one
before a later call is INCONCLUSIVE, since after the jump back the local
holds the value stored, not the one of the first return that the comparison
is about (a binary that kept the first value in a register reads no frame
slot, and is wrong).
When the call is in a function the compiler inlined (nlr_push called from a
small wrapper), the same argument is made for the function under verification,
whose frame it is, with one more condition from C11 7.13.2.1p2: the second
return is only defined while the activation that made the call is alive. Once
the source's inlined callee has returned, a jump back is undefined behaviour
and nothing is required of the binary; until then the frame slots read after
a non-zero return are checked as above. Such a call inside a loop proved by
induction is UNSUPPORTED.
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, loops made with
goto, and loops the compiler tests at another point than the source does. The relation is a conjunction of guesses, each of which the base case and the step must prove: a machine location equals a source variable or expression, or is a linear function of one or two of them (an array walked by a pointer, an index kept as the distance between two pointers, an end pointer, a count running down). A local the loop's callees can see (a buffer handed to an iterator, an out-parameter filled on every iteration) is carried across the loop head as the same memory on both sides, at the place of the frame where the binary keeps it. A loop whose memory accesses the prover cannot tell apart within the budget is not proved, nor is one whose exit test the compiler replaced by a comparison of pointers that is only equivalent because no object is larger than half the address space. A dispatch loop (an interpreter'sswitchover opcodes, a scanner driven by a state variable) is the same proof with one path of the step per arm; every arm must be proved for the function to bePROVED, and a function with some arms unproved staysBOUNDEDwith no part of it counted as proved. A dispatch loop that calls a function that may return twice (an interpreter inside its exception region) and one whose head the compiler split into several by threading jumps are not proved yet. 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 reportedBOUNDED; the text after the limit says what stopped the proof by induction (induction exposed-local,step-failed,budget,no-source-loop, ..., with the detail of the attempt that got furthest). 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. - Pointer arithmetic. The source is assumed not to step outside an object:
a pointer plus an unsigned count does not wrap around the address space, a
count that is a variable (
str + len) is at mostPTRDIFF_MAXbytes, since GCC and clang create no larger object and compile the sum as a signed offset, and a step back by a constant (--s) does not pass address zero. clang tests the sign oflenbeforefor (s = str + len; --s >= str;), which is the source's loop only under these three. - 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. - Decided, and kept as they are:
- the aliasing rules a source is held to by default are the compilers' (both tiers above), not ISO C's alone;
- a
staticfunction the linker folded with an identical one is verified for every argument, not for what the callers of either name pass; - comparing the addresses of two functions (
f1 == f2) is taken to give "different", as C says: a binary linked with--icf=all, where both names are one address, is aMISMATCHfor the function that compares them.
- Variadic function definitions and volatile bit-fields.
- Inline assembly other than the system instructions and the two block forms described above. Assembly is compared, not understood: a routine proved "instruction by instruction" does what its source does, and nothing is said about what that is. Macros and conditional assembly are not read.
- A GCC clone (
f.isra.0,f.constprop.0) is verified on its own only when its interface is the source's with at most one parameter left out; other clones, and the pieces of a function (.part,.cold), are verified as part of their callers. A wrong clone has no verdict of its own (no interface fits) and is aMISMATCHin its callers. - 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.
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/asm_src.rs compares assembly files, naked functions and assembly
blocks with what GCC assembles from them (Cortex-M3 and M0+), with a mutant
of every kind of line; tests/gaps.rs holds reproducers of goals the prover
used to give up on and of GCC's function clones.
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.
MIT