Repository navigation
Inline assembly: interpret x86 instructions - #9500
Draft
tautschnig wants to merge 61 commits into
Draft
tautschnig wants to merge 61 commits into
tautschnig wants to merge 61 commits into
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #9500 +/- ##
===========================================
+ Coverage 81.29% 81.58% +0.28%
===========================================
Files 1725 1742 +17
Lines 191680 195188 +3508
Branches 73 74 +1
===========================================
+ Hits 155835 159241 +3406
- Misses 35845 35947 +102 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
4 of 5 tasks
tautschnig
force-pushed
the
up/asm-x86
branch
3 times, most recently
from
November 17, 2026 19:14
71c5ef9 to
0dedb13
Compare
__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>
`goto-analyzer --dependence-graph --show` crashed with a stack overflow
(SIGSEGV, unbounded recursion in value_set_fit::get_reference_set_sharing_rec)
on programs whose inline assembly has a "memory" clobber and that allocate
heap memory, for example `int **gpp; ... gpp = malloc(sizeof(int *));
asm volatile("cli" ::: "memory");` compiled with goto-cc.
The flow-insensitive value sets, which the reaching definitions of the
dependence graph use, store a variable's value as a reference (an object
of type #REF#) to the value set of another variable; such references may
form cycles, which value_set_fit::flatten handles. value_set_fit::
havoc_reachable collected the objects whose address is stored anywhere from
the raw value sets, and so took these references as objects. Assigning
their addresses to the pointers in the reachable objects then made the
value set analysis follow the cycles without end.
Skip references when collecting the objects whose address is stored
anywhere: the values they refer to are visited as entries of their own.
References to variables without a value set stand for these variables, as
in flatten_rec. Also, as the assignments of the flow-insensitive analysis
add to the previous values, no longer list the previous value of a pointer
(which made its value set refer to itself), and express the positions
within the objects it pointed to via these objects.
The new test (in goto-cc-goto-analyzer, as the crash needs a goto binary)
checks the dependencies of the statement on a program with heap objects.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
havoc_reachable splits each object it changes into the pointers it contains
and the remaining parts, and assigns each of them separately. The parts were
expressions such as a[i][j], an index or member expression of the whole
object. Reading such an expression (to record the previous value of a
pointer) renames it, and renaming the whole object expands it into all its
fields (field-sensitive symbolic execution has a symbol for each element),
once for each part. For `int *a[64][64]` of static lifetime and two
statements `asm volatile("cli" ::: "memory")`, cbmc took 164 s and 600 MB.
With one statement, symbolic execution took 80 s (2.7 s with a[32][32]).
Convert the parts to the symbols that field-sensitive symbolic execution
has for them (state.field_sensitivity.apply, for writing) before reading and
assigning them. cbmc now takes 1.3 s and 170 MB on the program with two
statements, and symbolic execution takes 0.5 s with one statement (0.1 s
with a[32][32]). The formula is unchanged (20572 steps for one statement).
The new test inline_asm_havoc_reachable_array has the program with one
statement; it exceeds a timeout of 20 s (test.pl -t 20) without this change.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Since "havoc_reachable: pointers may move within the objects they can
reach", a pointer that may point into an object larger than its target type
is assigned (among its other choices) a choice among its candidates plus a
nondeterministic offset, with an assumption, guarded by the choice, that an
object of the target type fits at the resulting position. The assumption
uses the object size and the pointer offset of that choice. This was slow on
arrays of structs that contain pointers: for 8 struct types, each with a
static array of 30 elements whose first element points to the second, and
two statements `asm volatile("cli" ::: "memory")`, cbmc took 21 s (61 s for
16 types; 2.9 s for 16 types and one statement).
Express the moved pointer instead relative to the objects that the
candidates may point into: the start of one of these objects (a choice with
constant sizes) plus a nondeterministic position of few bits if an object
of the target type fits there, and the start of the object otherwise. The
condition is part of the value rather than an assumption. The candidates
themselves remain choices. Candidates with unknown targets are moved within
the object they point to, using its object size, as before.
The position is a multiple of the alignment of the target type, as CBMC
lays out objects. Arbitrary byte positions made dereferencing slow: with
four pointers of static lifetime into an array of 256 int, dereferenced
after the statement, cbmc took 37 s instead of 1.4 s (and more than 600 s
instead of 12.5 s for 1024 int and an additional dereference of p0[1]). The
statement is thus assumed not to store misaligned pointers, which the
per-statement warning and the manual's limitations now state. Objects that
contain a packed struct or union, or a type whose given alignment is smaller
than that of its members, are exempt, as their members may be at any
position (in `struct __attribute__((packed)) { char c; int x; } ps[4]`,
ps[1].x is at offset 6): pointers are moved to arbitrary positions within
them. A smaller alignment given for the target type is used instead of its
natural one.
Measurements (cbmc with default options, wall-clock time, before -> after):
- 8 struct types with 30 elements each, two statements: 21 s -> 0.9 s;
16 types: 61 s -> 1.9 s; 64 types: 9.1 s after.
- four pointers into int[256], dereferenced: 1.7 s -> 1.8 s; with p0[1]
in addition: 12.6 s -> 1.8 s; int[1024] with p0[1]: 10.5 s -> 13.7 s.
- a list of 16 heap nodes traversed after the statement: 1.0 s both.
The new test inline_asm_havoc_reachable_alignment has the 8 struct types
(19.7 s before, 0.9 s after), and checks the misaligned pointer (which the
assumption excludes), the packed struct, and the reduced alignment.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Symbolic execution restricts each pointer stored in an object that
havoc_reachable changes to a choice among at most 64 candidate values, but
the number of such pointers was not bounded: the formula grows with the
number of pointers times their candidates. For 128 struct types, each with
a static array of 60 elements that contain a pointer to the struct type
(7680 pointers with 61 candidates each), and two statements
`asm volatile("cli" ::: "memory")`, cbmc ran out of memory (4 GB, after
47 s) in the propositional reduction. Also, finding the compatible
candidates of each pointer visited all candidates: 1920 pointers times 1984
candidates for 64 types with 30 elements each.
Once the pointers that one statement restricts to their candidates have
65536 candidate values in total, assign the remaining pointers arbitrary
values instead (which is sound, as for pointers with more than 64
candidates), and print a warning. The program above now takes 15 s and
1.4 GB. Index the candidates by the type they point to, plus the candidates
of type `void *` or `char *`, which are compatible with all pointers; the
order of the candidates is unchanged. 64 types with 30 elements take 8.3 s
instead of 9.1 s, 16 types 1.9 s as before.
The new test inline_asm_havoc_reachable_budget has 17 types with 63
elements (1071 pointers with 64 candidates each) and checks that the
pointers beyond the bound may point anywhere.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
havoc_reachable changes the objects that the value sets of the reachable
pointers point to. Two kinds of memory that C code accesses have no address
in the value sets, and kept their values:
- Dereferencing a pointer variable p whose target is not known (or invalid)
yields its failed object p$object. For `int *gp = ext();` with a function
ext without a body, `*gp = 1; asm volatile("cli" ::: "memory");` followed
by `assert(*gp == 1)` gave VERIFICATION SUCCESSFUL (with
--no-standard-checks), and likewise for a struct behind such a pointer,
and for `"r"(gp + 1)` as an operand without a "memory" clobber.
- Memory at integer addresses, such as the memory-mapped register in
`*(volatile int *)0x10000 = 1; asm volatile("movl $0, 0x10000" ::: "memory");
assert(*(volatile int *)0x10000 == 1);`, which CBMC models as the array
__CPROVER_memory. static_lifetime_objects excludes it, as it excludes all
objects with the __CPROVER_ prefix. The assertion failed natively but held
in CBMC.
Now the statement also changes the failed objects of the reachable pointer
variables (of the operands, and of the pointers computed from them by
pointer arithmetic and casts), also if they point to a constant type, and
follows the pointers stored in them. Failed objects are no candidate values
of pointers, as their address is not known, and neither are the previous
values of the pointers stored in them, as these are mostly not written: in
the test inline_asm_havoc_reachable, the failed object head$object of
`struct node *head` made `head` take the unknown value of head$object.next,
and dereferencing it failed. It changes __CPROVER_memory if the statement
may access arbitrary memory, or if a reachable pointer may point to an
integer address.
The message about pointers with unknown targets was a debug message, and
was printed for all of them. It is now a warning, printed only if an
operand whose targets are not known is no pointer variable (such as a
pointer read from memory that was not written). Dereferencing other
pointers with unknown targets (such as members) yields a fresh object each
time, so no value is kept. The manual describes this, and that the static
analyses do not take the statement to change these objects.
cbmc on a program with 3000 objects of static lifetime of each of int,
int * and a struct with an int * member, and two statements, takes 9.6 s
instead of 9.0 s.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A pointer stored in an object that havoc_reachable changes, and that has
more than 64 candidate values, is assigned an arbitrary value: a temporary
that is never assigned, with the value set of a nondeterministic pointer,
which is the union of the objects in all value sets (and null). That union
lacks the reachable objects whose address no pointer holds, although the
statement may store their addresses. With 70 int variables of static
lifetime and `int *p = &g00`, `asm volatile("cli" ::: "memory")` followed
by `g69 = 0; *p = 1; assert(g69 == 0);` gave VERIFICATION SUCCESSFUL (with
--no-standard-checks; with the default checks, the assertion was UNKNOWN):
dereferencing p could not yield g69.
Add the reachable objects of a type compatible with the pointer's type (with
an unknown offset) to the shared value set: these are the objects whose
start addresses the pointer has as candidates when it is restricted to its
candidates. The shared value set is now computed once per statement and
target type. Adding all reachable objects instead made cbmc take 9.7 s
instead of 0.9 s on 300 objects of static lifetime of each of int, int *,
and a struct with an int * member (and 275 s instead of 35 s for 2000
each), as dereferencing an int * after the statement then considered the
pointers and structs as well. With compatible types only, the times are
unchanged (0.9 s, 35 s; 15 s for 128 struct types with 60 elements each).
The test inline_asm_havoc_reachable_candidates now writes through p.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
havoc_reachable splits the objects it changes into their pointers, which
are assigned a choice among candidate values or an arbitrary pointer, and
the other parts, which are assigned nondeterministic values. Unions, and
arrays of more than 64 elements or of a size that is not constant, are not
split, and were assigned a nondeterministic value as a whole. The value
set of a pointer in a union then had only an unknown target, which
dereferencing turns into a fresh object, and that of an element of a large
array kept its previous targets. For `union U { int *p; long l; } u;`,
`u.p = &x; asm volatile("cli" ::: "memory"); y = 0; *u.p = 5;` followed by
`assert(y == 0)` gave VERIFICATION SUCCESSFUL (with --no-standard-checks),
as did the same with `int *big[100]` instead of the union, although the
statement may store &y in u.p or in big[0].
After assigning such a part, also assign each pointer it contains an
arbitrary pointer, whose value set contains every object whose address is
stored anywhere and the reachable objects of a compatible type. For arrays,
the element at a nondeterministic index stands for all elements, as
assignments to array elements add to the value set. Members of unions are
accessed by byte extraction, as goto programs access them (rewrite_union).
The part's value remains nondeterministic, as the arbitrary pointers are
unconstrained. A warning is printed, as for pointers with more than 64
candidates. The manual already said that such pointers are assigned
arbitrary values.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The value set analyses give a pointer that havoc_reachable may change an
unknown target instead of listing more than 64 candidate objects, which no
test checked. Symbolic execution with path exploration (where the
statement is executed with the value set of each path) is checked by CI's
cbmc-paths-lifo profile, which runs all CORE tests of regression/cbmc with
--paths lifo, but not when running the suite with test.pl directly.
The new test show-value-sets-havoc-reachable-unknown (goto-instrument) has
70 int objects of static lifetime and a pointer to one of them: after the
statement, its value set is its previous target and unknown, while a
pointer with two candidates lists them. inline_asm_havoc_reachable now also
has a descriptor with --paths lifo, which pins the same verdicts.
The manual of the approximation that this series replaces said that objects
of static lifetime that are added when linking the CPROVER library are not
changed, which was true when the approximation assigned the objects of
static lifetime explicitly before linking. Symbolic execution now finds the
objects of static lifetime when it executes the statement, after linking,
and changes those of the library as well (for example, optind for getopt,
checked with cbmc on a program that reads optind before and after
`asm volatile("cli" ::: "memory")`), except those whose names start with
__CPROVER_. The manual dropped the sentence without saying this. It now
does, including that this excludes __CPROVER_errno, the model of errno, so
that the approximation assumes that the statement does not change errno.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
CI runs the CORE tests of regression/cbmc also with the new SMT backend (--incremental-smt2-solver 'z3 --smt2 -in'), except those tagged no-new-smt. With z3, inline_asm_havoc_reachable_array took 57 s and inline_asm_havoc_reachable_budget 31 s (with the SAT backend: 1 s and 2.5 s; with --cprover-smt2: 5 s and 8 s). Both check what symbolic execution generates, not the solver, so tag them no-new-smt. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An asm goto statement may jump to one of the C labels it lists. Goto conversion kept it as an OTHER instruction, followed by the next statement, so the jumps were lost: code after the labels was only reached in other ways, and properties there could be reported as holding when they do not. Goto conversion now introduces a variable that the translation of the statement sets to the (1-based) index of the label it jumps to, or to 0 if it does not jump. After the statement, it dispatches on this variable with ordinary gotos, which are converted like any other goto, so leaving scopes is handled as usual. remove_asm sets the variable as follows: - for a statement whose instructions are all modeled, to 0, as none of the modeled instructions jumps; - for a statement that is approximated, to a nondeterministic value, so that it may jump to any of its labels or fall through. The variable is the optional sixth operand of code_asm_gcct (has_goto_target, goto_target, add_goto_target), not a named sub-tree. Passes that rename the symbols of a function, such as goto-cc --export-file-local-symbols for file-local functions, rename operands, but not named sub-trees. With a named sub-tree, symbolic execution would fail to find the variable in a renamed function, as the Linux kernel's static keys (arch_static_branch) show. The test goto-cc-file-local/asm-goto covers this. The gotos have code of their own, which relies on the fix to finish_gotos of diffblue#9495: without it, valgrind reports a use-after-free in finish_gotos for an asm goto that leaves a block with local variables. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The test asserted x <= 1 for the _Bool result of arch_static_branch, which holds whether or not the asm goto jumps. It caught the crash of symbolic execution when renaming the file-local symbols missed the variable that selects the label, but not a dispatch that is lost, in which case control always falls through to "return 0". Add an assertion x == 0 that is expected to fail, as the approximated statement may jump to l_yes, and pin the verdicts of both assertions. With goto-cc and cbmc of the layer below (no asm goto handling), the new assertion holds and the test fails. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Goto conversion lowers the jumps of an asm goto statement to ordinary gotos so that leaving a scope is handled like for any other goto, but no test covered an asm goto that leaves a block with local variables, or one that jumps backwards. The new test inline_asm_goto_scope has an asm goto that jumps out of a block whose local y has escaped through a global pointer: a dereference of that pointer after the jump fails with "dead object", which shows the DEAD instructions on the jump path. A second asm goto jumps back to a label before its block, forming a loop that is taken at most twice. Both choose whether to jump from a nondeterministic operand, so the verdicts do not depend on whether their instructions are modeled. The test runs with --validate-goto-model --validate-ssa-equation. With cbmc of the layer below (no asm goto handling), the jumps are lost and the test fails. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
expr2c printed an asm goto statement as a plain asm statement, without
"goto" and the labels. Since goto conversion now dispatches on a variable
that the translation of the statement sets, goto-instrument --dump-c
produced, for asm goto("nop" : : : : out),
unsigned int tmp_asm_goto_target;
asm("nop" : : : );
if(!(tmp_asm_goto_target == 1u))
so the dumped program lost the jumps of the statement and branched on a
variable that nothing assigns: compiled natively it reads an
indeterminate value, and compiled with goto-cc again the modeled "nop"
statement, which does not jump, may jump.
expr2c now prints "asm goto(...)" with the labels as the fifth list, and
still does not print the variable, which is internal to CBMC. In C the
statement jumps to the label directly, so dump-c also assigns 0 ("no
jump") to the variable before the statement, and the dispatch that
follows is only reached when the statement falls through.
The test goto-instrument/dump-asm-goto compiles the output of --dump-c
again and checks that a modeled asm goto still does not jump and that an
approximated one may still jump or fall through. It uses gcc-only syntax,
so the goto-instrument suite now excludes gcc-only tests on Windows, as
the cbmc suite does.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
convert_asm had grown to about 80 lines: it cleans side effects in the operands, emits the OTHER instruction, and builds the dispatch on the variable that selects the label an asm goto jumps to. Move the dispatch into convert_asm_goto_dispatch, whose documentation states the convention that the translation of the statement (remove_asm) relies on: the variable holds the 1-based index of the label the statement jumps to, or 0 if it does not jump. No change in behaviour: goto-instrument --show-goto-functions and cbmc --show-goto-functions print the same programs as before for the asm goto regression tests and for an asm goto with two __label__ local labels. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The tests of the architecture-independent translation and of the conservative approximation of inline assembly use x86 instructions without pinning the architecture, so their results would change once CBMC interprets the instructions of the configured architecture, which is the host's by default. Run the cbmc and goto-analyzer tests with --arch riscv64, which has no instruction semantics; unlike for x86 or Power, CBMC then passes no -m32 or -m64 option to the host's preprocessor, which would fail on hosts of other architectures (such as arm64 CI runners). goto-instrument has no --arch option, so the goto-instrument and goto-cc-goto-analyzer tests use an instruction that does not exist instead. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Apart from fences, the x87 control word, and no-ops, remove_asm approximated every inline assembly statement, so that the values it computes, and the memory it writes, became nondeterministic. Inline assembly in kernel and library code (atomics, bit operations, byte swaps, spin locks) thus made verification imprecise, and spin loops around approximated lock acquisitions unwound to the bound. On x86 (--arch i386, x86_64, or x32), interpret GCC-style statements whose instructions CBMC's x86 semantics support, translating them into goto- program instructions with the same effect on the C program state. Other statements are translated or approximated as before. The interpretation consists of: - asm_operandst: the constraints of the operands, classified as register, memory, immediate, or flag outputs; - split_asm_template: the instructions of the template, with %N, %[name], and %lN references and local labels resolved; - asm_lowering_contextt: the goto code being built, with block-local storage of register operands, hardware registers, and flags; - asm_semanticst and its x86 implementation: data movement, arithmetic and logic with flags, shifts, bit operations, atomics, condition codes, branches within the statement and to the labels of asm goto, fences, and the x87 control word. To be sound, a statement is not interpreted (and hence approximated) when it contains instructions in another section, such as exception fixups, which run when an instruction faults; when it writes a register that is neither bound to an operand nor clobbered, which may be a register variable the front end does not record; or when an input tied to a memory output is a different object. Instructions with 64-bit operands are not interpreted in 32-bit mode. A lock-prefixed instruction (or xchg with a memory operand) is an atomic section of its own: making the whole statement atomic would hide races on its other instructions. The x86 semantics model values that the architecture leaves undefined as nondeterministic: a 32-bit cmpxchg writes only one of accumulator and destination (a 32-bit register write zero-extends), and bsf/bsr with a zero source may leave any value in the whole destination register. The overflow flag of 1-bit shifts and rotates is defined. A sub-register input operand is zero-extended unless a reference to it reads more bits, so that a constant input stays constant: otherwise, a lock word written through such an operand would become symbolic, and the spin loops of a lock would unwind to the bound. The code of the instructions has the checks for undefined behaviour of C disabled, as the hardware defines the results of wrapping arithmetic and of large shifts; the inputs are also evaluated at the statement's location, so that the checks apply to the C expressions of the operands. Register inputs that are arrays decay to pointers. Based on the inline assembly support developed for the analysis of Linux kernel code, with fixes for the problems found in its review. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The interpretation of inline assembly models values it cannot know as
nondeterministic: hardware registers that the statement does not
initialise, rdtsc and the like, and output operands read before they are
written. That over-approximates the values, but not memory accesses at
addresses computed from them: CBMC cannot relate a nondeterministic integer
to the objects it may point to, so a store through such an address changed
no object.
This made, for example,
register int *p asm("rcx") = &x;
asm volatile("movl %0, (%%rcx)" : : "r"(5), "r"(p) : "memory");
leave x unchanged, while on hardware x is 5: GCC places the register
variable p in rcx, which the front end does not record.
Track, per position in the statement, which symbols may hold such a value
(asm_lowering_contextt::depends_on_unknown), and do not interpret a
statement that accesses memory at an address that may depend on one, so
that it is approximated. An unconditional assignment of a known value makes
its target known; a value stored to memory makes all loaded values unknown;
a label joins the fall-through state with the states of the forward
branches to it; and a backward branch must not make a value unknown that
its target took as known. Statements that initialise the registers they
use as addresses from operands remain interpreted.
As the semantics report such failures via asm_lowering_contextt::fail
while lowering an instruction otherwise, lower_instructions now checks the
context for a failure after each instruction and label.
The results of the regression test were validated natively on x86-64.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Data in another section (between .pushsection and .popsection) was ignored. Data there that refers to a label of the statement records that label for run-time patching or as the continuation of a fault. Linux's arch_static_branch_jump, `1: jmp %l[l_yes]` with a __jump_table entry for 1b, was interpreted as always jumping, although the kernel patches the jmp into a nop when the key is disabled, so the other path was proved unreachable. Likewise, the fault path of a store with an __ex_table entry (as in __put_user_goto) was unreachable. lower_instructions now fails, so that the statement is approximated and an asm goto may jump to any of its labels, when data in another section refers to a local label of the statement, a label it defines, or a C label of asm goto. The lock prefixes recorded in .smp_locks (Linux's LOCK_PREFIX), which the kernel replaces by a no-op prefix on a single processor, and the sections that the linker discards (.discard.*) stay interpretable. The check is architecture-independent, so it also applies to the static branches of other architectures, such as arm64's `1: nop` with a __jump_table entry. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A register input narrower than its register was zero-extended unless a reference to that operand read it at a wider width. The bits above the input's width are unspecified, and they could also be read through the register in other ways, so that CBMC proved properties that fail on hardware: - through an output tied to the input: `addl $1, %0` with "=r"(r) and "0"(c) for a signed char c (GCC -O2 sign-extends c); - by the name of the register: `movl %%ecx, %0` with "c"((signed char)y); - with %h, which reads bits 8 to 15: reference_widens treated %h of an 8-bit input as reading 8 bits; - by an instruction that reads the register implicitly (cwtl on "a"); - as the output that shares the register (`""` with "=r"(r) and "0"((unsigned char)x)). prepare now computes, for each register, the number of low-order bits that may be read: by references to any operand held in it (via the new asm_semanticst::reference_bits, whose default is derived from reference_widens), by register names (register_name_bits), by instructions that read it implicitly (implicit_reads; on x86, the accumulator of cmpxchg and of the sign extensions), and by the outputs assigned from it. An input's upper bits are nondeterministic if any of these exceeds its width; otherwise the input is zero-extended as before, which keeps constant inputs constant. The upper bits of narrow inputs leave bit extractions in the formulas of asm_x86 and asm_x86_narrow_inputs, which the new SMT backend does not support yet, so these tests are tagged no-new-smt. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Two mistakes made CBMC compute different constants than the hardware: - The modifier of an operand reference after `$` was ignored, so `addl $%n1, %0` with "i"(5) added 5, whereas GCC prints %n as the negated constant and the instruction adds -5. - Numbers were read as decimal unless they started with 0x, whereas GAS reads a leading 0 as octal and 0b as binary: `addl $010, %0` added 10 instead of 8, and `movl 010(%1), %0` read at offset 10 instead of 8. Binary numbers made the statement fail to parse. The tokenizer now reads 0x, 0b (unless it refers to the local label 0, as GAS decides), and leading-0 numbers as GAS does, and rejects octal numbers with the digits 8 or 9. After `$`, the x86 semantics accept the modifiers that print a bare constant (%c, %P) and %n, which negates, and fail on any other (without a modifier, GCC prints the `$` of the immediate as well, which GAS reads as a symbol). Displacements also accept %n. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
Without a size suffix, the operand size of an x86 instruction was taken from a register operand or else from the C type of a memory operand, and the count register of a shift counted as a register operand. GAS does not see C types: without a suffix and a register operand, it uses a default size or rejects the instruction. On x86-64 hardware, `shl %%cl, %0` on "+m"(unsigned) shifts 32 bits (CBMC: 8, the size of %cl), `add $1, %0` on "+m"(long) adds 32 bits (CBMC: 64), and `movzx %1, %0` on "m"(short) reads a byte (CBMC: 16 bits), so CBMC proved properties that fail. operation_width no longer uses the C type of a memory operand, so such statements are approximated, and the size of a shift is that of its destination only. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
An operand whose constraint allows a register and memory ("rm", "g") was
always modelled as a register, on the grounds that the effect is the same
either way. It is not: GCC 13 on x86-64 chooses a register for a global
at -O0 and the global's memory at -O2, and
- `movl $1, %k0` with "+rm"(gx) for a long gx clears the upper half of a
register, but not of memory, so CBMC proved gx == 1;
- `btl %2, %1` with "rm"(p->word) and a bit offset of 32 takes the offset
modulo 32 in a register, but addresses the next word in memory;
- an operand that may be an immediate ("ri", "g") is sign-extended to the
width the instruction reads, as in `addq %1, %0` with "g"(-1), whereas
the register was zero-extended;
- only the first alternative of a constraint such as "r,m" was used.
remove_asmt::lower_gcc now lowers every combination of register and
memory for the operands that allow both (up to three such operands;
otherwise the statement is approximated) and chooses one of them
nondeterministically. An rvalue input in memory is a temporary object.
The x86 semantics accept size modifiers on memory operands, which GCC
prints the same way as without one. They fail if an operand that may be
an immediate is read at a width other than its own or from bits 8 to 15,
or is the bit offset of a bit-string operation in memory, unless its
constraint keeps immediates below the operand size (as "I" does for btl
and btq). Constraints with several alternatives are approximated.
Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
The operand storage of the lowering gives every operand a register of its own. GCC does not: it assumes that the instructions read all inputs before they write an output without the earlyclobber modifier `&`, and may allocate such an output to the register of an input or of the address of a memory operand; and it assumes that input-only operands are not changed, and may hold two inputs with the same value in one register. With -O2, GCC 13 on x86-64 does so for - `movl $1, %0; movl %2, %1` with "=r"(a), "=r"(b), "r"(c): a and c share a register, so b is 1, but CBMC proved b == c; - `incl %1; movl %2, %0` with "r"(x), "r"(x): both inputs share one register, so the result is x + 1, but CBMC proved it to be x; - `addq $8, %0; movq %2, %1` with "+r"(p) and "m"(*p): p and the address of *p share a register, so the load reads p[1], but CBMC proved p[0]. The same holds on other architectures, for example for AArch64's `mov %0, #1; add %0, %0, %1` with "=r"(out), "r"(in). asm_lowering_contextt now records, per instruction, the writes of register outputs without `&` and the reads of register inputs and of the addresses of memory operands, and the backward branches. It fails, so that the statement is approximated, if an instruction writes an input-only register operand, or reads such an input or address after an instruction wrote such an output, in sequence or in a later iteration of a loop. An output that holds its own value when the statement starts (+, or tied to an input) can share a register only with an operand that GCC knows to have the same value, which its register allocator only knows for operands of the same machine mode, so only operands of its width (or the width of an input tied to it) count for such outputs; this keeps, for example, a spin lock that reads a memory operand after writing the 32-bit lock value interpreted. The check is independent of the architecture. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
goto-cc and goto-gcc accepted -masm=intel without effect, so that cbmc read the templates of a goto binary compiled with it as AT&T syntax, in which the operands are in the opposite order: `sub %0, %1` with "+r"(a) and "+r"(b) subtracts b from a with -masm=intel, but CBMC proved that a is unchanged. gcc_mode now sets config.ansi_c.asm_dialect from -masm, and the C front end records it on each GCC-style asm statement as ID_asm_dialect, so that it survives into goto binaries that other tools process. remove_asm does not interpret statements in a dialect other than AT&T, nor templates that switch to Intel syntax with .intel_syntax (in any section, as the directive applies to all that follows); they are approximated. The goto-cc-cbmc test driver now passes the options before " _ " to goto-cc, and that suite skips gcc-only tests with Visual Studio. Co-authored-by: Kiro <kiro-agent@users.noreply.github.com>
A store relative to %fs or %gs was dropped as "not visible to the C program". The segment base is not modeled, and with a base of zero (as for %gs in x86-64 Linux user space) such a store changes the object at the address: `movl $5, %%gs:%0` with "=m"(x) sets x to 5 natively, but CBMC proved x unchanged. The x86 semantics now fail, so that the statement is approximated, on a segment-relative store to a memory operand, and on any segment-relative store in a statement with a "memory" clobber or a memory output. Other segment-relative stores change no C object, as GCC's operand contract requires, and remain modeled as having no effect; loads remain nondeterministic. x86_operandt::lvalue is now nil unless the operand is bound to a C lvalue, as the new check relies on. 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>
tautschnig
force-pushed
the
up/asm-x86
branch
from
December 2, 2026 06:21
0dedb13 to
e28cb88
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: #9499
Apart from fences, the x87 control word, and no-ops, remove_asm
approximated every inline assembly statement, so that the values it
computes, and the memory it writes, became nondeterministic. Inline
assembly in kernel and library code (atomics, bit operations, byte swaps,
spin locks) thus made verification imprecise, and spin loops around
approximated lock acquisitions unwound to the bound.
On x86 (--arch i386, x86_64, or x32), interpret GCC-style statements whose
instructions CBMC's x86 semantics support, translating them into goto-
program instructions with the same effect on the C program state. Other
statements are translated or approximated as before. The interpretation
consists of:
memory, immediate, or flag outputs;
and %lN references and local labels resolved;
storage of register operands, hardware registers, and flags;
logic with flags, shifts, bit operations, atomics, condition codes,
branches within the statement and to the labels of asm goto, fences, and
the x87 control word.
To be sound, a statement is not interpreted (and hence approximated) when
it contains instructions in another section, such as exception fixups,
which run when an instruction faults; when it writes a register that is
neither bound to an operand nor clobbered, which may be a register
variable the front end does not record; or when an input tied to a memory
output is a different object. Instructions with 64-bit operands are not
interpreted in 32-bit mode. A lock-prefixed instruction (or xchg with a
memory operand) is an atomic section of its own: making the whole
statement atomic would hide races on its other instructions.
The x86 semantics model values that the architecture leaves undefined as
nondeterministic: a 32-bit cmpxchg writes only one of accumulator and
destination (a 32-bit register write zero-extends), and bsf/bsr with a zero
source may leave any value in the whole destination register. The overflow
flag of 1-bit shifts and rotates is defined.
A sub-register input operand is zero-extended unless a reference to it reads
more bits, so that a constant input stays constant: otherwise, a lock word
written through such an operand would become symbolic, and the spin loops of
a lock would unwind to the bound. The code of the instructions has the
checks for undefined behaviour of C disabled, as the hardware defines the
results of wrapping arithmetic and of large shifts; the inputs are also
evaluated at the statement's location, so that the checks apply to the C
expressions of the operands. Register inputs that are arrays decay to
pointers.
A second commit makes the interpretation sound for memory accesses at
addresses computed from values that CBMC models as nondeterministic:
hardware registers that the statement does not initialise, the results of
rdtsc and the like, and output operands read before they are written. CBMC
cannot relate a nondeterministic integer to the objects it may point to, so
a store through such an address changed no object. For example,
register int *p asm("rcx") = &x;followed byasm volatile("movl %0, (%%rcx)" : : "r"(5), "r"(p) : "memory");leftxunchanged, while on hardware
xis 5 (GCC places the register variable inrcx, which the front end does not record). The lowering now tracks, per
position in the statement and across branches, loops, and memory, which
values may be unknown, and approximates statements that access memory at an
address that may depend on one; statements that initialise the registers
they use as addresses from operands remain interpreted. lower_instructions
also checks the lowering context for a failure after each instruction and
label, as the semantics report such failures without failing the
instruction. The new test asm_unknown_address was validated natively on
x86-64.
The interpretation tests are
gcc-only, as Visual Studio mode does notparse GCC-style inline assembly, and their x86 sources are preprocessed
(
main.i), as preprocessing for x86 passes-m64or-m32to the host'scompiler, which fails on arm64 hosts. For the same reason, the tests that pin
an architecture without semantics use
--arch riscv64. regression/cbmc-concurrency now skipsgcc-onlytests under Visual Studio, as regression/cbmc already does.Based on the inline assembly support developed for the analysis of Linux
kernel code, with fixes for the problems found in its review.
Co-authored-by: Kiro kiro-agent@users.noreply.github.com
Update after a review of the whole inline-assembly stack
This PR is now stacked on the PR below it. The commits added in this round each describe the problem they fix and how they were validated:
Design notes: where the statement cannot be interpreted exactly, it is approximated soundly instead of being rejected. This applies to statements whose labels are referenced from other sections (except
.smp_locksand.discard.*), to statements that rely on more than GCC's operand contract guarantees (outputs without&written before an input is read), and to statements whose output addresses depend on other outputs. For register-or-memory (rm) operands, both alternatives are lowered and one is chosen nondeterministically.