Repository navigation
Inline assembly: a differential test harness against hardware - #9506
Draft
tautschnig wants to merge 86 commits into
Draft
tautschnig wants to merge 86 commits into
tautschnig wants to merge 86 commits into
Conversation
2 of 4 tasks
tautschnig
force-pushed
the
up/asm-harness
branch
from
November 17, 2026 19:14
e7b2100 to
94d31e6
Compare
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #9506 +/- ##
===========================================
+ Coverage 81.29% 81.65% +0.35%
===========================================
Files 1725 1745 +20
Lines 191680 196626 +4946
Branches 73 74 +1
===========================================
+ Hits 155835 160548 +4713
- Misses 35845 36078 +233 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
__CPROVER_havoc_object(p) with p pointing to a string literal failed the invariant "Attempted to symex havoc applied to unsupported expression", as dereferencing p yields the literal itself: a string constant for a narrow string literal, and an array for a wide or Unicode string literal or for the part of any literal that a pointer into its middle refers to. String literals and other constants are not objects whose value can change, so there is nothing to havoc. Use goto_symex_statet::is_read_only_object, which symex_assign uses to ignore writes to such objects, to recognise them. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Add doc/cprover-manual/modeling-inline-asm.md describing how CBMC's remove_asm
pass translates inline assembly: x86 fences (mfence/lfence/sfence) and the FP
control word (fstcw/fnstcw/fldcw), ARM barriers (dmb/dsb/isb), Power
synchronisation (sync/lwsync/isync), and the lock prefix. The page documents
the actual behaviour, including that lfence/sfence are modeled identically to
mfence, that isb/isync are empty fences, that xchg and lock-prefixed
read-modify-write instructions are not modeled (dropped), that an
inline-assembly statement containing any unrecognized instruction is dropped
in its entirety (including recognized siblings), that output operands are not
assigned nondeterministic values, and that MSVC-style asm only models the x86
subset. Link the new page from the manual index.
Add regression tests regression/cbmc/inline_asm_{modeling,dropped} that pin
these documented contracts against the goto program shown by
cbmc --show-goto-functions, so the documentation and remove_asm.cpp cannot
drift silently.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
remove_asm replaces an entire inline-assembly statement with skip whenever it contains an instruction that is not modeled, silently discarding any modeled instructions in the same statement. Emit a warning identifying the source location so users are not left silently relying on un-modeled assembly. Update the inline-assembly manual page and the inline_asm_dropped regression test to reflect the new diagnostic. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
process_instruction_gcc and process_instruction_msc shared near-identical scaffolding: parsing the assembly text, handling the lock prefix and xchg, wrapping locked instructions in an atomic section with a full fence, and dropping the whole statement when an instruction is not recognized. Extract this into a shared process_asm helper parameterized by a per-flavor command handler (handle_gcc_command / handle_msc_command), and replace the repeated by-hand fence construction with a make_fence helper. No change in behavior; the inline_asm_modeling and inline_asm_dropped regression tests pin the emitted goto program. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
With gcc's -fasm-blocks (and in CodeWarrior style), a function body may be
an assembly block, as in `void asm f() { mov eax, eax }`. The parser
produced an asm statement without a flavor for these, which made
remove_asm fail the invariant "unexpected assembler flavor". Give these
statements the gcc flavor and the operand layout of gcc-style statements
without operands, as already done for `__asm__ { ... }` blocks.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The operands of a gcc-style inline assembly statement are evaluated before the statement executes, but goto conversion copied the statement including any side effects in its operands, such as function calls or assignments. remove_asm then either dropped those side effects together with the statement or emitted instructions with side-effect expressions in them. Clean the output and input operands as for any other expression, so that the side effects become explicit instructions before the statement. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Several modeled instructions were translated without looking at their operands: - `fstcw %0; fldcw %1` passed the first operand of the statement to both library models, so fldcw loaded the control word from `%0`. Resolve the `%N` operand reference of each instruction instead, and treat any other operand (a register, `%[name]`, an explicit address) as not modeled. MSVC-style blocks naming a variable that is shadowed are not modeled either, rather than picking one of the candidates. - ARM `dmb ishld` and `dmb ishst` were full fences. A fence that is stronger than the hardware's prunes behaviours that weak-memory instrumentation needs to consider. Options ending in `ld` now order loads before loads and stores, options ending in `st` order stores before stores, and other unknown options are not modeled. - Fences and `isb` with operands they do not take (e.g. Power `sync 1`, which is `lwsync`) are not modeled. Also model Power `hwsync` and `eieio`, and the no-ops `nop`, `pause`, and `yield`. Merge the two copies of the library call helper, and replace the eight positional flags of make_fence by the four orderings plus a single cumulativity flag (all existing users set cumulativity for all of the orderings they set, or for none). process_asm now returns the first instruction that is not modeled instead of emitting the warning, to let callers handle that case. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An inline assembly statement containing an instruction that is not modeled was removed, so that its effects were lost: any property that depends on an output operand, on memory written through a pointer operand, or on memory changed behind a "memory" clobber could be reported as holding although it does not (see diffblue#6374). Replace such statements by a conservative approximation (in the new asm_approximationt): 1. the input operands, and the in-out operands, are read, so that they are subject to the usual checks; 2. the addresses of the outputs, and the pointers found in the input and in-out operands (pointer operands, arrays decaying to pointers, pointers cast to integers, pointer members of structs and unions) are recorded in temporaries before anything changes; 3. the objects these pointers point to are havocked; 4. with a "memory" clobber, and for basic assembly without any operands or clobbers, the objects of static lifetime, the objects that pointers among them point to, and the address-taken local variables of the enclosing function are havocked; 5. the outputs are havocked, at their recorded addresses; 6. the rounding mode is havocked, as the statement may write the control registers of the floating-point unit. MSVC-style blocks have no operand interface: every local variable named in the block (all of them, if the name is shadowed) is treated as an output and pointer operand, and the block as having a "memory" clobber. Objects reachable only through other pointers (heap objects not pointed to by an operand or an object of static lifetime, or a caller's local variables) keep their values, which the warning now printed for each approximated statement says. Fixes: diffblue#6374 Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Describe the instructions remove_asm now models, including the barrier options, and the conservative approximation of statements with instructions that are not modeled, together with its limitations. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The C library's fegetround and fesetround (for example, FreeBSD's fenv.h) read and write the rounding mode with stmxcsr and ldmxcsr, which were approximated: the rounding mode then became nondeterministic, so that Float-no-simp9 failed on FreeBSD. Model them like fstcw and fldcw, via library functions: the rounding mode is bits 13 and 14 of the SSE control and status register (with the same encoding as __CPROVER_rounding_mode). The other bits of the register (the exception flags and masks, flush-to-zero, and denormals-are-zero) are not modeled: stmxcsr stores nondeterministic values in them. inline_asm_approximation_rounding_mode now uses fxrstor, which remains approximated. The results of inline_asm_mxcsr were validated natively on x86-64. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
When all instructions of a gcc-style statement were modeled, remove_asm
emitted only their translation, so the output operands kept their old
values. On hardware, an output receives the register that the compiler
chose for it: `asm("" : "=r"(x) : "0"(y))` (the Linux kernel's RELOC_HIDE
and OPTIMIZER_HIDE_VAR) sets x to y, and `asm("nop" : "=a"(z) : "a"(w))`
sets z to w, but CBMC proved x == 0 and z == 0. The manual's claim that an
empty template does nothing was wrong for statements with outputs.
After the translation of the instructions, remove_asm now assigns each
output with an `=` constraint that no modeled instruction writes (the
operand of fstcw, fnstcw, and stmxcsr is written):
- the value of the input that is tied to it by a matching constraint (its
number, or its symbolic name in brackets), if the types are the same or
are integer, enumeration, or pointer types of the same width;
- otherwise a nondeterministic value.
In-out operands keep their values. As for the approximation, the inputs and
the addresses of the outputs are recorded before the instructions, so that
`"=r"(p), "=r"(q) : "0"(q), "1"(p)` swaps p and q.
To resolve symbolic names, the parser keeps them in ID_identifier of the
operands, as the commit "C front end: keep the symbolic names of asm
operands" of a later change does with the same lines.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
In gcc mode, `__asm { mov x, 1 }` (Clang and Apple gcc -fasm-blocks) and
asm blocks that form a function body, as in `void asm f(int *p) { ... }`,
had the gcc flavor without operands. remove_asm thus approximated them as
gcc-style basic assembly, which changes objects of static lifetime and
address-taken local variables only, and CBMC proved that x is unchanged
(it is 1 with clang-18 -fasm-blocks) and that f does not write *p.
These blocks use Intel syntax and name the C variables they access, as
MSVC blocks do. Give them the msc flavor (with the text as only operand),
so that remove_asm changes the local variables and parameters they name and
the objects these point to. asm_block_function_body now checks that the
object a parameter of such a function points to may change; asm_block_gcc
checks blocks in braces.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The assembler lexer of remove_asm treated '#' as the start of a comment anywhere. On ARM and AArch64, '#' starts a comment only at the start of a line or statement; elsewhere it introduces an immediate. With --arch arm64, `dmb #11; str %w1, [%0]` thus lost the store, and the statement was modeled as a fence only: CBMC proved that the stored-to object is unchanged. `dmb #9` (ishld) became a full fence, which prunes weak-memory behaviours. The parser now knows whether '#' starts a comment anywhere, which is the case on x86 (and for MSVC-style blocks), Power, MIPS, RISC-V, s390, and LoongArch, as GNU as and llvm-mc agree. For other targets, including ARM and AArch64, '#' starts a comment at the start of a line or statement only and is a token otherwise, which at worst makes a statement approximated. The immediate forms of the dmb, dsb, and isb options are mapped to the named options; reserved values are not modeled. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
__asm_lfence and __asm_sfence, which remove_asm calls for lfence and sfence, were full fences like __asm_mfence. A full fence orders stores before later loads, which neither instruction does: in a store-buffering test with lfence or sfence between the store and the load in each thread, x86 hardware exhibits r0 == 0 && r1 == 0 (observed 111 and 1968240 times, respectively, in 2e6 runs), but CBMC with --mm tso proved that it cannot happen. lfence now orders loads before later loads and stores (RR, RW), and sfence stores before later stores (WW). The new cbmc-concurrency test asm_x86_fences_sb checks store buffering with each of the three fences, and the cbmc-library tests of __asm_lfence and __asm_sfence, which were KNOWNBUG placeholders that included a header that does not exist, now pin the fences. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
`dsb ishst` (and dsb with any other option ending in st) was modeled like `dmb ishst`: as a fence that orders stores before later stores only. Unlike a dmb, a dsb waits for the accesses it orders to complete before any later instruction executes, so the stores before it are also ordered before the loads after it. The weaker fence admitted store buffering across dsb ishst, which the architecture forbids. dsb with a st option now also orders stores before later loads (WW and WR, cumulative); dmb with a st option is unchanged. The new cbmc-concurrency test asm_arm_dsb_st_sb checks store buffering with dsb ishst and dmb ishst, and inline_asm_modeling pins both fences. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The scanner of remove_asm returns `s.a` as one identifier, as it allows
'.' in identifiers. For an MSVC-style block that is approximated, such as
`__asm { mov s.a, 1 }` with --winx64, the lookup of the local variables
the block names thus found nothing for `s.a`, and CBMC proved s.a == 0.
The name up to the first '.' is now looked up, so s is changed.
The operand of an MSVC-style fstcw, fnstcw, fldcw, stmxcsr, or ldmxcsr
was looked up preferring a unique local variable over a global variable,
even if that local variable is not in scope at the block: with a local cw
in an earlier block and `__asm { fnstcw cw }` referring to the global cw,
CBMC wrote the dead local (reporting a dead-object failure) and proved that
the global is unchanged. CBMC does not know which variables are in scope,
so the instruction is now modeled only if there is exactly one variable of
that name among the local variables and parameters of the function and the
global variables; otherwise the block is approximated.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
__asm_fstcw and __asm_fnstcw stored the rounding mode in bits 10 and 11 of the x87 control word and 0 in all other bits. The other bits are the exception masks and the precision control, which are 0x037f initially on x86 hardware, so CBMC proved, for example, that `(cw & 0x300) == 0` after `fnstcw %0`, which fails on hardware. The other bits are now nondeterministic, as __asm_stmxcsr already does for the bits of the SSE control and status register other than the rounding mode. inline_asm_fpu_control_word checks this, and the cbmc-library test of __asm_fnstcw, a KNOWNBUG placeholder that included a header that does not exist, now checks the rounding mode like the test of __asm_fstcw. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
abstract_environmentt::havoc, which the variable-sensitivity domain uses for calls of functions without a body and for writes through pointers it cannot resolve, removed all variables from the environment, as a variable that is not in it is top. A merge, however, only merges the variables that both environments have, and keeps the others. When the path that jumps over `opaque(&m)` reached the label first, m kept the value 0 after the merge, and goto-analyzer --vsd reported `m == 0` as holding. havoc now replaces each value by top instead, so the merge results in top. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The approximation of inline assembly assigns nondeterministic values to the
objects that its pointer operands point to with havoc_object. The constant
propagation, interval, and variable-sensitivity domains ignored that
statement, so goto-analyzer --constants and --vsd proved that k is
unchanged after `asm volatile("movl $1, (%0)" : : "r"(&k))`, as they did
after `__CPROVER_havoc_object(&k)`. invariant_sett threw an exception for
the statement. goto-instrument --constant-propagator, which uses the
constant propagation domain, replaced the assertion `k == 0` after
`__CPROVER_havoc_object(&k)` by true.
These domains do not track what pointers point to, so treat the statement
as changing anything a pointer may point to:
- constant propagation forgets the values of the objects of static lifetime
and of the address-taken variables, as for calls of functions without a
body;
- the interval and variable-sensitivity domains forget all values;
- invariant sets forget all invariants.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The C++ parser (Parser::rGCCAsmStatement) parses the outputs, inputs, and
clobbers of gcc-style inline assembly, but discards them. remove_asm thus
treats such a statement as basic assembly: an output of an approximated
statement, as in `asm volatile("movl $1, %0" : "=r"(out))`, is not
changed, and CBMC proves `out == 0`, which fails with g++. Likewise, an
output tied to an input keeps its value.
Fixing the C++ parser is left to other work on it. Add a KNOWNBUG test
that documents the problem, and list it among the limitations in the
manual.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
process_asm turned a lock prefix, and xchg, into an atomic section with a full fence around the instruction. As none of the instructions that take a lock prefix is modeled, nor is xchg, such a statement was approximated and the atomic section discarded; the scaffolding only produced output for a lock prefix on a modeled instruction, as in `lock; nop` or `lock; mfence`, which is invalid (it raises an invalid-opcode exception) and was translated into an atomic section with a full fence. Remove the scaffolding. A lock prefix is now the command of its instruction, which is not modeled, so statements with it are approximated and the warning names it. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
inline_asm_modeling checked that each expected fence occurs somewhere in the goto program, so a statement translated into the fence of another one (several statements translate into the same fences) went unnoticed, and the fences in the bodies of the x86 fence helpers were not checked at all. The test now matches the instruction that each statement's line is translated into, and the bodies of __asm_mfence, __asm_lfence, and __asm_sfence. It also covers dsb ishld and hwsync. In the manual, the description of lwsync as "all fences except write-after-read" read backwards; it now says what lwsync orders. The manual now also says that CBMC has a single rounding mode, which fldcw sets although, on x86-64, float and double arithmetic uses the SSE rounding mode, which fldcw does not change; the KNOWNBUG test inline_asm_fldcw_sse documents the resulting wrong proof. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
For an output whose address depends on the program state, such as
arr[idx] next to the output idx in
asm("" : "=r"(idx), "=r"(arr[idx]) : "0"(1), "1"(9));
compilers differ in whether they compute the address before or after
writing the other outputs: GCC at -O0 stores 9 to arr[1], GCC at -O2 and
Clang to arr[0]. Both the assignment of the outputs of a statement whose
instructions are all modeled and the approximation of other statements
used the address before the statement only, so CBMC proved properties
that the code compiled by GCC at -O0 violates.
Approximate a statement whose instructions are all modeled if it has more
than one output and one of them has an address that depends on the program
state. The approximation now assigns such outputs nondeterministic values
both at the address before and at the address after the statement.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Add a havoc_reachable statement. Its operands are pointers, and its arbitrary_memory flag says whether the objects of static lifetime and the address-taken local variables of all functions on the call stack are also roots. Symbolic execution computes the objects reachable from the roots using the value set, following pointers stored in reachable objects transitively. This includes heap objects and, through the dirty analysis, a caller's local variables whose address has escaped. It then assigns nondeterministic values to all of them. The approximation of inline assembly will emit this statement. A static pass cannot name heap objects or a caller's local variables, which is why this is done in symbolic execution. Assigning a nondeterministic value to a pointer would give it a value set containing every object in the value set. That is imprecise: dereferencing a pointer after the statement yields a case split over all objects, and --pointer-check flags pointers that point nowhere. It is also costly, as every such assignment visits the whole value set. Instead, each pointer stored in a changed object is assigned a nondeterministic choice among: - the pointers previously stored in the changed objects (its own first), - the addresses of the reachable objects of a compatible type, and - null. The choice is restricted to at most 64 candidates. This models a statement that relinks a list, and keeps dereferencing precise. Pointers in unions and in arrays that are large or of non-constant size are assigned arbitrary values. Other analyses treat the statement like havoc_object: value sets and dirty-variable analysis consider the operands only, and goto_rw records writes to the objects the operands point to. As the dependencies of the statement are only known during symbolic execution, the full slicer does not slice programs that contain it. The regression tests come with the use of the statement in remove_asm. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The approximation of inline assembly that is not modeled only changed the objects that the pointer operands point to and, with a "memory" clobber, the objects of static lifetime, the objects that pointers among them point to, and the address-taken local variables of the enclosing function. Heap objects more than one pointer away from these, such as the second node of a list whose head is stored in a global variable, kept their values. So did the local variables of a caller whose address has escaped. Emit a havoc_reachable statement instead. Its roots are the pointer operands and, for a "memory" clobber or basic assembly, all objects of static lifetime and the address-taken local variables of all functions on the call stack. The new statement is evaluated before the outputs are assigned, while the value sets still describe the state before the statement. The explicit assignments to the objects of static lifetime are now done by the new statement instead. They also caused symbolic execution time to grow cubically with the number of statics: every nondeterministic pointer assignment gives that pointer a value set of all objects, which the next statement then has to havoc. For a program with 300 objects of static lifetime (100 pointers and 100 structs with a pointer member) and two such statements, cbmc took 363 seconds; it now takes 0.2 seconds, and symbolic execution takes 10 seconds with 6000 objects of static lifetime. Analyses other than symbolic execution ignore the new statement until the following commits, which make them interpret it. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
goto_rw treated havoc_reachable like havoc_object of each operand: with a "memory" clobber, which has no operands, the statement neither read nor wrote anything. Analyses built on goto_rw, such as reaching definitions and the dependence graph, thus considered the havocked objects unchanged. With value sets (rw_range_set_value_sett), compute the reachable objects like symbolic execution does: - the roots are the operands and, with the arbitrary_memory flag, the objects of static lifetime and the address-taken local variables (as set by the new set_dirty, which reaching definitions and the dependence graph use); - the closure follows the pointers stored in reachable objects using the value sets. The statement reads the operands and the pointers it follows, and writes the reachable objects that are symbols. Heap objects remain untracked, as for all other instructions. Without value sets, it writes the objects the operands point to and, with the arbitrary_memory flag, the objects of static lifetime. The closure is computed by the new find_reachable_objects. It works for any pointer analysis, as it traverses objects with the type of the pointer they are reached through. This handles dynamic objects, whose type the static analyses do not know. Symbolic execution now shares the list of objects of static lifetime and the pointer compatibility check with it. The full slicer still does not slice programs that contain the statement. The dependence graph does not track heap objects, so the instructions that link heap objects would be sliced away, making the objects that the statement changes unreachable. --full-slice already gets this wrong for heap accesses without inline assembly (diffblue#260). Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The Intel SDM leaves CF undefined for shl and shr whose count is at least the operand size, which only 8- and 16-bit operands can reach as the count is masked to 5 or 6 bits. CBMC modeled CF as undefined for counts above the width only, and as the last bit shifted out for a count equal to the width, so it proved, for example, that `shlb %%cl, %1` with %cl == 8 and %1 == 1 sets CF (as the Intel Xeon this was run on does, but the architecture does not require). CF is now nondeterministic for shl, sal, and shr with counts of the width or more. For sar, CF is the sign bit for a count of the width, as before. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The manual on inline assembly listed --arch i386 and x86_64 only, whereas the x86 semantics also apply to x32 (with the x86-64 instructions and 32-bit pointers), and it omitted clc, stc, and cmc, which the semantics model, and out, which they model as having no effect on the C program state. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The unit tests of split_asm_template did not cover references to the C labels of asm goto (%lN and %l[name], numbered after the operands), forward and backward references to local labels (including 0b, which is a label reference rather than a binary number), %=, the %n modifier, and numbers in octal, hexadecimal, and binary as GAS reads them. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Register and flag outputs are assigned after the interpreted instructions,
in the order of the operands, and the address of each was computed when it
was assigned. For an output whose address depends on the program state,
such as arr[idx] next to the output idx in
asm("movl $1, %0; movl $9, %1" : "=&r"(idx), "=r"(arr[idx]));
GCC at -O0 computes the address after writing idx (arr[1] = 9), but GCC
at -O2 and Clang compute it before (arr[0] = 9), so CBMC proved
properties that the code compiled by the latter violates.
Do not interpret a statement with more than one output, or with a
"memory" clobber, if one of its register or flag outputs has such an
address. The approximation that is used instead assigns these outputs
nondeterministic values at both addresses.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
On AArch64 (--arch arm64), remove_asm approximated every inline assembly statement other than fences and no-ops. Kernel and library code uses inline assembly for atomics, barriers, bit operations, and access to the condition flags, all of which thus became nondeterministic. Add AArch64 instruction semantics to the inline assembly interpretation: moves (mov, mvn, movz, movk, movn), arithmetic and logic with optionally shifted operands and the NZCV flags, shifts and rotates, compare and test, conditional set and select, single-register loads and stores (including acquire/release and exclusive variants), swp, cas, and the LSE atomic memory operations, branches within the statement and to the labels of asm goto, barriers (dmb/dsb with their access-type options, and isb), hints, and msr/mrs of nzcv. Load/store pairs and bit-field instructions are not yet interpreted. msr of daif, daifset, and daifclr is a no-op; mrs of other system registers yields a nondeterministic value; msr of other system registers is not interpreted. The condition flags and condition codes live in asm_arm_flags.h to be shared with AArch32. Load-exclusive/store-exclusive sequences are modelled soundly: - ldxr opens an exclusive region, which ends at the matching stxr; the instructions of the region form a single atomic section. - stxr succeeds nondeterministically, as the architecture permits spurious failure. A stxr after a clrex or after another stxr fails (status 1, no store), as the monitor is then clear. - Any other memory access, branch, or label inside an open region makes the statement uninterpreted (and hence approximated), as the architecture does not guarantee the reservation then. Retry loops around stxr consequently need --unwind; bounding them is state-complete as a failed attempt has no effect. To be sound, a statement is also not interpreted when an instruction uses a symbolic operand that does not name a register, or when it writes a hardware register that is neither bound to an operand nor clobbered (canonical_register maps w-registers to x-registers for this check). The regression tests were validated against qemu-aarch64 (corner cases, unknown addresses) and Unicorn (asm_aarch64). Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Every `hint #imm` was a no-op, but the hint space also holds the pointer authentication instructions, which write x17 (pacia1716 = hint #8, ...) or x30 (xpaclri = hint #7, paciasp = hint #25, ...), and chkfeat (hint diffblue#40), which writes x16. With `mov x17, %1; mov x16, #0; hint #8; mov %0, x17`, qemu-aarch64 (-cpu max) changes x17, but CBMC proved the output equal to the input. Interpret `hint #imm` as a no-op only for the numbers of hints that leave registers and memory unchanged (nop, yield, wfe, wfi, sev, sevl, dgh, esb, psb csync, tsb csync, gcsb dsync, csdb, clrbhb, and the bti variants), and approximate the statement for any other number, including numbers not allocated yet. The named pointer authentication instructions were not interpreted already. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Operand modifiers of immediate operands were ignored, but some of them change what the compiler prints: `add %0, %1, #%n2` with "i"(5) prints `#-5`, so the instruction subtracts 5 (qemu-aarch64: 100 becomes 95), while CBMC proved that it adds 5. Accept an immediate operand only without a modifier or with %c, which prints the constant like a plain reference, and with %w and %x if the constant is 0, which the compiler prints as wzr and xzr; approximate the statement for any other modifier. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Whether the exclusive monitor was cleared (by clrex or a store-exclusive) was tracked along the text of the statement, not along its control flow. In `cbnz %3, 1f; clrex; 1: stxr %w0, %2, [%1]`, after a load-exclusive in an earlier statement and with the branch taken, the store-exclusive succeeds on qemu-aarch64 (status 0, and the store happens), but CBMC proved that it fails. A branch to a label may skip the clearing instruction, so forget at each label that the monitor is cleared: a store-exclusive after a label succeeds or fails nondeterministically. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
`dsb` with an option ending in `st` (dsb st, dsb ishst, ...) was modeled like `dmb ishst`, as a fence that orders stores only before later stores. But no instruction after a dsb executes before the dsb completes, and a dsb st completes once the stores before it have completed, so it also orders these stores before later loads. With `dsb ishst` between the store and the load of both threads of the store-buffering test, CBMC (--mm tso) reported that both loads may read 0. Emit a fence with WW and WR for dsb with an st option; dmb with an st option stays WW only. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A memory access, branch, or label between a load-exclusive and a store-exclusive made the whole statement uninterpreted, and hence approximated. Linux uses such statements for __cmpwait (ldxr, then a branch, and no store-exclusive at all) and for the LL/SC cmpxchg (which branches past the stxr if the values differ), so CBMC could not prove that __cmpwait leaves memory unchanged, or what cmpxchg returns. Abandon the exclusive access region at such a point instead: the load-exclusive is then a plain load, and a later store-exclusive succeeds or fails nondeterministically, as before, but is not atomic with the load. This is sound: hardware guarantees the atomicity only when the store-exclusive succeeds, and a model without the atomic section admits more interleavings. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
asm_aarch64.cpp declared bool_to_bv, borrow_sub, carry_add, even_parity_low_byte, msb, overflow_add, and overflow_sub, but uses none of them: the flags are computed in asm_arm_flags.h, which qualifies the names. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The regression tests of the AArch64 interpretation did not cover the C and V flags of adds, subs, cmn, and negs, most condition codes, the conditional selects and csetm, sign-extending loads, ldur, ldar and stlr, the b, h, and st forms of the LSE atomics, tbz and tbnz, ror and asr, mvn, movn, and neg, flag outputs, or asm goto. Add two tests that compare each such statement with a C reference on concrete inputs, chosen to set and clear each flag in 64 and 32 bits. All assertions hold when main.c is compiled for AArch64 and run on qemu-aarch64; CBMC interprets all statements and proves all assertions. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
dmb, dsb, and isb, with their options, are the same in AArch64 and AArch32. Move their lowering from the AArch64 semantics to asm_arm_flags.h, which already holds the condition flags that both share, so that the AArch32 semantics can use it. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
On AArch32 (--arch arm, armel, or armhf), remove_asm approximated every inline assembly statement other than fences and no-ops. Kernel and library code uses inline assembly for atomics (ldrex/strex), barriers, bit operations, and the interrupt masks, all of which thus became nondeterministic. Add AArch32 instruction semantics for A32 and T32 code, in unified and divided syntax: data processing with the flags (s suffix) and conditional execution (condition suffixes; it, whose conditions the instructions repeat as suffixes that the assemblers check), multiplication, bit and byte manipulation, movw/movt, loads and stores of single registers with an immediate or register offset, branches within the statement and to the labels of asm goto, flag outputs, barriers (dmb/dsb/isb and their CP15 forms), mrs/msr of the flags, the interrupt masks, hints, and CP15 cache, TLB, and thread ID operations. Load-exclusive/store-exclusive sequences follow the AArch64 model: ldrex opens an exclusive region, which ends at strex and is atomic; strex succeeds nondeterministically; after clrex or strex, a strex fails. A conditional strex may not execute, and then does not clear the monitor. To be sound, as found by validating against qemu-arm: - In divided syntax, which GCC uses for inline assembly in A32 code and for Thumb-1 targets, Thumb-1 add, mov, and the like set the flags without an s suffix. Unless the statement starts with .syntax unified or uses an instruction or form that Thumb-1 lacks, the flags are nondeterministic after a data-processing instruction without s suffix. - msr of the control field may change the processor mode, which banks r8 to r14: a statement that does so and names any of them is not interpreted. - pc (whose value is the address of the instruction), coprocessor writes other than the CP15 ones above, and other special registers are not modeled. Semantics that depend on the statement as a whole, as these two rules do, now create an asm_semantics_statet via asm_semanticst::make_state. This fixes the reviewer reproducers for a crash on mov from pc, the approximation of four-instruction IT blocks, and strex always succeeding. The fork's Unicorn-validated test (asm_arm) passes unchanged in its expected values; asm_arm_corner_cases was validated with qemu-arm for A32 and T32 code compiled by GCC and Clang. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
msr of the control field may change the processor mode, which banks r8
to r14. make_a32_state refused statements that do so only if they name
one of these registers, but it looked at identifier tokens only, so
operand references were missed although the compiler may allocate them
to r8 to r14. CBMC thus proved
register unsigned x __asm__("r8") = 1;
__asm__ volatile("msr cpsr_c, %1\n mov %0, #2\n msr cpsr_c, %2"
: "+r"(x) : "r"(0x11), "r"(0x13));
assert(x == 2);
whereas in FIQ mode the mov writes r8_fiq, and the assertion fails.
A statement that changes the mode is now also approximated if it uses an
operand after the first such msr (whose source may be an operand), or at
all if a label precedes that msr, as a later branch could return to it.
Operands used before the mode changes, as in the ARMv5 local_irq_save
sequence "mrs %0, cpsr; orr %1, %0, diffblue#128; msr cpsr_c, %1", remain
modeled.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
In divided syntax, which GCC uses for inline assembly for Thumb-1 targets, the 16-bit add is adds. make_a32_state took movw, movt, cbz, cbnz, and the exclusive loads and stores as evidence that a statement is not such code, and kept the flags exact. ARMv8-M Baseline, a Thumb-1 target, has all of these, so CBMC proved, for example, r == 2 after cmp %1, %1; movw %0, #1; add %0, %0, #1; beq 1f; mov %0, #7; 1: which GCC assembles for -march=armv8-m.base as adds; the code then returns 7 on qemu-arm. Likewise for an ldrex after the add. Moreover, an explicit .syntax divided in Thumb-2 code selects the Thumb-1 forms of add and the like, while GNU as accepts clz, rbit, rsbs, and so on, so that these instructions are no evidence either. These instructions no longer count as evidence, and the flags are nondeterministic after a data-processing instruction without s suffix in any statement that contains .syntax divided. The remaining evidence (conditional execution other than of branches, it, s suffixes other than movs, teq, clz, rbit, mrc, mcr) is rejected by GNU as in divided syntax for armv4t, armv5t, armv6, armv6-m, and armv8-m.base. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
In divided syntax for Thumb-1 targets, GNU as assembles movs between low registers as adds with #0, which clears C and V, and movs with a high register as mov, which keeps the flags. CBMC modeled movs as in unified syntax (N and Z set, C and V unchanged), and so proved r == 5 after cmp %1, %1; movs %0, %2; bcs 1f; mov %0, #7; 1: with %2 holding 5, whereas the code that GCC generates for -march=armv5t or -march=armv8-m.base yields 7 on qemu-arm. Where the statement may be divided Thumb-1 code, the flags are now nondeterministic after movs, as after the data-processing instructions without s suffix. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
lower_system treated every CP15 operation with CRn c7 other than the
barriers as cache maintenance without effect on the modeled state. The
operations that invalidate data or unified caches without cleaning them
(CRm c6 and c7: DCIMVAC, DCISW, and the ARMv5/ARMv6 whole-cache and
unified forms) may discard dirty lines, so that memory reverts to an
older value. CBMC thus proved
x = 1;
__asm__ volatile("mcr p15, 0, %0, c7, c6, 1" : : "r"(&x) : "memory");
assert(x == 1);
Only the c7 operations known not to change memory are now interpreted:
invalidating instruction caches and branch predictors, cleaning, and
cleaning and invalidating data or unified caches, as well as the ARMv6
CP15 wait for interrupt and the barriers. Invalidation without cleaning,
and any other c7 operation (such as the address translation operations),
makes the statement approximated.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
lower strips the width qualifiers .n and .w before decoding a mnemonic, but make_a32_state decoded the raw mnemonic, so add.w was skipped. The qualifiers exist in unified syntax only, yet without other evidence the statement was taken as possibly divided Thumb-1 code, and the flags were nondeterministic after the add.w. CBMC thus reported a spurious failure of r == x + 1 after cmp %1, %1; add.w %0, %1, #1; beq 1f; mov %0, #7; 1: The statement-wide scan and lower now share helpers that strip the width qualifiers (normalise_mnemonic) and recognise IT instructions (is_it_mnemonic), so that the two cannot drift apart, and a width qualifier shows that the statement is not divided Thumb-1 code. A single to_lower helper replaces the four lower-casing loops. The new test asm_arm_instructions holds cases that exist in one instruction set only, each in a function with a target attribute. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The exclusive access region and the exclusive monitor are tracked while lowering, not on the paths that execute the instructions, but the condition of an instruction only guards its code. Hence a conditional ldrex opened the region also on the path where it does not execute, and a conditional strex ended the region on both paths. For clrex; cmp one, #0; ldrexeq v, [p]; strex st, rep, [p] with one == 1, the strex fails on hardware, while CBMC let it succeed. In "ldrex; add; cmp nz, #0; strexeq; strexne" the strexne that executes succeeded outside any atomic section, so that CBMC reported a lost update in a two-thread increment. Both are over-approximations, but they were not reported as approximations. A statement with a conditional load-exclusive, or with a conditional store-exclusive and another store-exclusive, is now approximated. A conditional store-exclusive that is the only one of its statement, as in the compare-and-swap sequence "ldrex; mov; teq; strexeq" of Linux, is modeled exactly: the atomic section from the load-exclusive includes it, and no other store-exclusive observes the monitor that it leaves set if it does not execute. asm_arm_exclusive now checks that such a compare-and-swap is atomic. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The shifts with an s suffix (lsls, lsrs, asrs, rors) left the carry flag nondeterministic, so that CBMC could not prove, for example, that C is bit 31 of x after "lsls r, x, #1". The differential test against qemu-arm reported every vector of the shift forms as imprecise. C is now the last bit shifted out, for a shift by an immediate or by the bottom byte of a register: bit 32 - n for lsl and bit n - 1 for lsr (0 for n > 32), bit min(n, 32) - 1 for asr, and for ror bit (n - 1) mod 32. A shift by 0 keeps C; GNU as assembles shifts by #0 as movs. With this, the review's differential test (A32 and T32, 280 vectors for each register form and 28 for each immediate form) reports all shift forms exact and sound. C remains nondeterministic after logical operations with an immediate operand, where it depends on the encoding that the assembler chooses. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
msr of the control field may leave the processor in another mode, as in msr cpsr_c, #0x1f. The interpretation treats the mode bits as having no effect, so the C code after such a statement is modeled as running in the original mode, although it uses the banked sp and lr of the new mode (and r8 to r12 in FIQ mode), and so are the output operands that the compiler then reads from banked registers. Say so in the user and the architecture documentation. Whether a register source of msr changes the mode cannot be decided statically, so approximating the statement would not help: the approximation does not model the mode either. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The AArch32 tests did not exercise lower_system at all, nor cbz/cbnz, divided-syntax suffix order, several data-processing instructions, the byte and halfword exclusives, register offsets, pld, or asm goto. asm_arm_system covers each branch of lower_system: cpsid/cpsie (and cps with a mode, which is approximated), msr of cpsr_c and cpsr_fc with the flags they keep or set, the rejection of a mode change in a statement that names r8, mrs and msr of other special registers, mrc, the CP15 barriers (fences.desc checks the fences), cache cleaning and invalidation of instruction caches (no effect), invalidation without cleaning by set/way and of both caches, other c7 operations, TLB maintenance, the thread ID registers, and CP15 registers, opc1 values, and coprocessors (p14) that are not modeled. asm_arm_instructions gains cbz and cbnz (T32), addeqs (A32, divided syntax), mvn, neg, sxth, uxtb, cmn, tst, ldrsh, strh, ldrb and strb with register offsets, pld, ldrexb/strexb, ldrexh/strexh, and asm goto. Both tests were validated with qemu-arm for A32 and T32 code compiled by GCC; privileged instructions were skipped by a SIGILL handler there. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A memory access between a load-exclusive and a store-exclusive made the whole AArch32 statement uninterpreted, and hence approximated, while the AArch64 semantics abandon the exclusive access region at that point, as the shared lowering does at branches and labels. Do the same for AArch32: the load-exclusive is then a plain load, and a later store-exclusive succeeds or fails nondeterministically, but is not atomic with the load. The manual already describes AArch32 exclusive accesses as following the AArch64 model. The new test, with Linux's arch_atomic_fetch_add_unless (a branch past the store-exclusive) and a plain store between the two exclusive accesses, passes on qemu-arm when built by arm-linux-gnueabihf-gcc for A32 and T32 code. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The asm_x86, asm_aarch64, and asm_arm regression tests pin results of inline assembly statements that were observed on hardware (x86-64) or with the Unicorn emulator (AArch64, AArch32), so that a wrong instruction semantics, or a statement that is approximated rather than interpreted, makes an assertion fail. The tests were generated by a script that was not part of the repository, so they could neither be reproduced nor extended. Add that script, scripts/asm_differential: it compiles each case (a C function with one inline assembly statement) natively or with a cross compiler, runs it on pseudo-random input vectors with fixed seeds, and writes a test whose assertions are the observed results. Over the version used to create the tests, it formats the output with the repository's clang-format style also when the output directory is elsewhere, uses clang for AArch64 when aarch64-linux-gnu-gcc is not available, and writes the headers of the committed tests, which now name the generator. Regenerating the three tests with ASM_DIFF_MAX_VECTORS=3 reproduces them byte for byte. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The case "x86 memory operand with a struct field offset" runs orl %1,%0 with s.hi as its memory operand, but its function copies the unchanged locals lo and hi back to io, not the fields of s. The generated assertions therefore did not depend on what the statement does: with the statement replaced by "xorl %1,%0; notl %0", asm_x86 still verified. Give a case an optional epilogue that runs after the statement, and copy s.lo and s.hi to lo and hi in this case's epilogue, so that the result of the statement is observed. asm_x86 is regenerated (its expected values for hi change); with the replaced statement, the three assertions of the case now fail. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The generated tests expected VERIFICATION SUCCESSFUL, which also holds if an assumption makes the assertions unreachable. For example, replacing ldxr/stxr in the first AArch64 case by ldr and "mov %w1, #1" makes its retry loop never exit, which with --unwind 2 --no-unwinding-assertions leaves no path to the following assertions: asm_aarch64 still verified, even with a wrong expected value for a later case. End main with __CPROVER_assert(0, "end of main is reachable"), and expect in test.desc that this assertion fails and is the only one that fails (EXIT=10, its FAILURE line, and ** 1 of N failed). The number of properties is not pinned, so that adding a case only requires regenerating main. The three tests are regenerated; with the mutation above, the sentinel now holds and asm_aarch64 fails. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The case "x86 cmpxchg exchanges on a match" only had random input vectors, whose 32-bit memory and expected values never matched, so the generated assertions only covered the path that loads the memory value into eax. Replacing "lock; cmpxchgl %3,%1" by "cmpl %1,%2; movl %1,%2", which never exchanges, still verified. Give the case explicit inputs, as the AArch64 cas case has: two that match (and exchange) and one that does not. asm_x86 is regenerated; with the replaced statement, the assertions of the two matching vectors fail. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The README claimed that a wrong semantics of any instruction would make the generated assertions fail, but only the outputs that a case copies back to io are checked, and only for the sampled inputs. It also did not say that cases must not observe results that the architecture leaves undefined, that new cases must be appended (the seed of a case's random vectors is 1000 plus its index), or that ASM_DIFF_MAX_VECTORS does not cap the explicit inputs of a case. The module docstring did not mention pyelftools or the clang fallback for AArch64. Document these, and format the output with clang-format-18, the version that CI uses, in preference to clang-format-15. Regenerating the three tests with ASM_DIFF_MAX_VECTORS=3 still reproduces them byte for byte. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
tautschnig
force-pushed
the
up/asm-harness
branch
from
December 2, 2026 06:21
94d31e6 to
a8afa36
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Depends-on: #9504
The asm_x86, asm_aarch64, and asm_arm regression tests pin results of
inline assembly statements that were observed on hardware (x86-64) or with
the Unicorn emulator (AArch64, AArch32), so that a wrong instruction
semantics, or a statement that is approximated rather than interpreted,
makes an assertion fail. The tests were generated by a script that was not
part of the repository, so they could neither be reproduced nor extended.
Add that script, scripts/asm_differential: it compiles each case (a C
function with one inline assembly statement) natively or with a cross
compiler, runs it on pseudo-random input vectors with fixed seeds, and
writes a test whose assertions are the observed results. Over the version
used to create the tests, it formats the output with the repository's
clang-format style also when the output directory is elsewhere, uses clang
for AArch64 when aarch64-linux-gnu-gcc is not available, and writes the
headers of the committed tests, which now name the generator.
Regenerating the three tests with ASM_DIFF_MAX_VECTORS=3 reproduces them
byte for byte.
Co-authored-by: Kiro kiro-agent@users.noreply.github.com