cverif 0.0.3

Verifies that compiled machine code faithfully matches its C source
Documentation

cverif

CI crates.io docs.rs License: MIT

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.

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 becomes DIFFERENT when a caller in the images reads the result. r1 differing is a printed condition (if it does not return a 64-bit value), or DIFFERENT when 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.

Limits of the comparison: 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 main and 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 unknown bytes 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 .data is located by the address the code uses, its initial values (stored somewhere in flash) are not compared unless the table names it. With -frwpi the 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 nm listing.
  • Thumb only; an image that mixes in other code or holds a compressed second stage shows it as unknown.

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, 8 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 493 113 34 0 50.7% 31 s, 0.7 GB
the same without _FORTIFY_SOURCE 639 490 109 40 0 50.2% (before the last merge) 31 s, 0.6 GB
GCC -O2 598 386 174 38 0 49.8% 47 s, 1.1 GB
clang -Os, Cortex-M0+, -fropi -fno-jump-tables (objects joined with ld -r, without main.c) 721 509 169 38 5 57.3% 64 s, 1.7 GB

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 two classes left under clang:

  • clang reorders two stores through pointers of different types (for example items[len++] = x, where the element and the counter could be the same memory as far as C is concerned: C lets a store give allocated memory a new type). --typed-memory assumes what clang assumes, that memory is never reused with another type, and four of the five reports go away. It is off by default because the C standard does not grant it.
  • clang narrows a static function to the argument values its callers pass (stream_readinto_write_generic is only called with flags 0 to 3). cverif verifies each function for every argument, so the function is reported although the program as a whole is right.

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 107 of 640 functions are proved instead of 493. The price is that a caller's PROVED rests 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 152 of the 493 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); variable array bounds in a type name (one macro in MicroPython's obj.h accounts for 24 functions); the assembly of nlr_jump; 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: 30 to 60 seconds 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 (-I to 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_SOURCE by 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, trusting the object size the compiler passes.
  • A source file the front end cannot parse is skipped with a warning and listed (SKIPPED, "skipped_sources"); the rest is verified.

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 -O level 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, not into other objects, and it neither reads nor writes the stack below its stack pointer (the procedure call standard gives a function nothing there, and an interrupt may overwrite it at any time).

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: arrays of variable-length arrays, pointers to and typedefs of variable-length array types, and sizeof of such a type name 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.

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 is reported as a MISMATCH ("binary reads ... below its stack pointer"): an interrupt arriving between the two instructions overwrites the array.

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; cverif checks that over all paths and reports the function INCONCLUSIVE otherwise (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. 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 static function that the compiler specialised for the arguments its callers pass, without renaming it, is verified for all arguments and may be reported as a MISMATCH (seen with clang).
  • 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).
  • 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.
  • malloc and 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 than fabs are 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 an nm listing 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 a DATA difference, 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 -frwpi and -mcpu=cortex-m35p+nodsp -msoft-float -frwpi, and GCC for cortex-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