Repository navigation
Inline assembly: interpret AArch64 instructions - #9502
Draft
tautschnig wants to merge 69 commits into
Draft
tautschnig wants to merge 69 commits into
tautschnig wants to merge 69 commits into
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #9502 +/- ##
===========================================
+ Coverage 81.29% 81.62% +0.33%
===========================================
Files 1725 1744 +19
Lines 191680 195924 +4244
Branches 73 74 +1
===========================================
+ Hits 155835 159932 +4097
- Misses 35845 35992 +147 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
tautschnig
force-pushed
the
up/asm-aarch64
branch
from
November 17, 2026 08:44
ab32883 to
591d11c
Compare
4 of 6 tasks
tautschnig
force-pushed
the
up/asm-aarch64
branch
3 times, most recently
from
November 17, 2026 19:14
ca74631 to
d66714d
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>
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>
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>
tautschnig
force-pushed
the
up/asm-aarch64
branch
from
December 2, 2026 06:21
d66714d to
8c857e2
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: #9500
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:
instructions of the region form a single atomic section.
spurious failure. A stxr after a clrex or after another stxr fails
(status 1, no store), as the monitor is then clear.
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).
Memory accesses at addresses computed from values that are not modeled
(such as a register variable in an uninitialised register, or a system
register read by mrs) are approximated, as on x86 (see #9500).
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