From 931a93b653f2466bf9817164fe4a3a63172b98ac Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:08:14 +0000 Subject: [PATCH 001/100] Symex: havocking a string literal has no effect __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 --- .../cbmc/havoc_object_string_literal/main.c | 36 +++++++++++++++++++ .../havoc_object_string_literal/test.desc | 23 ++++++++++++ src/goto-symex/symex_other.cpp | 6 ++++ 3 files changed, 65 insertions(+) create mode 100644 regression/cbmc/havoc_object_string_literal/main.c create mode 100644 regression/cbmc/havoc_object_string_literal/test.desc diff --git a/regression/cbmc/havoc_object_string_literal/main.c b/regression/cbmc/havoc_object_string_literal/main.c new file mode 100644 index 000000000000..29961ad08735 --- /dev/null +++ b/regression/cbmc/havoc_object_string_literal/main.c @@ -0,0 +1,36 @@ +#include + +int main() +{ + char *s = "abc"; + int i = 0; + _Bool c; + char *p = c ? s : (char *)&i; + + // String literals cannot be modified, havocking them has no effect. + __CPROVER_havoc_object(s); + __CPROVER_assert(s[0] == 'a', "string literal unchanged"); + + __CPROVER_havoc_object(p); + __CPROVER_assert(i == 0, "i may be havocked"); // should fail + + // A pointer into the middle of a string literal. + __CPROVER_havoc_object(s + 1); + __CPROVER_assert(s[1] == 'b', "offset into string literal unchanged"); + + // Wide and Unicode string literals are arrays rather than string constants. + const wchar_t *w = L"abc"; + __CPROVER_havoc_object((void *)w); + __CPROVER_assert(w[0] == L'a', "wide string literal unchanged"); + + const unsigned short *u16 = (const unsigned short *)u"abc"; + __CPROVER_havoc_object((void *)u16); + __CPROVER_assert(u16[0] == 'a', "UTF-16 string literal unchanged"); + + const unsigned int *u32 = (const unsigned int *)U"abc"; + __CPROVER_havoc_object((void *)(u32 + 1)); + __CPROVER_assert( + u32[1] == 'b', "offset into UTF-32 string literal unchanged"); + + return 0; +} diff --git a/regression/cbmc/havoc_object_string_literal/test.desc b/regression/cbmc/havoc_object_string_literal/test.desc new file mode 100644 index 000000000000..9279523e0b41 --- /dev/null +++ b/regression/cbmc/havoc_object_string_literal/test.desc @@ -0,0 +1,23 @@ +CORE +main.c +--no-pointer-check +^EXIT=10$ +^SIGNAL=0$ +^\[main.assertion.1\] line 12 string literal unchanged: SUCCESS$ +^\[main.assertion.2\] line 15 i may be havocked: FAILURE$ +^\[main.assertion.3\] line 19 offset into string literal unchanged: SUCCESS$ +^\[main.assertion.4\] line 24 wide string literal unchanged: SUCCESS$ +^\[main.assertion.5\] line 28 UTF-16 string literal unchanged: SUCCESS$ +^\[main.assertion.6\] line 32 offset into UTF-32 string literal unchanged: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +Invariant check failed +-- +__CPROVER_havoc_object applied to a pointer to a string literal used to fail +an invariant in symbolic execution ("Attempted to symex havoc applied to +unsupported expression"). Narrow string literals are string constants, while +wide and Unicode string literals, and the part of a literal that a pointer +into its middle refers to, are arrays. The test uses --no-pointer-check, as +reading a wide string literal currently gives a spurious pointer check failure, +and makes the SMT2 back-end fail an invariant in convert_address_of_rec. diff --git a/src/goto-symex/symex_other.cpp b/src/goto-symex/symex_other.cpp index c5e046356bf5..fc797d41b36c 100644 --- a/src/goto-symex/symex_other.cpp +++ b/src/goto-symex/symex_other.cpp @@ -66,6 +66,12 @@ void goto_symext::havoc_rec( { havoc_rec(state, guard, to_member_expr(dest).struct_op()); } + else if(goto_symex_statet::is_read_only_object(dest)) + { + // Read-only objects, such as string literals (narrow ones are string + // constants, wide ones are arrays) and other constants, do not change, so + // there is nothing to havoc. + } else { INVARIANT_WITH_DIAGNOSTICS( From 7753c24fbcfea75386e864655a63726c02083c9a Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 30 Mar 2026 17:51:08 +0000 Subject: [PATCH 002/100] Document supported inline assembly instructions 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 --- doc/cprover-manual/index.md | 1 + doc/cprover-manual/modeling-inline-asm.md | 79 +++++++++++++++++++ regression/cbmc/inline_asm_dropped/main.c | 21 +++++ regression/cbmc/inline_asm_dropped/test.desc | 16 ++++ regression/cbmc/inline_asm_modeling/main.c | 33 ++++++++ regression/cbmc/inline_asm_modeling/test.desc | 25 ++++++ regression/validate-trace-xml-schema/check.py | 2 + 7 files changed, 177 insertions(+) create mode 100644 doc/cprover-manual/modeling-inline-asm.md create mode 100644 regression/cbmc/inline_asm_dropped/main.c create mode 100644 regression/cbmc/inline_asm_dropped/test.desc create mode 100644 regression/cbmc/inline_asm_modeling/main.c create mode 100644 regression/cbmc/inline_asm_modeling/test.desc diff --git a/doc/cprover-manual/index.md b/doc/cprover-manual/index.md index 12e1a9c046b7..83b0a2eb85ba 100644 --- a/doc/cprover-manual/index.md +++ b/doc/cprover-manual/index.md @@ -24,6 +24,7 @@ * [Floating Point](modeling/floating-point/) * [Generating Environments](goto-harness/) * [Memory-mapped I/O](modeling/mmio/) + * [Inline Assembly](modeling/inline-asm/) * [Shadow Memory](modeling/shadow-memory/) 8. Build Systems diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md new file mode 100644 index 000000000000..cb7b9dc66480 --- /dev/null +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -0,0 +1,79 @@ +[CPROVER Manual TOC](../../) + +## Modeling Inline Assembly + +CBMC supports GCC-style (`asm`/`__asm__`) and MSVC-style (`__asm {}`) +inline assembly syntax. During verification, the `remove_asm` pass +translates recognized instructions into equivalent goto-program +operations. + +**If an inline-assembly statement contains any unrecognized instruction, the +entire statement is replaced with `skip` — including any sibling instructions +in the same statement that would otherwise be translated.** For example, an +asm statement containing both an `mfence` and an `addl` loses *both*. This may +lead to unsound results if the assembly has side effects that matter for the +property being verified. + +### Supported Instructions + +#### x86 + +| Instruction | Effect in CBMC | +|---|---| +| `mfence` | Full memory fence | +| `lfence` | Full memory fence (currently modeled identically to `mfence`) | +| `sfence` | Full memory fence (currently modeled identically to `mfence`) | +| `fstcw` / `fnstcw` | Store FP control word (maps to `__CPROVER_rounding_mode`) | +| `fldcw` | Load FP control word (maps to `__CPROVER_rounding_mode`) | +| `lock` prefix | Only effective when followed by another recognized instruction (e.g. `lock; mfence`); the recognized instruction is wrapped in an atomic section with a full fence. The read-modify-write/exchange value itself is not modeled. | +| `xchg` / `xchgl` | Not modeled: the inline-assembly statement is dropped (treated as unrecognized). | + +#### ARM + +| Instruction | Effect in CBMC | +|---|---| +| `dmb` | Data memory barrier (full fence) | +| `dsb` | Data synchronization barrier (full fence) | +| `isb` | Empty fence; no observable effect unless combined with a branch | + +#### Power + +| Instruction | Effect in CBMC | +|---|---| +| `sync` | Full memory barrier | +| `lwsync` | Lightweight sync (all fences except write-after-read) | +| `isync` | Empty fence; no observable effect unless combined with a branch | + +### Operand Handling + +For GCC extended assembly, CBMC parses the output (`=r`, `+r`) and input +(`r`, `m`) operand lists, but in most cases the operand list does not +influence the generated goto program. For recognized fence instructions (for +example `mfence`, `lfence`, `sfence`, `dmb`, `dsb`, `sync`), the inline +assembly is replaced by a fence and the C-level output operands are not +written. For unrecognized instructions, the entire statement is replaced with +`skip`; output operands are **not** assigned nondeterministic values. Output +operands are only written when the modeled helper for a particular instruction +reads or writes through a pointer associated with that operand — currently +only `fstcw` / `fnstcw` / `fldcw`, which read or write `__CPROVER_rounding_mode`. +Clobber lists are parsed but do not affect verification. + +### Limitations + +- Only the instructions listed above are modeled. Any inline-assembly + statement that contains an unrecognized instruction is replaced with `skip` + in its entirety, **including any recognized instructions in the same + statement**. This can be unsound if the dropped assembly has side effects + relevant to the property being verified. +- No diagnostic is emitted for dropped assembly. Use + `goto-instrument --show-goto-functions` (or `cbmc --show-goto-functions`) to + inspect whether an inline-assembly statement was translated or dropped. +- For GCC-style inline assembly, complex atomic operations beyond the basic + `lock; ` pattern listed above are not modeled as + single atomic operations; in particular `xchg` and `lock`-prefixed + read-modify-write instructions (e.g. `lock addl`, `lock cmpxchgl`) are + dropped. +- MSVC-style `__asm` blocks are parsed, but only the x86 + `mfence` / `lfence` / `sfence`, `fstcw` / `fnstcw`, and `fldcw` instructions + are modeled. ARM and Power instructions and `lock` / `xchg` patterns are + **not** modeled for MSVC-style inline assembly. diff --git a/regression/cbmc/inline_asm_dropped/main.c b/regression/cbmc/inline_asm_dropped/main.c new file mode 100644 index 000000000000..7818e7326eb8 --- /dev/null +++ b/regression/cbmc/inline_asm_dropped/main.c @@ -0,0 +1,21 @@ +// Statements containing an unrecognized instruction are dropped entirely by +// the remove_asm pass -- including recognized siblings in the same statement +// (see doc/cprover-manual/modeling-inline-asm.md). This test pins that no +// fence/atomic/helper-call is emitted for any of them. +int main(void) +{ + int x = 0, y = 1; + + // xchg is not modeled: the statement is dropped. + asm volatile("xchg %0,%1" : "+r"(x), "+r"(y)); + + // lock followed by an unrecognized instruction: the whole statement is + // dropped (the atomic/fence wrapper is discarded too). + asm volatile("lock; addl $1, %0" : "+m"(x)); + + // A recognized mfence combined with an unrecognized addl: *both* are + // dropped, not just the addl. + asm volatile("mfence; addl $1, %0" : "+m"(x)); + + return 0; +} diff --git a/regression/cbmc/inline_asm_dropped/test.desc b/regression/cbmc/inline_asm_dropped/test.desc new file mode 100644 index 000000000000..9e0182308b83 --- /dev/null +++ b/regression/cbmc/inline_asm_dropped/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.c +--show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +-- +^warning: ignoring +CALL __asm_ +^ *FENCE +ATOMIC_BEGIN +-- +Pins that inline-assembly statements containing an unrecognized instruction +are dropped by the remove_asm pass: no fence, atomic section, or __asm_* +helper call is emitted -- including for "mfence; addl", where the recognized +mfence is dropped together with the unrecognized addl. +See GitHub issue diffblue/cbmc#6374. diff --git a/regression/cbmc/inline_asm_modeling/main.c b/regression/cbmc/inline_asm_modeling/main.c new file mode 100644 index 000000000000..26d306a51ac7 --- /dev/null +++ b/regression/cbmc/inline_asm_modeling/main.c @@ -0,0 +1,33 @@ +// Each statement below is processed independently by the remove_asm pass. +// This test pins the documented translation of the recognized instructions +// (see doc/cprover-manual/modeling-inline-asm.md) via the goto program shown +// by --show-goto-functions. +int main(void) +{ + unsigned short cw = 0; + + // x86 fences: modeled as calls to the __asm_* fence helpers. + asm volatile("mfence"); + asm volatile("lfence"); + asm volatile("sfence"); + + // ARM barriers: dmb/dsb are full fences, isb is an empty fence. + asm volatile("dmb"); + asm volatile("dsb"); + asm volatile("isb"); + + // Power barriers: sync is a full fence, lwsync omits write-after-read, + // isync is an empty fence. + asm volatile("sync"); + asm volatile("lwsync"); + asm volatile("isync"); + + // x86 FP control word: writes/reads __CPROVER_rounding_mode via the operand. + asm volatile("fstcw %0" : "=m"(cw)); + asm volatile("fldcw %0" : : "m"(cw)); + + // lock prefix followed by a recognized instruction: atomic section + fence. + asm volatile("lock; mfence"); + + return 0; +} diff --git a/regression/cbmc/inline_asm_modeling/test.desc b/regression/cbmc/inline_asm_modeling/test.desc new file mode 100644 index 000000000000..ed85c172885b --- /dev/null +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -0,0 +1,25 @@ +CORE gcc-only +main.c +--show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^ *CALL __asm_mfence\(\)$ +^ *CALL __asm_lfence\(\)$ +^ *CALL __asm_sfence\(\)$ +^ *CALL __asm_fstcw\( +^ *CALL __asm_fldcw\( +^ *FENCE WW RR RW WR$ +^ *FENCE WW RR RW$ +^ *FENCE$ +^ *ATOMIC_BEGIN$ +^ *ATOMIC_END$ +-- +^warning: ignoring +-- +Pins the documented translation of recognized inline-assembly instructions by +the remove_asm pass (see doc/cprover-manual/modeling-inline-asm.md): +x86 mfence/lfence/sfence -> __asm_* fence helper calls; ARM dmb/dsb and Power +sync -> full fence (WW RR RW WR); Power lwsync -> fence without WR; ARM isb / +Power isync -> empty fence; fstcw/fldcw -> __CPROVER_rounding_mode helpers; +lock-prefixed recognized instruction -> atomic section with a full fence. +See GitHub issue diffblue/cbmc#6374. diff --git a/regression/validate-trace-xml-schema/check.py b/regression/validate-trace-xml-schema/check.py index 674dec2e91c9..7048a2ca0bb3 100644 --- a/regression/validate-trace-xml-schema/check.py +++ b/regression/validate-trace-xml-schema/check.py @@ -30,6 +30,8 @@ ['destructors', 'enter_lexical_block.desc'], ['enum_is_in_range', 'enum_test3-simplified.desc'], ['enum_is_in_range', 'format.desc'], + ['inline_asm_dropped', 'test.desc'], + ['inline_asm_modeling', 'test.desc'], ['integer-assignments1', 'integer-typecheck.desc'], ['r_w_ok9', 'simplify.desc'], ['rational1', 'typecheck.desc'], From 9147084b12fd5a1bf3618f1a6d3b66dac57d67cf Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Wed, 10 Jun 2026 20:56:22 +0000 Subject: [PATCH 003/100] Warn when inline assembly is dropped 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 --- doc/cprover-manual/modeling-inline-asm.md | 3 ++- regression/cbmc/inline_asm_dropped/test.desc | 1 + src/assembler/remove_asm.cpp | 25 +++++++++++++++++--- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index cb7b9dc66480..e4475abeb57f 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -65,7 +65,8 @@ Clobber lists are parsed but do not affect verification. in its entirety, **including any recognized instructions in the same statement**. This can be unsound if the dropped assembly has side effects relevant to the property being verified. -- No diagnostic is emitted for dropped assembly. Use +- When an inline-assembly statement is dropped, CBMC emits a warning + identifying its source location. You can also use `goto-instrument --show-goto-functions` (or `cbmc --show-goto-functions`) to inspect whether an inline-assembly statement was translated or dropped. - For GCC-style inline assembly, complex atomic operations beyond the basic diff --git a/regression/cbmc/inline_asm_dropped/test.desc b/regression/cbmc/inline_asm_dropped/test.desc index 9e0182308b83..77ee8699402f 100644 --- a/regression/cbmc/inline_asm_dropped/test.desc +++ b/regression/cbmc/inline_asm_dropped/test.desc @@ -3,6 +3,7 @@ main.c --show-goto-functions ^EXIT=0$ ^SIGNAL=0$ +dropping inline assembly statement at .*: it contains an instruction that is not modeled -- ^warning: ignoring CALL __asm_ diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 43426ace3452..8cd5fdf36aaa 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -16,6 +16,7 @@ Date: December 2014 #include "remove_asm.h" #include +#include #include #include #include @@ -36,7 +37,8 @@ class remove_asmt message_handlert &message_handler) : symbol_table(_symbol_table), goto_functions(_goto_functions), - message_handler(message_handler) + message_handler(message_handler), + log(message_handler) { } @@ -50,6 +52,7 @@ class remove_asmt symbol_tablet &symbol_table; goto_functionst &goto_functions; message_handlert &message_handler; + messaget log; void process_function(const irep_idt &, goto_functionst::goto_functiont &); @@ -402,7 +405,15 @@ void remove_asmt::process_instruction_gcc( if(unknown) { - // we give up; we should perhaps print a warning + // The entire inline-assembly statement is dropped (turned into skip below) + // when any of its instructions is not recognized; warn so that the user is + // not left silently relying on un-modeled assembly. + log.warning() << "dropping inline assembly statement at " + << code.source_location() + << ": it contains an instruction that is not modeled, so the " + "whole statement (including any modeled instructions) is " + "removed" + << messaget::eom; } else dest.destructive_append(tmp_dest); @@ -530,7 +541,15 @@ void remove_asmt::process_instruction_msc( if(unknown) { - // we give up; we should perhaps print a warning + // The entire inline-assembly statement is dropped (turned into skip below) + // when any of its instructions is not recognized; warn so that the user is + // not left silently relying on un-modeled assembly. + log.warning() << "dropping inline assembly statement at " + << code.source_location() + << ": it contains an instruction that is not modeled, so the " + "whole statement (including any modeled instructions) is " + "removed" + << messaget::eom; } else dest.destructive_append(tmp_dest); From 598837a43ae9c4a014e508917a288b95598f320f Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Wed, 10 Jun 2026 21:03:40 +0000 Subject: [PATCH 004/100] Factor shared inline-assembly scaffolding in remove_asm 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 --- src/assembler/remove_asm.cpp | 451 ++++++++++++++++++----------------- 1 file changed, 234 insertions(+), 217 deletions(-) diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 8cd5fdf36aaa..b6a430002a78 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -28,6 +28,8 @@ Date: December 2014 #include "assembler_parser.h" +#include + class remove_asmt { public: @@ -68,6 +70,38 @@ class remove_asmt const code_asmt &, goto_programt &dest); + // Shared scaffolding for the gcc and msc flavors: parse the assembly text, + // handle the lock prefix and xchg, wrap locked instructions in an atomic + // section with a full fence, and either append the translation to \p dest or + // drop the whole statement (emitting a warning) if \p handle_command reports + // an unrecognized instruction. + void process_asm( + const code_asmt &code, + const irep_idt &assembly, + goto_programt &dest, + const std::function &handle_command); + + // Translates a single recognized gcc-style command, returning false if the + // command is not modeled. + bool handle_gcc_command( + const irep_idt &command, + const code_asm_gcct &code, + goto_programt &tmp_dest); + + // Translates a single recognized msc-style command, returning false if the + // command is not modeled. + bool handle_msc_command( + const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, + const irep_idt &function_id, + const code_asmt &code, + goto_programt &tmp_dest); + void gcc_asm_function_call( const irep_idt &function_base_name, const code_asm_gcct &code, @@ -242,18 +276,65 @@ void remove_asmt::process_instruction( DATA_INVARIANT(false, "unexpected assembler flavor"); } -/// Translates the given inline assembly code (in gcc style) to non-assembly -/// goto program instructions +/// Builds a `fence` codet with the requested ordering and cumulativity flags. +/// Only the flags set to true are added, matching the ireps that the individual +/// fence instructions used to construct by hand. +static codet make_fence( + const source_locationt &source_location, + bool ww, + bool rr, + bool rw, + bool wr, + bool ww_cumul = false, + bool rw_cumul = false, + bool rr_cumul = false, + bool wr_cumul = false) +{ + codet code_fence{ID_fence}; + code_fence.add_source_location() = source_location; + if(ww) + code_fence.set(ID_WWfence, true); + if(rr) + code_fence.set(ID_RRfence, true); + if(rw) + code_fence.set(ID_RWfence, true); + if(wr) + code_fence.set(ID_WRfence, true); + if(ww_cumul) + code_fence.set(ID_WWcumul, true); + if(rw_cumul) + code_fence.set(ID_RWcumul, true); + if(rr_cumul) + code_fence.set(ID_RRcumul, true); + if(wr_cumul) + code_fence.set(ID_WRcumul, true); + return code_fence; +} + +/// Shared scaffolding for translating gcc-style and msc-style inline assembly. +/// Parses \p assembly, and for each parsed instruction handles the `lock` +/// prefix and `xchg` (which start an atomic section containing a full fence), +/// delegates the actual command translation to \p handle_command, and closes +/// the atomic section. If any instruction is not recognized by +/// \p handle_command, the whole statement is dropped (a warning is emitted and +/// nothing is appended to \p dest); otherwise the translation is appended. /// -/// \param code: The inline assembly code statement to translate +/// \param code: The inline assembly code statement being translated +/// \param assembly: The assembly text to parse /// \param dest: The goto program to append the new instructions to -void remove_asmt::process_instruction_gcc( - const code_asm_gcct &code, - goto_programt &dest) +/// \param handle_command: Translates a single command into \p tmp_dest and +/// returns whether the command was recognized +void remove_asmt::process_asm( + const code_asmt &code, + const irep_idt &assembly, + goto_programt &dest, + const std::function &handle_command) { - const irep_idt &i_str = to_string_constant(code.asm_text()).value(); - - std::istringstream str(id2string(i_str)); + std::istringstream str(id2string(assembly)); assembler_parsert assembler_parser{message_handler}; assembler_parser.in = &str; assembler_parser.parse(); @@ -267,19 +348,9 @@ void remove_asmt::process_instruction_gcc( if(instruction.empty()) continue; -#if 0 - std::cout << "A ********************\n"; - for(const auto &ins : instruction) - { - std::cout << "XX: " << ins.pretty() << '\n'; - } - - std::cout << "B ********************\n"; -#endif - // deal with prefixes irep_idt command; - unsigned pos = 0; + std::size_t pos = 0; if( instruction.front().id() == ID_symbol && @@ -305,94 +376,12 @@ void remove_asmt::process_instruction_gcc( if(x86_32_locked_atomic) { tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); - - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - code_fence.set(ID_WWfence, true); - code_fence.set(ID_RRfence, true); - code_fence.set(ID_RWfence, true); - code_fence.set(ID_WRfence, true); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - } - - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 - { - gcc_asm_function_call("__asm_" + id2string(command), code, 1, tmp_dest); + tmp_dest.add(goto_programt::make_other( + make_fence(code.source_location(), true, true, true, true), + code.source_location())); } - else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 - { - gcc_asm_function_call("__asm_" + id2string(command), code, 0, tmp_dest); - } - else if(command == ID_sync) // Power - { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - code_fence.set(ID_WWfence, true); - code_fence.set(ID_RRfence, true); - code_fence.set(ID_RWfence, true); - code_fence.set(ID_WRfence, true); - code_fence.set(ID_WWcumul, true); - code_fence.set(ID_RWcumul, true); - code_fence.set(ID_RRcumul, true); - code_fence.set(ID_WRcumul, true); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - } - else if(command == ID_lwsync) // Power - { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - code_fence.set(ID_WWfence, true); - code_fence.set(ID_RRfence, true); - code_fence.set(ID_RWfence, true); - code_fence.set(ID_WWcumul, true); - code_fence.set(ID_RWcumul, true); - code_fence.set(ID_RRcumul, true); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - } - else if(command == ID_isync) // Power - { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - // doesn't do anything by itself, - // needs to be combined with branch - } - else if(command == "dmb" || command == "dsb") // ARM - { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - code_fence.set(ID_WWfence, true); - code_fence.set(ID_RRfence, true); - code_fence.set(ID_RWfence, true); - code_fence.set(ID_WRfence, true); - code_fence.set(ID_WWcumul, true); - code_fence.set(ID_RWcumul, true); - code_fence.set(ID_RRcumul, true); - code_fence.set(ID_WRcumul, true); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - } - else if(command == "isb") // ARM - { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - // doesn't do anything by itself, - // needs to be combined with branch - } - else + if(!handle_command(command, pos, instruction, tmp_dest)) unknown = true; // give up if(x86_32_locked_atomic) @@ -419,140 +408,168 @@ void remove_asmt::process_instruction_gcc( dest.destructive_append(tmp_dest); } -/// Translates the given inline assembly code (in msc style) to non-assembly +/// Translates the given inline assembly code (in gcc style) to non-assembly /// goto program instructions /// -/// \param function_id: Name of function being processed /// \param code: The inline assembly code statement to translate /// \param dest: The goto program to append the new instructions to -void remove_asmt::process_instruction_msc( - const irep_idt &function_id, - const code_asmt &code, +void remove_asmt::process_instruction_gcc( + const code_asm_gcct &code, goto_programt &dest) { - const irep_idt &i_str = to_string_constant(code.op0()).value(); - - std::istringstream str(id2string(i_str)); - assembler_parsert assembler_parser{message_handler}; - assembler_parser.in = &str; - assembler_parser.parse(); + process_asm( + code, + to_string_constant(code.asm_text()).value(), + dest, + [this, &code]( + const irep_idt &command, + std::size_t, + const assembler_parsert::instructiont &, + goto_programt &tmp_dest) + { return handle_gcc_command(command, code, tmp_dest); }); +} - goto_programt tmp_dest; - bool unknown = false; - bool x86_32_locked_atomic = false; +/// Translates a single recognized gcc-style command into \p tmp_dest. +/// +/// \param command: The instruction mnemonic to translate +/// \param code: The inline assembly code statement being translated +/// \param tmp_dest: The goto program to append the translation to +/// \return Whether the command was recognized (and hence modeled) +bool remove_asmt::handle_gcc_command( + const irep_idt &command, + const code_asm_gcct &code, + goto_programt &tmp_dest) +{ + const source_locationt &source_location = code.source_location(); - for(const auto &instruction : assembler_parser.instructions) + if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 { - if(instruction.empty()) - continue; - -#if 0 - std::cout << "A ********************\n"; - for(const auto &ins : instruction) - { - std::cout << "XX: " << ins.pretty() << '\n'; - } - - std::cout << "B ********************\n"; -#endif - - // deal with prefixes - irep_idt command; - unsigned pos = 0; - - if( - instruction.front().id() == ID_symbol && - instruction.front().get(ID_identifier) == "lock") - { - x86_32_locked_atomic = true; - pos++; - } - - // done? - if(pos == instruction.size()) - continue; - - if(instruction[pos].id() == ID_symbol) - { - command = instruction[pos].get(ID_identifier); - pos++; - } + gcc_asm_function_call("__asm_" + id2string(command), code, 1, tmp_dest); + } + else if( + command == "mfence" || command == "lfence" || command == "sfence") // x86 + { + gcc_asm_function_call("__asm_" + id2string(command), code, 0, tmp_dest); + } + else if(command == ID_sync) // Power + { + tmp_dest.add(goto_programt::make_other( + make_fence( + source_location, true, true, true, true, true, true, true, true), + source_location)); + } + else if(command == ID_lwsync) // Power + { + tmp_dest.add(goto_programt::make_other( + make_fence( + source_location, true, true, true, false, true, true, true, false), + source_location)); + } + else if(command == ID_isync) // Power + { + // doesn't do anything by itself, needs to be combined with branch + tmp_dest.add(goto_programt::make_other( + make_fence(source_location, false, false, false, false), + source_location)); + } + else if(command == "dmb" || command == "dsb") // ARM + { + tmp_dest.add(goto_programt::make_other( + make_fence( + source_location, true, true, true, true, true, true, true, true), + source_location)); + } + else if(command == "isb") // ARM + { + // doesn't do anything by itself, needs to be combined with branch + tmp_dest.add(goto_programt::make_other( + make_fence(source_location, false, false, false, false), + source_location)); + } + else + return false; - if(command == "xchg" || command == "xchgl") - x86_32_locked_atomic = true; + return true; +} - if(x86_32_locked_atomic) +/// Translates the given inline assembly code (in msc style) to non-assembly +/// goto program instructions +/// +/// \param function_id: Name of function being processed +/// \param code: The inline assembly code statement to translate +/// \param dest: The goto program to append the new instructions to +void remove_asmt::process_instruction_msc( + const irep_idt &function_id, + const code_asmt &code, + goto_programt &dest) +{ + process_asm( + code, + to_string_constant(code.op0()).value(), + dest, + [this, &code, &function_id]( + const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, + goto_programt &tmp_dest) { - tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); - - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); - code_fence.set(ID_WWfence, true); - code_fence.set(ID_RRfence, true); - code_fence.set(ID_RWfence, true); - code_fence.set(ID_WRfence, true); - - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - } + return handle_msc_command( + command, pos, instruction, function_id, code, tmp_dest); + }); +} - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 +/// Translates a single recognized msc-style command into \p tmp_dest. +/// +/// \param command: The instruction mnemonic to translate +/// \param pos: Index of the token following the command in \p instruction +/// \param instruction: The parsed instruction tokens +/// \param function_id: Name of function being processed +/// \param code: The inline assembly code statement being translated +/// \param tmp_dest: The goto program to append the translation to +/// \return Whether the command was recognized (and hence modeled) +bool remove_asmt::handle_msc_command( + const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, + const irep_idt &function_id, + const code_asmt &code, + goto_programt &tmp_dest) +{ + if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + { + exprt::operandst args{null_pointer_exprt{pointer_type(empty_typet{})}}; + // try to typecheck the argument + if(pos != instruction.size() && instruction[pos].id() == ID_symbol) { - exprt::operandst args{null_pointer_exprt{pointer_type(empty_typet{})}}; - // try to typecheck the argument - if(pos != instruction.size() && instruction[pos].id() == ID_symbol) + const irep_idt &name = instruction[pos].get(ID_identifier); + for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) { - const irep_idt &name = instruction[pos].get(ID_identifier); - for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) + // global scope symbol, don't replace a local one + if(entry.second == name && args[0].id() != ID_address_of) { - // global scope symbol, don't replace a local one - if(entry.second == name && args[0].id() != ID_address_of) - { - args[0] = - address_of_exprt{symbol_table.lookup_ref(name).symbol_expr()}; - } - // parameter or symbol in local scope - else if(has_prefix( - id2string(entry.second), id2string(function_id) + "::")) - { - args[0] = address_of_exprt{ - symbol_table.lookup_ref(entry.second).symbol_expr()}; - } + args[0] = + address_of_exprt{symbol_table.lookup_ref(name).symbol_expr()}; + } + // parameter or symbol in local scope + else if(has_prefix( + id2string(entry.second), id2string(function_id) + "::")) + { + args[0] = address_of_exprt{ + symbol_table.lookup_ref(entry.second).symbol_expr()}; } } - msc_asm_function_call( - "__asm_" + id2string(command), args, code, tmp_dest); - } - else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 - { - msc_asm_function_call("__asm_" + id2string(command), {}, code, tmp_dest); - } - else - unknown = true; // give up - - if(x86_32_locked_atomic) - { - tmp_dest.add(goto_programt::make_atomic_end(code.source_location())); - - x86_32_locked_atomic = false; } + msc_asm_function_call("__asm_" + id2string(command), args, code, tmp_dest); } - - if(unknown) + else if( + command == "mfence" || command == "lfence" || command == "sfence") // x86 { - // The entire inline-assembly statement is dropped (turned into skip below) - // when any of its instructions is not recognized; warn so that the user is - // not left silently relying on un-modeled assembly. - log.warning() << "dropping inline assembly statement at " - << code.source_location() - << ": it contains an instruction that is not modeled, so the " - "whole statement (including any modeled instructions) is " - "removed" - << messaget::eom; + msc_asm_function_call("__asm_" + id2string(command), {}, code, tmp_dest); } else - dest.destructive_append(tmp_dest); + return false; + + return true; } /// Replaces inline assembly instructions in the goto function by non-assembly From c645d50c98c099de7c780dc7f76e66ad6b7e4207 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:24:37 +0000 Subject: [PATCH 005/100] C front end: asm blocks that form a function body are gcc-style 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 --- regression/cbmc/asm_block_function_body/main.c | 15 +++++++++++++++ regression/cbmc/asm_block_function_body/test.desc | 12 ++++++++++++ src/ansi-c/parser.y | 6 +++++- 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 regression/cbmc/asm_block_function_body/main.c create mode 100644 regression/cbmc/asm_block_function_body/test.desc diff --git a/regression/cbmc/asm_block_function_body/main.c b/regression/cbmc/asm_block_function_body/main.c new file mode 100644 index 000000000000..f2370cf4dae2 --- /dev/null +++ b/regression/cbmc/asm_block_function_body/main.c @@ -0,0 +1,15 @@ +#ifdef __GNUC__ +// an asm block as a function body, as with gcc -fasm-blocks +void asm test() +{ + mov eax, eax +} +#endif + +int main() +{ +#ifdef __GNUC__ + test(); +#endif + return 0; +} diff --git a/regression/cbmc/asm_block_function_body/test.desc b/regression/cbmc/asm_block_function_body/test.desc new file mode 100644 index 000000000000..debc63cbcefb --- /dev/null +++ b/regression/cbmc/asm_block_function_body/test.desc @@ -0,0 +1,12 @@ +CORE +main.c + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +Invariant check failed +-- +An asm block that forms a function body (as with gcc -fasm-blocks) used to +have no assembler flavor, which made remove_asm fail an invariant. diff --git a/src/ansi-c/parser.y b/src/ansi-c/parser.y index 8b5df32cf803..ffa7d4d35bbd 100644 --- a/src/ansi-c/parser.y +++ b/src/ansi-c/parser.y @@ -2495,10 +2495,14 @@ compound_statement: } | compound_scope '{' TOK_ASM_STRING '}' { + // a block of assembly following the asm keyword, as in + // asm int f() { ... }: gcc-style basic assembly $$=$2; statement($$, ID_asm); + parser_stack($$).set(ID_flavor, ID_gcc); parser_stack($$).set(ID_C_end_location, parser_stack($4).source_location()); - mto($$, $3); + parser_stack($$).operands().resize(5); + to_multi_ary_expr(parser_stack($$)).op0()=parser_stack($3); PARSER.pop_scope(); } ; From f2023348923d6493d17a106bd0e892c51ccb9210 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:24:37 +0000 Subject: [PATCH 006/100] Goto conversion: make side effects in asm operands explicit 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 --- .../cbmc/asm_operand_side_effects/main.c | 26 +++++++++++++ .../cbmc/asm_operand_side_effects/test.desc | 11 ++++++ src/ansi-c/goto-conversion/goto_asm.cpp | 38 +++++++++++++++++-- src/ansi-c/goto-conversion/goto_convert.cpp | 2 +- .../goto-conversion/goto_convert_class.h | 3 +- 5 files changed, 75 insertions(+), 5 deletions(-) create mode 100644 regression/cbmc/asm_operand_side_effects/main.c create mode 100644 regression/cbmc/asm_operand_side_effects/test.desc diff --git a/regression/cbmc/asm_operand_side_effects/main.c b/regression/cbmc/asm_operand_side_effects/main.c new file mode 100644 index 000000000000..9888f50e4651 --- /dev/null +++ b/regression/cbmc/asm_operand_side_effects/main.c @@ -0,0 +1,26 @@ +int calls; + +int *f(int *p) +{ + ++calls; + return p; +} + +int g(void) +{ + ++calls; + return 1; +} + +int main() +{ + int m = 0; +#ifdef __GNUC__ + // the operands are evaluated exactly once, before the statement + __asm__ volatile("mfence" : "=m"(*f(&m)) : "r"(g())); +#else + calls = 2; +#endif + __CPROVER_assert(calls == 2, "operands are evaluated"); + return 0; +} diff --git a/regression/cbmc/asm_operand_side_effects/test.desc b/regression/cbmc/asm_operand_side_effects/test.desc new file mode 100644 index 000000000000..185c414c027d --- /dev/null +++ b/regression/cbmc/asm_operand_side_effects/test.desc @@ -0,0 +1,11 @@ +CORE +main.c + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +-- +Side effects in the operands of gcc-style inline assembly used to be lost, as +the operands were only kept in the (later removed) assembly statement. diff --git a/src/ansi-c/goto-conversion/goto_asm.cpp b/src/ansi-c/goto-conversion/goto_asm.cpp index 9b85ff0cb7f0..370f9cc68232 100644 --- a/src/ansi-c/goto-conversion/goto_asm.cpp +++ b/src/ansi-c/goto-conversion/goto_asm.cpp @@ -11,8 +11,40 @@ Author: Daniel Kroening, kroening@kroening.com #include "goto_convert_class.h" -void goto_convertt::convert_asm(const code_asmt &code, goto_programt &dest) +#include "destructor.h" + +void goto_convertt::convert_asm( + const code_asmt &code, + goto_programt &dest, + const irep_idt &mode) { - // copy as OTHER - copy(code, OTHER, dest); + if(code.get_flavor() != ID_gcc || code.operands().size() != 5) + { + // copy as OTHER + copy(code, OTHER, dest); + return; + } + + // The operands of a gcc-style statement are evaluated before the statement + // executes; side effects in them (function calls, assignments, statement + // expressions) need to be made explicit so that the lowering of the + // statement only sees side-effect free expressions. + code_asm_gcct new_code = to_code_asm_gcc(code); + clean_expr_resultt side_effects; + for(auto *list : {&new_code.outputs(), &new_code.inputs()}) + { + for(auto &operand : list->operands()) + { + if(operand.operands().size() != 2) + continue; + exprt &expr = to_binary_expr(operand).op1(); + if(needs_cleaning(expr)) + side_effects.add(clean_expr(expr, mode)); + } + } + dest.destructive_append(side_effects.side_effects); + + copy(new_code, OTHER, dest); + + destruct_locals(side_effects.temporaries, dest, ns); } diff --git a/src/ansi-c/goto-conversion/goto_convert.cpp b/src/ansi-c/goto-conversion/goto_convert.cpp index 036358751981..b934edefa568 100644 --- a/src/ansi-c/goto-conversion/goto_convert.cpp +++ b/src/ansi-c/goto-conversion/goto_convert.cpp @@ -694,7 +694,7 @@ void goto_convertt::convert( else if(statement == ID_CPROVER_try_finally) convert_CPROVER_try_finally(code, dest, mode); else if(statement == ID_asm) - convert_asm(to_code_asm(code), dest); + convert_asm(to_code_asm(code), dest, mode); else if(statement == ID_static_assert) { // C23 allows static_assert without message diff --git a/src/ansi-c/goto-conversion/goto_convert_class.h b/src/ansi-c/goto-conversion/goto_convert_class.h index 1d2a29aca3ec..e9a9cfaabcf5 100644 --- a/src/ansi-c/goto-conversion/goto_convert_class.h +++ b/src/ansi-c/goto-conversion/goto_convert_class.h @@ -357,7 +357,8 @@ class goto_convertt : public messaget const codet &code, goto_programt &dest, const irep_idt &mode); - void convert_asm(const code_asmt &code, goto_programt &dest); + void + convert_asm(const code_asmt &code, goto_programt &dest, const irep_idt &mode); void convert(const codet &code, goto_programt &dest, const irep_idt &mode); From d0484c5d00075c599b439a3908c7da9d71d7b902 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:25:47 +0000 Subject: [PATCH 007/100] remove_asm: model barriers and x87 control word operands precisely 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 --- .../cbmc/inline_asm_fpu_control_word/main.c | 13 + .../inline_asm_fpu_control_word/test.desc | 11 + regression/cbmc/inline_asm_modeling/main.c | 19 +- regression/cbmc/inline_asm_modeling/test.desc | 17 +- src/assembler/remove_asm.cpp | 514 ++++++++++-------- 5 files changed, 320 insertions(+), 254 deletions(-) create mode 100644 regression/cbmc/inline_asm_fpu_control_word/main.c create mode 100644 regression/cbmc/inline_asm_fpu_control_word/test.desc diff --git a/regression/cbmc/inline_asm_fpu_control_word/main.c b/regression/cbmc/inline_asm_fpu_control_word/main.c new file mode 100644 index 000000000000..d49c67cb770d --- /dev/null +++ b/regression/cbmc/inline_asm_fpu_control_word/main.c @@ -0,0 +1,13 @@ +int main(void) +{ + unsigned short old, new = 3 << 10; + + // fldcw uses its own operand (%1), not the first operand of the statement + asm volatile("fstcw %0; fldcw %1" : "=m"(old) : "m"(new)); + __CPROVER_assert((old >> 10 & 3) == 0, "initial rounding mode"); + + asm volatile("fstcw %0" : "=m"(old)); + __CPROVER_assert((old >> 10 & 3) == 3, "rounding mode set by fldcw"); + + return 0; +} diff --git a/regression/cbmc/inline_asm_fpu_control_word/test.desc b/regression/cbmc/inline_asm_fpu_control_word/test.desc new file mode 100644 index 000000000000..2b39abc611cb --- /dev/null +++ b/regression/cbmc/inline_asm_fpu_control_word/test.desc @@ -0,0 +1,11 @@ +CORE gcc-only +main.c + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +inline assembly statement at +-- +The x87 control word instructions are modeled using the operand they refer to. diff --git a/regression/cbmc/inline_asm_modeling/main.c b/regression/cbmc/inline_asm_modeling/main.c index 26d306a51ac7..2afcb491c524 100644 --- a/regression/cbmc/inline_asm_modeling/main.c +++ b/regression/cbmc/inline_asm_modeling/main.c @@ -11,23 +11,30 @@ int main(void) asm volatile("lfence"); asm volatile("sfence"); - // ARM barriers: dmb/dsb are full fences, isb is an empty fence. + // ARM barriers: dmb/dsb are full fences unless the option restricts them + // to loads (ld) or stores (st); isb is an empty fence. asm volatile("dmb"); - asm volatile("dsb"); + asm volatile("dsb sy"); + asm volatile("dmb ish" ::: "memory"); + asm volatile("dmb ishld"); + asm volatile("dsb ishst"); asm volatile("isb"); // Power barriers: sync is a full fence, lwsync omits write-after-read, - // isync is an empty fence. + // eieio orders stores, isync is an empty fence. asm volatile("sync"); asm volatile("lwsync"); + asm volatile("eieio"); asm volatile("isync"); + // Instructions without effect on the C program state. + asm volatile("nop"); + asm volatile("pause"); + asm volatile("yield"); + // x86 FP control word: writes/reads __CPROVER_rounding_mode via the operand. asm volatile("fstcw %0" : "=m"(cw)); asm volatile("fldcw %0" : : "m"(cw)); - // lock prefix followed by a recognized instruction: atomic section + fence. - asm volatile("lock; mfence"); - return 0; } diff --git a/regression/cbmc/inline_asm_modeling/test.desc b/regression/cbmc/inline_asm_modeling/test.desc index ed85c172885b..071b814941fe 100644 --- a/regression/cbmc/inline_asm_modeling/test.desc +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -6,20 +6,23 @@ main.c ^ *CALL __asm_mfence\(\)$ ^ *CALL __asm_lfence\(\)$ ^ *CALL __asm_sfence\(\)$ -^ *CALL __asm_fstcw\( -^ *CALL __asm_fldcw\( +^ *CALL __asm_fstcw\(cast\(address_of\(main::1::cw\), empty\*\)\)$ +^ *CALL __asm_fldcw\(cast\(address_of\(main::1::cw\), empty\*\)\)$ ^ *FENCE WW RR RW WR$ ^ *FENCE WW RR RW$ +^ *FENCE RR RW$ +^ *FENCE WW$ ^ *FENCE$ -^ *ATOMIC_BEGIN$ -^ *ATOMIC_END$ -- ^warning: ignoring +inline assembly statement at +ATOMIC_BEGIN -- Pins the documented translation of recognized inline-assembly instructions by the remove_asm pass (see doc/cprover-manual/modeling-inline-asm.md): x86 mfence/lfence/sfence -> __asm_* fence helper calls; ARM dmb/dsb and Power -sync -> full fence (WW RR RW WR); Power lwsync -> fence without WR; ARM isb / -Power isync -> empty fence; fstcw/fldcw -> __CPROVER_rounding_mode helpers; -lock-prefixed recognized instruction -> atomic section with a full fence. +sync -> full fence (WW RR RW WR); ARM dmb/dsb with an ld option -> RR RW, with +an st option -> WW; Power lwsync -> fence without WR; Power eieio -> WW; ARM +isb / Power isync -> empty fence; nop/pause/yield -> nothing; fstcw/fldcw -> +__CPROVER_rounding_mode helpers called with the address of the operand. See GitHub issue diffblue/cbmc#6374. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index b6a430002a78..6979a55eb9a8 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -22,13 +22,16 @@ Date: December 2014 #include #include #include +#include #include #include #include "assembler_parser.h" +#include #include +#include class remove_asmt { @@ -56,6 +59,14 @@ class remove_asmt message_handlert &message_handler; messaget log; + using instructionst = std::list; + + using handle_commandt = std::function; + void process_function(const irep_idt &, goto_functionst::goto_functiont &); void process_instruction( @@ -66,34 +77,27 @@ class remove_asmt void process_instruction_gcc(const code_asm_gcct &, goto_programt &dest); void process_instruction_msc( - const irep_idt &, + const irep_idt &function_id, const code_asmt &, goto_programt &dest); - // Shared scaffolding for the gcc and msc flavors: parse the assembly text, - // handle the lock prefix and xchg, wrap locked instructions in an atomic - // section with a full fence, and either append the translation to \p dest or - // drop the whole statement (emitting a warning) if \p handle_command reports - // an unrecognized instruction. - void process_asm( + instructionst parse(const irep_idt &assembly); + + std::optional process_asm( const code_asmt &code, - const irep_idt &assembly, + const instructionst &instructions, goto_programt &dest, - const std::function &handle_command); + const handle_commandt &handle_command); + + void warn_dropped(const code_asmt &code); - // Translates a single recognized gcc-style command, returning false if the - // command is not modeled. bool handle_gcc_command( const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, const code_asm_gcct &code, goto_programt &tmp_dest); - // Translates a single recognized msc-style command, returning false if the - // command is not modeled. bool handle_msc_command( const irep_idt &command, std::size_t pos, @@ -102,81 +106,48 @@ class remove_asmt const code_asmt &code, goto_programt &tmp_dest); - void gcc_asm_function_call( - const irep_idt &function_base_name, - const code_asm_gcct &code, - std::size_t n_args, - goto_programt &dest); - - void msc_asm_function_call( + void asm_function_call( const irep_idt &function_base_name, const exprt::operandst &operands, - const code_asmt &code, + const source_locationt &source_location, goto_programt &dest); }; -/// Adds a call to a library function that implements the given gcc-style inline -/// assembly statement +/// Adds a call to a library function that implements an inline assembly +/// instruction. The function is declared if it does not exist yet; the +/// library provides its body. /// /// \param function_base_name: Name of the function to call -/// \param code: gcc-style inline assembly statement to translate to function -/// call -/// \param n_args: Number of arguments required by \p function_base_name +/// \param operands: Arguments to be passed to the function, each of which is +/// converted to `void *` +/// \param source_location: Location of the inline assembly statement /// \param dest: Goto program to append the function call to -void remove_asmt::gcc_asm_function_call( +void remove_asmt::asm_function_call( const irep_idt &function_base_name, - const code_asm_gcct &code, - std::size_t n_args, + const exprt::operandst &operands, + const source_locationt &source_location, goto_programt &dest) { - irep_idt function_identifier = function_base_name; + const irep_idt &function_identifier = function_base_name; code_function_callt::argumentst arguments; - const typet void_pointer = pointer_type(empty_typet()); - - // outputs - forall_operands(it, code.outputs()) - { - if(it->operands().size() == 2) - { - arguments.push_back(typecast_exprt( - address_of_exprt(to_binary_expr(*it).op1()), void_pointer)); - } - } - - // inputs - forall_operands(it, code.inputs()) - { - if(it->operands().size() == 2) - { - arguments.push_back(typecast_exprt( - address_of_exprt(to_binary_expr(*it).op1()), void_pointer)); - } - } + const typet void_pointer = pointer_type(empty_typet{}); - // An inline asm statement may consist of multiple commands, not all of which - // use all of the inputs/outputs of the inline asm statement. - DATA_INVARIANT_WITH_DIAGNOSTICS( - arguments.size() >= n_args, - "insufficient number of arguments for calling " + - id2string(function_identifier), - "required arguments: " + std::to_string(n_args), - code.pretty()); - arguments.resize(n_args); + for(const auto &op : operands) + arguments.push_back(typecast_exprt::conditional_cast(op, void_pointer)); code_typet fkt_type{ code_typet::parameterst{ arguments.size(), code_typet::parametert{void_pointer}}, - empty_typet()}; + empty_typet{}}; auto fkt = symbol_exprt{function_identifier, fkt_type}.with_source_location( - code.source_location()); + source_location); - code_function_callt function_call(std::move(fkt), std::move(arguments)); - - dest.add( - goto_programt::make_function_call(function_call, code.source_location())); + dest.add(goto_programt::make_function_call( + code_function_callt{std::move(fkt), std::move(arguments)}, + source_location)); // do we have it? if(!symbol_table.has_symbol(function_identifier)) @@ -193,65 +164,11 @@ void remove_asmt::gcc_asm_function_call( DATA_INVARIANT_WITH_DIAGNOSTICS( symbol_table.lookup_ref(function_identifier).type == fkt_type, "types of function " + id2string(function_identifier) + " should match", - code.pretty(), symbol_table.lookup_ref(function_identifier).type.pretty(), fkt_type.pretty()); } } -/// Adds a call to a library function that implements the given msc-style inline -/// assembly statement -/// -/// \param function_base_name: Name of the function to call -/// \param operands: Arguments to be passed to function -/// \param code: msc-style inline assembly statement to translate to function -/// call -/// \param dest: Goto program to append the function call to -void remove_asmt::msc_asm_function_call( - const irep_idt &function_base_name, - const exprt::operandst &operands, - const code_asmt &code, - goto_programt &dest) -{ - irep_idt function_identifier = function_base_name; - - code_function_callt::argumentst arguments; - - const typet void_pointer = pointer_type(empty_typet()); - - for(const auto &op : operands) - arguments.push_back(typecast_exprt::conditional_cast(op, void_pointer)); - - code_typet fkt_type{ - code_typet::parameterst{ - arguments.size(), code_typet::parametert{void_pointer}}, - empty_typet()}; - - auto fkt = symbol_exprt{function_identifier, fkt_type}.with_source_location( - code.source_location()); - code_function_callt function_call(std::move(fkt), std::move(arguments)); - - dest.add( - goto_programt::make_function_call(function_call, code.source_location())); - - // do we have it? - if(!symbol_table.has_symbol(function_identifier)) - { - symbolt symbol{function_identifier, fkt_type, ID_C}; - symbol.base_name = function_base_name; - - symbol_table.add(symbol); - - goto_functions.function_map.emplace(function_identifier, goto_functiont()); - } - else - { - DATA_INVARIANT( - symbol_table.lookup_ref(function_identifier).type == fkt_type, - "function types should match"); - } -} - /// Translates the given inline assembly code (which must be in either gcc or /// msc style) to non-assembly goto program instructions /// @@ -276,19 +193,22 @@ void remove_asmt::process_instruction( DATA_INVARIANT(false, "unexpected assembler flavor"); } -/// Builds a `fence` codet with the requested ordering and cumulativity flags. -/// Only the flags set to true are added, matching the ireps that the individual -/// fence instructions used to construct by hand. +/// Builds a `fence` codet with the requested orderings. +/// \param source_location: Location of the fence +/// \param ww: Whether writes are ordered before later writes +/// \param rr: Whether reads are ordered before later reads +/// \param rw: Whether reads are ordered before later writes +/// \param wr: Whether writes are ordered before later reads +/// \param cumulative: Whether each of the requested orderings is cumulative, +/// i.e., also applies to the accesses of other threads that were observed +/// before the fence static codet make_fence( const source_locationt &source_location, bool ww, bool rr, bool rw, bool wr, - bool ww_cumul = false, - bool rw_cumul = false, - bool rr_cumul = false, - bool wr_cumul = false) + bool cumulative) { codet code_fence{ID_fence}; code_fence.add_source_location() = source_location; @@ -300,50 +220,56 @@ static codet make_fence( code_fence.set(ID_RWfence, true); if(wr) code_fence.set(ID_WRfence, true); - if(ww_cumul) - code_fence.set(ID_WWcumul, true); - if(rw_cumul) - code_fence.set(ID_RWcumul, true); - if(rr_cumul) - code_fence.set(ID_RRcumul, true); - if(wr_cumul) - code_fence.set(ID_WRcumul, true); + if(cumulative) + { + if(ww) + code_fence.set(ID_WWcumul, true); + if(rw) + code_fence.set(ID_RWcumul, true); + if(rr) + code_fence.set(ID_RRcumul, true); + if(wr) + code_fence.set(ID_WRcumul, true); + } return code_fence; } +/// Parses the text of an inline assembly statement. +/// \param assembly: The assembly text +/// \return The instructions, each a sequence of tokens +remove_asmt::instructionst remove_asmt::parse(const irep_idt &assembly) +{ + std::istringstream str(id2string(assembly)); + assembler_parsert assembler_parser{message_handler}; + assembler_parser.in = &str; + assembler_parser.parse(); + return std::move(assembler_parser.instructions); +} + /// Shared scaffolding for translating gcc-style and msc-style inline assembly. -/// Parses \p assembly, and for each parsed instruction handles the `lock` -/// prefix and `xchg` (which start an atomic section containing a full fence), -/// delegates the actual command translation to \p handle_command, and closes -/// the atomic section. If any instruction is not recognized by -/// \p handle_command, the whole statement is dropped (a warning is emitted and -/// nothing is appended to \p dest); otherwise the translation is appended. +/// For each instruction in \p instructions, handles the `lock` prefix and +/// `xchg` (which start an atomic section containing a full fence), delegates +/// the actual command translation to \p handle_command, and closes the atomic +/// section. The translation is appended to \p dest only if all instructions +/// are recognized by \p handle_command. /// /// \param code: The inline assembly code statement being translated -/// \param assembly: The assembly text to parse +/// \param instructions: The parsed assembly text /// \param dest: The goto program to append the new instructions to /// \param handle_command: Translates a single command into \p tmp_dest and /// returns whether the command was recognized -void remove_asmt::process_asm( +/// \return The first command that is not recognized, if any; nothing is +/// appended to \p dest in this case. +std::optional remove_asmt::process_asm( const code_asmt &code, - const irep_idt &assembly, + const instructionst &instructions, goto_programt &dest, - const std::function &handle_command) + const handle_commandt &handle_command) { - std::istringstream str(id2string(assembly)); - assembler_parsert assembler_parser{message_handler}; - assembler_parser.in = &str; - assembler_parser.parse(); - goto_programt tmp_dest; - bool unknown = false; bool x86_32_locked_atomic = false; - for(const auto &instruction : assembler_parser.instructions) + for(const auto &instruction : instructions) { if(instruction.empty()) continue; @@ -377,12 +303,12 @@ void remove_asmt::process_asm( { tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); tmp_dest.add(goto_programt::make_other( - make_fence(code.source_location(), true, true, true, true), + make_fence(code.source_location(), true, true, true, true, false), code.source_location())); } if(!handle_command(command, pos, instruction, tmp_dest)) - unknown = true; // give up + return command; if(x86_32_locked_atomic) { @@ -392,24 +318,28 @@ void remove_asmt::process_asm( } } - if(unknown) - { - // The entire inline-assembly statement is dropped (turned into skip below) - // when any of its instructions is not recognized; warn so that the user is - // not left silently relying on un-modeled assembly. - log.warning() << "dropping inline assembly statement at " - << code.source_location() - << ": it contains an instruction that is not modeled, so the " - "whole statement (including any modeled instructions) is " - "removed" - << messaget::eom; - } - else - dest.destructive_append(tmp_dest); + dest.destructive_append(tmp_dest); + return {}; +} + +/// Warns that the inline assembly statement \p code is dropped. +/// \param code: The inline assembly code statement +void remove_asmt::warn_dropped(const code_asmt &code) +{ + // The entire inline-assembly statement is dropped when any of its + // instructions is not recognized; warn so that the user is not left + // silently relying on un-modeled assembly. + log.warning() << "dropping inline assembly statement at " + << code.source_location() + << ": it contains an instruction that is not modeled, so the " + "whole statement (including any modeled instructions) is " + "removed" + << messaget::eom; } /// Translates the given inline assembly code (in gcc style) to non-assembly -/// goto program instructions +/// goto program instructions, dropping it if it contains an instruction +/// that is not modeled. /// /// \param code: The inline assembly code statement to translate /// \param dest: The goto program to append the new instructions to @@ -417,83 +347,163 @@ void remove_asmt::process_instruction_gcc( const code_asm_gcct &code, goto_programt &dest) { - process_asm( + const instructionst instructions = + parse(to_string_constant(code.asm_text()).value()); + + const auto unknown = process_asm( code, - to_string_constant(code.asm_text()).value(), + instructions, dest, [this, &code]( const irep_idt &command, - std::size_t, - const assembler_parsert::instructiont &, + std::size_t pos, + const assembler_parsert::instructiont &instruction, goto_programt &tmp_dest) - { return handle_gcc_command(command, code, tmp_dest); }); + { return handle_gcc_command(command, pos, instruction, code, tmp_dest); }); + + if(unknown.has_value()) + warn_dropped(code); +} + +/// \return The operand of \p code referred to as `%N` by the tokens of +/// \p instruction starting at \p pos, if these are the only remaining +/// tokens. Operands are numbered as in gcc: outputs first, then inputs. +static std::optional gcc_operand( + const code_asm_gcct &code, + std::size_t pos, + const assembler_parsert::instructiont &instruction) +{ + if(pos + 1 >= instruction.size() || instruction[pos].id() != "%") + return {}; + + std::size_t index = 0; + for(++pos; pos < instruction.size(); ++pos) + { + const std::string &digit = id2string(instruction[pos].id()); + if(digit.size() != 1 || !isdigit(digit[0])) + return {}; + index = index * 10 + static_cast(digit[0] - '0'); + } + + for(const auto *list : {&code.outputs(), &code.inputs()}) + { + for(const auto &operand : list->operands()) + { + if(operand.operands().size() != 2) + return {}; + if(index == 0) + return to_binary_expr(operand).op1(); + --index; + } + } + + return {}; } /// Translates a single recognized gcc-style command into \p tmp_dest. /// /// \param command: The instruction mnemonic to translate +/// \param pos: Index of the token following the command in \p instruction +/// \param instruction: The parsed instruction tokens /// \param code: The inline assembly code statement being translated /// \param tmp_dest: The goto program to append the translation to /// \return Whether the command was recognized (and hence modeled) bool remove_asmt::handle_gcc_command( const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, const code_asm_gcct &code, goto_programt &tmp_dest) { const source_locationt &source_location = code.source_location(); + const bool no_operands = pos == instruction.size(); - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 - { - gcc_asm_function_call("__asm_" + id2string(command), code, 1, tmp_dest); - } - else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 - { - gcc_asm_function_call("__asm_" + id2string(command), code, 0, tmp_dest); - } - else if(command == ID_sync) // Power + auto fence = [&](bool ww, bool rr, bool rw, bool wr, bool cumulative) { tmp_dest.add(goto_programt::make_other( - make_fence( - source_location, true, true, true, true, true, true, true, true), + make_fence(source_location, ww, rr, rw, wr, cumulative), source_location)); + return true; + }; + + if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + { + const auto operand = gcc_operand(code, pos, instruction); + if(!operand.has_value()) + return false; + asm_function_call( + "__asm_" + id2string(command), + {address_of_exprt{*operand}}, + source_location, + tmp_dest); + return true; } - else if(command == ID_lwsync) // Power + + if(command == "dmb" || command == "dsb") // ARM { - tmp_dest.add(goto_programt::make_other( - make_fence( - source_location, true, true, true, false, true, true, true, false), - source_location)); + if(no_operands) + return fence(true, true, true, true, true); + + // the barrier option selects the accesses being ordered + if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) + return false; + const std::string &option = id2string(instruction[pos].get(ID_identifier)); + if(option == "sy" || option == "ish" || option == "osh" || option == "nsh") + return fence(true, true, true, true, true); + else if(has_suffix(option, "ld")) // loads before loads and stores + return fence(false, true, true, false, true); + else if(has_suffix(option, "st")) // stores before stores + return fence(true, false, false, false, true); + else + return false; } - else if(command == ID_isync) // Power + + if(command == "isb") // ARM { + if( + !no_operands && + (pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol || + instruction[pos].get(ID_identifier) != "sy")) + { + return false; + } // doesn't do anything by itself, needs to be combined with branch - tmp_dest.add(goto_programt::make_other( - make_fence(source_location, false, false, false, false), - source_location)); + return fence(false, false, false, false, false); } - else if(command == "dmb" || command == "dsb") // ARM + + // all other modeled instructions have no operands + if(!no_operands) + return false; + + if(command == "mfence" || command == "lfence" || command == "sfence") // x86 { - tmp_dest.add(goto_programt::make_other( - make_fence( - source_location, true, true, true, true, true, true, true, true), - source_location)); + asm_function_call( + "__asm_" + id2string(command), {}, source_location, tmp_dest); + return true; + } + else if(command == "nop" || command == "pause" || command == "yield") + { + // no effect on the C program state + return true; } - else if(command == "isb") // ARM + else if(command == ID_sync || command == "hwsync") // Power + return fence(true, true, true, true, true); + else if(command == ID_lwsync) // Power: everything but store-load + return fence(true, true, true, false, true); + else if(command == "eieio") // Power: orders stores + return fence(true, false, false, false, true); + else if(command == ID_isync) // Power { // doesn't do anything by itself, needs to be combined with branch - tmp_dest.add(goto_programt::make_other( - make_fence(source_location, false, false, false, false), - source_location)); + return fence(false, false, false, false, false); } else return false; - - return true; } /// Translates the given inline assembly code (in msc style) to non-assembly -/// goto program instructions +/// goto program instructions, dropping it if it contains an instruction +/// that is not modeled. /// /// \param function_id: Name of function being processed /// \param code: The inline assembly code statement to translate @@ -503,9 +513,12 @@ void remove_asmt::process_instruction_msc( const code_asmt &code, goto_programt &dest) { - process_asm( + const instructionst instructions = + parse(to_string_constant(code.op0()).value()); + + const auto unknown = process_asm( code, - to_string_constant(code.op0()).value(), + instructions, dest, [this, &code, &function_id]( const irep_idt &command, @@ -516,6 +529,9 @@ void remove_asmt::process_instruction_msc( return handle_msc_command( command, pos, instruction, function_id, code, tmp_dest); }); + + if(unknown.has_value()) + warn_dropped(code); } /// Translates a single recognized msc-style command into \p tmp_dest. @@ -535,36 +551,51 @@ bool remove_asmt::handle_msc_command( const code_asmt &code, goto_programt &tmp_dest) { + const bool no_operands = pos == instruction.size(); + if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 { - exprt::operandst args{null_pointer_exprt{pointer_type(empty_typet{})}}; - // try to typecheck the argument - if(pos != instruction.size() && instruction[pos].id() == ID_symbol) + if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) + return false; + + // a local variable (or parameter) takes precedence over a global one; + // if several local variables of that name exist (shadowing), it is not + // known which one is meant + const irep_idt &name = instruction[pos].get(ID_identifier); + const std::string local_prefix = id2string(function_id) + "::"; + std::optional global, local; + for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) { - const irep_idt &name = instruction[pos].get(ID_identifier); - for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) + if(entry.second == name) + global = entry.second; + else if(has_prefix(id2string(entry.second), local_prefix)) { - // global scope symbol, don't replace a local one - if(entry.second == name && args[0].id() != ID_address_of) - { - args[0] = - address_of_exprt{symbol_table.lookup_ref(name).symbol_expr()}; - } - // parameter or symbol in local scope - else if(has_prefix( - id2string(entry.second), id2string(function_id) + "::")) - { - args[0] = address_of_exprt{ - symbol_table.lookup_ref(entry.second).symbol_expr()}; - } + if(local.has_value()) + return false; + local = entry.second; } } - msc_asm_function_call("__asm_" + id2string(command), args, code, tmp_dest); + + if(!local.has_value() && !global.has_value()) + return false; + + const exprt arg = address_of_exprt{ + symbol_table.lookup_ref(local.has_value() ? *local : *global) + .symbol_expr()}; + + asm_function_call( + "__asm_" + id2string(command), {arg}, code.source_location(), tmp_dest); } else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 + no_operands && + (command == "mfence" || command == "lfence" || command == "sfence")) // x86 + { + asm_function_call( + "__asm_" + id2string(command), {}, code.source_location(), tmp_dest); + } + else if(no_operands && (command == "nop" || command == "pause")) { - msc_asm_function_call("__asm_" + id2string(command), {}, code, tmp_dest); + // no effect on the C program state } else return false; @@ -619,9 +650,10 @@ void remove_asm( /// Replaces inline assembly instructions in the goto program (i.e., /// instructions of kind `OTHER` with a `code` member of type `code_asmt`) with -/// an appropriate (sequence of) non-assembly goto program instruction(s). At -/// present only a small number of x86 and Power instructions are supported. -/// Unrecognised assembly instructions are ignored. +/// an appropriate (sequence of) non-assembly goto program instruction(s). +/// At present only a small number of x86, ARM, and Power instructions are +/// supported. Statements that contain an unrecognised instruction are +/// removed. /// /// \param goto_model: The goto model /// \param message_handler: Message handler From 04ff9576dd29571b7845d6153febb4807af0e5ee Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:26:06 +0000 Subject: [PATCH 008/100] remove_asm: approximate assembly that is not modeled conservatively 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 #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: #6374 Co-authored-by: Kiro --- .../cbmc/inline_asm_approximation/main.c | 72 ++++ .../cbmc/inline_asm_approximation/test.desc | 29 ++ .../cbmc/inline_asm_approximation_msvc/main.i | 23 ++ .../inline_asm_approximation_msvc/test.desc | 19 + .../main.c | 10 + .../test.desc | 13 + regression/cbmc/inline_asm_dropped/main.c | 21 -- regression/cbmc/inline_asm_dropped/test.desc | 17 - regression/validate-trace-xml-schema/check.py | 1 - src/assembler/Makefile | 3 +- src/assembler/asm_approximation.cpp | 356 ++++++++++++++++++ src/assembler/asm_approximation.h | 112 ++++++ src/assembler/remove_asm.cpp | 229 +++++++++-- src/assembler/remove_asm.h | 8 +- 14 files changed, 845 insertions(+), 68 deletions(-) create mode 100644 regression/cbmc/inline_asm_approximation/main.c create mode 100644 regression/cbmc/inline_asm_approximation/test.desc create mode 100644 regression/cbmc/inline_asm_approximation_msvc/main.i create mode 100644 regression/cbmc/inline_asm_approximation_msvc/test.desc create mode 100644 regression/cbmc/inline_asm_approximation_rounding_mode/main.c create mode 100644 regression/cbmc/inline_asm_approximation_rounding_mode/test.desc delete mode 100644 regression/cbmc/inline_asm_dropped/main.c delete mode 100644 regression/cbmc/inline_asm_dropped/test.desc create mode 100644 src/assembler/asm_approximation.cpp create mode 100644 src/assembler/asm_approximation.h diff --git a/regression/cbmc/inline_asm_approximation/main.c b/regression/cbmc/inline_asm_approximation/main.c new file mode 100644 index 000000000000..1ebb476be39d --- /dev/null +++ b/regression/cbmc/inline_asm_approximation/main.c @@ -0,0 +1,72 @@ +// Statements containing an instruction that is not modeled are approximated +// conservatively by the remove_asm pass (see +// doc/cprover-manual/modeling-inline-asm.md): everything they may change is +// assigned a nondeterministic value. Each assertion marked "fails" would hold +// if the statement were dropped. +#include + +int global; +int *global_pointer; + +struct S +{ + int *p; + int v; +}; + +static void clobber(void) +{ + // pointee is not a local variable of this function + asm volatile("incl global" ::: "memory"); +} + +int main(void) +{ + int x = 0, y = 1; + // output operands + asm volatile("xchg %0,%1" : "+r"(x), "+r"(y)); + __CPROVER_assert(x == 0, "output operand"); // fails + + // a recognized mfence combined with an unrecognized addl: the recognized + // instruction does not hide the unrecognized one + int z = 0; + asm volatile("mfence; addl $1, %0" : "+m"(z)); + __CPROVER_assert(z == 0, "mixed statement"); // fails + + // the object a pointer operand points to, also via an array that decays + // to a pointer, a cast to an integer type, or a struct member + int a[2] = {0, 0}; + asm volatile("movl $1, (%0)" : : "r"(a)); + __CPROVER_assert(a[0] == 0, "array operand"); // fails + int h = 0; + asm volatile("movl $1, (%0)" : : "r"((uintptr_t)&h)); + __CPROVER_assert(h == 0, "pointer cast to integer"); // fails + int k = 0; + struct S s = {&k, 0}; + asm volatile("movl $1, (%0)" : : "m"(s)); + __CPROVER_assert(k == 0, "pointer member"); // fails + __CPROVER_assert(s.v == 0, "input operand"); // holds + + // "memory" clobber: objects of static lifetime and what they point to + int pointee = 0; + global = 0; + global_pointer = &pointee; + clobber(); + __CPROVER_assert(global == 0, "static object"); // fails + __CPROVER_assert(pointee == 0, "pointee of static pointer"); // fails + + // "memory" clobber: address-taken local variables + int unaddressed = 0, addressed = 0; + int *escape = &addressed; + asm volatile("cli" ::: "memory"); + __CPROVER_assert(addressed == 0, "address-taken local"); // fails + __CPROVER_assert(unaddressed == 0, "local without address"); // holds + + // an empty statement is a compiler barrier only + int barrier = 0; + int *barrier_address = &barrier; + asm volatile("" ::: "memory"); + __CPROVER_assert(barrier == 0, "empty statement"); // holds + + return 0; +} diff --git a/regression/cbmc/inline_asm_approximation/test.desc b/regression/cbmc/inline_asm_approximation/test.desc new file mode 100644 index 000000000000..269f81be1471 --- /dev/null +++ b/regression/cbmc/inline_asm_approximation/test.desc @@ -0,0 +1,29 @@ +CORE gcc-only +main.c +--no-standard-checks +^EXIT=10$ +^SIGNAL=0$ +approximating inline assembly statement at .* line 27 function main: instruction 'xchg' is not modeled, so its output operands and the rounding mode are assigned nondeterministic values +approximating inline assembly statement at .* line 33 function main: instruction 'addl' is not modeled +^\[main\.assertion\.1\] line 28 output operand: FAILURE$ +^\[main\.assertion\.2\] line 34 mixed statement: FAILURE$ +^\[main\.assertion\.3\] line 40 array operand: FAILURE$ +^\[main\.assertion\.4\] line 43 pointer cast to integer: FAILURE$ +^\[main\.assertion\.5\] line 47 pointer member: FAILURE$ +^\[main\.assertion\.6\] line 48 input operand: SUCCESS$ +^\[main\.assertion\.7\] line 55 static object: FAILURE$ +^\[main\.assertion\.8\] line 56 pointee of static pointer: FAILURE$ +^\[main\.assertion\.9\] line 62 address-taken local: FAILURE$ +^\[main\.assertion\.10\] line 63 local without address: SUCCESS$ +^\[main\.assertion\.11\] line 69 empty statement: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dropping inline assembly +-- +Inline-assembly statements containing an unrecognized instruction are +approximated conservatively by the remove_asm pass: output operands, the +objects pointer operands point to, with a "memory" clobber the objects of +static lifetime, what these point to, and address-taken local variables, and +the rounding mode are assigned nondeterministic values. +See GitHub issue diffblue/cbmc#6374. diff --git a/regression/cbmc/inline_asm_approximation_msvc/main.i b/regression/cbmc/inline_asm_approximation_msvc/main.i new file mode 100644 index 000000000000..060d5aef323d --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_msvc/main.i @@ -0,0 +1,23 @@ +// MSVC-style __asm blocks have no operand interface: a block containing an +// instruction that is not modeled may change any variable it names (with +// shadowing, any local variable of that name) and any memory it can reach. +int global; + +int main(void) +{ + int z = 0; + __asm { nop } + __CPROVER_assert(z == 0, "nop is modeled"); // holds + + int x = 0, y = 0; + { + int x = 0; + __asm { mov x, 1 } + __CPROVER_assert(x == 0, "inner x"); // fails + } + __CPROVER_assert(x == 0, "outer x"); // fails + __CPROVER_assert(y == 0, "y is not named"); // holds + __CPROVER_assert(global == 0, "static object"); // fails + + return 0; +} diff --git a/regression/cbmc/inline_asm_approximation_msvc/test.desc b/regression/cbmc/inline_asm_approximation_msvc/test.desc new file mode 100644 index 000000000000..3c376555afc2 --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_msvc/test.desc @@ -0,0 +1,19 @@ +CORE +main.i +--winx64 +^EXIT=10$ +^SIGNAL=0$ +approximating inline assembly statement at .* line 15 function main: instruction 'mov' is not modeled, so the local variables it names, all objects of static lifetime +^\[main\.assertion\.1\] line 10 nop is modeled: SUCCESS$ +^\[main\.assertion\.2\] line 16 inner x: FAILURE$ +^\[main\.assertion\.3\] line 18 outer x: FAILURE$ +^\[main\.assertion\.4\] line 19 y is not named: SUCCESS$ +^\[main\.assertion\.5\] line 20 static object: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +MSVC-style inline assembly that is not modeled is approximated conservatively. +The input is preprocessed (main.i), and the test uses no instruction that is +modeled by a library function (as fstcw is, see cbmc-library/__asm_fstcw), as +preprocessing for --winx64 fails on a non-x86 host. diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/main.c b/regression/cbmc/inline_asm_approximation_rounding_mode/main.c new file mode 100644 index 000000000000..f702657290ad --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/main.c @@ -0,0 +1,10 @@ +int main(void) +{ + float f = 1.0f; + unsigned csr = 0; + // ldmxcsr is not modeled, and may change the rounding mode + asm volatile("ldmxcsr %0" : : "m"(csr)); + // holds with round-to-nearest only + __CPROVER_assert(f / 3.0f == 0x1.555556p-2f, "rounding mode"); + return 0; +} diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc new file mode 100644 index 000000000000..87fc62729d21 --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc @@ -0,0 +1,13 @@ +CORE gcc-only no-new-smt +main.c + +^EXIT=10$ +^SIGNAL=0$ +approximating inline assembly statement at .* line 6 function main: instruction 'ldmxcsr' is not modeled, so the rounding mode is assigned a nondeterministic value +^\[main\.assertion\.1\] line 8 rounding mode: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +Inline assembly that is not modeled may change the floating-point rounding +mode. diff --git a/regression/cbmc/inline_asm_dropped/main.c b/regression/cbmc/inline_asm_dropped/main.c deleted file mode 100644 index 7818e7326eb8..000000000000 --- a/regression/cbmc/inline_asm_dropped/main.c +++ /dev/null @@ -1,21 +0,0 @@ -// Statements containing an unrecognized instruction are dropped entirely by -// the remove_asm pass -- including recognized siblings in the same statement -// (see doc/cprover-manual/modeling-inline-asm.md). This test pins that no -// fence/atomic/helper-call is emitted for any of them. -int main(void) -{ - int x = 0, y = 1; - - // xchg is not modeled: the statement is dropped. - asm volatile("xchg %0,%1" : "+r"(x), "+r"(y)); - - // lock followed by an unrecognized instruction: the whole statement is - // dropped (the atomic/fence wrapper is discarded too). - asm volatile("lock; addl $1, %0" : "+m"(x)); - - // A recognized mfence combined with an unrecognized addl: *both* are - // dropped, not just the addl. - asm volatile("mfence; addl $1, %0" : "+m"(x)); - - return 0; -} diff --git a/regression/cbmc/inline_asm_dropped/test.desc b/regression/cbmc/inline_asm_dropped/test.desc deleted file mode 100644 index 77ee8699402f..000000000000 --- a/regression/cbmc/inline_asm_dropped/test.desc +++ /dev/null @@ -1,17 +0,0 @@ -CORE gcc-only -main.c ---show-goto-functions -^EXIT=0$ -^SIGNAL=0$ -dropping inline assembly statement at .*: it contains an instruction that is not modeled --- -^warning: ignoring -CALL __asm_ -^ *FENCE -ATOMIC_BEGIN --- -Pins that inline-assembly statements containing an unrecognized instruction -are dropped by the remove_asm pass: no fence, atomic section, or __asm_* -helper call is emitted -- including for "mfence; addl", where the recognized -mfence is dropped together with the unrecognized addl. -See GitHub issue diffblue/cbmc#6374. diff --git a/regression/validate-trace-xml-schema/check.py b/regression/validate-trace-xml-schema/check.py index 7048a2ca0bb3..0c545eee3a25 100644 --- a/regression/validate-trace-xml-schema/check.py +++ b/regression/validate-trace-xml-schema/check.py @@ -30,7 +30,6 @@ ['destructors', 'enter_lexical_block.desc'], ['enum_is_in_range', 'enum_test3-simplified.desc'], ['enum_is_in_range', 'format.desc'], - ['inline_asm_dropped', 'test.desc'], ['inline_asm_modeling', 'test.desc'], ['integer-assignments1', 'integer-typecheck.desc'], ['r_w_ok9', 'simplify.desc'], diff --git a/src/assembler/Makefile b/src/assembler/Makefile index 57638617bddf..65ca8480544b 100644 --- a/src/assembler/Makefile +++ b/src/assembler/Makefile @@ -1,4 +1,5 @@ -SRC = assembler_lex.yy.cpp \ +SRC = asm_approximation.cpp \ + assembler_lex.yy.cpp \ assembler_parser.cpp \ remove_asm.cpp \ # Empty last line diff --git a/src/assembler/asm_approximation.cpp b/src/assembler/asm_approximation.cpp new file mode 100644 index 000000000000..758e74ed3e67 --- /dev/null +++ b/src/assembler/asm_approximation.cpp @@ -0,0 +1,356 @@ +/*******************************************************************\ + +Module: Conservative approximation of inline assembly + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Conservative approximation of inline assembly statements + +#include "asm_approximation.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +/// \return True iff objects of type \p type cannot be modified. +static bool is_constant_type(const typet &type) +{ + if(type.get_bool(ID_C_constant)) + return true; + if(type.id() == ID_array) + return is_constant_type(to_array_type(type).element_type()); + return false; +} + +/// \return True iff objects of type \p type can be assigned a value as a +/// whole. +static bool is_complete_type(const typet &type, const namespacet &ns) +{ + if(type.id() == ID_code || type.id() == ID_empty) + return false; + if(type.id() == ID_array) + { + const array_typet &array_type = to_array_type(type); + return array_type.size().is_not_nil() && + is_complete_type(array_type.element_type(), ns); + } + if(type.id() == ID_struct_tag) + return !ns.follow_tag(to_struct_tag_type(type)).is_incomplete(); + if(type.id() == ID_union_tag) + return !ns.follow_tag(to_union_tag_type(type)).is_incomplete(); + return true; +} + +/// \return True iff the address of lvalue \p expr does not depend on the +/// program state. +static bool has_constant_address(const exprt &expr) +{ + if(expr.id() == ID_symbol) + return true; + if(expr.id() == ID_member) + return has_constant_address(to_member_expr(expr).struct_op()); + if(expr.id() == ID_index) + { + const index_exprt &index = to_index_expr(expr); + return index.index().is_constant() && has_constant_address(index.array()); + } + return false; +} + +void asm_approximationt::collect_addresses( + const exprt &expr, + const namespacet &ns, + std::vector &dest) +{ + // look through casts of pointers to integers, as in (uintptr_t)&x + const exprt &e = expr.type().id() == ID_pointer ? expr : skip_typecast(expr); + const typet &type = e.type(); + + if(type.id() == ID_pointer) + { + const typet &base_type = to_pointer_type(type).base_type(); + if(base_type.id() != ID_code && !is_constant_type(base_type)) + dest.push_back(e); + } + else if(type.id() == ID_array) + { + // the array decays to the address of its first element + if(!is_constant_type(type)) + { + dest.push_back( + address_of_exprt{index_exprt{e, from_integer(0, c_index_type())}}); + } + } + else if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + const struct_union_typet &struct_union_type = + type.id() == ID_struct_tag ? static_cast( + ns.follow_tag(to_struct_tag_type(type))) + : static_cast( + ns.follow_tag(to_union_tag_type(type))); + for(const auto &component : struct_union_type.components()) + { + const typet &component_type = component.type(); + if( + component_type.id() == ID_pointer || + component_type.id() == ID_struct_tag || + component_type.id() == ID_union_tag) + { + collect_addresses(member_exprt{e, component}, ns, dest); + } + } + } +} + +std::vector asm_approximationt::address_taken_locals( + const goto_programt &body, + const namespacet &ns) +{ + std::vector result; + + auto collect = [&result, &ns](const exprt &root) + { + for(auto it = root.depth_cbegin(); it != root.depth_cend(); ++it) + { + if(it->id() != ID_address_of) + continue; + + const exprt *object = &to_address_of_expr(*it).object(); + while(object->id() == ID_member || object->id() == ID_index || + object->id() == ID_typecast || + object->id() == ID_byte_extract_little_endian || + object->id() == ID_byte_extract_big_endian) + { + object = &object->operands().front(); + } + + if(object->id() != ID_symbol) + continue; + + const symbolt *symbol = nullptr; + if(ns.lookup(to_symbol_expr(*object).get_identifier(), symbol)) + continue; + + if( + !symbol->is_static_lifetime && symbol->is_lvalue && + !is_constant_type(symbol->type) && is_complete_type(symbol->type, ns)) + { + result.push_back(to_symbol_expr(*object)); + } + } + }; + + for(const auto &instruction : body.instructions) + { + collect(instruction.code()); + if(instruction.has_condition()) + collect(instruction.condition()); + } + + auto by_name = [](const symbol_exprt &a, const symbol_exprt &b) + { return id2string(a.get_identifier()) < id2string(b.get_identifier()); }; + std::sort(result.begin(), result.end(), by_name); + result.erase(std::unique(result.begin(), result.end()), result.end()); + + return result; +} + +const std::vector &asm_approximationt::get_static_objects() +{ + if(static_objects.has_value()) + return *static_objects; + + const namespacet ns{symbol_table}; + static_objects = std::vector{}; + for(const auto &entry : symbol_table.symbols) + { + const symbolt &symbol = entry.second; + if( + !symbol.is_static_lifetime || symbol.is_type || symbol.is_macro || + !symbol.is_lvalue || is_constant_type(symbol.type) || + !is_complete_type(symbol.type, ns) || + symbol.name.starts_with(CPROVER_PREFIX) || + symbol.base_name.starts_with(CPROVER_PREFIX)) + { + continue; + } + + static_objects->push_back(symbol.symbol_expr()); + } + + std::sort( + static_objects->begin(), + static_objects->end(), + [](const symbol_exprt &a, const symbol_exprt &b) + { return id2string(a.get_identifier()) < id2string(b.get_identifier()); }); + + return *static_objects; +} + +/// Appends to \p dest an assignment of a nondeterministic value to \p lvalue. +static void havoc_lvalue( + const exprt &lvalue, + const source_locationt &source_location, + goto_programt &dest) +{ + dest.add(goto_programt::make_assignment( + lvalue, + side_effect_expr_nondett{lvalue.type(), source_location}, + source_location)); +} + +/// Appends to \p dest instructions that assign a nondeterministic value to the +/// object \p pointer points to, unless \p pointer is null. +static void havoc_pointee( + const exprt &pointer, + const source_locationt &source_location, + goto_programt &dest) +{ + const null_pointer_exprt null{to_pointer_type(pointer.type())}; + auto skip = dest.add(goto_programt::make_incomplete_goto( + equal_exprt{pointer, null}, source_location)); + + const codet havoc{ID_havoc_object, {pointer}, source_location}; + dest.add(goto_programt::make_other(havoc, source_location)); + + skip->complete_goto(dest.add(goto_programt::make_skip(source_location))); +} + +void asm_approximationt::operator()( + const asm_footprintt &footprint, + const std::vector &address_taken_locals, + const irep_idt &function_id, + const source_locationt &source_location, + goto_programt &dest) +{ + const namespacet ns{symbol_table}; + std::vector temporaries; + + // 1. the statement reads its inputs + for(const auto &read : footprint.reads) + { + code_expressiont evaluate{read}; + evaluate.add_source_location() = source_location; + dest.add(goto_programt::make_other(evaluate, source_location)); + } + + // 2. record the values of addresses before any of them is changed, as the + // instructions below may change the objects these are stored in + auto snapshot = [&](const exprt &value) -> exprt + { + const symbolt &tmp = get_fresh_aux_symbol( + value.type(), + id2string(function_id), + "asm_address", + source_location, + ID_C, + symbol_table); + const symbol_exprt tmp_expr = tmp.symbol_expr(); + temporaries.push_back(tmp_expr); + dest.add(goto_programt::make_decl(tmp_expr, source_location)); + dest.add(goto_programt::make_assignment(tmp_expr, value, source_location)); + return tmp_expr; + }; + + // pointers, and the values of the pointers stored in objects of static + // lifetime if the statement may access arbitrary memory + std::vector addresses = footprint.addresses; + if(footprint.arbitrary_memory) + { + for(const auto &object : get_static_objects()) + { + if(object.type().id() != ID_array) + collect_addresses(object, ns, addresses); + } + } + + std::vector pointers; + for(const auto &address : addresses) + { + if(address.id() == ID_address_of) + { + const exprt &object = to_address_of_expr(address).object(); + if(has_constant_address(object)) + { + pointers.push_back(address); + continue; + } + } + pointers.push_back(snapshot(address)); + } + + // the lvalues written, with addresses evaluated before the statement; for + // bit fields, whose address cannot be taken, record the address of the + // enclosing object + std::vector writes; + for(const auto &write : footprint.writes) + { + exprt lvalue = write; + std::vector bit_field_members; + while(lvalue.id() == ID_member && lvalue.type().id() == ID_c_bit_field) + { + bit_field_members.push_back(to_member_expr(lvalue)); + lvalue = to_member_expr(lvalue).struct_op(); + } + + if(!has_constant_address(lvalue)) + lvalue = dereference_exprt{snapshot(address_of_exprt{lvalue})}; + + for(auto it = bit_field_members.rbegin(); it != bit_field_members.rend(); + ++it) + { + lvalue = member_exprt{lvalue, it->get_component_name(), it->type()}; + } + writes.push_back(lvalue); + } + + // 3. the objects pointed to + for(const auto &pointer : pointers) + havoc_pointee(pointer, source_location, dest); + + // 4. arbitrary memory: what the statement can name + if(footprint.arbitrary_memory) + { + for(const auto &object : get_static_objects()) + havoc_lvalue(object, source_location, dest); + for(const auto &local : address_taken_locals) + havoc_lvalue(local, source_location, dest); + } + + // 5. the outputs + for(const auto &write : writes) + havoc_lvalue(write, source_location, dest); + + // 6. the floating-point rounding mode, which the statement may change via + // the control registers of the floating-point unit + const symbolt *rounding_mode = nullptr; + if(!ns.lookup(CPROVER_PREFIX "rounding_mode", rounding_mode)) + { + const symbol_exprt rounding_mode_expr = rounding_mode->symbol_expr(); + havoc_lvalue(rounding_mode_expr, source_location, dest); + const typet &type = rounding_mode_expr.type(); + dest.add(goto_programt::make_assumption( + and_exprt{ + binary_relation_exprt{rounding_mode_expr, ID_ge, from_integer(0, type)}, + binary_relation_exprt{ + rounding_mode_expr, ID_le, from_integer(3, type)}}, + source_location)); + } + + for(auto it = temporaries.rbegin(); it != temporaries.rend(); ++it) + dest.add(goto_programt::make_dead(*it, source_location)); +} diff --git a/src/assembler/asm_approximation.h b/src/assembler/asm_approximation.h new file mode 100644 index 000000000000..7d2a031cd5ca --- /dev/null +++ b/src/assembler/asm_approximation.h @@ -0,0 +1,112 @@ +/*******************************************************************\ + +Module: Conservative approximation of inline assembly + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Conservative approximation of inline assembly statements whose +/// instructions are not modeled: everything the statement may change is +/// assigned a nondeterministic value. + +#ifndef CPROVER_ASSEMBLER_ASM_APPROXIMATION_H +#define CPROVER_ASSEMBLER_ASM_APPROXIMATION_H + +#include +#include +#include + +#include +#include + +class goto_programt; +class namespacet; +class source_locationt; +class symbol_table_baset; + +/// The C-level footprint of an inline assembly statement: what the statement +/// may read and write. +struct asm_footprintt +{ + /// Expressions the statement may read. These are evaluated (and hence + /// subject to the usual checks) before the statement. + std::vector reads; + + /// Lvalues the statement may write. + std::vector writes; + + /// Expressions whose values the statement may use as addresses: the objects + /// they point to may be written. Arrays decay to the address of their first + /// element, casts to integer types are looked through, and the pointer + /// members of structs and unions are included. + std::vector addresses; + + /// Whether the statement may access memory not described by its operands + /// (a "memory" clobber, basic assembly, or an MSVC-style block). + bool arbitrary_memory = false; +}; + +/// Builds the instructions that conservatively approximate an inline assembly +/// statement given its footprint. The objects of static lifetime are +/// computed once and shared across statements. +class asm_approximationt +{ +public: + explicit asm_approximationt(symbol_table_baset &_symbol_table) + : symbol_table(_symbol_table) + { + } + + /// Appends to \p dest instructions that + /// 1. evaluate the reads of \p footprint; + /// 2. record the addresses of the writes and the values of the addresses + /// of \p footprint in temporaries; + /// 3. assign nondeterministic values to the objects the addresses point to; + /// 4. if \p footprint has arbitrary memory accesses: assign + /// nondeterministic values to the objects of static lifetime, to the + /// objects that pointers stored in objects of static lifetime point to, + /// and to \p address_taken_locals; + /// 5. assign nondeterministic values to the writes; + /// 6. assign a nondeterministic rounding mode. + /// Objects that are reachable only through other pointers (for example, a + /// caller's local variables or heap objects not referenced by an object of + /// static lifetime) are not changed. + /// \param footprint: What the statement may read and write + /// \param address_taken_locals: The local variables of the enclosing + /// function whose address is taken + /// \param function_id: Name of the enclosing function, which temporaries + /// are added to + /// \param source_location: Location of the statement + /// \param dest: Goto program to append the instructions to + void operator()( + const asm_footprintt &footprint, + const std::vector &address_taken_locals, + const irep_idt &function_id, + const source_locationt &source_location, + goto_programt &dest); + + /// \return The local variables of \p body whose address is taken, sorted by + /// name and excluding objects of static lifetime and constant objects. + static std::vector + address_taken_locals(const goto_programt &body, const namespacet &ns); + + /// Appends to \p dest the expressions contained in \p expr that may hold + /// addresses, as described for \ref asm_footprintt::addresses. + static void collect_addresses( + const exprt &expr, + const namespacet &ns, + std::vector &dest); + +private: + symbol_table_baset &symbol_table; + + /// The modifiable objects of static lifetime, sorted by name; computed on + /// first use. + std::optional> static_objects; + + const std::vector &get_static_objects(); +}; + +#endif // CPROVER_ASSEMBLER_ASM_APPROXIMATION_H diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 6979a55eb9a8..205c33b22716 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -17,6 +17,7 @@ Date: December 2014 #include #include +#include #include #include #include @@ -27,11 +28,13 @@ Date: December 2014 #include #include +#include "asm_approximation.h" #include "assembler_parser.h" #include #include #include +#include class remove_asmt { @@ -43,7 +46,8 @@ class remove_asmt : symbol_table(_symbol_table), goto_functions(_goto_functions), message_handler(message_handler), - log(message_handler) + log(message_handler), + approximate(_symbol_table) { } @@ -58,6 +62,10 @@ class remove_asmt goto_functionst &goto_functions; message_handlert &message_handler; messaget log; + asm_approximationt approximate; + + /// The address-taken local variables of the function being processed. + std::vector address_taken_locals; using instructionst = std::list; @@ -74,7 +82,10 @@ class remove_asmt goto_programt::instructiont &instruction, goto_programt &dest); - void process_instruction_gcc(const code_asm_gcct &, goto_programt &dest); + void process_instruction_gcc( + const irep_idt &function_id, + const code_asm_gcct &, + goto_programt &dest); void process_instruction_msc( const irep_idt &function_id, @@ -89,7 +100,14 @@ class remove_asmt goto_programt &dest, const handle_commandt &handle_command); - void warn_dropped(const code_asmt &code); + void approximate_asm( + const irep_idt &function_id, + const code_asmt &code, + const irep_idt &unknown_command, + const asm_footprintt &footprint, + const std::string &writes_description, + const std::string &addresses_description, + goto_programt &dest); bool handle_gcc_command( const irep_idt &command, @@ -186,7 +204,7 @@ void remove_asmt::process_instruction( const irep_idt &flavor = code.get_flavor(); if(flavor == ID_gcc) - process_instruction_gcc(to_code_asm_gcc(code), dest); + process_instruction_gcc(function_id, to_code_asm_gcc(code), dest); else if(flavor == ID_msc) process_instruction_msc(function_id, code, dest); else @@ -322,28 +340,74 @@ std::optional remove_asmt::process_asm( return {}; } -/// Warns that the inline assembly statement \p code is dropped. +/// Appends the conservative approximation of the inline assembly statement +/// \p code (see \ref asm_approximationt) to \p dest and warns about it. +/// +/// \param function_id: Name of function being processed /// \param code: The inline assembly code statement -void remove_asmt::warn_dropped(const code_asmt &code) +/// \param unknown_command: The first command in \p code that is not modeled +/// \param footprint: What \p code may read and write +/// \param writes_description: Description of the writes in \p footprint, +/// for the warning +/// \param addresses_description: Description of the objects the addresses +/// in \p footprint point to, for the warning +/// \param dest: The goto program to append the new instructions to +void remove_asmt::approximate_asm( + const irep_idt &function_id, + const code_asmt &code, + const irep_idt &unknown_command, + const asm_footprintt &footprint, + const std::string &writes_description, + const std::string &addresses_description, + goto_programt &dest) { - // The entire inline-assembly statement is dropped when any of its - // instructions is not recognized; warn so that the user is not left - // silently relying on un-modeled assembly. - log.warning() << "dropping inline assembly statement at " - << code.source_location() - << ": it contains an instruction that is not modeled, so the " - "whole statement (including any modeled instructions) is " - "removed" + approximate( + footprint, address_taken_locals, function_id, code.source_location(), dest); + + std::vector parts; + if(!footprint.writes.empty()) + parts.push_back(writes_description); + if(!footprint.addresses.empty()) + parts.push_back(addresses_description); + if(footprint.arbitrary_memory) + { + parts.push_back( + "all objects of static lifetime and the objects their pointers point " + "to"); + parts.push_back( + "the address-taken local variables of " + id2string(function_id)); + } + parts.push_back("the rounding mode"); + + std::string havocked; + for(std::size_t i = 0; i < parts.size(); ++i) + { + if(i > 0) + havocked += i + 1 == parts.size() ? (i > 1 ? ", and " : " and ") : ", "; + havocked += parts[i]; + } + + log.warning() << "approximating inline assembly statement at " + << code.source_location() << ": " + << (unknown_command.empty() + ? std::string{"an instruction"} + : "instruction '" + id2string(unknown_command) + "'") + << " is not modeled, so " << havocked + << (parts.size() == 1 ? " is assigned a nondeterministic value" + : " are assigned nondeterministic values") + << "; other objects are assumed to be unchanged" << messaget::eom; } /// Translates the given inline assembly code (in gcc style) to non-assembly -/// goto program instructions, dropping it if it contains an instruction -/// that is not modeled. +/// goto program instructions, approximating it conservatively if it +/// contains an instruction that is not modeled. /// +/// \param function_id: Name of function being processed /// \param code: The inline assembly code statement to translate /// \param dest: The goto program to append the new instructions to void remove_asmt::process_instruction_gcc( + const irep_idt &function_id, const code_asm_gcct &code, goto_programt &dest) { @@ -361,8 +425,68 @@ void remove_asmt::process_instruction_gcc( goto_programt &tmp_dest) { return handle_gcc_command(command, pos, instruction, code, tmp_dest); }); - if(unknown.has_value()) - warn_dropped(code); + if(!unknown.has_value()) + return; + + const namespacet ns{symbol_table}; + asm_footprintt footprint; + + for(const auto &output : code.outputs().operands()) + { + if(output.operands().size() != 2) + continue; + const exprt &constraint = to_binary_expr(output).op0(); + const exprt &lvalue = to_binary_expr(output).op1(); + footprint.writes.push_back(lvalue); + // in-out operands are also read, and may be addresses + if( + constraint.id() == ID_string_constant && + id2string(to_string_constant(constraint).value()).find('+') != + std::string::npos) + { + footprint.reads.push_back(lvalue); + asm_approximationt::collect_addresses(lvalue, ns, footprint.addresses); + } + } + + for(const auto &input : code.inputs().operands()) + { + if(input.operands().size() != 2) + continue; + const exprt &expr = to_binary_expr(input).op1(); + footprint.reads.push_back(expr); + asm_approximationt::collect_addresses(expr, ns, footprint.addresses); + } + + for(const auto &clobber : code.clobbers().operands()) + { + const exprt &name = clobber.id() == ID_gcc_asm_clobbered_register + ? to_unary_expr(clobber).op() + : clobber; + if( + name.id() == ID_string_constant && + to_string_constant(name).value() == "memory") + { + footprint.arbitrary_memory = true; + } + } + + // basic assembly (without operands) may access any memory + if( + code.outputs().operands().empty() && code.inputs().operands().empty() && + code.clobbers().operands().empty()) + { + footprint.arbitrary_memory = true; + } + + approximate_asm( + function_id, + code, + *unknown, + footprint, + "its output operands", + "the objects its operands point to", + dest); } /// \return The operand of \p code referred to as `%N` by the tokens of @@ -502,8 +626,8 @@ bool remove_asmt::handle_gcc_command( } /// Translates the given inline assembly code (in msc style) to non-assembly -/// goto program instructions, dropping it if it contains an instruction -/// that is not modeled. +/// goto program instructions, approximating it conservatively if it +/// contains an instruction that is not modeled. /// /// \param function_id: Name of function being processed /// \param code: The inline assembly code statement to translate @@ -530,8 +654,54 @@ void remove_asmt::process_instruction_msc( command, pos, instruction, function_id, code, tmp_dest); }); - if(unknown.has_value()) - warn_dropped(code); + if(!unknown.has_value()) + return; + + // MSVC-style blocks have no operand interface: any variable named in the + // block may be read or written, and so may any memory. As C names may be + // shadowed, every local variable of the function with that name is + // considered. + const namespacet ns{symbol_table}; + asm_footprintt footprint; + footprint.arbitrary_memory = true; + + const std::string local_prefix = id2string(function_id) + "::"; + std::set names; + for(const auto &instruction : instructions) + { + for(const auto &token : instruction) + { + if(token.id() == ID_symbol) + names.insert(token.get(ID_identifier)); + } + } + + for(const auto &name : names) + { + for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) + { + const symbolt &symbol = symbol_table.lookup_ref(entry.second); + if( + !symbol.is_lvalue || symbol.is_type || symbol.is_macro || + symbol.type.id() == ID_code || symbol.is_static_lifetime || + !has_prefix(id2string(symbol.name), local_prefix)) + { + continue; + } + footprint.writes.push_back(symbol.symbol_expr()); + asm_approximationt::collect_addresses( + symbol.symbol_expr(), ns, footprint.addresses); + } + } + + approximate_asm( + function_id, + code, + *unknown, + footprint, + "the local variables it names", + "the objects these point to", + dest); } /// Translates a single recognized msc-style command into \p tmp_dest. @@ -613,11 +783,20 @@ void remove_asmt::process_function( goto_functionst::goto_functiont &goto_function) { bool did_something = false; + bool locals_computed = false; Forall_goto_program_instructions(it, goto_function.body) { if(it->is_other() && it->get_other().get_statement() == ID_asm) { + // compute before any of the statements is replaced + if(!locals_computed) + { + address_taken_locals = asm_approximationt::address_taken_locals( + goto_function.body, namespacet{symbol_table}); + locals_computed = true; + } + goto_programt tmp_dest; process_instruction(function_id, *it, tmp_dest); it->turn_into_skip(); @@ -651,9 +830,9 @@ void remove_asm( /// Replaces inline assembly instructions in the goto program (i.e., /// instructions of kind `OTHER` with a `code` member of type `code_asmt`) with /// an appropriate (sequence of) non-assembly goto program instruction(s). -/// At present only a small number of x86, ARM, and Power instructions are -/// supported. Statements that contain an unrecognised instruction are -/// removed. +/// Statements that contain an instruction that is not modeled are +/// approximated conservatively: everything they may change is assigned a +/// nondeterministic value (see \ref asm_approximationt). /// /// \param goto_model: The goto model /// \param message_handler: Message handler diff --git a/src/assembler/remove_asm.h b/src/assembler/remove_asm.h index e37ee6409426..22dff375efaa 100644 --- a/src/assembler/remove_asm.h +++ b/src/assembler/remove_asm.h @@ -45,9 +45,11 @@ Date: December 2014 /// instructions, or call a suitable library function (see /// `library/x86_assembler.c`). /// -/// At present only a small number of x86 and Power instructions are supported. -/// Unrecognised assembly instructions are ignored (i.e., they are simply -/// removed from the goto program). +/// At present only a small number of x86, ARM, and Power instructions are +/// supported (see doc/cprover-manual/modeling-inline-asm.md). Statements that +/// contain an instruction that is not supported are approximated +/// conservatively: everything they may change is assigned a nondeterministic +/// value (see `asm_approximationt`). #ifndef CPROVER_ASSEMBLER_REMOVE_ASM_H #define CPROVER_ASSEMBLER_REMOVE_ASM_H From 3156fb9a9fbb2bdb3a4511e0c9e5d6da11196549 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Sun, 15 Nov 2026 22:26:07 +0000 Subject: [PATCH 009/100] Document the modeling and approximation of inline assembly 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 --- doc/cprover-manual/modeling-inline-asm.md | 127 ++++++++++++++-------- 1 file changed, 81 insertions(+), 46 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index e4475abeb57f..a7ef84412950 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -3,16 +3,20 @@ ## Modeling Inline Assembly CBMC supports GCC-style (`asm`/`__asm__`) and MSVC-style (`__asm {}`) -inline assembly syntax. During verification, the `remove_asm` pass -translates recognized instructions into equivalent goto-program -operations. +inline assembly syntax. Before verification, the `remove_asm` pass replaces +each inline-assembly statement by goto-program instructions: -**If an inline-assembly statement contains any unrecognized instruction, the -entire statement is replaced with `skip` — including any sibling instructions -in the same statement that would otherwise be translated.** For example, an -asm statement containing both an `mfence` and an `addl` loses *both*. This may -lead to unsound results if the assembly has side effects that matter for the -property being verified. +- If CBMC models every instruction of the statement (see the tables below), + the statement is translated into the corresponding fences or calls to + library functions. +- Otherwise the statement is **approximated conservatively**: everything the + statement may change, as far as CBMC can tell from its operands, is + assigned a nondeterministic value, and a warning that names the first + instruction that is not modeled is printed. The modeled instructions of + such a statement are not translated either. + +A statement with an empty assembly template, such as the compiler barrier +`asm volatile("" ::: "memory")`, does nothing. ### Supported Instructions @@ -23,58 +27,89 @@ property being verified. | `mfence` | Full memory fence | | `lfence` | Full memory fence (currently modeled identically to `mfence`) | | `sfence` | Full memory fence (currently modeled identically to `mfence`) | -| `fstcw` / `fnstcw` | Store FP control word (maps to `__CPROVER_rounding_mode`) | -| `fldcw` | Load FP control word (maps to `__CPROVER_rounding_mode`) | -| `lock` prefix | Only effective when followed by another recognized instruction (e.g. `lock; mfence`); the recognized instruction is wrapped in an atomic section with a full fence. The read-modify-write/exchange value itself is not modeled. | -| `xchg` / `xchgl` | Not modeled: the inline-assembly statement is dropped (treated as unrecognized). | +| `fstcw` / `fnstcw` | Stores the rounding mode (`__CPROVER_rounding_mode`) to bits 10 and 11 of the operand; the other bits of the control word are zero | +| `fldcw` | Sets the rounding mode from bits 10 and 11 of the operand | +| `nop`, `pause` | No effect | + +For GCC-style statements, the operand of `fstcw`, `fnstcw`, and `fldcw` must +be an operand reference (`%0`, `%1`, ...); for MSVC-style blocks, it must be +the name of a variable. None of the read-modify-write instructions that +take a `lock` prefix is modeled, and neither is `xchg`, so statements using +them are approximated. #### ARM | Instruction | Effect in CBMC | |---|---| -| `dmb` | Data memory barrier (full fence) | -| `dsb` | Data synchronization barrier (full fence) | +| `dmb`, `dsb` | Full fence without an option or with option `sy`, `ish`, `osh`, or `nsh`; with an option ending in `ld` (such as `ishld`), loads are ordered before later loads and stores; with an option ending in `st` (such as `ishst`), stores are ordered before later stores | | `isb` | Empty fence; no observable effect unless combined with a branch | +| `nop`, `yield` | No effect | #### Power | Instruction | Effect in CBMC | |---|---| -| `sync` | Full memory barrier | +| `sync`, `hwsync` | Full memory barrier | | `lwsync` | Lightweight sync (all fences except write-after-read) | +| `eieio` | Orders stores before later stores | | `isync` | Empty fence; no observable effect unless combined with a branch | +| `nop` | No effect | + +Only the x86 fences, `fstcw`, `fnstcw`, `fldcw`, `nop`, and `pause` are +modeled in MSVC-style blocks. + +### Conservative Approximation + +The operands of a GCC-style statement are evaluated before the statement, +including any side effects they have. If the statement contains an +instruction that is not modeled, then -### Operand Handling +1. the input operands (and the in-out operands, those with a `+` + constraint) are read, which makes them subject to the checks that CBMC + performs, for example `--pointer-check`; +2. the objects that the input and in-out operands point to are assigned + nondeterministic values. This includes operands of pointer type, arrays + (which decay to pointers), pointers cast to integer types (as in + `(uintptr_t)&x`), and the pointer members of operands of struct or union + type; +3. if the statement has a `"memory"` clobber, or no operands and no clobbers + at all (basic assembly), all objects of static lifetime, the objects that + those of them that are pointers (or structs or unions with pointer + members) point to, and all local variables of the enclosing function whose + address is taken are assigned nondeterministic values; +4. the output operands are assigned nondeterministic values, at the + addresses they had before the statement; +5. the rounding mode is assigned a nondeterministic value. -For GCC extended assembly, CBMC parses the output (`=r`, `+r`) and input -(`r`, `m`) operand lists, but in most cases the operand list does not -influence the generated goto program. For recognized fence instructions (for -example `mfence`, `lfence`, `sfence`, `dmb`, `dsb`, `sync`), the inline -assembly is replaced by a fence and the C-level output operands are not -written. For unrecognized instructions, the entire statement is replaced with -`skip`; output operands are **not** assigned nondeterministic values. Output -operands are only written when the modeled helper for a particular instruction -reads or writes through a pointer associated with that operand — currently -only `fstcw` / `fnstcw` / `fldcw`, which read or write `__CPROVER_rounding_mode`. -Clobber lists are parsed but do not affect verification. +MSVC-style blocks have no operand interface. If a block contains an +instruction that is not modeled, each local variable of the enclosing +function that the block names (all of them, if a name is shadowed) is +treated like an output operand and like an input operand of pointer type, +and the block is treated as having a `"memory"` clobber. ### Limitations -- Only the instructions listed above are modeled. Any inline-assembly - statement that contains an unrecognized instruction is replaced with `skip` - in its entirety, **including any recognized instructions in the same - statement**. This can be unsound if the dropped assembly has side effects - relevant to the property being verified. -- When an inline-assembly statement is dropped, CBMC emits a warning - identifying its source location. You can also use - `goto-instrument --show-goto-functions` (or `cbmc --show-goto-functions`) to - inspect whether an inline-assembly statement was translated or dropped. -- For GCC-style inline assembly, complex atomic operations beyond the basic - `lock; ` pattern listed above are not modeled as - single atomic operations; in particular `xchg` and `lock`-prefixed - read-modify-write instructions (e.g. `lock addl`, `lock cmpxchgl`) are - dropped. -- MSVC-style `__asm` blocks are parsed, but only the x86 - `mfence` / `lfence` / `sfence`, `fstcw` / `fnstcw`, and `fldcw` instructions - are modeled. ARM and Power instructions and `lock` / `xchg` patterns are - **not** modeled for MSVC-style inline assembly. +- The approximation only reaches the objects listed above. Objects that the + statement can reach only through other pointers, for example heap objects + or local variables of a caller that are not pointed to by an operand or an + object of static lifetime, keep their values. Objects of static lifetime + that are added when linking the CPROVER library are not changed. +- Constant objects and the objects that pointers to constant types point to + are not changed. +- Control flow out of a statement is not modeled: `asm goto` statements + always continue with the next statement. +- Atomicity and memory ordering of instructions that are not modeled are not + modeled; such statements are not atomic and do not act as fences. +- A loop that retries an approximated statement until it succeeds, such as a + spin lock that is acquired with `xchg` or `cmpxchg`, may retry arbitrarily + often, as the result of each attempt is nondeterministic. Symbolic + execution thus unwinds such loops up to the unwinding bound, and their + unwinding assertions fail. Replace the functions that contain such loops + by C models (for example, with `goto-instrument --remove-function-body` + and a definition of the function without inline assembly). +- CBMC does not check whether the instructions are valid for the target + architecture: for example, `sync` is modeled as a Power barrier regardless + of the `--arch` option. +- You can use `goto-instrument --show-goto-functions` (or + `cbmc --show-goto-functions`) to inspect how an inline-assembly statement + was translated. From 210d7a26acebff65a2b15299b4ab975b9c9cfd6c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 10:26:28 +0000 Subject: [PATCH 010/100] remove_asm: model stmxcsr and ldmxcsr 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 --- doc/cprover-manual/modeling-inline-asm.md | 16 ++++++------ regression/cbmc-library/__asm_ldmxcsr/main.c | 10 ++++++++ .../cbmc-library/__asm_ldmxcsr/test.desc | 8 ++++++ regression/cbmc-library/__asm_stmxcsr/main.c | 13 ++++++++++ .../cbmc-library/__asm_stmxcsr/test.desc | 8 ++++++ .../main.c | 6 ++--- .../test.desc | 2 +- regression/cbmc/inline_asm_mxcsr/main.c | 23 +++++++++++++++++ regression/cbmc/inline_asm_mxcsr/test.desc | 16 ++++++++++++ src/ansi-c/library/x86_assembler.c | 25 +++++++++++++++++++ src/assembler/remove_asm.cpp | 8 ++++-- 11 files changed, 122 insertions(+), 13 deletions(-) create mode 100644 regression/cbmc-library/__asm_ldmxcsr/main.c create mode 100644 regression/cbmc-library/__asm_ldmxcsr/test.desc create mode 100644 regression/cbmc-library/__asm_stmxcsr/main.c create mode 100644 regression/cbmc-library/__asm_stmxcsr/test.desc create mode 100644 regression/cbmc/inline_asm_mxcsr/main.c create mode 100644 regression/cbmc/inline_asm_mxcsr/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a7ef84412950..14345f63e9b8 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -29,13 +29,15 @@ A statement with an empty assembly template, such as the compiler barrier | `sfence` | Full memory fence (currently modeled identically to `mfence`) | | `fstcw` / `fnstcw` | Stores the rounding mode (`__CPROVER_rounding_mode`) to bits 10 and 11 of the operand; the other bits of the control word are zero | | `fldcw` | Sets the rounding mode from bits 10 and 11 of the operand | +| `stmxcsr` | Stores the rounding mode to bits 13 and 14 of the operand; the other bits of the SSE control and status register are nondeterministic | +| `ldmxcsr` | Sets the rounding mode from bits 13 and 14 of the operand | | `nop`, `pause` | No effect | -For GCC-style statements, the operand of `fstcw`, `fnstcw`, and `fldcw` must -be an operand reference (`%0`, `%1`, ...); for MSVC-style blocks, it must be -the name of a variable. None of the read-modify-write instructions that -take a `lock` prefix is modeled, and neither is `xchg`, so statements using -them are approximated. +For GCC-style statements, the operand of `fstcw`, `fnstcw`, `fldcw`, +`stmxcsr`, and `ldmxcsr` must be an operand reference (`%0`, `%1`, ...); for +MSVC-style blocks, it must be the name of a variable. None of the +read-modify-write instructions that take a `lock` prefix is modeled, and +neither is `xchg`, so statements using them are approximated. #### ARM @@ -55,8 +57,8 @@ them are approximated. | `isync` | Empty fence; no observable effect unless combined with a branch | | `nop` | No effect | -Only the x86 fences, `fstcw`, `fnstcw`, `fldcw`, `nop`, and `pause` are -modeled in MSVC-style blocks. +Only the x86 fences, `fstcw`, `fnstcw`, `fldcw`, `stmxcsr`, `ldmxcsr`, +`nop`, and `pause` are modeled in MSVC-style blocks. ### Conservative Approximation diff --git a/regression/cbmc-library/__asm_ldmxcsr/main.c b/regression/cbmc-library/__asm_ldmxcsr/main.c new file mode 100644 index 000000000000..1777e89dc22a --- /dev/null +++ b/regression/cbmc-library/__asm_ldmxcsr/main.c @@ -0,0 +1,10 @@ +#include +#include + +int main() +{ + unsigned csr = 0x6000; // round toward zero + __asm__("ldmxcsr %0" : : "m"(csr)); + assert(fegetround() == FE_TOWARDZERO); + return 0; +} diff --git a/regression/cbmc-library/__asm_ldmxcsr/test.desc b/regression/cbmc-library/__asm_ldmxcsr/test.desc new file mode 100644 index 000000000000..28345e3383da --- /dev/null +++ b/regression/cbmc-library/__asm_ldmxcsr/test.desc @@ -0,0 +1,8 @@ +CORE gcc-only +main.c +--pointer-check --bounds-check +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/cbmc-library/__asm_stmxcsr/main.c b/regression/cbmc-library/__asm_stmxcsr/main.c new file mode 100644 index 000000000000..bf8b120380ae --- /dev/null +++ b/regression/cbmc-library/__asm_stmxcsr/main.c @@ -0,0 +1,13 @@ +#include +#include + +int main() +{ + unsigned csr; + __asm__("stmxcsr %0" : "=m"(csr)); + assert((csr & 0x6000) == 0); + fesetround(FE_UPWARD); + __asm__("stmxcsr %0" : "=m"(csr)); + assert((csr & 0x6000) == 0x4000); + return 0; +} diff --git a/regression/cbmc-library/__asm_stmxcsr/test.desc b/regression/cbmc-library/__asm_stmxcsr/test.desc new file mode 100644 index 000000000000..28345e3383da --- /dev/null +++ b/regression/cbmc-library/__asm_stmxcsr/test.desc @@ -0,0 +1,8 @@ +CORE gcc-only +main.c +--pointer-check --bounds-check +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/main.c b/regression/cbmc/inline_asm_approximation_rounding_mode/main.c index f702657290ad..83392ca9ed8a 100644 --- a/regression/cbmc/inline_asm_approximation_rounding_mode/main.c +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/main.c @@ -1,9 +1,9 @@ int main(void) { float f = 1.0f; - unsigned csr = 0; - // ldmxcsr is not modeled, and may change the rounding mode - asm volatile("ldmxcsr %0" : : "m"(csr)); + char state[512] = {0}; + // fxrstor is not modeled, and may change the rounding mode + asm volatile("fxrstor %0" : : "m"(state)); // holds with round-to-nearest only __CPROVER_assert(f / 3.0f == 0x1.555556p-2f, "rounding mode"); return 0; diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc index 87fc62729d21..6fc01678b71f 100644 --- a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc @@ -3,7 +3,7 @@ main.c ^EXIT=10$ ^SIGNAL=0$ -approximating inline assembly statement at .* line 6 function main: instruction 'ldmxcsr' is not modeled, so the rounding mode is assigned a nondeterministic value +approximating inline assembly statement at .* line 6 function main: instruction 'fxrstor' is not modeled, so the objects its operands point to ^\[main\.assertion\.1\] line 8 rounding mode: FAILURE$ ^VERIFICATION FAILED$ -- diff --git a/regression/cbmc/inline_asm_mxcsr/main.c b/regression/cbmc/inline_asm_mxcsr/main.c new file mode 100644 index 000000000000..8afc7b4294bd --- /dev/null +++ b/regression/cbmc/inline_asm_mxcsr/main.c @@ -0,0 +1,23 @@ +int main(void) +{ + unsigned csr; + + // the rounding mode is bits 13 and 14 of the SSE control register + asm volatile("stmxcsr %0" : "=m"(csr)); + __CPROVER_assert((csr >> 13 & 3) == 0, "initial rounding mode"); + + // round downwards + csr = (csr & ~0x6000u) | 0x2000u; + asm volatile("ldmxcsr %0" : : "m"(csr)); + float f = 1.0f; + __CPROVER_assert(f / 3.0f == 0x1.555554p-2f, "rounded downwards"); + + unsigned again; + asm volatile("stmxcsr %0" : "=m"(again)); + __CPROVER_assert((again >> 13 & 3) == 1, "rounding mode set by ldmxcsr"); + + // the other bits are not modeled + __CPROVER_assert(again == csr, "other bits"); // fails + + return 0; +} diff --git a/regression/cbmc/inline_asm_mxcsr/test.desc b/regression/cbmc/inline_asm_mxcsr/test.desc new file mode 100644 index 000000000000..22d4fdc5fa5d --- /dev/null +++ b/regression/cbmc/inline_asm_mxcsr/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only no-new-smt +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 7 initial rounding mode: SUCCESS$ +^\[main\.assertion\.2\] line 13 rounded downwards: SUCCESS$ +^\[main\.assertion\.3\] line 17 rounding mode set by ldmxcsr: SUCCESS$ +^\[main\.assertion\.4\] line 20 other bits: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +inline assembly statement at +-- +stmxcsr and ldmxcsr read and set the rounding mode (bits 13 and 14 of the +SSE control and status register); the other bits are not modeled. diff --git a/src/ansi-c/library/x86_assembler.c b/src/ansi-c/library/x86_assembler.c index 9b70e185c3b6..62f2b0c82979 100644 --- a/src/ansi-c/library/x86_assembler.c +++ b/src/ansi-c/library/x86_assembler.c @@ -29,6 +29,31 @@ void __asm_fldcw(void *src) __CPROVER_rounding_mode = ((*(const unsigned short *)src) >> 10) & 3; } +/* FUNCTION: __asm_stmxcsr */ + +extern int __CPROVER_rounding_mode; +unsigned int __VERIFIER_nondet_unsigned_int(void); + +void __asm_stmxcsr(void *dest) +{ + // The rounding mode is bits 13 and 14 in the SSE control and status + // register. The other bits (exception flags and masks, flush-to-zero, + // denormals-are-zero) are not modeled. + *(unsigned int *)dest = (__VERIFIER_nondet_unsigned_int() & ~0x6000u) | + ((unsigned int)__CPROVER_rounding_mode << 13); +} + +/* FUNCTION: __asm_ldmxcsr */ + +extern int __CPROVER_rounding_mode; + +void __asm_ldmxcsr(void *src) +{ + // the rounding mode is bits 13 and 14 in the SSE control and status + // register + __CPROVER_rounding_mode = ((*(const unsigned int *)src) >> 13) & 3; +} + /* FUNCTION: __asm_mfence */ void __asm_mfence(void) diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 205c33b22716..49d80893e537 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -550,7 +550,9 @@ bool remove_asmt::handle_gcc_command( return true; }; - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + if( + command == "fstcw" || command == "fnstcw" || command == "fldcw" || + command == "stmxcsr" || command == "ldmxcsr") // x86 { const auto operand = gcc_operand(code, pos, instruction); if(!operand.has_value()) @@ -723,7 +725,9 @@ bool remove_asmt::handle_msc_command( { const bool no_operands = pos == instruction.size(); - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + if( + command == "fstcw" || command == "fnstcw" || command == "fldcw" || + command == "stmxcsr" || command == "ldmxcsr") // x86 { if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) return false; From f8540db09a19d0eb11f2224f1274f8f582eae6e6 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:11:52 +0000 Subject: [PATCH 011/100] remove_asm: write the outputs of statements that are modeled 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 --- doc/cprover-manual/modeling-inline-asm.md | 32 ++- .../cbmc/inline_asm_modeled_outputs/main.c | 48 +++++ .../cbmc/inline_asm_modeled_outputs/test.desc | 23 +++ src/ansi-c/parser.y | 6 + src/assembler/asm_approximation.cpp | 161 +++++++++++---- src/assembler/asm_approximation.h | 53 +++++ src/assembler/remove_asm.cpp | 194 ++++++++++++++++-- 7 files changed, 463 insertions(+), 54 deletions(-) create mode 100644 regression/cbmc/inline_asm_modeled_outputs/main.c create mode 100644 regression/cbmc/inline_asm_modeled_outputs/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 14345f63e9b8..29961e54067b 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -8,15 +8,17 @@ each inline-assembly statement by goto-program instructions: - If CBMC models every instruction of the statement (see the tables below), the statement is translated into the corresponding fences or calls to - library functions. + library functions, followed by assignments to its output operands. - Otherwise the statement is **approximated conservatively**: everything the statement may change, as far as CBMC can tell from its operands, is assigned a nondeterministic value, and a warning that names the first instruction that is not modeled is printed. The modeled instructions of such a statement are not translated either. -A statement with an empty assembly template, such as the compiler barrier -`asm volatile("" ::: "memory")`, does nothing. +A statement with an empty assembly template has no instructions, so CBMC +models it. Such a statement only writes its output operands (see Output +Operands below); without outputs, as in the compiler barrier +`asm volatile("" ::: "memory")`, it does nothing. ### Supported Instructions @@ -60,6 +62,30 @@ neither is `xchg`, so statements using them are approximated. Only the x86 fences, `fstcw`, `fnstcw`, `fldcw`, `stmxcsr`, `ldmxcsr`, `nop`, and `pause` are modeled in MSVC-style blocks. +### Output Operands + +If CBMC models every instruction of a GCC-style statement, the output +operands with an `=` constraint are written as follows, after the +instructions: + +- An output that a modeled instruction writes (the operand of `fstcw`, + `fnstcw`, or `stmxcsr`) receives the value that the instruction stores. +- An output that is tied to an input operand by a matching constraint (an + input constraint that is the number of the output, as in + `asm("" : "=r"(x) : "0"(y))`, or its symbolic name in brackets, as in + `"[out]"`) receives the value of that input, as none of the modeled + instructions changes the register that holds both. This requires that the + types of input and output are the same, or are integer, enumeration, or + pointer types of the same width; otherwise the output is treated as not + tied. +- Any other output is assigned a nondeterministic value: none of the + modeled instructions writes it, so it receives whatever the register (or + memory location) that the compiler chose for it holds. + +All inputs and the addresses of all outputs are evaluated before any output +is written. In-out operands (those with a `+` constraint) keep their values +unless a modeled instruction writes them. + ### Conservative Approximation The operands of a GCC-style statement are evaluated before the statement, diff --git a/regression/cbmc/inline_asm_modeled_outputs/main.c b/regression/cbmc/inline_asm_modeled_outputs/main.c new file mode 100644 index 000000000000..4b0c1e2f4854 --- /dev/null +++ b/regression/cbmc/inline_asm_modeled_outputs/main.c @@ -0,0 +1,48 @@ +int main(void) +{ + // an empty template with an output tied to an input, as in the Linux + // kernel's RELOC_HIDE and OPTIMIZER_HIDE_VAR: the output receives the value + // of the input + int x = 0, y = 5; + asm("" : "=r"(x) : "0"(y)); + __CPROVER_assert(x == 5, "tied output"); + + // the same, with a symbolic name + int a = 0, b = 6; + asm("" : [out] "=r"(a) : "[out]"(b)); + __CPROVER_assert(a == 6, "tied named output"); + + // an output that is not tied to an input receives the contents of a + // register that CBMC does not know + int z = 0, w = 7; + asm volatile("nop" : "=a"(z) : "a"(w)); + __CPROVER_assert(z == 0, "untied output"); // fails + + // an in-out operand keeps its value + int c = 8; + asm("" : "+r"(c)); + __CPROVER_assert(c == 8, "in-out operand"); + + // all inputs are read before any output is written + int p = 1, q = 2; + asm("" : "=r"(p), "=r"(q) : "0"(q), "1"(p)); + __CPROVER_assert(p == 2 && q == 1, "swapped"); + + // the addresses of the outputs are those before the statement + int idx = 0, arr[2] = {0, 0}; + asm("" : "=r"(idx), "=r"(arr[idx]) : "0"(1), "1"(9)); + __CPROVER_assert(idx == 1 && arr[0] == 9 && arr[1] == 0, "addresses"); + + // the upper bits of a wider output are not known + long long wide = 0; + int narrow = 3; + asm("" : "=r"(wide) : "0"(narrow)); + __CPROVER_assert(wide == 3, "wider output"); // fails + + // an output that a modeled instruction writes is not changed otherwise + unsigned short cw; + asm volatile("fnstcw %0" : "=m"(cw)); + __CPROVER_assert((cw >> 10 & 3) == 0, "written by fnstcw"); + + return 0; +} diff --git a/regression/cbmc/inline_asm_modeled_outputs/test.desc b/regression/cbmc/inline_asm_modeled_outputs/test.desc new file mode 100644 index 000000000000..f71b7af03022 --- /dev/null +++ b/regression/cbmc/inline_asm_modeled_outputs/test.desc @@ -0,0 +1,23 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 8 tied output: SUCCESS$ +^\[main\.assertion\.2\] line 13 tied named output: SUCCESS$ +^\[main\.assertion\.3\] line 19 untied output: FAILURE$ +^\[main\.assertion\.4\] line 24 in-out operand: SUCCESS$ +^\[main\.assertion\.5\] line 29 swapped: SUCCESS$ +^\[main\.assertion\.6\] line 34 addresses: SUCCESS$ +^\[main\.assertion\.7\] line 40 wider output: FAILURE$ +^\[main\.assertion\.8\] line 45 written by fnstcw: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +inline assembly statement at +-- +The instructions of these statements are all modeled. Their outputs with an +"=" constraint are written by the statement: an output tied to an input by a +matching constraint receives the value of the input (if the types have the +same width), any other output receives a nondeterministic value unless a +modeled instruction writes it. These outputs used to keep their values. diff --git a/src/ansi-c/parser.y b/src/ansi-c/parser.y index ffa7d4d35bbd..fb31beee0248 100644 --- a/src/ansi-c/parser.y +++ b/src/ansi-c/parser.y @@ -2888,6 +2888,9 @@ gcc_asm_output: { $$=$5; parser_stack($$).id(ID_gcc_asm_output); + // the symbolic name, for %[name] references + parser_stack($$).set( + ID_identifier, parser_stack($2).get(ID_C_base_name)); parser_stack($$).add_to_operands(std::move(parser_stack($4)), std::move(parser_stack($6))); } ; @@ -2925,6 +2928,9 @@ gcc_asm_input: { $$=$5; parser_stack($$).id(ID_gcc_asm_input); + // the symbolic name, for %[name] references + parser_stack($$).set( + ID_identifier, parser_stack($2).get(ID_C_base_name)); parser_stack($$).add_to_operands(std::move(parser_stack($4)), std::move(parser_stack($6))); } ; diff --git a/src/assembler/asm_approximation.cpp b/src/assembler/asm_approximation.cpp index 758e74ed3e67..749dc8901c52 100644 --- a/src/assembler/asm_approximation.cpp +++ b/src/assembler/asm_approximation.cpp @@ -230,6 +230,126 @@ static void havoc_pointee( skip->complete_goto(dest.add(goto_programt::make_skip(source_location))); } +symbol_exprt asm_approximationt::snapshot( + const exprt &value, + const std::string &base_name, + const irep_idt &function_id, + const source_locationt &source_location, + std::vector &temporaries, + goto_programt &dest) +{ + // the temporary is assigned, and must not be subject to --nondet-volatile + typet type = value.type(); + type.remove(ID_C_constant); + type.remove(ID_C_volatile); + const symbolt &tmp = get_fresh_aux_symbol( + type, + id2string(function_id), + base_name, + source_location, + ID_C, + symbol_table); + const symbol_exprt tmp_expr = tmp.symbol_expr(); + temporaries.push_back(tmp_expr); + dest.add(goto_programt::make_decl(tmp_expr, source_location)); + dest.add(goto_programt::make_assignment( + tmp_expr, typecast_exprt::conditional_cast(value, type), source_location)); + return tmp_expr; +} + +exprt asm_approximationt::at_current_address( + const exprt &lvalue, + const irep_idt &function_id, + const source_locationt &source_location, + std::vector &temporaries, + goto_programt &dest) +{ + exprt result = lvalue; + std::vector bit_field_members; + while(result.id() == ID_member && result.type().id() == ID_c_bit_field) + { + bit_field_members.push_back(to_member_expr(result)); + result = to_member_expr(result).struct_op(); + } + + if(!has_constant_address(result)) + { + result = dereference_exprt{snapshot( + address_of_exprt{result}, + "asm_address", + function_id, + source_location, + temporaries, + dest)}; + } + + for(auto it = bit_field_members.rbegin(); it != bit_field_members.rend(); + ++it) + { + result = member_exprt{result, it->get_component_name(), it->type()}; + } + + return result; +} + +void asm_approximationt::assign_outputs( + const std::vector &outputs, + goto_programt &instructions, + const irep_idt &function_id, + const source_locationt &source_location, + goto_programt &dest) +{ + std::vector temporaries; + + // 1. the values and addresses before the statement executes + std::vector>> assignments; + for(const auto &output : outputs) + { + std::optional value; + if(output.value.has_value()) + { + const exprt &v = *output.value; + if( + v.is_constant() || + (v.id() == ID_address_of && + has_constant_address(to_address_of_expr(v).object()))) + { + value = v; + } + else + { + value = snapshot( + v, "asm_value", function_id, source_location, temporaries, dest); + } + } + assignments.emplace_back( + at_current_address( + output.lvalue, function_id, source_location, temporaries, dest), + std::move(value)); + } + + // 2. the instructions + dest.destructive_append(instructions); + + // 3. the outputs + for(const auto &assignment : assignments) + { + if(assignment.second.has_value()) + { + dest.add(goto_programt::make_assignment( + assignment.first, + typecast_exprt::conditional_cast( + *assignment.second, assignment.first.type()), + source_location)); + } + else + havoc_lvalue(assignment.first, source_location, dest); + } + + for(auto it = temporaries.rbegin(); it != temporaries.rend(); ++it) + dest.add(goto_programt::make_dead(*it, source_location)); +} + void asm_approximationt::operator()( const asm_footprintt &footprint, const std::vector &address_taken_locals, @@ -250,21 +370,6 @@ void asm_approximationt::operator()( // 2. record the values of addresses before any of them is changed, as the // instructions below may change the objects these are stored in - auto snapshot = [&](const exprt &value) -> exprt - { - const symbolt &tmp = get_fresh_aux_symbol( - value.type(), - id2string(function_id), - "asm_address", - source_location, - ID_C, - symbol_table); - const symbol_exprt tmp_expr = tmp.symbol_expr(); - temporaries.push_back(tmp_expr); - dest.add(goto_programt::make_decl(tmp_expr, source_location)); - dest.add(goto_programt::make_assignment(tmp_expr, value, source_location)); - return tmp_expr; - }; // pointers, and the values of the pointers stored in objects of static // lifetime if the statement may access arbitrary memory @@ -290,32 +395,16 @@ void asm_approximationt::operator()( continue; } } - pointers.push_back(snapshot(address)); + pointers.push_back(snapshot( + address, "asm_address", function_id, source_location, temporaries, dest)); } - // the lvalues written, with addresses evaluated before the statement; for - // bit fields, whose address cannot be taken, record the address of the - // enclosing object + // the lvalues written, with addresses evaluated before the statement std::vector writes; for(const auto &write : footprint.writes) { - exprt lvalue = write; - std::vector bit_field_members; - while(lvalue.id() == ID_member && lvalue.type().id() == ID_c_bit_field) - { - bit_field_members.push_back(to_member_expr(lvalue)); - lvalue = to_member_expr(lvalue).struct_op(); - } - - if(!has_constant_address(lvalue)) - lvalue = dereference_exprt{snapshot(address_of_exprt{lvalue})}; - - for(auto it = bit_field_members.rbegin(); it != bit_field_members.rend(); - ++it) - { - lvalue = member_exprt{lvalue, it->get_component_name(), it->type()}; - } - writes.push_back(lvalue); + writes.push_back(at_current_address( + write, function_id, source_location, temporaries, dest)); } // 3. the objects pointed to diff --git a/src/assembler/asm_approximation.h b/src/assembler/asm_approximation.h index 7d2a031cd5ca..0d7ca241fa1d 100644 --- a/src/assembler/asm_approximation.h +++ b/src/assembler/asm_approximation.h @@ -87,6 +87,35 @@ class asm_approximationt const source_locationt &source_location, goto_programt &dest); + /// An output operand that a statement whose instructions are all modeled + /// writes, but none of these instructions does: the lvalue and the value it + /// receives, or no value if the value is not known. + struct outputt + { + exprt lvalue; + std::optional value; + }; + + /// Appends to \p dest instructions that + /// 1. record the values of \p outputs and the addresses of their lvalues + /// in temporaries, unless these do not depend on the program state; + /// 2. execute \p instructions, the translation of the instructions of the + /// statement, which are moved to \p dest; + /// 3. assign the lvalues of \p outputs their values, or nondeterministic + /// values if no value is given. + /// \param outputs: The outputs to assign + /// \param instructions: The translation of the instructions + /// \param function_id: Name of the enclosing function, which temporaries + /// are added to + /// \param source_location: Location of the statement + /// \param dest: Goto program to append the instructions to + void assign_outputs( + const std::vector &outputs, + goto_programt &instructions, + const irep_idt &function_id, + const source_locationt &source_location, + goto_programt &dest); + /// \return The local variables of \p body whose address is taken, sorted by /// name and excluding objects of static lifetime and constant objects. static std::vector @@ -107,6 +136,30 @@ class asm_approximationt std::optional> static_objects; const std::vector &get_static_objects(); + + /// Appends to \p dest the declaration of a fresh temporary of the function + /// \p function_id, whose name starts with \p base_name, and the assignment + /// of \p value to it, and adds the temporary to \p temporaries. + /// \return The temporary + symbol_exprt snapshot( + const exprt &value, + const std::string &base_name, + const irep_idt &function_id, + const source_locationt &source_location, + std::vector &temporaries, + goto_programt &dest); + + /// \return \p lvalue, but at the address it has now: if the address of + /// \p lvalue depends on the program state, the address is recorded in a + /// temporary as described for \ref snapshot. For a bit field, whose + /// address cannot be taken, the address of the enclosing object is + /// recorded. + exprt at_current_address( + const exprt &lvalue, + const irep_idt &function_id, + const source_locationt &source_location, + std::vector &temporaries, + goto_programt &dest); }; #endif // CPROVER_ASSEMBLER_ASM_APPROXIMATION_H diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 49d80893e537..f4db613ff999 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -19,6 +19,7 @@ Date: December 2014 #include #include #include +#include #include #include #include @@ -31,6 +32,7 @@ Date: December 2014 #include "asm_approximation.h" #include "assembler_parser.h" +#include #include #include #include @@ -114,6 +116,7 @@ class remove_asmt std::size_t pos, const assembler_parsert::instructiont &instruction, const code_asm_gcct &code, + std::set &written_operands, goto_programt &tmp_dest); bool handle_msc_command( @@ -399,9 +402,138 @@ void remove_asmt::approximate_asm( << messaget::eom; } +/// \return The constraint of the operand \p operand of a gcc-style statement, +/// or the empty string if it has none. +static std::string gcc_constraint(const exprt &operand) +{ + if(operand.operands().size() != 2) + return {}; + const exprt &constraint = to_binary_expr(operand).op0(); + if(constraint.id() != ID_string_constant) + return {}; + return id2string(to_string_constant(constraint).value()); +} + +/// \return The index of the output among \p outputs that an input with +/// constraint \p constraint is tied to by a matching constraint (a number, +/// or the symbolic name of the output in brackets), if any. +static std::optional +matched_output(const std::string &constraint, const exprt::operandst &outputs) +{ + if( + !constraint.empty() && constraint.size() <= 2 && + std::all_of( + constraint.begin(), + constraint.end(), + [](char c) { return isdigit(static_cast(c)) != 0; })) + { + const std::size_t index = std::stoul(constraint); + if(index < outputs.size()) + return index; + return {}; + } + + if( + constraint.size() > 2 && constraint.front() == '[' && + constraint.back() == ']') + { + const std::string name = constraint.substr(1, constraint.size() - 2); + for(std::size_t i = 0; i < outputs.size(); ++i) + { + if(id2string(outputs[i].get(ID_identifier)) == name) + return i; + } + } + + return {}; +} + +/// \return Whether converting a value of type \p from to type \p to keeps +/// its bits, so that the converted value is what a register that holds the +/// value as an input of type \p from holds as an output of type \p to. +static bool +same_register_value(const typet &from, const typet &to, const namespacet &ns) +{ + if(from == to) + return true; + + auto is_bit_vector = [](const typet &type) + { + return type.id() == ID_signedbv || type.id() == ID_unsignedbv || + type.id() == ID_pointer || type.id() == ID_c_enum_tag; + }; + if(!is_bit_vector(from) || !is_bit_vector(to)) + return false; + + const auto from_width = pointer_offset_bits(from, ns); + return from_width.has_value() && from_width == pointer_offset_bits(to, ns); +} + +/// \return The output operands of \p code, a statement whose instructions +/// are all modeled, that the translation of the instructions does not +/// write, but the statement does: those with an `=` constraint whose +/// indices are not in \p written_operands. An output that is tied to an +/// input by a matching constraint receives the value of that input, as the +/// instructions do not change the register that holds both, provided that +/// the value of the input can be converted to the type of the output +/// without changing its bits. The other outputs receive nondeterministic +/// values. In-out operands (`+`) keep their values. +static std::vector outputs_of_modeled( + const code_asm_gcct &code, + const std::set &written_operands, + const namespacet &ns) +{ + const exprt::operandst &outputs = code.outputs().operands(); + + std::vector> assigned{ + outputs.size()}; + for(std::size_t i = 0; i < outputs.size(); ++i) + { + if( + outputs[i].operands().size() == 2 && + gcc_constraint(outputs[i]).find('+') == std::string::npos && + written_operands.find(i) == written_operands.end()) + { + assigned[i] = + asm_approximationt::outputt{to_binary_expr(outputs[i]).op1(), {}}; + } + } + + // inputs tied to the outputs; an output tied to more than one input is + // assigned a nondeterministic value + std::vector ties(outputs.size(), 0); + for(const auto &input : code.inputs().operands()) + { + const auto index = matched_output(gcc_constraint(input), outputs); + if(!index.has_value() || !assigned[*index].has_value()) + continue; + + auto &output = *assigned[*index]; + const exprt &value = to_binary_expr(input).op1(); + if( + ++ties[*index] == 1 && + same_register_value(value.type(), output.lvalue.type(), ns)) + { + output.value = value; + } + else + output.value.reset(); + } + + std::vector result; + for(auto &output : assigned) + { + if(output.has_value()) + result.push_back(std::move(*output)); + } + return result; +} + /// Translates the given inline assembly code (in gcc style) to non-assembly /// goto program instructions, approximating it conservatively if it -/// contains an instruction that is not modeled. +/// contains an instruction that is not modeled. If all instructions are +/// modeled, the outputs that the instructions do not write are assigned as +/// described for \ref outputs_of_modeled. /// /// \param function_id: Name of function being processed /// \param code: The inline assembly code statement to translate @@ -414,21 +546,35 @@ void remove_asmt::process_instruction_gcc( const instructionst instructions = parse(to_string_constant(code.asm_text()).value()); + goto_programt modeled; + std::set written_operands; const auto unknown = process_asm( code, instructions, - dest, - [this, &code]( + modeled, + [this, &code, &written_operands]( const irep_idt &command, std::size_t pos, const assembler_parsert::instructiont &instruction, goto_programt &tmp_dest) - { return handle_gcc_command(command, pos, instruction, code, tmp_dest); }); + { + return handle_gcc_command( + command, pos, instruction, code, written_operands, tmp_dest); + }); + + const namespacet ns{symbol_table}; if(!unknown.has_value()) + { + approximate.assign_outputs( + outputs_of_modeled(code, written_operands, ns), + modeled, + function_id, + code.source_location(), + dest); return; + } - const namespacet ns{symbol_table}; asm_footprintt footprint; for(const auto &output : code.outputs().operands()) @@ -489,10 +635,11 @@ void remove_asmt::process_instruction_gcc( dest); } -/// \return The operand of \p code referred to as `%N` by the tokens of -/// \p instruction starting at \p pos, if these are the only remaining -/// tokens. Operands are numbered as in gcc: outputs first, then inputs. -static std::optional gcc_operand( +/// \return The index of the operand of \p code referred to as `%N` by the +/// tokens of \p instruction starting at \p pos, if these are the only +/// remaining tokens. Operands are numbered as in gcc: outputs first, then +/// inputs. +static std::optional gcc_operand_index( const code_asm_gcct &code, std::size_t pos, const assembler_parsert::instructiont &instruction) @@ -509,27 +656,41 @@ static std::optional gcc_operand( index = index * 10 + static_cast(digit[0] - '0'); } + std::size_t remaining = index; for(const auto *list : {&code.outputs(), &code.inputs()}) { for(const auto &operand : list->operands()) { if(operand.operands().size() != 2) return {}; - if(index == 0) - return to_binary_expr(operand).op1(); - --index; + if(remaining == 0) + return index; + --remaining; } } return {}; } +/// \return The expression of the operand of \p code with index \p index, as +/// returned by \ref gcc_operand_index. +static const exprt &gcc_operand(const code_asm_gcct &code, std::size_t index) +{ + const auto &outputs = code.outputs().operands(); + const exprt &operand = index < outputs.size() + ? outputs[index] + : code.inputs().operands()[index - outputs.size()]; + return to_binary_expr(operand).op1(); +} + /// Translates a single recognized gcc-style command into \p tmp_dest. /// /// \param command: The instruction mnemonic to translate /// \param pos: Index of the token following the command in \p instruction /// \param instruction: The parsed instruction tokens /// \param code: The inline assembly code statement being translated +/// \param [out] written_operands: The indices of the operands of \p code +/// that the translation writes are added to this set /// \param tmp_dest: The goto program to append the translation to /// \return Whether the command was recognized (and hence modeled) bool remove_asmt::handle_gcc_command( @@ -537,6 +698,7 @@ bool remove_asmt::handle_gcc_command( std::size_t pos, const assembler_parsert::instructiont &instruction, const code_asm_gcct &code, + std::set &written_operands, goto_programt &tmp_dest) { const source_locationt &source_location = code.source_location(); @@ -554,14 +716,16 @@ bool remove_asmt::handle_gcc_command( command == "fstcw" || command == "fnstcw" || command == "fldcw" || command == "stmxcsr" || command == "ldmxcsr") // x86 { - const auto operand = gcc_operand(code, pos, instruction); - if(!operand.has_value()) + const auto index = gcc_operand_index(code, pos, instruction); + if(!index.has_value()) return false; asm_function_call( "__asm_" + id2string(command), - {address_of_exprt{*operand}}, + {address_of_exprt{gcc_operand(code, *index)}}, source_location, tmp_dest); + if(command != "fldcw" && command != "ldmxcsr") + written_operands.insert(*index); return true; } From c17598b166d9c77813e3859cdecb4d4e156ff81c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:14:54 +0000 Subject: [PATCH 012/100] C front end: asm blocks in braces are MSVC-style in all modes 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 --- doc/cprover-manual/modeling-inline-asm.md | 17 +++++++++----- .../cbmc/asm_block_function_body/main.c | 16 ++++++++++---- .../cbmc/asm_block_function_body/test.desc | 11 +++++++--- regression/cbmc/asm_block_gcc/main.c | 22 +++++++++++++++++++ regression/cbmc/asm_block_gcc/test.desc | 19 ++++++++++++++++ src/ansi-c/parser.y | 15 +++++++------ 6 files changed, 80 insertions(+), 20 deletions(-) create mode 100644 regression/cbmc/asm_block_gcc/main.c create mode 100644 regression/cbmc/asm_block_gcc/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 29961e54067b..465f78f78c13 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -3,8 +3,13 @@ ## Modeling Inline Assembly CBMC supports GCC-style (`asm`/`__asm__`) and MSVC-style (`__asm {}`) -inline assembly syntax. Before verification, the `remove_asm` pass replaces -each inline-assembly statement by goto-program instructions: +inline assembly syntax. Blocks in braces (`asm { ... }`, `__asm { ... }`, +and `__asm__ { ... }`, which Clang and Apple's GCC accept with +`-fasm-blocks`) and functions whose body is a block of assembly (as in +`void asm f(int *p) { ... }`, which Apple's GCC and CodeWarrior accept) use +Intel syntax and name C variables; CBMC treats them as MSVC-style blocks in +all modes. Before verification, the `remove_asm` pass replaces each +inline-assembly statement by goto-program instructions: - If CBMC models every instruction of the statement (see the tables below), the statement is translated into the corresponding fences or calls to @@ -110,10 +115,10 @@ instruction that is not modeled, then 5. the rounding mode is assigned a nondeterministic value. MSVC-style blocks have no operand interface. If a block contains an -instruction that is not modeled, each local variable of the enclosing -function that the block names (all of them, if a name is shadowed) is -treated like an output operand and like an input operand of pointer type, -and the block is treated as having a `"memory"` clobber. +instruction that is not modeled, each local variable (or parameter) of the +enclosing function that the block names (all of them, if a name is +shadowed) is treated like an output operand and like an input operand of +pointer type, and the block is treated as having a `"memory"` clobber. ### Limitations diff --git a/regression/cbmc/asm_block_function_body/main.c b/regression/cbmc/asm_block_function_body/main.c index f2370cf4dae2..3d35230d94c1 100644 --- a/regression/cbmc/asm_block_function_body/main.c +++ b/regression/cbmc/asm_block_function_body/main.c @@ -1,15 +1,23 @@ #ifdef __GNUC__ -// an asm block as a function body, as with gcc -fasm-blocks -void asm test() +// an asm block as a function body, as with Apple gcc -fasm-blocks: like an +// MSVC block, it uses Intel syntax and names the parameters +// clang-format off +void asm test(int *p) { - mov eax, eax + mov eax, p + mov dword ptr [eax], 1 } +// clang-format on #endif int main() { + int x = 0; #ifdef __GNUC__ - test(); + test(&x); +#else + x = 1; #endif + __CPROVER_assert(x == 0, "x unchanged"); // fails return 0; } diff --git a/regression/cbmc/asm_block_function_body/test.desc b/regression/cbmc/asm_block_function_body/test.desc index debc63cbcefb..6c3daf17ff3f 100644 --- a/regression/cbmc/asm_block_function_body/test.desc +++ b/regression/cbmc/asm_block_function_body/test.desc @@ -1,12 +1,17 @@ CORE main.c -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.1\] line 21 x unchanged: FAILURE$ +^VERIFICATION FAILED$ -- ^warning: ignoring Invariant check failed -- An asm block that forms a function body (as with gcc -fasm-blocks) used to -have no assembler flavor, which made remove_asm fail an invariant. +have no assembler flavor, which made remove_asm fail an invariant. Such a +block uses Intel syntax and names C variables, as an MSVC block does, so it +has the msc flavor: the parameter p it names is treated as an operand of +pointer type, and x, which p points to, may be changed. As gcc-style basic +assembly, the statement did not change x. diff --git a/regression/cbmc/asm_block_gcc/main.c b/regression/cbmc/asm_block_gcc/main.c new file mode 100644 index 000000000000..869e366e0853 --- /dev/null +++ b/regression/cbmc/asm_block_gcc/main.c @@ -0,0 +1,22 @@ +int main(void) +{ + // an Intel-syntax block (gcc and clang -fasm-blocks, MSVC) names the + // variables it accesses + int x = 0; + __asm { mov x, 1 } + __CPROVER_assert(x == 0, "x unchanged"); // fails + + int y = 0; +#ifdef __GNUC__ + __asm__ { mov y, 1 } +#else + y = 1; +#endif + __CPROVER_assert(y == 0, "y unchanged"); // fails + + int z = 0; + __asm { mov eax, 1 } + __CPROVER_assert(z == 0, "z unchanged"); // holds + + return 0; +} diff --git a/regression/cbmc/asm_block_gcc/test.desc b/regression/cbmc/asm_block_gcc/test.desc new file mode 100644 index 000000000000..3620f75960b7 --- /dev/null +++ b/regression/cbmc/asm_block_gcc/test.desc @@ -0,0 +1,19 @@ +CORE +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 7 x unchanged: FAILURE$ +^\[main\.assertion\.2\] line 15 y unchanged: FAILURE$ +^\[main\.assertion\.3\] line 19 z unchanged: SUCCESS$ +^approximating inline assembly statement at file main\.c line 6 function main: instruction 'mov' is not modeled, so the local variables it names, +^VERIFICATION FAILED$ +-- +^warning: ignoring +Invariant check failed +-- +In gcc mode, an asm block in braces (as with gcc and clang -fasm-blocks) was +treated as gcc-style basic assembly, which only changes objects of static +lifetime and address-taken local variables, so x and y kept their values. +Such a block uses Intel syntax and names C variables, as an MSVC block does, +so it now has the msc flavor and changes the local variables it names. diff --git a/src/ansi-c/parser.y b/src/ansi-c/parser.y index fb31beee0248..2853d9e47c11 100644 --- a/src/ansi-c/parser.y +++ b/src/ansi-c/parser.y @@ -2496,13 +2496,13 @@ compound_statement: | compound_scope '{' TOK_ASM_STRING '}' { // a block of assembly following the asm keyword, as in - // asm int f() { ... }: gcc-style basic assembly + // asm int f() { ... } (gcc -fasm-blocks, CodeWarrior): like an + // MSVC block, it uses Intel syntax and names C variables $$=$2; statement($$, ID_asm); - parser_stack($$).set(ID_flavor, ID_gcc); + parser_stack($$).set(ID_flavor, ID_msc); parser_stack($$).set(ID_C_end_location, parser_stack($4).source_location()); - parser_stack($$).operands().resize(5); - to_multi_ary_expr(parser_stack($$)).op0()=parser_stack($3); + mto($$, $3); PARSER.pop_scope(); } ; @@ -2735,11 +2735,12 @@ gcc_asm_statement: } | TOK_GCC_ASM_PAREN volatile_or_goto_opt '{' TOK_ASM_STRING '}' { + // asm { ... } (gcc -fasm-blocks, CodeWarrior): like an MSVC block, + // it uses Intel syntax and names C variables $$=$1; statement($$, ID_asm); - parser_stack($$).set(ID_flavor, ID_gcc); - parser_stack($$).operands().resize(5); - to_multi_ary_expr(parser_stack($$)).op0()=parser_stack($4); + parser_stack($$).set(ID_flavor, ID_msc); + mto($$, $4); } ; From b385391ea6fed6041797b572d2104d7d58e5b242 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:20:22 +0000 Subject: [PATCH 013/100] remove_asm: '#' starts a comment only where the target says so 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 --- doc/cprover-manual/modeling-inline-asm.md | 12 ++ regression/cbmc/inline_asm_hash/arm.desc | 14 ++ regression/cbmc/inline_asm_hash/barriers.desc | 16 +++ regression/cbmc/inline_asm_hash/barriers.i | 10 ++ regression/cbmc/inline_asm_hash/comments.i | 6 + regression/cbmc/inline_asm_hash/main.i | 18 +++ regression/cbmc/inline_asm_hash/ppc.desc | 12 ++ regression/cbmc/inline_asm_hash/test.desc | 14 ++ regression/cbmc/inline_asm_hash/x86.desc | 12 ++ regression/validate-trace-xml-schema/check.py | 4 + src/assembler/assembler_parser.h | 14 ++ src/assembler/remove_asm.cpp | 125 ++++++++++++++++-- src/assembler/scanner.l | 11 +- 13 files changed, 255 insertions(+), 13 deletions(-) create mode 100644 regression/cbmc/inline_asm_hash/arm.desc create mode 100644 regression/cbmc/inline_asm_hash/barriers.desc create mode 100644 regression/cbmc/inline_asm_hash/barriers.i create mode 100644 regression/cbmc/inline_asm_hash/comments.i create mode 100644 regression/cbmc/inline_asm_hash/main.i create mode 100644 regression/cbmc/inline_asm_hash/ppc.desc create mode 100644 regression/cbmc/inline_asm_hash/test.desc create mode 100644 regression/cbmc/inline_asm_hash/x86.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 465f78f78c13..9c796eb582cc 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -27,6 +27,13 @@ Operands below); without outputs, as in the compiler barrier ### Supported Instructions +CBMC splits the assembler text into instructions at newlines and `;`. On +x86 (and in MSVC-style blocks), Power, MIPS, RISC-V, s390, and LoongArch, +`#` starts a comment that extends to the end of the line. For the other +targets (see `--arch`), including ARM and AArch64, `#` starts a comment only +at the start of a line or statement; elsewhere it introduces an immediate +operand, as in `dmb #11`. + #### x86 | Instruction | Effect in CBMC | @@ -54,6 +61,11 @@ neither is `xchg`, so statements using them are approximated. | `isb` | Empty fence; no observable effect unless combined with a branch | | `nop`, `yield` | No effect | +The barrier options can also be given as immediates: `#15` is `sy`, `#14` +`st`, `#13` `ld`, `#11` `ish`, `#10` `ishst`, `#9` `ishld`, `#7` `nsh`, `#6` +`nshst`, `#5` `nshld`, `#3` `osh`, `#2` `oshst`, and `#1` `oshld`. The other +values are reserved, and barriers with them are not modeled. + #### Power | Instruction | Effect in CBMC | diff --git a/regression/cbmc/inline_asm_hash/arm.desc b/regression/cbmc/inline_asm_hash/arm.desc new file mode 100644 index 000000000000..b6b7dc970877 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/arm.desc @@ -0,0 +1,14 @@ +CORE +comments.i +--arch arm64 --show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^approximating inline assembly statement at file comments\.i line 3 function main: instruction 'mfence' is not modeled +^approximating inline assembly statement at file comments\.i line 4 function main: instruction 'sync' is not modeled +-- +^warning: ignoring +^ *CALL __asm_mfence\(\)$ +^ *FENCE +-- +On AArch64, '#' after the start of a statement introduces an immediate, so +the instructions have operands they do not take and are not modeled. diff --git a/regression/cbmc/inline_asm_hash/barriers.desc b/regression/cbmc/inline_asm_hash/barriers.desc new file mode 100644 index 000000000000..700b7f4b528d --- /dev/null +++ b/regression/cbmc/inline_asm_hash/barriers.desc @@ -0,0 +1,16 @@ +CORE +barriers.i +--arch arm64 --show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^ *FENCE RR RW$ +^ *FENCE WW$ +^ *FENCE WW RR RW WR$ +^ *FENCE$ +^approximating inline assembly statement at file barriers\.i line 8 function main: instruction 'dmb' is not modeled +-- +^warning: ignoring +^approximating inline assembly statement at file barriers\.i line [4-7] function +-- +The immediate forms of the options of dmb, dsb, and isb are modeled like the +named options; reserved options are not modeled. diff --git a/regression/cbmc/inline_asm_hash/barriers.i b/regression/cbmc/inline_asm_hash/barriers.i new file mode 100644 index 000000000000..5040c5121613 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/barriers.i @@ -0,0 +1,10 @@ +// the immediate forms of the barrier options +int main(void) +{ + asm volatile("dmb #9"); // ishld + asm volatile("dmb #10"); // ishst + asm volatile("dsb #15"); // sy + asm volatile("isb #15"); // sy + asm volatile("dmb #0x0"); // reserved + return 0; +} diff --git a/regression/cbmc/inline_asm_hash/comments.i b/regression/cbmc/inline_asm_hash/comments.i new file mode 100644 index 000000000000..4b0407899d10 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/comments.i @@ -0,0 +1,6 @@ +int main(void) +{ + asm volatile("mfence # x86 comment"); + asm volatile("sync # Power comment"); + return 0; +} diff --git a/regression/cbmc/inline_asm_hash/main.i b/regression/cbmc/inline_asm_hash/main.i new file mode 100644 index 000000000000..1795bba4ad69 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/main.i @@ -0,0 +1,18 @@ +// preprocessed input, as preprocessing for --arch arm64 may fail on hosts +// of other architectures +int main(void) +{ + // on ARM and AArch64, '#' introduces an immediate: the store must not be + // lost in a comment + int v = 0; + int *p = &v; + asm volatile("dmb #11; str %w1, [%0]" : : "r"(p), "r"(1) : "memory"); + __CPROVER_assert(v == 0, "v unchanged"); // fails + + // at the start of a statement, '#' starts a comment + int w = 0; + asm volatile("nop; # str %w1, [%0]" : : "r"(&w), "r"(1)); + __CPROVER_assert(w == 0, "w unchanged"); // holds + + return 0; +} diff --git a/regression/cbmc/inline_asm_hash/ppc.desc b/regression/cbmc/inline_asm_hash/ppc.desc new file mode 100644 index 000000000000..0d9a45115f62 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/ppc.desc @@ -0,0 +1,12 @@ +CORE +comments.i +--arch ppc64le --show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^ *CALL __asm_mfence\(\)$ +^ *FENCE WW RR RW WR$ +-- +^warning: ignoring +inline assembly statement at +-- +On Power, '#' starts a comment anywhere on a line. diff --git a/regression/cbmc/inline_asm_hash/test.desc b/regression/cbmc/inline_asm_hash/test.desc new file mode 100644 index 000000000000..056ed474498e --- /dev/null +++ b/regression/cbmc/inline_asm_hash/test.desc @@ -0,0 +1,14 @@ +CORE +main.i +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 10 v unchanged: FAILURE$ +^\[main\.assertion\.2\] line 15 w unchanged: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +On AArch64, '#' starts a comment only at the start of a line or statement. +The assembler lexer of remove_asm treated it as a comment anywhere, so the +store after "dmb #11" was lost and the statement was modeled as a fence. diff --git a/regression/cbmc/inline_asm_hash/x86.desc b/regression/cbmc/inline_asm_hash/x86.desc new file mode 100644 index 000000000000..66368e9bf781 --- /dev/null +++ b/regression/cbmc/inline_asm_hash/x86.desc @@ -0,0 +1,12 @@ +CORE +comments.i +--arch x86_64 --show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^ *CALL __asm_mfence\(\)$ +^ *FENCE WW RR RW WR$ +-- +^warning: ignoring +inline assembly statement at +-- +On x86, '#' starts a comment anywhere on a line. diff --git a/regression/validate-trace-xml-schema/check.py b/regression/validate-trace-xml-schema/check.py index 0c545eee3a25..3f50f623cb45 100644 --- a/regression/validate-trace-xml-schema/check.py +++ b/regression/validate-trace-xml-schema/check.py @@ -30,6 +30,10 @@ ['destructors', 'enter_lexical_block.desc'], ['enum_is_in_range', 'enum_test3-simplified.desc'], ['enum_is_in_range', 'format.desc'], + ['inline_asm_hash', 'arm.desc'], + ['inline_asm_hash', 'barriers.desc'], + ['inline_asm_hash', 'ppc.desc'], + ['inline_asm_hash', 'x86.desc'], ['inline_asm_modeling', 'test.desc'], ['integer-assignments1', 'integer-typecheck.desc'], ['r_w_ok9', 'simplify.desc'], diff --git a/src/assembler/assembler_parser.h b/src/assembler/assembler_parser.h index 1e52566c7a41..b4e93d9a2fa0 100644 --- a/src/assembler/assembler_parser.h +++ b/src/assembler/assembler_parser.h @@ -36,6 +36,20 @@ class assembler_parsert:public parsert instructions.push_back(instructiont()); } + /// \return Whether no token of the current instruction has been read yet, + /// i.e., the scanner is at the start of a line or statement + bool at_instruction_start() const + { + return instructions.empty() || instructions.back().empty(); + } + + /// Whether `#` starts a comment anywhere on a line, as on x86 and Power. + /// Otherwise, `#` starts a comment only at the start of a line or + /// statement, as on ARM and AArch64, where it elsewhere introduces an + /// immediate operand and is returned as a token. The latter is the default + /// as it never drops the text of an instruction. + bool hash_comment_anywhere = false; + explicit assembler_parsert(message_handlert &message_handler) : parsert(message_handler) { diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index f4db613ff999..4d8b8d96f095 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -16,6 +16,7 @@ Date: December 2014 #include "remove_asm.h" #include +#include #include #include #include @@ -94,7 +95,7 @@ class remove_asmt const code_asmt &, goto_programt &dest); - instructionst parse(const irep_idt &assembly); + instructionst parse(const irep_idt &assembly, const irep_idt &flavor); std::optional process_asm( const code_asmt &code, @@ -257,12 +258,25 @@ static codet make_fence( /// Parses the text of an inline assembly statement. /// \param assembly: The assembly text +/// \param flavor: The flavor of the statement (gcc or msc) /// \return The instructions, each a sequence of tokens -remove_asmt::instructionst remove_asmt::parse(const irep_idt &assembly) +remove_asmt::instructionst +remove_asmt::parse(const irep_idt &assembly, const irep_idt &flavor) { std::istringstream str(id2string(assembly)); assembler_parsert assembler_parser{message_handler}; assembler_parser.in = &str; + // `#` starts a comment anywhere on x86 (which MSVC-style blocks are for), + // Power, MIPS, RISC-V, s390, and LoongArch; on ARM and AArch64, it does so + // only at the start of a line or statement and otherwise introduces an + // immediate. For other targets, the latter is assumed, as it may only make + // a statement be approximated rather than lose instructions. + const std::string arch = id2string(config.ansi_c.arch); + assembler_parser.hash_comment_anywhere = + flavor == ID_msc || arch == "i386" || arch == "x86_64" || arch == "x32" || + arch == "powerpc" || arch == "ppc64" || arch == "ppc64le" || + has_prefix(arch, "mips") || arch == "riscv64" || arch == "s390" || + arch == "s390x" || arch == "loongarch64"; assembler_parser.parse(); return std::move(assembler_parser.instructions); } @@ -544,7 +558,7 @@ void remove_asmt::process_instruction_gcc( goto_programt &dest) { const instructionst instructions = - parse(to_string_constant(code.asm_text()).value()); + parse(to_string_constant(code.asm_text()).value(), ID_gcc); goto_programt modeled; std::set written_operands; @@ -683,6 +697,97 @@ static const exprt &gcc_operand(const code_asm_gcct &code, std::size_t index) return to_binary_expr(operand).op1(); } +/// \return The value of the immediate operand `#N` (decimal or hexadecimal) +/// that the tokens of \p instruction starting at \p pos form, if these are +/// the only remaining tokens. +static std::optional arm_immediate( + std::size_t pos, + const assembler_parsert::instructiont &instruction) +{ + if(pos + 1 >= instruction.size() || instruction[pos].id() != "#") + return {}; + + // the scanner returns digits as single tokens, and the x of a hexadecimal + // number and the hexadecimal digits following it as an identifier + std::string text; + for(++pos; pos < instruction.size(); ++pos) + { + const irept &token = instruction[pos]; + text += id2string( + token.id() == ID_symbol ? token.get(ID_identifier) : token.id()); + } + + int base = 10; + std::string digits = text; + if(text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) + { + base = 16; + digits = text.substr(2); + } + if( + digits.empty() || digits.size() > 8 || + !std::all_of( + digits.begin(), + digits.end(), + [base](char c) + { + const unsigned char u = static_cast(c); + return base == 16 ? isxdigit(u) != 0 : isdigit(u) != 0; + })) + { + return {}; + } + + return std::stoul(digits, nullptr, base); +} + +/// \return The name of the option of an ARM `dmb` or `dsb` barrier given by +/// the tokens of \p instruction starting at \p pos, which are a name or an +/// immediate (`#11` is `ish`), if these are the only remaining tokens and +/// the immediate is not reserved. +static std::optional arm_barrier_option( + std::size_t pos, + const assembler_parsert::instructiont &instruction) +{ + if(pos + 1 == instruction.size() && instruction[pos].id() == ID_symbol) + return id2string(instruction[pos].get(ID_identifier)); + + const auto immediate = arm_immediate(pos, instruction); + if(!immediate.has_value()) + return {}; + + // the encodings of the options; the others are reserved + switch(*immediate) + { + case 1: + return "oshld"; + case 2: + return "oshst"; + case 3: + return "osh"; + case 5: + return "nshld"; + case 6: + return "nshst"; + case 7: + return "nsh"; + case 9: + return "ishld"; + case 10: + return "ishst"; + case 11: + return "ish"; + case 13: + return "ld"; + case 14: + return "st"; + case 15: + return "sy"; + default: + return {}; + } +} + /// Translates a single recognized gcc-style command into \p tmp_dest. /// /// \param command: The instruction mnemonic to translate @@ -735,9 +840,10 @@ bool remove_asmt::handle_gcc_command( return fence(true, true, true, true, true); // the barrier option selects the accesses being ordered - if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) + const auto barrier_option = arm_barrier_option(pos, instruction); + if(!barrier_option.has_value()) return false; - const std::string &option = id2string(instruction[pos].get(ID_identifier)); + const std::string &option = *barrier_option; if(option == "sy" || option == "ish" || option == "osh" || option == "nsh") return fence(true, true, true, true, true); else if(has_suffix(option, "ld")) // loads before loads and stores @@ -750,13 +856,8 @@ bool remove_asmt::handle_gcc_command( if(command == "isb") // ARM { - if( - !no_operands && - (pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol || - instruction[pos].get(ID_identifier) != "sy")) - { + if(!no_operands && arm_barrier_option(pos, instruction) != "sy") return false; - } // doesn't do anything by itself, needs to be combined with branch return fence(false, false, false, false, false); } @@ -804,7 +905,7 @@ void remove_asmt::process_instruction_msc( goto_programt &dest) { const instructionst instructions = - parse(to_string_constant(code.op0()).value()); + parse(to_string_constant(code.op0()).value(), ID_msc); const auto unknown = process_asm( code, diff --git a/src/assembler/scanner.l b/src/assembler/scanner.l index 614185472bb1..3119855de1d8 100755 --- a/src/assembler/scanner.l +++ b/src/assembler/scanner.l @@ -69,7 +69,16 @@ string_lit ("L"|"u"|"U"|"u8")?["]{s_char}*["] yyless(0); /* start again with this character */ } -"#" { PARSER.new_instruction(); BEGIN(LINE_COMMENT); } /* begin comment state */ +"#" { // a comment, or the start of an immediate operand on ARM + if(PARSER.hash_comment_anywhere || + PARSER.at_instruction_start()) + { + PARSER.new_instruction(); + BEGIN(LINE_COMMENT); + } + else + PARSER.add_token(irept("#")); + } { \n { BEGIN(GRAMMAR); } /* end comment state, back GRAMMAR */ From 6afa4de335bd90f879c951a7716e3ad8cd9f2186 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:24:28 +0000 Subject: [PATCH 014/100] x86 library: lfence and sfence are not full fences __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 --- doc/cprover-manual/modeling-inline-asm.md | 4 +- .../asm_x86_fences_sb/lfence.desc | 12 +++++ .../cbmc-concurrency/asm_x86_fences_sb/main.c | 45 +++++++++++++++++++ .../asm_x86_fences_sb/sfence.desc | 12 +++++ .../asm_x86_fences_sb/test.desc | 11 +++++ regression/cbmc-library/__asm_lfence/main.c | 6 +-- .../cbmc-library/__asm_lfence/test.desc | 11 +++-- regression/cbmc-library/__asm_sfence/main.c | 6 +-- .../cbmc-library/__asm_sfence/test.desc | 10 +++-- src/ansi-c/library/x86_assembler.c | 8 +++- 10 files changed, 105 insertions(+), 20 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_x86_fences_sb/lfence.desc create mode 100644 regression/cbmc-concurrency/asm_x86_fences_sb/main.c create mode 100644 regression/cbmc-concurrency/asm_x86_fences_sb/sfence.desc create mode 100644 regression/cbmc-concurrency/asm_x86_fences_sb/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 9c796eb582cc..eee18a5501ee 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -39,8 +39,8 @@ operand, as in `dmb #11`. | Instruction | Effect in CBMC | |---|---| | `mfence` | Full memory fence | -| `lfence` | Full memory fence (currently modeled identically to `mfence`) | -| `sfence` | Full memory fence (currently modeled identically to `mfence`) | +| `lfence` | Orders loads before later loads and stores; a store may still be delayed beyond a later load | +| `sfence` | Orders stores before later stores; a store may still be delayed beyond a later load | | `fstcw` / `fnstcw` | Stores the rounding mode (`__CPROVER_rounding_mode`) to bits 10 and 11 of the operand; the other bits of the control word are zero | | `fldcw` | Sets the rounding mode from bits 10 and 11 of the operand | | `stmxcsr` | Stores the rounding mode to bits 13 and 14 of the operand; the other bits of the SSE control and status register are nondeterministic | diff --git a/regression/cbmc-concurrency/asm_x86_fences_sb/lfence.desc b/regression/cbmc-concurrency/asm_x86_fences_sb/lfence.desc new file mode 100644 index 000000000000..a8ca00c62dee --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_fences_sb/lfence.desc @@ -0,0 +1,12 @@ +CORE +main.c +--mm tso -DLFENCE +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 43 store buffering: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +lfence only orders loads before later loads and stores. It used to be +modeled as a full fence, which prevented store buffering. diff --git a/regression/cbmc-concurrency/asm_x86_fences_sb/main.c b/regression/cbmc-concurrency/asm_x86_fences_sb/main.c new file mode 100644 index 000000000000..2a8f3ee93ca8 --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_fences_sb/main.c @@ -0,0 +1,45 @@ +// Store buffering: each thread stores to one variable and then loads the +// other. On x86, a store may be delayed beyond a later load, unless a fence +// that orders stores before later loads (mfence) separates them. lfence +// and sfence do not, and x86 hardware exhibits r0 == 0 && r1 == 0 with +// either of them. +#if defined(LFENCE) +# define FENCE "lfence" +# define KINDS "RRfence", "RWfence" +#elif defined(SFENCE) +# define FENCE "sfence" +# define KINDS "WWfence" +#else +# define FENCE "mfence" +# define KINDS "WWfence", "RRfence", "RWfence", "WRfence" +#endif + +int x, y, r0, r1, done; + +void t0(void) +{ + x = 1; +#ifdef __GNUC__ + __asm__ volatile(FENCE ::: "memory"); +#else + __CPROVER_fence(KINDS); +#endif + r0 = y; + done = 1; +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t0(); + y = 1; +#ifdef __GNUC__ + __asm__ volatile(FENCE ::: "memory"); +#else + __CPROVER_fence(KINDS); +#endif + r1 = x; + __CPROVER_assume(done); + __CPROVER_assert(!(r0 == 0 && r1 == 0), "store buffering"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_x86_fences_sb/sfence.desc b/regression/cbmc-concurrency/asm_x86_fences_sb/sfence.desc new file mode 100644 index 000000000000..f2047923fcaa --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_fences_sb/sfence.desc @@ -0,0 +1,12 @@ +CORE +main.c +--mm tso -DSFENCE +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 43 store buffering: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +sfence only orders stores before later stores. It used to be modeled as a +full fence, which prevented store buffering. diff --git a/regression/cbmc-concurrency/asm_x86_fences_sb/test.desc b/regression/cbmc-concurrency/asm_x86_fences_sb/test.desc new file mode 100644 index 000000000000..159f8667959c --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_fences_sb/test.desc @@ -0,0 +1,11 @@ +CORE +main.c +--mm tso +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 43 store buffering: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +-- +mfence orders stores before later loads, so store buffering is prevented. diff --git a/regression/cbmc-library/__asm_lfence/main.c b/regression/cbmc-library/__asm_lfence/main.c index 6ebebf84c631..140c4ea48894 100644 --- a/regression/cbmc-library/__asm_lfence/main.c +++ b/regression/cbmc-library/__asm_lfence/main.c @@ -1,9 +1,5 @@ -#include -#include - int main() { - __asm_lfence(); - assert(0); + __asm__ volatile("lfence"); return 0; } diff --git a/regression/cbmc-library/__asm_lfence/test.desc b/regression/cbmc-library/__asm_lfence/test.desc index 9542d988e8d5..195cf69da630 100644 --- a/regression/cbmc-library/__asm_lfence/test.desc +++ b/regression/cbmc-library/__asm_lfence/test.desc @@ -1,8 +1,13 @@ -KNOWNBUG +CORE gcc-only main.c ---pointer-check --bounds-check +--show-goto-functions ^EXIT=0$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^ *FENCE RR RW$ -- +^ *FENCE WW +^ *FENCE .*WR ^warning: ignoring +-- +lfence orders loads before later loads and stores, but it does not order +stores before later accesses. diff --git a/regression/cbmc-library/__asm_sfence/main.c b/regression/cbmc-library/__asm_sfence/main.c index fefd01fb46e5..7cbec5d7f44a 100644 --- a/regression/cbmc-library/__asm_sfence/main.c +++ b/regression/cbmc-library/__asm_sfence/main.c @@ -1,9 +1,5 @@ -#include -#include - int main() { - __asm_sfence(); - assert(0); + __asm__ volatile("sfence"); return 0; } diff --git a/regression/cbmc-library/__asm_sfence/test.desc b/regression/cbmc-library/__asm_sfence/test.desc index 9542d988e8d5..0a30650280ed 100644 --- a/regression/cbmc-library/__asm_sfence/test.desc +++ b/regression/cbmc-library/__asm_sfence/test.desc @@ -1,8 +1,12 @@ -KNOWNBUG +CORE gcc-only main.c ---pointer-check --bounds-check +--show-goto-functions ^EXIT=0$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^ *FENCE WW$ -- +^ *FENCE .*R ^warning: ignoring +-- +sfence orders stores before later stores, but it does not order stores +before later loads, nor loads before later accesses. diff --git a/src/ansi-c/library/x86_assembler.c b/src/ansi-c/library/x86_assembler.c index 62f2b0c82979..b4dba9c88899 100644 --- a/src/ansi-c/library/x86_assembler.c +++ b/src/ansi-c/library/x86_assembler.c @@ -65,12 +65,16 @@ void __asm_mfence(void) void __asm_sfence(void) { - __CPROVER_fence("WWfence", "RRfence", "RWfence", "WRfence"); + // orders stores before later stores only; stores may still be delayed + // beyond later loads + __CPROVER_fence("WWfence"); } /* FUNCTION: __asm_lfence */ void __asm_lfence(void) { - __CPROVER_fence("WWfence", "RRfence", "RWfence", "WRfence"); + // orders loads before later loads and stores only; stores may still be + // delayed beyond later loads + __CPROVER_fence("RRfence", "RWfence"); } From e0c3ac8568507ac16624e712423934581fe04573 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:25:34 +0000 Subject: [PATCH 015/100] remove_asm: dsb with a st option also orders stores before loads `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 --- doc/cprover-manual/modeling-inline-asm.md | 2 +- .../asm_arm_dsb_st_sb/dmb.desc | 12 ++++++++++ .../cbmc-concurrency/asm_arm_dsb_st_sb/dmb.i | 24 +++++++++++++++++++ .../cbmc-concurrency/asm_arm_dsb_st_sb/dsb.i | 24 +++++++++++++++++++ .../asm_arm_dsb_st_sb/test.desc | 14 +++++++++++ regression/cbmc/inline_asm_modeling/main.c | 4 +++- regression/cbmc/inline_asm_modeling/test.desc | 10 ++++---- src/assembler/remove_asm.cpp | 9 +++++-- 8 files changed, 91 insertions(+), 8 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.desc create mode 100644 regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.i create mode 100644 regression/cbmc-concurrency/asm_arm_dsb_st_sb/dsb.i create mode 100644 regression/cbmc-concurrency/asm_arm_dsb_st_sb/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index eee18a5501ee..22a4f008562f 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -57,7 +57,7 @@ neither is `xchg`, so statements using them are approximated. | Instruction | Effect in CBMC | |---|---| -| `dmb`, `dsb` | Full fence without an option or with option `sy`, `ish`, `osh`, or `nsh`; with an option ending in `ld` (such as `ishld`), loads are ordered before later loads and stores; with an option ending in `st` (such as `ishst`), stores are ordered before later stores | +| `dmb`, `dsb` | Full fence without an option or with option `sy`, `ish`, `osh`, or `nsh`; with an option ending in `ld` (such as `ishld`), loads are ordered before later loads and stores; with an option ending in `st` (such as `ishst`), stores are ordered before later stores, and a `dsb` also orders them before later loads, as it waits for the stores to complete before any later instruction executes | | `isb` | Empty fence; no observable effect unless combined with a branch | | `nop`, `yield` | No effect | diff --git a/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.desc b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.desc new file mode 100644 index 000000000000..397b8ddea1ae --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.desc @@ -0,0 +1,12 @@ +CORE +dmb.i +--arch arm64 --mm tso +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 22 store buffering: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +dmb ishst only orders stores before later stores, so the store may be +delayed beyond the later load. diff --git a/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.i b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.i new file mode 100644 index 000000000000..a0b6f3167cfe --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dmb.i @@ -0,0 +1,24 @@ +// Store buffering: each thread stores to one variable and then loads the +// other. A dmb ishst separates the store from the load. Preprocessed input, as +// preprocessing for --arch arm64 may fail on hosts of other architectures. +int x, y, r0, r1, done; + +void t0(void) +{ + x = 1; + __asm__ volatile("dmb ishst" ::: "memory"); + r0 = y; + done = 1; +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t0(); + y = 1; + __asm__ volatile("dmb ishst" ::: "memory"); + r1 = x; + __CPROVER_assume(done); + __CPROVER_assert(!(r0 == 0 && r1 == 0), "store buffering"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dsb.i b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dsb.i new file mode 100644 index 000000000000..fb40bf7be03f --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/dsb.i @@ -0,0 +1,24 @@ +// Store buffering: each thread stores to one variable and then loads the +// other. A dsb ishst separates the store from the load. Preprocessed input, as +// preprocessing for --arch arm64 may fail on hosts of other architectures. +int x, y, r0, r1, done; + +void t0(void) +{ + x = 1; + __asm__ volatile("dsb ishst" ::: "memory"); + r0 = y; + done = 1; +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t0(); + y = 1; + __asm__ volatile("dsb ishst" ::: "memory"); + r1 = x; + __CPROVER_assume(done); + __CPROVER_assert(!(r0 == 0 && r1 == 0), "store buffering"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_arm_dsb_st_sb/test.desc b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/test.desc new file mode 100644 index 000000000000..c6f6c65bf7e1 --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_dsb_st_sb/test.desc @@ -0,0 +1,14 @@ +CORE +dsb.i +--arch arm64 --mm tso +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 22 store buffering: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +-- +A dsb waits for the accesses it orders, here the stores, to complete before +any later instruction executes, so it also orders the store before the later +load, and store buffering is prevented. dsb ishst used to be modeled like +dmb ishst, which only orders stores before later stores. diff --git a/regression/cbmc/inline_asm_modeling/main.c b/regression/cbmc/inline_asm_modeling/main.c index 2afcb491c524..39a6da3dc1bb 100644 --- a/regression/cbmc/inline_asm_modeling/main.c +++ b/regression/cbmc/inline_asm_modeling/main.c @@ -12,11 +12,13 @@ int main(void) asm volatile("sfence"); // ARM barriers: dmb/dsb are full fences unless the option restricts them - // to loads (ld) or stores (st); isb is an empty fence. + // to loads (ld) or stores (st); a dsb with a st option also orders stores + // before later loads; isb is an empty fence. asm volatile("dmb"); asm volatile("dsb sy"); asm volatile("dmb ish" ::: "memory"); asm volatile("dmb ishld"); + asm volatile("dmb ishst"); asm volatile("dsb ishst"); asm volatile("isb"); diff --git a/regression/cbmc/inline_asm_modeling/test.desc b/regression/cbmc/inline_asm_modeling/test.desc index 071b814941fe..fcaba9b4bfe2 100644 --- a/regression/cbmc/inline_asm_modeling/test.desc +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -12,6 +12,7 @@ main.c ^ *FENCE WW RR RW$ ^ *FENCE RR RW$ ^ *FENCE WW$ +^ *FENCE WW WR$ ^ *FENCE$ -- ^warning: ignoring @@ -21,8 +22,9 @@ ATOMIC_BEGIN Pins the documented translation of recognized inline-assembly instructions by the remove_asm pass (see doc/cprover-manual/modeling-inline-asm.md): x86 mfence/lfence/sfence -> __asm_* fence helper calls; ARM dmb/dsb and Power -sync -> full fence (WW RR RW WR); ARM dmb/dsb with an ld option -> RR RW, with -an st option -> WW; Power lwsync -> fence without WR; Power eieio -> WW; ARM -isb / Power isync -> empty fence; nop/pause/yield -> nothing; fstcw/fldcw -> -__CPROVER_rounding_mode helpers called with the address of the operand. +sync -> full fence (WW RR RW WR); ARM dmb/dsb with an ld option -> RR RW, dmb +with an st option -> WW, dsb with an st option -> WW WR; Power lwsync -> fence +without WR; Power eieio -> WW; ARM isb / Power isync -> empty fence; +nop/pause/yield -> nothing; fstcw/fldcw -> __CPROVER_rounding_mode helpers +called with the address of the operand. See GitHub issue diffblue/cbmc#6374. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 4d8b8d96f095..ed1327837a20 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -848,8 +848,13 @@ bool remove_asmt::handle_gcc_command( return fence(true, true, true, true, true); else if(has_suffix(option, "ld")) // loads before loads and stores return fence(false, true, true, false, true); - else if(has_suffix(option, "st")) // stores before stores - return fence(true, false, false, false, true); + else if(has_suffix(option, "st")) + { + // stores before stores; a dsb also waits for the stores to complete + // before any later instruction executes, which orders them before + // later loads, too + return fence(true, false, false, command == "dsb", true); + } else return false; } From 5e4d6f6ede1092ca5578c705a031f09703393fdb Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:27:26 +0000 Subject: [PATCH 016/100] remove_asm: MSVC blocks name the variable of a member access 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 --- doc/cprover-manual/modeling-inline-asm.md | 8 +++- regression/cbmc/inline_asm_msvc_names/main.i | 32 ++++++++++++++++ .../cbmc/inline_asm_msvc_names/test.desc | 18 +++++++++ src/assembler/remove_asm.cpp | 38 ++++++++++++------- 4 files changed, 80 insertions(+), 16 deletions(-) create mode 100644 regression/cbmc/inline_asm_msvc_names/main.i create mode 100644 regression/cbmc/inline_asm_msvc_names/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 22a4f008562f..73f19064eb9a 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -49,7 +49,10 @@ operand, as in `dmb #11`. For GCC-style statements, the operand of `fstcw`, `fnstcw`, `fldcw`, `stmxcsr`, and `ldmxcsr` must be an operand reference (`%0`, `%1`, ...); for -MSVC-style blocks, it must be the name of a variable. None of the +MSVC-style blocks, it must be the name of a variable, and the only variable +of that name among the local variables and parameters of the enclosing +function and the global variables (as CBMC does not know which of them is +in scope). None of the read-modify-write instructions that take a `lock` prefix is modeled, and neither is `xchg`, so statements using them are approximated. @@ -130,7 +133,8 @@ MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the enclosing function that the block names (all of them, if a name is shadowed) is treated like an output operand and like an input operand of -pointer type, and the block is treated as having a `"memory"` clobber. +pointer type, and the block is treated as having a `"memory"` clobber. A +member access such as `s.a` names the variable `s`. ### Limitations diff --git a/regression/cbmc/inline_asm_msvc_names/main.i b/regression/cbmc/inline_asm_msvc_names/main.i new file mode 100644 index 000000000000..0c357954f3af --- /dev/null +++ b/regression/cbmc/inline_asm_msvc_names/main.i @@ -0,0 +1,32 @@ +// preprocessed input, as preprocessing for --winx64 fails on non-x86 hosts +struct S +{ + int a; + int b; +}; + +unsigned short cw = 0x1234; + +int main(void) +{ + // the operand of fnstcw is a variable whose name is unique + unsigned short own; + __asm { fnstcw own } + __CPROVER_assert((own >> 10 & 3) == 0, "unique name"); // holds + + // the operand of fnstcw names the global cw, but there is also a local cw, + // which is not in scope here + { + unsigned short cw = 0; + (void)cw; + } + __asm { fnstcw cw } + __CPROVER_assert(cw == 0x1234, "global cw unchanged"); // fails + + // a member access names the variable that contains the member + struct S s = {0, 0}; + __asm { mov s.a, 1 } + __CPROVER_assert(s.a == 0, "member written"); // fails + + return 0; +} diff --git a/regression/cbmc/inline_asm_msvc_names/test.desc b/regression/cbmc/inline_asm_msvc_names/test.desc new file mode 100644 index 000000000000..3fbd963b055b --- /dev/null +++ b/regression/cbmc/inline_asm_msvc_names/test.desc @@ -0,0 +1,18 @@ +CORE +main.i +--winx64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 15 unique name: SUCCESS$ +^\[main\.assertion\.2\] line 24 global cw unchanged: FAILURE$ +^\[main\.assertion\.3\] line 29 member written: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dead object.*: FAILURE$ +-- +The operand of fnstcw was looked up preferring a unique local variable over +a global one, even when the local variable is not in scope, so a dead object +was written and the global cw was not. If several variables have the name, +the block is now approximated. The scanner of remove_asm returns s.a as one +identifier, whose lookup failed, so s was not changed; now s.a names s. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index ed1327837a20..14a4d376555b 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -943,8 +943,12 @@ void remove_asmt::process_instruction_msc( { for(const auto &token : instruction) { + // a member of a struct or union, as in s.a, is part of the variable s if(token.id() == ID_symbol) - names.insert(token.get(ID_identifier)); + { + const std::string &identifier = id2string(token.get(ID_identifier)); + names.insert(identifier.substr(0, identifier.find('.'))); + } } } @@ -1002,30 +1006,36 @@ bool remove_asmt::handle_msc_command( if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) return false; - // a local variable (or parameter) takes precedence over a global one; - // if several local variables of that name exist (shadowing), it is not - // known which one is meant + // the variable of that name: a local variable (or parameter) of the + // function or a global one; if there are several of them (shadowing), it + // is not known which one is in scope const irep_idt &name = instruction[pos].get(ID_identifier); const std::string local_prefix = id2string(function_id) + "::"; - std::optional global, local; + std::optional variable; for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) { - if(entry.second == name) - global = entry.second; - else if(has_prefix(id2string(entry.second), local_prefix)) + const symbolt &symbol = symbol_table.lookup_ref(entry.second); + if( + !symbol.is_lvalue || symbol.is_type || symbol.is_macro || + symbol.type.id() == ID_code) + { + continue; + } + if( + entry.second == name || + has_prefix(id2string(entry.second), local_prefix)) { - if(local.has_value()) + if(variable.has_value()) return false; - local = entry.second; + variable = entry.second; } } - if(!local.has_value() && !global.has_value()) + if(!variable.has_value()) return false; - const exprt arg = address_of_exprt{ - symbol_table.lookup_ref(local.has_value() ? *local : *global) - .symbol_expr()}; + const exprt arg = + address_of_exprt{symbol_table.lookup_ref(*variable).symbol_expr()}; asm_function_call( "__asm_" + id2string(command), {arg}, code.source_location(), tmp_dest); From 781eb0153b5e4def9662c614164578cf70c32009 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:29:09 +0000 Subject: [PATCH 017/100] x86 library: fstcw and fnstcw do not store zeros in the other bits __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 --- doc/cprover-manual/modeling-inline-asm.md | 2 +- regression/cbmc-library/__asm_fnstcw/main.c | 19 +++++++++++++++---- .../cbmc-library/__asm_fnstcw/test.desc | 2 +- .../cbmc/inline_asm_fpu_control_word/main.c | 9 +++++++++ .../inline_asm_fpu_control_word/test.desc | 14 +++++++++++--- src/ansi-c/library/x86_assembler.c | 16 ++++++++++++---- 6 files changed, 49 insertions(+), 13 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 73f19064eb9a..d477d28b66d3 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -41,7 +41,7 @@ operand, as in `dmb #11`. | `mfence` | Full memory fence | | `lfence` | Orders loads before later loads and stores; a store may still be delayed beyond a later load | | `sfence` | Orders stores before later stores; a store may still be delayed beyond a later load | -| `fstcw` / `fnstcw` | Stores the rounding mode (`__CPROVER_rounding_mode`) to bits 10 and 11 of the operand; the other bits of the control word are zero | +| `fstcw` / `fnstcw` | Stores the rounding mode (`__CPROVER_rounding_mode`) to bits 10 and 11 of the operand; the other bits of the control word (exception masks and precision control) are nondeterministic | | `fldcw` | Sets the rounding mode from bits 10 and 11 of the operand | | `stmxcsr` | Stores the rounding mode to bits 13 and 14 of the operand; the other bits of the SSE control and status register are nondeterministic | | `ldmxcsr` | Sets the rounding mode from bits 13 and 14 of the operand | diff --git a/regression/cbmc-library/__asm_fnstcw/main.c b/regression/cbmc-library/__asm_fnstcw/main.c index e06e67bee515..1d5f938536ca 100644 --- a/regression/cbmc-library/__asm_fnstcw/main.c +++ b/regression/cbmc-library/__asm_fnstcw/main.c @@ -1,9 +1,20 @@ #include -#include +#include int main() { - __asm_fnstcw(); - assert(0); - return 0; + unsigned short cw; +#ifdef __GNUC__ + __asm__("fnstcw %0" : "=m"(cw)); +#else + __asm { fnstcw cw; } +#endif + assert((cw & 0xc00) == 0); + fesetround(FE_UPWARD); +#ifdef __GNUC__ + __asm__("fnstcw %0" : "=m"(cw)); +#else + __asm { fnstcw cw; } +#endif + assert((cw & 0xc00) == 0x800); } diff --git a/regression/cbmc-library/__asm_fnstcw/test.desc b/regression/cbmc-library/__asm_fnstcw/test.desc index 9542d988e8d5..96c9b4bcd7bc 100644 --- a/regression/cbmc-library/__asm_fnstcw/test.desc +++ b/regression/cbmc-library/__asm_fnstcw/test.desc @@ -1,4 +1,4 @@ -KNOWNBUG +CORE main.c --pointer-check --bounds-check ^EXIT=0$ diff --git a/regression/cbmc/inline_asm_fpu_control_word/main.c b/regression/cbmc/inline_asm_fpu_control_word/main.c index d49c67cb770d..6376ec6cb520 100644 --- a/regression/cbmc/inline_asm_fpu_control_word/main.c +++ b/regression/cbmc/inline_asm_fpu_control_word/main.c @@ -9,5 +9,14 @@ int main(void) asm volatile("fstcw %0" : "=m"(old)); __CPROVER_assert((old >> 10 & 3) == 3, "rounding mode set by fldcw"); + // the other bits of the control word (the exception masks and the + // precision control) are not modeled: on x86 hardware, the control word + // is 0x037f initially + asm volatile("fnstcw %0" : "=m"(old)); + __CPROVER_assert((old >> 10 & 3) == 3, "fnstcw rounding mode"); + __CPROVER_assert((old & 0x0300) == 0, "precision control"); // fails + asm volatile("fstcw %0" : "=m"(old)); + __CPROVER_assert((old & 0x003f) == 0, "exception masks"); // fails + return 0; } diff --git a/regression/cbmc/inline_asm_fpu_control_word/test.desc b/regression/cbmc/inline_asm_fpu_control_word/test.desc index 2b39abc611cb..45818158f8f4 100644 --- a/regression/cbmc/inline_asm_fpu_control_word/test.desc +++ b/regression/cbmc/inline_asm_fpu_control_word/test.desc @@ -1,11 +1,19 @@ CORE gcc-only main.c -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.1\] line 7 initial rounding mode: SUCCESS$ +^\[main\.assertion\.2\] line 10 rounding mode set by fldcw: SUCCESS$ +^\[main\.assertion\.3\] line 16 fnstcw rounding mode: SUCCESS$ +^\[main\.assertion\.4\] line 17 precision control: FAILURE$ +^\[main\.assertion\.5\] line 19 exception masks: FAILURE$ +^VERIFICATION FAILED$ -- ^warning: ignoring inline assembly statement at -- -The x87 control word instructions are modeled using the operand they refer to. +The x87 control word instructions are modeled using the operand they refer +to. fstcw and fnstcw store the rounding mode in bits 10 and 11; they used to +store 0 in the other bits, which made CBMC prove properties that fail on +hardware. diff --git a/src/ansi-c/library/x86_assembler.c b/src/ansi-c/library/x86_assembler.c index b4dba9c88899..e330aabc5a4a 100644 --- a/src/ansi-c/library/x86_assembler.c +++ b/src/ansi-c/library/x86_assembler.c @@ -2,21 +2,29 @@ /* FUNCTION: __asm_fnstcw */ extern int __CPROVER_rounding_mode; +unsigned short __VERIFIER_nondet_unsigned_short(void); void __asm_fnstcw(void *dest) { - // the rounding mode is bits 10 and 11 in the control word - *(unsigned short *)dest = __CPROVER_rounding_mode << 10; + // The rounding mode is bits 10 and 11 in the control word. The other bits + // (exception masks, precision control) are not modeled. + unsigned int other = __VERIFIER_nondet_unsigned_short() & ~0x0c00u; + unsigned int rounding = (unsigned int)__CPROVER_rounding_mode << 10; + *(unsigned short *)dest = (unsigned short)(other | rounding); } /* FUNCTION: __asm_fstcw */ extern int __CPROVER_rounding_mode; +unsigned short __VERIFIER_nondet_unsigned_short(void); void __asm_fstcw(void *dest) { - // the rounding mode is bits 10 and 11 in the control word - *(unsigned short *)dest = __CPROVER_rounding_mode << 10; + // The rounding mode is bits 10 and 11 in the control word. The other bits + // (exception masks, precision control) are not modeled. + unsigned int other = __VERIFIER_nondet_unsigned_short() & ~0x0c00u; + unsigned int rounding = (unsigned int)__CPROVER_rounding_mode << 10; + *(unsigned short *)dest = (unsigned short)(other | rounding); } /* FUNCTION: __asm_fldcw */ From 580ab02e0091c211e00c30d04b8a0900d964762d Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:36:40 +0000 Subject: [PATCH 018/100] Variable sensitivity: havocking keeps the variables of the environment 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 --- .../variable-sensitivity-havoc-merge/main.c | 14 ++++++++++++++ .../variable-sensitivity-havoc-merge/test.desc | 13 +++++++++++++ .../variable-sensitivity/abstract_environment.cpp | 14 +++++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 regression/goto-analyzer/variable-sensitivity-havoc-merge/main.c create mode 100644 regression/goto-analyzer/variable-sensitivity-havoc-merge/test.desc diff --git a/regression/goto-analyzer/variable-sensitivity-havoc-merge/main.c b/regression/goto-analyzer/variable-sensitivity-havoc-merge/main.c new file mode 100644 index 000000000000..075036b371c7 --- /dev/null +++ b/regression/goto-analyzer/variable-sensitivity-havoc-merge/main.c @@ -0,0 +1,14 @@ +void opaque(int *); +int nondet(void); + +int main() +{ + int m = 0; + if(nondet()) + goto done; + // a call of a function without a body havocs the environment + opaque(&m); +done: + __CPROVER_assert(m == 0, "conditional call"); // may fail + return 0; +} diff --git a/regression/goto-analyzer/variable-sensitivity-havoc-merge/test.desc b/regression/goto-analyzer/variable-sensitivity-havoc-merge/test.desc new file mode 100644 index 000000000000..9c3b1313ee5f --- /dev/null +++ b/regression/goto-analyzer/variable-sensitivity-havoc-merge/test.desc @@ -0,0 +1,13 @@ +CORE +main.c +--verify --vsd +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 12 conditional call: UNKNOWN$ +-- +^warning: ignoring +-- +Havocking the environment, as for a call of a function without a body, +removed all variables from it. A merge only merges the variables that both +environments have, so when the path that jumps over the call reached the +label first, m kept the value 0, and the assertion was reported as holding. diff --git a/src/analyses/variable-sensitivity/abstract_environment.cpp b/src/analyses/variable-sensitivity/abstract_environment.cpp index c5fa3a3f6fde..3d7178fbd519 100644 --- a/src/analyses/variable-sensitivity/abstract_environment.cpp +++ b/src/analyses/variable-sensitivity/abstract_environment.cpp @@ -384,7 +384,19 @@ bool abstract_environmentt::merge( void abstract_environmentt::havoc(const std::string &havoc_string) { // TODO(tkiley): error reporting - make_top(); + // Each value becomes top. The values are replaced rather than removed (as + // make_top does), as merge only merges the values of the variables that + // both environments have: a variable removed here would keep the value it + // has in an environment that this one is merged with. + bottom = false; + std::vector> tops; + for(const auto &entry : map.get_view()) + { + if(!entry.second->is_top()) + tops.emplace_back(entry.first, entry.second->make_top()); + } + for(auto &top : tops) + map.replace(top.first, std::move(top.second)); } void abstract_environmentt::make_top() From 2c23d9564b3848249cb29241cdd7738aecb6c36a Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:37:04 +0000 Subject: [PATCH 019/100] goto-analyzer domains: havoc_object may change any variable 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 --- doc/cprover-manual/modeling-inline-asm.md | 6 ++++++ .../havoc-object-domains/constants.desc | 14 +++++++++++++ .../havoc-object-domains/intervals.desc | 13 ++++++++++++ .../goto-analyzer/havoc-object-domains/main.c | 20 +++++++++++++++++++ .../havoc-object-domains/vsd.desc | 13 ++++++++++++ src/analyses/constant_propagator.cpp | 11 ++++++++++ src/analyses/interval_domain.cpp | 4 ++++ src/analyses/invariant_set.cpp | 5 +++++ .../variable_sensitivity_domain.cpp | 3 +++ 9 files changed, 89 insertions(+) create mode 100644 regression/goto-analyzer/havoc-object-domains/constants.desc create mode 100644 regression/goto-analyzer/havoc-object-domains/intervals.desc create mode 100644 regression/goto-analyzer/havoc-object-domains/main.c create mode 100644 regression/goto-analyzer/havoc-object-domains/vsd.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index d477d28b66d3..7711c699234d 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -129,6 +129,12 @@ instruction that is not modeled, then addresses they had before the statement; 5. the rounding mode is assigned a nondeterministic value. +Step 2 uses `__CPROVER_havoc_object`. The abstract domains of +`goto-analyzer` do not track what pointers point to; for such a statement, +the constant propagation domain forgets the values of the objects of static +lifetime and of the address-taken variables, and the interval and +variable-sensitivity domains forget all values. + MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the enclosing function that the block names (all of them, if a name is diff --git a/regression/goto-analyzer/havoc-object-domains/constants.desc b/regression/goto-analyzer/havoc-object-domains/constants.desc new file mode 100644 index 000000000000..88fcee47df75 --- /dev/null +++ b/regression/goto-analyzer/havoc-object-domains/constants.desc @@ -0,0 +1,14 @@ +CORE +main.c +--verify --constants +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 7 pointee: UNKNOWN$ +^\[main\.assertion\.2\] line 8 local without address: SUCCESS$ +^\[main\.assertion\.3\] line 17 conditional pointee: UNKNOWN$ +-- +^warning: ignoring +-- +__CPROVER_havoc_object, which the approximation of inline assembly uses for +the objects its pointer operands point to, may change any of the objects of +static lifetime and the address-taken variables. The domain ignored it. diff --git a/regression/goto-analyzer/havoc-object-domains/intervals.desc b/regression/goto-analyzer/havoc-object-domains/intervals.desc new file mode 100644 index 000000000000..8065eb977b0f --- /dev/null +++ b/regression/goto-analyzer/havoc-object-domains/intervals.desc @@ -0,0 +1,13 @@ +CORE +main.c +--verify --intervals +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 7 pointee: UNKNOWN$ +^\[main\.assertion\.3\] line 17 conditional pointee: UNKNOWN$ +-- +^warning: ignoring +-- +__CPROVER_havoc_object, which the approximation of inline assembly uses for +the objects its pointer operands point to, may change any variable. The +domain ignored it. diff --git a/regression/goto-analyzer/havoc-object-domains/main.c b/regression/goto-analyzer/havoc-object-domains/main.c new file mode 100644 index 000000000000..d79880f1cdd7 --- /dev/null +++ b/regression/goto-analyzer/havoc-object-domains/main.c @@ -0,0 +1,20 @@ +int main() +{ + int k = 0; + int *p = &k; + int unaddressed = 0; + __CPROVER_havoc_object(p); + __CPROVER_assert(k <= 0, "pointee"); // may change + __CPROVER_assert(unaddressed <= 0, "local without address"); // unchanged + + // as in the approximation of inline assembly, which skips null pointers + int j = 0; + int *q = &j; + if(q == 0) + goto skip; + __CPROVER_havoc_object(q); +skip: + __CPROVER_assert(j <= 0, "conditional pointee"); // may change + + return 0; +} diff --git a/regression/goto-analyzer/havoc-object-domains/vsd.desc b/regression/goto-analyzer/havoc-object-domains/vsd.desc new file mode 100644 index 000000000000..6af36cb8f77d --- /dev/null +++ b/regression/goto-analyzer/havoc-object-domains/vsd.desc @@ -0,0 +1,13 @@ +CORE +main.c +--verify --vsd +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 7 pointee: UNKNOWN$ +^\[main\.assertion\.3\] line 17 conditional pointee: UNKNOWN$ +-- +^warning: ignoring +-- +__CPROVER_havoc_object, which the approximation of inline assembly uses for +the objects its pointer operands point to, may change any variable. The +domain ignored it. diff --git a/src/analyses/constant_propagator.cpp b/src/analyses/constant_propagator.cpp index e0ffc9e87f27..52c8d069dc41 100644 --- a/src/analyses/constant_propagator.cpp +++ b/src/analyses/constant_propagator.cpp @@ -191,6 +191,17 @@ void constant_propagator_domaint::transform( { values.set_to_top(from->dead_symbol()); } + else if( + from->is_other() && from->get_other().get_statement() == ID_havoc_object) + { + // the object the pointer points to may be any of the objects of static + // lifetime and the address-taken variables, as the domain does not track + // pointers + if(have_dirty) + values.set_dirty_to_top(cp->dirty, ns); + else + values.set_to_top(); + } else if(from->is_function_call()) { const exprt &function = from->call_function(); diff --git a/src/analyses/interval_domain.cpp b/src/analyses/interval_domain.cpp index dcc22a1ac34d..e014b2873c07 100644 --- a/src/analyses/interval_domain.cpp +++ b/src/analyses/interval_domain.cpp @@ -127,6 +127,10 @@ void interval_domaint::transform( case SKIP: // No action required break; case OTHER: + // the object the pointer points to may be any of the variables, as the + // domain does not track pointers + if(instruction.get_other().get_statement() == ID_havoc_object) + make_top(); #if 0 DATA_INVARIANT(false, "Unclear what is a safe over-approximation of OTHER"); #endif diff --git a/src/analyses/invariant_set.cpp b/src/analyses/invariant_set.cpp index 26eca1aef504..b0f6211ca59e 100644 --- a/src/analyses/invariant_set.cpp +++ b/src/analyses/invariant_set.cpp @@ -1081,6 +1081,11 @@ void invariant_sett::apply_code(const codet &code) // may be a disaster make_true(); } + else if(statement == ID_havoc_object) + { + // the object the pointer points to may be any of the objects + make_true(); + } else if(statement==ID_cpp_delete || statement==ID_cpp_delete_array) { diff --git a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp index 10efb04e147f..2732fd00e69f 100644 --- a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp +++ b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp @@ -154,6 +154,9 @@ void variable_sensitivity_domaint::transform( throw "exceptions not handled"; case OTHER: + // the object the pointer points to may be any of the variables + if(instruction.get_other().get_statement() == ID_havoc_object) + abstract_state.havoc("havoc_object"); // throw "other"; break; From b8e3dae5d786b1240087ae72e8f283a91106014f Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:38:24 +0000 Subject: [PATCH 020/100] Document that C++ loses the operands of gcc-style inline assembly 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 --- doc/cprover-manual/modeling-inline-asm.md | 7 +++++++ regression/cbmc-cpp/asm_gcc_operands/main.cpp | 14 ++++++++++++++ regression/cbmc-cpp/asm_gcc_operands/test.desc | 15 +++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 regression/cbmc-cpp/asm_gcc_operands/main.cpp create mode 100644 regression/cbmc-cpp/asm_gcc_operands/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 7711c699234d..f48bee5d0786 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -153,6 +153,13 @@ member access such as `s.a` names the variable `s`. are not changed. - Control flow out of a statement is not modeled: `asm goto` statements always continue with the next statement. +- In C++ code, the C++ front end discards the operands and clobbers of + GCC-style statements. Such a statement is thus treated as basic assembly: + its outputs are not written (neither by the approximation nor as + described under Output Operands), and the objects its operands point to + are changed only if they are objects of static lifetime or address-taken + local variables. CBMC may hence prove properties of C++ code that fail + when compiled. - Atomicity and memory ordering of instructions that are not modeled are not modeled; such statements are not atomic and do not act as fences. - A loop that retries an approximated statement until it succeeds, such as a diff --git a/regression/cbmc-cpp/asm_gcc_operands/main.cpp b/regression/cbmc-cpp/asm_gcc_operands/main.cpp new file mode 100644 index 000000000000..ed666266c13f --- /dev/null +++ b/regression/cbmc-cpp/asm_gcc_operands/main.cpp @@ -0,0 +1,14 @@ +int main() +{ + // an output of an approximated statement + int out = 0; + asm volatile("movl $1, %0" : "=r"(out)); + __CPROVER_assert(out == 0, "output of an approximated statement"); // fails + + // an output tied to an input by a matching constraint + int x = 0, y = 5; + asm("" : "=r"(x) : "0"(y)); + __CPROVER_assert(x == 5, "tied output"); // holds + + return 0; +} diff --git a/regression/cbmc-cpp/asm_gcc_operands/test.desc b/regression/cbmc-cpp/asm_gcc_operands/test.desc new file mode 100644 index 000000000000..7aecdf70100c --- /dev/null +++ b/regression/cbmc-cpp/asm_gcc_operands/test.desc @@ -0,0 +1,15 @@ +KNOWNBUG gcc-only +main.cpp + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 6 output of an approximated statement: FAILURE$ +^\[main\.assertion\.2\] line 11 tied output: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The C++ parser (rGCCAsmStatement in src/cpp/parse.cpp) parses the operands +of gcc-style inline assembly, but discards them. remove_asm thus treats the +statements as basic assembly: it neither writes out nor x, and CBMC proves +out == 0, which fails with g++. From 8ec5c0869d69c2e44eb80017efa0a87130ad6f11 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:41:39 +0000 Subject: [PATCH 021/100] remove_asm: the lock prefix is not modeled 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 --- doc/cprover-manual/modeling-inline-asm.md | 6 +-- regression/cbmc/inline_asm_lock_prefix/main.c | 14 +++++ .../cbmc/inline_asm_lock_prefix/test.desc | 16 ++++++ src/assembler/remove_asm.cpp | 52 +++---------------- 4 files changed, 40 insertions(+), 48 deletions(-) create mode 100644 regression/cbmc/inline_asm_lock_prefix/main.c create mode 100644 regression/cbmc/inline_asm_lock_prefix/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index f48bee5d0786..314e375949e9 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -52,9 +52,9 @@ For GCC-style statements, the operand of `fstcw`, `fnstcw`, `fldcw`, MSVC-style blocks, it must be the name of a variable, and the only variable of that name among the local variables and parameters of the enclosing function and the global variables (as CBMC does not know which of them is -in scope). None of the -read-modify-write instructions that take a `lock` prefix is modeled, and -neither is `xchg`, so statements using them are approximated. +in scope). Neither the `lock` prefix nor the read-modify-write instructions +that take it are modeled, and neither is `xchg`, so statements using them +are approximated. #### ARM diff --git a/regression/cbmc/inline_asm_lock_prefix/main.c b/regression/cbmc/inline_asm_lock_prefix/main.c new file mode 100644 index 000000000000..ecba417207a9 --- /dev/null +++ b/regression/cbmc/inline_asm_lock_prefix/main.c @@ -0,0 +1,14 @@ +int main(void) +{ + // a lock prefix on a line of its own, followed by an instruction that + // takes it + int x = 0; + asm volatile("lock\n\tincl %0" : "+m"(x)); + __CPROVER_assert(x == 0, "locked increment"); // fails + + // the lock prefix is not modeled, even if the instruction it prefixes is + // (which makes the instruction invalid) + asm volatile("lock; nop"); + + return 0; +} diff --git a/regression/cbmc/inline_asm_lock_prefix/test.desc b/regression/cbmc/inline_asm_lock_prefix/test.desc new file mode 100644 index 000000000000..fe26e638f228 --- /dev/null +++ b/regression/cbmc/inline_asm_lock_prefix/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^approximating inline assembly statement at file main\.c line 6 function main: instruction 'lock' is not modeled +^approximating inline assembly statement at file main\.c line 11 function main: instruction 'lock' is not modeled +^\[main\.assertion\.1\] line 7 locked increment: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +A lock prefix used to start an atomic section with a full fence around the +instruction it prefixes, which was translated only if it was modeled. As +none of the instructions that take a lock prefix is modeled, the prefix is +now not modeled either. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 14a4d376555b..f8ab383e3732 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -98,7 +98,6 @@ class remove_asmt instructionst parse(const irep_idt &assembly, const irep_idt &flavor); std::optional process_asm( - const code_asmt &code, const instructionst &instructions, goto_programt &dest, const handle_commandt &handle_command); @@ -282,13 +281,12 @@ remove_asmt::parse(const irep_idt &assembly, const irep_idt &flavor) } /// Shared scaffolding for translating gcc-style and msc-style inline assembly. -/// For each instruction in \p instructions, handles the `lock` prefix and -/// `xchg` (which start an atomic section containing a full fence), delegates -/// the actual command translation to \p handle_command, and closes the atomic -/// section. The translation is appended to \p dest only if all instructions -/// are recognized by \p handle_command. +/// Delegates the translation of each instruction in \p instructions to +/// \p handle_command. The translation is appended to \p dest only if all +/// instructions are recognized by \p handle_command. A `lock` prefix is the +/// command of its instruction, and is not recognized: none of the +/// instructions that take it is modeled. /// -/// \param code: The inline assembly code statement being translated /// \param instructions: The parsed assembly text /// \param dest: The goto program to append the new instructions to /// \param handle_command: Translates a single command into \p tmp_dest and @@ -296,61 +294,27 @@ remove_asmt::parse(const irep_idt &assembly, const irep_idt &flavor) /// \return The first command that is not recognized, if any; nothing is /// appended to \p dest in this case. std::optional remove_asmt::process_asm( - const code_asmt &code, const instructionst &instructions, goto_programt &dest, const handle_commandt &handle_command) { goto_programt tmp_dest; - bool x86_32_locked_atomic = false; for(const auto &instruction : instructions) { if(instruction.empty()) continue; - // deal with prefixes irep_idt command; std::size_t pos = 0; - - if( - instruction.front().id() == ID_symbol && - instruction.front().get(ID_identifier) == "lock") - { - x86_32_locked_atomic = true; - pos++; - } - - // done? - if(pos == instruction.size()) - continue; - - if(instruction[pos].id() == ID_symbol) + if(instruction.front().id() == ID_symbol) { - command = instruction[pos].get(ID_identifier); + command = instruction.front().get(ID_identifier); pos++; } - if(command == "xchg" || command == "xchgl") - x86_32_locked_atomic = true; - - if(x86_32_locked_atomic) - { - tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); - tmp_dest.add(goto_programt::make_other( - make_fence(code.source_location(), true, true, true, true, false), - code.source_location())); - } - if(!handle_command(command, pos, instruction, tmp_dest)) return command; - - if(x86_32_locked_atomic) - { - tmp_dest.add(goto_programt::make_atomic_end(code.source_location())); - - x86_32_locked_atomic = false; - } } dest.destructive_append(tmp_dest); @@ -563,7 +527,6 @@ void remove_asmt::process_instruction_gcc( goto_programt modeled; std::set written_operands; const auto unknown = process_asm( - code, instructions, modeled, [this, &code, &written_operands]( @@ -913,7 +876,6 @@ void remove_asmt::process_instruction_msc( parse(to_string_constant(code.op0()).value(), ID_msc); const auto unknown = process_asm( - code, instructions, dest, [this, &code, &function_id]( From e2903d7725710b4d42f98160c0d3bc0129ccf961 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:41:52 +0000 Subject: [PATCH 022/100] Inline assembly: pin the translation of each modeled statement 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 --- doc/cprover-manual/modeling-inline-asm.md | 10 +++- regression/cbmc/inline_asm_fldcw_sse/main.i | 15 +++++ .../cbmc/inline_asm_fldcw_sse/test.desc | 13 +++++ regression/cbmc/inline_asm_modeling/main.c | 20 ++++--- regression/cbmc/inline_asm_modeling/test.desc | 56 ++++++++++++------- 5 files changed, 84 insertions(+), 30 deletions(-) create mode 100644 regression/cbmc/inline_asm_fldcw_sse/main.i create mode 100644 regression/cbmc/inline_asm_fldcw_sse/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 314e375949e9..2ffb9e02047e 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -74,7 +74,7 @@ values are reserved, and barriers with them are not modeled. | Instruction | Effect in CBMC | |---|---| | `sync`, `hwsync` | Full memory barrier | -| `lwsync` | Lightweight sync (all fences except write-after-read) | +| `lwsync` | Lightweight sync: orders loads before later loads and stores, and stores before later stores, but not stores before later loads | | `eieio` | Orders stores before later stores | | `isync` | Empty fence; no observable effect unless combined with a branch | | `nop` | No effect | @@ -172,6 +172,14 @@ member access such as `s.a` names the variable `s`. - CBMC does not check whether the instructions are valid for the target architecture: for example, `sync` is modeled as a Power barrier regardless of the `--arch` option. +- CBMC has a single rounding mode, `__CPROVER_rounding_mode`, which applies + to all floating-point operations, while x86 processors have one for x87 + operations (set by `fldcw`) and one for SSE operations (set by + `ldmxcsr`). Both instructions set CBMC's rounding mode, and `fstcw`, + `fnstcw`, and `stmxcsr` all read it. On x86-64, where `float` and `double` + arithmetic uses SSE, `fldcw` thus changes how CBMC rounds these operations + although the processor does not, and CBMC may prove properties that fail + on hardware. C libraries set both control registers in `fesetround`. - You can use `goto-instrument --show-goto-functions` (or `cbmc --show-goto-functions`) to inspect how an inline-assembly statement was translated. diff --git a/regression/cbmc/inline_asm_fldcw_sse/main.i b/regression/cbmc/inline_asm_fldcw_sse/main.i new file mode 100644 index 000000000000..43af28e0d6f2 --- /dev/null +++ b/regression/cbmc/inline_asm_fldcw_sse/main.i @@ -0,0 +1,15 @@ +// preprocessed input, as preprocessing for --arch x86_64 fails on hosts of +// other architectures +int main(void) +{ + unsigned short cw; + __asm__ volatile("fnstcw %0" : "=m"(cw)); + // x87: round downwards + cw = (unsigned short)((cw & ~0x0c00) | 0x0400); + __asm__ volatile("fldcw %0" : : "m"(cw)); + volatile float f = 1.0f; + float q = f / 3.0f; + // float arithmetic uses SSE on x86-64, which still rounds to nearest + __CPROVER_assert(q == 0x1.555554p-2f, "rounded downwards"); // fails + return 0; +} diff --git a/regression/cbmc/inline_asm_fldcw_sse/test.desc b/regression/cbmc/inline_asm_fldcw_sse/test.desc new file mode 100644 index 000000000000..e12543fa45f9 --- /dev/null +++ b/regression/cbmc/inline_asm_fldcw_sse/test.desc @@ -0,0 +1,13 @@ +KNOWNBUG no-new-smt +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 13 rounded downwards: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +CBMC has a single rounding mode, which fldcw sets. On x86-64, float +arithmetic uses SSE, whose rounding mode is in MXCSR and not changed by +fldcw: compiled with gcc, the assertion fails, but CBMC proves it. diff --git a/regression/cbmc/inline_asm_modeling/main.c b/regression/cbmc/inline_asm_modeling/main.c index 39a6da3dc1bb..1569359e1b44 100644 --- a/regression/cbmc/inline_asm_modeling/main.c +++ b/regression/cbmc/inline_asm_modeling/main.c @@ -1,40 +1,42 @@ // Each statement below is processed independently by the remove_asm pass. -// This test pins the documented translation of the recognized instructions -// (see doc/cprover-manual/modeling-inline-asm.md) via the goto program shown -// by --show-goto-functions. +// This test pins the documented translation of each statement (see +// doc/cprover-manual/modeling-inline-asm.md) via the goto program shown by +// --show-goto-functions. int main(void) { unsigned short cw = 0; - // x86 fences: modeled as calls to the __asm_* fence helpers. + // x86 fences: calls of the __asm_* fence helpers asm volatile("mfence"); asm volatile("lfence"); asm volatile("sfence"); // ARM barriers: dmb/dsb are full fences unless the option restricts them // to loads (ld) or stores (st); a dsb with a st option also orders stores - // before later loads; isb is an empty fence. + // before later loads; isb is an empty fence asm volatile("dmb"); asm volatile("dsb sy"); asm volatile("dmb ish" ::: "memory"); asm volatile("dmb ishld"); + asm volatile("dsb ishld"); asm volatile("dmb ishst"); asm volatile("dsb ishst"); asm volatile("isb"); - // Power barriers: sync is a full fence, lwsync omits write-after-read, - // eieio orders stores, isync is an empty fence. + // Power barriers: sync is a full fence, lwsync does not order stores + // before later loads, eieio orders stores, isync is an empty fence asm volatile("sync"); + asm volatile("hwsync"); asm volatile("lwsync"); asm volatile("eieio"); asm volatile("isync"); - // Instructions without effect on the C program state. + // instructions without effect on the C program state asm volatile("nop"); asm volatile("pause"); asm volatile("yield"); - // x86 FP control word: writes/reads __CPROVER_rounding_mode via the operand. + // x86 FP control word: writes/reads __CPROVER_rounding_mode via the operand asm volatile("fstcw %0" : "=m"(cw)); asm volatile("fldcw %0" : : "m"(cw)); diff --git a/regression/cbmc/inline_asm_modeling/test.desc b/regression/cbmc/inline_asm_modeling/test.desc index fcaba9b4bfe2..1a7bff556065 100644 --- a/regression/cbmc/inline_asm_modeling/test.desc +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -1,30 +1,46 @@ CORE gcc-only main.c --show-goto-functions +activate-multi-line-match ^EXIT=0$ ^SIGNAL=0$ -^ *CALL __asm_mfence\(\)$ -^ *CALL __asm_lfence\(\)$ -^ *CALL __asm_sfence\(\)$ -^ *CALL __asm_fstcw\(cast\(address_of\(main::1::cw\), empty\*\)\)$ -^ *CALL __asm_fldcw\(cast\(address_of\(main::1::cw\), empty\*\)\)$ -^ *FENCE WW RR RW WR$ -^ *FENCE WW RR RW$ -^ *FENCE RR RW$ -^ *FENCE WW$ -^ *FENCE WW WR$ -^ *FENCE$ +^ *// \d+ file main\.c line 10 function main\n *CALL __asm_mfence\(\)\n *// \d+ file main\.c line (?!10 ) +^ *// \d+ file main\.c line 11 function main\n *CALL __asm_lfence\(\)\n *// \d+ file main\.c line (?!11 ) +^ *// \d+ file main\.c line 12 function main\n *CALL __asm_sfence\(\)\n *// \d+ file main\.c line (?!12 ) +^ *// \d+ file main\.c line 17 function main\n *FENCE WW RR RW WR\n *// \d+ file main\.c line (?!17 ) +^ *// \d+ file main\.c line 18 function main\n *FENCE WW RR RW WR\n *// \d+ file main\.c line (?!18 ) +^ *// \d+ file main\.c line 19 function main\n *FENCE WW RR RW WR\n *// \d+ file main\.c line (?!19 ) +^ *// \d+ file main\.c line 20 function main\n *FENCE RR RW\n *// \d+ file main\.c line (?!20 ) +^ *// \d+ file main\.c line 21 function main\n *FENCE RR RW\n *// \d+ file main\.c line (?!21 ) +^ *// \d+ file main\.c line 22 function main\n *FENCE WW\n *// \d+ file main\.c line (?!22 ) +^ *// \d+ file main\.c line 23 function main\n *FENCE WW WR\n *// \d+ file main\.c line (?!23 ) +^ *// \d+ file main\.c line 24 function main\n *FENCE\n *// \d+ file main\.c line (?!24 ) +^ *// \d+ file main\.c line 28 function main\n *FENCE WW RR RW WR\n *// \d+ file main\.c line (?!28 ) +^ *// \d+ file main\.c line 29 function main\n *FENCE WW RR RW WR\n *// \d+ file main\.c line (?!29 ) +^ *// \d+ file main\.c line 30 function main\n *FENCE WW RR RW\n *// \d+ file main\.c line (?!30 ) +^ *// \d+ file main\.c line 31 function main\n *FENCE WW\n *// \d+ file main\.c line (?!31 ) +^ *// \d+ file main\.c line 32 function main\n *FENCE\n *// \d+ file main\.c line (?!32 ) +^ *// \d+ file main\.c line 40 function main\n *CALL __asm_fstcw\(cast\(address_of\(main::1::cw\), empty\*\)\)\n *// \d+ file main\.c line (?!40 ) +^ *// \d+ file main\.c line 41 function main\n *CALL __asm_fldcw\(cast\(address_of\(main::1::cw\), empty\*\)\)\n *// \d+ file main\.c line (?!41 ) +^__asm_lfence /\* __asm_lfence \*/\n *// [^\n]*\n *FENCE RR RW\n *// [^\n]*\n *END_FUNCTION$ +^__asm_mfence /\* __asm_mfence \*/\n *// [^\n]*\n *FENCE WW RR RW WR\n *// [^\n]*\n *END_FUNCTION$ +^__asm_sfence /\* __asm_sfence \*/\n *// [^\n]*\n *FENCE WW\n *// [^\n]*\n *END_FUNCTION$ -- ^warning: ignoring inline assembly statement at ATOMIC_BEGIN +file main\.c line 35 function main +file main\.c line 36 function main +file main\.c line 37 function main -- -Pins the documented translation of recognized inline-assembly instructions by -the remove_asm pass (see doc/cprover-manual/modeling-inline-asm.md): -x86 mfence/lfence/sfence -> __asm_* fence helper calls; ARM dmb/dsb and Power -sync -> full fence (WW RR RW WR); ARM dmb/dsb with an ld option -> RR RW, dmb -with an st option -> WW, dsb with an st option -> WW WR; Power lwsync -> fence -without WR; Power eieio -> WW; ARM isb / Power isync -> empty fence; -nop/pause/yield -> nothing; fstcw/fldcw -> __CPROVER_rounding_mode helpers -called with the address of the operand. -See GitHub issue diffblue/cbmc#6374. +Pins the documented translation of each recognized inline-assembly statement +by the remove_asm pass (see doc/cprover-manual/modeling-inline-asm.md): each +pattern requires the statement on the given line to be translated into +exactly the given instruction. x86 mfence/lfence/sfence -> __asm_* fence +helper calls, which are full, RR RW, and WW fences, respectively; ARM +dmb/dsb and Power sync/hwsync -> full fence (WW RR RW WR); ARM dmb/dsb with +an ld option -> RR RW, dmb with an st option -> WW, dsb with an st option -> +WW WR; Power lwsync -> fence without WR; Power eieio -> WW; ARM isb / Power +isync -> empty fence; nop/pause/yield -> nothing; fstcw/fldcw -> +__CPROVER_rounding_mode helpers called with the address of the operand. See +GitHub issue diffblue/cbmc#6374. From ca672d36484976f801e4152458e67022dbc3e66d Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 20:59:19 +0000 Subject: [PATCH 023/100] Inline assembly: output addresses that depend on the other outputs 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 --- doc/cprover-manual/modeling-inline-asm.md | 9 ++- .../cbmc/inline_asm_modeled_outputs/main.c | 5 -- .../cbmc/inline_asm_modeled_outputs/test.desc | 5 +- .../cbmc/inline_asm_output_addresses/main.c | 23 +++++++ .../inline_asm_output_addresses/test.desc | 20 ++++++ src/assembler/asm_approximation.cpp | 18 +++++- src/assembler/asm_approximation.h | 12 +++- src/assembler/remove_asm.cpp | 64 +++++++++++++++---- 8 files changed, 133 insertions(+), 23 deletions(-) create mode 100644 regression/cbmc/inline_asm_output_addresses/main.c create mode 100644 regression/cbmc/inline_asm_output_addresses/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 2ffb9e02047e..ac13734c6f9e 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -103,7 +103,11 @@ instructions: memory location) that the compiler chose for it holds. All inputs and the addresses of all outputs are evaluated before any output -is written. In-out operands (those with a `+` constraint) keep their values +is written. A statement with more than one output, one of which has an +address that depends on the program state (as `arr[idx]` does), is +approximated instead: compilers differ in whether they compute that address +before or after writing the other outputs (GCC at `-O0` computes it after). +In-out operands (those with a `+` constraint) keep their values unless a modeled instruction writes them. ### Conservative Approximation @@ -126,7 +130,8 @@ instruction that is not modeled, then members) point to, and all local variables of the enclosing function whose address is taken are assigned nondeterministic values; 4. the output operands are assigned nondeterministic values, at the - addresses they had before the statement; + addresses they had before the statement and, for outputs whose address + depends on the program state, also at the addresses they have after it; 5. the rounding mode is assigned a nondeterministic value. Step 2 uses `__CPROVER_havoc_object`. The abstract domains of diff --git a/regression/cbmc/inline_asm_modeled_outputs/main.c b/regression/cbmc/inline_asm_modeled_outputs/main.c index 4b0c1e2f4854..bcbffe99b161 100644 --- a/regression/cbmc/inline_asm_modeled_outputs/main.c +++ b/regression/cbmc/inline_asm_modeled_outputs/main.c @@ -28,11 +28,6 @@ int main(void) asm("" : "=r"(p), "=r"(q) : "0"(q), "1"(p)); __CPROVER_assert(p == 2 && q == 1, "swapped"); - // the addresses of the outputs are those before the statement - int idx = 0, arr[2] = {0, 0}; - asm("" : "=r"(idx), "=r"(arr[idx]) : "0"(1), "1"(9)); - __CPROVER_assert(idx == 1 && arr[0] == 9 && arr[1] == 0, "addresses"); - // the upper bits of a wider output are not known long long wide = 0; int narrow = 3; diff --git a/regression/cbmc/inline_asm_modeled_outputs/test.desc b/regression/cbmc/inline_asm_modeled_outputs/test.desc index f71b7af03022..b3abc072b589 100644 --- a/regression/cbmc/inline_asm_modeled_outputs/test.desc +++ b/regression/cbmc/inline_asm_modeled_outputs/test.desc @@ -8,9 +8,8 @@ main.c ^\[main\.assertion\.3\] line 19 untied output: FAILURE$ ^\[main\.assertion\.4\] line 24 in-out operand: SUCCESS$ ^\[main\.assertion\.5\] line 29 swapped: SUCCESS$ -^\[main\.assertion\.6\] line 34 addresses: SUCCESS$ -^\[main\.assertion\.7\] line 40 wider output: FAILURE$ -^\[main\.assertion\.8\] line 45 written by fnstcw: SUCCESS$ +^\[main\.assertion\.6\] line 35 wider output: FAILURE$ +^\[main\.assertion\.7\] line 40 written by fnstcw: SUCCESS$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/cbmc/inline_asm_output_addresses/main.c b/regression/cbmc/inline_asm_output_addresses/main.c new file mode 100644 index 000000000000..e5c7fea21e66 --- /dev/null +++ b/regression/cbmc/inline_asm_output_addresses/main.c @@ -0,0 +1,23 @@ +// The address of the output arr[idx] depends on the output idx. GCC at -O0 +// computes it after writing idx (arr[1] = 9), GCC at -O2 and Clang compute it +// before (arr[0] = 9), so both behaviours must be possible. +int main(void) +{ + // all instructions modeled (none) + int idx = 0, arr[2] = {0, 0}; + asm("" : "=r"(idx), "=r"(arr[idx]) : "0"(1), "1"(9)); + __CPROVER_assert( + !(idx == 1 && arr[0] == 9 && arr[1] == 0), + "address before writing idx"); // fails + __CPROVER_assert( + !(idx == 1 && arr[0] == 0 && arr[1] == 9), + "address after writing idx"); // fails + + // an instruction that is not modeled + int j = 0, brr[2] = {0, 0}; + asm("unknown_instruction" : "=r"(j), "=r"(brr[j])); + __CPROVER_assert(brr[1] == 0, "address after writing j"); // fails + __CPROVER_assert(brr[0] == 0, "address before writing j"); // fails + + return 0; +} diff --git a/regression/cbmc/inline_asm_output_addresses/test.desc b/regression/cbmc/inline_asm_output_addresses/test.desc new file mode 100644 index 000000000000..e8aaf6999a28 --- /dev/null +++ b/regression/cbmc/inline_asm_output_addresses/test.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c +--arch riscv64 +^EXIT=10$ +^SIGNAL=0$ +^approximating inline assembly statement at file main\.c line 8 function main: the address of an output operand depends on the program state, and compilers differ in whether they compute it before or after writing the other outputs, so +^\[main\.assertion\.1\] line 9 address before writing idx: FAILURE$ +^\[main\.assertion\.2\] line 12 address after writing idx: FAILURE$ +^\[main\.assertion\.3\] line 19 address after writing j: FAILURE$ +^\[main\.assertion\.4\] line 20 address before writing j: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The address of an output such as arr[idx] depends on another output, idx. +GCC at -O0 computes it after writing idx, GCC at -O2 and Clang before. A +statement whose instructions are all modeled used to write the output at the +address before the statement only, and the approximation of a statement with +an instruction that is not modeled used to change only the object at that +address; both excluded the behaviour of GCC at -O0. diff --git a/src/assembler/asm_approximation.cpp b/src/assembler/asm_approximation.cpp index 749dc8901c52..bbbdc061fd65 100644 --- a/src/assembler/asm_approximation.cpp +++ b/src/assembler/asm_approximation.cpp @@ -71,6 +71,14 @@ static bool has_constant_address(const exprt &expr) return false; } +bool asm_approximationt::has_state_dependent_address(const exprt &lvalue) +{ + const exprt *object = &lvalue; + while(object->id() == ID_member && object->type().id() == ID_c_bit_field) + object = &to_member_expr(*object).struct_op(); + return !has_constant_address(*object); +} + void asm_approximationt::collect_addresses( const exprt &expr, const namespacet &ns, @@ -420,9 +428,17 @@ void asm_approximationt::operator()( havoc_lvalue(local, source_location, dest); } - // 5. the outputs + // 5. the outputs, at their addresses before the statement and, as + // compilers differ in when they compute the address of an output (GCC at + // -O0 computes it after the statement has written the other outputs, other + // compilers and optimization levels before), at their addresses after it for(const auto &write : writes) havoc_lvalue(write, source_location, dest); + for(const auto &write : footprint.writes) + { + if(has_state_dependent_address(write)) + havoc_lvalue(write, source_location, dest); + } // 6. the floating-point rounding mode, which the statement may change via // the control registers of the floating-point unit diff --git a/src/assembler/asm_approximation.h b/src/assembler/asm_approximation.h index 0d7ca241fa1d..6e0826a9d91c 100644 --- a/src/assembler/asm_approximation.h +++ b/src/assembler/asm_approximation.h @@ -68,7 +68,10 @@ class asm_approximationt /// nondeterministic values to the objects of static lifetime, to the /// objects that pointers stored in objects of static lifetime point to, /// and to \p address_taken_locals; - /// 5. assign nondeterministic values to the writes; + /// 5. assign nondeterministic values to the writes, at the addresses they + /// had before the statement and, for writes whose address depends on the + /// program state, also at the addresses they have after it, as compilers + /// differ in when they compute these addresses; /// 6. assign a nondeterministic rounding mode. /// Objects that are reachable only through other pointers (for example, a /// caller's local variables or heap objects not referenced by an object of @@ -121,6 +124,13 @@ class asm_approximationt static std::vector address_taken_locals(const goto_programt &body, const namespacet &ns); + /// \return True iff the address of the lvalue \p lvalue (of the object + /// that contains it, for a bit field) depends on the program state, as + /// for `a[i]` or `*p`. Compilers differ in whether they compute the + /// address of such an output operand before or after the statement has + /// written its other outputs. + static bool has_state_dependent_address(const exprt &lvalue); + /// Appends to \p dest the expressions contained in \p expr that may hold /// addresses, as described for \ref asm_footprintt::addresses. static void collect_addresses( diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index f8ab383e3732..8431b694664a 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -105,7 +105,7 @@ class remove_asmt void approximate_asm( const irep_idt &function_id, const code_asmt &code, - const irep_idt &unknown_command, + const std::string &reason, const asm_footprintt &footprint, const std::string &writes_description, const std::string &addresses_description, @@ -326,7 +326,7 @@ std::optional remove_asmt::process_asm( /// /// \param function_id: Name of function being processed /// \param code: The inline assembly code statement -/// \param unknown_command: The first command in \p code that is not modeled +/// \param reason: Why \p code is approximated, for the warning /// \param footprint: What \p code may read and write /// \param writes_description: Description of the writes in \p footprint, /// for the warning @@ -336,7 +336,7 @@ std::optional remove_asmt::process_asm( void remove_asmt::approximate_asm( const irep_idt &function_id, const code_asmt &code, - const irep_idt &unknown_command, + const std::string &reason, const asm_footprintt &footprint, const std::string &writes_description, const std::string &addresses_description, @@ -369,11 +369,8 @@ void remove_asmt::approximate_asm( } log.warning() << "approximating inline assembly statement at " - << code.source_location() << ": " - << (unknown_command.empty() - ? std::string{"an instruction"} - : "instruction '" + id2string(unknown_command) + "'") - << " is not modeled, so " << havocked + << code.source_location() << ": " << reason << ", so " + << havocked << (parts.size() == 1 ? " is assigned a nondeterministic value" : " are assigned nondeterministic values") << "; other objects are assumed to be unchanged" @@ -507,6 +504,41 @@ static std::vector outputs_of_modeled( return result; } +/// \return The reason for approximating a statement whose instruction +/// \p unknown_command (if not empty) is not modeled, for the warning. +static std::string not_modeled(const irep_idt &unknown_command) +{ + if(unknown_command.empty()) + return "an instruction is not modeled"; + return "instruction '" + id2string(unknown_command) + "' is not modeled"; +} + +/// \return Whether \p code has more than one output operand, one of which has +/// an address that depends on the program state (see +/// \ref asm_approximationt::has_state_dependent_address). As compilers +/// differ in whether they compute that address before or after the +/// statement writes its other outputs, assigning the outputs as described +/// for \ref outputs_of_modeled would exclude behaviours. +static bool output_addresses_may_change(const code_asm_gcct &code) +{ + const exprt::operandst &outputs = code.outputs().operands(); + if(outputs.size() < 2) + return false; + + for(const auto &output : outputs) + { + if( + output.operands().size() == 2 && + asm_approximationt::has_state_dependent_address( + to_binary_expr(output).op1())) + { + return true; + } + } + + return false; +} + /// Translates the given inline assembly code (in gcc style) to non-assembly /// goto program instructions, approximating it conservatively if it /// contains an instruction that is not modeled. If all instructions are @@ -541,7 +573,17 @@ void remove_asmt::process_instruction_gcc( const namespacet ns{symbol_table}; - if(!unknown.has_value()) + std::string reason; + if(unknown.has_value()) + reason = not_modeled(*unknown); + else if(output_addresses_may_change(code)) + { + reason = + "the address of an output operand depends on the program state, and " + "compilers differ in whether they compute it before or after writing " + "the other outputs"; + } + else { approximate.assign_outputs( outputs_of_modeled(code, written_operands, ns), @@ -605,7 +647,7 @@ void remove_asmt::process_instruction_gcc( approximate_asm( function_id, code, - *unknown, + reason, footprint, "its output operands", "the objects its operands point to", @@ -935,7 +977,7 @@ void remove_asmt::process_instruction_msc( approximate_asm( function_id, code, - *unknown, + not_modeled(*unknown), footprint, "the local variables it names", "the objects these point to", From edd7321cc0933b16b4f7bf4a9f7892ab713c6ffd Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Thu, 3 Dec 2026 17:33:18 +0000 Subject: [PATCH 024/100] remove_asm: ';' starts a comment in MSVC-style blocks MSVC-style blocks (and asm blocks in braces, which have the same flavor) use MASM syntax, in which ';' starts a comment that extends to the end of the line. remove_asm split them into instructions at ';', as GNU as does, so the text of a comment was taken as instructions. In __asm { mfence ; mov x, 1 } the comment made the block be approximated, and x be changed. A comment whose text happens to be an instruction that is modeled, such as "; lfence", made CBMC add a fence that the block does not have. The assembler parser now has a semicolon_comment option, which remove_asm sets for MSVC-style blocks. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 13 +++++++------ regression/cbmc/asm_block_comment/main.c | 20 ++++++++++++++++++++ regression/cbmc/asm_block_comment/test.desc | 17 +++++++++++++++++ src/assembler/assembler_parser.h | 5 +++++ src/assembler/remove_asm.cpp | 2 ++ src/assembler/scanner.l | 6 +++++- 6 files changed, 56 insertions(+), 7 deletions(-) create mode 100644 regression/cbmc/asm_block_comment/main.c create mode 100644 regression/cbmc/asm_block_comment/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index ac13734c6f9e..c9b907f7e0f9 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -27,12 +27,13 @@ Operands below); without outputs, as in the compiler barrier ### Supported Instructions -CBMC splits the assembler text into instructions at newlines and `;`. On -x86 (and in MSVC-style blocks), Power, MIPS, RISC-V, s390, and LoongArch, -`#` starts a comment that extends to the end of the line. For the other -targets (see `--arch`), including ARM and AArch64, `#` starts a comment only -at the start of a line or statement; elsewhere it introduces an immediate -operand, as in `dmb #11`. +CBMC splits the assembler text into instructions at newlines and `;`, except +in MSVC-style blocks, where `;` starts a comment that extends to the end of +the line, as in MASM. On x86 (and in MSVC-style blocks), Power, MIPS, RISC-V, +s390, and LoongArch, `#` starts a comment that extends to the end of the line. +For the other targets (see `--arch`), including ARM and AArch64, `#` starts a +comment only at the start of a line or statement; elsewhere it introduces an +immediate operand, as in `dmb #11`. #### x86 diff --git a/regression/cbmc/asm_block_comment/main.c b/regression/cbmc/asm_block_comment/main.c new file mode 100644 index 000000000000..16c5be200072 --- /dev/null +++ b/regression/cbmc/asm_block_comment/main.c @@ -0,0 +1,20 @@ +// In MSVC-style blocks (and asm blocks in braces), ';' starts a comment that +// extends to the end of the line, as in MASM: it does not separate +// instructions. +int main(void) +{ + int x = 0; + // the comment names x and an instruction that is not modeled + __asm { mfence ; mov x, 1 } + __CPROVER_assert(x == 0, "x unchanged"); + + int y = 0; + // the comment ends at the end of the line + __asm { + mfence ; a comment + mov y, 1 + } + __CPROVER_assert(y == 0, "y unchanged"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_block_comment/test.desc b/regression/cbmc/asm_block_comment/test.desc new file mode 100644 index 000000000000..940c82274fa5 --- /dev/null +++ b/regression/cbmc/asm_block_comment/test.desc @@ -0,0 +1,17 @@ +CORE +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 9 x unchanged: SUCCESS$ +^\[main\.assertion\.2\] line 17 y unchanged: FAILURE$ +^approximating inline assembly statement at file main\.c line 13 function main: instruction 'mov' is not modeled, so the local variables it names, +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at file main\.c line 8 +-- +In MASM syntax, which MSVC-style blocks use, ';' starts a comment. The +comment in the first block was taken as an instruction (mov x, 1), so the +block was approximated and x changed. The second block shows that the +comment ends at the end of the line. diff --git a/src/assembler/assembler_parser.h b/src/assembler/assembler_parser.h index b4e93d9a2fa0..693520fd49fe 100644 --- a/src/assembler/assembler_parser.h +++ b/src/assembler/assembler_parser.h @@ -50,6 +50,11 @@ class assembler_parsert:public parsert /// as it never drops the text of an instruction. bool hash_comment_anywhere = false; + /// Whether `;` starts a comment that extends to the end of the line, as in + /// MSVC-style blocks (MASM syntax). Otherwise, `;` separates instructions, + /// as in GNU as. + bool semicolon_comment = false; + explicit assembler_parsert(message_handlert &message_handler) : parsert(message_handler) { diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 8431b694664a..75745ff19c7e 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -276,6 +276,8 @@ remove_asmt::parse(const irep_idt &assembly, const irep_idt &flavor) arch == "powerpc" || arch == "ppc64" || arch == "ppc64le" || has_prefix(arch, "mips") || arch == "riscv64" || arch == "s390" || arch == "s390x" || arch == "loongarch64"; + // In MSVC-style blocks, `;` starts a comment, as in MASM. + assembler_parser.semicolon_comment = flavor == ID_msc; assembler_parser.parse(); return std::move(assembler_parser.instructions); } diff --git a/src/assembler/scanner.l b/src/assembler/scanner.l index 3119855de1d8..90f06f80f38f 100755 --- a/src/assembler/scanner.l +++ b/src/assembler/scanner.l @@ -86,7 +86,11 @@ string_lit ("L"|"u"|"U"|"u8")?["]{s_char}*["] } {newline} { PARSER.new_instruction(); } -";" { PARSER.new_instruction(); } +";" { // a comment in MASM syntax, else a separator + PARSER.new_instruction(); + if(PARSER.semicolon_comment) + BEGIN(LINE_COMMENT); + } {whitespace} { } /* skipped */ /*** keywords ***/ From 3e16e923669ab843b00e5c8132e317f28cb0b4a2 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 10:24:02 +0000 Subject: [PATCH 025/100] Symex: havoc all objects reachable from a set of pointers 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 --- src/analyses/dirty.cpp | 3 +- src/analyses/goto_rw.cpp | 9 + src/goto-instrument/full_slicer.cpp | 21 ++ src/goto-programs/goto_program.cpp | 14 + src/goto-symex/Makefile | 1 + src/goto-symex/goto_symex.h | 12 + src/goto-symex/path_storage.h | 5 + src/goto-symex/symex_havoc_reachable.cpp | 462 +++++++++++++++++++++++ src/goto-symex/symex_other.cpp | 4 + src/pointer-analysis/value_set.cpp | 2 +- src/pointer-analysis/value_set_fi.cpp | 2 +- src/util/irep_ids.def | 2 + 12 files changed, 534 insertions(+), 3 deletions(-) create mode 100644 src/goto-symex/symex_havoc_reachable.cpp diff --git a/src/analyses/dirty.cpp b/src/analyses/dirty.cpp index 941d6b79622a..7c425615c590 100644 --- a/src/analyses/dirty.cpp +++ b/src/analyses/dirty.cpp @@ -42,7 +42,8 @@ void dirtyt::search_other(const goto_programt::instructiont &instruction) statement == ID_expression || statement == ID_array_set || statement == ID_array_equal || statement == ID_array_copy || statement == ID_array_replace || statement == ID_havoc_object || - statement == ID_input || statement == ID_output) + statement == ID_havoc_reachable || statement == ID_input || + statement == ID_output) { for(const auto &op : code.operands()) find_dirty(op); diff --git a/src/analyses/goto_rw.cpp b/src/analyses/goto_rw.cpp index 1416236f84a7..84f5aa242121 100644 --- a/src/analyses/goto_rw.cpp +++ b/src/analyses/goto_rw.cpp @@ -840,6 +840,15 @@ static void goto_rw_other( rw_set.get_array_objects( function, target, rw_range_sett::get_modet::LHS_W, code.op0()); } + else if(statement == ID_havoc_reachable) + { + // at least the objects the operands point to are written + for(const auto &op : code.operands()) + { + rw_set.get_array_objects( + function, target, rw_range_sett::get_modet::LHS_W, op); + } + } } static void goto_rw( diff --git a/src/goto-instrument/full_slicer.cpp b/src/goto-instrument/full_slicer.cpp index 812d9b5ba5ce..c56666f09f0b 100644 --- a/src/goto-instrument/full_slicer.cpp +++ b/src/goto-instrument/full_slicer.cpp @@ -14,6 +14,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include +#include #include @@ -257,6 +258,26 @@ void full_slicert::operator()( const slicing_criteriont &criterion, message_handlert &message_handler) { + // The objects that havoc_reachable (from the approximation of inline + // assembly) changes, and hence the instructions it depends on, are only + // known during symbolic execution. + for(const auto &gf_entry : goto_functions.function_map) + { + for(const auto &instruction : gf_entry.second.body.instructions) + { + if( + instruction.is_other() && + instruction.get_other().get_statement() == ID_havoc_reachable) + { + messaget log{message_handler}; + log.warning() << "not slicing, as the program contains inline " + "assembly that may change any reachable object" + << messaget::eom; + return; + } + } + } + // build the CFG data structure cfg(goto_functions); for(const auto &gf_entry : goto_functions.function_map) diff --git a/src/goto-programs/goto_program.cpp b/src/goto-programs/goto_program.cpp index 360759e4a1ec..39f4314d863d 100644 --- a/src/goto-programs/goto_program.cpp +++ b/src/goto-programs/goto_program.cpp @@ -135,6 +135,20 @@ std::ostream &goto_programt::instructiont::output(std::ostream &out) const out << "HAVOC_OBJECT " << format(code.op0()) << '\n'; break; } + else if(code.get_statement() == ID_havoc_reachable) + { + out << "HAVOC_REACHABLE"; + if(code.get_bool(ID_arbitrary_memory)) + out << " (arbitrary memory)"; + bool first = true; + for(const auto &op : code.operands()) + { + out << (first ? " " : ", ") << format(op); + first = false; + } + out << '\n'; + break; + } else if(code.get_statement() == ID_fence) { out << "FENCE"; diff --git a/src/goto-symex/Makefile b/src/goto-symex/Makefile index ec56bb5e12cb..d4d5584792a9 100644 --- a/src/goto-symex/Makefile +++ b/src/goto-symex/Makefile @@ -33,6 +33,7 @@ SRC = auto_objects.cpp \ symex_dereference_state.cpp \ symex_function_call.cpp \ symex_goto.cpp \ + symex_havoc_reachable.cpp \ symex_main.cpp \ symex_other.cpp \ symex_set_return_value.cpp \ diff --git a/src/goto-symex/goto_symex.h b/src/goto-symex/goto_symex.h index 69da868a7a61..0cd7fce9c2a6 100644 --- a/src/goto-symex/goto_symex.h +++ b/src/goto-symex/goto_symex.h @@ -747,6 +747,18 @@ class goto_symext // havocs the given object void havoc_rec(statet &state, const guardt &guard, const exprt &dest); + /// Symbolically executes a `havoc_reachable` statement: assigns + /// nondeterministic values to the objects that the operands of \p code + /// point to (and, if \p code has the `arbitrary_memory` flag, to the + /// objects of static lifetime and the address-taken local variables of all + /// functions on the call stack), and to all objects reachable from these + /// according to the value set. Pointers stored in these objects are + /// restricted to pointers previously stored in them, the addresses of the + /// objects, or null. + /// \param state: Symbolic execution state + /// \param code: The `havoc_reachable` statement + void symex_havoc_reachable(statet &state, const codet &code); + typedef symex_targett::assignment_typet assignment_typet; /// Execute any let expressions in \p expr using diff --git a/src/goto-symex/path_storage.h b/src/goto-symex/path_storage.h index 1b230776cd57..bad08e27cc88 100644 --- a/src/goto-symex/path_storage.h +++ b/src/goto-symex/path_storage.h @@ -115,6 +115,11 @@ class path_storaget /// therefore may be referred to by a pointer. incremental_dirtyt dirty; + /// Number of temporaries introduced by goto_symext::symex_havoc_reachable, + /// to give them unique names (across all paths) without searching the + /// symbol table. + std::size_t havoc_reachable_temporaries = 0; + /// Generates a loop analysis for the instructions in goto_programt and /// keys it against function ID. void add_function_loops(const irep_idt &identifier, const goto_programt &body) diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp new file mode 100644 index 000000000000..c02dcfbb4306 --- /dev/null +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -0,0 +1,462 @@ +/*******************************************************************\ + +Module: Symbolic Execution of havoc_reachable + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Symbolic execution of the havoc_reachable statement, which assigns +/// nondeterministic values to all objects reachable from a set of pointers + +#include +#include +#include +#include +#include +#include + +#include "goto_symex.h" +#include "path_storage.h" + +#include +#include +#include + +/// The maximum number of candidate values of a pointer stored in a havocked +/// object. +static const std::size_t max_pointer_candidates = 64; + +/// The maximum number of elements of an array whose pointer elements are +/// restricted to candidate values. +static const std::size_t max_array_elements = 64; + +/// \return The identifier of the (L1-renamed) object \p object, or the empty +/// identifier if \p object is not a symbol. +static irep_idt object_identifier(const exprt &object) +{ + if(is_ssa_expr(object)) + return remove_level_2(to_ssa_expr(object)).get_identifier(); + if(object.id() == ID_symbol) + return to_symbol_expr(object).get_identifier(); + return {}; +} + +/// \return The identifier of the object that the value set entry with +/// identifier \p identifier belongs to: field-sensitive SSA identifiers +/// append "..component" and "[[index]]" to the identifier of the object. +static irep_idt entry_object_identifier(const irep_idt &identifier) +{ + const std::string &s = id2string(identifier); + const std::size_t pos = std::min(s.find(".."), s.find("[[")); + return pos == std::string::npos ? identifier : irep_idt{s.substr(0, pos)}; +} + +/// \return True iff objects of type \p type cannot be modified. +static bool is_constant_type(const typet &type) +{ + if(type.get_bool(ID_C_constant)) + return true; + if(type.id() == ID_array) + return is_constant_type(to_array_type(type).element_type()); + return false; +} + +/// \return True iff objects of type \p type can be assigned a value as a +/// whole. +static bool is_complete_type(const typet &type, const namespacet &ns) +{ + if(type.id() == ID_code || type.id() == ID_empty) + return false; + if(type.id() == ID_array) + { + const array_typet &array_type = to_array_type(type); + return array_type.size().is_not_nil() && + is_complete_type(array_type.element_type(), ns); + } + if(type.id() == ID_struct_tag) + return !ns.follow_tag(to_struct_tag_type(type)).is_incomplete(); + if(type.id() == ID_union_tag) + return !ns.follow_tag(to_union_tag_type(type)).is_incomplete(); + return true; +} + +/// \return True iff \p type is a pointer to data. +static bool is_data_pointer(const typet &type) +{ + return type.id() == ID_pointer && + to_pointer_type(type).base_type().id() != ID_code; +} + +/// \return True iff objects of type \p type contain pointers to data. +static bool contains_data_pointer(const typet &type, const namespacet &ns) +{ + if(is_data_pointer(type)) + return true; + if(type.id() == ID_array) + return contains_data_pointer(to_array_type(type).element_type(), ns); + if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + const struct_union_typet &struct_union_type = + ns.follow_tag(to_struct_or_union_tag_type(type)); + for(const auto &component : struct_union_type.components()) + { + if(contains_data_pointer(component.type(), ns)) + return true; + } + } + return false; +} + +/// Splits \p lvalue into the pointers to data it contains (\p pointers) and +/// the remaining parts (\p others), descending into structs and into arrays +/// of constant size that contain pointers. Unions and other arrays that +/// contain pointers are not split, and are added to \p others. +static void split_lvalue( + const exprt &lvalue, + const namespacet &ns, + std::vector &pointers, + std::vector &others) +{ + const typet &type = lvalue.type(); + if(is_data_pointer(type)) + pointers.push_back(lvalue); + else if(!contains_data_pointer(type, ns)) + others.push_back(lvalue); + else if(type.id() == ID_struct_tag) + { + for(const auto &component : + ns.follow_tag(to_struct_tag_type(type)).components()) + { + split_lvalue(member_exprt{lvalue, component}, ns, pointers, others); + } + } + else if(type.id() == ID_array) + { + const auto size = numeric_cast(to_array_type(type).size()); + if(!size.has_value() || *size > max_array_elements) + { + others.push_back(lvalue); + return; + } + for(mp_integer i = 0; i < *size; ++i) + { + split_lvalue( + index_exprt{lvalue, from_integer(i, c_index_type())}, + ns, + pointers, + others); + } + } + else + others.push_back(lvalue); +} + +/// \return True iff a pointer of type \p candidate may be stored in a pointer +/// of type \p location without changing what kind of object it points to. +static bool is_compatible_pointer(const typet &location, const typet &candidate) +{ + const typet &location_base = to_pointer_type(location).base_type(); + const typet &candidate_base = to_pointer_type(candidate).base_type(); + auto is_generic = [](const typet &base) + { + return base.id() == ID_empty || + ((base.id() == ID_signedbv || base.id() == ID_unsignedbv) && + to_bitvector_type(base).get_width() == 8); + }; + return location_base == candidate_base || is_generic(location_base) || + is_generic(candidate_base); +} + +/// \return The type of the part of an object of type \p type that \p path +/// denotes, where \p path is a sequence of "..component" and "[[index]]" +/// (as in field-sensitive SSA identifiers) and ".component" and "[]" (as in +/// value set suffixes), or nullptr if \p path cannot be resolved. +static const typet * +type_of_path(const typet &type, const std::string &path, const namespacet &ns) +{ + const typet *current = &type; + std::size_t pos = 0; + while(pos < path.size()) + { + if(path.compare(pos, 2, "[]") == 0 || path.compare(pos, 2, "[[") == 0) + { + if(current->id() != ID_array) + return nullptr; + const std::size_t end = + path.compare(pos, 2, "[]") == 0 ? pos + 2 : path.find("]]", pos) + 2; + if(end < pos + 2) + return nullptr; + current = &to_array_type(*current).element_type(); + pos = end; + } + else if(path[pos] == '.') + { + const std::size_t start = + path.compare(pos, 2, "..") == 0 ? pos + 2 : pos + 1; + std::size_t end = start; + while(end < path.size() && path[end] != '.' && path[end] != '[') + ++end; + if(current->id() != ID_struct_tag && current->id() != ID_union_tag) + { + return nullptr; + } + const struct_union_typet &struct_union_type = + ns.follow_tag(to_struct_or_union_tag_type(*current)); + const irep_idt name = path.substr(start, end - start); + if(!struct_union_type.has_component(name)) + return nullptr; + current = &struct_union_type.get_component(name).type(); + pos = end; + } + else + return nullptr; + } + return current; +} + +void goto_symext::symex_havoc_reachable(statet &state, const codet &code) +{ + const source_locationt &source_location = state.source.pc->source_location(); + + // the objects reachable, in the order they are found + std::vector objects; + std::unordered_set known; + bool unknown_target = false; + + auto add_object = [&objects, &known](const exprt &object) + { + if(known.insert(object_identifier(object)).second) + objects.push_back(object); + }; + + auto add_target = [&add_object, &unknown_target](const exprt &target) + { + if(target.id() == ID_unknown) + { + unknown_target = true; + return; + } + if(target.id() != ID_object_descriptor) + return; + const exprt &root = to_object_descriptor_expr(target).root_object(); + if(root.id() == ID_symbol && root.type().id() != ID_code) + add_object(root); + else if( + root.id() != ID_null_object && root.id() != ID_integer_address && + root.id() != ID_string_constant && root.id() != ID_constant && + root.type().id() != ID_code) + { + unknown_target = true; + } + }; + + // the objects the operands point to + for(const auto &operand : code.operands()) + { + if(operand.type().id() != ID_pointer) + continue; + const exprt pointer = + state.rename(clean_expr(operand, state, false), ns).get(); + for(const auto &target : state.value_set.get_value_set(pointer, ns)) + add_target(target); + } + + // the objects that can be named, and the address-taken local variables of + // all functions on the call stack + if(code.get_bool(ID_arbitrary_memory)) + { + std::vector statics; + for(const auto &entry : outer_symbol_table.symbols) + { + const symbolt &symbol = entry.second; + if( + symbol.is_static_lifetime && !symbol.is_type && !symbol.is_macro && + symbol.is_lvalue && symbol.type.id() != ID_code && + symbol.type.id() != ID_empty && is_complete_type(symbol.type, ns) && + !symbol.name.starts_with(CPROVER_PREFIX) && + !symbol.base_name.starts_with(CPROVER_PREFIX)) + { + statics.push_back(symbol.name); + } + } + std::sort( + statics.begin(), + statics.end(), + [](const irep_idt &a, const irep_idt &b) + { return id2string(a) < id2string(b); }); + for(const auto &name : statics) + { + add_object(state.rename(ns.lookup(name).symbol_expr(), ns).get()); + } + + for(const auto &frame : state.call_stack()) + { + std::vector locals; + for(const irep_idt &l1_identifier : frame.local_objects) + { + const auto entry = state.get_level2().current_names.find(l1_identifier); + if( + entry.has_value() && + path_storage.dirty(entry->get().first.get_object_name())) + { + locals.push_back(entry->get().first); + } + } + std::sort( + locals.begin(), + locals.end(), + [](const ssa_exprt &a, const ssa_exprt &b) { + return id2string(a.get_identifier()) < id2string(b.get_identifier()); + }); + for(const auto &local : locals) + add_object(local); + } + } + + // the closure: the objects pointers stored in reachable objects point to + { + value_sett::valuest::viewt view; + state.value_set.values.get_view(view); + std::unordered_map> + entries; + for(const auto &item : view) + entries[entry_object_identifier(item.second.identifier)].push_back( + &item.second); + + for(std::size_t i = 0; i < objects.size(); ++i) + { + const auto it = entries.find(object_identifier(objects[i])); + if(it == entries.end()) + continue; + const std::string object_id = id2string(it->first); + for(const auto *entry : it->second) + { + // an unknown value of a non-pointer part of the object is no + // unknown pointer target + const typet *type = type_of_path( + objects[i].type(), + id2string(entry->identifier).substr(object_id.size()) + entry->suffix, + ns); + const bool is_pointer = type == nullptr || type->id() == ID_pointer; + for(const auto &target : entry->object_map.read()) + { + const exprt target_expr = state.value_set.to_expr(target); + if(is_pointer || target_expr.id() != ID_unknown) + add_target(target_expr); + } + } + } + } + + std::vector havocked; + for(const auto &object : objects) + { + if(!is_constant_type(object.type())) + havocked.push_back(object); + } + + // Split the objects into the pointers they contain and the remaining + // parts. Assigning a nondeterministic pointer would make its value set + // contain every object in the value set (which is costly to compute, and + // imprecise), so the pointers are assigned a nondeterministic choice among + // candidate values instead. + std::vector pointers, others; + for(const auto &object : havocked) + split_lvalue(object, ns, pointers, others); + + // record the pointers stored in the objects before changing them + std::vector candidates; + for(const auto &pointer : pointers) + { + // get_fresh_aux_symbol would search the symbol table for each of the + // (possibly many) temporaries + const std::string base_name = + "old_pointer$" + + std::to_string(path_storage.havoc_reachable_temporaries++); + auxiliary_symbolt old_value{ + "symex::havoc_reachable::" + base_name, pointer.type(), language_mode}; + old_value.base_name = base_name; + old_value.location = source_location; + const symbol_exprt old_value_expr = old_value.symbol_expr(); + const bool inserted = + state.symbol_table.insert(std::move(old_value)).second; + CHECK_RETURN(inserted); + symex_assign(state, old_value_expr, pointer); + candidates.push_back(old_value_expr); + } + for(const auto &object : objects) + { + if(object.type().id() == ID_array) + { + candidates.push_back( + address_of_exprt{index_exprt{object, from_integer(0, c_index_type())}}); + } + else + candidates.push_back(address_of_exprt{object}); + } + + // the parts that are not pointers + for(const auto &other : others) + { + symex_assign( + state, other, side_effect_expr_nondett{other.type(), source_location}); + } + + // The statement may store any pointer it can obtain: the pointers stored + // in the reachable objects, or the addresses of these objects. Restricting + // the pointers to these values (or null) keeps the value sets, and hence + // dereferencing, precise. To bound the size of the value sets, each pointer + // is restricted to at most max_pointer_candidates of them, starting with + // its own previous value. + bool too_many_candidates = false; + for(std::size_t i = 0; i < pointers.size(); ++i) + { + const exprt &pointer = pointers[i]; + const typet &type = pointer.type(); + std::vector chosen{&candidates[i]}; + for(const auto &candidate : candidates) + { + if( + &candidate == &candidates[i] || + !is_compatible_pointer(type, candidate.type())) + continue; + if(chosen.size() == max_pointer_candidates) + { + too_many_candidates = true; + break; + } + chosen.push_back(&candidate); + } + + exprt value = null_pointer_exprt{to_pointer_type(type)}; + for(auto it = chosen.rbegin(); it != chosen.rend(); ++it) + { + value = if_exprt{ + path_storage.build_symex_nondet(bool_typet{}, source_location), + typecast_exprt::conditional_cast(**it, type), + std::move(value)}; + } + symex_assign(state, pointer, value); + } + + // Unknown targets are common (for example, the pointers stored in memory + // that is allocated, but not yet written), and mean that the pointer may + // hold any value, including addresses of objects that are not in the set. + if(unknown_target) + { + log.debug() << "havocking the objects reachable at " << source_location + << ": some pointers have unknown targets, objects only " + "reachable through them keep their values" + << messaget::eom; + } + + if(too_many_candidates) + { + log.warning() << "havocking the objects reachable at " << source_location + << ": some pointers have more than " << max_pointer_candidates + << " possible values, and are restricted to " + << max_pointer_candidates << " of them" << messaget::eom; + } +} diff --git a/src/goto-symex/symex_other.cpp b/src/goto-symex/symex_other.cpp index fc797d41b36c..57c54d7f4d41 100644 --- a/src/goto-symex/symex_other.cpp +++ b/src/goto-symex/symex_other.cpp @@ -259,6 +259,10 @@ void goto_symext::symex_other( { target.memory_barrier(state.guard.as_expr(), state.source); } + else if(statement == ID_havoc_reachable) + { + symex_havoc_reachable(state, code); + } else if(statement==ID_havoc_object) { DATA_INVARIANT( diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index d9d4dcd561cc..4efac71df477 100644 --- a/src/pointer-analysis/value_set.cpp +++ b/src/pointer-analysis/value_set.cpp @@ -1951,7 +1951,7 @@ void value_sett::apply_code_rec( { // Ignore by default; could prune the value set. } - else if(statement == ID_havoc_object) + else if(statement == ID_havoc_object || statement == ID_havoc_reachable) { } else diff --git a/src/pointer-analysis/value_set_fi.cpp b/src/pointer-analysis/value_set_fi.cpp index 7a57fdad707f..f3336fd8fa78 100644 --- a/src/pointer-analysis/value_set_fi.cpp +++ b/src/pointer-analysis/value_set_fi.cpp @@ -1458,7 +1458,7 @@ void value_set_fit::apply_code(const codet &code, const namespacet &ns) { // doesn't do anything } - else if(statement == ID_havoc_object) + else if(statement == ID_havoc_object || statement == ID_havoc_reachable) { } else diff --git a/src/util/irep_ids.def b/src/util/irep_ids.def index 43bf0c5b7c07..fffe6f046f6f 100644 --- a/src/util/irep_ids.def +++ b/src/util/irep_ids.def @@ -701,6 +701,8 @@ IREP_ID_ONE(java_lambda_method_handle) IREP_ID_TWO(java_lambda_method_handle_index, lambda_method_handle_index) IREP_ID_TWO(java_lambda_method_handles, lambda_method_handles) IREP_ID_ONE(havoc_object) +IREP_ID_ONE(havoc_reachable) +IREP_ID_ONE(arbitrary_memory) IREP_ID_TWO(overflow_shl, overflow-shl) IREP_ID_TWO(C_no_initialization_required, #no_initialization_required) IREP_ID_TWO(C_no_nondet_initialization, #no_nondet_initialization) From 3a87b6f4b6bef846b43d5f8e47c4c9d34e538f52 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 10:24:02 +0000 Subject: [PATCH 026/100] remove_asm: havoc all objects reachable by unmodeled assembly The approximation of inline assembly that is not modeled only changed the objects that the pointer operands point to and, with a "memory" clobber, the objects of static lifetime, the objects that pointers among them point to, and the address-taken local variables of the enclosing function. Heap objects more than one pointer away from these, such as the second node of a list whose head is stored in a global variable, kept their values. So did the local variables of a caller whose address has escaped. Emit a havoc_reachable statement instead. Its roots are the pointer operands and, for a "memory" clobber or basic assembly, all objects of static lifetime and the address-taken local variables of all functions on the call stack. The new statement is evaluated before the outputs are assigned, while the value sets still describe the state before the statement. The explicit assignments to the objects of static lifetime are now done by the new statement instead. They also caused symbolic execution time to grow cubically with the number of statics: every nondeterministic pointer assignment gives that pointer a value set of all objects, which the next statement then has to havoc. For a program with 300 objects of static lifetime (100 pointers and 100 structs with a pointer member) and two such statements, cbmc took 363 seconds; it now takes 0.2 seconds, and symbolic execution takes 10 seconds with 6000 objects of static lifetime. Analyses other than symbolic execution ignore the new statement until the following commits, which make them interpret it. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 49 +++-- .../test.desc | 2 +- .../full-slice.desc | 20 ++ .../cbmc/inline_asm_havoc_reachable/main.c | 63 ++++++ .../cbmc/inline_asm_havoc_reachable/test.desc | 24 +++ src/assembler/asm_approximation.cpp | 182 ++---------------- src/assembler/asm_approximation.h | 45 ++--- src/assembler/remove_asm.cpp | 26 +-- 8 files changed, 169 insertions(+), 242 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable/full-slice.desc create mode 100644 regression/cbmc/inline_asm_havoc_reachable/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index c9b907f7e0f9..47f5f75a518d 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -120,26 +120,29 @@ instruction that is not modeled, then 1. the input operands (and the in-out operands, those with a `+` constraint) are read, which makes them subject to the checks that CBMC performs, for example `--pointer-check`; -2. the objects that the input and in-out operands point to are assigned - nondeterministic values. This includes operands of pointer type, arrays - (which decay to pointers), pointers cast to integer types (as in - `(uintptr_t)&x`), and the pointer members of operands of struct or union - type; +2. the objects that the input and in-out operands point to, and all objects + reachable from these, are assigned nondeterministic values. This includes + operands of pointer type, arrays (which decay to pointers), pointers cast + to integer types (as in `(uintptr_t)&x`), and the pointer members of + operands of struct or union type; 3. if the statement has a `"memory"` clobber, or no operands and no clobbers - at all (basic assembly), all objects of static lifetime, the objects that - those of them that are pointers (or structs or unions with pointer - members) point to, and all local variables of the enclosing function whose - address is taken are assigned nondeterministic values; + at all (basic assembly), all objects of static lifetime, all local + variables whose address is taken of all functions on the call stack, and + all objects reachable from these are assigned nondeterministic values; 4. the output operands are assigned nondeterministic values, at the addresses they had before the statement and, for outputs whose address depends on the program state, also at the addresses they have after it; 5. the rounding mode is assigned a nondeterministic value. -Step 2 uses `__CPROVER_havoc_object`. The abstract domains of -`goto-analyzer` do not track what pointers point to; for such a statement, -the constant propagation domain forgets the values of the objects of static -lifetime and of the address-taken variables, and the interval and -variable-sensitivity domains forget all values. +Symbolic execution computes the reachable objects from the value sets of the +pointers stored in the objects (following pointers transitively), so this +includes, for example, all nodes of a linked list whose head is stored in a +variable of static lifetime. The pointers stored in the objects that are +changed are not made arbitrary: each of them is assigned a nondeterministic +choice among the pointers previously stored in these objects, the addresses +of the reachable objects (of a compatible type), and null. The statement can +thus relink a list, and dereferencing the pointers afterwards remains +precise. MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the @@ -151,12 +154,18 @@ member access such as `s.a` names the variable `s`. ### Limitations - The approximation only reaches the objects listed above. Objects that the - statement can reach only through other pointers, for example heap objects - or local variables of a caller that are not pointed to by an operand or an - object of static lifetime, keep their values. Objects of static lifetime - that are added when linking the CPROVER library are not changed. -- Constant objects and the objects that pointers to constant types point to - are not changed. + statement can reach only through pointers that CBMC does not track (for + example, addresses computed from integers, or pointers stored in local + variables of a caller whose address is not taken) keep their values. +- A pointer stored in a changed object takes one of at most 64 of the + candidate values described above (its own previous value first); a warning + is printed if there are more candidates. Pointers in unions and in arrays + of more than 64 elements, or of a size that is not constant, are assigned + arbitrary values. +- Constant objects are not changed. +- The reachable objects are only changed by symbolic execution (`cbmc`): + other tools, such as `goto-analyzer`, only see the changes to the output + operands and the rounding mode. - Control flow out of a statement is not modeled: `asm goto` statements always continue with the next statement. - In C++ code, the C++ front end discards the operands and clobbers of diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc index 6fc01678b71f..b3be79752232 100644 --- a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc @@ -3,7 +3,7 @@ main.c ^EXIT=10$ ^SIGNAL=0$ -approximating inline assembly statement at .* line 6 function main: instruction 'fxrstor' is not modeled, so the objects its operands point to +approximating inline assembly statement at .* line 6 function main: instruction 'fxrstor' is not modeled, so the objects reachable from its operands ^\[main\.assertion\.1\] line 8 rounding mode: FAILURE$ ^VERIFICATION FAILED$ -- diff --git a/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc new file mode 100644 index 000000000000..a9190cf68c65 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c +--full-slice +^EXIT=10$ +^SIGNAL=0$ +^not slicing, as the program contains inline assembly that may change any reachable object$ +^\[main\.assertion\.1\] line 37 heap object reachable from static: FAILURE$ +^\[main\.assertion\.2\] line 38 pointer in static: FAILURE$ +^\[main\.assertion\.3\] line 39 pointers are restricted to known values: SUCCESS$ +^\[main\.assertion\.4\] line 50 escaped local of caller: FAILURE$ +^\[main\.assertion\.5\] line 51 local without address: SUCCESS$ +^\[main\.assertion\.6\] line 59 heap object reachable from operand: FAILURE$ +^\[main\.assertion\.7\] line 60 unreachable heap object: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dereference failure.*: FAILURE$ +-- +The full slicer does not know which objects havoc_reachable changes and +reads, and therefore does not slice such programs. diff --git a/regression/cbmc/inline_asm_havoc_reachable/main.c b/regression/cbmc/inline_asm_havoc_reachable/main.c new file mode 100644 index 000000000000..beefb179756d --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/main.c @@ -0,0 +1,63 @@ +// Inline assembly that is not modeled may change all objects it can reach: +// with a "memory" clobber, everything reachable from objects of static +// lifetime and from address-taken local variables of all functions on the +// call stack, and otherwise everything reachable from its pointer operands. +#include + +struct node +{ + int data; + struct node *next; +}; + +struct node *head; + +static void clobber(void) +{ + asm volatile("cli" ::: "memory"); +} + +static struct node *new_node(int data, struct node *next) +{ + struct node *n = malloc(sizeof(struct node)); + __CPROVER_assume(n != NULL); + n->data = data; + n->next = next; + return n; +} + +int main(void) +{ + struct node *b = new_node(2, NULL); + struct node *a = new_node(1, b); + + // reachable from an object of static lifetime, two levels deep + head = a; + clobber(); + __CPROVER_assert(b->data == 2, "heap object reachable from static"); // fails + __CPROVER_assert(head == a, "pointer in static"); // fails + __CPROVER_assert( + head == a || head == b || head == NULL, + "pointers are restricted to known values"); // holds + if(head != NULL) + head->data = 0; // no dereference failure + + // a local variable of a caller whose address is taken + int local = 0; + int *alias = &local; + int unaddressed = 0; + clobber(); + __CPROVER_assert(local == 0, "escaped local of caller"); // fails + __CPROVER_assert(unaddressed == 0, "local without address"); // holds + + // without a "memory" clobber: only what the operands reach + head = NULL; + struct node *d = new_node(4, NULL); + struct node *c = new_node(3, d); + struct node *e = new_node(5, NULL); + asm volatile("foo %0" : : "r"(c)); + __CPROVER_assert(d->data == 4, "heap object reachable from operand"); // fails + __CPROVER_assert(e->data == 5, "unreachable heap object"); // holds + + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable/test.desc b/regression/cbmc/inline_asm_havoc_reachable/test.desc new file mode 100644 index 000000000000..3f9c80faf63c --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 37 heap object reachable from static: FAILURE$ +^\[main\.assertion\.2\] line 38 pointer in static: FAILURE$ +^\[main\.assertion\.3\] line 39 pointers are restricted to known values: SUCCESS$ +^\[main\.assertion\.4\] line 50 escaped local of caller: FAILURE$ +^\[main\.assertion\.5\] line 51 local without address: SUCCESS$ +^\[main\.assertion\.6\] line 59 heap object reachable from operand: FAILURE$ +^\[main\.assertion\.7\] line 60 unreachable heap object: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dereference failure.*: FAILURE$ +-- +The havoc_reachable statement that the approximation of inline assembly emits +is implemented in symbolic execution using the value set: all objects +reachable from the pointer operands (and, with a "memory" clobber, from the +objects of static lifetime and the address-taken local variables of all +functions on the call stack) are assigned nondeterministic values. The +pointers stored in these objects are restricted to previously stored pointers, +the addresses of the reachable objects, and null. diff --git a/src/assembler/asm_approximation.cpp b/src/assembler/asm_approximation.cpp index bbbdc061fd65..78fab0063821 100644 --- a/src/assembler/asm_approximation.cpp +++ b/src/assembler/asm_approximation.cpp @@ -14,18 +14,15 @@ Author: Michael Tautschnig #include #include #include -#include #include #include #include #include #include -#include +#include #include -#include - /// \return True iff objects of type \p type cannot be modified. static bool is_constant_type(const typet &type) { @@ -36,25 +33,6 @@ static bool is_constant_type(const typet &type) return false; } -/// \return True iff objects of type \p type can be assigned a value as a -/// whole. -static bool is_complete_type(const typet &type, const namespacet &ns) -{ - if(type.id() == ID_code || type.id() == ID_empty) - return false; - if(type.id() == ID_array) - { - const array_typet &array_type = to_array_type(type); - return array_type.size().is_not_nil() && - is_complete_type(array_type.element_type(), ns); - } - if(type.id() == ID_struct_tag) - return !ns.follow_tag(to_struct_tag_type(type)).is_incomplete(); - if(type.id() == ID_union_tag) - return !ns.follow_tag(to_union_tag_type(type)).is_incomplete(); - return true; -} - /// \return True iff the address of lvalue \p expr does not depend on the /// program state. static bool has_constant_address(const exprt &expr) @@ -124,91 +102,6 @@ void asm_approximationt::collect_addresses( } } -std::vector asm_approximationt::address_taken_locals( - const goto_programt &body, - const namespacet &ns) -{ - std::vector result; - - auto collect = [&result, &ns](const exprt &root) - { - for(auto it = root.depth_cbegin(); it != root.depth_cend(); ++it) - { - if(it->id() != ID_address_of) - continue; - - const exprt *object = &to_address_of_expr(*it).object(); - while(object->id() == ID_member || object->id() == ID_index || - object->id() == ID_typecast || - object->id() == ID_byte_extract_little_endian || - object->id() == ID_byte_extract_big_endian) - { - object = &object->operands().front(); - } - - if(object->id() != ID_symbol) - continue; - - const symbolt *symbol = nullptr; - if(ns.lookup(to_symbol_expr(*object).get_identifier(), symbol)) - continue; - - if( - !symbol->is_static_lifetime && symbol->is_lvalue && - !is_constant_type(symbol->type) && is_complete_type(symbol->type, ns)) - { - result.push_back(to_symbol_expr(*object)); - } - } - }; - - for(const auto &instruction : body.instructions) - { - collect(instruction.code()); - if(instruction.has_condition()) - collect(instruction.condition()); - } - - auto by_name = [](const symbol_exprt &a, const symbol_exprt &b) - { return id2string(a.get_identifier()) < id2string(b.get_identifier()); }; - std::sort(result.begin(), result.end(), by_name); - result.erase(std::unique(result.begin(), result.end()), result.end()); - - return result; -} - -const std::vector &asm_approximationt::get_static_objects() -{ - if(static_objects.has_value()) - return *static_objects; - - const namespacet ns{symbol_table}; - static_objects = std::vector{}; - for(const auto &entry : symbol_table.symbols) - { - const symbolt &symbol = entry.second; - if( - !symbol.is_static_lifetime || symbol.is_type || symbol.is_macro || - !symbol.is_lvalue || is_constant_type(symbol.type) || - !is_complete_type(symbol.type, ns) || - symbol.name.starts_with(CPROVER_PREFIX) || - symbol.base_name.starts_with(CPROVER_PREFIX)) - { - continue; - } - - static_objects->push_back(symbol.symbol_expr()); - } - - std::sort( - static_objects->begin(), - static_objects->end(), - [](const symbol_exprt &a, const symbol_exprt &b) - { return id2string(a.get_identifier()) < id2string(b.get_identifier()); }); - - return *static_objects; -} - /// Appends to \p dest an assignment of a nondeterministic value to \p lvalue. static void havoc_lvalue( const exprt &lvalue, @@ -221,23 +114,6 @@ static void havoc_lvalue( source_location)); } -/// Appends to \p dest instructions that assign a nondeterministic value to the -/// object \p pointer points to, unless \p pointer is null. -static void havoc_pointee( - const exprt &pointer, - const source_locationt &source_location, - goto_programt &dest) -{ - const null_pointer_exprt null{to_pointer_type(pointer.type())}; - auto skip = dest.add(goto_programt::make_incomplete_goto( - equal_exprt{pointer, null}, source_location)); - - const codet havoc{ID_havoc_object, {pointer}, source_location}; - dest.add(goto_programt::make_other(havoc, source_location)); - - skip->complete_goto(dest.add(goto_programt::make_skip(source_location))); -} - symbol_exprt asm_approximationt::snapshot( const exprt &value, const std::string &base_name, @@ -360,7 +236,6 @@ void asm_approximationt::assign_outputs( void asm_approximationt::operator()( const asm_footprintt &footprint, - const std::vector &address_taken_locals, const irep_idt &function_id, const source_locationt &source_location, goto_programt &dest) @@ -376,38 +251,8 @@ void asm_approximationt::operator()( dest.add(goto_programt::make_other(evaluate, source_location)); } - // 2. record the values of addresses before any of them is changed, as the - // instructions below may change the objects these are stored in - - // pointers, and the values of the pointers stored in objects of static - // lifetime if the statement may access arbitrary memory - std::vector addresses = footprint.addresses; - if(footprint.arbitrary_memory) - { - for(const auto &object : get_static_objects()) - { - if(object.type().id() != ID_array) - collect_addresses(object, ns, addresses); - } - } - - std::vector pointers; - for(const auto &address : addresses) - { - if(address.id() == ID_address_of) - { - const exprt &object = to_address_of_expr(address).object(); - if(has_constant_address(object)) - { - pointers.push_back(address); - continue; - } - } - pointers.push_back(snapshot( - address, "asm_address", function_id, source_location, temporaries, dest)); - } - - // the lvalues written, with addresses evaluated before the statement + // 2. the lvalues written, with addresses evaluated before the statement + // changes any object std::vector writes; for(const auto &write : footprint.writes) { @@ -415,20 +260,17 @@ void asm_approximationt::operator()( write, function_id, source_location, temporaries, dest)); } - // 3. the objects pointed to - for(const auto &pointer : pointers) - havoc_pointee(pointer, source_location, dest); - - // 4. arbitrary memory: what the statement can name - if(footprint.arbitrary_memory) + // 3. the objects reachable from the addresses and, for arbitrary memory + // accesses, from what the statement can name + if(!footprint.addresses.empty() || footprint.arbitrary_memory) { - for(const auto &object : get_static_objects()) - havoc_lvalue(object, source_location, dest); - for(const auto &local : address_taken_locals) - havoc_lvalue(local, source_location, dest); + codet havoc{ID_havoc_reachable, footprint.addresses, source_location}; + if(footprint.arbitrary_memory) + havoc.set(ID_arbitrary_memory, true); + dest.add(goto_programt::make_other(havoc, source_location)); } - // 5. the outputs, at their addresses before the statement and, as + // 4. the outputs, at their addresses before the statement and, as // compilers differ in when they compute the address of an output (GCC at // -O0 computes it after the statement has written the other outputs, other // compilers and optimization levels before), at their addresses after it @@ -440,7 +282,7 @@ void asm_approximationt::operator()( havoc_lvalue(write, source_location, dest); } - // 6. the floating-point rounding mode, which the statement may change via + // 5. the floating-point rounding mode, which the statement may change via // the control registers of the floating-point unit const symbolt *rounding_mode = nullptr; if(!ns.lookup(CPROVER_PREFIX "rounding_mode", rounding_mode)) diff --git a/src/assembler/asm_approximation.h b/src/assembler/asm_approximation.h index 6e0826a9d91c..784fbc494b6c 100644 --- a/src/assembler/asm_approximation.h +++ b/src/assembler/asm_approximation.h @@ -38,9 +38,10 @@ struct asm_footprintt std::vector writes; /// Expressions whose values the statement may use as addresses: the objects - /// they point to may be written. Arrays decay to the address of their first - /// element, casts to integer types are looked through, and the pointer - /// members of structs and unions are included. + /// they point to, and all objects reachable from these, may be written. + /// Arrays decay to the address of their first element, casts to integer + /// types are looked through, and the pointer members of structs and unions + /// are included. std::vector addresses; /// Whether the statement may access memory not described by its operands @@ -49,8 +50,7 @@ struct asm_footprintt }; /// Builds the instructions that conservatively approximate an inline assembly -/// statement given its footprint. The objects of static lifetime are -/// computed once and shared across statements. +/// statement given its footprint. class asm_approximationt { public: @@ -61,31 +61,25 @@ class asm_approximationt /// Appends to \p dest instructions that /// 1. evaluate the reads of \p footprint; - /// 2. record the addresses of the writes and the values of the addresses - /// of \p footprint in temporaries; - /// 3. assign nondeterministic values to the objects the addresses point to; - /// 4. if \p footprint has arbitrary memory accesses: assign - /// nondeterministic values to the objects of static lifetime, to the - /// objects that pointers stored in objects of static lifetime point to, - /// and to \p address_taken_locals; - /// 5. assign nondeterministic values to the writes, at the addresses they + /// 2. record the addresses of the writes in temporaries; + /// 3. assign nondeterministic values to all objects reachable from the + /// addresses of \p footprint and, if \p footprint has arbitrary memory + /// accesses, from the objects of static lifetime and the address-taken + /// local variables of all functions on the call stack (a + /// `havoc_reachable` statement, which symbolic execution implements + /// using the value set); + /// 4. assign nondeterministic values to the writes, at the addresses they /// had before the statement and, for writes whose address depends on the /// program state, also at the addresses they have after it, as compilers /// differ in when they compute these addresses; - /// 6. assign a nondeterministic rounding mode. - /// Objects that are reachable only through other pointers (for example, a - /// caller's local variables or heap objects not referenced by an object of - /// static lifetime) are not changed. + /// 5. assign a nondeterministic rounding mode. /// \param footprint: What the statement may read and write - /// \param address_taken_locals: The local variables of the enclosing - /// function whose address is taken /// \param function_id: Name of the enclosing function, which temporaries /// are added to /// \param source_location: Location of the statement /// \param dest: Goto program to append the instructions to void operator()( const asm_footprintt &footprint, - const std::vector &address_taken_locals, const irep_idt &function_id, const source_locationt &source_location, goto_programt &dest); @@ -119,11 +113,6 @@ class asm_approximationt const source_locationt &source_location, goto_programt &dest); - /// \return The local variables of \p body whose address is taken, sorted by - /// name and excluding objects of static lifetime and constant objects. - static std::vector - address_taken_locals(const goto_programt &body, const namespacet &ns); - /// \return True iff the address of the lvalue \p lvalue (of the object /// that contains it, for a bit field) depends on the program state, as /// for `a[i]` or `*p`. Compilers differ in whether they compute the @@ -141,12 +130,6 @@ class asm_approximationt private: symbol_table_baset &symbol_table; - /// The modifiable objects of static lifetime, sorted by name; computed on - /// first use. - std::optional> static_objects; - - const std::vector &get_static_objects(); - /// Appends to \p dest the declaration of a fresh temporary of the function /// \p function_id, whose name starts with \p base_name, and the assignment /// of \p value to it, and adds the temporary to \p temporaries. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 75745ff19c7e..8018b4b66366 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -67,9 +67,6 @@ class remove_asmt messaget log; asm_approximationt approximate; - /// The address-taken local variables of the function being processed. - std::vector address_taken_locals; - using instructionst = std::list; using handle_commandt = std::function parts; if(!footprint.writes.empty()) @@ -354,11 +350,10 @@ void remove_asmt::approximate_asm( parts.push_back(addresses_description); if(footprint.arbitrary_memory) { + parts.push_back("all objects of static lifetime"); parts.push_back( - "all objects of static lifetime and the objects their pointers point " - "to"); - parts.push_back( - "the address-taken local variables of " + id2string(function_id)); + "the address-taken local variables of the functions on the call stack"); + parts.push_back("the objects reachable from any of these"); } parts.push_back("the rounding mode"); @@ -652,7 +647,7 @@ void remove_asmt::process_instruction_gcc( reason, footprint, "its output operands", - "the objects its operands point to", + "the objects reachable from its operands", dest); } @@ -982,7 +977,7 @@ void remove_asmt::process_instruction_msc( not_modeled(*unknown), footprint, "the local variables it names", - "the objects these point to", + "the objects reachable from these", dest); } @@ -1073,20 +1068,11 @@ void remove_asmt::process_function( goto_functionst::goto_functiont &goto_function) { bool did_something = false; - bool locals_computed = false; Forall_goto_program_instructions(it, goto_function.body) { if(it->is_other() && it->get_other().get_statement() == ID_asm) { - // compute before any of the statements is replaced - if(!locals_computed) - { - address_taken_locals = asm_approximationt::address_taken_locals( - goto_function.body, namespacet{symbol_table}); - locals_computed = true; - } - goto_programt tmp_dest; process_instruction(function_id, *it, tmp_dest); it->turn_into_skip(); From ec2a67749761b47b30091e4989f234580b9221a4 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 11:15:35 +0000 Subject: [PATCH 027/100] goto_rw: objects that havoc_reachable reads and writes goto_rw treated havoc_reachable like havoc_object of each operand: with a "memory" clobber, which has no operands, the statement neither read nor wrote anything. Analyses built on goto_rw, such as reaching definitions and the dependence graph, thus considered the havocked objects unchanged. With value sets (rw_range_set_value_sett), compute the reachable objects like symbolic execution does: - the roots are the operands and, with the arbitrary_memory flag, the objects of static lifetime and the address-taken local variables (as set by the new set_dirty, which reaching definitions and the dependence graph use); - the closure follows the pointers stored in reachable objects using the value sets. The statement reads the operands and the pointers it follows, and writes the reachable objects that are symbols. Heap objects remain untracked, as for all other instructions. Without value sets, it writes the objects the operands point to and, with the arbitrary_memory flag, the objects of static lifetime. The closure is computed by the new find_reachable_objects. It works for any pointer analysis, as it traverses objects with the type of the pointer they are reached through. This handles dynamic objects, whose type the static analyses do not know. Symbolic execution now shares the list of objects of static lifetime and the pointer compatibility check with it. The full slicer still does not slice programs that contain the statement. The dependence graph does not track heap objects, so the instructions that link heap objects would be sliced away, making the objects that the statement changes unreachable. --full-slice already gets this wrong for heap accesses without inline assembly (#260). Co-authored-by: Kiro --- jbmc/src/jbmc/Makefile | 1 + .../dependence-graph-havoc-reachable/main.c | 15 ++ .../test.desc | 15 ++ src/analyses/dependence_graph.cpp | 1 + src/analyses/goto_rw.cpp | 84 +++++++- src/analyses/goto_rw.h | 35 ++++ src/analyses/reaching_definitions.cpp | 1 + src/cbmc/Makefile | 1 + src/goto-instrument/full_slicer.cpp | 5 +- src/goto-symex/symex_havoc_reachable.cpp | 64 +----- src/libcprover-cpp/Makefile | 1 + src/pointer-analysis/Makefile | 1 + src/pointer-analysis/reachable_objects.cpp | 192 ++++++++++++++++++ src/pointer-analysis/reachable_objects.h | 75 +++++++ 14 files changed, 423 insertions(+), 68 deletions(-) create mode 100644 regression/goto-analyzer/dependence-graph-havoc-reachable/main.c create mode 100644 regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc create mode 100644 src/pointer-analysis/reachable_objects.cpp create mode 100644 src/pointer-analysis/reachable_objects.h diff --git a/jbmc/src/jbmc/Makefile b/jbmc/src/jbmc/Makefile index f87d8d3662d5..cd58c57f5ec2 100644 --- a/jbmc/src/jbmc/Makefile +++ b/jbmc/src/jbmc/Makefile @@ -10,6 +10,7 @@ OBJ += ../$(CPROVER_DIR)/src/ansi-c/ansi-c$(LIBEXT) \ ../$(CPROVER_DIR)/src/goto-checker/goto-checker$(LIBEXT) \ ../$(CPROVER_DIR)/src/goto-programs/goto-programs$(LIBEXT) \ ../$(CPROVER_DIR)/src/goto-symex/goto-symex$(LIBEXT) \ + ../$(CPROVER_DIR)/src/pointer-analysis/reachable_objects$(OBJEXT) \ ../$(CPROVER_DIR)/src/pointer-analysis/value_set$(OBJEXT) \ ../$(CPROVER_DIR)/src/pointer-analysis/value_set_analysis_fi$(OBJEXT) \ ../$(CPROVER_DIR)/src/pointer-analysis/value_set_domain_fi$(OBJEXT) \ diff --git a/regression/goto-analyzer/dependence-graph-havoc-reachable/main.c b/regression/goto-analyzer/dependence-graph-havoc-reachable/main.c new file mode 100644 index 000000000000..4cfaf3c84531 --- /dev/null +++ b/regression/goto-analyzer/dependence-graph-havoc-reachable/main.c @@ -0,0 +1,15 @@ +int x; +int *p; + +int main() +{ + p = &x; + x = 1; +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + int out = *p; + return out; +} diff --git a/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc b/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc new file mode 100644 index 000000000000..570de1bdf3c2 --- /dev/null +++ b/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc @@ -0,0 +1,15 @@ +CORE +main.c +--dependence-graph --show +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +\/\/ ([0-9]+).*\n.*p := address_of\(x\)\n(.*\n)*Data dependencies: ([0-9]+,)*\1(,[0-9]+)*\n\n.*\n.*HAVOC_REACHABLE \(arbitrary memory\) +\/\/ ([0-9]+).*\n.*HAVOC_REACHABLE \(arbitrary memory\)\n(.*\n)*Data dependencies: ([0-9]+,)*\1(,[0-9]+)*\n\n.*\n.*out := \*p +-- +^warning: ignoring +-- +The havoc_reachable statement emitted for the inline assembly reads the +pointers stored in the objects reachable from the objects of static lifetime +(here, p), and writes the objects it reaches (here, x, which out is then read +from). diff --git a/src/analyses/dependence_graph.cpp b/src/analyses/dependence_graph.cpp index efb7c6ae8fca..0c22ae8cc585 100644 --- a/src/analyses/dependence_graph.cpp +++ b/src/analyses/dependence_graph.cpp @@ -165,6 +165,7 @@ void dep_graph_domaint::data_dependencies( value_setst &value_sets= dep_graph.reaching_definitions().get_value_sets(); rw_range_set_value_sett rw_set(ns, value_sets, message_handler); + rw_set.set_dirty(dep_graph.reaching_definitions().get_is_dirty()); goto_rw(function_to, to, rw_set); for(const auto &read_object_entry : rw_set.get_r_set()) diff --git a/src/analyses/goto_rw.cpp b/src/analyses/goto_rw.cpp index 84f5aa242121..01844bb6d3a3 100644 --- a/src/analyses/goto_rw.cpp +++ b/src/analyses/goto_rw.cpp @@ -19,12 +19,17 @@ Date: April 2010 #include #include #include +#include #include #include #include +#include +#include "dirty.h" + +#include #include range_domain_baset::~range_domain_baset() @@ -673,6 +678,78 @@ void rw_range_sett::get_array_objects( mode, ode.root_object(), range_spect::unknown(), range_spect::unknown()); } +void rw_range_sett::get_havoc_reachable_objects( + const irep_idt &function, + goto_programt::const_targett target, + const codet &code) +{ + for(const auto &op : code.operands()) + { + get_objects_rec(function, target, get_modet::READ, op); + get_array_objects(function, target, get_modet::LHS_W, op); + } + + if(code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + { + get_objects_rec(function, target, get_modet::LHS_W, object); + } + } +} + +void rw_range_set_value_sett::get_havoc_reachable_objects( + const irep_idt &_function, + goto_programt::const_targett _target, + const codet &code) +{ + function = _function; + target = _target; + + std::vector roots; + if(code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + { + roots.push_back(object); + } + if(dirty != nullptr) + { + std::vector locals; + for(const auto &identifier : dirty->get_dirty_ids()) + { + const symbolt *symbol = nullptr; + if(!ns.lookup(identifier, symbol) && !symbol->is_static_lifetime) + locals.push_back(identifier); + } + std::sort( + locals.begin(), + locals.end(), + [](const irep_idt &a, const irep_idt &b) + { return id2string(a) < id2string(b); }); + for(const auto &identifier : locals) + roots.push_back(ns.lookup(identifier).symbol_expr()); + } + } + + const reachable_objectst reachable = find_reachable_objects( + code.operands(), + roots, + [this](const exprt &pointer) + { return value_sets.get_values(function, target, pointer); }, + ns); + + for(const auto &op : code.operands()) + get_objects_rec(get_modet::READ, op); + for(const auto &pointer : reachable.pointers) + get_objects_rec(get_modet::READ, pointer); + for(const auto &object : reachable.objects) + { + if(object.id() == ID_symbol) + get_objects_rec(get_modet::LHS_W, object); + } +} + void rw_range_set_value_sett::get_objects_dereference( get_modet mode, const dereference_exprt &deref, @@ -842,12 +919,7 @@ static void goto_rw_other( } else if(statement == ID_havoc_reachable) { - // at least the objects the operands point to are written - for(const auto &op : code.operands()) - { - rw_set.get_array_objects( - function, target, rw_range_sett::get_modet::LHS_W, op); - } + rw_set.get_havoc_reachable_objects(function, target, code); } } diff --git a/src/analyses/goto_rw.h b/src/analyses/goto_rw.h index 35bd191771bc..619481b8743e 100644 --- a/src/analyses/goto_rw.h +++ b/src/analyses/goto_rw.h @@ -257,6 +257,18 @@ class rw_range_sett get_modet, const exprt &); + /// Adds the objects that the `havoc_reachable` statement \p code reads and + /// writes. Without a pointer analysis, these are the operands (read), the + /// objects they point to (written), and, if \p code has the + /// `arbitrary_memory` flag, the objects of static lifetime (written). + /// \param function: Function containing \p target + /// \param target: The instruction \p code belongs to + /// \param code: The `havoc_reachable` statement + virtual void get_havoc_reachable_objects( + const irep_idt &function, + goto_programt::const_targett target, + const codet &code); + void output(std::ostream &out) const; protected: @@ -362,6 +374,7 @@ inline std::ostream &operator << ( return out; } +class dirtyt; class value_setst; class rw_range_set_value_sett:public rw_range_sett @@ -410,8 +423,30 @@ class rw_range_set_value_sett:public rw_range_sett rw_range_sett::get_array_objects(_function, _target, mode, pointer); } + /// Adds the objects that the `havoc_reachable` statement \p code reads and + /// writes, using the value sets: the operands and the pointers stored in + /// reachable objects are read, and all reachable objects that are symbols + /// are written. With the `arbitrary_memory` flag, the objects of static + /// lifetime and, if set via \ref set_dirty, the address-taken local + /// variables of all functions are additional roots. + /// \param function: Function containing \p target + /// \param target: The instruction \p code belongs to + /// \param code: The `havoc_reachable` statement + void get_havoc_reachable_objects( + const irep_idt &function, + goto_programt::const_targett target, + const codet &code) override; + + /// Sets the address-taken local variables that `havoc_reachable` with the + /// `arbitrary_memory` flag may change. + void set_dirty(const dirtyt &_dirty) + { + dirty = &_dirty; + } + protected: value_setst &value_sets; + const dirtyt *dirty = nullptr; irep_idt function; goto_programt::const_targett target; diff --git a/src/analyses/reaching_definitions.cpp b/src/analyses/reaching_definitions.cpp index c5d4adeb2097..2c3a4ffaf2e5 100644 --- a/src/analyses/reaching_definitions.cpp +++ b/src/analyses/reaching_definitions.cpp @@ -310,6 +310,7 @@ void rd_range_domaint::transform_assign( reaching_definitions_analysist &rd) { rw_range_set_value_sett rw_set(ns, rd.get_value_sets(), message_handler); + rw_set.set_dirty(rd.get_is_dirty()); goto_rw(function_to, to, rw_set); const bool is_must_alias=rw_set.get_w_set().size()==1; diff --git a/src/cbmc/Makefile b/src/cbmc/Makefile index cc5be488a552..19d3fc09a7a4 100644 --- a/src/cbmc/Makefile +++ b/src/cbmc/Makefile @@ -14,6 +14,7 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../goto-checker/goto-checker$(LIBEXT) \ ../goto-programs/goto-programs$(LIBEXT) \ ../goto-symex/goto-symex$(LIBEXT) \ + ../pointer-analysis/reachable_objects$(OBJEXT) \ ../pointer-analysis/value_set$(OBJEXT) \ ../pointer-analysis/value_set_analysis_fi$(OBJEXT) \ ../pointer-analysis/value_set_domain_fi$(OBJEXT) \ diff --git a/src/goto-instrument/full_slicer.cpp b/src/goto-instrument/full_slicer.cpp index c56666f09f0b..3a6f1c1e9c39 100644 --- a/src/goto-instrument/full_slicer.cpp +++ b/src/goto-instrument/full_slicer.cpp @@ -259,8 +259,9 @@ void full_slicert::operator()( message_handlert &message_handler) { // The objects that havoc_reachable (from the approximation of inline - // assembly) changes, and hence the instructions it depends on, are only - // known during symbolic execution. + // assembly) changes are reachable through heap objects, which the + // dependence graph does not track: the instructions that link heap objects + // would be sliced away, making these objects unreachable. for(const auto &gf_entry : goto_functions.function_map) { for(const auto &instruction : gf_entry.second.body.instructions) diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index c02dcfbb4306..1e90506ba52d 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -12,10 +12,10 @@ Author: Michael Tautschnig #include #include -#include #include #include -#include + +#include #include "goto_symex.h" #include "path_storage.h" @@ -63,25 +63,6 @@ static bool is_constant_type(const typet &type) return false; } -/// \return True iff objects of type \p type can be assigned a value as a -/// whole. -static bool is_complete_type(const typet &type, const namespacet &ns) -{ - if(type.id() == ID_code || type.id() == ID_empty) - return false; - if(type.id() == ID_array) - { - const array_typet &array_type = to_array_type(type); - return array_type.size().is_not_nil() && - is_complete_type(array_type.element_type(), ns); - } - if(type.id() == ID_struct_tag) - return !ns.follow_tag(to_struct_tag_type(type)).is_incomplete(); - if(type.id() == ID_union_tag) - return !ns.follow_tag(to_union_tag_type(type)).is_incomplete(); - return true; -} - /// \return True iff \p type is a pointer to data. static bool is_data_pointer(const typet &type) { @@ -153,22 +134,6 @@ static void split_lvalue( others.push_back(lvalue); } -/// \return True iff a pointer of type \p candidate may be stored in a pointer -/// of type \p location without changing what kind of object it points to. -static bool is_compatible_pointer(const typet &location, const typet &candidate) -{ - const typet &location_base = to_pointer_type(location).base_type(); - const typet &candidate_base = to_pointer_type(candidate).base_type(); - auto is_generic = [](const typet &base) - { - return base.id() == ID_empty || - ((base.id() == ID_signedbv || base.id() == ID_unsignedbv) && - to_bitvector_type(base).get_width() == 8); - }; - return location_base == candidate_base || is_generic(location_base) || - is_generic(candidate_base); -} - /// \return The type of the part of an object of type \p type that \p path /// denotes, where \p path is a sequence of "..component" and "[[index]]" /// (as in field-sensitive SSA identifiers) and ".component" and "[]" (as in @@ -267,29 +232,8 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // all functions on the call stack if(code.get_bool(ID_arbitrary_memory)) { - std::vector statics; - for(const auto &entry : outer_symbol_table.symbols) - { - const symbolt &symbol = entry.second; - if( - symbol.is_static_lifetime && !symbol.is_type && !symbol.is_macro && - symbol.is_lvalue && symbol.type.id() != ID_code && - symbol.type.id() != ID_empty && is_complete_type(symbol.type, ns) && - !symbol.name.starts_with(CPROVER_PREFIX) && - !symbol.base_name.starts_with(CPROVER_PREFIX)) - { - statics.push_back(symbol.name); - } - } - std::sort( - statics.begin(), - statics.end(), - [](const irep_idt &a, const irep_idt &b) - { return id2string(a) < id2string(b); }); - for(const auto &name : statics) - { - add_object(state.rename(ns.lookup(name).symbol_expr(), ns).get()); - } + for(const auto &object : static_lifetime_objects(outer_symbol_table, ns)) + add_object(state.rename(object, ns).get()); for(const auto &frame : state.call_stack()) { diff --git a/src/libcprover-cpp/Makefile b/src/libcprover-cpp/Makefile index d1d05f89c09b..886e6db9cd4c 100644 --- a/src/libcprover-cpp/Makefile +++ b/src/libcprover-cpp/Makefile @@ -33,6 +33,7 @@ OBJ += \ ../linking/linking$(LIBEXT) \ ../pointer-analysis/add_failed_symbols$(OBJEXT) \ ../pointer-analysis/goto_program_dereference$(OBJEXT) \ + ../pointer-analysis/reachable_objects$(OBJEXT) \ ../pointer-analysis/value_set$(OBJEXT) \ ../pointer-analysis/value_set_analysis_fi$(OBJEXT) \ ../pointer-analysis/value_set_dereference$(OBJEXT) \ diff --git a/src/pointer-analysis/Makefile b/src/pointer-analysis/Makefile index 657dabe719ee..65ac0f11ee00 100644 --- a/src/pointer-analysis/Makefile +++ b/src/pointer-analysis/Makefile @@ -1,5 +1,6 @@ SRC = add_failed_symbols.cpp \ goto_program_dereference.cpp \ + reachable_objects.cpp \ show_value_sets.cpp \ value_set.cpp \ value_set_analysis.cpp \ diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp new file mode 100644 index 000000000000..50f9efe702d5 --- /dev/null +++ b/src/pointer-analysis/reachable_objects.cpp @@ -0,0 +1,192 @@ +/*******************************************************************\ + +Module: Objects reachable from a set of pointers + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Objects reachable from a set of pointers + +#include "reachable_objects.h" + +#include +#include +#include +#include +#include +#include + +#include +#include + +/// \return True iff objects of type \p type can be assigned a value as a +/// whole. +static bool is_complete_type(const typet &type, const namespacet &ns) +{ + if(type.id() == ID_code || type.id() == ID_empty) + return false; + if(type.id() == ID_array) + { + const array_typet &array_type = to_array_type(type); + return array_type.size().is_not_nil() && + is_complete_type(array_type.element_type(), ns); + } + if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + return !ns.follow_tag(to_struct_or_union_tag_type(type)).is_incomplete(); + return true; +} + +/// \return True iff \p type is a pointer to data. +static bool is_data_pointer(const typet &type) +{ + return type.id() == ID_pointer && + to_pointer_type(type).base_type().id() != ID_code; +} + +/// Appends to \p dest the pointers to data within \p lvalue: \p lvalue itself, +/// the members of structs and unions, and the elements of arrays (represented +/// by the element with index 0, as the pointer analyses do not distinguish +/// elements). +static void collect_pointer_lvalues( + const exprt &lvalue, + const namespacet &ns, + std::vector &dest) +{ + const typet &type = lvalue.type(); + if(is_data_pointer(type)) + dest.push_back(lvalue); + else if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + const struct_union_typet &struct_union_type = + ns.follow_tag(to_struct_or_union_tag_type(type)); + if(struct_union_type.is_incomplete()) + return; + for(const auto &component : struct_union_type.components()) + collect_pointer_lvalues(member_exprt{lvalue, component}, ns, dest); + } + else if(type.id() == ID_array) + { + collect_pointer_lvalues( + index_exprt{lvalue, from_integer(0, c_index_type())}, ns, dest); + } +} + +reachable_objectst find_reachable_objects( + const std::vector &root_pointers, + const std::vector &root_objects, + const get_pointer_targetst &get_targets, + const namespacet &ns) +{ + reachable_objectst result; + + std::set objects_seen; + // an object is traversed once for each type it is reached with + std::set> traversed; + std::vector worklist; + + auto add_object = [&](const exprt &object, const exprt &view) + { + if(objects_seen.insert(object).second) + result.objects.push_back(object); + if(traversed.insert({object, view.type()}).second) + worklist.push_back(view); + }; + + auto follow = [&](const exprt &pointer) + { + const typet &base_type = to_pointer_type(pointer.type()).base_type(); + for(const auto &target : get_targets(pointer)) + { + if(target.id() == ID_unknown) + { + result.has_unknown_targets = true; + continue; + } + if(target.id() != ID_object_descriptor) + continue; + const exprt &root = to_object_descriptor_expr(target).root_object(); + if( + root.id() == ID_null_object || root.id() == ID_integer_address || + root.id() == ID_string_constant || root.id() == ID_constant || + root.type().id() == ID_code) + { + continue; + } + // Traverse the object directly if it is a symbol of the type it is + // accessed with, and through the pointer otherwise. + if(root.id() == ID_symbol && root.type() == base_type) + add_object(root, root); + else if(base_type.id() == ID_empty) + add_object(root, root); + else + add_object(root, dereference_exprt{pointer}); + } + }; + + for(const auto &object : root_objects) + add_object(object, object); + for(const auto &pointer : root_pointers) + { + if(is_data_pointer(pointer.type())) + follow(pointer); + } + + while(!worklist.empty()) + { + const exprt view = worklist.back(); + worklist.pop_back(); + + std::vector pointers; + collect_pointer_lvalues(view, ns, pointers); + for(const auto &pointer : pointers) + { + result.pointers.push_back(pointer); + follow(pointer); + } + } + + return result; +} + +std::vector static_lifetime_objects( + const symbol_table_baset &symbol_table, + const namespacet &ns) +{ + std::vector result; + for(const auto &entry : symbol_table.symbols) + { + const symbolt &symbol = entry.second; + if( + symbol.is_static_lifetime && !symbol.is_type && !symbol.is_macro && + symbol.is_lvalue && is_complete_type(symbol.type, ns) && + !symbol.name.starts_with(CPROVER_PREFIX) && + !symbol.base_name.starts_with(CPROVER_PREFIX)) + { + result.push_back(symbol.symbol_expr()); + } + } + + std::sort( + result.begin(), + result.end(), + [](const symbol_exprt &a, const symbol_exprt &b) + { return id2string(a.get_identifier()) < id2string(b.get_identifier()); }); + + return result; +} + +bool is_compatible_pointer(const typet &location, const typet &candidate) +{ + const typet &location_base = to_pointer_type(location).base_type(); + const typet &candidate_base = to_pointer_type(candidate).base_type(); + auto is_generic = [](const typet &base) + { + return base.id() == ID_empty || + ((base.id() == ID_signedbv || base.id() == ID_unsignedbv) && + to_bitvector_type(base).get_width() == 8); + }; + return location_base == candidate_base || is_generic(location_base) || + is_generic(candidate_base); +} diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h new file mode 100644 index 000000000000..b8252c3e0c14 --- /dev/null +++ b/src/pointer-analysis/reachable_objects.h @@ -0,0 +1,75 @@ +/*******************************************************************\ + +Module: Objects reachable from a set of pointers + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Objects reachable from a set of pointers, given a pointer analysis. This +/// implements the `havoc_reachable` statement (see `asm_approximationt`) for +/// the analyses that work on goto programs. + +#ifndef CPROVER_POINTER_ANALYSIS_REACHABLE_OBJECTS_H +#define CPROVER_POINTER_ANALYSIS_REACHABLE_OBJECTS_H + +#include +#include + +#include +#include + +class namespacet; +class symbol_table_baset; + +/// The result of \ref find_reachable_objects. +struct reachable_objectst +{ + /// The objects reachable, as root objects of object descriptors (symbols, + /// dynamic objects, ...), each listed once. + std::vector objects; + + /// The pointers stored in the reachable objects, as lvalues (possibly + /// containing dereferences) of pointer type. + std::vector pointers; + + /// Whether some pointer has unknown targets. + bool has_unknown_targets = false; +}; + +/// Returns the targets (object descriptors, `unknown`, or `invalid`) of the +/// pointer-typed expression it is given, as a value set does. +using get_pointer_targetst = std::function(const exprt &)>; + +/// Computes the objects reachable from the objects \p root_pointers point to +/// and from \p root_objects, following the pointers stored in reachable +/// objects (members of structs and unions, elements of arrays) transitively. +/// Objects are traversed with the type of the pointer through which they are +/// reached, so that objects whose type is unknown to the pointer analysis +/// (such as dynamic objects) are traversed as well. +/// \param root_pointers: Pointer-typed expressions +/// \param root_objects: Objects (lvalues) +/// \param get_targets: The pointer analysis +/// \param ns: Namespace +/// \return The reachable objects and the pointers stored in them +reachable_objectst find_reachable_objects( + const std::vector &root_pointers, + const std::vector &root_objects, + const get_pointer_targetst &get_targets, + const namespacet &ns); + +/// \return The objects of static lifetime in \p symbol_table, excluding +/// objects of incomplete type and objects used internally by CPROVER, +/// sorted by name. Constant objects are included, as they may contain +/// pointers to objects that can be modified. +std::vector static_lifetime_objects( + const symbol_table_baset &symbol_table, + const namespacet &ns); + +/// \return True iff a pointer of type \p candidate may be stored in a pointer +/// of type \p location without changing what kind of object it points to: +/// the pointed-to types are the same, or one of them is `void` or a byte. +bool is_compatible_pointer(const typet &location, const typet &candidate); + +#endif // CPROVER_POINTER_ANALYSIS_REACHABLE_OBJECTS_H From 42c7db9c6434bdb9d1f7eb99cffc818fa3f13c3b Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 11:16:41 +0000 Subject: [PATCH 028/100] goto-analyzer domains: havoc_reachable may change any variable The constant propagation, interval, variable-sensitivity, and invariant set domains ignored havoc_reachable, or (invariant sets) threw an exception. As remove_asm no longer assigns the objects of static lifetime explicitly, goto-analyzer reported assertions about variables that inline assembly may change as holding. The domains do not track what pointers point to, so treat the statement as changing everything it may reach: - 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 --- .../havoc-reachable-domains/constants.desc | 13 +++++++++++++ .../havoc-reachable-domains/intervals.desc | 12 ++++++++++++ .../havoc-reachable-domains/main.c | 18 ++++++++++++++++++ .../havoc-reachable-domains/vsd.desc | 12 ++++++++++++ src/analyses/constant_propagator.cpp | 10 ++++++---- src/analyses/interval_domain.cpp | 9 ++++++--- src/analyses/invariant_set.cpp | 5 +++-- .../variable_sensitivity_domain.cpp | 11 ++++++++--- 8 files changed, 78 insertions(+), 12 deletions(-) create mode 100644 regression/goto-analyzer/havoc-reachable-domains/constants.desc create mode 100644 regression/goto-analyzer/havoc-reachable-domains/intervals.desc create mode 100644 regression/goto-analyzer/havoc-reachable-domains/main.c create mode 100644 regression/goto-analyzer/havoc-reachable-domains/vsd.desc diff --git a/regression/goto-analyzer/havoc-reachable-domains/constants.desc b/regression/goto-analyzer/havoc-reachable-domains/constants.desc new file mode 100644 index 000000000000..0bb744f8e40d --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/constants.desc @@ -0,0 +1,13 @@ +CORE +main.c +--verify --constants +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 14 global: UNKNOWN$ +^\[main\.assertion\.2\] line 15 address-taken local: UNKNOWN$ +^\[main\.assertion\.3\] line 16 local without address: SUCCESS$ +-- +^warning: ignoring +-- +Inline assembly with a "memory" clobber may change the objects of static +lifetime and the address-taken local variables (the havoc_reachable statement). diff --git a/regression/goto-analyzer/havoc-reachable-domains/intervals.desc b/regression/goto-analyzer/havoc-reachable-domains/intervals.desc new file mode 100644 index 000000000000..5b19196b3a9e --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/intervals.desc @@ -0,0 +1,12 @@ +CORE +main.c +--verify --intervals +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 14 global: UNKNOWN$ +^\[main\.assertion\.2\] line 15 address-taken local: UNKNOWN$ +-- +^warning: ignoring +-- +Inline assembly with a "memory" clobber may change the objects of static +lifetime and the address-taken local variables (the havoc_reachable statement). diff --git a/regression/goto-analyzer/havoc-reachable-domains/main.c b/regression/goto-analyzer/havoc-reachable-domains/main.c new file mode 100644 index 000000000000..41ec0626fcdf --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/main.c @@ -0,0 +1,18 @@ +int global; + +int main() +{ + global = 1; + int local = 2; + int *p = &local; + int unaddressed = 3; +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + __CPROVER_assert(global == 1, "global"); // may change + __CPROVER_assert(local == 2, "address-taken local"); // may change + __CPROVER_assert(unaddressed == 3, "local without address"); // unchanged + return 0; +} diff --git a/regression/goto-analyzer/havoc-reachable-domains/vsd.desc b/regression/goto-analyzer/havoc-reachable-domains/vsd.desc new file mode 100644 index 000000000000..68d7c1049810 --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/vsd.desc @@ -0,0 +1,12 @@ +CORE +main.c +--verify --vsd +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 14 global: UNKNOWN$ +^\[main\.assertion\.2\] line 15 address-taken local: UNKNOWN$ +-- +^warning: ignoring +-- +Inline assembly with a "memory" clobber may change the objects of static +lifetime and the address-taken local variables (the havoc_reachable statement). diff --git a/src/analyses/constant_propagator.cpp b/src/analyses/constant_propagator.cpp index 52c8d069dc41..2b87a5422e88 100644 --- a/src/analyses/constant_propagator.cpp +++ b/src/analyses/constant_propagator.cpp @@ -192,11 +192,13 @@ void constant_propagator_domaint::transform( values.set_to_top(from->dead_symbol()); } else if( - from->is_other() && from->get_other().get_statement() == ID_havoc_object) + from->is_other() && + (from->get_other().get_statement() == ID_havoc_object || + from->get_other().get_statement() == ID_havoc_reachable)) { - // the object the pointer points to may be any of the objects of static - // lifetime and the address-taken variables, as the domain does not track - // pointers + // the objects that the pointer points to, or that are reachable from + // pointers, may be any of the objects of static lifetime and the + // address-taken variables, as the domain does not track pointers if(have_dirty) values.set_dirty_to_top(cp->dirty, ns); else diff --git a/src/analyses/interval_domain.cpp b/src/analyses/interval_domain.cpp index e014b2873c07..4a95d1b18960 100644 --- a/src/analyses/interval_domain.cpp +++ b/src/analyses/interval_domain.cpp @@ -127,9 +127,12 @@ void interval_domaint::transform( case SKIP: // No action required break; case OTHER: - // the object the pointer points to may be any of the variables, as the - // domain does not track pointers - if(instruction.get_other().get_statement() == ID_havoc_object) + // the objects that the pointer points to, or that are reachable from + // pointers, may be any of the variables, as the domain does not track + // pointers + if( + instruction.get_other().get_statement() == ID_havoc_object || + instruction.get_other().get_statement() == ID_havoc_reachable) make_top(); #if 0 DATA_INVARIANT(false, "Unclear what is a safe over-approximation of OTHER"); diff --git a/src/analyses/invariant_set.cpp b/src/analyses/invariant_set.cpp index b0f6211ca59e..aa4d33899120 100644 --- a/src/analyses/invariant_set.cpp +++ b/src/analyses/invariant_set.cpp @@ -1081,9 +1081,10 @@ void invariant_sett::apply_code(const codet &code) // may be a disaster make_true(); } - else if(statement == ID_havoc_object) + else if(statement == ID_havoc_object || statement == ID_havoc_reachable) { - // the object the pointer points to may be any of the objects + // the objects that the pointer points to, or that are reachable from + // pointers, may be any of the objects make_true(); } else if(statement==ID_cpp_delete || diff --git a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp index 2732fd00e69f..74fc25f8c281 100644 --- a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp +++ b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp @@ -154,9 +154,14 @@ void variable_sensitivity_domaint::transform( throw "exceptions not handled"; case OTHER: - // the object the pointer points to may be any of the variables - if(instruction.get_other().get_statement() == ID_havoc_object) - abstract_state.havoc("havoc_object"); + // the objects that the pointer points to, or that are reachable from + // pointers, may be any of the variables + if( + instruction.get_other().get_statement() == ID_havoc_object || + instruction.get_other().get_statement() == ID_havoc_reachable) + { + abstract_state.havoc(id2string(instruction.get_other().get_statement())); + } // throw "other"; break; From c4fa56fc37fa26d613074d450c5dbeef68e77c64 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 11:19:55 +0000 Subject: [PATCH 029/100] Value-set analyses: transformer for havoc_reachable The flow-sensitive and flow-insensitive value-set analyses ignored havoc_reachable. Their clients, such as goto-instrument's pointer instrumentation and the reaching definitions of the dependence graph, so assumed that the pointers inline assembly may change still point to what they pointed to before. Apply the same model as symbolic execution: 1. Find the objects reachable from the operands and, with the arbitrary_memory flag, from the objects of static lifetime and the objects whose address is stored anywhere. The value sets have no call stack, so the latter stand in for the address-taken local variables of the functions on the call stack. 2. Let each pointer stored in a reachable object in addition point to any reachable object of a compatible type, or be null. reachable_pointer_value builds an expression with this value set for the analyses to assign. With more than 64 candidate objects, the pointer may point to an unknown object instead: listing every candidate makes each of the pointers point to each of the objects. In a program with 6000 objects of static lifetime and two such statements, --show-value-sets took 245 seconds instead of 31 seconds without the statements; it now takes 32 seconds. Also update the manual page on what each tool does with approximated inline assembly. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 13 +++-- .../show-value-sets-havoc-reachable/main.c | 16 ++++++ .../show-value-sets-havoc-reachable/test.desc | 14 ++++++ src/pointer-analysis/reachable_objects.cpp | 32 ++++++++++++ src/pointer-analysis/reachable_objects.h | 15 ++++++ src/pointer-analysis/value_set.cpp | 49 ++++++++++++++++++- src/pointer-analysis/value_set.h | 9 ++++ src/pointer-analysis/value_set_fi.cpp | 44 ++++++++++++++++- src/pointer-analysis/value_set_fi.h | 6 +++ 9 files changed, 193 insertions(+), 5 deletions(-) create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable/main.c create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 47f5f75a518d..a0440d002a05 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -163,9 +163,16 @@ member access such as `s.a` names the variable `s`. of more than 64 elements, or of a size that is not constant, are assigned arbitrary values. - Constant objects are not changed. -- The reachable objects are only changed by symbolic execution (`cbmc`): - other tools, such as `goto-analyzer`, only see the changes to the output - operands and the rounding mode. +- Symbolic execution (`cbmc`) computes the reachable objects most + precisely. The static analyses use their own pointer analyses: the value + set analyses (as used by `goto-instrument`) and the reaching definitions and + dependence graph (as used by `goto-analyzer`) follow pointers using their + value sets, but do not track the contents of heap objects. The other + abstract domains of `goto-analyzer` treat the statement as changing all + variables (constant propagation: all objects of static lifetime and all + address-taken variables). `--full-slice` does not slice programs that + contain approximated inline assembly with pointer operands, a `"memory"` + clobber, or no operands (basic assembly). - Control flow out of a statement is not modeled: `asm goto` statements always continue with the next statement. - In C++ code, the C++ front end discards the operands and clobbers of diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable/main.c new file mode 100644 index 000000000000..b80fffa5f772 --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable/main.c @@ -0,0 +1,16 @@ +int x; +int y; +int *p = &x; +int *q; + +int main() +{ + int *local_p = &y; +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + int *r = q; + return 0; +} diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable/test.desc b/regression/goto-instrument/show-value-sets-havoc-reachable/test.desc new file mode 100644 index 000000000000..6c7e1a69003e --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable/test.desc @@ -0,0 +1,14 @@ +CORE +main.c +--show-value-sets +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +\nq = \{[^}]* +\nq = \{[^}]* +-- +^warning: ignoring +-- +q is null until the inline assembly, which may store in q the address of any +object reachable from the objects of static lifetime (x, through p) or whose +address is stored in a variable (y, through local_p). diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp index 50f9efe702d5..aca1e1893cd6 100644 --- a/src/pointer-analysis/reachable_objects.cpp +++ b/src/pointer-analysis/reachable_objects.cpp @@ -190,3 +190,35 @@ bool is_compatible_pointer(const typet &location, const typet &candidate) return location_base == candidate_base || is_generic(location_base) || is_generic(candidate_base); } + +exprt reachable_pointer_value( + const exprt &pointer, + const reachable_objectst &reachable) +{ + const typet &type = pointer.type(); + const nondet_symbol_exprt choice{"value_set::havoc_reachable", bool_typet{}}; + + std::vector candidates; + for(const auto &object : reachable.objects) + { + exprt address = + object.type().id() == ID_array + ? address_of_exprt{index_exprt{object, from_integer(0, c_index_type())}} + : address_of_exprt{object}; + if(is_compatible_pointer(type, address.type())) + { + // Value sets with this many objects make the analyses slow (each of + // the pointers may point to each of the objects); an unknown target is + // a sound and compact alternative. + if(candidates.size() == max_reachable_pointer_candidates) + return if_exprt{choice, pointer, exprt{ID_unknown, type}}; + candidates.push_back(typecast_exprt::conditional_cast(address, type)); + } + } + + exprt value = null_pointer_exprt{to_pointer_type(type)}; + for(auto it = candidates.rbegin(); it != candidates.rend(); ++it) + value = if_exprt{choice, *it, value}; + + return if_exprt{choice, pointer, value}; +} diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h index b8252c3e0c14..3a07d25ede8b 100644 --- a/src/pointer-analysis/reachable_objects.h +++ b/src/pointer-analysis/reachable_objects.h @@ -67,6 +67,21 @@ std::vector static_lifetime_objects( const symbol_table_baset &symbol_table, const namespacet &ns); +/// The maximum number of objects \ref reachable_pointer_value lists +/// explicitly. +const std::size_t max_reachable_pointer_candidates = 64; + +/// \return An expression whose value set is what the pointer \p pointer, +/// stored in one of the objects of \p reachable, may point to after these +/// objects have been changed: its previous value, the address of any of the +/// reachable objects of a compatible type, or null. With more than +/// \ref max_reachable_pointer_candidates such objects, the pointer may point +/// to any (unknown) object instead. This is a nondeterministic choice, and +/// only meaningful to pointer analyses. +exprt reachable_pointer_value( + const exprt &pointer, + const reachable_objectst &reachable); + /// \return True iff a pointer of type \p candidate may be stored in a pointer /// of type \p location without changing what kind of object it points to: /// the pointed-to types are the same, or one of them is `void` or a byte. diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index 4efac71df477..f526ad310f85 100644 --- a/src/pointer-analysis/value_set.cpp +++ b/src/pointer-analysis/value_set.cpp @@ -28,11 +28,14 @@ Author: Daniel Kroening, kroening@kroening.com #include #include +#include + #ifdef DEBUG # include #endif #include "add_failed_symbols.h" +#include "reachable_objects.h" // Due to a large number of functions defined inline, `value_sett` and // associated types are documented in its header file, `value_set.h`. @@ -1841,6 +1844,46 @@ void value_sett::do_end_function( assign(lhs, rhs, ns, false, false); } +void value_sett::havoc_reachable(const codet &code, const namespacet &ns) +{ + std::vector roots; + if(code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + roots.push_back(object); + + // The address-taken local variables of the functions on the call stack: + // without a call stack, all variables whose address is stored anywhere. + std::set stored; + values.iterate( + [this, &stored](const irep_idt &, const entryt &entry) + { + for(const auto &target : entry.object_map.read()) + { + const exprt object = to_expr(target); + if(object.id() != ID_object_descriptor) + continue; + const exprt &root = to_object_descriptor_expr(object).root_object(); + if(root.id() == ID_symbol && root.type().id() != ID_code) + stored.insert(root); + } + }); + roots.insert(roots.end(), stored.begin(), stored.end()); + } + + const reachable_objectst reachable = find_reachable_objects( + code.operands(), + roots, + [this, &ns](const exprt &pointer) { return get_value_set(pointer, ns); }, + ns); + + for(const auto &pointer : reachable.pointers) + { + assign( + pointer, reachable_pointer_value(pointer, reachable), ns, false, false); + } +} + void value_sett::apply_code_rec( const codet &code, const namespacet &ns) @@ -1951,8 +1994,12 @@ void value_sett::apply_code_rec( { // Ignore by default; could prune the value set. } - else if(statement == ID_havoc_object || statement == ID_havoc_reachable) + else if(statement == ID_havoc_object) + { + } + else if(statement == ID_havoc_reachable) { + havoc_reachable(code, ns); } else { diff --git a/src/pointer-analysis/value_set.h b/src/pointer-analysis/value_set.h index 73119a8ffb67..1160cadf6170 100644 --- a/src/pointer-analysis/value_set.h +++ b/src/pointer-analysis/value_set.h @@ -491,6 +491,15 @@ class value_sett const codet &code, const namespacet &ns); + /// Applies the `havoc_reachable` statement \p code: the pointers stored in + /// the objects reachable from its operands (and, with the + /// `arbitrary_memory` flag, from the objects of static lifetime and the + /// objects whose address is stored anywhere) may in addition point to any + /// of the reachable objects of a compatible type, or be null. + /// \param code: The `havoc_reachable` statement + /// \param ns: Namespace + void havoc_reachable(const codet &code, const namespacet &ns); + private: /// Subclass customisation point to filter or otherwise alter the value-set /// returned from get_value_set before it is passed into assign. For example, diff --git a/src/pointer-analysis/value_set_fi.cpp b/src/pointer-analysis/value_set_fi.cpp index f3336fd8fa78..16acd4274233 100644 --- a/src/pointer-analysis/value_set_fi.cpp +++ b/src/pointer-analysis/value_set_fi.cpp @@ -24,7 +24,10 @@ Author: Daniel Kroening, kroening@kroening.com #include +#include "reachable_objects.h" + #include +#include const value_set_fit::object_map_dt value_set_fit::object_map_dt::blank{}; @@ -1380,6 +1383,41 @@ void value_set_fit::do_end_function( assign(lhs, rhs, ns); } +void value_set_fit::havoc_reachable(const codet &code, const namespacet &ns) +{ + std::vector roots; + if(code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + roots.push_back(object); + + // all variables whose address is stored anywhere + std::set stored; + for(const auto &entry : values) + { + for(const auto &target : entry.second.object_map.read()) + { + const exprt object = to_expr(target); + if(object.id() != ID_object_descriptor) + continue; + const exprt &root = to_object_descriptor_expr(object).root_object(); + if(root.id() == ID_symbol && root.type().id() != ID_code) + stored.insert(root); + } + } + roots.insert(roots.end(), stored.begin(), stored.end()); + } + + const reachable_objectst reachable = find_reachable_objects( + code.operands(), + roots, + [this, &ns](const exprt &pointer) { return get_value_set(pointer, ns); }, + ns); + + for(const auto &pointer : reachable.pointers) + assign(pointer, reachable_pointer_value(pointer, reachable), ns); +} + void value_set_fit::apply_code(const codet &code, const namespacet &ns) { const irep_idt &statement=code.get(ID_statement); @@ -1458,8 +1496,12 @@ void value_set_fit::apply_code(const codet &code, const namespacet &ns) { // doesn't do anything } - else if(statement == ID_havoc_object || statement == ID_havoc_reachable) + else if(statement == ID_havoc_object) + { + } + else if(statement == ID_havoc_reachable) { + havoc_reachable(code, ns); } else throw diff --git a/src/pointer-analysis/value_set_fi.h b/src/pointer-analysis/value_set_fi.h index d07e01ead438..b2a909bad7a1 100644 --- a/src/pointer-analysis/value_set_fi.h +++ b/src/pointer-analysis/value_set_fi.h @@ -265,6 +265,12 @@ class value_set_fit void apply_code(const codet &code, const namespacet &ns); + /// Applies the `havoc_reachable` statement \p code, as + /// value_sett::havoc_reachable does. + /// \param code: The `havoc_reachable` statement + /// \param ns: Namespace + void havoc_reachable(const codet &code, const namespacet &ns); + void assign( const exprt &lhs, const exprt &rhs, From e0063192d5d6c2266f73742ed812cc8616417c21 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:35:36 +0000 Subject: [PATCH 030/100] Symex: havoc_reachable must not truncate the candidate pointers Each pointer stored in an object that havoc_reachable changes was assigned a nondeterministic choice among at most 64 candidate values (its previous value, the previous values of the other pointers of a compatible type, the addresses of the reachable objects of a compatible type), and null. With more candidates, the others were dropped, although the statement may store any of them. For a program with 70 int variables of static lifetime and `int *p = &g00`, `asm volatile("cli" ::: "memory")` followed by `assert(p != &g69)` gave VERIFICATION SUCCESSFUL (the native program can fail the assertion if the assembly stores &g69 in p). Assign pointers with more than 64 candidates an arbitrary value instead, as #8937 did. A nondeterministic pointer would have a value set of all objects in the value set, which value_sett computes for each assignment by visiting the value sets of all pointers, including those assigned an arbitrary value before: the time grows quadratically with the number of such pointers. For 900 objects of static lifetime (300 int, 300 int*, 300 structs with an int* member) and two statements, symex took 17 s instead of 1.6 s. Instead, the pointers are assigned temporaries that are never assigned (and hence unconstrained), whose value set is computed once per statement and shared. To make sharing effective, value_sett::make_union now shares the map it adds to an empty one, and the computation of the reachable objects visits each shared map once. Symex now takes 0.9 s on this program. With 6000 such objects of static lifetime, cbmc now takes 4 s and 290 MB instead of 29 s and 2.3 GB (and reports s1.q != &g2, which the truncation proved, as failing). Dereferencing a pointer with an arbitrary value considers all objects: with an additional dereference of one of the pointers after the statements, the program takes 40 s, mostly in simplify_inequality_pointer_object. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 13 ++- .../main.c | 92 +++++++++++++++++++ .../test.desc | 18 ++++ src/goto-symex/goto_symex.h | 3 +- src/goto-symex/symex_havoc_reachable.cpp | 91 +++++++++++++----- src/pointer-analysis/value_set.cpp | 7 ++ 6 files changed, 197 insertions(+), 27 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_candidates/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a0440d002a05..44a6a244261a 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -157,11 +157,14 @@ member access such as `s.a` names the variable `s`. statement can reach only through pointers that CBMC does not track (for example, addresses computed from integers, or pointers stored in local variables of a caller whose address is not taken) keep their values. -- A pointer stored in a changed object takes one of at most 64 of the - candidate values described above (its own previous value first); a warning - is printed if there are more candidates. Pointers in unions and in arrays - of more than 64 elements, or of a size that is not constant, are assigned - arbitrary values. +- A pointer stored in a changed object is restricted to the candidate values + described above only if there are at most 64 of them (counting its own + previous value). Otherwise, it is assigned an arbitrary value, and a + warning is printed. Such a pointer may point to any object whose address is + stored anywhere, or be invalid: dereferencing it considers all these + objects, which is slow if there are many, and the pointer checks of the + dereference fail. Pointers in unions and in arrays of more than 64 + elements, or of a size that is not constant, are assigned arbitrary values. - Constant objects are not changed. - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value diff --git a/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c b/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c new file mode 100644 index 000000000000..5fc0e4c864cd --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c @@ -0,0 +1,92 @@ +// A pointer stored in an object that unmodeled inline assembly may change +// has more candidate values (here: 70 objects of type int, and its own +// previous value) than symbolic execution restricts pointers to. It must +// then be assigned an arbitrary value, not one of the first candidates only. + +int g00; +int g01; +int g02; +int g03; +int g04; +int g05; +int g06; +int g07; +int g08; +int g09; +int g10; +int g11; +int g12; +int g13; +int g14; +int g15; +int g16; +int g17; +int g18; +int g19; +int g20; +int g21; +int g22; +int g23; +int g24; +int g25; +int g26; +int g27; +int g28; +int g29; +int g30; +int g31; +int g32; +int g33; +int g34; +int g35; +int g36; +int g37; +int g38; +int g39; +int g40; +int g41; +int g42; +int g43; +int g44; +int g45; +int g46; +int g47; +int g48; +int g49; +int g50; +int g51; +int g52; +int g53; +int g54; +int g55; +int g56; +int g57; +int g58; +int g59; +int g60; +int g61; +int g62; +int g63; +int g64; +int g65; +int g66; +int g67; +int g68; +int g69; +int *p = &g00; + +// a pointer with few candidates remains restricted to them +struct S +{ + int x; +} s1, s2; +struct S *sp = &s1; + +int main(void) +{ + asm volatile("cli" ::: "memory"); + __CPROVER_assert(p != &g69, "many candidates"); + __CPROVER_assert(p == &g00, "previous value"); + __CPROVER_assert(sp == &s1 || sp == &s2 || sp == 0, "few candidates"); + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc new file mode 100644 index 000000000000..c844c673bf6c --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^havocking the objects reachable at file main\.c line 87 function main: some pointers have more than 64 possible values, and are assigned arbitrary values$ +^\[main\.assertion\.1\] line 88 many candidates: FAILURE$ +^\[main\.assertion\.2\] line 89 previous value: FAILURE$ +^\[main\.assertion\.3\] line 90 few candidates: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +Symbolic execution restricts each pointer stored in an object that the +havoc_reachable statement changes to its candidate values (previous values, +addresses of reachable objects, null) only if there are at most 64 of them. +Restricting p to the first 64 candidates would exclude &g69, which the +assembly may store in p. diff --git a/src/goto-symex/goto_symex.h b/src/goto-symex/goto_symex.h index 0cd7fce9c2a6..d5ed20bb0a09 100644 --- a/src/goto-symex/goto_symex.h +++ b/src/goto-symex/goto_symex.h @@ -754,7 +754,8 @@ class goto_symext /// functions on the call stack), and to all objects reachable from these /// according to the value set. Pointers stored in these objects are /// restricted to pointers previously stored in them, the addresses of the - /// objects, or null. + /// objects, or null, unless there are too many of these candidates: such + /// pointers are assigned arbitrary values. /// \param state: Symbolic execution state /// \param code: The `havoc_reachable` statement void symex_havoc_reachable(statet &state, const codet &code); diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 1e90506ba52d..7feac8de6855 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -21,6 +21,7 @@ Author: Michael Tautschnig #include "path_storage.h" #include +#include #include #include @@ -269,6 +270,10 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) entries[entry_object_identifier(item.second.identifier)].push_back( &item.second); + // the maps of targets visited so far, which pointers assigned an + // arbitrary value share + std::set> visited; + for(std::size_t i = 0; i < objects.size(); ++i) { const auto it = entries.find(object_identifier(objects[i])); @@ -284,6 +289,8 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) id2string(entry->identifier).substr(object_id.size()) + entry->suffix, ns); const bool is_pointer = type == nullptr || type->id() == ID_pointer; + if(!visited.insert({&entry->object_map.read(), is_pointer}).second) + continue; for(const auto &target : entry->object_map.read()) { const exprt target_expr = state.value_set.to_expr(target); @@ -310,25 +317,30 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) for(const auto &object : havocked) split_lvalue(object, ns, pointers, others); + // Fresh temporaries. get_fresh_aux_symbol would search the symbol table for + // each of the (possibly many) temporaries. + auto new_temporary = [this, &state, &source_location]( + const std::string &prefix, const typet &type) + { + const std::string base_name = + prefix + "$" + std::to_string(path_storage.havoc_reachable_temporaries++); + auxiliary_symbolt symbol{ + "symex::havoc_reachable::" + base_name, type, language_mode}; + symbol.base_name = base_name; + symbol.location = source_location; + const symbol_exprt symbol_expr = symbol.symbol_expr(); + const bool inserted = state.symbol_table.insert(std::move(symbol)).second; + CHECK_RETURN(inserted); + return symbol_expr; + }; + // record the pointers stored in the objects before changing them std::vector candidates; for(const auto &pointer : pointers) { - // get_fresh_aux_symbol would search the symbol table for each of the - // (possibly many) temporaries - const std::string base_name = - "old_pointer$" + - std::to_string(path_storage.havoc_reachable_temporaries++); - auxiliary_symbolt old_value{ - "symex::havoc_reachable::" + base_name, pointer.type(), language_mode}; - old_value.base_name = base_name; - old_value.location = source_location; - const symbol_exprt old_value_expr = old_value.symbol_expr(); - const bool inserted = - state.symbol_table.insert(std::move(old_value)).second; - CHECK_RETURN(inserted); - symex_assign(state, old_value_expr, pointer); - candidates.push_back(old_value_expr); + const symbol_exprt old_value = new_temporary("old_pointer", pointer.type()); + symex_assign(state, old_value, pointer); + candidates.push_back(old_value); } for(const auto &object : objects) { @@ -348,12 +360,42 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) state, other, side_effect_expr_nondett{other.type(), source_location}); } + // An arbitrary pointer: a temporary that is never assigned, and hence + // unconstrained, whose value set is that of a nondeterministic pointer (any + // object in the value set, or null). Assigning a nondeterministic pointer + // instead would compute this value set anew for each pointer, visiting the + // value sets of all pointers assigned before: the time would grow + // quadratically with the number of such pointers. Instead, the value set is + // computed once per statement, and shared. + std::optional any_pointer; + auto arbitrary_pointer = [&](const typet &type) + { + if(!any_pointer.has_value()) + { + const typet void_pointer = pointer_type(empty_typet{}); + any_pointer = + state.rename(new_temporary("any_pointer", void_pointer), ns).get(); + state.value_set.assign( + *any_pointer, + nondet_symbol_exprt{"symex::havoc_reachable::any", void_pointer}, + ns, + true, + false); + } + const symbol_exprt result = new_temporary("arbitrary_pointer", type); + state.value_set.assign( + state.rename(result, ns).get(), *any_pointer, ns, true, false); + return result; + }; + // The statement may store any pointer it can obtain: the pointers stored // in the reachable objects, or the addresses of these objects. Restricting // the pointers to these values (or null) keeps the value sets, and hence - // dereferencing, precise. To bound the size of the value sets, each pointer - // is restricted to at most max_pointer_candidates of them, starting with - // its own previous value. + // dereferencing, precise. To bound the size of the formula and of the value + // sets, this is done only for pointers with at most max_pointer_candidates + // candidate values (including their own previous value). Restricting a + // pointer to some of its candidates would exclude values the statement may + // store, so the other pointers are assigned arbitrary values. bool too_many_candidates = false; for(std::size_t i = 0; i < pointers.size(); ++i) { @@ -368,12 +410,19 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) continue; if(chosen.size() == max_pointer_candidates) { - too_many_candidates = true; + chosen.clear(); break; } chosen.push_back(&candidate); } + if(chosen.empty()) + { + too_many_candidates = true; + symex_assign(state, pointer, arbitrary_pointer(type)); + continue; + } + exprt value = null_pointer_exprt{to_pointer_type(type)}; for(auto it = chosen.rbegin(); it != chosen.rend(); ++it) { @@ -400,7 +449,7 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) { log.warning() << "havocking the objects reachable at " << source_location << ": some pointers have more than " << max_pointer_candidates - << " possible values, and are restricted to " - << max_pointer_candidates << " of them" << messaget::eom; + << " possible values, and are assigned arbitrary values" + << messaget::eom; } } diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index f526ad310f85..ef0a2fe94ce3 100644 --- a/src/pointer-analysis/value_set.cpp +++ b/src/pointer-analysis/value_set.cpp @@ -322,6 +322,13 @@ bool value_sett::make_union_would_change( bool value_sett::make_union(object_mapt &dest, const object_mapt &src) const { + // share the (possibly large) map instead of copying it element by element + if(dest.read().empty()) + { + dest = src; + return !src.read().empty(); + } + bool result=false; for(object_map_dt::const_iterator it=src.read().begin(); From 9ccc36f4984bfa235b2cbf7d34d02b7804e78db7 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:55:12 +0000 Subject: [PATCH 031/100] havoc_reachable: pointers may move within the objects they can reach Each pointer stored in an object that havoc_reachable changes was assigned a choice among its previous value, the previous values of the other pointers of a compatible type, the start addresses of the reachable objects of a compatible type, and null. Pointer arithmetic and interior pointers were thus excluded: for `int a[4]; int *gp = &a[0];`, `asm volatile("addq $4, gp(%%rip)" ::: "memory"); assert(gp != &a[1]);` gave VERIFICATION SUCCESSFUL, as did `assert(ip != &s.y)` after an assembly statement that stores &s.y in `int *ip = &s.x`. Both assertions fail natively. Symbolic execution now also lets the pointer point to any position, given by a nondeterministic offset, within the objects that these candidates point into, provided that an object of the pointer's target type fits at that position (an assumption on the result, guarded by the choice). Offsets make dereferencing costly (byte_extract at a symbolic offset), so they are only added to candidates that may point into an object larger than the pointer's target type, or of unknown size. Pointers to objects of exactly their target type, such as list nodes, are unchanged. The value-set analyses now give the corresponding targets an unknown offset. Variants evaluated (cbmc, default checks and --no-standard-checks): - Unconstrained offsets: the regression test inline_asm_havoc_reachable gets spurious failures for the pointer checks of `head->data`, and a list of 8 heap nodes that the C code traverses after the assembly gets 12 spurious pointer-check failures out of 29 properties. - Offsets constrained to positions where the target type fits (with or without requiring a multiple of its size), for all candidates: no spurious failures, but the list traversal took 1.95 s instead of 0.20 s for 8 nodes, and 10.9 s instead of 1.0 s for 16 nodes. - As committed (constrained, only for larger objects): the list traversal takes the same time as without offsets (0.20 s, 1.03 s). Four pointers into a static array of N ints dereferenced after the statement take 1.7 s instead of 0.8 s for N = 256 and 7.0 s instead of 3.7 s for N = 1024. Dereferencing p0[1] in addition takes 13.9 s instead of 0.9 s for N = 256, and fails the bounds check, as the statement may have moved p0 to the last element. The remaining assumption, now documented in the manual: the statement does not store pointers one past the end of an object or to positions at which an object of the target type does not fit, pointers to unreachable objects, pointers into objects of another type that no pointer of a compatible type pointed into, or pointers computed from integers. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 34 ++-- .../inline_asm_havoc_reachable_offsets/main.c | 36 ++++ .../test.desc | 20 +++ .../main.c | 15 ++ .../test.desc | 15 ++ src/goto-symex/goto_symex.h | 7 +- src/goto-symex/symex_havoc_reachable.cpp | 167 +++++++++++++++++- src/pointer-analysis/reachable_objects.cpp | 64 ++++++- src/pointer-analysis/reachable_objects.h | 17 +- src/pointer-analysis/value_set.cpp | 15 +- src/pointer-analysis/value_set_fi.cpp | 16 +- 11 files changed, 365 insertions(+), 41 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_offsets/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable-offset/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 44a6a244261a..5c94b58b531a 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -139,10 +139,12 @@ pointers stored in the objects (following pointers transitively), so this includes, for example, all nodes of a linked list whose head is stored in a variable of static lifetime. The pointers stored in the objects that are changed are not made arbitrary: each of them is assigned a nondeterministic -choice among the pointers previously stored in these objects, the addresses -of the reachable objects (of a compatible type), and null. The statement can -thus relink a list, and dereferencing the pointers afterwards remains -precise. +choice among its previous value, null, and a pointer to any position within +the objects that the following candidates point to, at which an object of the +pointer's target type fits: the pointers previously stored in the changed +objects, and the reachable objects (of a compatible type). The statement can +thus relink a list or advance a pointer within an array, and dereferencing +the pointers afterwards remains precise. MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the @@ -158,13 +160,23 @@ member access such as `s.a` names the variable `s`. example, addresses computed from integers, or pointers stored in local variables of a caller whose address is not taken) keep their values. - A pointer stored in a changed object is restricted to the candidate values - described above only if there are at most 64 of them (counting its own - previous value). Otherwise, it is assigned an arbitrary value, and a - warning is printed. Such a pointer may point to any object whose address is - stored anywhere, or be invalid: dereferencing it considers all these - objects, which is slow if there are many, and the pointer checks of the - dereference fail. Pointers in unions and in arrays of more than 64 - elements, or of a size that is not constant, are assigned arbitrary values. + described above. The approximation thus assumes that the statement does + not store other pointers in it: no pointer one past the end of an object or + to a position at which an object of the pointer's target type does not fit + entirely, no pointer to an object that is not reachable, no pointer into an + object of a different type unless a pointer of a compatible type previously + pointed into it, and no pointer computed from an integer. Dereferencing a + pointer that may point to other positions than the start of an object, such + as `p[1]` for a pointer `p` into an array, may fail the pointer checks after + the statement, as the statement may have moved `p` to the last element. +- The candidate values are only used if there are at most 64 of them + (counting the pointer's own previous value). Otherwise, the pointer is + assigned an arbitrary value, and a warning is printed. Such a pointer may + point to any object whose address is stored anywhere, or be invalid: + dereferencing it considers all these objects, which is slow if there are + many, and the pointer checks of the dereference fail. Pointers in unions and + in arrays of more than 64 elements, or of a size that is not constant, are + assigned arbitrary values. - Constant objects are not changed. - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value diff --git a/regression/cbmc/inline_asm_havoc_reachable_offsets/main.c b/regression/cbmc/inline_asm_havoc_reachable_offsets/main.c new file mode 100644 index 000000000000..a9e67b158556 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_offsets/main.c @@ -0,0 +1,36 @@ +// Inline assembly that is not modeled may store in the pointers it can reach +// a pointer to any position within the objects it can reach (pointer +// arithmetic, interior pointers), as long as an object of the pointer's +// target type fits at that position. +int a[4]; +int *gp = &a[0]; + +struct S +{ + int x; + int y; +} s; +int *ip = &s.x; + +struct node +{ + int data; + struct node *next; +} n1, n2; +struct node *head = &n1; + +int main(void) +{ + n1.next = &n2; + asm volatile("cli" ::: "memory"); + __CPROVER_assert(gp != &a[1], "pointer arithmetic"); // fails + __CPROVER_assert(ip != &s.y, "interior pointer"); // fails + __CPROVER_assert(gp != &a[3] + 1, "one past the end"); // holds (assumed) + if(gp != 0) + *gp = 1; // no dereference failure + __CPROVER_assert( + head == 0 || head == &n1 || head == &n2, "start of a node"); // holds + if(head != 0) + head->data = 1; // no dereference failure + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc new file mode 100644 index 000000000000..10b1ea0f2f9f --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 26 pointer arithmetic: FAILURE$ +^\[main\.assertion\.2\] line 27 interior pointer: FAILURE$ +^\[main\.assertion\.3\] line 28 one past the end: SUCCESS$ +^\[main\.assertion\.4\] line 31 start of a node: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dereference failure.*: FAILURE$ +-- +Each pointer stored in an object that the havoc_reachable statement changes +may, after the statement, point to any position within the objects its +candidate values point into, provided that an object of the pointer's target +type fits there. The statement is assumed not to store other pointers, such as +pointers one past the end of an object. Pointers to objects of exactly the +pointer's target type, such as head, keep pointing to the start of objects. diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c new file mode 100644 index 000000000000..cf21e57ba6e7 --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c @@ -0,0 +1,15 @@ +int a[2]; +int *pa = a; +int x; +int *px = &x; + +int main() +{ +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + int *r = pa; + return 0; +} diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-offset/test.desc b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/test.desc new file mode 100644 index 000000000000..5a1a8afedee1 --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/test.desc @@ -0,0 +1,15 @@ +CORE +main.c +--show-value-sets +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +\npa = \{[^}]* +\npx = \{[^}]* +-- +^warning: ignoring +\npx = \{[^}]* +-- +The inline assembly may store in pa and px a pointer to any position within a +(an array larger than the pointers' target type), so the offset becomes +unknown. Only one int fits in x, so pointers to x keep offset 0. diff --git a/src/goto-symex/goto_symex.h b/src/goto-symex/goto_symex.h index d5ed20bb0a09..d09cfa1be082 100644 --- a/src/goto-symex/goto_symex.h +++ b/src/goto-symex/goto_symex.h @@ -753,9 +753,10 @@ class goto_symext /// objects of static lifetime and the address-taken local variables of all /// functions on the call stack), and to all objects reachable from these /// according to the value set. Pointers stored in these objects are - /// restricted to pointers previously stored in them, the addresses of the - /// objects, or null, unless there are too many of these candidates: such - /// pointers are assigned arbitrary values. + /// restricted to their previous values, null, and pointers to positions + /// within the objects that the pointers previously stored in them and the + /// addresses of the objects point to, unless there are too many of these + /// candidates: such pointers are assigned arbitrary values. /// \param state: Symbolic execution state /// \param code: The `havoc_reachable` statement void symex_havoc_reachable(statet &state, const codet &code); diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 7feac8de6855..6ff35d0f1f34 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -13,6 +13,8 @@ Author: Michael Tautschnig #include #include #include +#include +#include #include #include @@ -182,6 +184,63 @@ type_of_path(const typet &type, const std::string &path, const namespacet &ns) return current; } +/// \return The size of the objects that pointers of type \p type point to: +/// 1 for `void *` and for pointers to objects of unknown size. +static mp_integer pointee_size(const typet &type, const namespacet &ns) +{ + const typet &base_type = to_pointer_type(type).base_type(); + if(base_type.id() == ID_empty) + return 1; + const auto size = pointer_offset_size(base_type, ns); + return size.has_value() && *size > bytest{0} ? size->get() : mp_integer{1}; +} + +/// \return The size of the largest object that a pointer with value set +/// \p targets may point into (ignoring null), or an empty optional if that +/// is not known. +static std::optional +largest_target(const std::vector &targets, const namespacet &ns) +{ + mp_integer result = 0; + for(const auto &target : targets) + { + if(target.id() != ID_object_descriptor) + return {}; + const exprt &root = to_object_descriptor_expr(target).root_object(); + if(root.id() == ID_null_object) + continue; + if(root.id() == ID_integer_address) + return {}; + const auto size = pointer_offset_size(root.type(), ns); + if(!size.has_value()) + return {}; + result = std::max(result, size->get()); + } + return result; +} + +/// \return A condition under which \p pointer, obtained by adding \p offset +/// bytes to a pointer, points into an object (not null) such that an object +/// of \p element_size bytes fits at that position. +static exprt +fits(const exprt &pointer, const exprt &offset, const mp_integer &element_size) +{ + const typet &type = offset.type(); + const exprt position = pointer_offset_exprt{pointer, type}; + const exprt size = + typecast_exprt{object_size_exprt{pointer, size_type()}, type}; + return and_exprt{ + {not_exprt{equal_exprt{ + pointer_object(pointer), + pointer_object(null_pointer_exprt{to_pointer_type(pointer.type())})}}, + // the offset is small enough not to wrap around + binary_relation_exprt{offset, ID_le, size}, + binary_relation_exprt{offset, ID_ge, unary_minus_exprt{size}}, + binary_relation_exprt{position, ID_ge, from_integer(0, type)}, + binary_relation_exprt{ + plus_exprt{position, from_integer(element_size, type)}, ID_le, size}}}; +} + void goto_symext::symex_havoc_reachable(statet &state, const codet &code) { const source_locationt &source_location = state.source.pc->source_location(); @@ -360,6 +419,53 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) state, other, side_effect_expr_nondett{other.type(), source_location}); } + // The size of the largest object each candidate may point into, computed + // on demand: the value sets of the previous values may be large. + std::vector>> extents( + candidates.size()); + auto extent = [&](const exprt *candidate) -> const std::optional & + { + const std::size_t i = candidate - candidates.data(); + if(!extents[i].has_value()) + { + if(i < pointers.size()) + { + extents[i] = largest_target( + state.value_set.get_value_set( + state.rename(candidates[i], ns).get(), ns), + ns); + } + else + { + const auto size = + pointer_offset_size(objects[i - pointers.size()].type(), ns); + extents[i] = size.has_value() ? std::optional{size->get()} + : std::nullopt; + } + } + return *extents[i]; + }; + + // a choice among the candidates in movable, plus offset bytes + auto move_pointer = [this, &source_location]( + const std::vector &movable, + const exprt &offset, + const typet &type) + { + const typet char_pointer = pointer_type(char_type()); + exprt base = + typecast_exprt::conditional_cast(*movable.back(), char_pointer); + for(auto it = std::next(movable.rbegin()); it != movable.rend(); ++it) + { + base = if_exprt{ + path_storage.build_symex_nondet(bool_typet{}, source_location), + typecast_exprt::conditional_cast(**it, char_pointer), + std::move(base)}; + } + return typecast_exprt::conditional_cast( + plus_exprt{std::move(base), offset}, type); + }; + // An arbitrary pointer: a temporary that is never assigned, and hence // unconstrained, whose value set is that of a nondeterministic pointer (any // object in the value set, or null). Assigning a nondeterministic pointer @@ -389,13 +495,19 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) }; // The statement may store any pointer it can obtain: the pointers stored - // in the reachable objects, or the addresses of these objects. Restricting - // the pointers to these values (or null) keeps the value sets, and hence - // dereferencing, precise. To bound the size of the formula and of the value - // sets, this is done only for pointers with at most max_pointer_candidates - // candidate values (including their own previous value). Restricting a - // pointer to some of its candidates would exclude values the statement may - // store, so the other pointers are assigned arbitrary values. + // in the reachable objects, or the addresses of these objects, possibly + // with an offset. Restricting the pointers to these values (or null) keeps + // the value sets, and hence dereferencing, precise. The offset is + // nondeterministic, but must leave room for an object of the pointer's + // target type: the statement is assumed not to store pointers to positions + // at which no such object fits, such as one past the end of an object. As + // offsets make dereferencing costly, they are only added to candidates + // that may point into objects that are larger than the target type. + // To bound the size of the formula and of the value sets, this is done only + // for pointers with at most max_pointer_candidates candidate values + // (including their own previous value). Restricting a pointer to some of + // its candidates would exclude values the statement may store, so the + // other pointers are assigned arbitrary values. bool too_many_candidates = false; for(std::size_t i = 0; i < pointers.size(); ++i) { @@ -423,14 +535,53 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) continue; } + // The candidates that may point into an object in which more than one + // object of the pointer's target type fits: the statement may store a + // pointer to any position in that object (pointer arithmetic, interior + // pointers). + const mp_integer element_size = pointee_size(type, ns); + std::vector fixed, movable; + for(const exprt *candidate : chosen) + { + const auto &candidate_extent = extent(candidate); + if(!candidate_extent.has_value() || *candidate_extent > element_size) + movable.push_back(candidate); + else if(candidate != &candidates[i]) + fixed.push_back(candidate); + } + + // a choice among: the previous value, the fixed candidates, a position + // within the objects the movable candidates point into, and null exprt value = null_pointer_exprt{to_pointer_type(type)}; - for(auto it = chosen.rbegin(); it != chosen.rend(); ++it) + for(auto it = fixed.rbegin(); it != fixed.rend(); ++it) { value = if_exprt{ path_storage.build_symex_nondet(bool_typet{}, source_location), typecast_exprt::conditional_cast(**it, type), std::move(value)}; } + if(!movable.empty()) + { + // the position must leave room for an object of the target type, + // unless it is the one the candidate points to + const symbol_exprt moved = new_temporary("moved_pointer", type); + const exprt offset = + path_storage.build_symex_nondet(signed_size_type(), source_location); + symex_assign(state, moved, move_pointer(movable, offset, type)); + const exprt choice = + path_storage.build_symex_nondet(bool_typet{}, source_location); + value = if_exprt{choice, moved, std::move(value)}; + symex_assume( + state, + or_exprt{ + not_exprt{choice}, + equal_exprt{offset, from_integer(0, offset.type())}, + fits(moved, offset, element_size)}); + } + value = if_exprt{ + path_storage.build_symex_nondet(bool_typet{}, source_location), + typecast_exprt::conditional_cast(candidates[i], type), + std::move(value)}; symex_assign(state, pointer, value); } diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp index aca1e1893cd6..73b2d1288d0d 100644 --- a/src/pointer-analysis/reachable_objects.cpp +++ b/src/pointer-analysis/reachable_objects.cpp @@ -16,6 +16,7 @@ Author: Michael Tautschnig #include #include #include +#include #include #include @@ -191,13 +192,52 @@ bool is_compatible_pointer(const typet &location, const typet &candidate) is_generic(candidate_base); } +/// \return The size of the objects that pointers of type \p type point to: +/// 1 for `void *` and for pointers to objects of unknown size. +static mp_integer pointee_size(const typet &type, const namespacet &ns) +{ + const typet &base_type = to_pointer_type(type).base_type(); + if(base_type.id() == ID_empty) + return 1; + const auto size = pointer_offset_size(base_type, ns); + return size.has_value() && *size > bytest{0} ? size->get() : mp_integer{1}; +} + +/// \return True iff \p object may contain more than one object of +/// \p element_size bytes, or its size is not known. +static bool is_larger_than( + const exprt &object, + const mp_integer &element_size, + const namespacet &ns) +{ + const auto size = pointer_offset_size(object.type(), ns); + return !size.has_value() || size->get() > element_size; +} + exprt reachable_pointer_value( const exprt &pointer, - const reachable_objectst &reachable) + const reachable_objectst &reachable, + const get_pointer_targetst &get_targets, + const namespacet &ns) { const typet &type = pointer.type(); const nondet_symbol_exprt choice{"value_set::havoc_reachable", bool_typet{}}; + // The statement may also store pointers to other positions within objects + // larger than the pointer's target type (pointer arithmetic, interior + // pointers): these are pointers with an unknown offset. + const mp_integer element_size = pointee_size(type, ns); + const typet char_pointer = pointer_type(char_type()); + auto moved = [&type, &char_pointer](const exprt &candidate) + { + return typecast_exprt::conditional_cast( + plus_exprt{ + typecast_exprt::conditional_cast(candidate, char_pointer), + nondet_symbol_exprt{ + "value_set::havoc_reachable_offset", signed_size_type()}}, + type); + }; + std::vector candidates; for(const auto &object : reachable.objects) { @@ -212,7 +252,10 @@ exprt reachable_pointer_value( // a sound and compact alternative. if(candidates.size() == max_reachable_pointer_candidates) return if_exprt{choice, pointer, exprt{ID_unknown, type}}; - candidates.push_back(typecast_exprt::conditional_cast(address, type)); + if(is_larger_than(object, element_size, ns)) + candidates.push_back(moved(address)); + else + candidates.push_back(typecast_exprt::conditional_cast(address, type)); } } @@ -220,5 +263,22 @@ exprt reachable_pointer_value( for(auto it = candidates.rbegin(); it != candidates.rend(); ++it) value = if_exprt{choice, *it, value}; + // the previous value, possibly moved within the objects it points to + const std::vector targets = get_targets(pointer); + if(std::any_of( + targets.begin(), + targets.end(), + [&element_size, &ns](const exprt &target) + { + if(target.id() != ID_object_descriptor) + return true; + const exprt &root = to_object_descriptor_expr(target).root_object(); + return root.id() != ID_null_object && + is_larger_than(root, element_size, ns); + })) + { + value = if_exprt{choice, moved(pointer), value}; + } + return if_exprt{choice, pointer, value}; } diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h index 3a07d25ede8b..0c72d07c8e40 100644 --- a/src/pointer-analysis/reachable_objects.h +++ b/src/pointer-analysis/reachable_objects.h @@ -74,13 +74,20 @@ const std::size_t max_reachable_pointer_candidates = 64; /// \return An expression whose value set is what the pointer \p pointer, /// stored in one of the objects of \p reachable, may point to after these /// objects have been changed: its previous value, the address of any of the -/// reachable objects of a compatible type, or null. With more than -/// \ref max_reachable_pointer_candidates such objects, the pointer may point -/// to any (unknown) object instead. This is a nondeterministic choice, and -/// only meaningful to pointer analyses. +/// reachable objects of a compatible type, or null, where pointers into +/// objects larger than the pointer's target type may have any offset. With +/// more than \ref max_reachable_pointer_candidates such objects, the +/// pointer may point to any (unknown) object instead. This is a +/// nondeterministic choice, and only meaningful to pointer analyses. +/// \param pointer: A pointer stored in one of the objects of \p reachable +/// \param reachable: The result of \ref find_reachable_objects +/// \param get_targets: The pointer analysis +/// \param ns: Namespace exprt reachable_pointer_value( const exprt &pointer, - const reachable_objectst &reachable); + const reachable_objectst &reachable, + const get_pointer_targetst &get_targets, + const namespacet &ns); /// \return True iff a pointer of type \p candidate may be stored in a pointer /// of type \p location without changing what kind of object it points to: diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index ef0a2fe94ce3..3f88c13a605f 100644 --- a/src/pointer-analysis/value_set.cpp +++ b/src/pointer-analysis/value_set.cpp @@ -1878,16 +1878,19 @@ void value_sett::havoc_reachable(const codet &code, const namespacet &ns) roots.insert(roots.end(), stored.begin(), stored.end()); } - const reachable_objectst reachable = find_reachable_objects( - code.operands(), - roots, - [this, &ns](const exprt &pointer) { return get_value_set(pointer, ns); }, - ns); + const get_pointer_targetst get_targets = [this, &ns](const exprt &pointer) + { return get_value_set(pointer, ns); }; + const reachable_objectst reachable = + find_reachable_objects(code.operands(), roots, get_targets, ns); for(const auto &pointer : reachable.pointers) { assign( - pointer, reachable_pointer_value(pointer, reachable), ns, false, false); + pointer, + reachable_pointer_value(pointer, reachable, get_targets, ns), + ns, + false, + false); } } diff --git a/src/pointer-analysis/value_set_fi.cpp b/src/pointer-analysis/value_set_fi.cpp index 16acd4274233..6667219ecd97 100644 --- a/src/pointer-analysis/value_set_fi.cpp +++ b/src/pointer-analysis/value_set_fi.cpp @@ -1408,14 +1408,18 @@ void value_set_fit::havoc_reachable(const codet &code, const namespacet &ns) roots.insert(roots.end(), stored.begin(), stored.end()); } - const reachable_objectst reachable = find_reachable_objects( - code.operands(), - roots, - [this, &ns](const exprt &pointer) { return get_value_set(pointer, ns); }, - ns); + const get_pointer_targetst get_targets = [this, &ns](const exprt &pointer) + { return get_value_set(pointer, ns); }; + const reachable_objectst reachable = + find_reachable_objects(code.operands(), roots, get_targets, ns); for(const auto &pointer : reachable.pointers) - assign(pointer, reachable_pointer_value(pointer, reachable), ns); + { + assign( + pointer, + reachable_pointer_value(pointer, reachable, get_targets, ns), + ns); + } } void value_set_fit::apply_code(const codet &code, const namespacet &ns) From 6268bbfd4651b6f8eca97445d1b745c5eacbcb91 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 17:00:11 +0000 Subject: [PATCH 032/100] VSD: a havoc in a callee must survive the three-way merge The variable-sensitivity domain implements havoc_reachable (and writes through pointers it does not know) by forgetting all values: havoc() clears the map of the abstract environment. With --three-way-merge, the state after a call is the caller's state with the values of the modified symbols taken from the callee's end state, where abstract_environmentt::modified_symbols only reports symbols that are in the map at the end of the callee. A havoc in the callee was thus lost: for `g = 1; clobber();` with `asm volatile("movl $0, g(%%rip)" ::: "memory")` in clobber, `goto-analyzer --verify --vsd --three-way-merge` reported `assert(g == 1)` as SUCCESS (natively, it fails). The same holds for `*p = 3` in a callee with an unknown p (pre-existing). Reporting the symbols that are in the map at the entry of the callee, but not at its end, would not suffice: a variable that is unknown at the entry of the callee (for example, because it has different values at two call sites, which are merged) is in neither map, but may have a known value in the caller. Instead, the abstract environment now records whether havoc() was applied since the entry of the function (on any path: merging propagates it, the transformer of a call clears it for the callee's entry state). If so, the three-way merge havocs the caller's state before applying the modified symbols, as without --three-way-merge, where the caller continues with the callee's end state. Co-authored-by: Kiro --- .../havoc-reachable-three-way-merge/main.c | 48 +++++++++++++++++++ .../havoc-reachable-three-way-merge/test.desc | 19 ++++++++ .../abstract_environment.cpp | 10 +++- .../abstract_environment.h | 19 ++++++++ .../variable_sensitivity_domain.cpp | 10 +++- 5 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 regression/goto-analyzer/havoc-reachable-three-way-merge/main.c create mode 100644 regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc diff --git a/regression/goto-analyzer/havoc-reachable-three-way-merge/main.c b/regression/goto-analyzer/havoc-reachable-three-way-merge/main.c new file mode 100644 index 000000000000..4a3559602ad2 --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-three-way-merge/main.c @@ -0,0 +1,48 @@ +int g; +int h; +int *p; + +static void clobber(void) +{ +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif +} + +static void write_through_pointer(void) +{ + *p = 3; +} + +static void set_h(void) +{ + h = 2; +} + +int main() +{ + g = 1; + clobber(); + __CPROVER_assert(g == 1, "known at the entry of the callee"); // may change + + g = 2; + clobber(); + __CPROVER_assert(g == 2, "unknown at the entry of the callee"); // may change + + int local = 3; + int *alias = &local; + clobber(); + __CPROVER_assert(local == 3, "address-taken local"); // may change + + g = 4; + write_through_pointer(); + __CPROVER_assert(g == 4, "written through a pointer"); // may change + + g = 5; + set_h(); + __CPROVER_assert(g == 5, "not changed by the callee"); // unchanged + __CPROVER_assert(h == 2, "assigned by the callee"); // unchanged + return 0; +} diff --git a/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc b/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc new file mode 100644 index 000000000000..e82a0b9ff61d --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc @@ -0,0 +1,19 @@ +CORE +main.c +--verify --vsd --three-way-merge +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 28 known at the entry of the callee: UNKNOWN$ +^\[main\.assertion\.2\] line 32 unknown at the entry of the callee: UNKNOWN$ +^\[main\.assertion\.3\] line 37 address-taken local: UNKNOWN$ +^\[main\.assertion\.4\] line 41 written through a pointer: UNKNOWN$ +^\[main\.assertion\.5\] line 45 not changed by the callee: SUCCESS$ +^\[main\.assertion\.6\] line 46 assigned by the callee: SUCCESS$ +-- +^warning: ignoring +-- +The inline assembly in clobber (and the write through a pointer that the +domain does not know) makes the variable-sensitivity domain forget all values. +The three-way merge at the return of the function must propagate this to the +caller, also for variables that are unknown at the entry of the function (the +two calls of clobber are merged at its entry, so g is unknown there). diff --git a/src/analyses/variable-sensitivity/abstract_environment.cpp b/src/analyses/variable-sensitivity/abstract_environment.cpp index 3d7178fbd519..36c605b4e509 100644 --- a/src/analyses/variable-sensitivity/abstract_environment.cpp +++ b/src/analyses/variable-sensitivity/abstract_environment.cpp @@ -366,9 +366,15 @@ bool abstract_environmentt::merge( if(env.bottom) return false; + bool modified = false; + if(env.havocked && !havocked) + { + havocked = true; + modified = true; + } + // For each element in the intersection of map and env.map merge // If the result of the merge is top, remove from the map - bool modified = false; for(const auto &entry : env.map.get_delta_view(map)) { auto merge_result = abstract_objectt::merge( @@ -397,6 +403,7 @@ void abstract_environmentt::havoc(const std::string &havoc_string) } for(auto &top : tops) map.replace(top.first, std::move(top.second)); + havocked = true; } void abstract_environmentt::make_top() @@ -410,6 +417,7 @@ void abstract_environmentt::make_bottom() { map.clear(); bottom = true; + havocked = false; } bool abstract_environmentt::is_bottom() const diff --git a/src/analyses/variable-sensitivity/abstract_environment.h b/src/analyses/variable-sensitivity/abstract_environment.h index f1785e917df4..d0d0e6861c5e 100644 --- a/src/analyses/variable-sensitivity/abstract_environment.h +++ b/src/analyses/variable-sensitivity/abstract_environment.h @@ -201,6 +201,22 @@ class abstract_environmentt /// Set the domain to top (i.e. everything) void make_top(); + /// Gets whether \ref havoc was applied since the last call of + /// \ref clear_havocked (at the entry of a function), on any path. Variables + /// that are not in the map at the entry of the function may then have + /// changed as well. + bool has_been_havocked() const + { + return havocked; + } + + /// Forget about past applications of \ref havoc, see + /// \ref has_been_havocked. + void clear_havocked() + { + havocked = false; + } + /// Set the domain to top (i.e. no possible states / unreachable) void make_bottom(); @@ -250,6 +266,9 @@ class abstract_environmentt protected: bool bottom; + /// See \ref has_been_havocked. + bool havocked = false; + // We may need to break out more of these cases into these virtual abstract_object_pointert eval_expression(const exprt &e, const namespacet &ns) const; diff --git a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp index 74fc25f8c281..5a684ddaec39 100644 --- a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp +++ b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp @@ -363,7 +363,10 @@ void variable_sensitivity_domaint::transform_function_call( } else { - // we have an actual call + // we have an actual call: record whether the callee havocs anything + // (see merge_three_way_function_return) + abstract_state.clear_havocked(); + const symbolt &symbol = ns.lookup(function_id); const code_typet &code_type = to_code_type(symbol.type); const code_typet::parameterst &declaration_parameters = @@ -435,6 +438,11 @@ void variable_sensitivity_domaint::merge_three_way_function_return( const variable_sensitivity_domaint &cast_function_end = static_cast(function_end); + // The function may have changed any variable, including those that are + // not in the map at its entry (and thus not among the modified symbols). + if(cast_function_end.abstract_state.has_been_havocked()) + abstract_state.havoc("havoc in a called function"); + const std::vector &modified_symbol_names = abstract_environmentt::modified_symbols( cast_function_start.abstract_state, cast_function_end.abstract_state); From cd0fa5fb1bfd1786a23f337c8149042b779c921c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 17:04:43 +0000 Subject: [PATCH 033/100] goto-instrument: read/write sets of havoc_reachable rw_set, which the race check (--race-check), the interrupt instrumentation (--isr), and the weak memory instrumentation use, ignored OTHER instructions. Before havoc_reachable, the approximation of inline assembly assigned the objects of static lifetime explicitly, and these assignments were in the read/write sets. Now the writes of unmodeled assembly were invisible: with a thread that runs `asm volatile("cli" ::: "memory")` and a main function that writes g, `goto-instrument --race-check` followed by cbmc reported no data race on g; with an interrupt handler that consists of such a statement, `--isr` did not insert calls of the handler before main reads a variable, and an assertion that the variable keeps its value held. The read/write set of havoc_reachable now reads its operands and the pointers stored in the reachable objects, and writes the reachable objects that are symbols, using the value sets (as goto_rw does). The roots are the operands and, with the arbitrary_memory flag (or if the operands have unknown targets), the objects of static lifetime. The address-taken local variables of the functions on the call stack are not roots: other threads and interrupt handlers can only reach them through pointers, which the closure follows. The race check now also instruments havoc_reachable. The weak memory instrumentation (--mm) still ignores the statement, so its writes become visible to other threads at once; the manual says so. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 8 +++- .../isr-havoc-reachable/main.c | 18 ++++++++ .../isr-havoc-reachable/test.desc | 12 +++++ .../race-check-havoc-reachable/main.c | 18 ++++++++ .../race-check-havoc-reachable/test.desc | 14 ++++++ src/goto-instrument/race_check.cpp | 5 ++- src/goto-instrument/rw_set.cpp | 45 ++++++++++++++++++- src/goto-instrument/rw_set.h | 8 ++++ 8 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 regression/goto-instrument/isr-havoc-reachable/main.c create mode 100644 regression/goto-instrument/isr-havoc-reachable/test.desc create mode 100644 regression/goto-instrument/race-check-havoc-reachable/main.c create mode 100644 regression/goto-instrument/race-check-havoc-reachable/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 5c94b58b531a..74a6c97a46cb 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -187,7 +187,13 @@ member access such as `s.a` names the variable `s`. variables (constant propagation: all objects of static lifetime and all address-taken variables). `--full-slice` does not slice programs that contain approximated inline assembly with pointer operands, a `"memory"` - clobber, or no operands (basic assembly). + clobber, or no operands (basic assembly). The race check + (`goto-instrument --race-check`) and the instrumentation of interrupt + handlers (`--isr`) take the statement to write the reachable variables (all + objects of static lifetime, if it may access arbitrary memory) found by the + value set analysis. The weak memory instrumentation (`--mm`) ignores the + statement: its writes are not delayed, but become visible to other threads + at once. - Control flow out of a statement is not modeled: `asm goto` statements always continue with the next statement. - In C++ code, the C++ front end discards the operands and clobbers of diff --git a/regression/goto-instrument/isr-havoc-reachable/main.c b/regression/goto-instrument/isr-havoc-reachable/main.c new file mode 100644 index 000000000000..3993c225aaf1 --- /dev/null +++ b/regression/goto-instrument/isr-havoc-reachable/main.c @@ -0,0 +1,18 @@ +int flag; + +void isr(void) +{ +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif +} + +int main() +{ + flag = 0; + int v = flag; + __CPROVER_assert(v == 0, "the handler may run before the read"); + return 0; +} diff --git a/regression/goto-instrument/isr-havoc-reachable/test.desc b/regression/goto-instrument/isr-havoc-reachable/test.desc new file mode 100644 index 000000000000..0d767be9683f --- /dev/null +++ b/regression/goto-instrument/isr-havoc-reachable/test.desc @@ -0,0 +1,12 @@ +CORE +main.c +--isr isr +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 16 the handler may run before the read: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The inline assembly in the interrupt handler may write flag (it has a "memory" +clobber), so the handler may run before main reads flag. diff --git a/regression/goto-instrument/race-check-havoc-reachable/main.c b/regression/goto-instrument/race-check-havoc-reachable/main.c new file mode 100644 index 000000000000..5dbe7d2e5c16 --- /dev/null +++ b/regression/goto-instrument/race-check-havoc-reachable/main.c @@ -0,0 +1,18 @@ +int g; + +static void thread(void) +{ +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif +} + +int main() +{ +__CPROVER_ASYNC_1: + thread(); + g = 1; + return 0; +} diff --git a/regression/goto-instrument/race-check-havoc-reachable/test.desc b/regression/goto-instrument/race-check-havoc-reachable/test.desc new file mode 100644 index 000000000000..84aeb70bda7f --- /dev/null +++ b/regression/goto-instrument/race-check-havoc-reachable/test.desc @@ -0,0 +1,14 @@ +CORE +main.c +--race-check +^EXIT=10$ +^SIGNAL=0$ +^\[main\.1\] line 16 W/W data race on g: FAILURE$ +^\[thread\.1\] line 6 W/W data race on g: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The inline assembly in the thread may write g (it has a "memory" clobber), as +may main: the race check must consider the objects that the havoc_reachable +statement changes. diff --git a/src/goto-instrument/race_check.cpp b/src/goto-instrument/race_check.cpp index 6a4c48e493f4..5669348619bf 100644 --- a/src/goto-instrument/race_check.cpp +++ b/src/goto-instrument/race_check.cpp @@ -177,7 +177,10 @@ static void race_check( { goto_programt::instructiont &instruction=*i_it; - if(instruction.is_assign()) + if( + instruction.is_assign() || + (instruction.is_other() && + instruction.get_other().get_statement() == ID_havoc_reachable)) { rw_set_loct rw_set( ns, diff --git a/src/goto-instrument/rw_set.cpp b/src/goto-instrument/rw_set.cpp index 14850b3333c7..1734b885e863 100644 --- a/src/goto-instrument/rw_set.cpp +++ b/src/goto-instrument/rw_set.cpp @@ -16,8 +16,8 @@ Date: February 2006 #include #include - #include +#include void rw_set_baset::output(std::ostream &out) const { @@ -68,6 +68,49 @@ void _rw_set_loct::compute() if(target->call_lhs().is_not_nil()) write(target->call_lhs()); } + else if( + target->is_other() && + target->get_other().get_statement() == ID_havoc_reachable) + { + havoc_reachable(target->get_other()); + } +} + +void _rw_set_loct::havoc_reachable(const codet &code) +{ + for(const auto &op : code.operands()) + read(op); + + std::vector roots; + if(code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + roots.push_back(object); + } + + const reachable_objectst reachable = find_reachable_objects( + code.operands(), + roots, + [this](const exprt &pointer) + { return value_sets.get_values(function_id, target, pointer); }, + ns); + + // pointers with unknown targets may point to any object + if(reachable.has_unknown_targets && !code.get_bool(ID_arbitrary_memory)) + { + for(const auto &object : static_lifetime_objects(ns.get_symbol_table(), ns)) + write(object); + } + + // the statement reads the pointers it follows, and writes the objects it + // reaches (objects other than symbols are not tracked) + for(const auto &pointer : reachable.pointers) + read(pointer); + for(const auto &object : reachable.objects) + { + if(object.id() == ID_symbol) + write(object); + } } void _rw_set_loct::assign(const exprt &lhs, const exprt &rhs) diff --git a/src/goto-instrument/rw_set.h b/src/goto-instrument/rw_set.h index 3eefa66b5541..f616f991af8f 100644 --- a/src/goto-instrument/rw_set.h +++ b/src/goto-instrument/rw_set.h @@ -169,6 +169,14 @@ class _rw_set_loct:public rw_set_baset void assign(const exprt &lhs, const exprt &rhs); + /// Adds the objects that the `havoc_reachable` statement \p code reads and + /// writes, using the value sets: it reads its operands and the pointers + /// stored in the objects reachable from them (and, with the + /// `arbitrary_memory` flag, from the objects of static lifetime), and + /// writes the reachable objects that are symbols. + /// \param code: The `havoc_reachable` statement + void havoc_reachable(const codet &code); + void read_write_rec( const exprt &expr, bool r, From a9a893fd67baf45c9315dab54ddeb09e3caecc16 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 17:11:43 +0000 Subject: [PATCH 034/100] Value sets (FI): havoc_reachable must not take references as objects `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 --- .../main.c | 23 ++++++++++++ .../test.desc | 17 +++++++++ src/pointer-analysis/reachable_objects.cpp | 35 ++++++++++--------- src/pointer-analysis/reachable_objects.h | 7 +++- src/pointer-analysis/value_set.cpp | 2 +- src/pointer-analysis/value_set_fi.cpp | 15 ++++++-- 6 files changed, 79 insertions(+), 20 deletions(-) create mode 100644 regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c create mode 100644 regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/test.desc diff --git a/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c new file mode 100644 index 000000000000..11577860e30c --- /dev/null +++ b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c @@ -0,0 +1,23 @@ +#include + +struct node +{ + struct node *next; + int data; +}; + +struct node *head; + +int main() +{ + struct node *a = malloc(sizeof(struct node)); + a->next = malloc(sizeof(struct node)); + head = a; +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + struct node *second = head->next; + return second != 0; +} diff --git a/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/test.desc b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/test.desc new file mode 100644 index 000000000000..76408ec9ae74 --- /dev/null +++ b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/test.desc @@ -0,0 +1,17 @@ +CORE +main.c +--dependence-graph --show +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +\/\/ ([0-9]+).*\n.*head := main::1::a\n(.*\n)*Data dependencies: ([0-9]+,)*\1(,[0-9]+)*\n\n.*\n.*HAVOC_REACHABLE \(arbitrary memory\) +\/\/ ([0-9]+).*\n.*HAVOC_REACHABLE \(arbitrary memory\)\n(.*\n)*Data dependencies: ([0-9]+,)*\1(,[0-9]+)*\n\n.*\n.*second := \*head\.next +-- +^warning: ignoring +-- +The flow-insensitive value sets that the reaching definitions use contain +references to the value sets of other variables, which the havoc_reachable +statement must not take as objects of their own: following them made +goto-analyzer recurse until the stack overflowed. The statement reads head and +the pointers in the heap objects it reaches, and writes the objects it +reaches. diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp index 73b2d1288d0d..6eeb2aaf8689 100644 --- a/src/pointer-analysis/reachable_objects.cpp +++ b/src/pointer-analysis/reachable_objects.cpp @@ -218,7 +218,8 @@ exprt reachable_pointer_value( const exprt &pointer, const reachable_objectst &reachable, const get_pointer_targetst &get_targets, - const namespacet &ns) + const namespacet &ns, + bool include_previous_value) { const typet &type = pointer.type(); const nondet_symbol_exprt choice{"value_set::havoc_reachable", bool_typet{}}; @@ -251,7 +252,11 @@ exprt reachable_pointer_value( // the pointers may point to each of the objects); an unknown target is // a sound and compact alternative. if(candidates.size() == max_reachable_pointer_candidates) - return if_exprt{choice, pointer, exprt{ID_unknown, type}}; + { + const exprt unknown{ID_unknown, type}; + return include_previous_value ? if_exprt{choice, pointer, unknown} + : unknown; + } if(is_larger_than(object, element_size, ns)) candidates.push_back(moved(address)); else @@ -264,21 +269,19 @@ exprt reachable_pointer_value( value = if_exprt{choice, *it, value}; // the previous value, possibly moved within the objects it points to - const std::vector targets = get_targets(pointer); - if(std::any_of( - targets.begin(), - targets.end(), - [&element_size, &ns](const exprt &target) - { - if(target.id() != ID_object_descriptor) - return true; - const exprt &root = to_object_descriptor_expr(target).root_object(); - return root.id() != ID_null_object && - is_larger_than(root, element_size, ns); - })) + std::set moved_targets; + for(const auto &target : get_targets(pointer)) { - value = if_exprt{choice, moved(pointer), value}; + if(target.id() != ID_object_descriptor) + continue; + const exprt &root = to_object_descriptor_expr(target).root_object(); + if( + root.id() != ID_null_object && is_larger_than(root, element_size, ns) && + moved_targets.insert(root).second) + { + value = if_exprt{choice, moved(address_of_exprt{root}), value}; + } } - return if_exprt{choice, pointer, value}; + return include_previous_value ? if_exprt{choice, pointer, value} : value; } diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h index 0c72d07c8e40..a3c137f1cb22 100644 --- a/src/pointer-analysis/reachable_objects.h +++ b/src/pointer-analysis/reachable_objects.h @@ -83,11 +83,16 @@ const std::size_t max_reachable_pointer_candidates = 64; /// \param reachable: The result of \ref find_reachable_objects /// \param get_targets: The pointer analysis /// \param ns: Namespace +/// \param include_previous_value: Whether the result includes \p pointer +/// itself. A flow-insensitive analysis, whose assignments add to the +/// previous values, does not need it; in such an analysis, a value set +/// that refers to itself may make the analysis recurse indefinitely. exprt reachable_pointer_value( const exprt &pointer, const reachable_objectst &reachable, const get_pointer_targetst &get_targets, - const namespacet &ns); + const namespacet &ns, + bool include_previous_value); /// \return True iff a pointer of type \p candidate may be stored in a pointer /// of type \p location without changing what kind of object it points to: diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index 3f88c13a605f..891e790d1634 100644 --- a/src/pointer-analysis/value_set.cpp +++ b/src/pointer-analysis/value_set.cpp @@ -1887,7 +1887,7 @@ void value_sett::havoc_reachable(const codet &code, const namespacet &ns) { assign( pointer, - reachable_pointer_value(pointer, reachable, get_targets, ns), + reachable_pointer_value(pointer, reachable, get_targets, ns, true), ns, false, false); diff --git a/src/pointer-analysis/value_set_fi.cpp b/src/pointer-analysis/value_set_fi.cpp index 6667219ecd97..899d45241853 100644 --- a/src/pointer-analysis/value_set_fi.cpp +++ b/src/pointer-analysis/value_set_fi.cpp @@ -1401,7 +1401,18 @@ void value_set_fit::havoc_reachable(const codet &code, const namespacet &ns) if(object.id() != ID_object_descriptor) continue; const exprt &root = to_object_descriptor_expr(object).root_object(); - if(root.id() == ID_symbol && root.type().id() != ID_code) + if(root.type().id() == "#REF#") + { + // a reference to the values of another variable, which are + // visited as that variable's entry (see flatten_rec) + if(values.find(root.get(ID_identifier)) == values.end()) + { + stored.insert(symbol_exprt{ + root.get(ID_identifier), + to_type_with_subtype(root.type()).subtype()}); + } + } + else if(root.id() == ID_symbol && root.type().id() != ID_code) stored.insert(root); } } @@ -1417,7 +1428,7 @@ void value_set_fit::havoc_reachable(const codet &code, const namespacet &ns) { assign( pointer, - reachable_pointer_value(pointer, reachable, get_targets, ns), + reachable_pointer_value(pointer, reachable, get_targets, ns, false), ns); } } From 4ea18895ea0af39004b2c7397590fc3a3c1ea1d8 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 19:01:46 +0000 Subject: [PATCH 035/100] Symex: havoc_reachable must assign the parts of objects directly 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 --- .../inline_asm_havoc_reachable_array/main.c | 14 ++++++++++++++ .../inline_asm_havoc_reachable_array/test.desc | 17 +++++++++++++++++ src/goto-symex/symex_havoc_reachable.cpp | 9 +++++++++ 3 files changed, 40 insertions(+) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_array/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_array/test.desc diff --git a/regression/cbmc/inline_asm_havoc_reachable_array/main.c b/regression/cbmc/inline_asm_havoc_reachable_array/main.c new file mode 100644 index 000000000000..054674b76621 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_array/main.c @@ -0,0 +1,14 @@ +// Inline assembly that is not modeled may change each of the 4096 pointers in +// a two-dimensional array of static lifetime. Symbolic execution assigns them +// one by one, and must not expand the whole array for each of them. +int x; +int *a[64][64]; + +int main(void) +{ + a[0][0] = &x; + asm volatile("cli" ::: "memory"); + __CPROVER_assert(a[1][1] == 0, "element changed"); // fails + __CPROVER_assert(a[0][0] == &x, "first element changed"); // fails + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_array/test.desc b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc new file mode 100644 index 000000000000..7cddc39504f4 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc @@ -0,0 +1,17 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 11 element changed: FAILURE$ +^\[main\.assertion\.2\] line 12 first element changed: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The havoc_reachable statement assigns each pointer in the array separately. +Assigning a[i][j] as an element of the whole array, rather than assigning the +symbol that field-sensitive symbolic execution has for it, expanded all 4096 +elements for each of the 4096 assignments: symbolic execution took 80 s +instead of 0.5 s. The test thus checks a time bound when run with a timeout +(test.pl -t). diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 6ff35d0f1f34..d89342556d4b 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -376,6 +376,15 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) for(const auto &object : havocked) split_lvalue(object, ns, pointers, others); + // Use the symbols that field-sensitive symbolic execution has for these + // parts: reading a member or an element of the expression of a whole object + // would expand all fields of that object, for each part. + for(auto &pointer : pointers) + pointer = + state.field_sensitivity.apply(ns, state, std::move(pointer), true); + for(auto &other : others) + other = state.field_sensitivity.apply(ns, state, std::move(other), true); + // Fresh temporaries. get_fresh_aux_symbol would search the symbol table for // each of the (possibly many) temporaries. auto new_temporary = [this, &state, &source_location]( From 437c1414234daf439062b7c7e02fb09e5835a913 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 19:12:38 +0000 Subject: [PATCH 036/100] havoc_reachable: move pointers to aligned positions within objects 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 --- doc/cprover-manual/modeling-inline-asm.md | 29 +- .../main.c | 59 +++ .../test.desc | 23 + .../test.desc | 3 +- src/assembler/remove_asm.cpp | 8 + src/goto-symex/symex_havoc_reachable.cpp | 491 +++++++++++++++--- 6 files changed, 520 insertions(+), 93 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_alignment/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 74a6c97a46cb..dbfab92440e7 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -139,12 +139,13 @@ pointers stored in the objects (following pointers transitively), so this includes, for example, all nodes of a linked list whose head is stored in a variable of static lifetime. The pointers stored in the objects that are changed are not made arbitrary: each of them is assigned a nondeterministic -choice among its previous value, null, and a pointer to any position within -the objects that the following candidates point to, at which an object of the -pointer's target type fits: the pointers previously stored in the changed -objects, and the reachable objects (of a compatible type). The statement can -thus relink a list or advance a pointer within an array, and dereferencing -the pointers afterwards remains precise. +choice among its previous value, null, the following candidates, and a +pointer to any aligned position (see below) within the objects that the +candidates point to, at which an object of the pointer's target type fits: the +pointers previously stored in the changed objects, and the reachable objects +(of a compatible type). The statement can thus relink a list or advance a +pointer within an array, and dereferencing the pointers afterwards remains +precise. MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the @@ -169,6 +170,22 @@ member access such as `s.a` names the variable `s`. pointer that may point to other positions than the start of an object, such as `p[1]` for a pointer `p` into an array, may fail the pointer checks after the statement, as the statement may have moved `p` to the last element. +- A pointer that the statement may move within an object is also assumed to + be aligned: its offset from the start of the object is a multiple of the + alignment of the pointer's target type, which is its size for scalars + whose size is a power of two (and 1 for other scalars), the alignment of + the elements for arrays, and the largest alignment of the members for + structs and unions (1 if they are packed); a smaller alignment given with + `__attribute__((aligned))` is used instead. The statement is thus assumed + not to store pointers such as `(int *)((char *)a + 1)` for an `int` array + `a`, although the processor may be able to access them. Pointers of type + `char *` and `void *` may point to any byte. Objects that contain a packed + struct or union, or a type whose given alignment is smaller than that of its + members, are exempt: pointers may point to any byte in them. The + assumption also applies to objects of unknown type, such as the objects + behind pointers whose targets are unknown. Arbitrary positions are not used + in general, as dereferencing a pointer that may point to them is costly + (25 times slower for four pointers into an array of 256 `int`). - The candidate values are only used if there are at most 64 of them (counting the pointer's own previous value). Otherwise, the pointer is assigned an arbitrary value, and a warning is printed. Such a pointer may diff --git a/regression/cbmc/inline_asm_havoc_reachable_alignment/main.c b/regression/cbmc/inline_asm_havoc_reachable_alignment/main.c new file mode 100644 index 000000000000..fbc303066c66 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_alignment/main.c @@ -0,0 +1,59 @@ +// Inline assembly that is not modeled may move the pointers it can reach +// within the objects they point into. In an object whose members are at +// positions that are multiples of their alignment, the pointers are assumed to +// point to positions that are multiples of the alignment of their target type +// (relative to the start of the object). In an object that contains a packed +// struct or a type with a reduced alignment, any position is considered. + +// arrays of structs that contain pointers, which two statements change +#define NODES(T) \ + struct T \ + { \ + struct T *next; \ + int data; \ + } T##s[30]; +NODES(t0) +NODES(t1) +NODES(t2) +NODES(t3) +NODES(t4) +NODES(t5) +NODES(t6) +NODES(t7) + +int a[4]; +int *gp = &a[0]; + +struct __attribute__((packed)) packed +{ + char c; + int x; +} ps[4]; +int *pp = &ps[0].x; + +typedef int int2 __attribute__((aligned(2))); +struct reduced +{ + short s; + int2 x; +} rs[4]; +int2 *rp = &rs[0].x; + +int main(void) +{ + t0s[0].next = &t0s[1]; + t1s[0].next = &t1s[1]; + t2s[0].next = &t2s[1]; + t3s[0].next = &t3s[1]; + t4s[0].next = &t4s[1]; + t5s[0].next = &t5s[1]; + t6s[0].next = &t6s[1]; + t7s[0].next = &t7s[1]; + asm volatile("cli" ::: "memory"); + asm volatile("cli" ::: "memory"); + __CPROVER_assert(t0s[0].next != &t0s[2], "array of structs"); // fails + __CPROVER_assert(gp != (int *)((char *)a + 1), "misaligned"); // holds + __CPROVER_assert(pp != &ps[1].x, "packed struct"); // fails + __CPROVER_assert(rp != &rs[2].x, "reduced alignment"); // fails + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc b/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc new file mode 100644 index 000000000000..abe1ac8033f3 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc @@ -0,0 +1,23 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^approximating inline assembly statement at file main\.c line 52 function main: .*; other objects are assumed to be unchanged, and the pointers stored in the changed objects are assumed to be null, previous values of such pointers, or pointers into the reachable objects at offsets that are multiples of the alignment of their target type and at which an object of that type fits$ +^\[main\.assertion\.1\] line 54 array of structs: FAILURE$ +^\[main\.assertion\.2\] line 55 misaligned: SUCCESS$ +^\[main\.assertion\.3\] line 56 packed struct: FAILURE$ +^\[main\.assertion\.4\] line 57 reduced alignment: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +A pointer that the havoc_reachable statement moves within an object points to +the start of the object plus a nondeterministic position. In objects whose +members are at multiples of their alignment, the position is a multiple of the +alignment of the pointer's target type: the statement is assumed not to store +misaligned pointers (assertion 2 holds by this assumption). In arrays of +packed structs, and of structs with a member whose alignment is reduced, the +position is arbitrary. With a nondeterministic offset added to the candidate +pointer and an assumption that the target type fits, cbmc took 20 s on this +program instead of 1 s. diff --git a/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc index 10b1ea0f2f9f..bc442e410fd1 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc @@ -15,6 +15,7 @@ dereference failure.*: FAILURE$ Each pointer stored in an object that the havoc_reachable statement changes may, after the statement, point to any position within the objects its candidate values point into, provided that an object of the pointer's target -type fits there. The statement is assumed not to store other pointers, such as +type fits there and that the position is a multiple of the alignment of that +type. The statement is assumed not to store other pointers, such as pointers one past the end of an object. Pointers to objects of exactly the pointer's target type, such as head, keep pointing to the start of objects. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 8018b4b66366..139c65d9d717 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -371,6 +371,14 @@ void remove_asmt::approximate_asm( << (parts.size() == 1 ? " is assigned a nondeterministic value" : " are assigned nondeterministic values") << "; other objects are assumed to be unchanged" + << (footprint.addresses.empty() && !footprint.arbitrary_memory + ? "" + : ", and the pointers stored in the changed objects are " + "assumed to be null, previous values of such " + "pointers, or pointers into the reachable objects at " + "offsets that are multiples of the alignment of their " + "target type and at which an object of that type " + "fits") << messaget::eom; } diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index d89342556d4b..85dfc46450e7 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -23,6 +23,8 @@ Author: Michael Tautschnig #include "path_storage.h" #include +#include +#include #include #include #include @@ -195,50 +197,293 @@ static mp_integer pointee_size(const typet &type, const namespacet &ns) return size.has_value() && *size > bytest{0} ? size->get() : mp_integer{1}; } -/// \return The size of the largest object that a pointer with value set -/// \p targets may point into (ignoring null), or an empty optional if that -/// is not known. -static std::optional -largest_target(const std::vector &targets, const namespacet &ns) +/// \return The address of the start of \p object, as a pointer to its +/// first element if it is an array (as value sets represent it). +static exprt start_address(const exprt &object) { - mp_integer result = 0; + if(object.type().id() == ID_array) + return address_of_exprt{ + index_exprt{object, from_integer(0, c_index_type())}}; + return address_of_exprt{object}; +} + +/// \return The alignment given in the source for \p type, or 0 if none is +/// given. +static mp_integer given_alignment(const typet &type) +{ + const auto alignment = numeric_cast( + static_cast(type.find(ID_C_alignment))); + return alignment.has_value() && *alignment > 0 ? *alignment : mp_integer{0}; +} + +/// \return A lower bound of the alignment of objects of type \p type, as +/// CBMC lays out objects: scalars are aligned to their size (if it is a +/// power of two), arrays to their elements, and structs and unions that +/// are not packed to their most strictly aligned member, unless the source +/// gives a smaller alignment. Larger alignments given in the source are +/// ignored, so that the bound also holds for objects of a type without +/// that alignment that the pointer points into. +static mp_integer alignment_of(const typet &type, const namespacet &ns) +{ + if(type.get_bool(ID_C_packed)) + return 1; + mp_integer result = 1; + if(type.id() == ID_array) + result = alignment_of(to_array_type(type).element_type(), ns); + else if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + const struct_union_typet &struct_union_type = + ns.follow_tag(to_struct_or_union_tag_type(type)); + if(struct_union_type.get_bool(ID_C_packed)) + return 1; + for(const auto &component : struct_union_type.components()) + { + if(component.type().id() != ID_c_bit_field && !component.get_is_padding()) + result = std::max(result, alignment_of(component.type(), ns)); + } + const mp_integer given = given_alignment(struct_union_type); + if(given > 0) + result = std::min(result, given); + } + else if(type.id() == ID_c_enum_tag) + result = alignment_of(ns.follow_tag(to_c_enum_tag_type(type)), ns); + else if(type.id() == ID_c_enum) + result = alignment_of(to_c_enum_type(type).underlying_type(), ns); + else if( + type.id() == ID_signedbv || type.id() == ID_unsignedbv || + type.id() == ID_floatbv || type.id() == ID_fixedbv || + type.id() == ID_c_bool || type.id() == ID_pointer) + { + const auto size = pointer_offset_size(type, ns); + if(size.has_value() && *size > bytest{0}) + { + const mp_integer &s = size->get(); + // a power of two + if(bitwise_and(s, s - 1) == 0) + result = s; + } + } + const mp_integer given = given_alignment(type); + return given > 0 ? std::min(result, given) : result; +} + +/// \return True iff CBMC lays out the members and elements of objects of +/// type \p type at positions that are multiples of their \ref alignment_of +/// relative to the start of the object: \p type contains no packed struct +/// or union, and no type with a given alignment that is smaller than the +/// alignment of its members or of its size. In other objects, objects of +/// any type may be at any position. +/// \param type: The type of an object +/// \param ns: Namespace +/// \param [in,out] cache: The result for the struct and union tags visited +static bool has_natural_layout( + const typet &type, + const namespacet &ns, + std::unordered_map &cache) +{ + if(type.get_bool(ID_C_packed)) + return false; + if(type.id() == ID_array) + { + const typet &element_type = to_array_type(type).element_type(); + return has_natural_layout(element_type, ns, cache) && + alignment_of(type, ns) == alignment_of(element_type, ns); + } + if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + const irep_idt &identifier = + to_struct_or_union_tag_type(type).get_identifier(); + const auto entry = cache.find(identifier); + if(entry != cache.end()) + return entry->second; + // a recursive type contains itself only through pointers + cache[identifier] = true; + const struct_union_typet &struct_union_type = + ns.follow_tag(to_struct_or_union_tag_type(type)); + bool result = !struct_union_type.get_bool(ID_C_packed); + mp_integer members = 1; + for(const auto &component : struct_union_type.components()) + { + if(!result) + break; + if(component.type().id() == ID_c_bit_field || component.get_is_padding()) + continue; + result = has_natural_layout(component.type(), ns, cache); + members = std::max(members, alignment_of(component.type(), ns)); + } + const mp_integer given = given_alignment(struct_union_type); + if(given > 0 && given < members) + result = false; + if(given_alignment(type) > 0 && given_alignment(type) < members) + result = false; + cache[identifier] = result; + return result; + } + const mp_integer given = given_alignment(type); + if(given > 0) + { + typet without_alignment = type; + without_alignment.remove(ID_C_alignment); + return given >= alignment_of(without_alignment, ns); + } + return true; +} + +/// The objects that a pointer may point into, with their sizes. +struct pointer_targetst +{ + /// Whether all targets are known objects of known size. + bool known = true; + /// Whether all targets of unknown size, if their type is known, have a + /// natural layout (see \ref has_natural_layout). + bool natural_layout = true; + std::vector> objects; +}; + +/// \return The objects (other than null) that a pointer with value set +/// \p targets may point into. +/// \param targets: A value set +/// \param ns: Namespace +/// \param [in,out] layouts: Cache for \ref has_natural_layout +static pointer_targetst targets_of( + const std::vector &targets, + const namespacet &ns, + std::unordered_map &layouts) +{ + pointer_targetst result; for(const auto &target : targets) { if(target.id() != ID_object_descriptor) - return {}; + { + result.known = false; + continue; + } const exprt &root = to_object_descriptor_expr(target).root_object(); if(root.id() == ID_null_object) continue; - if(root.id() == ID_integer_address) - return {}; - const auto size = pointer_offset_size(root.type(), ns); - if(!size.has_value()) - return {}; - result = std::max(result, size->get()); + const auto size = root.id() == ID_integer_address + ? std::optional{} + : pointer_offset_size(root.type(), ns); + if(size.has_value()) + result.objects.emplace_back(root, size->get()); + else + { + result.known = false; + if( + root.id() != ID_integer_address && + !has_natural_layout(root.type(), ns, layouts)) + { + result.natural_layout = false; + } + } } return result; } -/// \return A condition under which \p pointer, obtained by adding \p offset -/// bytes to a pointer, points into an object (not null) such that an object -/// of \p element_size bytes fits at that position. -static exprt -fits(const exprt &pointer, const exprt &offset, const mp_integer &element_size) +/// \return A pointer of type \p type to a position within one of the +/// \p objects (with their sizes) at which an object of \p element_size +/// bytes fits and that is a multiple of \p element_alignment, or to the +/// start of one of the objects. Positions are expressed relative to the +/// start of the objects, so that the solver only needs to consider the bits +/// that the sizes require. +/// \param objects: Objects with their sizes +/// \param element_size: Size of the objects that \p type points to +/// \param element_alignment: Alignment of the objects that \p type points to +/// \param type: A pointer type +/// \param new_choice: Returns a fresh nondeterministic Boolean +/// \param new_value: Returns a fresh nondeterministic value of a given type +static exprt move_within_objects( + const std::vector> &objects, + const mp_integer &element_size, + const mp_integer &element_alignment, + const typet &type, + const std::function &new_choice, + const std::function &new_value) +{ + PRECONDITION(!objects.empty()); + const typet char_pointer = pointer_type(char_type()); + const typet offset_type = signed_size_type(); + + exprt start = nil_exprt{}, size = nil_exprt{}; + mp_integer largest = 0; + for(auto it = objects.rbegin(); it != objects.rend(); ++it) + { + const exprt object_start = + typecast_exprt{start_address(it->first), char_pointer}; + const exprt object_size = from_integer(it->second, offset_type); + largest = std::max(largest, it->second); + if(start.is_nil()) + { + start = object_start; + size = object_size; + } + else + { + const exprt choice = new_choice(); + start = if_exprt{choice, object_start, std::move(start)}; + size = if_exprt{choice, object_size, std::move(size)}; + } + } + + // positions that are multiples of the alignment, which needs few bits + const std::size_t width = + largest > element_size + ? address_bits((largest - element_size) / element_alignment + 1) + : 1; + exprt position = + typecast_exprt{new_value(unsignedbv_typet{width}), offset_type}; + if(element_alignment > 1) + position = + mult_exprt{position, from_integer(element_alignment, offset_type)}; + return if_exprt{ + binary_relation_exprt{ + position, + ID_le, + minus_exprt{size, from_integer(element_size, offset_type)}}, + typecast_exprt::conditional_cast(plus_exprt{start, position}, type), + typecast_exprt::conditional_cast(start, type)}; +} + +/// \return A pointer of type \p type to a position within the object that +/// \p pointer (a symbol) points to at which an object of \p element_size +/// bytes fits and that is a multiple of \p element_alignment, or +/// \p pointer itself, using the object size of \p pointer. +/// \param pointer: A symbol of pointer type +/// \param element_size: Size of the objects that \p type points to +/// \param element_alignment: Alignment of the objects that \p type points to +/// \param type: A pointer type +/// \param value: A nondeterministic value of type `signed_size_type()` +static exprt move_within_object_of( + const symbol_exprt &pointer, + const mp_integer &element_size, + const mp_integer &element_alignment, + const typet &type, + const exprt &value) { - const typet &type = offset.type(); - const exprt position = pointer_offset_exprt{pointer, type}; + const typet &offset_type = value.type(); + const exprt position = + element_alignment > 1 + ? exprt{mult_exprt{value, from_integer(element_alignment, offset_type)}} + : value; const exprt size = - typecast_exprt{object_size_exprt{pointer, size_type()}, type}; - return and_exprt{ + typecast_exprt{object_size_exprt{pointer, size_type()}, offset_type}; + const exprt fits = and_exprt{ {not_exprt{equal_exprt{ pointer_object(pointer), pointer_object(null_pointer_exprt{to_pointer_type(pointer.type())})}}, - // the offset is small enough not to wrap around - binary_relation_exprt{offset, ID_le, size}, - binary_relation_exprt{offset, ID_ge, unary_minus_exprt{size}}, - binary_relation_exprt{position, ID_ge, from_integer(0, type)}, + binary_relation_exprt{position, ID_ge, from_integer(0, offset_type)}, binary_relation_exprt{ - plus_exprt{position, from_integer(element_size, type)}, ID_le, size}}}; + position, + ID_le, + minus_exprt{size, from_integer(element_size, offset_type)}}}}; + return if_exprt{ + fits, + typecast_exprt::conditional_cast( + plus_exprt{ + pointer, + minus_exprt{position, pointer_offset_exprt{pointer, offset_type}}}, + type), + typecast_exprt::conditional_cast(pointer, type)}; } void goto_symext::symex_havoc_reachable(statet &state, const codet &code) @@ -411,15 +656,7 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) candidates.push_back(old_value); } for(const auto &object : objects) - { - if(object.type().id() == ID_array) - { - candidates.push_back( - address_of_exprt{index_exprt{object, from_integer(0, c_index_type())}}); - } - else - candidates.push_back(address_of_exprt{object}); - } + candidates.push_back(start_address(object)); // the parts that are not pointers for(const auto &other : others) @@ -428,51 +665,129 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) state, other, side_effect_expr_nondett{other.type(), source_location}); } - // The size of the largest object each candidate may point into, computed - // on demand: the value sets of the previous values may be large. - std::vector>> extents( + // whether the types of objects have a natural layout, by struct tag + std::unordered_map layouts; + + // The objects each candidate may point into, computed on demand: the value + // sets of the previous values may be large. + std::vector> candidate_targets_cache( candidates.size()); - auto extent = [&](const exprt *candidate) -> const std::optional & + auto candidate_targets = + [&](const exprt *candidate) -> const pointer_targetst & { const std::size_t i = candidate - candidates.data(); - if(!extents[i].has_value()) + auto &entry = candidate_targets_cache[i]; + if(!entry.has_value()) { if(i < pointers.size()) { - extents[i] = largest_target( + entry = targets_of( state.value_set.get_value_set( state.rename(candidates[i], ns).get(), ns), - ns); + ns, + layouts); } else { - const auto size = - pointer_offset_size(objects[i - pointers.size()].type(), ns); - extents[i] = size.has_value() ? std::optional{size->get()} - : std::nullopt; + const exprt &object = objects[i - pointers.size()]; + entry = pointer_targetst{}; + const auto size = pointer_offset_size(object.type(), ns); + if(size.has_value()) + entry->objects.emplace_back(object, size->get()); + else + { + entry->known = false; + entry->natural_layout = + has_natural_layout(object.type(), ns, layouts); + } } } - return *extents[i]; + return *entry; }; - // a choice among the candidates in movable, plus offset bytes - auto move_pointer = [this, &source_location]( + auto new_choice = [this, &source_location]() + { return path_storage.build_symex_nondet(bool_typet{}, source_location); }; + auto new_value = [this, &source_location](const typet &type) + { return path_storage.build_symex_nondet(type, source_location); }; + + // A pointer of type type to a position within the objects that the + // candidates in movable point into, at which an object of element_size + // bytes fits, or the start of one of these objects. In objects with a + // natural layout, the position is a multiple of element_alignment + // relative to the start of the object; in others, it is arbitrary. + auto move_pointer = [&]( const std::vector &movable, - const exprt &offset, - const typet &type) + const typet &type, + const mp_integer &element_size, + const mp_integer &element_alignment) { - const typet char_pointer = pointer_type(char_type()); - exprt base = - typecast_exprt::conditional_cast(*movable.back(), char_pointer); - for(auto it = std::next(movable.rbegin()); it != movable.rend(); ++it) + // the objects with a natural layout, and the others + std::vector> aligned, unaligned; + std::set seen; + std::vector unknown; + bool unknown_aligned = true; + for(const exprt *candidate : movable) { - base = if_exprt{ - path_storage.build_symex_nondet(bool_typet{}, source_location), - typecast_exprt::conditional_cast(**it, char_pointer), - std::move(base)}; + const pointer_targetst &targets = candidate_targets(candidate); + if(!targets.known) + { + unknown.push_back(candidate); + unknown_aligned = unknown_aligned && targets.natural_layout; + } + for(const auto &object : targets.objects) + { + if(!seen.insert(object.first).second) + continue; + if(has_natural_layout(object.first.type(), ns, layouts)) + aligned.push_back(object); + else + unaligned.push_back(object); + } + } + + std::optional result; + for(const auto &group : + {std::make_pair(&aligned, element_alignment), + std::make_pair(&unaligned, mp_integer{1})}) + { + if(group.first->empty()) + continue; + const exprt moved = move_within_objects( + *group.first, element_size, group.second, type, new_choice, new_value); + result = + result.has_value() ? if_exprt{new_choice(), moved, *result} : moved; } - return typecast_exprt::conditional_cast( - plus_exprt{std::move(base), offset}, type); + + // candidates with unknown targets: move them within whatever object + // they point to + if(!unknown.empty()) + { + const typet char_pointer = pointer_type(char_type()); + exprt base = + typecast_exprt::conditional_cast(*unknown.back(), char_pointer); + for(auto it = std::next(unknown.rbegin()); it != unknown.rend(); ++it) + { + base = if_exprt{ + new_choice(), + typecast_exprt::conditional_cast(**it, char_pointer), + std::move(base)}; + } + // a temporary keeps the simplifier from distributing the following + // over the choice among the candidates + const symbol_exprt pointer = + new_temporary("movable_pointer", char_pointer); + symex_assign(state, pointer, base); + const exprt moved = move_within_object_of( + pointer, + element_size, + unknown_aligned ? element_alignment : mp_integer{1}, + type, + new_value(signed_size_type())); + result = + result.has_value() ? if_exprt{new_choice(), moved, *result} : moved; + } + + return *result; }; // An arbitrary pointer: a temporary that is never assigned, and hence @@ -506,12 +821,17 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // The statement may store any pointer it can obtain: the pointers stored // in the reachable objects, or the addresses of these objects, possibly // with an offset. Restricting the pointers to these values (or null) keeps - // the value sets, and hence dereferencing, precise. The offset is - // nondeterministic, but must leave room for an object of the pointer's - // target type: the statement is assumed not to store pointers to positions - // at which no such object fits, such as one past the end of an object. As - // offsets make dereferencing costly, they are only added to candidates - // that may point into objects that are larger than the target type. + // the value sets, and hence dereferencing, precise. A pointer moved within + // an object points to the start of the object plus a nondeterministic + // position that leaves room for an object of the pointer's target type: + // the statement is assumed not to store pointers to positions at which no + // such object fits, such as one past the end of an object. In objects with + // a natural layout, the position is a multiple of the alignment of the + // target type: the statement is assumed not to store misaligned pointers + // (positions at arbitrary bytes make dereferencing an array of int after + // the statement 25 times slower). As positions make dereferencing costly, + // they are only added to candidates that may point into objects that are + // larger than the target type. // To bound the size of the formula and of the value sets, this is done only // for pointers with at most max_pointer_candidates candidate values // (including their own previous value). Restricting a pointer to some of @@ -549,13 +869,23 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // pointer to any position in that object (pointer arithmetic, interior // pointers). const mp_integer element_size = pointee_size(type, ns); + const mp_integer element_alignment = + alignment_of(to_pointer_type(type).base_type(), ns); std::vector fixed, movable; for(const exprt *candidate : chosen) { - const auto &candidate_extent = extent(candidate); - if(!candidate_extent.has_value() || *candidate_extent > element_size) + const pointer_targetst &targets = candidate_targets(candidate); + if( + !targets.known || + std::any_of( + targets.objects.begin(), + targets.objects.end(), + [&element_size](const std::pair &object) + { return object.second > element_size; })) + { movable.push_back(candidate); - else if(candidate != &candidates[i]) + } + if(candidate != &candidates[i]) fixed.push_back(candidate); } @@ -571,21 +901,10 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) } if(!movable.empty()) { - // the position must leave room for an object of the target type, - // unless it is the one the candidate points to - const symbol_exprt moved = new_temporary("moved_pointer", type); - const exprt offset = - path_storage.build_symex_nondet(signed_size_type(), source_location); - symex_assign(state, moved, move_pointer(movable, offset, type)); - const exprt choice = - path_storage.build_symex_nondet(bool_typet{}, source_location); - value = if_exprt{choice, moved, std::move(value)}; - symex_assume( - state, - or_exprt{ - not_exprt{choice}, - equal_exprt{offset, from_integer(0, offset.type())}, - fits(moved, offset, element_size)}); + value = if_exprt{ + path_storage.build_symex_nondet(bool_typet{}, source_location), + move_pointer(movable, type, element_size, element_alignment), + std::move(value)}; } value = if_exprt{ path_storage.build_symex_nondet(bool_typet{}, source_location), From 775797f3c5bcac9d156bc5528155157898db5ebe Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 19:41:35 +0000 Subject: [PATCH 037/100] havoc_reachable: bound the candidate values of all pointers together 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 --- doc/cprover-manual/modeling-inline-asm.md | 6 +- .../inline_asm_havoc_reachable_budget/main.c | 44 +++++++++ .../test.desc | 18 ++++ src/goto-symex/symex_havoc_reachable.cpp | 95 ++++++++++++++++--- src/pointer-analysis/reachable_objects.cpp | 21 ++-- src/pointer-analysis/reachable_objects.h | 4 + 6 files changed, 164 insertions(+), 24 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_budget/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_budget/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index dbfab92440e7..4b9f29839b17 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -187,8 +187,10 @@ member access such as `s.a` names the variable `s`. in general, as dereferencing a pointer that may point to them is costly (25 times slower for four pointers into an array of 256 `int`). - The candidate values are only used if there are at most 64 of them - (counting the pointer's own previous value). Otherwise, the pointer is - assigned an arbitrary value, and a warning is printed. Such a pointer may + (counting the pointer's own previous value), and only until the pointers + that one statement restricts to their candidates have 65536 candidate + values in total. Otherwise, the pointer is assigned an arbitrary value, + and a warning is printed. Such a pointer may point to any object whose address is stored anywhere, or be invalid: dereferencing it considers all these objects, which is slow if there are many, and the pointer checks of the dereference fail. Pointers in unions and diff --git a/regression/cbmc/inline_asm_havoc_reachable_budget/main.c b/regression/cbmc/inline_asm_havoc_reachable_budget/main.c new file mode 100644 index 000000000000..b9160a547cac --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_budget/main.c @@ -0,0 +1,44 @@ +// Inline assembly that is not modeled changes 17 arrays of 63 nodes. Each of +// the 1071 pointers has 64 candidate values (the previous values of the 63 +// pointers of its type, and the start of the array), 68544 in total. Symbolic +// execution restricts pointers to their candidates only up to 65536 candidate +// values in total; the remaining pointers are assigned arbitrary values. + +#define NODES(T) \ + struct T \ + { \ + struct T *next; \ + int data; \ + } T##s[63]; +NODES(t00) +NODES(t01) +NODES(t02) +NODES(t03) +NODES(t04) +NODES(t05) +NODES(t06) +NODES(t07) +NODES(t08) +NODES(t09) +NODES(t10) +NODES(t11) +NODES(t12) +NODES(t13) +NODES(t14) +NODES(t15) +NODES(t16) + +int main(void) +{ + asm volatile("cli" ::: "memory"); + __CPROVER_assert( + t00s[62].next == 0 || __CPROVER_same_object(t00s[62].next, t00s), + "first array"); // holds + __CPROVER_assert( + t16s[0].next == 0 || __CPROVER_same_object(t16s[0].next, t16s), + "within the bound"); // holds + __CPROVER_assert( + t16s[62].next == 0 || __CPROVER_same_object(t16s[62].next, t16s), + "beyond the bound"); // fails + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc new file mode 100644 index 000000000000..81aaf1ac4593 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c + +^EXIT=10$ +^SIGNAL=0$ +^havocking the objects reachable at file main\.c line 33 function main: the pointers have more than 65536 possible values in total, and some are assigned arbitrary values$ +^\[main\.assertion\.1\] line 34 first array: SUCCESS$ +^\[main\.assertion\.2\] line 37 within the bound: SUCCESS$ +^\[main\.assertion\.3\] line 40 beyond the bound: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The objects of static lifetime are visited in the order of their names, and so +are their pointers. 16 arrays (1008 pointers with 64 candidates each) and the +first 16 elements of t16s are restricted to their candidates, which keeps them +within the array of their type (or null). The other 47 pointers of t16s are +assigned arbitrary values, which may point anywhere. diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 85dfc46450e7..521b3c30eb24 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -37,6 +37,11 @@ static const std::size_t max_pointer_candidates = 64; /// restricted to candidate values. static const std::size_t max_array_elements = 64; +/// The maximum total number of candidate values of the pointers that one +/// statement restricts to candidate values; the other pointers are assigned +/// arbitrary values. +static const std::size_t max_pointer_choices = 1 << 16; + /// \return The identifier of the (L1-renamed) object \p object, or the empty /// identifier if \p object is not a symbol. static irep_idt object_identifier(const exprt &object) @@ -836,25 +841,74 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // for pointers with at most max_pointer_candidates candidate values // (including their own previous value). Restricting a pointer to some of // its candidates would exclude values the statement may store, so the - // other pointers are assigned arbitrary values. - bool too_many_candidates = false; + // other pointers are assigned arbitrary values. To bound the size of the + // formula for statements that change many pointers, pointers are also + // assigned arbitrary values once the pointers restricted to candidates + // have max_pointer_choices candidates in total. + + // the indices of the candidates by the type they point to, and of the + // candidates that are compatible with all pointers (see + // is_compatible_pointer) + std::unordered_map, irep_hash> + candidates_by_type; + std::vector generic_candidates; + for(std::size_t j = 0; j < candidates.size(); ++j) + { + if(is_generic_pointer(candidates[j].type())) + generic_candidates.push_back(j); + else + { + candidates_by_type[to_pointer_type(candidates[j].type()).base_type()] + .push_back(j); + } + } + + bool too_many_candidates = false, too_many_choices = false; + std::size_t pointer_choices = 0; for(std::size_t i = 0; i < pointers.size(); ++i) { const exprt &pointer = pointers[i]; const typet &type = pointer.type(); - std::vector chosen{&candidates[i]}; - for(const auto &candidate : candidates) + + // the compatible candidates (including the pointer's own previous + // value), in the order of their indices; none if there are too many + std::vector compatible; + if(is_generic_pointer(type)) { - if( - &candidate == &candidates[i] || - !is_compatible_pointer(type, candidate.type())) - continue; - if(chosen.size() == max_pointer_candidates) + if(candidates.size() <= max_pointer_candidates) { - chosen.clear(); - break; + for(std::size_t j = 0; j < candidates.size(); ++j) + compatible.push_back(j); + } + } + else + { + const auto by_type = + candidates_by_type.find(to_pointer_type(type).base_type()); + const std::vector empty; + const std::vector &same_type = + by_type == candidates_by_type.end() ? empty : by_type->second; + if(same_type.size() + generic_candidates.size() <= max_pointer_candidates) + { + std::merge( + same_type.begin(), + same_type.end(), + generic_candidates.begin(), + generic_candidates.end(), + std::back_inserter(compatible)); + } + } + + // its own previous value first + std::vector chosen; + if(!compatible.empty()) + { + chosen.push_back(&candidates[i]); + for(const std::size_t j : compatible) + { + if(j != i) + chosen.push_back(&candidates[j]); } - chosen.push_back(&candidate); } if(chosen.empty()) @@ -864,6 +918,14 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) continue; } + if(pointer_choices + chosen.size() > max_pointer_choices) + { + too_many_choices = true; + symex_assign(state, pointer, arbitrary_pointer(type)); + continue; + } + pointer_choices += chosen.size(); + // The candidates that may point into an object in which more than one // object of the pointer's target type fits: the statement may store a // pointer to any position in that object (pointer arithmetic, interior @@ -931,4 +993,13 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) << " possible values, and are assigned arbitrary values" << messaget::eom; } + + if(too_many_choices) + { + log.warning() << "havocking the objects reachable at " << source_location + << ": the pointers have more than " << max_pointer_choices + << " possible values in total, and some are assigned " + "arbitrary values" + << messaget::eom; + } } diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp index 6eeb2aaf8689..74ffb8b712bb 100644 --- a/src/pointer-analysis/reachable_objects.cpp +++ b/src/pointer-analysis/reachable_objects.cpp @@ -178,18 +178,19 @@ std::vector static_lifetime_objects( return result; } +bool is_generic_pointer(const typet &type) +{ + const typet &base = to_pointer_type(type).base_type(); + return base.id() == ID_empty || + ((base.id() == ID_signedbv || base.id() == ID_unsignedbv) && + to_bitvector_type(base).get_width() == 8); +} + bool is_compatible_pointer(const typet &location, const typet &candidate) { - const typet &location_base = to_pointer_type(location).base_type(); - const typet &candidate_base = to_pointer_type(candidate).base_type(); - auto is_generic = [](const typet &base) - { - return base.id() == ID_empty || - ((base.id() == ID_signedbv || base.id() == ID_unsignedbv) && - to_bitvector_type(base).get_width() == 8); - }; - return location_base == candidate_base || is_generic(location_base) || - is_generic(candidate_base); + return to_pointer_type(location).base_type() == + to_pointer_type(candidate).base_type() || + is_generic_pointer(location) || is_generic_pointer(candidate); } /// \return The size of the objects that pointers of type \p type point to: diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h index a3c137f1cb22..6575bedfd80a 100644 --- a/src/pointer-analysis/reachable_objects.h +++ b/src/pointer-analysis/reachable_objects.h @@ -94,6 +94,10 @@ exprt reachable_pointer_value( const namespacet &ns, bool include_previous_value); +/// \return True iff \p type is a pointer to void or to bytes, which +/// \ref is_compatible_pointer considers compatible with all pointers. +bool is_generic_pointer(const typet &type); + /// \return True iff a pointer of type \p candidate may be stored in a pointer /// of type \p location without changing what kind of object it points to: /// the pointed-to types are the same, or one of them is `void` or a byte. From 9d3a2b511df954b1bd8fad40dac6aed9d71d3985 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 19:56:37 +0000 Subject: [PATCH 038/100] havoc_reachable: change failed objects and memory at integer addresses 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 --- doc/cprover-manual/modeling-inline-asm.md | 27 +- .../inline_asm_havoc_reachable_unknown/main.c | 54 ++++ .../test.desc | 30 ++ src/goto-symex/symex_havoc_reachable.cpp | 277 ++++++++++-------- 4 files changed, 263 insertions(+), 125 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_unknown/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 4b9f29839b17..311f0c95aed9 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -147,6 +147,17 @@ pointers previously stored in the changed objects, and the reachable objects pointer within an array, and dereferencing the pointers afterwards remains precise. +Two kinds of memory have no address that CBMC knows, and are changed as +well. Dereferencing a pointer variable whose target is not known (for +example, the result of a function without a body) yields a placeholder +object for that variable; the placeholder objects of the reachable pointer +variables are changed (the pointers stored in them are not candidate values +of other pointers, as they are mostly not written). Memory at integer +addresses (such as a memory-mapped register accessed as +`*(volatile int *)0x1000`), which CBMC models as the array +`__CPROVER_memory`, is changed if the statement may access arbitrary memory +(item 3 above), or if a reachable pointer may point to an integer address. + MSVC-style blocks have no operand interface. If a block contains an instruction that is not modeled, each local variable (or parameter) of the enclosing function that the block names (all of them, if a name is @@ -158,8 +169,14 @@ member access such as `s.a` names the variable `s`. - The approximation only reaches the objects listed above. Objects that the statement can reach only through pointers that CBMC does not track (for - example, addresses computed from integers, or pointers stored in local - variables of a caller whose address is not taken) keep their values. + example, pointers stored in local variables of a caller whose address is + not taken) keep their values. If an operand whose target is not known is + not a pointer variable (or computed from one by pointer arithmetic and + casts), for example a pointer read from uninitialized memory, a warning is + printed, as the object it points to is not changed. As for C code, CBMC + does not consider that two pointers whose targets are not known may point + to the same object: changing the placeholder object of one of them does not + change that of the other. - A pointer stored in a changed object is restricted to the candidate values described above. The approximation thus assumes that the statement does not store other pointers in it: no pointer one past the end of an object or @@ -210,7 +227,11 @@ member access such as `s.a` names the variable `s`. (`goto-instrument --race-check`) and the instrumentation of interrupt handlers (`--isr`) take the statement to write the reachable variables (all objects of static lifetime, if it may access arbitrary memory) found by the - value set analysis. The weak memory instrumentation (`--mm`) ignores the + value set analysis. The objects that the static analyses take the + statement to read and write (for the dependence graph, the race check, and + `--isr`) do not include `__CPROVER_memory` and the placeholder objects of + pointers whose targets are not known. The weak memory instrumentation + (`--mm`) ignores the statement: its writes are not delayed, but become visible to other threads at once. - Control flow out of a statement is not modeled: `asm goto` statements diff --git a/regression/cbmc/inline_asm_havoc_reachable_unknown/main.c b/regression/cbmc/inline_asm_havoc_reachable_unknown/main.c new file mode 100644 index 000000000000..56d16e4532bc --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_unknown/main.c @@ -0,0 +1,54 @@ +// Inline assembly that is not modeled may change memory whose address CBMC +// does not know: the objects behind pointers whose targets are unknown (here: +// returned by functions without a body), and memory at integer addresses (such +// as memory-mapped registers). +void *malloc(__CPROVER_size_t); +int *ext(void); + +struct node +{ + struct node *next; + int data; +}; +struct node *ext_node(void); + +const int *ext_const(void); + +int *gp; +struct node *gn; +const int *cp; + +#define REG (*(volatile int *)0x1000) + +int main(void) +{ + gp = ext(); + gn = ext_node(); + cp = ext_const(); + int v = *cp; + int *lp = ext(); // its address is not taken + *gp = 1; + gn->data = 2; + *lp = 3; + REG = 4; + asm volatile("cli" ::: "memory"); + __CPROVER_assert(*gp == 1, "unknown target of a static"); // fails + __CPROVER_assert(gn->data == 2, "unknown target, struct"); // fails + __CPROVER_assert(*lp == 3, "unknown target of a local"); // holds + __CPROVER_assert(REG == 4, "integer address, memory clobber"); // fails + __CPROVER_assert(*cp == v, "unknown target of a const pointer"); // fails + + *gp = 1; + asm volatile("cli" : : "r"(gp + 1)); + __CPROVER_assert(*gp == 1, "unknown target of an operand"); // fails + + REG = 4; + asm volatile("cli" : : "r"((int *)0x2000)); + __CPROVER_assert(REG == 4, "integer address of an operand"); // fails + + // a pointer read from memory that was not written + int **pp = malloc(sizeof(int *)); + __CPROVER_assume(pp != 0); + asm volatile("cli" : : "r"(*pp)); + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc b/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc new file mode 100644 index 000000000000..dae8311803b4 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc @@ -0,0 +1,30 @@ +CORE gcc-only +main.c +--no-standard-checks +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 35 unknown target of a static: FAILURE$ +^\[main\.assertion\.2\] line 36 unknown target, struct: FAILURE$ +^\[main\.assertion\.3\] line 37 unknown target of a local: SUCCESS$ +^\[main\.assertion\.4\] line 38 integer address, memory clobber: FAILURE$ +^\[main\.assertion\.5\] line 39 unknown target of a const pointer: FAILURE$ +^\[main\.assertion\.6\] line 43 unknown target of an operand: FAILURE$ +^\[main\.assertion\.7\] line 47 integer address of an operand: FAILURE$ +^havocking the objects reachable at file main\.c line 52 function main: some pointers have targets that are not known, and the objects they point to keep their values$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +^havocking the objects reachable at file main\.c line (34|42|46) function main: some pointers have targets +-- +Dereferencing a pointer variable whose target is not known (gp, gn, cp, lp: +the results of functions without a body) yields the variable's failed object +(gp$object, ...). The havoc_reachable statement changes the failed objects of +the reachable pointer variables (assertions 1, 2, 5, 6), also if the pointer +points to a constant type (the object it points to need not be constant), and +__CPROVER_memory, which models memory at integer addresses, with a "memory" +clobber or if an operand may point to an integer address (assertions 4, 7). +lp is a local variable whose address is not taken, which the statement cannot +reach (assertion 3). The operand *pp is read from memory that was not +written: it is no variable, and has no failed object, so a warning is +printed. Without --no-standard-checks, the dereferences of these pointers fail +the pointer checks. diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 521b3c30eb24..a291ab6c8886 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -21,6 +21,7 @@ Author: Michael Tautschnig #include "goto_symex.h" #include "path_storage.h" +#include "symex_dereference_state.h" #include #include @@ -144,53 +145,6 @@ static void split_lvalue( others.push_back(lvalue); } -/// \return The type of the part of an object of type \p type that \p path -/// denotes, where \p path is a sequence of "..component" and "[[index]]" -/// (as in field-sensitive SSA identifiers) and ".component" and "[]" (as in -/// value set suffixes), or nullptr if \p path cannot be resolved. -static const typet * -type_of_path(const typet &type, const std::string &path, const namespacet &ns) -{ - const typet *current = &type; - std::size_t pos = 0; - while(pos < path.size()) - { - if(path.compare(pos, 2, "[]") == 0 || path.compare(pos, 2, "[[") == 0) - { - if(current->id() != ID_array) - return nullptr; - const std::size_t end = - path.compare(pos, 2, "[]") == 0 ? pos + 2 : path.find("]]", pos) + 2; - if(end < pos + 2) - return nullptr; - current = &to_array_type(*current).element_type(); - pos = end; - } - else if(path[pos] == '.') - { - const std::size_t start = - path.compare(pos, 2, "..") == 0 ? pos + 2 : pos + 1; - std::size_t end = start; - while(end < path.size() && path[end] != '.' && path[end] != '[') - ++end; - if(current->id() != ID_struct_tag && current->id() != ID_union_tag) - { - return nullptr; - } - const struct_union_typet &struct_union_type = - ns.follow_tag(to_struct_or_union_tag_type(*current)); - const irep_idt name = path.substr(start, end - start); - if(!struct_union_type.has_component(name)) - return nullptr; - current = &struct_union_type.get_component(name).type(); - pos = end; - } - else - return nullptr; - } - return current; -} - /// \return The size of the objects that pointers of type \p type point to: /// 1 for `void *` and for pointers to objects of unknown size. static mp_integer pointee_size(const typet &type, const namespacet &ns) @@ -491,6 +445,27 @@ static exprt move_within_object_of( typecast_exprt::conditional_cast(pointer, type)}; } +/// \return The pointer that \p pointer is computed from by pointer +/// arithmetic and casts between pointer types. +static const exprt &base_pointer(const exprt &pointer) +{ + if( + pointer.id() == ID_typecast && + to_typecast_expr(pointer).op().type().id() == ID_pointer) + { + return base_pointer(to_typecast_expr(pointer).op()); + } + if(pointer.id() == ID_plus || pointer.id() == ID_minus) + { + for(const auto &operand : pointer.operands()) + { + if(operand.type().id() == ID_pointer) + return base_pointer(operand); + } + } + return pointer; +} + void goto_symext::symex_havoc_reachable(statet &state, const codet &code) { const source_locationt &source_location = state.source.pc->source_location(); @@ -498,7 +473,13 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // the objects reachable, in the order they are found std::vector objects; std::unordered_set known; + // the objects among these that the statement cannot take the address of, + // as their address is unknown: they are no candidate values of pointers + std::unordered_set without_address; + // whether some pointers have targets that the statement does not change bool unknown_target = false; + // whether some pointers may point to integer addresses + bool integer_address = false; auto add_object = [&objects, &known](const exprt &object) { @@ -506,27 +487,51 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) objects.push_back(object); }; - auto add_target = [&add_object, &unknown_target](const exprt &target) + // Unknown targets of pointer variables are handled by the failed objects + // (see below); dereferencing other pointers with unknown targets yields a + // fresh object each time. + auto add_target = + [&add_object, &unknown_target, &integer_address](const exprt &target) { - if(target.id() == ID_unknown) - { - unknown_target = true; - return; - } if(target.id() != ID_object_descriptor) return; const exprt &root = to_object_descriptor_expr(target).root_object(); if(root.id() == ID_symbol && root.type().id() != ID_code) add_object(root); + else if(root.id() == ID_integer_address) + integer_address = true; else if( - root.id() != ID_null_object && root.id() != ID_integer_address && - root.id() != ID_string_constant && root.id() != ID_constant && - root.type().id() != ID_code) + root.id() != ID_null_object && root.id() != ID_string_constant && + root.id() != ID_constant && root.type().id() != ID_code) { unknown_target = true; } }; + // Dereferencing a pointer variable whose targets are unknown or invalid + // yields its "failed object" (see symex_dereference_statet), which the + // statement may change as well if the pointer is reachable. Dereferencing + // other pointers with unknown targets (such as members) yields a fresh + // object each time. Returns false if pointer is no pointer variable. + symex_dereference_statet symex_dereference_state{state, ns}; + dereference_callbackt &dereference_state = symex_dereference_state; + auto add_failed_object = [&](const exprt &pointer) + { + const symbolt *failed = + dereference_state.get_or_create_failed_symbol(pointer); + if(failed == nullptr) + return false; + if( + failed->type.id() != ID_empty && failed->type.id() != ID_code && + pointer_offset_size(failed->type, ns).has_value()) + { + const exprt object = state.rename(failed->symbol_expr(), ns).get(); + without_address.insert(object_identifier(object)); + add_object(object); + } + return true; + }; + // the objects the operands point to for(const auto &operand : code.operands()) { @@ -534,8 +539,16 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) continue; const exprt pointer = state.rename(clean_expr(operand, state, false), ns).get(); + bool unknown = false; for(const auto &target : state.value_set.get_value_set(pointer, ns)) - add_target(target); + { + if(target.id() == ID_unknown) + unknown = true; + else + add_target(target); + } + if(!add_failed_object(base_pointer(pointer)) && unknown) + unknown_target = true; } // the objects that can be named, and the address-taken local variables of @@ -581,40 +594,50 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // the maps of targets visited so far, which pointers assigned an // arbitrary value share - std::set> visited; + std::unordered_set visited; for(std::size_t i = 0; i < objects.size(); ++i) { + if(objects[i].type().id() == ID_pointer) + add_failed_object(objects[i]); + const auto it = entries.find(object_identifier(objects[i])); if(it == entries.end()) continue; - const std::string object_id = id2string(it->first); for(const auto *entry : it->second) { - // an unknown value of a non-pointer part of the object is no - // unknown pointer target - const typet *type = type_of_path( - objects[i].type(), - id2string(entry->identifier).substr(object_id.size()) + entry->suffix, - ns); - const bool is_pointer = type == nullptr || type->id() == ID_pointer; - if(!visited.insert({&entry->object_map.read(), is_pointer}).second) + if(!visited.insert(&entry->object_map.read()).second) continue; for(const auto &target : entry->object_map.read()) - { - const exprt target_expr = state.value_set.to_expr(target); - if(is_pointer || target_expr.id() != ID_unknown) - add_target(target_expr); - } + add_target(state.value_set.to_expr(target)); } } } + // Memory at integer addresses, such as memory-mapped registers, is modeled + // by __CPROVER_memory, whose address is unknown as well. + const symbolt *memory_symbol = nullptr; + if( + (integer_address || code.get_bool(ID_arbitrary_memory)) && + !ns.lookup(CPROVER_PREFIX "memory", memory_symbol)) + { + const exprt memory = + state.rename(memory_symbol->symbol_expr(), ns).get(); + without_address.insert(object_identifier(memory)); + add_object(memory); + } + + // Objects without address (failed objects) take their type from the type + // of the pointer, which may point to a constant even if the object is not. std::vector havocked; for(const auto &object : objects) { - if(!is_constant_type(object.type())) + if( + !is_constant_type(object.type()) || + without_address.count(object_identifier(object))) + { havocked.push_back(object); + } } // Split the objects into the pointers they contain and the remaining @@ -623,8 +646,17 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // imprecise), so the pointers are assigned a nondeterministic choice among // candidate values instead. std::vector pointers, others; + // Whether the previous value of each pointer is a candidate value of the + // other pointers: not if it is stored in an object without address, which + // mostly stands for the target of an invalid pointer, and whose pointers + // are mostly not written (and hence have unknown targets). + std::vector offered; for(const auto &object : havocked) + { split_lvalue(object, ns, pointers, others); + offered.resize( + pointers.size(), !without_address.count(object_identifier(object))); + } // Use the symbols that field-sensitive symbolic execution has for these // parts: reading a member or an element of the expression of a whole object @@ -660,8 +692,15 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) symex_assign(state, old_value, pointer); candidates.push_back(old_value); } + std::vector candidate_objects; for(const auto &object : objects) - candidates.push_back(start_address(object)); + { + if(!without_address.count(object_identifier(object))) + { + candidates.push_back(start_address(object)); + candidate_objects.push_back(object); + } + } // the parts that are not pointers for(const auto &other : others) @@ -694,7 +733,7 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) } else { - const exprt &object = objects[i - pointers.size()]; + const exprt &object = candidate_objects[i - pointers.size()]; entry = pointer_targetst{}; const auto size = pointer_offset_size(object.type(), ns); if(size.has_value()) @@ -846,14 +885,18 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // assigned arbitrary values once the pointers restricted to candidates // have max_pointer_choices candidates in total. - // the indices of the candidates by the type they point to, and of the - // candidates that are compatible with all pointers (see - // is_compatible_pointer) + // the indices of the candidates offered to all pointers, of these by the + // type they point to, and of those that are compatible with all pointers + // (see is_compatible_pointer) + std::vector offered_candidates; std::unordered_map, irep_hash> candidates_by_type; std::vector generic_candidates; for(std::size_t j = 0; j < candidates.size(); ++j) { + if(j < pointers.size() && !offered[j]) + continue; + offered_candidates.push_back(j); if(is_generic_pointer(candidates[j].type())) generic_candidates.push_back(j); else @@ -870,54 +913,44 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) const exprt &pointer = pointers[i]; const typet &type = pointer.type(); - // the compatible candidates (including the pointer's own previous - // value), in the order of their indices; none if there are too many - std::vector compatible; - if(is_generic_pointer(type)) - { - if(candidates.size() <= max_pointer_candidates) - { - for(std::size_t j = 0; j < candidates.size(); ++j) - compatible.push_back(j); - } - } - else + // the compatible candidates, in the order of their indices, which + // include the pointer's own previous value if it is offered + const std::vector empty; + const std::vector *same_type = &offered_candidates; + const std::vector *other_type = ∅ + if(!is_generic_pointer(type)) { const auto by_type = candidates_by_type.find(to_pointer_type(type).base_type()); - const std::vector empty; - const std::vector &same_type = - by_type == candidates_by_type.end() ? empty : by_type->second; - if(same_type.size() + generic_candidates.size() <= max_pointer_candidates) - { - std::merge( - same_type.begin(), - same_type.end(), - generic_candidates.begin(), - generic_candidates.end(), - std::back_inserter(compatible)); - } - } - - // its own previous value first - std::vector chosen; - if(!compatible.empty()) - { - chosen.push_back(&candidates[i]); - for(const std::size_t j : compatible) - { - if(j != i) - chosen.push_back(&candidates[j]); - } + same_type = + by_type == candidates_by_type.end() ? &empty : &by_type->second; + other_type = &generic_candidates; } - if(chosen.empty()) + if( + same_type->size() + other_type->size() + (offered[i] ? 0 : 1) > + max_pointer_candidates) { too_many_candidates = true; symex_assign(state, pointer, arbitrary_pointer(type)); continue; } + // its own previous value first + std::vector compatible; + std::merge( + same_type->begin(), + same_type->end(), + other_type->begin(), + other_type->end(), + std::back_inserter(compatible)); + std::vector chosen{&candidates[i]}; + for(const std::size_t j : compatible) + { + if(j != i) + chosen.push_back(&candidates[j]); + } + if(pointer_choices + chosen.size() > max_pointer_choices) { too_many_choices = true; @@ -975,15 +1008,15 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) symex_assign(state, pointer, value); } - // Unknown targets are common (for example, the pointers stored in memory - // that is allocated, but not yet written), and mean that the pointer may - // hold any value, including addresses of objects that are not in the set. + // The objects that dereferencing pointers with unknown targets yields are + // changed above where symbolic execution keeps them (the failed objects of + // pointer variables). Other targets are not. if(unknown_target) { - log.debug() << "havocking the objects reachable at " << source_location - << ": some pointers have unknown targets, objects only " - "reachable through them keep their values" - << messaget::eom; + log.warning() << "havocking the objects reachable at " << source_location + << ": some pointers have targets that are not known, and " + "the objects they point to keep their values" + << messaget::eom; } if(too_many_candidates) From 5e78f3edccfbd1530cc65ceb2eda826f7d19ae07 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 20:09:45 +0000 Subject: [PATCH 039/100] havoc_reachable: arbitrary pointers must reach all compatible objects 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 --- doc/cprover-manual/modeling-inline-asm.md | 12 ++--- .../main.c | 5 +++ .../test.desc | 4 ++ src/goto-symex/symex_havoc_reachable.cpp | 44 ++++++++++++++++--- 4 files changed, 52 insertions(+), 13 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 311f0c95aed9..a5424f0b9b73 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -207,12 +207,12 @@ member access such as `s.a` names the variable `s`. (counting the pointer's own previous value), and only until the pointers that one statement restricts to their candidates have 65536 candidate values in total. Otherwise, the pointer is assigned an arbitrary value, - and a warning is printed. Such a pointer may - point to any object whose address is stored anywhere, or be invalid: - dereferencing it considers all these objects, which is slow if there are - many, and the pointer checks of the dereference fail. Pointers in unions and - in arrays of more than 64 elements, or of a size that is not constant, are - assigned arbitrary values. + and a warning is printed. Such a pointer may point to any object whose + address is stored anywhere, to any reachable object of a compatible type, + or be invalid: dereferencing it considers all these objects, which is slow + if there are many, and the pointer checks of the dereference fail. + Pointers in unions and in arrays of more than 64 elements, or of a size + that is not constant, are assigned arbitrary values. - Constant objects are not changed. - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value diff --git a/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c b/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c index 5fc0e4c864cd..f1fc020bd2b4 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c @@ -88,5 +88,10 @@ int main(void) __CPROVER_assert(p != &g69, "many candidates"); __CPROVER_assert(p == &g00, "previous value"); __CPROVER_assert(sp == &s1 || sp == &s2 || sp == 0, "few candidates"); + // the assembly may have stored &g69 in p, although no pointer pointed to + // g69 before + g69 = 0; + *p = 1; + __CPROVER_assert(g69 == 0, "write through the pointer"); return 0; } diff --git a/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc index c844c673bf6c..b82425dbb331 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc @@ -7,6 +7,7 @@ main.c ^\[main\.assertion\.1\] line 88 many candidates: FAILURE$ ^\[main\.assertion\.2\] line 89 previous value: FAILURE$ ^\[main\.assertion\.3\] line 90 few candidates: SUCCESS$ +^\[main\.assertion\.4\] line 95 write through the pointer: FAILURE$ ^VERIFICATION FAILED$ -- ^warning: ignoring @@ -16,3 +17,6 @@ havoc_reachable statement changes to its candidate values (previous values, addresses of reachable objects, null) only if there are at most 64 of them. Restricting p to the first 64 candidates would exclude &g69, which the assembly may store in p. +The value set of such an arbitrary pointer must contain the reachable objects +of a compatible type, such as g69, even if no pointer pointed to them: +otherwise, writing through p cannot change g69. diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index a291ab6c8886..2d405d6dcc97 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -836,17 +836,20 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) // An arbitrary pointer: a temporary that is never assigned, and hence // unconstrained, whose value set is that of a nondeterministic pointer (any - // object in the value set, or null). Assigning a nondeterministic pointer - // instead would compute this value set anew for each pointer, visiting the - // value sets of all pointers assigned before: the time would grow - // quadratically with the number of such pointers. Instead, the value set is - // computed once per statement, and shared. + // object in the value set, or null), plus the reachable objects of a + // compatible type, whose addresses the statement may store even if no + // pointer points to them. Assigning a nondeterministic pointer instead + // would compute this value set anew for each pointer, visiting the value + // sets of all pointers assigned before: the time would grow quadratically + // with the number of such pointers. Instead, the value set is computed once + // per statement (and target type), and shared. + const typet void_pointer = pointer_type(empty_typet{}); std::optional any_pointer; + std::unordered_map any_pointer_by_type; auto arbitrary_pointer = [&](const typet &type) { if(!any_pointer.has_value()) { - const typet void_pointer = pointer_type(empty_typet{}); any_pointer = state.rename(new_temporary("any_pointer", void_pointer), ns).get(); state.value_set.assign( @@ -856,9 +859,36 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) true, false); } + const typet key = is_generic_pointer(type) + ? typet{empty_typet{}} + : to_pointer_type(type).base_type(); + auto any_of_type = any_pointer_by_type.find(key); + if(any_of_type == any_pointer_by_type.end()) + { + const exprt pointer = + state.rename(new_temporary("any_pointer", void_pointer), ns).get(); + state.value_set.assign(pointer, *any_pointer, ns, true, false); + value_sett::object_mapt compatible; + for(std::size_t j = pointers.size(); j < candidates.size(); ++j) + { + if(is_compatible_pointer(type, candidates[j].type())) + { + state.value_set.insert( + compatible, + candidate_objects[j - pointers.size()], + value_sett::offsett{}); + } + } + state.value_set.update_entry( + value_sett::entryt{to_ssa_expr(pointer).get_identifier(), ""}, + void_pointer, + compatible, + true); + any_of_type = any_pointer_by_type.emplace(key, pointer).first; + } const symbol_exprt result = new_temporary("arbitrary_pointer", type); state.value_set.assign( - state.rename(result, ns).get(), *any_pointer, ns, true, false); + state.rename(result, ns).get(), any_of_type->second, ns, true, false); return result; }; From f8362ba08f79044bebb226916dd45383dd9ca5a0 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 20:12:32 +0000 Subject: [PATCH 040/100] havoc_reachable: pointers in unions and large arrays may point anywhere 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 --- doc/cprover-manual/modeling-inline-asm.md | 3 +- .../inline_asm_havoc_reachable_union/main.c | 59 +++++++++++++++ .../test.desc | 24 +++++++ src/goto-symex/symex_havoc_reachable.cpp | 72 +++++++++++++++++++ 4 files changed, 157 insertions(+), 1 deletion(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_union/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_union/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a5424f0b9b73..ebde88dadb98 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -212,7 +212,8 @@ member access such as `s.a` names the variable `s`. or be invalid: dereferencing it considers all these objects, which is slow if there are many, and the pointer checks of the dereference fail. Pointers in unions and in arrays of more than 64 elements, or of a size - that is not constant, are assigned arbitrary values. + that is not constant, are assigned arbitrary values as well, and a warning + is printed. - Constant objects are not changed. - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value diff --git a/regression/cbmc/inline_asm_havoc_reachable_union/main.c b/regression/cbmc/inline_asm_havoc_reachable_union/main.c new file mode 100644 index 000000000000..7be153377800 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_union/main.c @@ -0,0 +1,59 @@ +// Inline assembly that is not modeled may store any reachable object's address +// in the pointers stored in unions and in large arrays, which symbolic +// execution does not split into their pointers. Writing through these pointers +// after the statement may thus change y, although no pointer pointed to y. +int x, y; + +union U +{ + int *p; + char *q; + long l; +} u; + +struct S +{ + int a; + union U u; +} s; + +union V +{ + struct + { + int *p; + } st; + long l; +} v; + +int *big[100]; +union U unions[100]; + +int main(void) +{ + u.p = &x; + s.u.p = &x; + v.st.p = &x; + big[5] = &x; + unions[7].p = &x; + asm volatile("cli" ::: "memory"); + y = 0; + *u.p = 1; + __CPROVER_assert(y == 0, "first member of a union"); // fails + y = 0; + *u.q = 1; + __CPROVER_assert(y == 0, "second member of a union"); // fails + y = 0; + *s.u.p = 1; + __CPROVER_assert(y == 0, "union in a struct"); // fails + y = 0; + *v.st.p = 1; + __CPROVER_assert(y == 0, "struct in a union"); // fails + y = 0; + *big[3] = 1; + __CPROVER_assert(y == 0, "large array"); // fails + y = 0; + *unions[9].p = 1; + __CPROVER_assert(y == 0, "large array of unions"); // fails + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_union/test.desc b/regression/cbmc/inline_asm_havoc_reachable_union/test.desc new file mode 100644 index 000000000000..741de80410bb --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_union/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c +--no-standard-checks +^EXIT=10$ +^SIGNAL=0$ +^havocking the objects reachable at file main\.c line 39 function main: some pointers are stored in unions or in arrays of more than 64 elements \(or of a size that is not constant\), and are assigned arbitrary values$ +^\[main\.assertion\.1\] line 42 first member of a union: FAILURE$ +^\[main\.assertion\.2\] line 45 second member of a union: FAILURE$ +^\[main\.assertion\.3\] line 48 union in a struct: FAILURE$ +^\[main\.assertion\.4\] line 51 struct in a union: FAILURE$ +^\[main\.assertion\.5\] line 54 large array: FAILURE$ +^\[main\.assertion\.6\] line 57 large array of unions: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The havoc_reachable statement assigns unions, and arrays of more than 64 +elements, a nondeterministic value as a whole. The value set of a pointer in a +union then had only unknown targets (and that of an element of a large array +kept its previous targets), so that dereferencing it after the statement could +not yield y, and the assertions held. The pointers in these objects are now +assigned arbitrary values, whose value set contains all reachable objects of a +compatible type. Without --no-standard-checks, the pointer checks of these +dereferences fail. diff --git a/src/goto-symex/symex_havoc_reachable.cpp b/src/goto-symex/symex_havoc_reachable.cpp index 2d405d6dcc97..2c4797cd4b39 100644 --- a/src/goto-symex/symex_havoc_reachable.cpp +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -17,6 +17,8 @@ Author: Michael Tautschnig #include #include +#include + #include #include "goto_symex.h" @@ -145,6 +147,42 @@ static void split_lvalue( others.push_back(lvalue); } +/// Appends to \p leaves the pointers to data that \p lvalue contains, +/// descending into structs, unions and arrays. For an array, the element at +/// an index returned by \p new_index stands for all elements. +/// \param lvalue: An object or a part of an object +/// \param ns: Namespace +/// \param new_index: Returns a fresh nondeterministic value of a given type +/// \param [out] leaves: The pointers +static void pointer_leaves( + const exprt &lvalue, + const namespacet &ns, + const std::function &new_index, + std::vector &leaves) +{ + const typet &type = lvalue.type(); + if(is_data_pointer(type)) + leaves.push_back(lvalue); + else if(!contains_data_pointer(type, ns)) + return; + else if(type.id() == ID_array) + { + pointer_leaves( + index_exprt{lvalue, new_index(to_array_type(type).index_type())}, + ns, + new_index, + leaves); + } + else if(type.id() == ID_struct_tag || type.id() == ID_union_tag) + { + for(const auto &component : + ns.follow_tag(to_struct_or_union_tag_type(type)).components()) + { + pointer_leaves(member_exprt{lvalue, component}, ns, new_index, leaves); + } + } +} + /// \return The size of the objects that pointers of type \p type point to: /// 1 for `void *` and for pointers to objects of unknown size. static mp_integer pointee_size(const typet &type, const namespacet &ns) @@ -1038,6 +1076,29 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) symex_assign(state, pointer, value); } + // The pointers in the parts that are not split into their pointers (unions, + // and arrays that are large or of a size that is not constant): assigning + // such a part a nondeterministic value gives its pointers unknown targets + // (or keeps their previous targets, for arrays), which dereferencing does + // not resolve to the objects the statement may store pointers to. Assign + // the pointers arbitrary values instead, whose value set contains these + // objects. The element of an array at a nondeterministic index stands for + // all its elements (assignments to array elements add to the value set). + bool unsplit_pointers = false; + for(const auto &other : others) + { + std::vector leaves; + pointer_leaves(other, ns, new_value, leaves); + for(auto &leaf : leaves) + { + unsplit_pointers = true; + const exprt pointer = arbitrary_pointer(leaf.type()); + // members of unions are accessed by byte extraction + rewrite_union(leaf); + symex_assign(state, leaf, pointer); + } + } + // The objects that dereferencing pointers with unknown targets yields are // changed above where symbolic execution keeps them (the failed objects of // pointer variables). Other targets are not. @@ -1057,6 +1118,17 @@ void goto_symext::symex_havoc_reachable(statet &state, const codet &code) << messaget::eom; } + if(unsplit_pointers) + { + log.warning() << "havocking the objects reachable at " << source_location + << ": some pointers are stored in unions or in arrays of " + "more than " + << max_array_elements + << " elements (or of a size that is not constant), and are " + "assigned arbitrary values" + << messaget::eom; + } + if(too_many_choices) { log.warning() << "havocking the objects reachable at " << source_location From 20bdbab0ef5ab921efca4c6df8405f023a6fa2d1 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 20:15:07 +0000 Subject: [PATCH 041/100] havoc_reachable: test the value-set fallback and path exploration 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 --- doc/cprover-manual/modeling-inline-asm.md | 7 ++ .../paths-lifo.desc | 20 ++++ .../main.c | 92 +++++++++++++++++++ .../test.desc | 16 ++++ 4 files changed, 135 insertions(+) create mode 100644 regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c create mode 100644 regression/goto-instrument/show-value-sets-havoc-reachable-unknown/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index ebde88dadb98..c7402cd2d3a3 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -215,6 +215,13 @@ member access such as `s.a` names the variable `s`. that is not constant, are assigned arbitrary values as well, and a warning is printed. - Constant objects are not changed. +- Objects of static lifetime that the CPROVER library adds to the program + (such as `optind` for `getopt`) are changed like the objects of the + program. Objects whose names start with `__CPROVER_` hold CBMC's internal + state (for example, the bookkeeping of dynamic memory) and are not + changed, except the rounding mode and `__CPROVER_memory` (see above). This + includes `__CPROVER_errno`, which models `errno`: the approximation assumes + that the statement does not change `errno`. - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value set analyses (as used by `goto-instrument`) and the reaching definitions and diff --git a/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc new file mode 100644 index 000000000000..4fe347dd14af --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c +--paths lifo +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 37 heap object reachable from static: FAILURE$ +^\[main\.assertion\.2\] line 38 pointer in static: FAILURE$ +^\[main\.assertion\.3\] line 39 pointers are restricted to known values: SUCCESS$ +^\[main\.assertion\.4\] line 50 escaped local of caller: FAILURE$ +^\[main\.assertion\.5\] line 51 local without address: SUCCESS$ +^\[main\.assertion\.6\] line 59 heap object reachable from operand: FAILURE$ +^\[main\.assertion\.7\] line 60 unreachable heap object: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +dereference failure.*: FAILURE$ +-- +With path exploration, symbolic execution executes the havoc_reachable +statement once per path, with the value set of that path, and gives the same +verdicts as test.desc. diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c new file mode 100644 index 000000000000..633af1f5c3cb --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c @@ -0,0 +1,92 @@ +// More than 64 reachable objects of a compatible type: the value-set +// analyses give a pointer that the inline assembly may change an unknown +// target instead of listing all of them. +int g00; +int g01; +int g02; +int g03; +int g04; +int g05; +int g06; +int g07; +int g08; +int g09; +int g10; +int g11; +int g12; +int g13; +int g14; +int g15; +int g16; +int g17; +int g18; +int g19; +int g20; +int g21; +int g22; +int g23; +int g24; +int g25; +int g26; +int g27; +int g28; +int g29; +int g30; +int g31; +int g32; +int g33; +int g34; +int g35; +int g36; +int g37; +int g38; +int g39; +int g40; +int g41; +int g42; +int g43; +int g44; +int g45; +int g46; +int g47; +int g48; +int g49; +int g50; +int g51; +int g52; +int g53; +int g54; +int g55; +int g56; +int g57; +int g58; +int g59; +int g60; +int g61; +int g62; +int g63; +int g64; +int g65; +int g66; +int g67; +int g68; +int g69; +int *p = &g00; + +struct S +{ + int x; +} s1, s2; +struct S *sp = &s1; + +int main() +{ +#ifdef __GNUC__ + asm volatile("cli" ::: "memory"); +#else + __asm { cli } +#endif + int *r = p; + struct S *t = sp; + return 0; +} diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/test.desc b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/test.desc new file mode 100644 index 000000000000..d41c40abee95 --- /dev/null +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/test.desc @@ -0,0 +1,16 @@ +CORE +main.c +--show-value-sets +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +\nmain::1::r = \{ , unknown \} +\nmain::1::t = \{ , ,\s* \} +-- +^warning: ignoring +\nmain::1::r = \{[^}]* Date: Tue, 1 Dec 2026 20:19:28 +0000 Subject: [PATCH 042/100] Do not run two slow havoc_reachable tests with the new SMT backend 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 --- regression/cbmc/inline_asm_havoc_reachable_array/test.desc | 4 +++- regression/cbmc/inline_asm_havoc_reachable_budget/test.desc | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/regression/cbmc/inline_asm_havoc_reachable_array/test.desc b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc index 7cddc39504f4..6ac93e0bded2 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_array/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc @@ -1,4 +1,4 @@ -CORE gcc-only +CORE gcc-only no-new-smt main.c ^EXIT=10$ @@ -15,3 +15,5 @@ symbol that field-sensitive symbolic execution has for it, expanded all 4096 elements for each of the 4096 assignments: symbolic execution took 80 s instead of 0.5 s. The test thus checks a time bound when run with a timeout (test.pl -t). +The test is not run with the new SMT backend (no-new-smt), with which it took +57 s (z3), as the solver is not what it checks. diff --git a/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc index 81aaf1ac4593..093270e3c232 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc @@ -1,4 +1,4 @@ -CORE gcc-only +CORE gcc-only no-new-smt main.c ^EXIT=10$ @@ -16,3 +16,5 @@ are their pointers. 16 arrays (1008 pointers with 64 candidates each) and the first 16 elements of t16s are restricted to their candidates, which keeps them within the array of their type (or null). The other 47 pointers of t16s are assigned arbitrary values, which may point anywhere. +The test is not run with the new SMT backend (no-new-smt), with which it took +31 s (z3). From d2f261554cd20fad35337014641198fe899ff50f Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Thu, 3 Dec 2026 17:35:39 +0000 Subject: [PATCH 043/100] havoc_reachable: change errno and the other program state of the library A statement that may access arbitrary memory changes all objects of static lifetime, except the objects that CPROVER uses internally, which static_lifetime_objects recognised by the __CPROVER_ prefix of their names. The C library model also uses that prefix for memory that the program accesses: errno is *__errno_location(), which is __CPROVER_errno, and getpwnam and getpwuid return &__CPROVER_passwd. CBMC thus proved that errno == 0 and pw->pw_uid keep their values over an unmodeled statement with a "memory" clobber, which may, for example, call a function that sets errno. Treat __CPROVER_errno, __CPROVER_passwd, and __CPROVER_fpu_control_word (the x87 control word that the _controlfp model reads, which assembly may change as it may change the rounding mode) as objects of the program. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 8 +++--- .../inline_asm_havoc_reachable_errno/main.c | 25 +++++++++++++++++++ .../test.desc | 17 +++++++++++++ src/pointer-analysis/reachable_objects.cpp | 21 ++++++++++++++-- src/pointer-analysis/reachable_objects.h | 8 +++--- 5 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 regression/cbmc/inline_asm_havoc_reachable_errno/main.c create mode 100644 regression/cbmc/inline_asm_havoc_reachable_errno/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index c7402cd2d3a3..86ae53d68191 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -219,9 +219,11 @@ member access such as `s.a` names the variable `s`. (such as `optind` for `getopt`) are changed like the objects of the program. Objects whose names start with `__CPROVER_` hold CBMC's internal state (for example, the bookkeeping of dynamic memory) and are not - changed, except the rounding mode and `__CPROVER_memory` (see above). This - includes `__CPROVER_errno`, which models `errno`: the approximation assumes - that the statement does not change `errno`. + changed, except the rounding mode, `__CPROVER_memory` (see above), and the + objects of the library that stand for state the program can access: + `__CPROVER_errno` (`errno`), `__CPROVER_passwd` (the result of `getpwnam` + and `getpwuid`), and `__CPROVER_fpu_control_word` (the control word of + `_controlfp`). - Symbolic execution (`cbmc`) computes the reachable objects most precisely. The static analyses use their own pointer analyses: the value set analyses (as used by `goto-instrument`) and the reaching definitions and diff --git a/regression/cbmc/inline_asm_havoc_reachable_errno/main.c b/regression/cbmc/inline_asm_havoc_reachable_errno/main.c new file mode 100644 index 000000000000..0a89985bd47c --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_errno/main.c @@ -0,0 +1,25 @@ +#include +#include + +// errno and the result of getpwnam are objects of the C library model whose +// names start with __CPROVER_, but they are memory that the program can +// access: a statement that may access arbitrary memory may change them, for +// example by calling a function that sets errno. +int main(void) +{ + errno = 0; + struct passwd *pw = getpwnam("root"); + __CPROVER_assume(pw != 0); + unsigned uid = pw->pw_uid; + + int r; + __asm__ volatile("nonexistent_instruction %0" : "=r"(r)); + __CPROVER_assert(errno == 0, "errno unchanged by operands only"); + __CPROVER_assert(pw->pw_uid == uid, "passwd unchanged by operands only"); + + __asm__ volatile("nonexistent_instruction" ::: "memory"); + __CPROVER_assert(errno == 0, "errno unchanged"); // fails + __CPROVER_assert(pw->pw_uid == uid, "passwd unchanged"); // fails + + return 0; +} diff --git a/regression/cbmc/inline_asm_havoc_reachable_errno/test.desc b/regression/cbmc/inline_asm_havoc_reachable_errno/test.desc new file mode 100644 index 000000000000..5654e90d8efc --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_errno/test.desc @@ -0,0 +1,17 @@ +CORE gcc-only +main.c +--arch riscv64 --no-standard-checks +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 17 errno unchanged by operands only: SUCCESS$ +^\[main\.assertion\.2\] line 18 passwd unchanged by operands only: SUCCESS$ +^\[main\.assertion\.3\] line 21 errno unchanged: FAILURE$ +^\[main\.assertion\.4\] line 22 passwd unchanged: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +A statement with a "memory" clobber may change all objects of static lifetime, +including __CPROVER_errno, which models errno, and __CPROVER_passwd, which +getpwnam returns. Both were treated as internal objects of CPROVER and kept +their values. diff --git a/src/pointer-analysis/reachable_objects.cpp b/src/pointer-analysis/reachable_objects.cpp index 74ffb8b712bb..9a12571d6ca1 100644 --- a/src/pointer-analysis/reachable_objects.cpp +++ b/src/pointer-analysis/reachable_objects.cpp @@ -151,6 +151,24 @@ reachable_objectst find_reachable_objects( return result; } +/// \return True iff \p symbol is an object that CPROVER uses internally, for +/// example for the bookkeeping of dynamic memory. Objects of the C library +/// model that stand for state that the program can access are not internal, +/// although their names start with `__CPROVER_`: `errno`, the result of +/// `getpwnam` and `getpwuid`, and the floating-point control word of +/// `_controlfp`. +static bool is_internal_object(const symbolt &symbol) +{ + static const std::set program_state = { + CPROVER_PREFIX "errno", + CPROVER_PREFIX "passwd", + CPROVER_PREFIX "fpu_control_word"}; + if(program_state.count(symbol.name) != 0) + return false; + return symbol.name.starts_with(CPROVER_PREFIX) || + symbol.base_name.starts_with(CPROVER_PREFIX); +} + std::vector static_lifetime_objects( const symbol_table_baset &symbol_table, const namespacet &ns) @@ -162,8 +180,7 @@ std::vector static_lifetime_objects( if( symbol.is_static_lifetime && !symbol.is_type && !symbol.is_macro && symbol.is_lvalue && is_complete_type(symbol.type, ns) && - !symbol.name.starts_with(CPROVER_PREFIX) && - !symbol.base_name.starts_with(CPROVER_PREFIX)) + !is_internal_object(symbol)) { result.push_back(symbol.symbol_expr()); } diff --git a/src/pointer-analysis/reachable_objects.h b/src/pointer-analysis/reachable_objects.h index 6575bedfd80a..d852ef8c9cb6 100644 --- a/src/pointer-analysis/reachable_objects.h +++ b/src/pointer-analysis/reachable_objects.h @@ -60,9 +60,11 @@ reachable_objectst find_reachable_objects( const namespacet &ns); /// \return The objects of static lifetime in \p symbol_table, excluding -/// objects of incomplete type and objects used internally by CPROVER, -/// sorted by name. Constant objects are included, as they may contain -/// pointers to objects that can be modified. +/// objects of incomplete type and objects used internally by CPROVER +/// (but including the objects of the C library model that stand for state +/// the program can access, such as `__CPROVER_errno`), sorted by name. +/// Constant objects are included, as they may contain pointers to objects +/// that can be modified. std::vector static_lifetime_objects( const symbol_table_baset &symbol_table, const namespacet &ns); From 8a31e28b19e883bf88e0f96e07b039f0a5b82315 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 13:20:48 +0000 Subject: [PATCH 044/100] asm goto: jump to the label the statement chooses 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 #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 --- doc/cprover-manual/modeling-inline-asm.md | 9 ++-- regression/cbmc/inline_asm_goto/main.c | 38 ++++++++++++++ regression/cbmc/inline_asm_goto/test.desc | 18 +++++++ regression/goto-cc-file-local/asm-goto/main.c | 44 ++++++++++++++++ .../goto-cc-file-local/asm-goto/test.desc | 13 +++++ src/ansi-c/expr2c.cpp | 2 +- src/ansi-c/goto-conversion/goto_asm.cpp | 52 +++++++++++++++++++ src/assembler/asm_approximation.cpp | 5 +- src/assembler/asm_approximation.h | 7 ++- src/assembler/remove_asm.cpp | 13 +++++ src/util/std_code.h | 36 ++++++++++++- 11 files changed, 230 insertions(+), 7 deletions(-) create mode 100644 regression/cbmc/inline_asm_goto/main.c create mode 100644 regression/cbmc/inline_asm_goto/test.desc create mode 100644 regression/goto-cc-file-local/asm-goto/main.c create mode 100644 regression/goto-cc-file-local/asm-goto/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 86ae53d68191..379a54c04abe 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -25,6 +25,9 @@ models it. Such a statement only writes its output operands (see Output Operands below); without outputs, as in the compiler barrier `asm volatile("" ::: "memory")`, it does nothing. +None of the modeled instructions jumps, so an `asm goto` statement whose +instructions are all modeled continues with the next statement. + ### Supported Instructions CBMC splits the assembler text into instructions at newlines and `;`, except @@ -131,7 +134,9 @@ instruction that is not modeled, then all objects reachable from these are assigned nondeterministic values; 4. the output operands are assigned nondeterministic values, at the addresses they had before the statement and, for outputs whose address - depends on the program state, also at the addresses they have after it; + depends on the program state, also at the addresses they have after it, + and an `asm goto` statement jumps to any of its labels, or continues with + the next statement; 5. the rounding mode is assigned a nondeterministic value. Symbolic execution computes the reachable objects from the value sets of the @@ -244,8 +249,6 @@ member access such as `s.a` names the variable `s`. (`--mm`) ignores the statement: its writes are not delayed, but become visible to other threads at once. -- Control flow out of a statement is not modeled: `asm goto` statements - always continue with the next statement. - In C++ code, the C++ front end discards the operands and clobbers of GCC-style statements. Such a statement is thus treated as basic assembly: its outputs are not written (neither by the approximation nor as diff --git a/regression/cbmc/inline_asm_goto/main.c b/regression/cbmc/inline_asm_goto/main.c new file mode 100644 index 000000000000..e26ac4e336a1 --- /dev/null +++ b/regression/cbmc/inline_asm_goto/main.c @@ -0,0 +1,38 @@ +// asm goto: a statement that is not modeled may jump to any of its labels, or +// fall through; a modeled statement (none of the modeled instructions jumps) +// falls through. +static int branch(int *p) +{ + // not modeled: may jump to either label or fall through + asm goto("testl %0, %0; jz %l[zero]; jmp %l[nonzero]" + : + : "r"(*p) + : + : zero, nonzero); + return 0; +zero: + return 1; +nonzero: + return 2; +} + +static int modeled(void) +{ + // modeled, and does not jump + asm goto("nop" : : : : out); + return 0; +out: + return 1; +} + +int main(void) +{ + int x = 0; + int r = branch(&x); + __CPROVER_assert(r != 0, "falls through"); // fails + __CPROVER_assert(r != 1, "jumps to zero"); // fails + __CPROVER_assert(r != 2, "jumps to nonzero"); // fails + __CPROVER_assert(r >= 0 && r <= 2, "one of the labels"); // holds + __CPROVER_assert(modeled() == 0, "modeled statement does not jump"); // holds + return 0; +} diff --git a/regression/cbmc/inline_asm_goto/test.desc b/regression/cbmc/inline_asm_goto/test.desc new file mode 100644 index 000000000000..d72560f83fee --- /dev/null +++ b/regression/cbmc/inline_asm_goto/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c +--validate-goto-model --validate-ssa-equation +^EXIT=10$ +^SIGNAL=0$ +approximating inline assembly statement at .* function branch: instruction 'testl' is not modeled, so the choice of the label it jumps to \(if any\) +^\[main\.assertion\.1\] line 32 falls through: FAILURE$ +^\[main\.assertion\.2\] line 33 jumps to zero: FAILURE$ +^\[main\.assertion\.3\] line 34 jumps to nonzero: FAILURE$ +^\[main\.assertion\.4\] line 35 one of the labels: SUCCESS$ +^\[main\.assertion\.5\] line 36 modeled statement does not jump: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +goto conversion dispatches on a variable that the translation of the asm goto +statement sets to the label it jumps to: nondeterministically for a statement +that is approximated, and to "no jump" for a modeled one. diff --git a/regression/goto-cc-file-local/asm-goto/main.c b/regression/goto-cc-file-local/asm-goto/main.c new file mode 100644 index 000000000000..e16ef2e2fd16 --- /dev/null +++ b/regression/goto-cc-file-local/asm-goto/main.c @@ -0,0 +1,44 @@ +// asm goto in a file-local (static) function, as in the Linux kernel's +// arch_static_branch (static keys). goto-cc --export-file-local-symbols +// renames the symbols of such functions, which must include the variable that +// selects the label the asm goto jumps to. +struct static_key +{ + int enabled; +}; + +#ifdef __GNUC__ +# define ALWAYS_INLINE __attribute__((always_inline)) +#else +# define ALWAYS_INLINE +#endif + +static inline ALWAYS_INLINE _Bool +arch_static_branch(struct static_key *const key, const _Bool branch) +{ +#ifdef __GNUC__ + asm goto( + "1: jmp %l[l_yes]\n\t" + ".pushsection __jump_table, \"aw\"\n\t" + ".long 1b - . \n\t" + ".popsection\n\t" + : + : "i"(key), "i"(branch) + : + : l_yes); + return 0; +l_yes: + return 1; +#else + return branch; +#endif +} + +struct static_key kc; + +int main(void) +{ + int x = arch_static_branch(&kc, 1) ? 1 : 0; + __CPROVER_assert(x <= 1, "x"); + return 0; +} diff --git a/regression/goto-cc-file-local/asm-goto/test.desc b/regression/goto-cc-file-local/asm-goto/test.desc new file mode 100644 index 000000000000..6b20f4ecb6d8 --- /dev/null +++ b/regression/goto-cc-file-local/asm-goto/test.desc @@ -0,0 +1,13 @@ +CORE +main.c +compile-and-link assertion-check +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +^\*\*\*\* WARNING: no body for function +-- +goto-cc --export-file-local-symbols renames the symbols of file-local +functions. The variable that selects the label an asm goto jumps to must be +renamed with them, else symbolic execution fails to find it. diff --git a/src/ansi-c/expr2c.cpp b/src/ansi-c/expr2c.cpp index 6305d6f6b005..0ab40dfc11d0 100644 --- a/src/ansi-c/expr2c.cpp +++ b/src/ansi-c/expr2c.cpp @@ -2590,7 +2590,7 @@ std::string expr2ct::convert_code_asm( if(src.get_flavor()==ID_gcc) { - if(src.operands().size()==5) + if(src.operands().size() == 5 || src.operands().size() == 6) { dest+="asm("; dest+=convert(src.op0()); diff --git a/src/ansi-c/goto-conversion/goto_asm.cpp b/src/ansi-c/goto-conversion/goto_asm.cpp index 370f9cc68232..9058994d09c6 100644 --- a/src/ansi-c/goto-conversion/goto_asm.cpp +++ b/src/ansi-c/goto-conversion/goto_asm.cpp @@ -11,8 +11,14 @@ Author: Daniel Kroening, kroening@kroening.com #include "goto_convert_class.h" +#include +#include +#include + #include "destructor.h" +#include + void goto_convertt::convert_asm( const code_asmt &code, goto_programt &dest, @@ -44,7 +50,53 @@ void goto_convertt::convert_asm( } dest.destructive_append(side_effects.side_effects); + // asm goto: the translation of the statement (see remove_asm) records the + // label it jumps to in a variable, which is dispatched on below + std::vector labels; + for(const auto &label : new_code.labels().operands()) + labels.push_back(label.get(ID_identifier)); + + std::optional goto_target; + if(!labels.empty()) + { + goto_target = new_tmp_symbol( + unsigned_int_type(), + "asm_goto_target", + dest, + code.source_location(), + mode) + .symbol_expr(); + new_code.add_goto_target(*goto_target); + } + copy(new_code, OTHER, dest); + // the operands are no longer needed once the statement has executed destruct_locals(side_effects.temporaries, dest, ns); + + if(!goto_target.has_value()) + return; + + // Jump to the label with the (1-based) index the statement chose, if any. + // These are ordinary gotos, converted as such so that leaving scopes is + // handled like for any other goto. + code_deadt dead{*goto_target}; + dead.add_source_location() = code.source_location(); + for(std::size_t i = 0; i < labels.size(); ++i) + { + code_gotot code_goto{labels[i]}; + code_goto.add_source_location() = code.source_location(); + + code_blockt then_case{{dead, std::move(code_goto)}}; + then_case.add_source_location() = code.source_location(); + + code_ifthenelset if_goto{ + equal_exprt{*goto_target, from_integer(i + 1, goto_target->type())}, + std::move(then_case)}; + if_goto.add_source_location() = code.source_location(); + + convert(if_goto, dest, mode); + } + + dest.add(goto_programt::make_dead(*goto_target, code.source_location())); } diff --git a/src/assembler/asm_approximation.cpp b/src/assembler/asm_approximation.cpp index 78fab0063821..4d7588352fc1 100644 --- a/src/assembler/asm_approximation.cpp +++ b/src/assembler/asm_approximation.cpp @@ -273,7 +273,8 @@ void asm_approximationt::operator()( // 4. the outputs, at their addresses before the statement and, as // compilers differ in when they compute the address of an output (GCC at // -O0 computes it after the statement has written the other outputs, other - // compilers and optimization levels before), at their addresses after it + // compilers and optimization levels before), at their addresses after it; + // and whether and where the statement jumps for(const auto &write : writes) havoc_lvalue(write, source_location, dest); for(const auto &write : footprint.writes) @@ -281,6 +282,8 @@ void asm_approximationt::operator()( if(has_state_dependent_address(write)) havoc_lvalue(write, source_location, dest); } + if(footprint.goto_target.has_value()) + havoc_lvalue(*footprint.goto_target, source_location, dest); // 5. the floating-point rounding mode, which the statement may change via // the control registers of the floating-point unit diff --git a/src/assembler/asm_approximation.h b/src/assembler/asm_approximation.h index 784fbc494b6c..084ade89b792 100644 --- a/src/assembler/asm_approximation.h +++ b/src/assembler/asm_approximation.h @@ -47,6 +47,11 @@ struct asm_footprintt /// Whether the statement may access memory not described by its operands /// (a "memory" clobber, basic assembly, or an MSVC-style block). bool arbitrary_memory = false; + + /// For an `asm goto` statement: the variable that selects the label the + /// statement jumps to (see \ref code_asm_gcct::goto_target). The statement + /// may jump to any of its labels, or not jump. + std::optional goto_target; }; /// Builds the instructions that conservatively approximate an inline assembly @@ -71,7 +76,7 @@ class asm_approximationt /// 4. assign nondeterministic values to the writes, at the addresses they /// had before the statement and, for writes whose address depends on the /// program state, also at the addresses they have after it, as compilers - /// differ in when they compute these addresses; + /// differ in when they compute these addresses; and to the goto target; /// 5. assign a nondeterministic rounding mode. /// \param footprint: What the statement may read and write /// \param function_id: Name of the enclosing function, which temporaries diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 139c65d9d717..d10cc787afbb 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -15,6 +15,7 @@ Date: December 2014 #include "remove_asm.h" +#include #include #include #include @@ -348,6 +349,8 @@ void remove_asmt::approximate_asm( parts.push_back(writes_description); if(!footprint.addresses.empty()) parts.push_back(addresses_description); + if(footprint.goto_target.has_value()) + parts.push_back("the choice of the label it jumps to (if any)"); if(footprint.arbitrary_memory) { parts.push_back("all objects of static lifetime"); @@ -596,10 +599,20 @@ void remove_asmt::process_instruction_gcc( function_id, code.source_location(), dest); + + // none of the modeled instructions jumps + if(code.has_goto_target()) + { + const exprt &target = code.goto_target(); + dest.add(goto_programt::make_assignment( + target, from_integer(0, target.type()), code.source_location())); + } return; } asm_footprintt footprint; + if(code.has_goto_target()) + footprint.goto_target = code.goto_target(); for(const auto &output : code.outputs().operands()) { diff --git a/src/util/std_code.h b/src/util/std_code.h index 41f137b3dcf0..732c6d22ab27 100644 --- a/src/util/std_code.h +++ b/src/util/std_code.h @@ -1352,6 +1352,36 @@ class code_asm_gcct : public code_asmt return operands()[4]; } + /// \return True iff goto conversion has recorded the variable that selects + /// the label an `asm goto` statement jumps to (see \ref goto_target). + bool has_goto_target() const + { + return operands().size() == 6; + } + + /// The variable that the translation of an `asm goto` statement sets to the + /// (1-based) index of the label it jumps to, or to 0 if it does not jump. + /// This is an operand (rather than a named sub-tree) so that renaming the + /// symbols of a function also renames it. + exprt &goto_target() + { + PRECONDITION(has_goto_target()); + return operands()[5]; + } + + const exprt &goto_target() const + { + PRECONDITION(has_goto_target()); + return operands()[5]; + } + + /// Records \p target as the variable described at \ref goto_target. + void add_goto_target(exprt target) + { + PRECONDITION(operands().size() == 5); + operands().push_back(std::move(target)); + } + protected: using code_asmt::op0; using code_asmt::op1; @@ -1367,7 +1397,11 @@ inline bool can_cast_expr(const exprt &base) inline void validate_expr(const code_asm_gcct &x) { - validate_operands(x, 5, "code_asm_gcc must have five operands"); + // the template, outputs, inputs, clobbers, and labels, and possibly the + // variable that selects the label of an asm goto + DATA_INVARIANT( + x.operands().size() == 5 || x.operands().size() == 6, + "code_asm_gcc must have five or six operands"); } inline code_asm_gcct &to_code_asm_gcc(codet &code) From 9fc65d8b80d081cdfc73b8ffbbc8db2e47375b27 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:04:05 +0000 Subject: [PATCH 045/100] goto-cc-file-local/asm-goto: check that the jump may be taken 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 --- regression/goto-cc-file-local/asm-goto/main.c | 6 ++++-- regression/goto-cc-file-local/asm-goto/test.desc | 10 +++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/regression/goto-cc-file-local/asm-goto/main.c b/regression/goto-cc-file-local/asm-goto/main.c index e16ef2e2fd16..586c59b6b3d1 100644 --- a/regression/goto-cc-file-local/asm-goto/main.c +++ b/regression/goto-cc-file-local/asm-goto/main.c @@ -1,7 +1,8 @@ // asm goto in a file-local (static) function, as in the Linux kernel's // arch_static_branch (static keys). goto-cc --export-file-local-symbols // renames the symbols of such functions, which must include the variable that -// selects the label the asm goto jumps to. +// selects the label the asm goto jumps to: else symbolic execution fails to +// find it, or the jump is lost and control always reaches "return 0". struct static_key { int enabled; @@ -39,6 +40,7 @@ struct static_key kc; int main(void) { int x = arch_static_branch(&kc, 1) ? 1 : 0; - __CPROVER_assert(x <= 1, "x"); + __CPROVER_assert(x <= 1, "x"); // holds + __CPROVER_assert(x == 0, "jump is not taken"); // fails: the jump may be taken return 0; } diff --git a/regression/goto-cc-file-local/asm-goto/test.desc b/regression/goto-cc-file-local/asm-goto/test.desc index 6b20f4ecb6d8..39026da38cc8 100644 --- a/regression/goto-cc-file-local/asm-goto/test.desc +++ b/regression/goto-cc-file-local/asm-goto/test.desc @@ -1,13 +1,17 @@ CORE main.c compile-and-link assertion-check -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.1\] line 43 x: SUCCESS$ +^\[main\.assertion\.2\] line 44 jump is not taken: FAILURE$ +^VERIFICATION FAILED$ -- ^warning: ignoring ^\*\*\*\* WARNING: no body for function -- goto-cc --export-file-local-symbols renames the symbols of file-local functions. The variable that selects the label an asm goto jumps to must be -renamed with them, else symbolic execution fails to find it. +renamed with them, else symbolic execution fails to find it (and crashes), or +the dispatch on it is lost, in which case the jump is never taken and the +second assertion holds. From a869a2a76eb3d10dc8ff06c9407795f0c7875da5 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:07:00 +0000 Subject: [PATCH 046/100] Test asm goto statements that leave a block with local variables 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 --- regression/cbmc/inline_asm_goto_scope/main.c | 53 +++++++++++++++++++ .../cbmc/inline_asm_goto_scope/test.desc | 21 ++++++++ 2 files changed, 74 insertions(+) create mode 100644 regression/cbmc/inline_asm_goto_scope/main.c create mode 100644 regression/cbmc/inline_asm_goto_scope/test.desc diff --git a/regression/cbmc/inline_asm_goto_scope/main.c b/regression/cbmc/inline_asm_goto_scope/main.c new file mode 100644 index 000000000000..a4f091f74681 --- /dev/null +++ b/regression/cbmc/inline_asm_goto_scope/main.c @@ -0,0 +1,53 @@ +// asm goto statements that leave a block with local variables, jumping +// forwards and backwards. Whether they jump depends on a nondeterministic +// value, so they may jump to their label or fall through, whether or not +// their instructions are modeled. +int nondet_int(void); + +int *q; + +static int forward(void) +{ + int r = 0; + { + int c = nondet_int(); + int y = 5; + int *p = &y; + q = p; + asm goto("testl %0, %0; jz %l[out]" : : "r"(c), "r"(p) : : out); + r = 1; + } + return r; +out: + __CPROVER_assert(r == 0, "forward: jumped before r = 1"); // holds + // the jump has left the block, which ends the lifetime of y + r = *q; // fails: dead object + return 2; +} + +static int backward(void) +{ + int n = 0; +again: +{ + int z = nondet_int(); + ++n; + if(n < 3) + asm goto("testl %0, %0; jnz %l[again]" : : "r"(z) : : again); +} + return n; +} + +int main(void) +{ + int r = forward(); + __CPROVER_assert(r != 1, "forward: falls through"); // fails + __CPROVER_assert(r != 2, "forward: jumps out of the block"); // fails + __CPROVER_assert(r == 1 || r == 2, "forward: one of the two"); // holds + + int n = backward(); + __CPROVER_assert(n != 1, "backward: falls through"); // fails + __CPROVER_assert(n != 3, "backward: jumps back twice"); // fails + __CPROVER_assert(n >= 1 && n <= 3, "backward: at most twice"); // holds + return 0; +} diff --git a/regression/cbmc/inline_asm_goto_scope/test.desc b/regression/cbmc/inline_asm_goto_scope/test.desc new file mode 100644 index 000000000000..16355009d1eb --- /dev/null +++ b/regression/cbmc/inline_asm_goto_scope/test.desc @@ -0,0 +1,21 @@ +CORE gcc-only +main.c +--validate-goto-model --validate-ssa-equation +^EXIT=10$ +^SIGNAL=0$ +^\[forward\.assertion\.1\] line 22 forward: jumped before r = 1: SUCCESS$ +^\[forward\.pointer_dereference\.\d+\] line 24 dereference failure: dead object in \*q: FAILURE$ +^\[main\.assertion\.1\] line 44 forward: falls through: FAILURE$ +^\[main\.assertion\.2\] line 45 forward: jumps out of the block: FAILURE$ +^\[main\.assertion\.3\] line 46 forward: one of the two: SUCCESS$ +^\[main\.assertion\.4\] line 49 backward: falls through: FAILURE$ +^\[main\.assertion\.5\] line 50 backward: jumps back twice: FAILURE$ +^\[main\.assertion\.6\] line 51 backward: at most twice: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +goto conversion lowers the jumps of an asm goto statement to ordinary gotos, +so that leaving a block ends the lifetime of its local variables (here y, which +a dereference after the forward jump finds dead) and a jump back to a label +before the statement forms a loop (here taken at most twice). From 79ff9011c85d06af946f6d5c1dc9f7cdca25c70e Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:16:42 +0000 Subject: [PATCH 047/100] dump-c: print asm goto statements with their labels 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 --- regression/goto-instrument/CMakeLists.txt | 7 ++++ regression/goto-instrument/Makefile | 6 ++-- .../goto-instrument/dump-asm-goto/main.c | 32 +++++++++++++++++++ .../goto-instrument/dump-asm-goto/test.desc | 22 +++++++++++++ src/ansi-c/expr2c.cpp | 20 +++++++++++- src/goto-instrument/goto_program2code.cpp | 24 ++++++++++++-- src/goto-instrument/goto_program2code.h | 12 +++++++ 7 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 regression/goto-instrument/dump-asm-goto/main.c create mode 100644 regression/goto-instrument/dump-asm-goto/test.desc diff --git a/regression/goto-instrument/CMakeLists.txt b/regression/goto-instrument/CMakeLists.txt index f7f08694f6aa..758628d7a21f 100644 --- a/regression/goto-instrument/CMakeLists.txt +++ b/regression/goto-instrument/CMakeLists.txt @@ -4,6 +4,13 @@ else() set(is_windows false) endif() +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + set(gcc_only -X gcc-only) +else() + set(gcc_only "") +endif() + add_test_pl_tests( "${CMAKE_CURRENT_SOURCE_DIR}/chain.sh $ $ $ ${is_windows}" + ${gcc_only} ) diff --git a/regression/goto-instrument/Makefile b/regression/goto-instrument/Makefile index 6712245e3324..dc9ce6e27f05 100644 --- a/regression/goto-instrument/Makefile +++ b/regression/goto-instrument/Makefile @@ -6,16 +6,18 @@ include ../../src/common ifeq ($(BUILD_ENV_),MSVC) exe=../../../src/goto-cc/goto-cl is_windows=true + GCC_ONLY = -X gcc-only else exe=../../../src/goto-cc/goto-cc is_windows=false + GCC_ONLY = endif test: - @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/goto-instrument/goto-instrument ../../../src/cbmc/cbmc $(is_windows)' + @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/goto-instrument/goto-instrument ../../../src/cbmc/cbmc $(is_windows)' $(GCC_ONLY) tests.log: - @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/goto-instrument/goto-instrument ../../../src/cbmc/cbmc $(is_windows)' + @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/goto-instrument/goto-instrument ../../../src/cbmc/cbmc $(is_windows)' $(GCC_ONLY) clean: $(RM) tests.log diff --git a/regression/goto-instrument/dump-asm-goto/main.c b/regression/goto-instrument/dump-asm-goto/main.c new file mode 100644 index 000000000000..2486b26f44a8 --- /dev/null +++ b/regression/goto-instrument/dump-asm-goto/main.c @@ -0,0 +1,32 @@ +// asm goto statements in the output of --dump-c, which is compiled again and +// checked: the jumps of the statements must be preserved, and the variable that +// selects the label in the goto program must say "no jump" when the statement +// falls through. +int nondet_int(void); + +static int modeled(void) +{ + // modeled, and does not jump + asm goto("nop" : : : : out); + return 0; +out: + return 1; +} + +static int approximated(int c) +{ + // not modeled: may jump to zero or fall through + asm goto("testl %0, %0; jz %l[zero]" : : "r"(c) : : zero); + return 0; +zero: + return 1; +} + +int main(void) +{ + __CPROVER_assert(modeled() == 0, "modeled statement does not jump"); // holds + int r = approximated(nondet_int()); + __CPROVER_assert(r == 0, "falls through"); // fails + __CPROVER_assert(r == 1, "jumps"); // fails + return 0; +} diff --git a/regression/goto-instrument/dump-asm-goto/test.desc b/regression/goto-instrument/dump-asm-goto/test.desc new file mode 100644 index 000000000000..2c96337fc468 --- /dev/null +++ b/regression/goto-instrument/dump-asm-goto/test.desc @@ -0,0 +1,22 @@ +CORE gcc-only +main.c +--dump-c _ --validate-goto-model --validate-ssa-equation +^EXIT=10$ +^SIGNAL=0$ +^\s*asm goto\("nop" *: *: *: *: out\);$ +^\s*asm goto\("testl %0, %0; jz %l\[zero\]" *: *: "r"\(c\) *: *: zero\);$ +^\s*tmp_asm_goto_target = 0u;$ +^\[main\.assertion\.1\] .*: SUCCESS$ +^\[main\.assertion\.2\] .*: FAILURE$ +^\[main\.assertion\.3\] .*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +^\s*asm\("nop" +-- +--dump-c prints asm goto statements with their labels, and assigns 0 ("no +jump") to the variable that selects the label in the goto program before the +statement, as in C the statement jumps to the label directly. The output is +compiled again and checked: the modeled statement, which does not jump, still +does not jump (assertion 1), and the approximated one may still jump or fall +through (assertions 2 and 3). diff --git a/src/ansi-c/expr2c.cpp b/src/ansi-c/expr2c.cpp index 0ab40dfc11d0..ea155d24e271 100644 --- a/src/ansi-c/expr2c.cpp +++ b/src/ansi-c/expr2c.cpp @@ -2590,9 +2590,13 @@ std::string expr2ct::convert_code_asm( if(src.get_flavor()==ID_gcc) { + // The optional sixth operand, the variable that selects the label an asm + // goto statement jumps to, is internal to CBMC: in C, the statement jumps + // to the label directly. if(src.operands().size() == 5 || src.operands().size() == 6) { - dest+="asm("; + const exprt &labels = src.operands()[4]; + dest += labels.operands().empty() ? "asm(" : "asm goto("; dest+=convert(src.op0()); if(!src.operands()[1].operands().empty() || !src.operands()[2].operands().empty() || @@ -2642,6 +2646,20 @@ std::string expr2ct::convert_code_asm( else dest+=convert(*it); } + + // labels (asm goto) + if(!labels.operands().empty()) + { + dest += " : "; + bool first = true; + for(const auto &label : labels.operands()) + { + if(!first) + dest += ", "; + first = false; + dest += clean_identifier(label.get(ID_identifier)); + } + } } dest+=");"; } diff --git a/src/goto-instrument/goto_program2code.cpp b/src/goto-instrument/goto_program2code.cpp index 212152ca3c2a..d341fbf2fe7c 100644 --- a/src/goto-instrument/goto_program2code.cpp +++ b/src/goto-instrument/goto_program2code.cpp @@ -181,8 +181,7 @@ goto_programt::const_targett goto_program2codet::convert_instruction( return target; case OTHER: - dest.add(target->get_other()); - return target; + return convert_other(target, dest); case ASSIGN: return convert_assign(target, upper_bound, dest); @@ -288,6 +287,27 @@ void goto_program2codet::convert_labels( latest_block->add(code_skipt()); } +goto_programt::const_targett goto_program2codet::convert_other( + goto_programt::const_targett target, + code_blockt &dest) +{ + const codet &code = target->get_other(); + + // asm goto: in C, the statement jumps to the label directly, so the dispatch + // that follows it must not jump + const bool is_asm_gcc = + code.get_statement() == ID_asm && to_code_asm(code).get_flavor() == ID_gcc; + if(is_asm_gcc && to_code_asm_gcc(code).has_goto_target()) + { + const exprt &goto_target = to_code_asm_gcc(code).goto_target(); + exprt no_jump = from_integer(0, goto_target.type()); + dest.add(code_frontend_assignt{goto_target, std::move(no_jump)}); + } + + dest.add(code); + return target; +} + goto_programt::const_targett goto_program2codet::convert_assign( goto_programt::const_targett target, goto_programt::const_targett upper_bound, diff --git a/src/goto-instrument/goto_program2code.h b/src/goto-instrument/goto_program2code.h index 8bb837cb48ae..f2030001dbc9 100644 --- a/src/goto-instrument/goto_program2code.h +++ b/src/goto-instrument/goto_program2code.h @@ -134,6 +134,18 @@ class goto_program2codet void convert_labels(goto_programt::const_targett target, code_blockt &dest); + /// Appends the code of the OTHER instruction \p target to \p dest. An asm + /// goto statement is preceded by an assignment of 0 ("no jump") to the + /// variable that selects the label it jumps to (see + /// \ref code_asm_gcct::goto_target): in C, the statement jumps to the label + /// directly, so the dispatch on the variable after the statement is reached + /// only when the statement falls through. + /// \param target: The OTHER instruction + /// \param [out] dest: The block to append to + /// \return \p target + goto_programt::const_targett + convert_other(goto_programt::const_targett target, code_blockt &dest); + goto_programt::const_targett convert_assign( goto_programt::const_targett target, goto_programt::const_targett upper_bound, From 4a1b56e96e5df3324d2431057e60e1d3730475ec Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:19:11 +0000 Subject: [PATCH 048/100] goto_convertt: move the asm goto dispatch into its own function 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 --- src/ansi-c/goto-conversion/goto_asm.cpp | 33 ++++++++++++------- .../goto-conversion/goto_convert_class.h | 20 +++++++++++ 2 files changed, 42 insertions(+), 11 deletions(-) diff --git a/src/ansi-c/goto-conversion/goto_asm.cpp b/src/ansi-c/goto-conversion/goto_asm.cpp index 9058994d09c6..ded1708d9d05 100644 --- a/src/ansi-c/goto-conversion/goto_asm.cpp +++ b/src/ansi-c/goto-conversion/goto_asm.cpp @@ -51,7 +51,8 @@ void goto_convertt::convert_asm( dest.destructive_append(side_effects.side_effects); // asm goto: the translation of the statement (see remove_asm) records the - // label it jumps to in a variable, which is dispatched on below + // label it jumps to in a variable, which convert_asm_goto_dispatch then + // dispatches on std::vector labels; for(const auto &label : new_code.labels().operands()) labels.push_back(label.get(ID_identifier)); @@ -77,26 +78,36 @@ void goto_convertt::convert_asm( if(!goto_target.has_value()) return; - // Jump to the label with the (1-based) index the statement chose, if any. - // These are ordinary gotos, converted as such so that leaving scopes is - // handled like for any other goto. - code_deadt dead{*goto_target}; - dead.add_source_location() = code.source_location(); + convert_asm_goto_dispatch( + *goto_target, labels, code.source_location(), dest, mode); +} + +void goto_convertt::convert_asm_goto_dispatch( + const symbol_exprt &goto_target, + const std::vector &labels, + const source_locationt &source_location, + goto_programt &dest, + const irep_idt &mode) +{ + // goto_target == i + 1 selects labels[i], and 0 means that the statement + // does not jump (see the documentation of this function) + code_deadt dead{goto_target}; + dead.add_source_location() = source_location; for(std::size_t i = 0; i < labels.size(); ++i) { code_gotot code_goto{labels[i]}; - code_goto.add_source_location() = code.source_location(); + code_goto.add_source_location() = source_location; code_blockt then_case{{dead, std::move(code_goto)}}; - then_case.add_source_location() = code.source_location(); + then_case.add_source_location() = source_location; code_ifthenelset if_goto{ - equal_exprt{*goto_target, from_integer(i + 1, goto_target->type())}, + equal_exprt{goto_target, from_integer(i + 1, goto_target.type())}, std::move(then_case)}; - if_goto.add_source_location() = code.source_location(); + if_goto.add_source_location() = source_location; convert(if_goto, dest, mode); } - dest.add(goto_programt::make_dead(*goto_target, code.source_location())); + dest.add(goto_programt::make_dead(goto_target, source_location)); } diff --git a/src/ansi-c/goto-conversion/goto_convert_class.h b/src/ansi-c/goto-conversion/goto_convert_class.h index e9a9cfaabcf5..053352cb1cf1 100644 --- a/src/ansi-c/goto-conversion/goto_convert_class.h +++ b/src/ansi-c/goto-conversion/goto_convert_class.h @@ -360,6 +360,26 @@ class goto_convertt : public messaget void convert_asm(const code_asmt &code, goto_programt &dest, const irep_idt &mode); + /// Appends to \p dest the jumps of an `asm goto` statement, which follow + /// the OTHER instruction of the statement. The translation of the statement + /// (see remove_asm) sets \p goto_target to the 1-based index in \p labels of + /// the label it jumps to, or to 0 if it does not jump (see + /// \ref code_asm_gcct::goto_target). For each label i, this emits an + /// ordinary goto to `labels[i]`, guarded by `goto_target == i + 1`, which is + /// converted like any other goto, so that leaving scopes is handled as + /// usual. \p goto_target is dead on all paths that leave the dispatch. + /// \param goto_target: The variable that selects the label + /// \param labels: The labels of the statement, in the order they are listed + /// \param source_location: The location of the statement + /// \param [out] dest: The program to append to + /// \param mode: The language mode + void convert_asm_goto_dispatch( + const symbol_exprt &goto_target, + const std::vector &labels, + const source_locationt &source_location, + goto_programt &dest, + const irep_idt &mode); + void convert(const codet &code, goto_programt &dest, const irep_idt &mode); void copy( From 70cb6a17df7a15c531d4388aeade1bdfa5f4f7c5 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 13:55:25 +0000 Subject: [PATCH 049/100] Inline assembly tests: do not depend on the host architecture 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 --- regression/cbmc/asm_block_function_body/test.desc | 2 +- regression/cbmc/asm_operand_side_effects/test.desc | 2 +- regression/cbmc/inline_asm_approximation/test.desc | 2 +- .../cbmc/inline_asm_approximation_rounding_mode/test.desc | 2 +- regression/cbmc/inline_asm_fpu_control_word/test.desc | 2 +- regression/cbmc/inline_asm_goto/test.desc | 2 +- regression/cbmc/inline_asm_goto_scope/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable/full-slice.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable/test.desc | 2 +- .../cbmc/inline_asm_havoc_reachable_alignment/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable_array/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable_budget/test.desc | 2 +- .../cbmc/inline_asm_havoc_reachable_candidates/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable_union/test.desc | 2 +- regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc | 2 +- regression/cbmc/inline_asm_lock_prefix/test.desc | 2 +- regression/cbmc/inline_asm_modeling/test.desc | 2 +- regression/cbmc/inline_asm_mxcsr/test.desc | 2 +- .../goto-analyzer/dependence-graph-havoc-reachable/test.desc | 2 +- .../goto-analyzer/havoc-reachable-domains/constants.desc | 2 +- .../goto-analyzer/havoc-reachable-domains/intervals.desc | 2 +- regression/goto-analyzer/havoc-reachable-domains/vsd.desc | 2 +- .../goto-analyzer/havoc-reachable-three-way-merge/test.desc | 2 +- .../dependence-graph-havoc-reachable-heap/main.c | 4 ++-- regression/goto-instrument/isr-havoc-reachable/main.c | 4 ++-- regression/goto-instrument/race-check-havoc-reachable/main.c | 4 ++-- .../show-value-sets-havoc-reachable-offset/main.c | 4 ++-- .../show-value-sets-havoc-reachable-unknown/main.c | 4 ++-- .../goto-instrument/show-value-sets-havoc-reachable/main.c | 5 +++-- 31 files changed, 38 insertions(+), 37 deletions(-) diff --git a/regression/cbmc/asm_block_function_body/test.desc b/regression/cbmc/asm_block_function_body/test.desc index 6c3daf17ff3f..c19dc6878910 100644 --- a/regression/cbmc/asm_block_function_body/test.desc +++ b/regression/cbmc/asm_block_function_body/test.desc @@ -1,6 +1,6 @@ CORE main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 21 x unchanged: FAILURE$ diff --git a/regression/cbmc/asm_operand_side_effects/test.desc b/regression/cbmc/asm_operand_side_effects/test.desc index 185c414c027d..c08be45bac8f 100644 --- a/regression/cbmc/asm_operand_side_effects/test.desc +++ b/regression/cbmc/asm_operand_side_effects/test.desc @@ -1,6 +1,6 @@ CORE main.c - +--arch riscv64 ^EXIT=0$ ^SIGNAL=0$ ^VERIFICATION SUCCESSFUL$ diff --git a/regression/cbmc/inline_asm_approximation/test.desc b/regression/cbmc/inline_asm_approximation/test.desc index 269f81be1471..a2e6da68e940 100644 --- a/regression/cbmc/inline_asm_approximation/test.desc +++ b/regression/cbmc/inline_asm_approximation/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---no-standard-checks +--arch riscv64 --no-standard-checks ^EXIT=10$ ^SIGNAL=0$ approximating inline assembly statement at .* line 27 function main: instruction 'xchg' is not modeled, so its output operands and the rounding mode are assigned nondeterministic values diff --git a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc index b3be79752232..d06b0b037f54 100644 --- a/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ approximating inline assembly statement at .* line 6 function main: instruction 'fxrstor' is not modeled, so the objects reachable from its operands diff --git a/regression/cbmc/inline_asm_fpu_control_word/test.desc b/regression/cbmc/inline_asm_fpu_control_word/test.desc index 45818158f8f4..d0f4dd2cd1d7 100644 --- a/regression/cbmc/inline_asm_fpu_control_word/test.desc +++ b/regression/cbmc/inline_asm_fpu_control_word/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 7 initial rounding mode: SUCCESS$ diff --git a/regression/cbmc/inline_asm_goto/test.desc b/regression/cbmc/inline_asm_goto/test.desc index d72560f83fee..697082078e1a 100644 --- a/regression/cbmc/inline_asm_goto/test.desc +++ b/regression/cbmc/inline_asm_goto/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---validate-goto-model --validate-ssa-equation +--arch riscv64 --validate-goto-model --validate-ssa-equation ^EXIT=10$ ^SIGNAL=0$ approximating inline assembly statement at .* function branch: instruction 'testl' is not modeled, so the choice of the label it jumps to \(if any\) diff --git a/regression/cbmc/inline_asm_goto_scope/test.desc b/regression/cbmc/inline_asm_goto_scope/test.desc index 16355009d1eb..079ac343e738 100644 --- a/regression/cbmc/inline_asm_goto_scope/test.desc +++ b/regression/cbmc/inline_asm_goto_scope/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---validate-goto-model --validate-ssa-equation +--arch riscv64 --validate-goto-model --validate-ssa-equation ^EXIT=10$ ^SIGNAL=0$ ^\[forward\.assertion\.1\] line 22 forward: jumped before r = 1: SUCCESS$ diff --git a/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc index a9190cf68c65..e77e32e0c028 100644 --- a/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc +++ b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---full-slice +--arch riscv64 --full-slice ^EXIT=10$ ^SIGNAL=0$ ^not slicing, as the program contains inline assembly that may change any reachable object$ diff --git a/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc index 4fe347dd14af..dfb9aeb499bf 100644 --- a/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc +++ b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---paths lifo +--arch riscv64 --paths lifo ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 37 heap object reachable from static: FAILURE$ diff --git a/regression/cbmc/inline_asm_havoc_reachable/test.desc b/regression/cbmc/inline_asm_havoc_reachable/test.desc index 3f9c80faf63c..1efb572af131 100644 --- a/regression/cbmc/inline_asm_havoc_reachable/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 37 heap object reachable from static: FAILURE$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc b/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc index abe1ac8033f3..9d46d7a369cd 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^approximating inline assembly statement at file main\.c line 52 function main: .*; other objects are assumed to be unchanged, and the pointers stored in the changed objects are assumed to be null, previous values of such pointers, or pointers into the reachable objects at offsets that are multiples of the alignment of their target type and at which an object of that type fits$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_array/test.desc b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc index 6ac93e0bded2..1b8525ee77dd 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_array/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 11 element changed: FAILURE$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc index 093270e3c232..8e109fe085fc 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^havocking the objects reachable at file main\.c line 33 function main: the pointers have more than 65536 possible values in total, and some are assigned arbitrary values$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc index b82425dbb331..4c9128cd1902 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^havocking the objects reachable at file main\.c line 87 function main: some pointers have more than 64 possible values, and are assigned arbitrary values$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc index bc442e410fd1..e555513a5191 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 26 pointer arithmetic: FAILURE$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_union/test.desc b/regression/cbmc/inline_asm_havoc_reachable_union/test.desc index 741de80410bb..507ad777911e 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_union/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_union/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---no-standard-checks +--arch riscv64 --no-standard-checks ^EXIT=10$ ^SIGNAL=0$ ^havocking the objects reachable at file main\.c line 39 function main: some pointers are stored in unions or in arrays of more than 64 elements \(or of a size that is not constant\), and are assigned arbitrary values$ diff --git a/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc b/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc index dae8311803b4..ac49b1ccd3d4 100644 --- a/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc +++ b/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---no-standard-checks +--arch riscv64 --no-standard-checks ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 35 unknown target of a static: FAILURE$ diff --git a/regression/cbmc/inline_asm_lock_prefix/test.desc b/regression/cbmc/inline_asm_lock_prefix/test.desc index fe26e638f228..d908a0333a53 100644 --- a/regression/cbmc/inline_asm_lock_prefix/test.desc +++ b/regression/cbmc/inline_asm_lock_prefix/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^approximating inline assembly statement at file main\.c line 6 function main: instruction 'lock' is not modeled diff --git a/regression/cbmc/inline_asm_modeling/test.desc b/regression/cbmc/inline_asm_modeling/test.desc index 1a7bff556065..b40d42fad46c 100644 --- a/regression/cbmc/inline_asm_modeling/test.desc +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---show-goto-functions +--arch riscv64 --show-goto-functions activate-multi-line-match ^EXIT=0$ ^SIGNAL=0$ diff --git a/regression/cbmc/inline_asm_mxcsr/test.desc b/regression/cbmc/inline_asm_mxcsr/test.desc index 22d4fdc5fa5d..92913b97cce6 100644 --- a/regression/cbmc/inline_asm_mxcsr/test.desc +++ b/regression/cbmc/inline_asm_mxcsr/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c - +--arch riscv64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 7 initial rounding mode: SUCCESS$ diff --git a/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc b/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc index 570de1bdf3c2..2b8f05d32ad1 100644 --- a/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc +++ b/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc @@ -1,6 +1,6 @@ CORE main.c ---dependence-graph --show +--arch riscv64 --dependence-graph --show activate-multi-line-match ^EXIT=0$ ^SIGNAL=0$ diff --git a/regression/goto-analyzer/havoc-reachable-domains/constants.desc b/regression/goto-analyzer/havoc-reachable-domains/constants.desc index 0bb744f8e40d..bb808ac8431d 100644 --- a/regression/goto-analyzer/havoc-reachable-domains/constants.desc +++ b/regression/goto-analyzer/havoc-reachable-domains/constants.desc @@ -1,6 +1,6 @@ CORE main.c ---verify --constants +--arch riscv64 --verify --constants ^EXIT=0$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 14 global: UNKNOWN$ diff --git a/regression/goto-analyzer/havoc-reachable-domains/intervals.desc b/regression/goto-analyzer/havoc-reachable-domains/intervals.desc index 5b19196b3a9e..7a948a207074 100644 --- a/regression/goto-analyzer/havoc-reachable-domains/intervals.desc +++ b/regression/goto-analyzer/havoc-reachable-domains/intervals.desc @@ -1,6 +1,6 @@ CORE main.c ---verify --intervals +--arch riscv64 --verify --intervals ^EXIT=0$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 14 global: UNKNOWN$ diff --git a/regression/goto-analyzer/havoc-reachable-domains/vsd.desc b/regression/goto-analyzer/havoc-reachable-domains/vsd.desc index 68d7c1049810..10c6c3cbfe74 100644 --- a/regression/goto-analyzer/havoc-reachable-domains/vsd.desc +++ b/regression/goto-analyzer/havoc-reachable-domains/vsd.desc @@ -1,6 +1,6 @@ CORE main.c ---verify --vsd +--arch riscv64 --verify --vsd ^EXIT=0$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 14 global: UNKNOWN$ diff --git a/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc b/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc index e82a0b9ff61d..268fdef722ac 100644 --- a/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc +++ b/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc @@ -1,6 +1,6 @@ CORE main.c ---verify --vsd --three-way-merge +--arch riscv64 --verify --vsd --three-way-merge ^EXIT=0$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 28 known at the entry of the callee: UNKNOWN$ diff --git a/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c index 11577860e30c..7a0a22507812 100644 --- a/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c +++ b/regression/goto-cc-goto-analyzer/dependence-graph-havoc-reachable-heap/main.c @@ -14,9 +14,9 @@ int main() a->next = malloc(sizeof(struct node)); head = a; #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif struct node *second = head->next; return second != 0; diff --git a/regression/goto-instrument/isr-havoc-reachable/main.c b/regression/goto-instrument/isr-havoc-reachable/main.c index 3993c225aaf1..0f12a67b446e 100644 --- a/regression/goto-instrument/isr-havoc-reachable/main.c +++ b/regression/goto-instrument/isr-havoc-reachable/main.c @@ -3,9 +3,9 @@ int flag; void isr(void) { #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif } diff --git a/regression/goto-instrument/race-check-havoc-reachable/main.c b/regression/goto-instrument/race-check-havoc-reachable/main.c index 5dbe7d2e5c16..ec84e5e66a5c 100644 --- a/regression/goto-instrument/race-check-havoc-reachable/main.c +++ b/regression/goto-instrument/race-check-havoc-reachable/main.c @@ -3,9 +3,9 @@ int g; static void thread(void) { #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif } diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c index cf21e57ba6e7..28bbc134f5b1 100644 --- a/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-offset/main.c @@ -6,9 +6,9 @@ int *px = &x; int main() { #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif int *r = pa; return 0; diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c index 633af1f5c3cb..d18fb2306524 100644 --- a/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c +++ b/regression/goto-instrument/show-value-sets-havoc-reachable-unknown/main.c @@ -82,9 +82,9 @@ struct S *sp = &s1; int main() { #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif int *r = p; struct S *t = sp; diff --git a/regression/goto-instrument/show-value-sets-havoc-reachable/main.c b/regression/goto-instrument/show-value-sets-havoc-reachable/main.c index b80fffa5f772..f5cc9ad5b24b 100644 --- a/regression/goto-instrument/show-value-sets-havoc-reachable/main.c +++ b/regression/goto-instrument/show-value-sets-havoc-reachable/main.c @@ -7,9 +7,10 @@ int main() { int *local_p = &y; #ifdef __GNUC__ - asm volatile("cli" ::: "memory"); + // an instruction that CBMC does not model + asm volatile("unmodeled_instruction" ::: "memory"); #else - __asm { cli } + __asm { unmodeled_instruction } #endif int *r = q; return 0; From 11894346a16cc12181566225b041ce56ee2a29a4 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 13:55:58 +0000 Subject: [PATCH 050/100] Inline assembly: interpret x86 instructions 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 --- doc/architectural/front-page.md | 1 + doc/architectural/inline-assembly.md | 101 ++ doc/cprover-manual/modeling-inline-asm.md | 70 +- regression/cbmc-concurrency/CMakeLists.txt | 8 +- regression/cbmc-concurrency/Makefile | 8 +- .../asm_x86_atomic_instruction/main.i | 27 + .../asm_x86_atomic_instruction/test.desc | 14 + .../cbmc/asm_i386_64bit_instructions/main.i | 12 + .../asm_i386_64bit_instructions/test.desc | 16 + regression/cbmc/asm_x86/main.i | 454 +++++ regression/cbmc/asm_x86/test.desc | 13 + regression/cbmc/asm_x86_corner_cases/main.i | 62 + .../cbmc/asm_x86_corner_cases/test.desc | 26 + .../asm_x86_register_operand_constant/main.i | 50 + .../test.desc | 13 + src/assembler/Makefile | 5 + src/assembler/asm_bv_util.h | 155 ++ src/assembler/asm_lowering.cpp | 597 +++++++ src/assembler/asm_operands.cpp | 343 ++++ src/assembler/asm_operands.h | 98 ++ src/assembler/asm_semantics.cpp | 32 + src/assembler/asm_semantics.h | 325 ++++ src/assembler/asm_template.cpp | 399 +++++ src/assembler/asm_template.h | 115 ++ src/assembler/asm_x86.cpp | 1465 +++++++++++++++++ src/assembler/asm_x86.h | 22 + src/assembler/remove_asm.cpp | 210 ++- unit/Makefile | 1 + unit/assembler/asm_template.cpp | 92 ++ unit/assembler/module_dependencies.txt | 3 + unit/module_dependencies.txt | 1 + 31 files changed, 4725 insertions(+), 13 deletions(-) create mode 100644 doc/architectural/inline-assembly.md create mode 100644 regression/cbmc-concurrency/asm_x86_atomic_instruction/main.i create mode 100644 regression/cbmc-concurrency/asm_x86_atomic_instruction/test.desc create mode 100644 regression/cbmc/asm_i386_64bit_instructions/main.i create mode 100644 regression/cbmc/asm_i386_64bit_instructions/test.desc create mode 100644 regression/cbmc/asm_x86/main.i create mode 100644 regression/cbmc/asm_x86/test.desc create mode 100644 regression/cbmc/asm_x86_corner_cases/main.i create mode 100644 regression/cbmc/asm_x86_corner_cases/test.desc create mode 100644 regression/cbmc/asm_x86_register_operand_constant/main.i create mode 100644 regression/cbmc/asm_x86_register_operand_constant/test.desc create mode 100644 src/assembler/asm_bv_util.h create mode 100644 src/assembler/asm_lowering.cpp create mode 100644 src/assembler/asm_operands.cpp create mode 100644 src/assembler/asm_operands.h create mode 100644 src/assembler/asm_semantics.cpp create mode 100644 src/assembler/asm_semantics.h create mode 100644 src/assembler/asm_template.cpp create mode 100644 src/assembler/asm_template.h create mode 100644 src/assembler/asm_x86.cpp create mode 100644 src/assembler/asm_x86.h create mode 100644 unit/assembler/asm_template.cpp create mode 100644 unit/assembler/module_dependencies.txt diff --git a/doc/architectural/front-page.md b/doc/architectural/front-page.md index 24c34ad3ee8a..fd2848cfc7e8 100644 --- a/doc/architectural/front-page.md +++ b/doc/architectural/front-page.md @@ -67,6 +67,7 @@ you can access it here. * \subpage memory-bounds-checking +* \subpage inline-assembly * \subpage satabs ## For contributors: diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md new file mode 100644 index 000000000000..61a395dd8680 --- /dev/null +++ b/doc/architectural/inline-assembly.md @@ -0,0 +1,101 @@ +\ingroup module_hidden + +\page inline-assembly Inline Assembly + +This page describes how `remove_asm` (`src/assembler/`) gives meaning to +inline assembly, and how to extend the instruction semantics. The user-level +description is `doc/cprover-manual/modeling-inline-asm.md`. + +## Overview + +`remove_asm` replaces every inline assembly statement by goto-program +instructions. Every tool runs it before linking the CPROVER library. For a +GCC-style statement (`code_asm_gcct`), it tries, in this order: + +1. the instruction semantics of the configured architecture + (`config.ansi_c.arch`, see `make_asm_semantics`), if there are any: the + statement is *interpreted*; +2. the architecture-independent translation of fences, the x87 control word, + and no-ops (`handle_gcc_command` in `remove_asm.cpp`); +3. the conservative approximation (`asm_approximationt`), with a warning. + +MSVC-style blocks use steps 2 and 3 only. + +## Interpretation + +The interpretation of a statement has these parts: + +- `asm_operandst` (`asm_operands.h`) parses the constraints of the operands + and classifies each operand as a register, memory, immediate, or flag + output operand. Register inputs that are arrays decay to pointers. The + symbolic names used in `%[name]` references are kept by the C front end in + `ID_identifier`. +- `split_asm_template` (`asm_template.h`) splits the template into + instructions, and resolves `%N`, `%[name]`, `%lN`, and local label + references. +- `asm_lowering_contextt` (`asm_semantics.h`) holds the goto code being + built: the storage of register operands, hardware registers, and flags (all + block-local temporaries), labels, and helpers to read and write registers + and memory, branch, and fence. +- `asm_semanticst` is the interface of the per-architecture semantics; + `asm_x86.cpp` implements x86 (i386, x86-64, x32). + +The code of a statement consists of a prologue that evaluates the inputs, the +code of the instructions, and an epilogue that assigns the register outputs. +Memory operands are accessed in place. A sub-register input is zero-extended +to the register width unless a reference to it reads more bits (see +`asm_semanticst::reference_widens`), in which case the upper bits are +nondeterministic. Zero-extension keeps a constant input constant, which +symbolic execution relies on: otherwise, for example, a spin lock on a lock +word that is written through such an operand would make the lock word +symbolic, and the spin loops would be unwound to the unwinding bound. + +The code of the instructions has the checks for undefined behaviour of C +disabled (via pragmas on its source location), as it models hardware +operations whose results are defined. The prologue additionally evaluates the +inputs at the plain source location of the statement, so that the checks +apply to the C expressions of the operands. + +The following rules keep the interpretation sound. A statement that violates +one of them is not interpreted: + +- Every instruction, prefix, operand form, and directive must be understood. +- Instructions in another section (`.pushsection`/`.section`) are not + executed in sequence; they may be executed when another instruction faults + (exception fixups). Data in other sections is ignored. +- A write to a hardware register that is neither bound to an operand by its + constraint nor clobbered may be a write to a register variable + (`register long x asm("rax")`), which the front end does not record. +- An input tied to a memory output must be the same object. + +An instruction that is atomic on the hardware (on x86: lock-prefixed +instructions and `xchg` with a memory operand) is an atomic section of its +own, with a full fence; see `asm_lowering_contextt::mark_atomic`. Making the +whole statement atomic would hide races on the statement's other +instructions. + +For `asm goto`, goto conversion creates a variable that selects the label to +jump to (`code_asm_gcct::goto_target`) and dispatches on it after the +statement; the interpretation assigns it the index of the label that the +instructions jump to, or 0. + +## Adding instructions or an architecture + +To add an instruction, extend `lower` of the architecture's +`asm_semanticst`. Return false (via `asm_lowering_contextt::fail`, with a +reason) for any form that is not modeled exactly: the statement is then +approximated, which is always sound. Model values that the architecture +leaves undefined as nondeterministic, not as what one implementation does. + +To add an architecture, implement `asm_semanticst` (syntax, register width, +canonical register names, constraint letters, flag conditions, and `lower`) +and return it from `make_asm_semantics`. + +Tests that rely on the interpretation must pin the architecture with +`--arch`, as the default is the host architecture. Tests of the +architecture-independent translation and of the approximation use +`--arch riscv64`, which has no instruction semantics and for which CBMC +passes no `-m` option to the host preprocessor. The x86 tests use +preprocessed input (`main.i`), as preprocessing with `-m64` or `-m32` fails +on non-x86 hosts. Expected values of tests of instruction semantics should be +observed on hardware. diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 379a54c04abe..adb64fe49217 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -11,22 +11,76 @@ Intel syntax and name C variables; CBMC treats them as MSVC-style blocks in all modes. Before verification, the `remove_asm` pass replaces each inline-assembly statement by goto-program instructions: -- If CBMC models every instruction of the statement (see the tables below), - the statement is translated into the corresponding fences or calls to - library functions, followed by assignments to its output operands. +- On x86 (`--arch i386` or `--arch x86_64`, the default on x86 hosts), a + GCC-style statement is **interpreted** if CBMC's x86 instruction semantics + support all of its instructions (see "x86 Instruction Semantics" below): + it is translated into goto-program instructions with the same effect on the + C program state. +- Otherwise, if CBMC models every instruction of the statement (see + "Supported Instructions" below, on any architecture), the statement is + translated into the corresponding fences or calls to library functions, + followed by assignments to its output operands. - Otherwise the statement is **approximated conservatively**: everything the statement may change, as far as CBMC can tell from its operands, is - assigned a nondeterministic value, and a warning that names the first - instruction that is not modeled is printed. The modeled instructions of - such a statement are not translated either. + assigned a nondeterministic value, and a warning that says why the + statement is not modeled is printed. The modeled instructions of such a + statement are not translated either. A statement with an empty assembly template has no instructions, so CBMC models it. Such a statement only writes its output operands (see Output Operands below); without outputs, as in the compiler barrier `asm volatile("" ::: "memory")`, it does nothing. -None of the modeled instructions jumps, so an `asm goto` statement whose -instructions are all modeled continues with the next statement. +None of the instructions in the tables below jumps, so an `asm goto` +statement whose instructions are all listed there continues with the next +statement. An interpreted `asm goto` statement jumps to the label that its +instructions jump to. + +### x86 Instruction Semantics + +The x86 semantics cover the instructions that kernel and library code +commonly uses in inline assembly, with AT&T syntax: + +- data movement: `mov`, `movabs`, `movzx`/`movz*`, `movsx`/`movs*`, `lea`, + `xchg`, `bswap`, `cmov`, `set`, sign extensions of the accumulator + (`cltq`, `cwtl`, `cltd`, `cqto`, ...); +- arithmetic and logic, with the flags they set: `add`, `adc`, `sub`, `sbb`, + `and`, `or`, `xor`, `not`, `neg`, `inc`, `dec`, `cmp`, `test`; +- shifts and rotates (`shl`, `sal`, `shr`, `sar`, `rol`, `ror`), bit tests + (`bt`, `bts`, `btr`, `btc`), and bit scans and counts (`bsf`, `bsr`, + `tzcnt`, `lzcnt`, `popcnt`); +- atomics: the `lock` prefix, `xchg` with a memory operand, `xadd`, + `cmpxchg`; +- control flow within the statement: `jmp`, `j` to local and C labels + (`asm goto`), and flag outputs (`=@cc`); +- fences (`mfence`, `lfence`, `sfence`), the x87 control word (`fstcw`, + `fnstcw`, `fldcw`), and instructions without effect on the C program state + (`nop`, `pause`, `cli`, `sti`, `hlt`, `wrmsr`); `cpuid`, `rdtsc`, + `rdtscp`, `rdmsr`, and `in` produce nondeterministic values. + +Operands follow GCC's rules: inputs are evaluated before the first +instruction (and are subject to the checks CBMC performs), register outputs +are assigned after the last instruction, and memory operands are accessed in +place. Values that the architecture leaves undefined (such as some flags, or +the destination of `bsf` with a zero source) are nondeterministic. The +checks for undefined behaviour of C (such as `--signed-overflow-check`) do +not apply to the instructions, which have defined results on the hardware; +the checks of memory accesses do. + +A statement is not interpreted (and hence approximated, unless all of its +instructions are listed in the tables below) if it: + +- contains an instruction, operand, prefix, or directive that the semantics + do not support, or instructions in another section (such as exception + fixups, which run when an instruction faults); data in other sections (such + as the Linux kernel's jump tables) is ignored; +- writes a register that is neither bound to an operand nor clobbered: as + CBMC does not track register variables (`register long x asm("rax")`), + such a write may change a C variable. + +A lock-prefixed instruction (or `xchg` with a memory operand) is an atomic +section with a full fence; the other instructions of the statement are not +part of that atomic section. ### Supported Instructions diff --git a/regression/cbmc-concurrency/CMakeLists.txt b/regression/cbmc-concurrency/CMakeLists.txt index 58bbbe6cdb6e..01b695c1e260 100644 --- a/regression/cbmc-concurrency/CMakeLists.txt +++ b/regression/cbmc-concurrency/CMakeLists.txt @@ -1,3 +1,9 @@ +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + set(gcc_only_string "-X;gcc-only;") +else() + set(gcc_only_string "") +endif() + if((NOT WIN32) AND (NOT APPLE) AND (NOT (CMAKE_SYSTEM_NAME STREQUAL "FreeBSD"))) add_test_pl_tests( "$ --validate-goto-model --validate-ssa-equation" @@ -6,7 +12,7 @@ else() add_test_pl_profile( "cbmc-concurrency" "$ --validate-goto-model --validate-ssa-equation" - "-C;-X;pthread" + "${gcc_only_string}-C;-X;pthread" "CORE" ) endif() diff --git a/regression/cbmc-concurrency/Makefile b/regression/cbmc-concurrency/Makefile index 5d8281162303..7fb41fd257a6 100644 --- a/regression/cbmc-concurrency/Makefile +++ b/regression/cbmc-concurrency/Makefile @@ -9,11 +9,15 @@ ifeq ($(filter-out OSX MSVC FreeBSD,$(BUILD_ENV_)),) no_pthread = -X pthread endif +ifeq ($(BUILD_ENV_),MSVC) + gcc_only = -X gcc-only +endif + test: - @../test.pl -e -p -c "../../../src/cbmc/cbmc --validate-goto-model --validate-ssa-equation" $(no_pthread) + @../test.pl -e -p -c "../../../src/cbmc/cbmc --validate-goto-model --validate-ssa-equation" $(no_pthread) $(gcc_only) tests.log: ../test.pl - @../test.pl -e -p -c "../../../src/cbmc/cbmc --validate-goto-model --validate-ssa-equation" $(no_pthread) + @../test.pl -e -p -c "../../../src/cbmc/cbmc --validate-goto-model --validate-ssa-equation" $(no_pthread) $(gcc_only) clean: find . -name '*.out' -execdir $(RM) '{}' \; diff --git a/regression/cbmc-concurrency/asm_x86_atomic_instruction/main.i b/regression/cbmc-concurrency/asm_x86_atomic_instruction/main.i new file mode 100644 index 000000000000..6410b00cc812 --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_atomic_instruction/main.i @@ -0,0 +1,27 @@ +// An atomic instruction is an atomic section on its own, not the whole +// statement: the read-modify-write of x by plain instructions can race. +unsigned x, y, z, dummy; + +void t(void) +{ + __asm__ __volatile__( + "movl %0,%%eax\n\t" + "incl %%eax\n\t" + "movl %%eax,%0\n\t" + "lock orl $0,%1" + : "+m"(x), "+m"(dummy) + : + : "eax", "cc", "memory"); + __asm__ __volatile__("lock incl %0" : "+m"(y) : : "cc", "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), z = 1; + t(); + __CPROVER_assume(z); + __CPROVER_assert(x == 2, "plain read-modify-write"); // fails + __CPROVER_assert(y == 2, "locked increment"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_x86_atomic_instruction/test.desc b/regression/cbmc-concurrency/asm_x86_atomic_instruction/test.desc new file mode 100644 index 000000000000..d27a063be22d --- /dev/null +++ b/regression/cbmc-concurrency/asm_x86_atomic_instruction/test.desc @@ -0,0 +1,14 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 24 plain read-modify-write: FAILURE$ +^\[main\.assertion\.2\] line 25 locked increment: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +A lock-prefixed instruction is an atomic section on its own: making the whole +statement atomic would hide the race on the plain read-modify-write of x. diff --git a/regression/cbmc/asm_i386_64bit_instructions/main.i b/regression/cbmc/asm_i386_64bit_instructions/main.i new file mode 100644 index 000000000000..3e7ab1234c5a --- /dev/null +++ b/regression/cbmc/asm_i386_64bit_instructions/main.i @@ -0,0 +1,12 @@ +// 64-bit instructions are not valid in 32-bit mode: they are not modeled. +int main(void) +{ + unsigned a = 5, d = 0; + __asm__("cltq" : "+a"(a)); + __asm__("cqto" : "+a"(a), "=d"(d)); + __asm__("movzbq %b1,%0" : "=r"(d) : "q"(a)); + unsigned b = 1; + __asm__("addl $1,%0" : "+r"(b) : : "cc"); + __CPROVER_assert(b == 2, "32-bit instruction"); + return 0; +} diff --git a/regression/cbmc/asm_i386_64bit_instructions/test.desc b/regression/cbmc/asm_i386_64bit_instructions/test.desc new file mode 100644 index 000000000000..ac7a1905de95 --- /dev/null +++ b/regression/cbmc/asm_i386_64bit_instructions/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.i +--arch i386 +^EXIT=0$ +^SIGNAL=0$ +approximating inline assembly statement at .* line 5 function main: 64-bit instruction in 32-bit mode +approximating inline assembly statement at .* line 6 function main: 64-bit instruction in 32-bit mode +approximating inline assembly statement at .* line 7 function main: 64-bit instruction in 32-bit mode +^\[main\.assertion\.1\] line 10 32-bit instruction: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly statement at .* line 9 +-- +Instructions with 64-bit operands are not valid in 32-bit mode, and are not +modeled; the 32-bit addl is. diff --git a/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i new file mode 100644 index 000000000000..adbb5e869138 --- /dev/null +++ b/regression/cbmc/asm_x86/main.i @@ -0,0 +1,454 @@ +// x86 inline assembly that is interpreted exactly. The expected values were +// observed on x86-64 hardware. + +// x86 lock-or sets a bit (atomic_set_long) +void asm_case_0(unsigned long long *io) +{ + unsigned long m = (unsigned long)io[0]; + unsigned long v = (unsigned long)io[1]; + __asm__ __volatile__("lock; orq %1,%0" : "+m"(m) : "ir"(v) : "cc"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; +} + +// x86 lock-and clears bits (atomic_clear_long) +void asm_case_1(unsigned long long *io) +{ + unsigned long m = (unsigned long)io[0]; + unsigned long v = (unsigned long)io[1]; + __asm__ __volatile__("lock; andq %1,%0" : "+m"(m) : "ir"(v) : "cc"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; +} + +// x86 lock-add (atomic_add_long) +void asm_case_2(unsigned long long *io) +{ + unsigned long m = (unsigned long)io[0]; + unsigned long v = (unsigned long)io[1]; + __asm__ __volatile__("lock; addq %1,%0" : "+m"(m) : "ir"(v) : "cc"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; +} + +// x86 lock-xadd returns the previous value (atomic_fetchadd) +void asm_case_3(unsigned long long *io) +{ + unsigned int v = (unsigned int)io[0]; + unsigned int m = (unsigned int)io[1]; + __asm__ __volatile__("lock; xaddl %0,%1" : "+r"(v), "+m"(m) : : "cc"); + io[0] = (unsigned long long)v; + io[1] = (unsigned long long)m; +} + +// x86 lock-bts sets a bit and reports its old value +void asm_case_4(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int c = (unsigned int)io[1]; + unsigned int n = (unsigned int)io[2]; + __asm__ __volatile__("lock; btsl %2,%0" + : "+m"(m), "=@ccc"(c) + : "Ir"(n) + : "cc"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)c; + io[2] = (unsigned long long)n; +} + +// x86 bsr finds the highest set bit +void asm_case_5(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long v = (unsigned long)io[1]; + __asm__("bsrq %1,%0" : "=r"(r) : "rm"(v)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)v; +} + +// x86 add sets the carry flag +void asm_case_6(unsigned long long *io) +{ + unsigned int a = (unsigned int)io[0]; + unsigned int c = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__("addl %2,%0; setc %b1" : "+r"(a), "+q"(c) : "r"(b) : "cc"); + io[0] = (unsigned long long)a; + io[1] = (unsigned long long)c; + io[2] = (unsigned long long)b; +} + +// x86 shld-free shift: shr by cl +void asm_case_7(unsigned long long *io) +{ + unsigned long a = (unsigned long)io[0]; + unsigned long n = (unsigned long)io[1]; + __asm__("shrq %%cl,%0" : "+r"(a) : "c"(n) : "cc"); + io[0] = (unsigned long long)a; + io[1] = (unsigned long long)n; +} + +// x86 bswap reverses byte order +void asm_case_8(unsigned long long *io) +{ + unsigned long a = (unsigned long)io[0]; + __asm__("bswapq %0" : "+r"(a)); + io[0] = (unsigned long long)a; +} + +// x86 cmpxchg exchanges on a match (atomic_cmpset) +void asm_case_9(unsigned long long *io) +{ + unsigned int ok = (unsigned int)io[0]; + unsigned int m = (unsigned int)io[1]; + unsigned int expected = (unsigned int)io[2]; + unsigned int desired = (unsigned int)io[3]; + __asm__ __volatile__("lock; cmpxchgl %3,%1" + : "=@ccz"(ok), "+m"(m), "+a"(expected) + : "r"(desired) + : "cc"); + io[0] = (unsigned long long)ok; + io[1] = (unsigned long long)m; + io[2] = (unsigned long long)expected; + io[3] = (unsigned long long)desired; +} + +// x86 xchg swaps a register and memory +void asm_case_10(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int m = (unsigned int)io[1]; + __asm__ __volatile__("xchgl %0,%1" : "+r"(r), "+m"(m)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)m; +} + +// x86 and masks and sets the sign flag +void asm_case_11(unsigned long long *io) +{ + unsigned int a = (unsigned int)io[0]; + unsigned int s = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__("andl %2,%0; sets %b1" : "+r"(a), "+q"(s) : "r"(b) : "cc"); + io[0] = (unsigned long long)a; + io[1] = (unsigned long long)s; + io[2] = (unsigned long long)b; +} + +// x86 memory operand with a struct field offset +void asm_case_12(unsigned long long *io) +{ + unsigned int lo = (unsigned int)io[0]; + unsigned int hi = (unsigned int)io[1]; + unsigned int v = (unsigned int)io[2]; + struct + { + unsigned int lo, hi; + } s = {(unsigned)io[0], (unsigned)io[1]}; + __asm__ __volatile__("orl %1,%0" : "+m"(s.hi) : "r"(v) : "cc"); + io[0] = (unsigned long long)lo; + io[1] = (unsigned long long)hi; + io[2] = (unsigned long long)v; +} + +int main(void) +{ + { + unsigned long long io[2] = {0xc2a7af9eab79b005ULL, 0xffULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0xc2a7af9eab79b0ffULL && io[1] == 0xffULL, + "x86 lock-or sets a bit (atomic_set_long), vector 0"); + } + { + unsigned long long io[2] = {0x2ULL, 0x6ffe6666fa72766dULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x6ffe6666fa72766fULL && io[1] == 0x6ffe6666fa72766dULL, + "x86 lock-or sets a bit (atomic_set_long), vector 1"); + } + { + unsigned long long io[2] = {0x8000000000000000ULL, 0x8000000000000000ULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x8000000000000000ULL && io[1] == 0x8000000000000000ULL, + "x86 lock-or sets a bit (atomic_set_long), vector 2"); + } + { + unsigned long long io[2] = {0xc2b9546e0f0220f3ULL, 0xf1d5effedcda26fbULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xc091446e0c0220f3ULL && io[1] == 0xf1d5effedcda26fbULL, + "x86 lock-and clears bits (atomic_clear_long), vector 0"); + } + { + unsigned long long io[2] = {0x7fffffffULL, 0xb8d3af23681c2889ULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0x681c2889ULL && io[1] == 0xb8d3af23681c2889ULL, + "x86 lock-and clears bits (atomic_clear_long), vector 1"); + } + { + unsigned long long io[2] = {0xc60f8fe0a6269527ULL, 0x32f6ffa49275dc84ULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0x2068fa082249404ULL && io[1] == 0x32f6ffa49275dc84ULL, + "x86 lock-and clears bits (atomic_clear_long), vector 2"); + } + { + unsigned long long io[2] = {0xe638bca46bd70d89ULL, 0x2ULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0xe638bca46bd70d8bULL && io[1] == 0x2ULL, + "x86 lock-add (atomic_add_long), vector 0"); + } + { + unsigned long long io[2] = {0x2ULL, 0x17d967b89f01d73dULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x17d967b89f01d73fULL && io[1] == 0x17d967b89f01d73dULL, + "x86 lock-add (atomic_add_long), vector 1"); + } + { + unsigned long long io[2] = {0x82974e236f761b03ULL, 0x7fULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x82974e236f761b82ULL && io[1] == 0x7fULL, + "x86 lock-add (atomic_add_long), vector 2"); + } + { + unsigned long long io[2] = {0x38b1f9a35c2855baULL, 0x8a0cb201725c5338ULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0x725c5338ULL && io[1] == 0xce84a8f2ULL, + "x86 lock-xadd returns the previous value (atomic_fetchadd), vector 0"); + } + { + unsigned long long io[2] = {0xb0652c5806a310a8ULL, 0x808332e379bd40dbULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0x79bd40dbULL && io[1] == 0x80605183ULL, + "x86 lock-xadd returns the previous value (atomic_fetchadd), vector 1"); + } + { + unsigned long long io[2] = {0xe586f6e1167ff12eULL, 0xffULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0xffULL && io[1] == 0x167ff22dULL, + "x86 lock-xadd returns the previous value (atomic_fetchadd), vector 2"); + } + { + unsigned long long io[3] = { + 0xb8004092f9e22b92ULL, 0xab4d6d46b16b38cbULL, 0x5ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0xf9e22bb2ULL && io[1] == 0x0ULL && io[2] == 0x5ULL, + "x86 lock-bts sets a bit and reports its old value, vector 0"); + } + { + unsigned long long io[3] = { + 0xc662866ad84cf328ULL, 0x8000000000000000ULL, 0x1fULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0xd84cf328ULL && io[1] == 0x1ULL && io[2] == 0x1fULL, + "x86 lock-bts sets a bit and reports its old value, vector 1"); + } + { + unsigned long long io[3] = { + 0xd85ee36626a12990ULL, 0x816ffbff11966d8bULL, 0x0ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x26a12991ULL && io[1] == 0x0ULL && io[2] == 0x0ULL, + "x86 lock-bts sets a bit and reports its old value, vector 2"); + } + { + unsigned long long io[2] = {0x0ULL, 0x1ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x1ULL, + "x86 bsr finds the highest set bit, vector 0"); + } + { + unsigned long long io[2] = {0x0ULL, 0x8000000000000000ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0x3fULL && io[1] == 0x8000000000000000ULL, + "x86 bsr finds the highest set bit, vector 1"); + } + { + unsigned long long io[2] = {0x0ULL, 0x1234ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0xcULL && io[1] == 0x1234ULL, + "x86 bsr finds the highest set bit, vector 2"); + } + { + unsigned long long io[3] = { + 0x71985eb13a883919ULL, 0x7fffffffffffffffULL, 0xc42192ad002d93dcULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x3ab5ccf5ULL && io[1] == 0xffffff00ULL && io[2] == 0x2d93dcULL, + "x86 add sets the carry flag, vector 0"); + } + { + unsigned long long io[3] = { + 0xffffffffULL, 0x4f18c672fa42fe7cULL, 0x120984629605b44fULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x9605b44eULL && io[1] == 0xfa42fe01ULL && + io[2] == 0x9605b44fULL, + "x86 add sets the carry flag, vector 1"); + } + { + unsigned long long io[3] = { + 0x4eb832d5079a2474ULL, 0x0ULL, 0xfd64b9e5bd0edb5aULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0xc4a8ffceULL && io[1] == 0x0ULL && io[2] == 0xbd0edb5aULL, + "x86 add sets the carry flag, vector 2"); + } + { + unsigned long long io[2] = {0xd6bc0d35ccec83e4ULL, 0x3fULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x3fULL, + "x86 shld-free shift: shr by cl, vector 0"); + } + { + unsigned long long io[2] = {0x2d65a8a1cf4ce48eULL, 0x0ULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x2d65a8a1cf4ce48eULL && io[1] == 0x0ULL, + "x86 shld-free shift: shr by cl, vector 1"); + } + { + unsigned long long io[2] = {0xdae98f58edaf5ddULL, 0xcULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0xdae98f58edafULL && io[1] == 0xcULL, + "x86 shld-free shift: shr by cl, vector 2"); + } + { + unsigned long long io[1] = {0x71f2223ff559a0f9ULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0xf9a059f53f22f271ULL, + "x86 bswap reverses byte order, vector 0"); + } + { + unsigned long long io[1] = {0xc447a6fbb54b9c52ULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x529c4bb5fba647c4ULL, + "x86 bswap reverses byte order, vector 1"); + } + { + unsigned long long io[1] = {0xf34de6440ce23540ULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x4035e20c44e64df3ULL, + "x86 bswap reverses byte order, vector 2"); + } + { + unsigned long long io[4] = { + 0x80000000ULL, 0x85c6eecdbd37c64dULL, 0xe051fbafdcfbbb5eULL, 0x7fULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0xbd37c64dULL && io[2] == 0xbd37c64dULL && + io[3] == 0x7fULL, + "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 0"); + } + { + unsigned long long io[4] = { + 0x1ULL, 0x7fULL, 0x7e0269edac79ca6eULL, 0xffffffffffffffffULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x7fULL && io[2] == 0x7fULL && + io[3] == 0xffffffffULL, + "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 1"); + } + { + unsigned long long io[4] = { + 0xffULL, + 0xfc5d96cc82bdb472ULL, + 0x7fffffffffffffffULL, + 0x2355aca2a0edf46dULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x82bdb472ULL && io[2] == 0x82bdb472ULL && + io[3] == 0xa0edf46dULL, + "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 2"); + } + { + unsigned long long io[2] = {0xd29b8652db47179aULL, 0x1ULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0xdb47179aULL, + "x86 xchg swaps a register and memory, vector 0"); + } + { + unsigned long long io[2] = {0x2a12166c6984b1c3ULL, 0xffffffffffffffffULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0xffffffffULL && io[1] == 0x6984b1c3ULL, + "x86 xchg swaps a register and memory, vector 1"); + } + { + unsigned long long io[2] = {0xd57e59721b5c3f00ULL, 0x8161ebbba4c1b5daULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0xa4c1b5daULL && io[1] == 0x1b5c3f00ULL, + "x86 xchg swaps a register and memory, vector 2"); + } + { + unsigned long long io[3] = { + 0x6a08e48807e06ce6ULL, 0x80000000ULL, 0x715314e0aeb3b1f3ULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0x6a020e2ULL && io[1] == 0x80000000ULL && io[2] == 0xaeb3b1f3ULL, + "x86 and masks and sets the sign flag, vector 0"); + } + { + unsigned long long io[3] = { + 0x2dac4420420cf8f6ULL, 0x8000000000000000ULL, 0xffffffffffffffffULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0x420cf8f6ULL && io[1] == 0x0ULL && io[2] == 0xffffffffULL, + "x86 and masks and sets the sign flag, vector 1"); + } + { + unsigned long long io[3] = { + 0xff19d85a9e12e041ULL, 0x7fULL, 0x7fffffffffffffffULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0x9e12e041ULL && io[1] == 0x1ULL && io[2] == 0xffffffffULL, + "x86 and masks and sets the sign flag, vector 2"); + } + { + unsigned long long io[3] = { + 0x67474bfe2512affeULL, 0x0ULL, 0xd9b9851fa699e71cULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x2512affeULL && io[1] == 0x0ULL && io[2] == 0xa699e71cULL, + "x86 memory operand with a struct field offset, vector 0"); + } + { + unsigned long long io[3] = { + 0x32c9fc24972fa9f7ULL, 0x6a5b23a370b4c97bULL, 0x80000000ULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x972fa9f7ULL && io[1] == 0x70b4c97bULL && + io[2] == 0x80000000ULL, + "x86 memory operand with a struct field offset, vector 1"); + } + { + unsigned long long io[3] = { + 0x9c5bc4ac7a21b60aULL, 0x63ce12b6f4f5b47cULL, 0xd2f4c3415c4eb1fdULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x7a21b60aULL && io[1] == 0xf4f5b47cULL && + io[2] == 0x5c4eb1fdULL, + "x86 memory operand with a struct field offset, vector 2"); + } + return 0; +} diff --git a/regression/cbmc/asm_x86/test.desc b/regression/cbmc/asm_x86/test.desc new file mode 100644 index 000000000000..36862aa62698 --- /dev/null +++ b/regression/cbmc/asm_x86/test.desc @@ -0,0 +1,13 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +The x86 inline assembly in main.c is interpreted exactly: if CBMC approximated +any statement (assigning nondeterministic values to its outputs), the +assertions, which check values observed on x86-64 hardware, would fail. diff --git a/regression/cbmc/asm_x86_corner_cases/main.i b/regression/cbmc/asm_x86_corner_cases/main.i new file mode 100644 index 000000000000..4477e46467c8 --- /dev/null +++ b/regression/cbmc/asm_x86_corner_cases/main.i @@ -0,0 +1,62 @@ +// Corner cases of the x86 instruction semantics. "fails" marks properties +// that hardware violates (or that the architecture leaves undefined), so CBMC +// must not prove them. + +// asm goto that is interpreted: the statement jumps if and only if v is 0 +static int branch(int v) +{ + __asm__ goto("testl %0,%0; jz %l[zero]" : : "r"(v) : "cc" : zero); + return 0; +zero: + return 1; +} + +int main(void) +{ + // cmpxchgl in 64-bit mode writes only one of accumulator and destination; + // a 32-bit register write zero-extends, so the other keeps its upper half + unsigned long long rax = 0x1234567800000005ull; // eax == 5 + unsigned mem = 5; + __asm__ __volatile__("lock cmpxchgl %2,%1" + : "+a"(rax), "+m"(mem) + : "r"(7u) + : "cc", "memory"); + __CPROVER_assert(mem == 7, "cmpxchg stored"); + __CPROVER_assert(rax == 0x1234567800000005ull, "accumulator unchanged"); + unsigned long long acc = 1; + unsigned long long dst = 0xabcdef0000000002ull; + __asm__("cmpxchgl %k2,%k1" : "+a"(acc), "+r"(dst) : "r"(9ull) : "cc"); + __CPROVER_assert(acc == 2, "accumulator loaded"); + __CPROVER_assert(dst == 0xabcdef0000000002ull, "destination unchanged"); + + // bsf with a zero source: the destination is undefined (Intel) or unchanged + // (AMD), including the bits above a 32-bit destination + unsigned long long r = 0xdead000000000000ull; + unsigned zero = 0; + __asm__("bsfl %1,%k0" : "+r"(r) : "rm"(zero) : "cc"); + __CPROVER_assert((r >> 32) == 0, "bsf zero-extends"); // fails + + // shifts by more than the width and address arithmetic that wraps are + // defined on the hardware: no undefined-behaviour checks apply + unsigned x = 1; + __asm__("shlb $20,%b0" : "+q"(x) : : "cc"); + __CPROVER_assert((x & 0xff) == 0, "shlb by 20"); + unsigned long long a, b = 0x4000000000000000ull; + __asm__("leaq (,%1,4),%0" : "=r"(a) : "r"(b)); + __CPROVER_assert(a == 0, "lea wraps"); + + // an array operand in a register is the address of its first element + char buf[4] = {0}; + __asm__ volatile("movb $1,(%0)" : : "r"(buf) : "memory"); + __CPROVER_assert(buf[0] == 1, "array operand"); + + // a register variable bound to a register that the template writes + register unsigned long long reg asm("rax") = 5; + __asm__ volatile("addq $1, %%rax" : "+r"(reg)); + __CPROVER_assert(reg == 5, "register variable"); // fails + + __CPROVER_assert(branch(0) == 1, "asm goto jumps"); + __CPROVER_assert(branch(5) == 0, "asm goto falls through"); + + return 0; +} diff --git a/regression/cbmc/asm_x86_corner_cases/test.desc b/regression/cbmc/asm_x86_corner_cases/test.desc new file mode 100644 index 000000000000..caa607db193e --- /dev/null +++ b/regression/cbmc/asm_x86_corner_cases/test.desc @@ -0,0 +1,26 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 24 cmpxchg stored: SUCCESS$ +^\[main\.assertion\.2\] line 25 accumulator unchanged: SUCCESS$ +^\[main\.assertion\.3\] line 29 accumulator loaded: SUCCESS$ +^\[main\.assertion\.4\] line 30 destination unchanged: SUCCESS$ +^\[main\.assertion\.5\] line 37 bsf zero-extends: FAILURE$ +^\[main\.assertion\.6\] line 43 shlb by 20: SUCCESS$ +^\[main\.assertion\.7\] line 46 lea wraps: SUCCESS$ +^\[main\.assertion\.8\] line 51 array operand: SUCCESS$ +^\[main\.assertion\.9\] line 56 register variable: FAILURE$ +^\[main\.assertion\.10\] line 58 asm goto jumps: SUCCESS$ +^\[main\.assertion\.11\] line 59 asm goto falls through: SUCCESS$ +approximating inline assembly statement at .* line 55 function main: writes register rax, which is neither an operand nor clobbered +^VERIFICATION FAILED$ +-- +^warning: ignoring +undefined-shift.*: FAILURE$ +overflow.*: FAILURE$ +approximating inline assembly statement at .* function branch +-- +The properties marked "fails" in main.c are violated on hardware (or left +undefined by the architecture); all others hold on hardware. diff --git a/regression/cbmc/asm_x86_register_operand_constant/main.i b/regression/cbmc/asm_x86_register_operand_constant/main.i new file mode 100644 index 000000000000..6af95ec46d01 --- /dev/null +++ b/regression/cbmc/asm_x86_register_operand_constant/main.i @@ -0,0 +1,50 @@ +// A 32-bit input operand whose value is a known constant stays a constant in +// the register that holds it (the upper bits of the register are zero, as no +// reference reads them). Merging the value into a register with +// nondeterministic upper bits would make the lock word written by xchg +// symbolic, so that both spin loops would unwind to the unwinding bound. +typedef int word_t; +typedef struct +{ + word_t locked; +} spin_t; + +static inline void spin_lock(spin_t *sl) +{ + word_t lock_val = 1; + asm volatile( + "1:\n" + "xchg %[locked], %[lv]\n" + "test %[lv], %[lv]\n" + "jz 3f\n" + "2:\n" + "pause\n" + "cmpl $0, %[locked]\n" + "jnz 2b\n" + "jmp 1b\n" + "3:\n" + : [locked] "=m"(sl->locked), [lv] "=q"(lock_val) + : "[lv]"(lock_val) + : "memory"); +} + +static inline void spin_unlock(spin_t *sl) +{ + word_t v = 0; + asm volatile("xchg %[locked], %[ulv]\n" + : [locked] "=m"(sl->locked), [ulv] "=q"(v) + : "[ulv]"(v) + : "memory"); +} + +int main(void) +{ + spin_t s; + s.locked = 0; + for(int i = 0; i < 4; i++) + { + spin_lock(&s); + spin_unlock(&s); + } + return 0; +} diff --git a/regression/cbmc/asm_x86_register_operand_constant/test.desc b/regression/cbmc/asm_x86_register_operand_constant/test.desc new file mode 100644 index 000000000000..cedfe113e55b --- /dev/null +++ b/regression/cbmc/asm_x86_register_operand_constant/test.desc @@ -0,0 +1,13 @@ +CORE gcc-only +main.i +--arch x86_64 --unwind 5 --unwinding-assertions +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +The outer loop is fully unwound (five iterations cover the four lock/unlock +pairs), so a failing unwinding assertion could only come from a spin loop that +symbolic execution cannot resolve because the lock word is not a constant. diff --git a/src/assembler/Makefile b/src/assembler/Makefile index 65ca8480544b..d0424c455356 100644 --- a/src/assembler/Makefile +++ b/src/assembler/Makefile @@ -1,4 +1,9 @@ SRC = asm_approximation.cpp \ + asm_lowering.cpp \ + asm_operands.cpp \ + asm_semantics.cpp \ + asm_template.cpp \ + asm_x86.cpp \ assembler_lex.yy.cpp \ assembler_parser.cpp \ remove_asm.cpp \ diff --git a/src/assembler/asm_bv_util.h b/src/assembler/asm_bv_util.h new file mode 100644 index 000000000000..2674f7ad5400 --- /dev/null +++ b/src/assembler/asm_bv_util.h @@ -0,0 +1,155 @@ +/*******************************************************************\ + +Module: Inline assembly: bit-vector helpers for instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Bit-vector helpers shared by the instruction semantics of all +/// architectures. All values are of type unsignedbv; signedness is a property +/// of operations, as in the hardware. + +#ifndef CPROVER_ASSEMBLER_ASM_BV_UTIL_H +#define CPROVER_ASSEMBLER_ASM_BV_UTIL_H + +#include +#include +#include +#include + +namespace asm_bv // NOLINT +{ +inline unsignedbv_typet bv(std::size_t width) +{ + return unsignedbv_typet{width}; +} + +inline exprt constant(const mp_integer &value, std::size_t width) +{ + // reduce modulo 2^width so that negative values wrap + const mp_integer modulus = power(2, width); + mp_integer v = value % modulus; + if(v < 0) + v += modulus; + return from_integer(v, bv(width)); +} + +/// \p value converted to \p width bits, truncating or zero-extending +inline exprt resize(const exprt &value, std::size_t width) +{ + return typecast_exprt::conditional_cast(value, bv(width)); +} + +/// \p value sign-extended from \p from to \p to bits +inline exprt sign_extend(const exprt &value, std::size_t from, std::size_t to) +{ + return typecast_exprt{ + typecast_exprt{resize(value, from), signedbv_typet{from}}, bv(to)}; +} + +inline exprt msb(const exprt &value, std::size_t width) +{ + return extractbit_exprt{value, width - 1}; +} + +inline exprt is_zero(const exprt &value) +{ + return equal_exprt{value, from_integer(0, value.type())}; +} + +/// the bits of \p storage with bits [offset, offset+width) replaced by +/// \p value +inline exprt replace_bits( + const exprt &storage, + std::size_t storage_width, + std::size_t offset, + std::size_t width, + const exprt &value) +{ + if(offset == 0 && width == storage_width) + return resize(value, storage_width); + + const mp_integer mask = (power(2, width) - 1) * power(2, offset); + const mp_integer all = power(2, storage_width) - 1; + exprt shifted = resize(value, storage_width); + if(offset != 0) + shifted = shl_exprt{shifted, offset}; + return bitor_exprt{ + bitand_exprt{storage, from_integer(all - mask, bv(storage_width))}, + shifted}; +} + +/// bits [offset, offset+width) of \p storage +inline exprt +extract(const exprt &storage, std::size_t offset, std::size_t width) +{ + return extractbits_exprt{storage, offset, bv(width)}; +} + +/// carry out of \p a + \p b + \p carry_in (Boolean) +inline exprt carry_add( + const exprt &a, + const exprt &b, + const exprt &carry_in, + std::size_t width) +{ + const exprt sum = plus_exprt{ + plus_exprt{resize(a, width + 1), resize(b, width + 1)}, + resize(carry_in, width + 1)}; + return extractbit_exprt{sum, width}; +} + +/// borrow out of \p a - \p b - \p borrow_in (Boolean), i.e., the unsigned +/// value of a is less than that of b + borrow_in +inline exprt borrow_sub( + const exprt &a, + const exprt &b, + const exprt &borrow_in, + std::size_t width) +{ + const exprt diff = minus_exprt{ + minus_exprt{resize(a, width + 1), resize(b, width + 1)}, + resize(borrow_in, width + 1)}; + return extractbit_exprt{diff, width}; +} + +/// signed overflow of \p result = \p a + \p b +inline exprt +overflow_add(const exprt &a, const exprt &b, const exprt &result, std::size_t w) +{ + return and_exprt{ + equal_exprt{msb(a, w), msb(b, w)}, + notequal_exprt{msb(result, w), msb(a, w)}}; +} + +/// signed overflow of \p result = \p a - \p b +inline exprt +overflow_sub(const exprt &a, const exprt &b, const exprt &result, std::size_t w) +{ + return and_exprt{ + notequal_exprt{msb(a, w), msb(b, w)}, + notequal_exprt{msb(result, w), msb(a, w)}}; +} + +/// a Boolean as a one-bit value +inline exprt bool_to_bv(const exprt &b, std::size_t width) +{ + return if_exprt{b, from_integer(1, bv(width)), from_integer(0, bv(width))}; +} + +/// true if the low byte of \p value has an even number of set bits +inline exprt even_parity_low_byte(const exprt &value) +{ + exprt::operandst bits; + for(std::size_t i = 0; i < 8; ++i) + bits.push_back(extractbit_exprt{value, i}); + exprt x = bits[0]; + for(std::size_t i = 1; i < 8; ++i) + x = xor_exprt{x, bits[i]}; + return not_exprt{x}; +} +} // namespace asm_bv + +#endif // CPROVER_ASSEMBLER_ASM_BV_UTIL_H diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp new file mode 100644 index 000000000000..919537f6bd5f --- /dev/null +++ b/src/assembler/asm_lowering.cpp @@ -0,0 +1,597 @@ +/*******************************************************************\ + +Module: Inline assembly: lowering context + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// The state of lowering one inline assembly statement + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "asm_semantics.h" + +#include +#include + +asm_lowering_contextt::asm_lowering_contextt( + symbol_table_baset &_symbol_table, + const irep_idt &_function_id, + const source_locationt &_source_location, + asm_operandst &_operands, + const asm_semanticst &_semantics) + : ns(_symbol_table), + operands(_operands), + semantics(_semantics), + goto_target(nil_exprt{}), + symbol_table(_symbol_table), + function_id(_function_id), + statement_location(_source_location), + location(_source_location) +{ + // The generated code models the hardware, where arithmetic wraps around + // and shifts are defined for all distances: the checks for undefined + // behaviour of C do not apply. Checks of memory accesses still do. + for(const char *check : + {"signed-overflow-check", + "unsigned-overflow-check", + "pointer-overflow-check", + "conversion-check", + "undefined-shift-check", + "float-overflow-check", + "nan-check"}) + { + location.add_pragma(std::string{"disable:"} + check); + } + + const symbolt *function_symbol = symbol_table.lookup(function_id); + mode = function_symbol == nullptr || function_symbol->mode.empty() + ? ID_C + : function_symbol->mode; +} + +symbol_exprt +asm_lowering_contextt::temporary(const typet &type, const std::string &suffix) +{ + const symbolt &symbol = get_fresh_aux_symbol( + type, + id2string(function_id), + "asm_" + suffix, + location, + mode, + symbol_table); + declared.push_back(symbol.symbol_expr()); + return symbol.symbol_expr(); +} + +symbol_exprt +asm_lowering_contextt::hardware_register(const std::string &canonical) +{ + auto it = registers.find(canonical); + if(it != registers.end()) + return it->second; + + const symbol_exprt reg = + temporary(unsignedbv_typet{semantics.register_width()}, canonical); + registers.emplace(canonical, reg); + return reg; +} + +symbol_exprt asm_lowering_contextt::flag(const std::string &name) +{ + auto it = flags.find(name); + if(it != flags.end()) + return it->second; + + const symbol_exprt f = temporary(bool_typet{}, "flag_" + name); + flags.emplace(name, f); + return f; +} + +const symbol_exprt & +asm_lowering_contextt::operand_storage(std::size_t index) const +{ + return storage.at(index); +} + +const symbol_exprt & +asm_lowering_contextt::operand_address(std::size_t index) const +{ + return addresses.at(index); +} + +const exprt &asm_lowering_contextt::operand_immediate(std::size_t index) const +{ + return immediates.at(index); +} + +std::size_t asm_lowering_contextt::operand_width(std::size_t index) const +{ + return width(operands.operands.at(index).expr.type()); +} + +void asm_lowering_contextt::assign(const exprt &lhs, const exprt &rhs) +{ + for(const auto &entry : registers) + { + if(lhs == entry.second) + written_registers.insert(entry.first); + } + body.add(goto_programt::make_assignment(lhs, rhs, location)); +} + +void asm_lowering_contextt::begin_instruction() +{ + atomic = false; + if(body.instructions.empty()) + instruction_start.reset(); + else + instruction_start = std::prev(body.instructions.end()); +} + +void asm_lowering_contextt::end_instruction() +{ + if(!atomic) + return; + atomic = false; + + const goto_programt::targett first = instruction_start.has_value() + ? std::next(*instruction_start) + : body.instructions.begin(); + body.insert_before(first, goto_programt::make_atomic_begin(location)); + body.add(goto_programt::make_atomic_end(location)); +} + +void asm_lowering_contextt::assume(const exprt &condition) +{ + body.add(goto_programt::make_assumption(condition, location)); +} + +void asm_lowering_contextt::add(goto_programt::instructiont instruction) +{ + body.add(std::move(instruction)); +} + +void asm_lowering_contextt::fence( + bool ww, + bool rr, + bool rw, + bool wr, + bool cumulative) +{ + codet code_fence(ID_fence); + code_fence.add_source_location() = location; + if(ww) + code_fence.set(ID_WWfence, true); + if(rr) + code_fence.set(ID_RRfence, true); + if(rw) + code_fence.set(ID_RWfence, true); + if(wr) + code_fence.set(ID_WRfence, true); + if(cumulative) + { + if(ww) + code_fence.set(ID_WWcumul, true); + if(rr) + code_fence.set(ID_RRcumul, true); + if(rw) + code_fence.set(ID_RWcumul, true); + if(wr) + code_fence.set(ID_WRcumul, true); + } + body.add(goto_programt::make_other(code_fence, location)); +} + +void asm_lowering_contextt::call( + const irep_idt &function, + const exprt::operandst &arguments) +{ + const typet void_pointer = pointer_type(empty_typet{}); + + exprt::operandst args; + for(const auto &arg : arguments) + args.push_back(typecast_exprt::conditional_cast(arg, void_pointer)); + + code_typet type{ + code_typet::parameterst{args.size(), code_typet::parametert{void_pointer}}, + empty_typet{}}; + + if(!symbol_table.has_symbol(function)) + { + symbolt symbol{function, type, ID_C}; + symbol.base_name = function; + symbol_table.add(symbol); + } + + called_functions.push_back(function); + + body.add(goto_programt::make_function_call( + code_function_callt{ + symbol_exprt{function, type}.with_source_location(location), + std::move(args)}, + location)); +} + +exprt asm_lowering_contextt::nondet(const typet &type) const +{ + return side_effect_expr_nondett{type, location}; +} + +exprt asm_lowering_contextt::memory(const exprt &address, std::size_t w) const +{ + const pointer_typet target = pointer_type(unsignedbv_typet{w}); + exprt pointer = address; + if(address.type().id() != ID_pointer) + { + // an address held in a register + pointer = typecast_exprt{ + typecast_exprt::conditional_cast( + address, unsignedbv_typet{config.ansi_c.pointer_width}), + target}; + } + else + pointer = typecast_exprt::conditional_cast(address, target); + + return dereference_exprt{pointer}; +} + +std::size_t asm_lowering_contextt::width(const typet &type) const +{ + const typet &t = + type.id() == ID_c_enum_tag ? ns.follow_tag(to_c_enum_tag_type(type)) : type; + + if(t.id() == ID_pointer) + return config.ansi_c.pointer_width; + + if(t.id() == ID_bool) + return 1; + + if( + t.id() == ID_unsignedbv || t.id() == ID_signedbv || t.id() == ID_c_bool || + t.id() == ID_bv || t.id() == ID_c_bit_field || t.id() == ID_c_enum) + { + const auto bits = pointer_offset_bits(t, ns); + if(bits.has_value()) + return numeric_cast_v(*bits); + } + + return 0; +} + +exprt asm_lowering_contextt::to_bits(const exprt &value, std::size_t w) const +{ + const std::size_t own = width(value.type()); + if(own == 0) + return nil_exprt{}; + + exprt bits; + if(value.type().id() == ID_bool) + { + bits = if_exprt{ + value, + from_integer(1, unsignedbv_typet{1}), + from_integer(0, unsignedbv_typet{1})}; + } + else + bits = typecast_exprt::conditional_cast(value, unsignedbv_typet{own}); + + return typecast_exprt::conditional_cast(bits, unsignedbv_typet{w}); +} + +exprt asm_lowering_contextt::from_bits(const exprt &bits, const typet &type) + const +{ + const std::size_t own = width(type); + PRECONDITION(own != 0); + + const exprt resized = + typecast_exprt::conditional_cast(bits, unsignedbv_typet{own}); + + if(type.id() == ID_bool) + return notequal_exprt{resized, from_integer(0, resized.type())}; + + return typecast_exprt::conditional_cast(resized, type); +} + +bool asm_lowering_contextt::prepare( + const std::vector &instructions) +{ + const std::size_t register_width = semantics.register_width(); + + // Which input operands are read above their natural width by some + // reference: those must keep non-deterministic upper bits (see below). + std::set widened; + for(const auto &instruction : instructions) + { + for(const auto &tokens : instruction.operands) + { + for(const auto &token : tokens) + { + if( + token.kind == asm_tokent::kindt::OPERAND && + token.index < operands.operands.size()) + { + const std::size_t w = + width(operands.operands[token.index].expr.type()); + if(w != 0 && semantics.reference_widens(token.modifier, w)) + widened.insert(token.index); + } + } + } + } + + if(goto_target.is_not_nil()) + { + prologue.add(goto_programt::make_assignment( + goto_target, from_integer(0, goto_target.type()), location)); + } + + for(std::size_t i = 0; i < operands.operands.size(); ++i) + { + const asm_operandt &operand = operands.operands[i]; + + switch(operand.kind) + { + case asm_operandt::kindt::REGISTER: + { + const std::size_t w = width(operand.expr.type()); + if(w == 0 || w > register_width) + { + return fail( + "operand " + std::to_string(i) + + " does not fit into a general-purpose register"); + } + + symbol_exprt s = + operand.tied_output.has_value() ? storage.at(*operand.tied_output) + : !operand.fixed_register.empty() + ? hardware_register(operand.fixed_register) + : temporary( + unsignedbv_typet{register_width}, "op" + std::to_string(i)); + storage.emplace(i, s); + + if(operand.is_read) + { + // evaluate the C expression, with the checks that apply to it + code_expressiont evaluate{operand.expr}; + evaluate.add_source_location() = statement_location; + prologue.add(goto_programt::make_other(evaluate, statement_location)); + + // The value, zero-extended to the register width. + const exprt value = to_bits(operand.expr, register_width); + + if(w < register_width && widened.count(i) != 0) + { + // Some reference reads this operand above its natural width, where + // the bits are unspecified. Model them non-deterministically by + // keeping the (uninitialised) upper bits of the register. + const mp_integer mask = power(2, w) - 1; + prologue.add(goto_programt::make_assignment( + s, + bitor_exprt{ + bitand_exprt{ + s, from_integer(power(2, register_width) - 1 - mask, s.type())}, + value}, + location)); + } + else + { + // No reference reads above the operand's width, so zero-extension is + // exact. Unlike the merge above, the register is then a plain + // function of the input, so when the input is a constant the + // register stays a constant and symex constant propagation keeps + // working. (The merge would make, for example, a spinlock word + // written through the operand symbolic, forcing symex to unwind the + // lock's spin loops to the unwinding bound.) + prologue.add(goto_programt::make_assignment(s, value, location)); + } + } + break; + } + + case asm_operandt::kindt::MEMORY: + { + const symbol_exprt a = temporary( + pointer_type(operand.expr.type()), "addr" + std::to_string(i)); + addresses.emplace(i, a); + prologue.add(goto_programt::make_assignment( + a, address_of_exprt{operand.expr}, location)); + break; + } + + case asm_operandt::kindt::IMMEDIATE: + if(width(operand.expr.type()) == 0) + return fail("immediate operand " + std::to_string(i) + " not scalar"); + immediates.emplace(i, operand.expr); + break; + + case asm_operandt::kindt::FLAG_OUTPUT: + break; + } + } + + return true; +} + +void asm_lowering_contextt::define_label(const std::string &name) +{ + const auto t = body.add(goto_programt::make_skip(location)); + if( + !name.empty() && + std::all_of( + name.begin(), name.end(), [](char c) { return c >= '0' && c <= '9'; })) + { + numeric_labels[name].push_back(t); + } + else + label_definitions[name] = t; +} + +bool asm_lowering_contextt::branch( + const asm_tokent &target, + const exprt &condition) +{ + if(target.kind == asm_tokent::kindt::C_LABEL) + { + if(goto_target.is_nil()) + return fail("branch to a C label without asm goto"); + + assign( + goto_target, + if_exprt{ + condition, + from_integer(target.index + 1, goto_target.type()), + goto_target}); + exit_branches.push_back( + body.add(goto_programt::make_incomplete_goto(condition, location))); + return true; + } + + if(target.kind == asm_tokent::kindt::LOCAL_LABEL) + { + const auto &definitions = numeric_labels[target.text]; + if(target.backward) + { + if(definitions.empty()) + return fail("undefined label " + target.text + "b"); + body.add( + goto_programt::make_goto(definitions.back(), condition, location)); + return true; + } + + pending.push_back( + {body.add(goto_programt::make_incomplete_goto(condition, location)), + target.text, + definitions.size(), + true, + true}); + return true; + } + + if(target.kind == asm_tokent::kindt::IDENTIFIER) + { + pending.push_back( + {body.add(goto_programt::make_incomplete_goto(condition, location)), + target.text, + 0, + true, + false}); + return true; + } + + return fail("unsupported branch target"); +} + +goto_programt::targett +asm_lowering_contextt::begin_conditional(const exprt &condition) +{ + return body.add( + goto_programt::make_incomplete_goto(not_exprt{condition}, location)); +} + +void asm_lowering_contextt::end_conditional(goto_programt::targett begin) +{ + begin->complete_goto(body.add(goto_programt::make_skip(location))); +} + +bool asm_lowering_contextt::finish(goto_programt &dest) +{ + exit_label = body.add(goto_programt::make_skip(location)); + + for(auto &branch : pending) + { + goto_programt::targett target; + if(branch.numeric) + { + const auto &definitions = numeric_labels[branch.label]; + if(branch.definitions_before >= definitions.size()) + return fail("undefined label " + branch.label + "f"); + target = definitions[branch.definitions_before]; + } + else + { + auto it = label_definitions.find(branch.label); + if(it == label_definitions.end()) + return fail("undefined label " + branch.label); + target = it->second; + } + branch.instruction->complete_goto(target); + } + + for(auto &branch : exit_branches) + branch->complete_goto(exit_label); + + // GCC binds a register variable (`register long x asm("rax")`) used as a + // register operand to its register. The operand storage does not model + // that, so a write to a named register that is neither an operand nor + // clobbered may be a write to such a variable, and is not modeled. + std::set bound; + for(const auto &operand : operands.operands) + { + if(!operand.fixed_register.empty()) + bound.insert(operand.fixed_register); + } + for(const auto &clobber : operands.clobbers) + { + const std::string canonical = semantics.canonical_register(clobber); + if(!canonical.empty()) + bound.insert(canonical); + } + for(const auto ® : written_registers) + { + if(bound.count(reg) == 0) + { + return fail( + "writes register " + reg + + ", which is neither an operand nor clobbered (and may hold a register " + "variable)"); + } + } + + for(std::size_t i = 0; i < operands.operands.size(); ++i) + { + const asm_operandt &operand = operands.operands[i]; + if(!operand.is_output) + continue; + + if(operand.kind == asm_operandt::kindt::REGISTER) + { + epilogue.add(goto_programt::make_assignment( + operand.expr, from_bits(storage.at(i), operand.expr.type()), location)); + } + else if(operand.kind == asm_operandt::kindt::FLAG_OUTPUT) + { + const exprt value = semantics.condition(operand.flag_condition, *this); + if(value.is_nil()) + return fail("unsupported flag output " + operand.flag_condition); + epilogue.add(goto_programt::make_assignment( + operand.expr, + typecast_exprt::conditional_cast(value, operand.expr.type()), + location)); + } + } + + for(const auto &symbol : declared) + dest.add(goto_programt::make_decl(symbol, location)); + + dest.destructive_append(prologue); + dest.destructive_append(body); + dest.destructive_append(epilogue); + + for(const auto &symbol : declared) + dest.add(goto_programt::make_dead(symbol, location)); + + return true; +} diff --git a/src/assembler/asm_operands.cpp b/src/assembler/asm_operands.cpp new file mode 100644 index 000000000000..7556d5868da5 --- /dev/null +++ b/src/assembler/asm_operands.cpp @@ -0,0 +1,343 @@ +/*******************************************************************\ + +Module: Inline assembly: the operand interface of GCC-style statements + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// The operand interface of GCC-style inline assembly statements + +#include "asm_operands.h" + +#include +#include +#include +#include +#include + +#include "asm_semantics.h" + +#include + +std::optional asm_operandst::find(const irep_idt &name) const +{ + for(std::size_t i = 0; i < operands.size(); ++i) + { + if(!name.empty() && operands[i].name == name) + return i; + } + return {}; +} + +std::optional asm_operandst::find_label(const irep_idt &name) const +{ + for(std::size_t i = 0; i < label_names.size(); ++i) + { + if(label_names[i] == name) + return i; + } + return {}; +} + +static std::string string_of(const exprt &expr) +{ + if(expr.id() == ID_string_constant) + return id2string(to_string_constant(expr).value()); + return {}; +} + +/// Interpret \p constraint for operand \p operand +static bool parse_constraint( + asm_operandt &operand, + const asm_operandst &operands, + const asm_semanticst *semantics, + std::string &error) +{ + const std::string &constraint = operand.constraint; + std::size_t pos = 0; + + // modifiers + while(pos < constraint.size()) + { + const char c = constraint[pos]; + if(c == '=') + operand.is_read = false; + else if(c == '+') + operand.is_read = true; + else if(c == '&' || c == '%' || c == '?' || c == '!' || c == '*') + { + } + else + break; + ++pos; + } + + if(constraint.compare(pos, 3, "@cc") == 0) + { + if(!operand.is_output) + { + error = "flag output constraint on input"; + return false; + } + operand.kind = asm_operandt::kindt::FLAG_OUTPUT; + operand.flag_condition = constraint.substr(pos + 3); + if( + semantics == nullptr || + !semantics->is_flag_output_condition(operand.flag_condition)) + { + error = "unsupported flag output constraint \"" + constraint + "\""; + return false; + } + return true; + } + + bool reg = false, mem = false, imm = false, any = false; + std::string fixed; + + for(; pos < constraint.size(); ++pos) + { + const char c = constraint[pos]; + + if(c == ',') + break; // only the first alternative is used + + if(std::isdigit(static_cast(c))) + { + std::size_t index = 0; + while(pos < constraint.size() && + std::isdigit(static_cast(constraint[pos]))) + { + index = index * 10 + static_cast(constraint[pos] - '0'); + ++pos; + } + --pos; + if(operand.is_output || index >= operands.number_of_outputs) + { + error = "invalid matching constraint \"" + constraint + "\""; + return false; + } + operand.tied_output = index; + continue; + } + + if(c == '[') + { + const auto end = constraint.find(']', pos); + if(end == std::string::npos) + { + error = "malformed constraint \"" + constraint + "\""; + return false; + } + const auto index = + operands.find(constraint.substr(pos + 1, end - pos - 1)); + if( + operand.is_output || !index.has_value() || + *index >= operands.number_of_outputs) + { + error = "invalid matching constraint \"" + constraint + "\""; + return false; + } + operand.tied_output = *index; + pos = end; + continue; + } + + switch(c) + { + case 'm': + case 'o': + case 'V': + case '<': + case '>': + mem = true; + continue; + case 'r': + reg = true; + continue; + case 'g': + case 'X': + any = true; + continue; + case 'i': + case 'n': + case 's': + case 'E': + case 'F': + imm = true; + continue; + default: + break; + } + + asm_semanticst::constraint_classt cls = + asm_semanticst::constraint_classt::UNKNOWN; + std::string fixed_register; + if(semantics != nullptr) + cls = semantics->classify_constraint(constraint, pos, fixed_register); + + switch(cls) + { + case asm_semanticst::constraint_classt::REGISTER: + reg = true; + break; + case asm_semanticst::constraint_classt::MEMORY: + mem = true; + break; + case asm_semanticst::constraint_classt::IMMEDIATE: + imm = true; + break; + case asm_semanticst::constraint_classt::ANY: + any = true; + break; + case asm_semanticst::constraint_classt::FIXED_REGISTER: + if(!fixed.empty() && fixed != fixed_register) + { + error = "constraint \"" + constraint + "\" names several registers"; + return false; + } + fixed = fixed_register; + break; + case asm_semanticst::constraint_classt::IGNORE: + break; + case asm_semanticst::constraint_classt::UNKNOWN: + error = "unsupported constraint \"" + constraint + "\""; + return false; + } + } + + if(operand.tied_output.has_value()) + { + operand.kind = operands.operands[*operand.tied_output].kind; + // an input tied to a memory output is that memory; GCC rejects anything + // else + if( + operand.kind == asm_operandt::kindt::MEMORY && + operand.expr != operands.operands[*operand.tied_output].expr) + { + error = "input operand tied to a memory output is a different object"; + return false; + } + return true; + } + + if(!fixed.empty()) + { + operand.kind = asm_operandt::kindt::REGISTER; + operand.fixed_register = fixed; + } + else if(reg || any) + { + // the compiler may choose a register whenever one is allowed; the effect + // on the C value is the same either way + operand.kind = asm_operandt::kindt::REGISTER; + } + else if(mem) + operand.kind = asm_operandt::kindt::MEMORY; + else if(imm && !operand.is_output) + operand.kind = asm_operandt::kindt::IMMEDIATE; + else + { + error = "unsupported constraint \"" + constraint + "\""; + return false; + } + + // as an rvalue in a register, an array decays to the address of its first + // element, and a function to its address + if(operand.kind == asm_operandt::kindt::REGISTER && !operand.is_output) + { + if(operand.expr.type().id() == ID_array) + { + operand.expr = address_of_exprt{ + index_exprt{operand.expr, from_integer(0, c_index_type())}}; + } + else if(operand.expr.type().id() == ID_code) + operand.expr = address_of_exprt{operand.expr}; + } + + if( + operand.kind == asm_operandt::kindt::MEMORY && !operand.is_output && + !operand.expr.get_bool(ID_C_lvalue) && operand.expr.id() != ID_symbol && + operand.expr.id() != ID_dereference && operand.expr.id() != ID_index && + operand.expr.id() != ID_member) + { + error = "memory input operand is not an lvalue"; + return false; + } + + return true; +} + +bool asm_operandst::parse( + const code_asm_gcct &code, + const asm_semanticst *semantics, + std::string &error) +{ + // basic asm has no colon at all: the four lists are not even nil + is_basic = true; + for(const exprt *list : + {&code.outputs(), &code.inputs(), &code.clobbers(), &code.labels()}) + { + if(!list->id().empty() || !list->operands().empty()) + is_basic = false; + } + + for(const auto &output : code.outputs().operands()) + { + if(output.id() != ID_gcc_asm_output || output.operands().size() != 2) + { + error = "malformed output operand"; + return false; + } + asm_operandt operand; + operand.is_output = true; + operand.constraint = string_of(to_binary_expr(output).op0()); + operand.expr = to_binary_expr(output).op1(); + operand.name = output.get(ID_identifier); + operands.push_back(operand); + } + + number_of_outputs = operands.size(); + + for(const auto &input : code.inputs().operands()) + { + if(input.id() != ID_gcc_asm_input || input.operands().size() != 2) + { + error = "malformed input operand"; + return false; + } + asm_operandt operand; + operand.is_read = true; + operand.constraint = string_of(to_binary_expr(input).op0()); + operand.expr = to_binary_expr(input).op1(); + operand.name = input.get(ID_identifier); + operands.push_back(operand); + } + + for(const auto &clobber : code.clobbers().operands()) + { + std::string name = clobber.id() == ID_gcc_asm_clobbered_register + ? string_of(to_unary_expr(clobber).op()) + : string_of(clobber); + if(!name.empty() && name[0] == '%') + name.erase(0, 1); + clobbers.insert(name); + } + + for(const auto &label : code.labels().operands()) + { + labels.push_back(label.get(ID_identifier)); + const irep_idt &base_name = label.get(ID_C_base_name); + label_names.push_back( + base_name.empty() ? label.get(ID_identifier) : base_name); + } + + for(auto &operand : operands) + { + if(!parse_constraint(operand, *this, semantics, error)) + return false; + } + + return true; +} diff --git a/src/assembler/asm_operands.h b/src/assembler/asm_operands.h new file mode 100644 index 000000000000..cb010c93d474 --- /dev/null +++ b/src/assembler/asm_operands.h @@ -0,0 +1,98 @@ +/*******************************************************************\ + +Module: Inline assembly: the operand interface of GCC-style statements + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// The operands, clobbers and labels of a GCC-style inline assembly statement, +/// with their constraints interpreted. + +#ifndef CPROVER_ASSEMBLER_ASM_OPERANDS_H +#define CPROVER_ASSEMBLER_ASM_OPERANDS_H + +#include +#include + +#include +#include +#include +#include + +class code_asm_gcct; +class asm_semanticst; + +/// One operand of an inline assembly statement +struct asm_operandt +{ + enum class kindt + { + /// held in a register: the model uses block-local storage + REGISTER, + /// the C lvalue itself, accessed in place + MEMORY, + /// a constant + IMMEDIATE, + /// an x86 or AArch64 flag output `=@cc` + FLAG_OUTPUT + }; + + kindt kind = kindt::REGISTER; + bool is_output = false; + /// true for inputs and for `+` outputs + bool is_read = false; + /// the symbolic name used in `%[name]`, if any + irep_idt name; + std::string constraint; + /// the C expression; an lvalue for outputs + exprt expr; + /// for constraints that name one register, the architecture's name of it + std::string fixed_register; + /// for FLAG_OUTPUT: the condition, e.g. "e" for `=@cce` + std::string flag_condition; + /// for inputs with a matching constraint: the output they initialise + std::optional tied_output; +}; + +/// The operand interface of a GCC-style inline assembly statement, numbered as +/// GCC numbers them: outputs first, then inputs. +class asm_operandst +{ +public: + std::vector operands; + std::size_t number_of_outputs = 0; + /// the C labels of `asm goto`, as given in the statement + std::vector labels; + /// the base names of the labels, for `%l[name]` + std::vector label_names; + std::set clobbers; + /// true if the statement has no operand lists at all ("basic asm"), in + /// which case `%` in the template is not special + bool is_basic = false; + + bool clobbers_memory() const + { + return clobbers.count("memory") != 0; + } + + /// \return the index of the operand named \p name, if any + std::optional find(const irep_idt &name) const; + + /// \return the index of the label with base name \p name, if any + std::optional find_label(const irep_idt &name) const; + + /// Interpret the operands of \p code. + /// \param code: the statement + /// \param semantics: for architecture-specific constraint letters; may be + /// nullptr, in which case only generic letters are understood + /// \param [out] error: why the operands could not be interpreted + /// \return true on success + bool parse( + const code_asm_gcct &code, + const asm_semanticst *semantics, + std::string &error); +}; + +#endif // CPROVER_ASSEMBLER_ASM_OPERANDS_H diff --git a/src/assembler/asm_semantics.cpp b/src/assembler/asm_semantics.cpp new file mode 100644 index 000000000000..da2900f0d97f --- /dev/null +++ b/src/assembler/asm_semantics.cpp @@ -0,0 +1,32 @@ +/*******************************************************************\ + +Module: Inline assembly: instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Architecture-independent parts of the inline assembly semantics + +#include "asm_semantics.h" + +#include "asm_x86.h" + +asm_semanticst::constraint_classt asm_semanticst::classify_constraint( + const std::string &, + std::size_t &, + std::string &) const +{ + return constraint_classt::UNKNOWN; +} + +std::unique_ptr make_asm_semantics(const irep_idt &arch) +{ + if(arch == "x86_64" || arch == "x32") + return make_asm_x86_semantics(true); + else if(arch == "i386") + return make_asm_x86_semantics(false); + else + return nullptr; +} diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h new file mode 100644 index 000000000000..2904ae640615 --- /dev/null +++ b/src/assembler/asm_semantics.h @@ -0,0 +1,325 @@ +/*******************************************************************\ + +Module: Inline assembly: instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// The interface between the lowering of inline assembly statements and the +/// architecture-specific instruction semantics. See +/// doc/architectural/inline-assembly.md for the design. + +#ifndef CPROVER_ASSEMBLER_ASM_SEMANTICS_H +#define CPROVER_ASSEMBLER_ASM_SEMANTICS_H + +#include +#include +#include + +#include + +#include "asm_operands.h" // IWYU pragma: export +#include "asm_template.h" // IWYU pragma: export + +#include +#include +#include +#include +#include + +class symbol_table_baset; +class asm_semanticst; + +/// The state of lowering one inline assembly statement: the goto code being +/// built, the storage of register operands, hardware registers and flags, and +/// labels. Architecture semantics use it to emit the effect of instructions. +class asm_lowering_contextt +{ +public: + asm_lowering_contextt( + symbol_table_baset &symbol_table, + const irep_idt &function_id, + const source_locationt &source_location, + asm_operandst &operands, + const asm_semanticst &semantics); + + const namespacet ns; + asm_operandst &operands; + const asm_semanticst &semantics; + + const source_locationt &source_location() const + { + return location; + } + + /// A description of why lowering failed, for diagnostics + std::string failure; + + /// Record a failure reason and return false, for use in `return + /// ctx.fail(...)`. + bool fail(const std::string &reason) + { + if(failure.empty()) + failure = reason; + return false; + } + + /// \name Storage + /// \{ + + /// A fresh block-local variable, declared (with a non-deterministic value) + /// at the start of the statement. + symbol_exprt temporary(const typet &type, const std::string &suffix); + + /// A hardware register, identified by its canonical (full-width) name. Its + /// storage is block-local: the value is non-deterministic unless an operand + /// with a fixed-register constraint initialises it. + symbol_exprt hardware_register(const std::string &canonical); + + /// A condition flag (Boolean), non-deterministic initially + symbol_exprt flag(const std::string &name); + + /// The block-local storage of register operand \p index, a bit-vector of + /// the architecture's register width + const symbol_exprt &operand_storage(std::size_t index) const; + + /// A pointer to the start of memory operand \p index, evaluated before the + /// first instruction + const symbol_exprt &operand_address(std::size_t index) const; + + /// The value of immediate operand \p index + const exprt &operand_immediate(std::size_t index) const; + + /// The width, in bits, of the C expression of operand \p index; 0 if it is + /// not a scalar + std::size_t operand_width(std::size_t index) const; + + /// \} + + /// \name Code + /// \{ + void assign(const exprt &lhs, const exprt &rhs); + void assume(const exprt &condition); + void add(goto_programt::instructiont instruction); + + /// A memory barrier; \p cumulative for barriers that order accesses of all + /// observers (ARM `dmb`, Power `sync`) + void fence(bool ww, bool rr, bool rw, bool wr, bool cumulative); + + /// Make the instruction being lowered an atomic section + void mark_atomic() + { + atomic = true; + } + + /// Start lowering an instruction: code emitted until \ref end_instruction + /// belongs to it. + void begin_instruction(); + + /// Finish lowering an instruction: if it was marked atomic (see + /// \ref mark_atomic), wrap its code in an atomic section. + void end_instruction(); + + /// A call to a library function taking `void *` arguments + void call(const irep_idt &function, const exprt::operandst &arguments); + + /// The functions called via call(), which the caller has to make known + std::vector called_functions; + + /// A non-deterministic value of type \p type + exprt nondet(const typet &type) const; + + /// A memory location of \p width bits at \p address (any pointer or + /// integer type), as an lvalue of type unsignedbv(width) + exprt memory(const exprt &address, std::size_t width) const; + /// \} + + /// \name Control flow + /// \{ + + /// Define the local label \p name at the current position + void define_label(const std::string &name); + + /// Jump to the target named by \p target (a LOCAL_LABEL, C_LABEL, or + /// IDENTIFIER naming a label of this statement) if \p condition holds. + /// \return false if the target is not understood + bool branch(const asm_tokent &target, const exprt &condition); + + /// Start a region of code that only executes if \p condition holds, for + /// conditionally executed instructions; end it with end_conditional + goto_programt::targett begin_conditional(const exprt &condition); + void end_conditional(goto_programt::targett begin); + /// \} + + /// Initialise operand storage; must be called before lowering + /// instructions. + /// \return false if an operand cannot be modelled + /// Initialise operand storage; must be called before lowering + /// instructions. + /// \param instructions: the instructions of the statement, used to decide + /// whether an input operand is read above its natural width + /// \return false if an operand cannot be modelled + bool prepare(const std::vector &instructions); + + /// Assemble the complete lowering of the statement into \p dest: prologue + /// (inputs), instructions, epilogue (outputs). + /// \return false if a branch target could not be resolved + bool finish(goto_programt &dest); + + /// Symbol holding the label chosen by `asm goto` (0 for fall-through, k+1 + /// for label k), or nil if the statement has no labels + exprt goto_target; + + /// \name Conversion between C values and bit-vectors + /// \{ + + /// \p value (a C scalar) as unsignedbv(width), truncating or + /// zero-extending; nil if \p value is not a scalar + exprt to_bits(const exprt &value, std::size_t width) const; + + /// \p bits (a bit-vector) as a value of C type \p type + exprt from_bits(const exprt &bits, const typet &type) const; + + /// The width in bits of the scalar type \p type; 0 if not a scalar + std::size_t width(const typet &type) const; + /// \} + +protected: + symbol_table_baset &symbol_table; + irep_idt function_id; + irep_idt mode; + /// the location of the statement, for code evaluating C expressions + source_locationt statement_location; + /// the location of the statement, with the checks for undefined behaviour of + /// C disabled, for the code modeling the instructions + source_locationt location; + + goto_programt prologue, body, epilogue; + std::list declared; + bool atomic = false; + /// the last instruction of body before the current instruction, if any + std::optional instruction_start; + /// the canonical names of the hardware registers that are written + std::set written_registers; + + std::map registers; + std::map flags; + std::map storage; + std::map addresses; + std::map immediates; + + /// named and numeric labels: current definition + std::map label_definitions; + /// all definitions of numeric labels, in order + std::map> numeric_labels; + struct pending_brancht + { + goto_programt::targett instruction; + std::string label; + /// for numeric labels: the number of definitions of the label that + /// preceded the branch + std::size_t definitions_before; + bool forward; + bool numeric; + }; + std::vector pending; + goto_programt::targett exit_label; + std::vector exit_branches; +}; + +/// The instruction semantics of one architecture +class asm_semanticst +{ +public: + virtual ~asm_semanticst() = default; + + /// A name for diagnostics, e.g. "x86" + virtual std::string name() const = 0; + + /// The lexical conventions of templates + virtual const asm_syntaxt &syntax() const = 0; + + /// The width of general-purpose registers in bits + virtual std::size_t register_width() const = 0; + + /// \return The canonical (full-width) name of the register named \p name + /// (with or without a leading `%`), as used by + /// \ref asm_lowering_contextt::hardware_register, or the empty string if + /// \p name is not a general-purpose register. + virtual std::string canonical_register(const std::string &name) const + { + return {}; + } + + /// \return true if a `%`-reference with the given \p modifier reads an + /// operand of natural width \p natural_width bits at a wider view, so that + /// bits above \p natural_width are observed. For an input operand narrower + /// than the register, those bits are unspecified (except where the + /// architecture defines them), so when any reference to it widens, its + /// register is initialised with non-deterministic upper bits rather than + /// zero-extended. When none do, zero-extension is exact and keeps the + /// register a constant when the input is one. + virtual bool + reference_widens(const std::string &modifier, std::size_t natural_width) const + { + // Conservative default (used only where instruction semantics are absent): + // a bare reference reads the natural width, a modifier may select a wider + // view. + return !modifier.empty(); + } + + /// How a constraint letter is interpreted + enum class constraint_classt + { + UNKNOWN, + REGISTER, + MEMORY, + IMMEDIATE, + /// register, memory, or immediate + ANY, + /// a constraint letter that names one register; the name is returned in + /// the output parameter + FIXED_REGISTER, + /// a letter that is not about the operand location (modifiers like `%`) + IGNORE + }; + + /// Classify an architecture-specific constraint letter. + /// \param constraint: the constraint string + /// \param pos: position of the letter in \p constraint; may be advanced + /// for multi-letter constraints + /// \param [out] fixed_register: the register named by the letter + virtual constraint_classt classify_constraint( + const std::string &constraint, + std::size_t &pos, + std::string &fixed_register) const; + + /// \return true if \p condition is valid in an `=@cc` output + virtual bool is_flag_output_condition(const std::string &condition) const + { + return false; + } + + /// The value of the condition \p condition on the current flags, for + /// `=@cc` outputs; nil if not understood + virtual exprt + condition(const std::string &condition, asm_lowering_contextt &ctx) const + { + return nil_exprt{}; + } + + /// Lower \p instruction, appending its effect to \p ctx. + /// \return false if the instruction is not understood; the caller then + /// approximates the whole statement + virtual bool lower( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const = 0; +}; + +/// \return The instruction semantics for architecture \p arch (as in +/// `config.ansi_c.arch`), or nullptr if there are none. +std::unique_ptr make_asm_semantics(const irep_idt &arch); + +#endif // CPROVER_ASSEMBLER_ASM_SEMANTICS_H diff --git a/src/assembler/asm_template.cpp b/src/assembler/asm_template.cpp new file mode 100644 index 000000000000..1f0a3d22ace1 --- /dev/null +++ b/src/assembler/asm_template.cpp @@ -0,0 +1,399 @@ +/*******************************************************************\ + +Module: Inline assembly: splitting templates into instructions + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Splitting the template of an inline assembly statement into instructions + +#include "asm_template.h" + +#include "asm_operands.h" + +#include +#include + +static bool is_identifier_start(char c, const asm_syntaxt &syntax) +{ + return std::isalpha(static_cast(c)) || c == '_' || c == '.' || + syntax.identifier_characters.find(c) != std::string::npos; +} + +static bool is_identifier_char(char c, const asm_syntaxt &syntax) +{ + return is_identifier_start(c, syntax) || + std::isdigit(static_cast(c)); +} + +static std::string to_lower(std::string s) +{ + std::transform( + s.begin(), + s.end(), + s.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return s; +} + +/// Remove `/* ... */` comments and line comments, and split into statements +static std::vector +split_statements(const std::string &text, const asm_syntaxt &syntax) +{ + std::vector result; + std::string current; + bool in_string = false; + + for(std::size_t i = 0; i < text.size(); ++i) + { + const char c = text[i]; + + if(in_string) + { + current += c; + if(c == '\\' && i + 1 < text.size()) + current += text[++i]; + else if(c == '"') + in_string = false; + continue; + } + + if(c == '"') + { + in_string = true; + current += c; + continue; + } + + if(c == '/' && i + 1 < text.size() && text[i + 1] == '*') + { + const auto end = text.find("*/", i + 2); + i = end == std::string::npos ? text.size() : end + 1; + current += ' '; + continue; + } + + bool comment = false; + for(const auto &marker : syntax.line_comments) + { + if(text.compare(i, marker.size(), marker) == 0) + { + comment = true; + break; + } + } + + if(comment) + { + const auto end = text.find('\n', i); + i = end == std::string::npos ? text.size() : end - 1; + continue; + } + + if(c == '\n' || syntax.separators.find(c) != std::string::npos) + { + result.push_back(current); + current.clear(); + continue; + } + + current += c; + } + + result.push_back(current); + return result; +} + +/// Tokenize one statement, resolving `%` references +static bool tokenize( + const std::string &text, + const asm_syntaxt &syntax, + const asm_operandst *operands, + asm_token_listt &tokens, + std::string &error) +{ + std::size_t i = 0; + while(i < text.size()) + { + const char c = text[i]; + + if(std::isspace(static_cast(c))) + { + ++i; + continue; + } + + if(c == '%' && operands != nullptr) + { + ++i; + if( + i < text.size() && + (text[i] == '%' || text[i] == '|' || text[i] == '{' || text[i] == '}')) + { + // %% is a literal %; %|, %{, %} are dialect markers + if(text[i] == '%') + tokens.push_back({asm_tokent::kindt::PUNCTUATION, "%"}); + ++i; + continue; + } + + if(i < text.size() && text[i] == '=') + { + // a number unique to this instance of the statement + asm_tokent token{asm_tokent::kindt::NUMBER, "0"}; + tokens.push_back(token); + ++i; + continue; + } + + std::string modifier; + while(i < text.size() && + std::isalpha(static_cast(text[i]))) + modifier += text[i++]; + + asm_tokent token{asm_tokent::kindt::OPERAND, ""}; + token.modifier = modifier; + + if(i < text.size() && text[i] == '[') + { + const auto end = text.find(']', i); + if(end == std::string::npos) + { + error = "unterminated operand name"; + return false; + } + const std::string name = text.substr(i + 1, end - i - 1); + i = end + 1; + + if(modifier == "l") + { + const auto label = operands->find_label(name); + if(!label.has_value()) + { + error = "unknown label %l[" + name + "]"; + return false; + } + token.kind = asm_tokent::kindt::C_LABEL; + token.index = *label; + token.modifier.clear(); + } + else + { + const auto index = operands->find(name); + if(!index.has_value()) + { + error = "unknown operand %[" + name + "]"; + return false; + } + token.index = *index; + } + } + else if( + i < text.size() && std::isdigit(static_cast(text[i]))) + { + std::size_t index = 0; + while(i < text.size() && + std::isdigit(static_cast(text[i]))) + index = index * 10 + static_cast(text[i++] - '0'); + + if(modifier == "l") + { + if( + index < operands->operands.size() || + index >= operands->operands.size() + operands->labels.size()) + { + error = + "label reference %l" + std::to_string(index) + " out of range"; + return false; + } + token.kind = asm_tokent::kindt::C_LABEL; + token.index = index - operands->operands.size(); + token.modifier.clear(); + } + else if(index >= operands->operands.size()) + { + error = + "operand reference %" + std::to_string(index) + " out of range"; + return false; + } + else + token.index = index; + } + else + { + error = "unsupported % sequence"; + return false; + } + + tokens.push_back(token); + continue; + } + + if(std::isdigit(static_cast(c))) + { + std::size_t start = i; + bool hex = false; + if( + c == '0' && i + 1 < text.size() && + (text[i + 1] == 'x' || text[i + 1] == 'X')) + { + hex = true; + i += 2; + while(i < text.size() && + std::isxdigit(static_cast(text[i]))) + ++i; + } + else + { + while(i < text.size() && + std::isdigit(static_cast(text[i]))) + ++i; + } + + const std::string digits = text.substr(start, i - start); + + // GNU local label references: 1b, 1f + if( + !hex && i < text.size() && (text[i] == 'b' || text[i] == 'f') && + (i + 1 == text.size() || !is_identifier_char(text[i + 1], syntax))) + { + asm_tokent token{asm_tokent::kindt::LOCAL_LABEL, digits}; + token.backward = text[i] == 'b'; + tokens.push_back(token); + ++i; + continue; + } + + if(i < text.size() && is_identifier_char(text[i], syntax)) + { + error = "malformed number"; + return false; + } + + asm_tokent token{asm_tokent::kindt::NUMBER, digits}; + token.number = + hex ? string2integer(digits.substr(2), 16) : string2integer(digits, 10); + tokens.push_back(token); + continue; + } + + if(is_identifier_start(c, syntax)) + { + std::size_t start = i; + while(i < text.size() && is_identifier_char(text[i], syntax)) + ++i; + tokens.push_back( + {asm_tokent::kindt::IDENTIFIER, text.substr(start, i - start)}); + continue; + } + + if(c == '"') + { + std::string contents; + ++i; + while(i < text.size() && text[i] != '"') + { + if(text[i] == '\\' && i + 1 < text.size()) + ++i; + contents += text[i++]; + } + ++i; + tokens.push_back({asm_tokent::kindt::STRING, contents}); + continue; + } + + tokens.push_back({asm_tokent::kindt::PUNCTUATION, std::string(1, c)}); + ++i; + } + + return true; +} + +bool split_asm_template( + const std::string &text, + const asm_syntaxt &syntax, + const asm_operandst *operands, + std::vector &instructions, + std::string &error) +{ + for(const auto &statement : split_statements(text, syntax)) + { + asm_token_listt tokens; + if(!tokenize(statement, syntax, operands, tokens, error)) + { + error += " in '" + statement + "'"; + return false; + } + + asm_instructiont instruction; + instruction.text = statement; + + std::size_t pos = 0; + + // labels: `name:` or `1:` + while(pos + 1 < tokens.size() && tokens[pos + 1].is_punctuation(':') && + (tokens[pos].kind == asm_tokent::kindt::IDENTIFIER || + tokens[pos].kind == asm_tokent::kindt::NUMBER)) + { + instruction.labels.push_back(tokens[pos].text); + pos += 2; + } + + // prefixes and mnemonic + while(pos < tokens.size() && tokens[pos].is_identifier()) + { + const std::string word = to_lower(tokens[pos].text); + ++pos; + if( + std::find(syntax.prefixes.begin(), syntax.prefixes.end(), word) != + syntax.prefixes.end()) + { + instruction.prefixes.push_back(word); + continue; + } + instruction.mnemonic = word; + break; + } + + if(instruction.mnemonic.empty() && pos < tokens.size()) + { + error = "cannot parse '" + statement + "'"; + return false; + } + + // operands, split at top-level commas + int depth = 0; + asm_token_listt current; + for(; pos < tokens.size(); ++pos) + { + const auto &token = tokens[pos]; + if(token.is_punctuation('(') || token.is_punctuation('[')) + ++depth; + else if(token.is_punctuation(')') || token.is_punctuation(']')) + --depth; + + if(depth == 0 && token.is_punctuation(',')) + { + instruction.operands.push_back(current); + current.clear(); + } + else + current.push_back(token); + } + if(!current.empty()) + instruction.operands.push_back(current); + + if( + instruction.labels.empty() && instruction.prefixes.empty() && + instruction.mnemonic.empty()) + { + continue; + } + + instructions.push_back(instruction); + } + + return true; +} diff --git a/src/assembler/asm_template.h b/src/assembler/asm_template.h new file mode 100644 index 000000000000..85d2570ce8a3 --- /dev/null +++ b/src/assembler/asm_template.h @@ -0,0 +1,115 @@ +/*******************************************************************\ + +Module: Inline assembly: splitting templates into instructions + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Splitting the template of an inline assembly statement into instructions +/// and their operand tokens, with GCC's `%` operand references resolved to +/// operand indices. + +#ifndef CPROVER_ASSEMBLER_ASM_TEMPLATE_H +#define CPROVER_ASSEMBLER_ASM_TEMPLATE_H + +#include + +#include +#include + +class asm_operandst; + +/// A token in an operand of an assembly instruction +struct asm_tokent +{ + enum class kindt + { + /// a name: register, mnemonic part, condition, symbol + IDENTIFIER, + /// a numeric literal, value in `number` + NUMBER, + /// a single punctuation character, in `text` + PUNCTUATION, + /// a `%N` or `%[name]` reference to operand `index`, with `modifier` + OPERAND, + /// a `%lN` or `%l[name]` reference to the C label at `index` of the + /// statement's label list + C_LABEL, + /// a GNU local label reference like `1b` (`backward`) or `1f` + LOCAL_LABEL, + /// a string literal, contents in `text` + STRING + }; + + kindt kind; + std::string text; + mp_integer number = 0; + std::size_t index = 0; + std::string modifier; + bool backward = false; + + bool is_punctuation(char c) const + { + return kind == kindt::PUNCTUATION && text.size() == 1 && text[0] == c; + } + + bool is_identifier() const + { + return kind == kindt::IDENTIFIER; + } +}; + +using asm_token_listt = std::vector; + +/// One instruction (or directive) of an assembly template +struct asm_instructiont +{ + /// Labels defined right before this instruction, e.g., `1` for `1: ldxr` + std::vector labels; + /// Instruction prefixes, e.g., `lock` or `rep` on x86 (lower case) + std::vector prefixes; + /// The mnemonic or directive (lower case); empty for a label-only line + std::string mnemonic; + /// The operands, each a list of tokens, split at top-level commas + std::vector operands; + /// The source text of the instruction, for diagnostics + std::string text; + + bool is_directive() const + { + return !mnemonic.empty() && mnemonic[0] == '.'; + } +}; + +/// Architecture-dependent lexical conventions of assembly templates +struct asm_syntaxt +{ + /// Markers that start a comment extending to the end of the line + std::vector line_comments; + /// Characters that separate statements on one line + std::string separators = ";"; + /// Characters that, in addition to letters, digits, '_' and '.', may occur + /// in identifiers + std::string identifier_characters; + /// Prefixes that may precede a mnemonic in the same statement + std::vector prefixes; +}; + +/// Split \p text into instructions. +/// \param text: the assembly template +/// \param syntax: lexical conventions of the architecture +/// \param operands: the statement's operands, used to resolve `%` references; +/// if nullptr the template is basic assembly, where `%` is not special +/// \param [out] instructions: the instructions +/// \param [out] error: a description of the problem if parsing fails +/// \return true on success +bool split_asm_template( + const std::string &text, + const asm_syntaxt &syntax, + const asm_operandst *operands, + std::vector &instructions, + std::string &error); + +#endif // CPROVER_ASSEMBLER_ASM_TEMPLATE_H diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp new file mode 100644 index 000000000000..95a7c9b60f72 --- /dev/null +++ b/src/assembler/asm_x86.cpp @@ -0,0 +1,1465 @@ +/*******************************************************************\ + +Module: Inline assembly: x86 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for x86 (i386 and x86-64), AT&T syntax + +#include "asm_x86.h" + +#include +#include +#include +#include + +#include "asm_bv_util.h" +#include "asm_semantics.h" + +#include +#include +#include + +using asm_bv::bool_to_bv; +using asm_bv::borrow_sub; +using asm_bv::bv; +using asm_bv::carry_add; +using asm_bv::constant; +using asm_bv::even_parity_low_byte; +using asm_bv::extract; +using asm_bv::is_zero; +using asm_bv::msb; +using asm_bv::overflow_add; +using asm_bv::overflow_sub; +using asm_bv::replace_bits; +using asm_bv::resize; +using asm_bv::sign_extend; + +namespace +{ +struct x86_operandt +{ + enum class kindt + { + REGISTER, + IMMEDIATE, + MEMORY + }; + + kindt kind = kindt::REGISTER; + + // REGISTER + exprt storage; + std::size_t offset = 0; + /// width given by the register name or operand modifier; 0 if unknown + std::size_t width = 0; + /// true for the 8-bit registers %ah..%dh and the h modifier + bool high_byte = false; + + // IMMEDIATE + exprt value; + + // MEMORY + exprt address; + /// segment-relative: an address space the C program does not see + bool environment = false; + /// for memory operands bound to a C lvalue: that lvalue, typed + exprt lvalue; + /// width of the C lvalue, 0 if unknown + std::size_t natural_width = 0; +}; + +const std::set &sized_mnemonics() +{ + static const std::set mnemonics = { + "mov", "movabs", "add", "adc", "sub", "sbb", "and", "or", + "xor", "not", "neg", "inc", "dec", "shl", "sal", "shr", + "sar", "rol", "ror", "bt", "bts", "btr", "btc", "bsf", + "bsr", "tzcnt", "lzcnt", "popcnt", "bswap", "xchg", "xadd", "cmpxchg", + "cmp", "test", "lea", "in", "out"}; + return mnemonics; +} + +const std::set &condition_codes() +{ + static const std::set codes = { + "o", "no", "b", "c", "nae", "ae", "nb", "nc", "e", "z", + "ne", "nz", "be", "na", "a", "nbe", "s", "ns", "p", "pe", + "np", "po", "l", "nge", "ge", "nl", "le", "ng", "g", "nle"}; + return codes; +} + +std::size_t suffix_width(char c) +{ + switch(c) + { + case 'b': + return 8; + case 'w': + return 16; + case 'l': + return 32; + case 'q': + return 64; + default: + return 0; + } +} + +class asm_x86_semanticst : public asm_semanticst +{ +public: + explicit asm_x86_semanticst(bool _x86_64) : x86_64(_x86_64) + { + syntax_conventions.line_comments = {"#"}; + syntax_conventions.separators = ";"; + syntax_conventions.prefixes = { + "lock", "rep", "repe", "repz", "repne", "repnz"}; + + const char *const legacy[] = {"a", "b", "c", "d"}; + for(const char *r : legacy) + { + const std::string canonical = std::string("r") + r + "x"; + if(x86_64) + registers[canonical] = {canonical, 64, 0}; + registers[std::string("e") + r + "x"] = {canonical, 32, 0}; + registers[std::string(r) + "x"] = {canonical, 16, 0}; + registers[std::string(r) + "l"] = {canonical, 8, 0}; + registers[std::string(r) + "h"] = {canonical, 8, 8}; + } + + const char *const index[] = {"si", "di", "bp", "sp"}; + for(const char *r : index) + { + const std::string canonical = std::string("r") + r; + if(x86_64) + { + registers[canonical] = {canonical, 64, 0}; + registers[std::string(r) + "l"] = {canonical, 8, 0}; + } + registers[std::string("e") + r] = {canonical, 32, 0}; + registers[r] = {canonical, 16, 0}; + } + + if(x86_64) + { + for(int i = 8; i <= 15; ++i) + { + const std::string canonical = "r" + std::to_string(i); + registers[canonical] = {canonical, 64, 0}; + registers[canonical + "d"] = {canonical, 32, 0}; + registers[canonical + "w"] = {canonical, 16, 0}; + registers[canonical + "b"] = {canonical, 8, 0}; + } + } + } + + std::string name() const override + { + return x86_64 ? "x86-64" : "i386"; + } + + const asm_syntaxt &syntax() const override + { + return syntax_conventions; + } + + std::size_t register_width() const override + { + return x86_64 ? 64 : 32; + } + + std::string canonical_register(const std::string &name) const override + { + const std::string bare = + !name.empty() && name[0] == '%' ? name.substr(1) : name; + const auto it = registers.find(bare); + return it == registers.end() ? std::string{} : it->second.canonical; + } + + bool reference_widens(const std::string &modifier, std::size_t natural_width) + const override + { + std::size_t read = natural_width <= 8 ? 8 + : natural_width <= 16 ? 16 + : natural_width <= 32 ? 32 + : 64; + if(modifier == "b" || modifier == "h") + read = 8; + else if(modifier == "w") + read = 16; + else if(modifier == "k") + read = 32; + else if(modifier == "q") + read = 64; + return read > natural_width; + } + + constraint_classt classify_constraint( + const std::string &constraint, + std::size_t &pos, + std::string &fixed_register) const override + { + switch(constraint[pos]) + { + case 'a': + fixed_register = "rax"; + return constraint_classt::FIXED_REGISTER; + case 'b': + fixed_register = "rbx"; + return constraint_classt::FIXED_REGISTER; + case 'c': + fixed_register = "rcx"; + return constraint_classt::FIXED_REGISTER; + case 'd': + fixed_register = "rdx"; + return constraint_classt::FIXED_REGISTER; + case 'S': + fixed_register = "rsi"; + return constraint_classt::FIXED_REGISTER; + case 'D': + fixed_register = "rdi"; + return constraint_classt::FIXED_REGISTER; + case 'q': + case 'Q': + case 'R': + case 'l': + case 'U': + return constraint_classt::REGISTER; + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + case 'e': + case 'Z': + case 'G': + case 'C': + return constraint_classt::IMMEDIATE; + default: + // A (edx:eax), x87, vector and mask registers are not modelled + return constraint_classt::UNKNOWN; + } + } + + bool is_flag_output_condition(const std::string &condition) const override + { + return condition_codes().count(condition) != 0; + } + + exprt + condition(const std::string &cc, asm_lowering_contextt &ctx) const override + { + const exprt cf = ctx.flag("cf"), zf = ctx.flag("zf"), sf = ctx.flag("sf"), + of = ctx.flag("of"), pf = ctx.flag("pf"); + + if(cc == "o") + return of; + if(cc == "no") + return not_exprt{of}; + if(cc == "b" || cc == "c" || cc == "nae") + return cf; + if(cc == "ae" || cc == "nb" || cc == "nc") + return not_exprt{cf}; + if(cc == "e" || cc == "z") + return zf; + if(cc == "ne" || cc == "nz") + return not_exprt{zf}; + if(cc == "be" || cc == "na") + return or_exprt{cf, zf}; + if(cc == "a" || cc == "nbe") + return and_exprt{not_exprt{cf}, not_exprt{zf}}; + if(cc == "s") + return sf; + if(cc == "ns") + return not_exprt{sf}; + if(cc == "p" || cc == "pe") + return pf; + if(cc == "np" || cc == "po") + return not_exprt{pf}; + if(cc == "l" || cc == "nge") + return notequal_exprt{sf, of}; + if(cc == "ge" || cc == "nl") + return equal_exprt{sf, of}; + if(cc == "le" || cc == "ng") + return or_exprt{zf, notequal_exprt{sf, of}}; + if(cc == "g" || cc == "nle") + return and_exprt{not_exprt{zf}, equal_exprt{sf, of}}; + return nil_exprt{}; + } + + bool lower(const asm_instructiont &instruction, asm_lowering_contextt &ctx) + const override; + +protected: + bool x86_64; + asm_syntaxt syntax_conventions; + + struct registert + { + std::string canonical; + std::size_t width; + std::size_t offset; + }; + std::map registers; + + bool parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + x86_operandt &operand) const; + + bool parse_register( + const asm_token_listt &tokens, + std::size_t &pos, + asm_lowering_contextt &ctx, + x86_operandt &operand) const; + + bool parse_immediate( + const asm_token_listt &tokens, + std::size_t pos, + asm_lowering_contextt &ctx, + exprt &value) const; + + bool parse_memory( + const asm_token_listt &tokens, + std::size_t pos, + bool environment, + asm_lowering_contextt &ctx, + x86_operandt &operand) const; + + exprt read( + asm_lowering_contextt &ctx, + const x86_operandt &operand, + std::size_t width) const; + + bool write( + asm_lowering_contextt &ctx, + const x86_operandt &operand, + std::size_t width, + const exprt &value) const; + + /// the value of a register operand as an address + exprt + register_address(asm_lowering_contextt &ctx, const x86_operandt ®) const; + + void set_result_flags( + asm_lowering_contextt &ctx, + const exprt &result, + std::size_t width) const + { + ctx.assign(ctx.flag("zf"), is_zero(result)); + ctx.assign(ctx.flag("sf"), msb(result, width)); + ctx.assign(ctx.flag("pf"), even_parity_low_byte(result)); + } + + void set_logic_flags( + asm_lowering_contextt &ctx, + const exprt &result, + std::size_t width) const + { + ctx.assign(ctx.flag("cf"), false_exprt{}); + ctx.assign(ctx.flag("of"), false_exprt{}); + set_result_flags(ctx, result, width); + } + + void undefined_flags( + asm_lowering_contextt &ctx, + std::initializer_list names) const + { + for(const char *name : names) + ctx.assign(ctx.flag(name), ctx.nondet(bool_typet{})); + } + + /// accumulator register (al/ax/eax/rax) of \p width bits + x86_operandt accumulator(asm_lowering_contextt &ctx, std::size_t width) const + { + return named_register(ctx, "rax", width); + } + + x86_operandt named_register( + asm_lowering_contextt &ctx, + const std::string &canonical, + std::size_t width) const + { + x86_operandt op; + op.kind = x86_operandt::kindt::REGISTER; + op.storage = ctx.hardware_register(canonical); + op.width = width; + return op; + } + + static std::size_t + operation_width(const std::vector &operands, std::size_t suffix) + { + if(suffix != 0) + return suffix; + for(const auto &op : operands) + { + if(op.kind == x86_operandt::kindt::REGISTER && op.width != 0) + return op.width; + } + for(const auto &op : operands) + { + if(op.kind == x86_operandt::kindt::MEMORY && op.natural_width != 0) + return op.natural_width; + } + return 0; + } + + bool lower_sized( + const std::string &base, + std::size_t width, + std::vector &operands, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; +}; + +bool asm_x86_semanticst::parse_register( + const asm_token_listt &tokens, + std::size_t &pos, + asm_lowering_contextt &ctx, + x86_operandt &operand) const +{ + if( + pos + 1 < tokens.size() && tokens[pos].is_punctuation('%') && + tokens[pos + 1].is_identifier()) + { + auto it = registers.find(tokens[pos + 1].text); + if(it == registers.end()) + return ctx.fail("unsupported register %" + tokens[pos + 1].text); + operand.kind = x86_operandt::kindt::REGISTER; + operand.storage = ctx.hardware_register(it->second.canonical); + operand.width = it->second.width; + operand.offset = it->second.offset; + pos += 2; + return true; + } + + if(pos < tokens.size() && tokens[pos].kind == asm_tokent::kindt::OPERAND) + { + const asm_tokent &token = tokens[pos]; + const asm_operandt &bound = ctx.operands.operands.at(token.index); + if(bound.kind != asm_operandt::kindt::REGISTER) + return ctx.fail( + "operand %" + std::to_string(token.index) + " is not a register"); + + operand.kind = x86_operandt::kindt::REGISTER; + operand.storage = ctx.operand_storage(token.index); + const std::string &m = token.modifier; + if(m.empty()) + { + const std::size_t w = ctx.operand_width(token.index); + operand.width = w <= 8 ? 8 : w <= 16 ? 16 : w <= 32 ? 32 : 64; + if(operand.width > register_width()) + return ctx.fail("operand too wide"); + } + else if(m == "b") + operand.width = 8; + else if(m == "h") + { + operand.width = 8; + operand.offset = 8; + } + else if(m == "w") + operand.width = 16; + else if(m == "k") + operand.width = 32; + else if(m == "q" && x86_64) + operand.width = 64; + else + return ctx.fail("unsupported operand modifier %" + m); + ++pos; + return true; + } + + return false; +} + +bool asm_x86_semanticst::parse_immediate( + const asm_token_listt &tokens, + std::size_t pos, + asm_lowering_contextt &ctx, + exprt &value) const +{ + bool negative = false; + if(pos < tokens.size() && tokens[pos].is_punctuation('-')) + { + negative = true; + ++pos; + } + + if(pos + 1 != tokens.size()) + return ctx.fail("unsupported immediate"); + + const asm_tokent &token = tokens[pos]; + if(token.kind == asm_tokent::kindt::NUMBER) + { + value = + from_integer(negative ? -token.number : token.number, integer_typet{}); + return true; + } + + if(token.kind == asm_tokent::kindt::OPERAND) + { + const asm_operandt &bound = ctx.operands.operands.at(token.index); + if(bound.kind != asm_operandt::kindt::IMMEDIATE) + return ctx.fail( + "operand %" + std::to_string(token.index) + " is not an immediate"); + value = ctx.operand_immediate(token.index); + if(negative) + value = unary_minus_exprt{value}; + return true; + } + + return ctx.fail("unsupported immediate"); +} + +bool asm_x86_semanticst::parse_memory( + const asm_token_listt &tokens, + std::size_t pos, + bool environment, + asm_lowering_contextt &ctx, + x86_operandt &operand) const +{ + operand.kind = x86_operandt::kindt::MEMORY; + operand.environment = environment; + + // a memory operand bound to a C lvalue + if( + pos + 1 == tokens.size() && + tokens[pos].kind == asm_tokent::kindt::OPERAND && + ctx.operands.operands.at(tokens[pos].index).kind == + asm_operandt::kindt::MEMORY) + { + const std::size_t index = tokens[pos].index; + if(!tokens[pos].modifier.empty()) + return ctx.fail("unsupported memory operand modifier"); + operand.address = ctx.operand_address(index); + operand.lvalue = dereference_exprt{ctx.operand_address(index)}; + operand.natural_width = ctx.operand_width(index); + return true; + } + + // displacement + mp_integer displacement = 0; + exprt displacement_expr = nil_exprt{}; + bool negative = false; + if(pos < tokens.size() && tokens[pos].is_punctuation('-')) + { + negative = true; + ++pos; + } + if(pos < tokens.size() && tokens[pos].kind == asm_tokent::kindt::NUMBER) + { + displacement = negative ? -tokens[pos].number : tokens[pos].number; + ++pos; + } + else if( + pos < tokens.size() && tokens[pos].kind == asm_tokent::kindt::OPERAND && + (tokens[pos].modifier == "c" || tokens[pos].modifier == "P" || + tokens[pos].modifier.empty()) && + ctx.operands.operands.at(tokens[pos].index).kind == + asm_operandt::kindt::IMMEDIATE) + { + displacement_expr = ctx.operand_immediate(tokens[pos].index); + if(negative) + displacement_expr = unary_minus_exprt{displacement_expr}; + ++pos; + } + else if(negative) + return ctx.fail("unsupported displacement"); + + const signedbv_typet offset_type{config.ansi_c.pointer_width}; + exprt offset = from_integer(displacement, offset_type); + if(displacement_expr.is_not_nil()) + { + offset = plus_exprt{ + offset, typecast_exprt::conditional_cast(displacement_expr, offset_type)}; + } + + if(pos == tokens.size()) + { + // an absolute address; only meaningful relative to a segment + if(!environment) + return ctx.fail("absolute memory operand"); + operand.address = offset; + return true; + } + + if(!tokens[pos].is_punctuation('(') || !tokens.back().is_punctuation(')')) + return ctx.fail("unsupported memory operand"); + ++pos; + + exprt address = nil_exprt{}; + + // base + if(!tokens[pos].is_punctuation(',')) + { + x86_operandt base; + if(!parse_register(tokens, pos, ctx, base)) + return ctx.fail("unsupported base register"); + address = register_address(ctx, base); + } + + // index and scale + if(tokens[pos].is_punctuation(',')) + { + ++pos; + x86_operandt index; + if(!parse_register(tokens, pos, ctx, index)) + return ctx.fail("unsupported index register"); + mp_integer scale = 1; + if(tokens[pos].is_punctuation(',')) + { + ++pos; + if(tokens[pos].kind != asm_tokent::kindt::NUMBER) + return ctx.fail("unsupported scale"); + scale = tokens[pos].number; + ++pos; + } + offset = plus_exprt{ + offset, + mult_exprt{ + typecast_exprt{read(ctx, index, index.width), offset_type}, + from_integer(scale, offset_type)}}; + } + + if(!tokens[pos].is_punctuation(')') || pos + 1 != tokens.size()) + return ctx.fail("unsupported memory operand"); + + if(address.is_nil()) + { + // the address is the index and displacement only; within a segment, + // the offset is meaningful as such + operand.address = + environment ? offset + : exprt{typecast_exprt{offset, pointer_type(char_type())}}; + } + else + operand.address = plus_exprt{address, offset}; + + return true; +} + +exprt asm_x86_semanticst::register_address( + asm_lowering_contextt &ctx, + const x86_operandt ®) const +{ + const exprt value = read(ctx, reg, reg.width); + return typecast_exprt{ + resize(value, config.ansi_c.pointer_width), pointer_type(char_type())}; +} + +bool asm_x86_semanticst::parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + x86_operandt &operand) const +{ + if(tokens.empty()) + return ctx.fail("empty operand"); + + // immediate + if(tokens[0].is_punctuation('$')) + { + operand.kind = x86_operandt::kindt::IMMEDIATE; + return parse_immediate(tokens, 1, ctx, operand.value); + } + + // an operand bound to an immediate is printed with its $ + if( + tokens.size() == 1 && tokens[0].kind == asm_tokent::kindt::OPERAND && + tokens[0].modifier.empty() && + ctx.operands.operands.at(tokens[0].index).kind == + asm_operandt::kindt::IMMEDIATE) + { + operand.kind = x86_operandt::kindt::IMMEDIATE; + operand.value = ctx.operand_immediate(tokens[0].index); + return true; + } + + // segment prefix + if( + tokens.size() >= 3 && tokens[0].is_punctuation('%') && + tokens[1].is_identifier() && tokens[2].is_punctuation(':')) + { + const std::string &segment = tokens[1].text; + if(segment != "gs" && segment != "fs") + return ctx.fail("unsupported segment %" + segment); + return parse_memory(tokens, 3, true, ctx, operand); + } + + // register + if( + tokens.size() <= 2 && (tokens[0].is_punctuation('%') || + (tokens[0].kind == asm_tokent::kindt::OPERAND && + ctx.operands.operands.at(tokens[0].index).kind == + asm_operandt::kindt::REGISTER))) + { + std::size_t pos = 0; + if(!parse_register(tokens, pos, ctx, operand)) + return false; + if(pos != tokens.size()) + return ctx.fail("unsupported register operand"); + return true; + } + + return parse_memory(tokens, 0, false, ctx, operand); +} + +exprt asm_x86_semanticst::read( + asm_lowering_contextt &ctx, + const x86_operandt &operand, + std::size_t width) const +{ + switch(operand.kind) + { + case x86_operandt::kindt::REGISTER: + if(operand.offset == 0 && width == register_width()) + return operand.storage; + return extract(operand.storage, operand.offset, width); + + case x86_operandt::kindt::IMMEDIATE: + if(operand.value.type().id() == ID_integer) + { + return constant( + numeric_cast_v(to_constant_expr(operand.value)), width); + } + return typecast_exprt::conditional_cast(operand.value, bv(width)); + + case x86_operandt::kindt::MEMORY: + if(operand.environment) + return ctx.nondet(bv(width)); + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + return ctx.to_bits(operand.lvalue, width); + return ctx.memory(operand.address, width); + } + + UNREACHABLE; +} + +bool asm_x86_semanticst::write( + asm_lowering_contextt &ctx, + const x86_operandt &operand, + std::size_t width, + const exprt &value) const +{ + switch(operand.kind) + { + case x86_operandt::kindt::REGISTER: + { + const std::size_t full = register_width(); + if(width == 32 && x86_64 && operand.offset == 0) + { + // 32-bit writes zero the upper half + ctx.assign(operand.storage, resize(resize(value, 32), full)); + } + else + { + ctx.assign( + operand.storage, + replace_bits(operand.storage, full, operand.offset, width, value)); + } + return true; + } + + case x86_operandt::kindt::IMMEDIATE: + return ctx.fail("write to an immediate"); + + case x86_operandt::kindt::MEMORY: + if(operand.environment) + return true; // not visible to the C program + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + { + ctx.assign( + operand.lvalue, + ctx.from_bits(resize(value, width), operand.lvalue.type())); + } + else + ctx.assign(ctx.memory(operand.address, width), resize(value, width)); + return true; + } + + UNREACHABLE; +} + +bool asm_x86_semanticst::lower( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + const std::string &m = instruction.mnemonic; + + bool lock = false; + for(const auto &prefix : instruction.prefixes) + { + if(prefix == "lock") + lock = true; + else if(prefix == "rep" && m == "nop") + { + // rep; nop is pause + } + else + return ctx.fail("unsupported prefix " + prefix); + } + + if( + !x86_64 && !m.empty() && + (m.back() == 'q' || m == "cdqe" || m == "cqo" || m == "cqto" || + m == "movabs" || m == "movsxd")) + { + return ctx.fail("64-bit instruction in 32-bit mode"); + } + + std::vector operands; + for(const auto &tokens : instruction.operands) + { + if( + m.size() > 1 && m[0] == 'j' && tokens.size() == 1 && + (tokens[0].kind == asm_tokent::kindt::LOCAL_LABEL || + tokens[0].kind == asm_tokent::kindt::C_LABEL || + tokens[0].is_identifier())) + { + continue; // branch target, handled below + } + x86_operandt operand; + if(!parse_operand(tokens, ctx, operand)) + return false; + operands.push_back(operand); + } + + if(lock) + { + bool has_memory = false; + for(const auto &op : operands) + has_memory |= op.kind == x86_operandt::kindt::MEMORY; + if(!has_memory) + return ctx.fail("lock prefix without memory operand"); + ctx.mark_atomic(); + ctx.fence(true, true, true, true, false); + } + + // no-ops and environment instructions + if(m == "nop" || m == "pause" || m == "cli" || m == "sti" || m == "hlt") + return operands.empty() || m == "nop" ? true : ctx.fail("operands"); + + if(m == "clc" || m == "stc" || m == "cmc") + { + const exprt cf = ctx.flag("cf"); + ctx.assign( + cf, + m == "clc" ? exprt{false_exprt{}} + : m == "stc" ? exprt{true_exprt{}} + : exprt{not_exprt{cf}}); + return true; + } + + if(m == "rdtsc" || m == "rdtscp" || m == "rdmsr" || m == "cpuid") + { + std::vector written = {"rax", "rdx"}; + if(m == "rdtscp") + written.push_back("rcx"); + if(m == "cpuid") + written = {"rax", "rbx", "rcx", "rdx"}; + for(const auto &r : written) + { + x86_operandt reg = named_register(ctx, r, 32); + write(ctx, reg, 32, ctx.nondet(bv(32))); + } + return true; + } + + if(m == "wrmsr") + return true; + + if(m == "mfence" || m == "lfence" || m == "sfence") + { + if(!operands.empty()) + return ctx.fail("operands of " + m); + ctx.call("__asm_" + m, {}); + return true; + } + + if(m == "fstcw" || m == "fnstcw" || m == "fldcw") + { + if( + operands.size() != 1 || operands[0].kind != x86_operandt::kindt::MEMORY || + operands[0].environment) + { + return ctx.fail("unsupported operand of " + m); + } + ctx.call("__asm_" + m, {operands[0].address}); + return true; + } + + if(m == "cltq" || m == "cdqe" || m == "cwtl" || m == "cwde") + { + const std::size_t from = (m == "cltq" || m == "cdqe") ? 32 : 16; + const x86_operandt acc = accumulator(ctx, 2 * from); + write( + ctx, acc, 2 * from, sign_extend(read(ctx, acc, from), from, 2 * from)); + return true; + } + + if(m == "cltd" || m == "cdq" || m == "cqto" || m == "cqo") + { + const std::size_t w = (m == "cqto" || m == "cqo") ? 64 : 32; + const x86_operandt acc = accumulator(ctx, w); + const x86_operandt rdx = named_register(ctx, "rdx", w); + write( + ctx, + rdx, + w, + if_exprt{msb(read(ctx, acc, w), w), constant(-1, w), constant(0, w)}); + return true; + } + + // set, cmov, j + if(m.compare(0, 3, "set") == 0 && condition_codes().count(m.substr(3))) + { + if(operands.size() != 1) + return ctx.fail("set requires one operand"); + return write( + ctx, operands[0], 8, bool_to_bv(condition(m.substr(3), ctx), 8)); + } + + if(m.compare(0, 4, "cmov") == 0) + { + std::string cc = m.substr(4); + std::size_t suffix = 0; + if( + !condition_codes().count(cc) && !cc.empty() && + condition_codes().count(cc.substr(0, cc.size() - 1))) + { + suffix = suffix_width(cc.back()); + cc.pop_back(); + } + if(!condition_codes().count(cc) || operands.size() != 2) + return ctx.fail("unsupported " + m); + const std::size_t w = operation_width(operands, suffix); + if(w == 0) + return ctx.fail("unknown operand size"); + return write( + ctx, + operands[1], + w, + if_exprt{ + condition(cc, ctx), + read(ctx, operands[0], w), + read(ctx, operands[1], w)}); + } + + if(m[0] == 'j') + { + if(instruction.operands.size() != 1 || instruction.operands[0].size() != 1) + return ctx.fail("unsupported branch"); + const asm_tokent &target = instruction.operands[0][0]; + if(m == "jmp") + return ctx.branch(target, true_exprt{}); + const std::string cc = m.substr(1); + if(!condition_codes().count(cc)) + return ctx.fail("unsupported branch " + m); + return ctx.branch(target, condition(cc, ctx)); + } + + // movz/movs with explicit sizes, e.g. movzbl, movslq + if( + m.size() == 6 && + (m.compare(0, 4, "movz") == 0 || m.compare(0, 4, "movs") == 0)) + { + const std::size_t from = suffix_width(m[4]), to = suffix_width(m[5]); + if(from != 0 && to != 0 && from < to && operands.size() == 2) + { + const exprt src = read(ctx, operands[0], from); + return write( + ctx, + operands[1], + to, + m[3] == 'z' ? resize(src, to) : sign_extend(src, from, to)); + } + } + + if((m == "movzx" || m == "movsx" || m == "movsxd") && operands.size() == 2) + { + const std::size_t from = operation_width({operands[0]}, 0), + to = operation_width({operands[1]}, 0); + if(from == 0 || to == 0 || from >= to) + return ctx.fail("unsupported " + m); + const exprt src = read(ctx, operands[0], from); + return write( + ctx, + operands[1], + to, + m == "movzx" ? resize(src, to) : sign_extend(src, from, to)); + } + + // instructions with an optional size suffix + std::string base = m; + std::size_t suffix = 0; + if(!sized_mnemonics().count(base)) + { + if( + m.size() > 1 && suffix_width(m.back()) != 0 && + sized_mnemonics().count(m.substr(0, m.size() - 1))) + { + base = m.substr(0, m.size() - 1); + suffix = suffix_width(m.back()); + } + else + return ctx.fail("unsupported instruction " + m); + } + + if(suffix == 64 && !x86_64) + return ctx.fail("64-bit operation on i386"); + + // the size is that of the destination for shifts (whose count may be %cl) + // and for in (whose port may be %dx) + std::vector by_size = operands; + if( + base == "shl" || base == "sal" || base == "shr" || base == "sar" || + base == "rol" || base == "ror" || base == "in") + { + std::reverse(by_size.begin(), by_size.end()); + } + const std::size_t width = operation_width(by_size, suffix); + if(width == 0 && base != "lea") + return ctx.fail( + "cannot determine the operand size of '" + instruction.text + "'"); + + if(base == "xchg") + { + // xchg with a memory operand is implicitly locked + for(const auto &op : operands) + { + if(op.kind == x86_operandt::kindt::MEMORY && !lock) + { + ctx.mark_atomic(); + ctx.fence(true, true, true, true, false); + break; + } + } + } + + return lower_sized(base, width, operands, instruction, ctx); +} + +bool asm_x86_semanticst::lower_sized( + const std::string &base, + std::size_t w, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + auto expect = [&](std::size_t n) + { + if(ops.size() != n) + { + ctx.fail( + "'" + instruction.text + "' requires " + std::to_string(n) + + " operands"); + return false; + } + return true; + }; + + auto temp = [&](const exprt &value, const std::string &suffix) + { + const symbol_exprt t = ctx.temporary(value.type(), suffix); + ctx.assign(t, value); + return t; + }; + + const exprt cf = ctx.flag("cf"); + + if(base == "mov" || base == "movabs") + { + if(!expect(2)) + return false; + return write(ctx, ops[1], w, read(ctx, ops[0], w)); + } + + if(base == "lea") + { + if( + !expect(2) || ops[0].kind != x86_operandt::kindt::MEMORY || + ops[0].environment || ops[1].kind != x86_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported lea"); + } + const std::size_t to = ops[1].width; + const exprt address = typecast_exprt::conditional_cast( + ops[0].address, pointer_type(char_type())); + return write( + ctx, + ops[1], + to, + resize(typecast_exprt{address, bv(config.ansi_c.pointer_width)}, to)); + } + + if( + base == "add" || base == "adc" || base == "sub" || base == "sbb" || + base == "cmp") + { + if(!expect(2)) + return false; + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + const symbol_exprt dst = temp(read(ctx, ops[1], w), "dst"); + const exprt carry_in = + (base == "adc" || base == "sbb") ? bool_to_bv(cf, w) : constant(0, w); + const bool is_add = base == "add" || base == "adc"; + const symbol_exprt result = temp( + is_add ? exprt{plus_exprt{plus_exprt{dst, src}, carry_in}} + : exprt{minus_exprt{minus_exprt{dst, src}, carry_in}}, + "result"); + ctx.assign( + ctx.flag("of"), + is_add ? overflow_add(dst, src, result, w) + : overflow_sub(dst, src, result, w)); + ctx.assign( + cf, + is_add ? carry_add(dst, src, carry_in, w) + : borrow_sub(dst, src, carry_in, w)); + set_result_flags(ctx, result, w); + if(base == "cmp") + return true; + return write(ctx, ops[1], w, result); + } + + if(base == "and" || base == "or" || base == "xor" || base == "test") + { + if(!expect(2)) + return false; + const exprt src = read(ctx, ops[0], w), dst = read(ctx, ops[1], w); + const symbol_exprt result = temp( + base == "or" ? exprt{bitor_exprt{dst, src}} + : base == "xor" ? exprt{bitxor_exprt{dst, src}} + : exprt{bitand_exprt{dst, src}}, + "result"); + set_logic_flags(ctx, result, w); + if(base == "test") + return true; + return write(ctx, ops[1], w, result); + } + + if(base == "not") + { + if(!expect(1)) + return false; + return write(ctx, ops[0], w, bitnot_exprt{read(ctx, ops[0], w)}); + } + + if(base == "neg") + { + if(!expect(1)) + return false; + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + const symbol_exprt result = temp(unary_minus_exprt{src}, "result"); + ctx.assign(cf, not_exprt{is_zero(src)}); + ctx.assign(ctx.flag("of"), equal_exprt{src, constant(power(2, w - 1), w)}); + set_result_flags(ctx, result, w); + return write(ctx, ops[0], w, result); + } + + if(base == "inc" || base == "dec") + { + if(!expect(1)) + return false; + const symbol_exprt dst = temp(read(ctx, ops[0], w), "dst"); + const exprt one = constant(1, w); + const symbol_exprt result = temp( + base == "inc" ? exprt{plus_exprt{dst, one}} + : exprt{minus_exprt{dst, one}}, + "result"); + // CF is not affected + ctx.assign( + ctx.flag("of"), + base == "inc" ? overflow_add(dst, one, result, w) + : overflow_sub(dst, one, result, w)); + set_result_flags(ctx, result, w); + return write(ctx, ops[0], w, result); + } + + if( + base == "shl" || base == "sal" || base == "shr" || base == "sar" || + base == "rol" || base == "ror") + { + // count is an immediate or %cl; a single operand means a count of 1 + x86_operandt count_operand; + x86_operandt *dst_operand; + if(ops.size() == 1) + { + count_operand.kind = x86_operandt::kindt::IMMEDIATE; + count_operand.value = from_integer(1, integer_typet{}); + dst_operand = &ops[0]; + } + else if(ops.size() == 2) + { + count_operand = ops[0]; + dst_operand = &ops[1]; + } + else + return ctx.fail("unsupported shift"); + + const std::size_t mask = w == 64 ? 63 : 31; + const symbol_exprt count = temp( + bitand_exprt{read(ctx, count_operand, 8), constant(mask, 8)}, "count"); + const symbol_exprt dst = temp(read(ctx, *dst_operand, w), "dst"); + const exprt count_w = resize(count, w); + + exprt result; + exprt carry; + if(base == "shl" || base == "sal") + { + result = shl_exprt{dst, count_w}; + // the last bit shifted out: bit w - count of the original + carry = extractbit_exprt{ + lshr_exprt{dst, minus_exprt{constant(w, w), count_w}}, 0}; + } + else if(base == "shr" || base == "sar") + { + result = + base == "shr" + ? exprt{lshr_exprt{dst, count_w}} + : exprt{typecast_exprt{ + ashr_exprt{typecast_exprt{dst, signedbv_typet{w}}, count_w}, + bv(w)}}; + carry = extractbit_exprt{ + lshr_exprt{dst, minus_exprt{count_w, constant(1, w)}}, 0}; + } + else + { + // rotates: the count is taken modulo the width + const exprt n = bitand_exprt{count_w, constant(w - 1, w)}; + const exprt left = + base == "rol" ? n : exprt{minus_exprt{constant(w, w), n}}; + const exprt right = minus_exprt{constant(w, w), left}; + result = if_exprt{ + is_zero(n), + dst, + bitor_exprt{shl_exprt{dst, left}, lshr_exprt{dst, right}}}; + carry = base == "rol" ? extractbit_exprt{result, 0} : msb(result, w); + } + + const symbol_exprt res = temp(result, "result"); + const exprt changed = not_exprt{is_zero(count)}; + const bool beyond_possible = w < mask + 1; + exprt new_carry = carry; + if(beyond_possible && base != "rol" && base != "ror") + { + // counts larger than the width leave CF undefined + new_carry = if_exprt{ + binary_relation_exprt{count, ID_gt, constant(w, 8)}, + ctx.nondet(bool_typet{}), + carry}; + } + ctx.assign(cf, if_exprt{changed, new_carry, cf}); + // OF is only defined for counts of 1 + exprt of_one; + if(base == "shl" || base == "sal") + of_one = notequal_exprt{msb(res, w), carry}; + else if(base == "shr") + of_one = msb(dst, w); + else if(base == "sar") + of_one = false_exprt{}; + else if(base == "rol") + of_one = notequal_exprt{msb(res, w), extractbit_exprt{res, 0}}; + else + of_one = notequal_exprt{msb(res, w), extractbit_exprt{res, w - 2}}; + const exprt of = ctx.flag("of"); + ctx.assign( + of, + if_exprt{ + changed, + if_exprt{ + equal_exprt{count, constant(1, 8)}, of_one, ctx.nondet(bool_typet{})}, + of}); + if(base != "rol" && base != "ror") + { + ctx.assign( + ctx.flag("zf"), if_exprt{changed, is_zero(res), ctx.flag("zf")}); + ctx.assign( + ctx.flag("sf"), if_exprt{changed, msb(res, w), ctx.flag("sf")}); + ctx.assign( + ctx.flag("pf"), + if_exprt{changed, even_parity_low_byte(res), ctx.flag("pf")}); + } + return write(ctx, *dst_operand, w, res); + } + + if(base == "bt" || base == "bts" || base == "btr" || base == "btc") + { + if(!expect(2)) + return false; + + x86_operandt target = ops[1]; + exprt bit; + if( + target.kind == x86_operandt::kindt::MEMORY && + ops[0].kind == x86_operandt::kindt::REGISTER) + { + if(target.environment) + return ctx.fail("bit string operation on segment memory"); + // the bit offset addresses a bit string starting at the operand: + // the word is at address + (offset >> log2(w)) * (w / 8) + const std::size_t pw = config.ansi_c.pointer_width; + const exprt offset = sign_extend(read(ctx, ops[0], w), w, pw); + const std::size_t shift = w == 64 ? 6 : w == 32 ? 5 : 4; + const exprt word_index = typecast_exprt{ + ashr_exprt{typecast_exprt{offset, signedbv_typet{pw}}, shift}, + signedbv_typet{pw}}; + const exprt byte_offset = + mult_exprt{word_index, from_integer(w / 8, signedbv_typet{pw})}; + target.address = plus_exprt{ + typecast_exprt::conditional_cast( + target.address, pointer_type(char_type())), + byte_offset}; + target.lvalue = nil_exprt{}; + target.natural_width = 0; + bit = resize(bitand_exprt{offset, constant(w - 1, pw)}, w); + } + else + bit = bitand_exprt{read(ctx, ops[0], w), constant(w - 1, w)}; + + const symbol_exprt b = temp(resize(bit, w), "bit"); + const symbol_exprt word = temp(read(ctx, target, w), "word"); + ctx.assign(cf, extractbit_exprt{lshr_exprt{word, b}, 0}); + undefined_flags(ctx, {"of", "sf", "pf"}); + if(base == "bt") + return true; + const exprt mask = shl_exprt{constant(1, w), b}; + const exprt result = base == "bts" ? exprt{bitor_exprt{word, mask}} + : base == "btr" + ? exprt{bitand_exprt{word, bitnot_exprt{mask}}} + : exprt{bitxor_exprt{word, mask}}; + return write(ctx, target, w, result); + } + + if(base == "bsf" || base == "bsr" || base == "tzcnt" || base == "lzcnt") + { + if(!expect(2)) + return false; + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + const exprt zero_src = is_zero(src); + if(base == "bsf" || base == "bsr") + { + const exprt index = + base == "bsf" ? exprt{count_trailing_zeros_exprt{src, false, bv(w)}} + : exprt{minus_exprt{ + constant(w - 1, w), + count_leading_zeros_exprt{src, false, bv(w)}}}; + ctx.assign(ctx.flag("zf"), zero_src); + undefined_flags(ctx, {"cf", "of", "sf", "pf"}); + if(ops[1].kind != x86_operandt::kindt::REGISTER) + return ctx.fail("unsupported destination of " + base); + const auto nonzero = ctx.begin_conditional(not_exprt{zero_src}); + if(!write(ctx, ops[1], w, index)) + return false; + ctx.end_conditional(nonzero); + // For a zero source, the destination is undefined (Intel) or unchanged + // (AMD), including the bits above a 32-bit destination: the whole + // register may hold any value. + const auto zero = ctx.begin_conditional(zero_src); + ctx.assign(ops[1].storage, ctx.nondet(ops[1].storage.type())); + ctx.end_conditional(zero); + return true; + } + const symbol_exprt result = temp( + base == "tzcnt" ? exprt{count_trailing_zeros_exprt{src, true, bv(w)}} + : exprt{count_leading_zeros_exprt{src, true, bv(w)}}, + "result"); + ctx.assign(cf, zero_src); + ctx.assign(ctx.flag("zf"), is_zero(result)); + undefined_flags(ctx, {"of", "sf", "pf"}); + return write(ctx, ops[1], w, result); + } + + if(base == "popcnt") + { + if(!expect(2)) + return false; + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + ctx.assign(ctx.flag("zf"), is_zero(src)); + ctx.assign(cf, false_exprt{}); + ctx.assign(ctx.flag("of"), false_exprt{}); + ctx.assign(ctx.flag("sf"), false_exprt{}); + ctx.assign(ctx.flag("pf"), false_exprt{}); + return write(ctx, ops[1], w, popcount_exprt{src, bv(w)}); + } + + if(base == "bswap") + { + if(!expect(1) || (w != 32 && w != 64)) + return ctx.fail("unsupported bswap"); + return write(ctx, ops[0], w, bswap_exprt{read(ctx, ops[0], w), 8}); + } + + if(base == "xchg") + { + if(!expect(2)) + return false; + const symbol_exprt a = temp(read(ctx, ops[0], w), "a"); + const symbol_exprt b = temp(read(ctx, ops[1], w), "b"); + return write(ctx, ops[0], w, b) && write(ctx, ops[1], w, a); + } + + if(base == "xadd") + { + if(!expect(2)) + return false; + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + const symbol_exprt dst = temp(read(ctx, ops[1], w), "dst"); + const symbol_exprt sum = temp(plus_exprt{dst, src}, "sum"); + ctx.assign(ctx.flag("of"), overflow_add(dst, src, sum, w)); + ctx.assign(cf, carry_add(dst, src, constant(0, w), w)); + set_result_flags(ctx, sum, w); + return write(ctx, ops[0], w, dst) && write(ctx, ops[1], w, sum); + } + + if(base == "cmpxchg") + { + if(!expect(2)) + return false; + const x86_operandt acc = accumulator(ctx, w); + const symbol_exprt src = temp(read(ctx, ops[0], w), "src"); + const symbol_exprt dst = temp(read(ctx, ops[1], w), "dst"); + const symbol_exprt expected = temp(read(ctx, acc, w), "expected"); + const symbol_exprt diff = temp(minus_exprt{expected, dst}, "diff"); + ctx.assign(ctx.flag("of"), overflow_sub(expected, dst, diff, w)); + ctx.assign(cf, borrow_sub(expected, dst, constant(0, w), w)); + set_result_flags(ctx, diff, w); + const exprt equal = equal_exprt{expected, dst}; + // Only one of destination and accumulator is written: a 32-bit write + // zero-extends a register, so writing the other one with its own value + // would clear its upper bits. + const auto success = ctx.begin_conditional(equal); + if(!write(ctx, ops[1], w, src)) + return false; + ctx.end_conditional(success); + const auto failure = ctx.begin_conditional(not_exprt{equal}); + if(!write(ctx, acc, w, dst)) + return false; + ctx.end_conditional(failure); + return true; + } + + if(base == "in") + { + if(ops.size() != 2) + return ctx.fail("unsupported in"); + return write(ctx, ops[1], w, ctx.nondet(bv(w))); + } + + if(base == "out") + return ops.size() == 2 ? true : ctx.fail("unsupported out"); + + return ctx.fail("unsupported instruction " + instruction.mnemonic); +} +} // namespace + +std::unique_ptr make_asm_x86_semantics(bool x86_64) +{ + return std::make_unique(x86_64); +} diff --git a/src/assembler/asm_x86.h b/src/assembler/asm_x86.h new file mode 100644 index 000000000000..7b431d417f03 --- /dev/null +++ b/src/assembler/asm_x86.h @@ -0,0 +1,22 @@ +/*******************************************************************\ + +Module: Inline assembly: x86 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for x86 (i386 and x86-64), AT&T syntax + +#ifndef CPROVER_ASSEMBLER_ASM_X86_H +#define CPROVER_ASSEMBLER_ASM_X86_H + +#include + +class asm_semanticst; + +/// \param x86_64: true for 64-bit registers (x86_64, x32) +std::unique_ptr make_asm_x86_semantics(bool x86_64); + +#endif // CPROVER_ASSEMBLER_ASM_X86_H diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index d10cc787afbb..c4b3c66a595c 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -32,6 +32,7 @@ Date: December 2014 #include #include "asm_approximation.h" +#include "asm_semantics.h" #include "assembler_parser.h" #include @@ -51,7 +52,8 @@ class remove_asmt goto_functions(_goto_functions), message_handler(message_handler), log(message_handler), - approximate(_symbol_table) + approximate(_symbol_table), + semantics(make_asm_semantics(config.ansi_c.arch)) { } @@ -67,6 +69,8 @@ class remove_asmt message_handlert &message_handler; messaget log; asm_approximationt approximate; + /// The instruction semantics of the architecture, if there are any + std::unique_ptr semantics; using instructionst = std::list; @@ -95,6 +99,17 @@ class remove_asmt instructionst parse(const irep_idt &assembly, const irep_idt &flavor); + bool lower_gcc( + const irep_idt &function_id, + const code_asm_gcct &code, + goto_programt &dest, + std::string &failure); + + bool lower_instructions( + const std::vector &instructions, + asm_lowering_contextt &ctx, + std::string &failure); + std::optional process_asm( const instructionst &instructions, goto_programt &dest, @@ -547,6 +562,180 @@ static bool output_addresses_may_change(const code_asm_gcct &code) return false; } +/// Translates the gcc-style statement \p code using the instruction semantics +/// of the architecture. +/// +/// \param function_id: Name of function being processed +/// \param code: The inline assembly code statement to translate +/// \param dest: The goto program to append the translation to +/// \param [out] failure: Why \p code is not modeled, if it is not +/// \return Whether all of \p code is modeled +bool remove_asmt::lower_gcc( + const irep_idt &function_id, + const code_asm_gcct &code, + goto_programt &dest, + std::string &failure) +{ + PRECONDITION(semantics != nullptr); + + if(code.asm_text().id() != ID_string_constant) + { + failure = "the template is not a string"; + return false; + } + + asm_operandst operands; + if(!operands.parse(code, semantics.get(), failure)) + return false; + + std::vector instructions; + if(!split_asm_template( + id2string(to_string_constant(code.asm_text()).value()), + semantics->syntax(), + operands.is_basic ? nullptr : &operands, + instructions, + failure)) + { + return false; + } + + asm_lowering_contextt ctx{ + symbol_table, function_id, code.source_location(), operands, *semantics}; + if(code.has_goto_target()) + ctx.goto_target = code.goto_target(); + + if(!ctx.prepare(instructions)) + { + failure = ctx.failure; + return false; + } + + if(!lower_instructions(instructions, ctx, failure)) + return false; + + if(!ctx.finish(dest)) + { + failure = ctx.failure; + return false; + } + + for(const auto &function : ctx.called_functions) + goto_functions.function_map.emplace(function, goto_functiont{}); + + return true; +} + +/// Lowers each of \p instructions into \p ctx. +/// +/// Code in other sections (`.pushsection`/`.section` until `.popsection`/ +/// `.previous`) is not executed in sequence; data there (as in the Linux +/// kernel's jump tables) is ignored, but instructions there (such as +/// exception fixups, which run when an instruction faults) are not modeled. +/// +/// \param instructions: The instructions of the statement +/// \param ctx: The lowering context of the statement +/// \param [out] failure: Why an instruction is not modeled, if one is not +/// \return Whether all \p instructions are modeled +bool remove_asmt::lower_instructions( + const std::vector &instructions, + asm_lowering_contextt &ctx, + std::string &failure) +{ + static const std::set no_effect = { + ".arch_extension", + ".arch", + ".cpu", + ".align", + ".balign", + ".p2align", + ".syntax", + ".att_syntax"}; + + std::vector pending_prefixes; + std::size_t section_depth = 0; + + for(const auto &original : instructions) + { + asm_instructiont instruction = original; + const std::string &m = instruction.mnemonic; + + if(m == ".pushsection" || m == ".section") + { + ++section_depth; + continue; + } + if(m == ".popsection" || m == ".previous") + { + if(section_depth == 0) + { + failure = "unbalanced " + m; + return false; + } + --section_depth; + continue; + } + if(section_depth != 0) + { + if(m.empty() || instruction.is_directive()) + continue; + failure = "instruction '" + instruction.text + + "' in another section (such as an exception fixup)"; + return false; + } + + for(const auto &label : instruction.labels) + ctx.define_label(label); + + if(m.empty()) + { + // a prefix on its own, as in "lock; orq ..." + pending_prefixes.insert( + pending_prefixes.end(), + instruction.prefixes.begin(), + instruction.prefixes.end()); + continue; + } + + instruction.prefixes.insert( + instruction.prefixes.begin(), + pending_prefixes.begin(), + pending_prefixes.end()); + pending_prefixes.clear(); + + if(instruction.is_directive()) + { + if(no_effect.count(m) != 0) + continue; + failure = "unsupported directive '" + instruction.text + "'"; + return false; + } + + ctx.begin_instruction(); + if(!semantics->lower(instruction, ctx)) + { + failure = ctx.failure.empty() + ? "unsupported instruction '" + instruction.text + "'" + : ctx.failure + " in '" + instruction.text + "'"; + return false; + } + ctx.end_instruction(); + } + + if(!pending_prefixes.empty()) + { + failure = "prefix without instruction"; + return false; + } + + if(section_depth != 0) + { + failure = "unterminated section"; + return false; + } + + return true; +} + /// Translates the given inline assembly code (in gcc style) to non-assembly /// goto program instructions, approximating it conservatively if it /// contains an instruction that is not modeled. If all instructions are @@ -561,6 +750,18 @@ void remove_asmt::process_instruction_gcc( const code_asm_gcct &code, goto_programt &dest) { + // with the instruction semantics of the architecture + std::string lowering_failure; + if(semantics != nullptr) + { + goto_programt lowered; + if(lower_gcc(function_id, code, lowered, lowering_failure)) + { + dest.destructive_append(lowered); + return; + } + } + const instructionst instructions = parse(to_string_constant(code.asm_text()).value(), ID_gcc); @@ -583,7 +784,12 @@ void remove_asmt::process_instruction_gcc( std::string reason; if(unknown.has_value()) - reason = not_modeled(*unknown); + { + // why the instruction semantics of the architecture do not model the + // statement, if they were tried + reason = + lowering_failure.empty() ? not_modeled(*unknown) : lowering_failure; + } else if(output_addresses_may_change(code)) { reason = diff --git a/unit/Makefile b/unit/Makefile index b62e536d5308..eba360f66563 100644 --- a/unit/Makefile +++ b/unit/Makefile @@ -48,6 +48,7 @@ SRC += analyses/ai/ai.cpp \ analyses/variable-sensitivity/value_set_pointer_abstract_object/to_predicate.cpp \ analyses/variable-sensitivity/variable_sensitivity_domain/to_predicate.cpp \ analyses/variable-sensitivity/variable_sensitivity_test_helpers.cpp \ + assembler/asm_template.cpp \ ansi-c/allocate_objects.cpp \ ansi-c/expr2c.cpp \ ansi-c/file_converter.cpp \ diff --git a/unit/assembler/asm_template.cpp b/unit/assembler/asm_template.cpp new file mode 100644 index 000000000000..8ff441796c93 --- /dev/null +++ b/unit/assembler/asm_template.cpp @@ -0,0 +1,92 @@ +/*******************************************************************\ + +Module: Unit tests for split_asm_template + +Author: Michael Tautschnig + +\*******************************************************************/ + +#include +#include +#include + +static asm_syntaxt x86_like_syntax() +{ + asm_syntaxt syntax; + syntax.line_comments = {"#"}; + syntax.prefixes = {"lock", "rep"}; + return syntax; +} + +TEST_CASE("split_asm_template", "[core][assembler][asm_template]") +{ + const asm_syntaxt syntax = x86_like_syntax(); + std::vector instructions; + std::string error; + + SECTION("labels, prefixes, comments, and separators") + { + REQUIRE(split_asm_template( + "1: lock; xaddl $1, (%rax) # comment\n\tjnz 1b", + syntax, + nullptr, + instructions, + error)); + REQUIRE(instructions.size() == 3); + + // the label and the prefix form a statement of their own + REQUIRE(instructions[0].labels == std::vector{"1"}); + REQUIRE(instructions[0].prefixes == std::vector{"lock"}); + REQUIRE(instructions[0].mnemonic.empty()); + + REQUIRE(instructions[1].mnemonic == "xaddl"); + REQUIRE(instructions[1].operands.size() == 2); + REQUIRE(instructions[1].operands[0][0].is_punctuation('$')); + + REQUIRE(instructions[2].mnemonic == "jnz"); + REQUIRE(instructions[2].operands.size() == 1); + const asm_tokent &target = instructions[2].operands[0][0]; + REQUIRE(target.kind == asm_tokent::kindt::LOCAL_LABEL); + REQUIRE(target.backward); + } + + SECTION("operand references") + { + asm_operandst operands; + operands.operands.resize(2); + operands.operands[1].name = "value"; + + REQUIRE(split_asm_template( + "movl %k[value], %0", syntax, &operands, instructions, error)); + REQUIRE(instructions.size() == 1); + REQUIRE(instructions[0].operands.size() == 2); + + const asm_tokent &named = instructions[0].operands[0][0]; + REQUIRE(named.kind == asm_tokent::kindt::OPERAND); + REQUIRE(named.index == 1); + REQUIRE(named.modifier == "k"); + + const asm_tokent &numbered = instructions[0].operands[1][0]; + REQUIRE(numbered.kind == asm_tokent::kindt::OPERAND); + REQUIRE(numbered.index == 0); + REQUIRE(numbered.modifier.empty()); + } + + SECTION("references to operands that do not exist") + { + asm_operandst operands; + operands.operands.resize(1); + REQUIRE_FALSE(split_asm_template( + "movl %1, %0", syntax, &operands, instructions, error)); + REQUIRE_FALSE(error.empty()); + } + + SECTION("basic assembly: % is not special") + { + REQUIRE( + split_asm_template("incl %eax", syntax, nullptr, instructions, error)); + REQUIRE(instructions.size() == 1); + REQUIRE(instructions[0].operands.size() == 1); + REQUIRE(instructions[0].operands[0][0].is_punctuation('%')); + } +} diff --git a/unit/assembler/module_dependencies.txt b/unit/assembler/module_dependencies.txt new file mode 100644 index 000000000000..d1b7f1f98af3 --- /dev/null +++ b/unit/assembler/module_dependencies.txt @@ -0,0 +1,3 @@ +assembler +testing-utils +util diff --git a/unit/module_dependencies.txt b/unit/module_dependencies.txt index ffb354023654..fe9421bd0157 100644 --- a/unit/module_dependencies.txt +++ b/unit/module_dependencies.txt @@ -1,4 +1,5 @@ ansi-c +assembler cbmc cpp goto-checker From 894887260176d2dade4d84370f237351f4cc5871 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 07:31:39 +0000 Subject: [PATCH 051/100] Inline assembly: do not access memory at addresses CBMC cannot relate 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 --- doc/architectural/inline-assembly.md | 11 ++ doc/cprover-manual/modeling-inline-asm.md | 7 +- regression/cbmc/asm_unknown_address/main.i | 63 ++++++++++ regression/cbmc/asm_unknown_address/test.desc | 25 ++++ src/assembler/asm_lowering.cpp | 119 ++++++++++++++++-- src/assembler/asm_semantics.h | 48 ++++++- src/assembler/remove_asm.cpp | 8 +- 7 files changed, 270 insertions(+), 11 deletions(-) create mode 100644 regression/cbmc/asm_unknown_address/main.i create mode 100644 regression/cbmc/asm_unknown_address/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 61a395dd8680..e717a23ad146 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -66,6 +66,17 @@ one of them is not interpreted: - A write to a hardware register that is neither bound to an operand by its constraint nor clobbered may be a write to a register variable (`register long x asm("rax")`), which the front end does not record. +- A memory access must not use an address that may depend on a value that + is not modeled: a hardware register that the statement does not + initialise (which may hold a register variable), a nondeterministic value + (such as a system register, or `rdtsc`), an output operand read before it + is written, or memory that such a value was stored to. CBMC cannot relate + such an address to the objects it may point to, so the access would change + no object. `asm_lowering_contextt::depends_on_unknown` tracks these values + per position: an unconditional assignment of a known value makes its + target known; a label joins the states of the fall-through and of the + forward branches to it; a backward branch must not make a value unknown + that its target took as known. - An input tied to a memory output must be the same object. An instruction that is atomic on the hardware (on x86: lock-prefixed diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index adb64fe49217..4248ffcfbbda 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -76,7 +76,12 @@ instructions are listed in the tables below) if it: as the Linux kernel's jump tables) is ignored; - writes a register that is neither bound to an operand nor clobbered: as CBMC does not track register variables (`register long x asm("rax")`), - such a write may change a C variable. + such a write may change a C variable; +- accesses memory at an address that may be computed from a value that CBMC + does not model, such as a register that the statement does not initialise + (which may hold a register variable) or a value that is nondeterministic + (such as one produced by `rdtsc`): CBMC could not tell which object the + access changes. A lock-prefixed instruction (or `xchg` with a memory operand) is an atomic section with a full fence; the other instructions of the statement are not diff --git a/regression/cbmc/asm_unknown_address/main.i b/regression/cbmc/asm_unknown_address/main.i new file mode 100644 index 000000000000..307b81dcb50e --- /dev/null +++ b/regression/cbmc/asm_unknown_address/main.i @@ -0,0 +1,63 @@ +int x, y; + +int main(void) +{ + int *px = &x; + unsigned long c, slot; + + // rcx holds the register variable p, but the statement does not + // initialise it: the store is approximated + x = 0; + { + register int *p __asm__("rcx") = &x; + __asm__ volatile("movl %0, (%%rcx)" : : "r"(5), "r"(p) : "memory"); + } + __CPROVER_assert(x == 0, "store via register variable"); + + // rcx initialised from an operand before the store: interpreted + x = 0; + __asm__ volatile("mov %0, %%rcx\n movl %1, (%%rcx)" + : + : "r"(px), "r"(5) + : "rcx", "memory"); + __CPROVER_assert(x == 5, "store via initialised register"); + + // a forward branch skips the initialisation + x = 0; + __asm__ volatile("test %2, %2\n jz 1f\n mov %0, %%rcx\n1: movl %1, (%%rcx)" + : + : "r"(px), "r"(5), "r"(c) + : "rcx", "cc", "memory"); + __CPROVER_assert(x == 0, "initialisation skipped by forward branch"); + + // a backward branch makes rcx unknown at the store + x = 0; + __asm__ volatile( + "mov %0, %%rcx\n1: movl %1, (%%rcx)\n rdtsc\n mov %%rax, %%rcx\n" + " test %2, %2\n jnz 1b" + : + : "r"(px), "r"(5), "r"(c) + : "rax", "rcx", "rdx", "cc", "memory"); + __CPROVER_assert(x == 0, "register made unknown by backward branch"); + + // an unknown value stored to memory and loaded as an address + x = 0; + __asm__ volatile( + "rdtsc\n mov %%rax, (%0)\n mov (%0), %%rcx\n movl %1, (%%rcx)" + : + : "r"(&slot), "r"(5) + : "rax", "rcx", "rdx", "memory"); + __CPROVER_assert(x == 0, "unknown address loaded from memory"); + + // a loop with known values only: interpreted + y = 0; + __asm__ volatile( + "mov %0, %%rcx\n mov $3, %%edx\n" + "1: addl $1, (%%rcx)\n dec %%edx\n jnz 1b" + : + : "r"(&y) + : "rcx", "rdx", "cc", "memory"); + __CPROVER_assert(y == 3, "loop with known addresses"); + + return 0; +} diff --git a/regression/cbmc/asm_unknown_address/test.desc b/regression/cbmc/asm_unknown_address/test.desc new file mode 100644 index 000000000000..3c7911a5df3d --- /dev/null +++ b/regression/cbmc/asm_unknown_address/test.desc @@ -0,0 +1,25 @@ +CORE gcc-only +main.i +--arch x86_64 --unwind 4 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 15 store via register variable: FAILURE$ +^\[main\.assertion\.2\] line 23 store via initialised register: SUCCESS$ +^\[main\.assertion\.3\] line 31 initialisation skipped by forward branch: FAILURE$ +^\[main\.assertion\.4\] line 41 register made unknown by backward branch: FAILURE$ +^\[main\.assertion\.5\] line 50 unknown address loaded from memory: FAILURE$ +^\[main\.assertion\.6\] line 60 loop with known addresses: SUCCESS$ +approximating inline assembly statement at .* line 13 function main: memory access at an address computed from a value that is not modeled +approximating inline assembly statement at .* line 27 function main: memory access at an address computed from a value that is not modeled +approximating inline assembly statement at .* line 35 function main: branch with values that are not modeled to code that relies on them +approximating inline assembly statement at .* line 45 function main: memory access at an address computed from a value that is not modeled +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (19|54) function main +-- +A memory access at an address that may depend on a value CBMC does not model +(here: registers the statement does not initialise, or the result of rdtsc) +would change no object, as CBMC cannot relate such an address to an object. +Such statements are approximated. The assertions that fail may be violated +on hardware (x or y is then changed); the others hold on hardware. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 919537f6bd5f..113e022d703a 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -14,6 +14,7 @@ Author: Michael Tautschnig #include #include #include +#include #include #include #include @@ -85,9 +86,62 @@ asm_lowering_contextt::hardware_register(const std::string &canonical) const symbol_exprt reg = temporary(unsignedbv_typet{semantics.register_width()}, canonical); registers.emplace(canonical, reg); + // unless an operand initialises it (see prepare); it was unknown at all + // positions lowered so far + mark_unknown(reg.identifier()); + for(auto &branch : pending) + branch.unknown.insert(reg.identifier()); + for(auto &label : unknown_at_label) + label.second.insert(reg.identifier()); return reg; } +const irep_idt asm_lowering_contextt::unknown_memory = "asm::memory"; + +void asm_lowering_contextt::mark_unknown(const irep_idt &identifier) +{ + unknown.insert(identifier); + ever_unknown.insert(identifier); +} + +bool asm_lowering_contextt::depends_on_unknown(const exprt &expr) const +{ + return has_subexpr( + expr, + [this](const exprt &e) + { + if(e.id() == ID_symbol) + return unknown.count(to_symbol_expr(e).identifier()) != 0; + // nondeterministic Booleans (such as undefined flags) cannot be + // addresses + if(e.id() == ID_side_effect) + return to_side_effect_expr(e).get_statement() == ID_nondet && + e.type().id() != ID_bool; + if(e.id() == ID_dereference) + return unknown.count(unknown_memory) != 0; + return false; + }); +} + +bool asm_lowering_contextt::check_unknown_at_target( + goto_programt::const_targett target, + const std::set &at_branch) +{ + const auto entry = unknown_at_label.find(&*target); + INVARIANT( + entry != unknown_at_label.end(), "branch targets are label definitions"); + if(!std::includes( + entry->second.begin(), + entry->second.end(), + at_branch.begin(), + at_branch.end())) + { + return fail( + "branch with values that are not modeled to code that relies on them"); + } + return true; +} + symbol_exprt asm_lowering_contextt::flag(const std::string &name) { auto it = flags.find(name); @@ -128,6 +182,22 @@ void asm_lowering_contextt::assign(const exprt &lhs, const exprt &rhs) if(lhs == entry.second) written_registers.insert(entry.first); } + + const bool unknown_value = depends_on_unknown(rhs); + if(lhs.id() == ID_symbol) + { + const irep_idt &identifier = to_symbol_expr(lhs).identifier(); + if(unknown_value) + mark_unknown(identifier); + else if(conditional_depth == 0) + unknown.erase(identifier); + } + else if(unknown_value) + { + // memory, which is never known again + mark_unknown(unknown_memory); + } + body.add(goto_programt::make_assignment(lhs, rhs, location)); } @@ -229,8 +299,14 @@ exprt asm_lowering_contextt::nondet(const typet &type) const return side_effect_expr_nondett{type, location}; } -exprt asm_lowering_contextt::memory(const exprt &address, std::size_t w) const +exprt asm_lowering_contextt::memory(const exprt &address, std::size_t w) { + if(depends_on_unknown(address)) + fail( + "memory access at an address computed from a value that is not " + "modeled (such as a register that the statement does not " + "initialise, which may hold a register variable)"); + const pointer_typet target = pointer_type(unsignedbv_typet{w}); exprt pointer = address; if(address.type().id() != ID_pointer) @@ -362,7 +438,13 @@ bool asm_lowering_contextt::prepare( unsignedbv_typet{register_width}, "op" + std::to_string(i)); storage.emplace(i, s); - if(operand.is_read) + if(!operand.is_read) + { + // until the instructions write it; if an input is tied to it, it is + // initialised with that input below + mark_unknown(s.identifier()); + } + else { // evaluate the C expression, with the checks that apply to it code_expressiont evaluate{operand.expr}; @@ -385,6 +467,7 @@ bool asm_lowering_contextt::prepare( s, from_integer(power(2, register_width) - 1 - mask, s.type())}, value}, location)); + mark_unknown(s.identifier()); } else { @@ -396,6 +479,7 @@ bool asm_lowering_contextt::prepare( // written through the operand symbolic, forcing symex to unwind the // lock's spin loops to the unwinding bound.) prologue.add(goto_programt::make_assignment(s, value, location)); + unknown.erase(s.identifier()); } } break; @@ -428,13 +512,25 @@ bool asm_lowering_contextt::prepare( void asm_lowering_contextt::define_label(const std::string &name) { const auto t = body.add(goto_programt::make_skip(location)); - if( + // Join the forward branches to the label lowered so far. Backward branches, + // lowered later, are checked against the result (check_unknown_at_target). + const bool numeric = !name.empty() && std::all_of( - name.begin(), name.end(), [](char c) { return c >= '0' && c <= '9'; })) + name.begin(), name.end(), [](char c) { return c >= '0' && c <= '9'; }); + const std::size_t definitions = numeric ? numeric_labels[name].size() : 0; + for(const auto &branch : pending) { - numeric_labels[name].push_back(t); + if( + branch.label == name && branch.numeric == numeric && + (!numeric || branch.definitions_before == definitions)) + { + unknown.insert(branch.unknown.begin(), branch.unknown.end()); + } } + unknown_at_label[&*t] = unknown; + if(numeric) + numeric_labels[name].push_back(t); else label_definitions[name] = t; } @@ -466,6 +562,8 @@ bool asm_lowering_contextt::branch( { if(definitions.empty()) return fail("undefined label " + target.text + "b"); + if(!check_unknown_at_target(definitions.back(), unknown)) + return false; body.add( goto_programt::make_goto(definitions.back(), condition, location)); return true; @@ -476,7 +574,8 @@ bool asm_lowering_contextt::branch( target.text, definitions.size(), true, - true}); + true, + unknown}); return true; } @@ -487,7 +586,8 @@ bool asm_lowering_contextt::branch( target.text, 0, true, - false}); + false, + unknown}); return true; } @@ -497,12 +597,15 @@ bool asm_lowering_contextt::branch( goto_programt::targett asm_lowering_contextt::begin_conditional(const exprt &condition) { + ++conditional_depth; return body.add( goto_programt::make_incomplete_goto(not_exprt{condition}, location)); } void asm_lowering_contextt::end_conditional(goto_programt::targett begin) { + PRECONDITION(conditional_depth > 0); + --conditional_depth; begin->complete_goto(body.add(goto_programt::make_skip(location))); } @@ -527,6 +630,8 @@ bool asm_lowering_contextt::finish(goto_programt &dest) return fail("undefined label " + branch.label); target = it->second; } + if(!check_unknown_at_target(target, branch.unknown)) + return false; branch.instruction->complete_goto(target); } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index 2904ae640615..5f890cfca0b8 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -132,8 +132,26 @@ class asm_lowering_contextt exprt nondet(const typet &type) const; /// A memory location of \p width bits at \p address (any pointer or - /// integer type), as an lvalue of type unsignedbv(width) - exprt memory(const exprt &address, std::size_t width) const; + /// integer type), as an lvalue of type unsignedbv(width). Records a failure + /// if \p address may depend on a value that is not modeled (see + /// \ref depends_on_unknown). + exprt memory(const exprt &address, std::size_t width); + /// \} + + /// \name Values that are not modeled + /// Some values are modeled as nondeterministic: those of hardware registers + /// that the statement does not initialise (which may hold a register + /// variable, `register int *p asm("r1")`, that CBMC does not track), of + /// system registers, and of output operands that are read before they are + /// written. This over-approximates the value, but CBMC cannot relate a + /// nondeterministic address to the objects it may point to, so memory + /// accessed at such an address would not change any object. Hence such + /// accesses make the lowering fail. + /// \{ + + /// \return True iff \p expr may depend on a value that is not modeled at + /// the current position of the statement + bool depends_on_unknown(const exprt &expr) const; /// \} /// \name Control flow @@ -204,6 +222,30 @@ class asm_lowering_contextt /// the canonical names of the hardware registers that are written std::set written_registers; + /// The symbols that may hold a value that is not modeled at the current + /// position, and \ref unknown_memory if memory may hold such a value + std::set unknown; + /// all symbols that held a value that is not modeled at some position + /// lowered so far, a superset of \ref unknown at any of these positions + std::set ever_unknown; + /// \ref unknown at each label definition + std::map> + unknown_at_label; + /// the number of conditional regions (\ref begin_conditional) that are + /// open: an assignment in one of them does not make its target known + std::size_t conditional_depth = 0; + /// stands for memory in \ref unknown + static const irep_idt unknown_memory; + + void mark_unknown(const irep_idt &identifier); + + /// Fail if a branch to \p target with \ref unknown being \p at_branch + /// would make a value unknown at \p target that was taken as known when + /// lowering the code at \p target. + bool check_unknown_at_target( + goto_programt::const_targett target, + const std::set &at_branch); + std::map registers; std::map flags; std::map storage; @@ -223,6 +265,8 @@ class asm_lowering_contextt std::size_t definitions_before; bool forward; bool numeric; + /// \ref unknown at the branch + std::set unknown; }; std::vector pending; goto_programt::targett exit_label; diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index c4b3c66a595c..f11f933666f9 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -685,6 +685,11 @@ bool remove_asmt::lower_instructions( for(const auto &label : instruction.labels) ctx.define_label(label); + if(!ctx.failure.empty()) + { + failure = ctx.failure; + return false; + } if(m.empty()) { @@ -711,7 +716,8 @@ bool remove_asmt::lower_instructions( } ctx.begin_instruction(); - if(!semantics->lower(instruction, ctx)) + // semantics may also report a problem via ctx.fail and carry on + if(!semantics->lower(instruction, ctx) || !ctx.failure.empty()) { failure = ctx.failure.empty() ? "unsupported instruction '" + instruction.text + "'" From 639fae42f30898348c13330c1dc6736c84650201 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:20:39 +0000 Subject: [PATCH 052/100] remove_asm: approximate statements whose labels data refers to 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 --- doc/architectural/inline-assembly.md | 11 +- doc/cprover-manual/modeling-inline-asm.md | 12 +- .../cbmc/asm_x86_section_references/main.i | 103 ++++++++++++++++++ .../cbmc/asm_x86_section_references/test.desc | 25 +++++ src/assembler/remove_asm.cpp | 88 +++++++++++++-- 5 files changed, 224 insertions(+), 15 deletions(-) create mode 100644 regression/cbmc/asm_x86_section_references/main.i create mode 100644 regression/cbmc/asm_x86_section_references/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index e717a23ad146..02edc3978d40 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -62,7 +62,16 @@ one of them is not interpreted: - Every instruction, prefix, operand form, and directive must be understood. - Instructions in another section (`.pushsection`/`.section`) are not executed in sequence; they may be executed when another instruction faults - (exception fixups). Data in other sections is ignored. + (exception fixups). Data in another section that refers to a label of the + statement, or to a C label of `asm goto`, records the label for run-time + patching (the Linux kernel's jump tables, `__jump_table`, by which a `jmp` + becomes a `nop` or vice versa) or as the continuation of a fault (exception + tables, `__ex_table`): the statement may then jump where its instructions + do not show. Such references are allowed only in `.smp_locks`, which + records lock prefixes that the kernel replaces by a no-op prefix on a + single processor, and in the sections that the linker discards + (`.discard.*`). Other data in other sections is ignored. This check is in + `remove_asmt::lower_instructions` and applies to all architectures. - A write to a hardware register that is neither bound to an operand by its constraint nor clobbered may be a write to a register variable (`register long x asm("rax")`), which the front end does not record. diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 4248ffcfbbda..0816c74b8b9b 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -72,8 +72,16 @@ instructions are listed in the tables below) if it: - contains an instruction, operand, prefix, or directive that the semantics do not support, or instructions in another section (such as exception - fixups, which run when an instruction faults); data in other sections (such - as the Linux kernel's jump tables) is ignored; + fixups, which run when an instruction faults); +- contains data in another section that refers to one of its labels or, for + `asm goto`, to one of its C labels, other than in `.smp_locks` (the lock + prefixes that the Linux kernel removes on a single processor) and the + sections that the linker discards (`.discard.*`): such data records the + label for run-time patching, as do the Linux kernel's jump tables (static + branches), or as the place where execution continues when an instruction + faults, as do exception tables. The approximation of such an `asm goto` + statement jumps to any of its labels. Other data in other sections is + ignored; - writes a register that is neither bound to an operand nor clobbered: as CBMC does not track register variables (`register long x asm("rax")`), such a write may change a C variable; diff --git a/regression/cbmc/asm_x86_section_references/main.i b/regression/cbmc/asm_x86_section_references/main.i new file mode 100644 index 000000000000..3e8edeb72608 --- /dev/null +++ b/regression/cbmc/asm_x86_section_references/main.i @@ -0,0 +1,103 @@ +// Data in another section that refers to a label of the statement records the +// label for run-time patching or as the continuation of a fault, so that the +// statement may jump where its instructions do not show. + +struct static_key +{ + int enabled; +} key; + +// Linux x86 arch_static_branch_jump: the kernel patches the jmp recorded in +// __jump_table into a nop when the key is disabled (and back) +static inline __attribute__((always_inline)) _Bool +arch_static_branch_jump(struct static_key *const k, const _Bool branch) +{ + __asm__ goto("1:" + "jmp %l[l_yes]\n\t" + ".pushsection __jump_table, \"aw\" \n\t" + ".balign 8\n\t" + ".long 1b - . \n\t" + ".long %l[l_yes] - . \n\t" + ".quad %c0 + %c1 - . \n\t" + ".popsection \n\t" + : + : "i"(k), "i"(branch) + : + : l_yes); + return 0; +l_yes: + return 1; +} + +// Linux x86 __put_user_goto: a fault of the store continues at the label +// recorded in __ex_table +static int put_user(int x, int *p) +{ + __asm__ goto("1: movl %0,%1\n" + ".pushsection \"__ex_table\",\"a\"\n" + ".balign 4\n" + ".long (1b) - .\n" + ".long (%l2) - .\n" + ".long 3\n" + ".popsection\n" + : + : "r"(x), "m"(*p) + : + : efault); + return 0; +efault: + return -14; +} + +unsigned long bits[2]; + +// Linux x86-64 set_bit with LOCK_PREFIX: .smp_locks records the lock prefix, +// which the kernel replaces by a no-op prefix on a single processor +static inline void set_bit(long nr, volatile unsigned long *addr) +{ + __asm__ volatile(".pushsection .smp_locks,\"a\"\n" + ".balign 4\n" + ".long 671f - .\n" + ".popsection\n" + "671:" + "\n\tlock; " + "btsq %1,%0" + : + : "m"(*(volatile long *)addr), "Ir"(nr) + : "memory"); +} + +int main(void) +{ + if(!arch_static_branch_jump(&key, 0)) + __CPROVER_assert(0, "jump label disabled path"); + else + __CPROVER_assert(0, "jump label enabled path"); + + int y = 0; + __CPROVER_assert(put_user(5, &y) == 0, "store does not fault"); + + set_bit(70, bits); + __CPROVER_assert(bits[1] == 64, "bit 70 set"); + + // a discarded annotation that refers to a label + int r; + __asm__("999:\n\t" + ".pushsection .discard.retpoline_safe\n\t" + ".long 999b\n\t" + ".popsection\n\t" + "movl %1, %0" + : "=r"(r) + : "r"(7)); + __CPROVER_assert(r == 7, "discarded annotation"); + + // data in another section that refers to no label + __asm__(".pushsection .rodata\n\t" + ".long 42\n\t" + ".popsection\n\t" + "movl $8, %0" + : "=r"(r)); + __CPROVER_assert(r == 8, "data without label references"); + + return 0; +} diff --git a/regression/cbmc/asm_x86_section_references/test.desc b/regression/cbmc/asm_x86_section_references/test.desc new file mode 100644 index 000000000000..d76563cf58b8 --- /dev/null +++ b/regression/cbmc/asm_x86_section_references/test.desc @@ -0,0 +1,25 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 73 jump label disabled path: FAILURE$ +^\[main\.assertion\.2\] line 75 jump label enabled path: FAILURE$ +^\[main\.assertion\.3\] line 78 store does not fault: FAILURE$ +^\[main\.assertion\.4\] line 81 bit 70 set: SUCCESS$ +^\[main\.assertion\.5\] line 92 discarded annotation: SUCCESS$ +^\[main\.assertion\.6\] line 100 data without label references: SUCCESS$ +approximating inline assembly statement at .* line 15 function arch_static_branch_jump: data in section __jump_table refers to label 1b +approximating inline assembly statement at .* line 36 function put_user: data in section __ex_table refers to label 1b +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function (set_bit|main) +-- +Data in another section that refers to a label of the statement records the +label for run-time patching (jump tables) or as the continuation of a fault +(exception tables), so these statements are approximated: on hardware, the +static branch goes either way, depending on how the kernel patched it, and +the store may fault. The lock prefixes recorded in .smp_locks, discarded +sections, and data that refers to no label do not change the effect of the +statement, which is interpreted. diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index f11f933666f9..b74f418f1b39 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -625,12 +625,50 @@ bool remove_asmt::lower_gcc( return true; } +/// \return The name of the section that the `.section` or `.pushsection` +/// directive \p instruction switches to +static std::string section_name(const asm_instructiont &instruction) +{ + std::string name; + if(!instruction.operands.empty()) + { + for(const auto &token : instruction.operands.front()) + name += token.text; + } + return name; +} + +/// \return The label of the statement that \p token of data in another +/// section refers to, if any. \p labels are the labels that the statement +/// defines. +static std::optional +label_reference(const asm_tokent &token, const std::set &labels) +{ + if(token.kind == asm_tokent::kindt::C_LABEL) + return "%l" + std::to_string(token.index); + if(token.kind == asm_tokent::kindt::LOCAL_LABEL) + return token.text + (token.backward ? "b" : "f"); + if(token.kind == asm_tokent::kindt::IDENTIFIER && labels.count(token.text)) + return token.text; + return {}; +} + /// Lowers each of \p instructions into \p ctx. /// /// Code in other sections (`.pushsection`/`.section` until `.popsection`/ -/// `.previous`) is not executed in sequence; data there (as in the Linux -/// kernel's jump tables) is ignored, but instructions there (such as +/// `.previous`) is not executed in sequence. Instructions there (such as /// exception fixups, which run when an instruction faults) are not modeled. +/// Data there that refers to a label of the statement (or to a C label of +/// `asm goto`) records the label for run-time patching, as do the Linux +/// kernel's jump tables (`__jump_table`, by which a `jmp` may become a `nop` +/// and vice versa), or as the continuation of a fault, as do exception tables +/// (`__ex_table`); the effect of the statement then depends on data the +/// instructions do not show, so it is not modeled. Exceptions are the lock +/// prefixes recorded in `.smp_locks`, which the kernel replaces by a no-op +/// prefix when it runs on a single processor, where this does not change the +/// effect of the instruction, and sections that the linker discards +/// (`.discard.*`, annotations for objtool). Other data in other sections has +/// no effect on the statement. /// /// \param instructions: The instructions of the statement /// \param ctx: The lowering context of the statement @@ -651,8 +689,13 @@ bool remove_asmt::lower_instructions( ".syntax", ".att_syntax"}; + std::set labels; + for(const auto &instruction : instructions) + labels.insert(instruction.labels.begin(), instruction.labels.end()); + std::vector pending_prefixes; - std::size_t section_depth = 0; + // the names of the other sections that are active, innermost last + std::vector sections; for(const auto &original : instructions) { @@ -661,26 +704,47 @@ bool remove_asmt::lower_instructions( if(m == ".pushsection" || m == ".section") { - ++section_depth; + sections.push_back(section_name(instruction)); continue; } if(m == ".popsection" || m == ".previous") { - if(section_depth == 0) + if(sections.empty()) { failure = "unbalanced " + m; return false; } - --section_depth; + sections.pop_back(); continue; } - if(section_depth != 0) + if(!sections.empty()) { - if(m.empty() || instruction.is_directive()) + if(!m.empty() && !instruction.is_directive()) + { + failure = "instruction '" + instruction.text + + "' in another section (such as an exception fixup)"; + return false; + } + const std::string §ion = sections.back(); + if(section == ".smp_locks" || has_prefix(section, ".discard.")) continue; - failure = "instruction '" + instruction.text + - "' in another section (such as an exception fixup)"; - return false; + for(const auto &tokens : instruction.operands) + { + for(const auto &token : tokens) + { + const auto label = label_reference(token, labels); + if(label.has_value()) + { + failure = "data in section " + section + " refers to label " + + *label + + " (as do jump tables, by which the code may be patched " + "at run time, and exception tables, by which a fault " + "may continue at the label)"; + return false; + } + } + } + continue; } for(const auto &label : instruction.labels) @@ -733,7 +797,7 @@ bool remove_asmt::lower_instructions( return false; } - if(section_depth != 0) + if(!sections.empty()) { failure = "unterminated section"; return false; From 4c1228196fccb46f7013047aae255ff23271e828 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:24:08 +0000 Subject: [PATCH 053/100] Inline assembly: unspecified upper bits wherever they may be read 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 --- doc/architectural/inline-assembly.md | 20 +++-- doc/cprover-manual/modeling-inline-asm.md | 4 +- regression/cbmc/asm_x86/test.desc | 2 +- regression/cbmc/asm_x86_narrow_inputs/main.i | 84 +++++++++++++++++++ .../cbmc/asm_x86_narrow_inputs/test.desc | 22 +++++ src/assembler/asm_lowering.cpp | 76 ++++++++++++----- src/assembler/asm_semantics.h | 53 +++++++++--- src/assembler/asm_x86.cpp | 62 ++++++++++---- 8 files changed, 269 insertions(+), 54 deletions(-) create mode 100644 regression/cbmc/asm_x86_narrow_inputs/main.i create mode 100644 regression/cbmc/asm_x86_narrow_inputs/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 02edc3978d40..31919b1c1029 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -42,13 +42,19 @@ The interpretation of a statement has these parts: The code of a statement consists of a prologue that evaluates the inputs, the code of the instructions, and an epilogue that assigns the register outputs. -Memory operands are accessed in place. A sub-register input is zero-extended -to the register width unless a reference to it reads more bits (see -`asm_semanticst::reference_widens`), in which case the upper bits are -nondeterministic. Zero-extension keeps a constant input constant, which -symbolic execution relies on: otherwise, for example, a spin lock on a lock -word that is written through such an operand would make the lock word -symbolic, and the spin loops would be unwound to the unwinding bound. +Memory operands are accessed in place. The bits of a register above the +width of the input operand it holds are unspecified. `prepare` determines +whether they may be read: by a reference to the operand or to another operand +that shares the register (an output the input is tied to, or an operand bound +to the same register by its constraint), see +`asm_semanticst::reference_bits`; by the name of the register +(`register_name_bits`); by an instruction that reads the register without +naming it (`implicit_reads`); or as part of an output that shares the +register. If so, the upper bits are nondeterministic; otherwise the input is +zero-extended. Zero-extension keeps a constant input constant, which symbolic +execution relies on: otherwise, for example, a spin lock on a lock word that +is written through such an operand would make the lock word symbolic, and the +spin loops would be unwound to the unwinding bound. The code of the instructions has the checks for undefined behaviour of C disabled (via pragmas on its source location), as it models hardware diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 0816c74b8b9b..abb0083ef87b 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -62,7 +62,9 @@ Operands follow GCC's rules: inputs are evaluated before the first instruction (and are subject to the checks CBMC performs), register outputs are assigned after the last instruction, and memory operands are accessed in place. Values that the architecture leaves undefined (such as some flags, or -the destination of `bsf` with a zero source) are nondeterministic. The +the destination of `bsf` with a zero source) are nondeterministic, and so are +the bits of a register above the width of the input operand it holds, when +an instruction may read them. The checks for undefined behaviour of C (such as `--signed-overflow-check`) do not apply to the instructions, which have defined results on the hardware; the checks of memory accesses do. diff --git a/regression/cbmc/asm_x86/test.desc b/regression/cbmc/asm_x86/test.desc index 36862aa62698..6aa55e0b613a 100644 --- a/regression/cbmc/asm_x86/test.desc +++ b/regression/cbmc/asm_x86/test.desc @@ -1,4 +1,4 @@ -CORE gcc-only +CORE gcc-only no-new-smt main.i --arch x86_64 ^EXIT=0$ diff --git a/regression/cbmc/asm_x86_narrow_inputs/main.i b/regression/cbmc/asm_x86_narrow_inputs/main.i new file mode 100644 index 000000000000..358f66ed7f8b --- /dev/null +++ b/regression/cbmc/asm_x86_narrow_inputs/main.i @@ -0,0 +1,84 @@ +// An input operand narrower than its register leaves the bits of the register +// above its width unspecified. These bits are read here through an output tied +// to the input, by the name of the register, by %h, by an instruction that +// reads the register implicitly, and as an output that shares the register. +// "fails" marks properties that do not hold for all register allocations; +// "violated" those that GCC 13 -O0 or -O2 code violates on x86-64. + +__attribute__((noinline)) int tied(signed char c) +{ + int r; + __asm__("addl $1, %0" : "=r"(r) : "0"(c) : "cc"); + return r; +} + +__attribute__((noinline)) unsigned long tied_int(long y) +{ + unsigned long r; + __asm__("addq $0, %0" : "=r"(r) : "0"((int)y) : "cc"); + return r; +} + +__attribute__((noinline)) unsigned long by_name(long y) +{ + unsigned long r; + __asm__("movq %%rdx, %0" : "=r"(r) : "d"((int)y)); + return r; +} + +__attribute__((noinline)) unsigned by_name_char(int y) +{ + unsigned r; + __asm__("movl %%ecx, %0" : "=r"(r) : "c"((signed char)y)); + return r; +} + +__attribute__((noinline)) unsigned high_byte(unsigned x) +{ + unsigned char r; + __asm__("movb %h1, %0" : "=q"(r) : "Q"((unsigned char)x)); + return r; +} + +__attribute__((noinline)) int implicit(int x) +{ + int r; + // cwtl reads %ax + __asm__("cwtl" : "=a"(r) : "a"((unsigned char)x)); + return r; +} + +__attribute__((noinline)) unsigned shared_output(unsigned x) +{ + unsigned r; + __asm__("" : "=r"(r) : "0"((unsigned char)x)); + return r; +} + +__attribute__((noinline)) unsigned char narrow(void) +{ + unsigned char r; + __asm__("addb $1, %b0" : "=q"(r) : "0"((unsigned char)5) : "cc"); + return r; +} + +int main(void) +{ + // fails, violated at -O2: GCC sign-extends c + __CPROVER_assert(tied(-1) == 256, "tied char input zero-extended"); + // fails, violated at -O0: GCC sign-extends the int + __CPROVER_assert(tied_int(-1) == 0xffffffffUL, "tied int input zero-extended"); + // fails: GCC need not zero-extend + __CPROVER_assert(by_name(-1) == 0xffffffffUL, "fixed int input zero-extended"); + // fails, violated + __CPROVER_assert(by_name_char(-1) == 0xffu, "fixed char input zero-extended"); + // fails, violated: %h reads bits 8 to 15 of the register + __CPROVER_assert(high_byte(0x1234) == 0, "high byte of a char is 0"); + // fails: GCC need not zero-extend + __CPROVER_assert(implicit(0x80) == 0x80, "cwtl of a zero-extended char"); + // fails, violated + __CPROVER_assert(shared_output(0x1ff) == 0xff, "output zero-extended"); + // holds: no bits above the width of the input are read + __CPROVER_assert(narrow() == 6, "narrow access"); + return 0; +} diff --git a/regression/cbmc/asm_x86_narrow_inputs/test.desc b/regression/cbmc/asm_x86_narrow_inputs/test.desc new file mode 100644 index 000000000000..55a7e1c267b2 --- /dev/null +++ b/regression/cbmc/asm_x86_narrow_inputs/test.desc @@ -0,0 +1,22 @@ +CORE gcc-only no-new-smt +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 68 tied char input zero-extended: FAILURE$ +^\[main\.assertion\.2\] line 70 tied int input zero-extended: FAILURE$ +^\[main\.assertion\.3\] line 72 fixed int input zero-extended: FAILURE$ +^\[main\.assertion\.4\] line 74 fixed char input zero-extended: FAILURE$ +^\[main\.assertion\.5\] line 76 high byte of a char is 0: FAILURE$ +^\[main\.assertion\.6\] line 78 cwtl of a zero-extended char: FAILURE$ +^\[main\.assertion\.7\] line 80 output zero-extended: FAILURE$ +^\[main\.assertion\.8\] line 82 narrow access: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +The bits of a register above the width of the input operand it holds are +unspecified. Where they may be read, they are nondeterministic, so that CBMC +does not prove the properties that depend on them; where they are not read, +the input is zero-extended, which keeps a constant input constant. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 113e022d703a..d951f1ce795e 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -386,9 +386,25 @@ bool asm_lowering_contextt::prepare( { const std::size_t register_width = semantics.register_width(); - // Which input operands are read above their natural width by some - // reference: those must keep non-deterministic upper bits (see below). - std::set widened; + // The register that holds operand i: that of the output it is tied to, if + // any, and that of operands bound to the same register by their constraint. + auto register_of = [this](std::size_t i) + { + const std::size_t owner = operands.operands[i].tied_output.value_or(i); + const std::string &fixed = operands.operands[owner].fixed_register; + return fixed.empty() ? "operand " + std::to_string(owner) + : "register " + fixed; + }; + + // The number of low-order bits of each register that may be read. Bits of + // an input operand's register above its natural width are unspecified: if + // they may be read, they must be nondeterministic (see below). + std::map read_bits; + auto note_read = [&read_bits](const std::string ®, std::size_t bits) + { + std::size_t &entry = read_bits[reg]; + entry = std::max(entry, bits); + }; for(const auto &instruction : instructions) { for(const auto &tokens : instruction.operands) @@ -397,15 +413,37 @@ bool asm_lowering_contextt::prepare( { if( token.kind == asm_tokent::kindt::OPERAND && - token.index < operands.operands.size()) + token.index < operands.operands.size() && + operands.operands[token.index].kind == asm_operandt::kindt::REGISTER) + { + note_read( + register_of(token.index), + semantics.reference_bits( + token.modifier, + width(operands.operands[token.index].expr.type()))); + } + else if(token.kind == asm_tokent::kindt::IDENTIFIER) { - const std::size_t w = - width(operands.operands[token.index].expr.type()); - if(w != 0 && semantics.reference_widens(token.modifier, w)) - widened.insert(token.index); + // a register read by name + const std::string canonical = + semantics.canonical_register(token.text); + if(!canonical.empty()) + { + note_read( + "register " + canonical, + semantics.register_name_bits(token.text)); + } } } } + for(const auto &canonical : semantics.implicit_reads(instruction)) + note_read("register " + canonical, register_width); + } + // the outputs, which are assigned from their registers + for(std::size_t i = 0; i < operands.number_of_outputs; ++i) + { + if(operands.operands[i].kind == asm_operandt::kindt::REGISTER) + note_read(register_of(i), width(operands.operands[i].expr.type())); } if(goto_target.is_not_nil()) @@ -454,11 +492,11 @@ bool asm_lowering_contextt::prepare( // The value, zero-extended to the register width. const exprt value = to_bits(operand.expr, register_width); - if(w < register_width && widened.count(i) != 0) + if(w < register_width && read_bits[register_of(i)] > w) { - // Some reference reads this operand above its natural width, where - // the bits are unspecified. Model them non-deterministically by - // keeping the (uninitialised) upper bits of the register. + // The bits above the operand's width, which are unspecified, may + // be read. Model them non-deterministically by keeping the + // (uninitialised) upper bits of the register. const mp_integer mask = power(2, w) - 1; prologue.add(goto_programt::make_assignment( s, @@ -471,13 +509,13 @@ bool asm_lowering_contextt::prepare( } else { - // No reference reads above the operand's width, so zero-extension is - // exact. Unlike the merge above, the register is then a plain - // function of the input, so when the input is a constant the - // register stays a constant and symex constant propagation keeps - // working. (The merge would make, for example, a spinlock word - // written through the operand symbolic, forcing symex to unwind the - // lock's spin loops to the unwinding bound.) + // The bits above the operand's width are not read, so + // zero-extension is exact. Unlike the merge above, the register is + // then a plain function of the input, so when the input is a + // constant the register stays a constant and symex constant + // propagation keeps working. (The merge would make, for example, a + // spinlock word written through the operand symbolic, forcing symex + // to unwind the lock's spin loops to the unwinding bound.) prologue.add(goto_programt::make_assignment(s, value, location)); unknown.erase(s.identifier()); } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index 5f890cfca0b8..1f3aa2abb873 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -171,13 +171,11 @@ class asm_lowering_contextt void end_conditional(goto_programt::targett begin); /// \} - /// Initialise operand storage; must be called before lowering - /// instructions. - /// \return false if an operand cannot be modelled /// Initialise operand storage; must be called before lowering /// instructions. /// \param instructions: the instructions of the statement, used to decide - /// whether an input operand is read above its natural width + /// whether the bits above the natural width of an input operand may be + /// read /// \return false if an operand cannot be modelled bool prepare(const std::vector &instructions); @@ -299,12 +297,8 @@ class asm_semanticst /// \return true if a `%`-reference with the given \p modifier reads an /// operand of natural width \p natural_width bits at a wider view, so that - /// bits above \p natural_width are observed. For an input operand narrower - /// than the register, those bits are unspecified (except where the - /// architecture defines them), so when any reference to it widens, its - /// register is initialised with non-deterministic upper bits rather than - /// zero-extended. When none do, zero-extension is exact and keeps the - /// register a constant when the input is one. + /// bits above \p natural_width are observed. Used only by the default + /// implementation of \ref reference_bits. virtual bool reference_widens(const std::string &modifier, std::size_t natural_width) const { @@ -314,6 +308,45 @@ class asm_semanticst return !modifier.empty(); } + /// \return The number of low-order bits of the register holding an operand + /// of natural width \p natural_width that a `%`-reference with the given + /// \p modifier may read: bits from this number up are not read. + /// + /// For an input operand narrower than the register, the bits above its + /// natural width are unspecified, so when they may be read (by a reference + /// to the operand, or to an output that shares its register, by name, by an + /// instruction that reads the register implicitly, or as part of an output + /// that shares its register), the register is initialised with + /// nondeterministic upper bits rather than zero-extended. When they are not + /// read, zero-extension is exact and keeps the register a constant when the + /// input is one. The default is derived from \ref reference_widens. + virtual std::size_t + reference_bits(const std::string &modifier, std::size_t natural_width) const + { + return reference_widens(modifier, natural_width) ? register_width() + : natural_width; + } + + /// \return The number of low-order bits of its canonical register (see + /// \ref canonical_register) that the register name \p name reads, or 0 if + /// \p name is not the name of a general-purpose register. + virtual std::size_t register_name_bits(const std::string &name) const + { + return canonical_register(name).empty() ? 0 : register_width(); + } + + /// \return The canonical names of the general-purpose registers that + /// \p instruction may read without naming them in its operands (such as + /// the accumulator of x86 `cmpxchg`). Architectures with constraints that + /// bind an operand to a particular register must report them, as the + /// register may hold an input narrower than the register (see + /// \ref reference_bits). + virtual std::vector + implicit_reads(const asm_instructiont &instruction) const + { + return {}; + } + /// How a constraint letter is interpreted enum class constraint_classt { diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index 95a7c9b60f72..b6e3de4c80ee 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -180,22 +180,52 @@ class asm_x86_semanticst : public asm_semanticst return it == registers.end() ? std::string{} : it->second.canonical; } - bool reference_widens(const std::string &modifier, std::size_t natural_width) - const override - { - std::size_t read = natural_width <= 8 ? 8 - : natural_width <= 16 ? 16 - : natural_width <= 32 ? 32 - : 64; - if(modifier == "b" || modifier == "h") - read = 8; - else if(modifier == "w") - read = 16; - else if(modifier == "k") - read = 32; - else if(modifier == "q") - read = 64; - return read > natural_width; + std::size_t reference_bits( + const std::string &modifier, + std::size_t natural_width) const override + { + if(modifier.empty()) + { + // the register of the operand's size + return natural_width <= 8 ? 8 + : natural_width <= 16 ? 16 + : natural_width <= 32 ? 32 + : 64; + } + if(modifier == "b") + return 8; + if(modifier == "h") + return 16; // bits 8 to 15 + if(modifier == "w") + return 16; + if(modifier == "k") + return 32; + return register_width(); + } + + std::size_t register_name_bits(const std::string &name) const override + { + const std::string bare = + !name.empty() && name[0] == '%' ? name.substr(1) : name; + const auto it = registers.find(bare); + return it == registers.end() ? 0 : it->second.offset + it->second.width; + } + + std::vector + implicit_reads(const asm_instructiont &instruction) const override + { + // the accumulator, read by sign extensions and as the expected value of + // cmpxchg; the other implicit reads of the instructions that are + // modelled do not affect the modelled values + const std::string &m = instruction.mnemonic; + if( + m == "cltq" || m == "cdqe" || m == "cwtl" || m == "cwde" || m == "cltd" || + m == "cdq" || m == "cqto" || m == "cqo" || + m.compare(0, 7, "cmpxchg") == 0) + { + return {"rax"}; + } + return {}; } constraint_classt classify_constraint( From fb558c1d75d8dc61478e741678643179ef62df83 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:27:08 +0000 Subject: [PATCH 054/100] Inline assembly: read immediates as GCC prints and GAS reads them 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 --- doc/architectural/inline-assembly.md | 6 ++- .../cbmc/asm_x86_immediate_syntax/main.i | 53 +++++++++++++++++++ .../cbmc/asm_x86_immediate_syntax/test.desc | 18 +++++++ src/assembler/asm_template.cpp | 50 ++++++++++++----- src/assembler/asm_x86.cpp | 26 +++++++-- 5 files changed, 136 insertions(+), 17 deletions(-) create mode 100644 regression/cbmc/asm_x86_immediate_syntax/main.i create mode 100644 regression/cbmc/asm_x86_immediate_syntax/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 31919b1c1029..66cfd84dc851 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -32,7 +32,11 @@ The interpretation of a statement has these parts: `ID_identifier`. - `split_asm_template` (`asm_template.h`) splits the template into instructions, and resolves `%N`, `%[name]`, `%lN`, and local label - references. + references. It reads numbers as GAS does: `0x` is hexadecimal, `0b` + binary (unless it refers to the local label 0), and a leading `0` octal. + The modifiers of operand references are left to the semantics, which fail + on modifiers they do not understand (on x86, `%c`, `%P`, and `%n`, which + negates, are the modifiers of immediates). - `asm_lowering_contextt` (`asm_semantics.h`) holds the goto code being built: the storage of register operands, hardware registers, and flags (all block-local temporaries), labels, and helpers to read and write registers diff --git a/regression/cbmc/asm_x86_immediate_syntax/main.i b/regression/cbmc/asm_x86_immediate_syntax/main.i new file mode 100644 index 000000000000..faeedf5650be --- /dev/null +++ b/regression/cbmc/asm_x86_immediate_syntax/main.i @@ -0,0 +1,53 @@ +// Immediates and displacements as GCC prints and GAS reads them: %n prints +// the negated constant; 0x, 0b, and a leading 0 select hexadecimal, binary, +// and octal. The expected values were observed on x86-64 hardware. + +__attribute__((noinline)) int negated(int x) +{ + __asm__("addl $%n1, %0" : "+r"(x) : "i"(5) : "cc"); + return x; +} + +__attribute__((noinline)) int octal(int x) +{ + __asm__("addl $010, %0" : "+r"(x) : : "cc"); + return x; +} + +__attribute__((noinline)) int binary_and_hex(int x) +{ + __asm__("addl $0b101, %0\n\t" + "addl $0x10, %0\n\t" + "addl $0, %0" + : "+r"(x) + : + : "cc"); + return x; +} + +__attribute__((noinline)) int octal_displacement(const int *p) +{ + int r; + __asm__("movl 010(%1), %0" : "=r"(r) : "r"(p), "m"(*(const int(*)[8])p)); + return r; +} + +__attribute__((noinline)) int negated_displacement(const int *p) +{ + int r; + __asm__("movl %n2(%1), %0" + : "=r"(r) + : "r"(p), "i"(-12), "m"(*(const int(*)[8])p)); + return r; +} + +int main(void) +{ + int a[8] = {0, 1, 2, 3, 4, 5, 6, 7}; + __CPROVER_assert(negated(0) == -5, "%n negates"); + __CPROVER_assert(octal(0) == 8, "$010 is octal"); + __CPROVER_assert(binary_and_hex(0) == 21, "0b and 0x"); + __CPROVER_assert(octal_displacement(a) == 2, "010(%1) is octal"); + __CPROVER_assert(negated_displacement(a) == 3, "%n in a displacement"); + return 0; +} diff --git a/regression/cbmc/asm_x86_immediate_syntax/test.desc b/regression/cbmc/asm_x86_immediate_syntax/test.desc new file mode 100644 index 000000000000..0e5852cca370 --- /dev/null +++ b/regression/cbmc/asm_x86_immediate_syntax/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 47 %n negates: SUCCESS$ +^\[main\.assertion\.2\] line 48 \$010 is octal: SUCCESS$ +^\[main\.assertion\.3\] line 49 0b and 0x: SUCCESS$ +^\[main\.assertion\.4\] line 50 010\(%1\) is octal: SUCCESS$ +^\[main\.assertion\.5\] line 51 %n in a displacement: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +GCC prints %n of a constant as the negated constant, and GAS reads numbers +with a leading 0 as octal, 0b as binary, and 0x as hexadecimal. The expected +values were observed on x86-64 hardware. diff --git a/src/assembler/asm_template.cpp b/src/assembler/asm_template.cpp index 1f0a3d22ace1..97523a637681 100644 --- a/src/assembler/asm_template.cpp +++ b/src/assembler/asm_template.cpp @@ -233,30 +233,54 @@ static bool tokenize( if(std::isdigit(static_cast(c))) { + // as GAS reads numbers: 0x (hexadecimal), 0b (binary, unless it is a + // reference to the local label 0), and a leading 0 (octal) std::size_t start = i; - bool hex = false; + unsigned base = 10; + std::size_t digits_start = i; + auto is_digit = [&base](char d) + { + if(base == 16) + return std::isxdigit(static_cast(d)) != 0; + return d >= '0' && d < static_cast('0' + std::min(base, 10u)); + }; if( - c == '0' && i + 1 < text.size() && - (text[i + 1] == 'x' || text[i + 1] == 'X')) + c == '0' && i + 2 < text.size() && + (text[i + 1] == 'x' || text[i + 1] == 'X') && + std::isxdigit(static_cast(text[i + 2]))) + { + base = 16; + } + else if( + c == '0' && i + 2 < text.size() && + (text[i + 1] == 'b' || text[i + 1] == 'B') && + (text[i + 2] == '0' || text[i + 2] == '1')) + { + base = 2; + } + + if(base != 10) { - hex = true; i += 2; - while(i < text.size() && - std::isxdigit(static_cast(text[i]))) - ++i; + digits_start = i; } - else + else if( + c == '0' && i + 1 < text.size() && + std::isdigit(static_cast(text[i + 1]))) { - while(i < text.size() && - std::isdigit(static_cast(text[i]))) - ++i; + base = 8; + ++i; + digits_start = i; } + while(i < text.size() && is_digit(text[i])) + ++i; + const std::string digits = text.substr(start, i - start); // GNU local label references: 1b, 1f if( - !hex && i < text.size() && (text[i] == 'b' || text[i] == 'f') && + base == 10 && i < text.size() && (text[i] == 'b' || text[i] == 'f') && (i + 1 == text.size() || !is_identifier_char(text[i + 1], syntax))) { asm_tokent token{asm_tokent::kindt::LOCAL_LABEL, digits}; @@ -274,7 +298,7 @@ static bool tokenize( asm_tokent token{asm_tokent::kindt::NUMBER, digits}; token.number = - hex ? string2integer(digits.substr(2), 16) : string2integer(digits, 10); + string2integer(text.substr(digits_start, i - digits_start), base); tokens.push_back(token); continue; } diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index b6e3de4c80ee..46f9a3c0915e 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -540,9 +540,26 @@ bool asm_x86_semanticst::parse_immediate( if(bound.kind != asm_operandt::kindt::IMMEDIATE) return ctx.fail( "operand %" + std::to_string(token.index) + " is not an immediate"); + // after a $, only the modifiers that print the bare constant make sense + // (without one, GCC prints the $ of the immediate as well); %n prints it + // negated + if(token.modifier == "n") + negative = !negative; + else if(token.modifier != "c" && token.modifier != "P") + { + return ctx.fail( + "unsupported modifier '" + token.modifier + "' of an immediate"); + } value = ctx.operand_immediate(token.index); if(negative) + { + if(value.type().id() == ID_pointer) + { + value = + typecast_exprt{value, signedbv_typet{config.ansi_c.pointer_width}}; + } value = unary_minus_exprt{value}; + } return true; } @@ -592,12 +609,15 @@ bool asm_x86_semanticst::parse_memory( else if( pos < tokens.size() && tokens[pos].kind == asm_tokent::kindt::OPERAND && (tokens[pos].modifier == "c" || tokens[pos].modifier == "P" || - tokens[pos].modifier.empty()) && + tokens[pos].modifier == "n" || tokens[pos].modifier.empty()) && ctx.operands.operands.at(tokens[pos].index).kind == asm_operandt::kindt::IMMEDIATE) { - displacement_expr = ctx.operand_immediate(tokens[pos].index); - if(negative) + displacement_expr = typecast_exprt::conditional_cast( + ctx.operand_immediate(tokens[pos].index), + signedbv_typet{config.ansi_c.pointer_width}); + // %n prints the constant negated + if(negative != (tokens[pos].modifier == "n")) displacement_expr = unary_minus_exprt{displacement_expr}; ++pos; } From d88315efe4ea3e2ce02a00296585023a7bb253cc Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:29:05 +0000 Subject: [PATCH 055/100] Inline assembly: do not size x86 instructions by C types of memory 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 --- doc/cprover-manual/modeling-inline-asm.md | 4 ++ regression/cbmc/asm_x86_operand_size/main.i | 57 +++++++++++++++++++ .../cbmc/asm_x86_operand_size/test.desc | 25 ++++++++ src/assembler/asm_x86.cpp | 35 ++++++++---- 4 files changed, 109 insertions(+), 12 deletions(-) create mode 100644 regression/cbmc/asm_x86_operand_size/main.i create mode 100644 regression/cbmc/asm_x86_operand_size/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index abb0083ef87b..134caba13036 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -75,6 +75,10 @@ instructions are listed in the tables below) if it: - contains an instruction, operand, prefix, or directive that the semantics do not support, or instructions in another section (such as exception fixups, which run when an instruction faults); +- contains an instruction without a size suffix whose operand size is not + given by a register operand (other than the count of a shift): the + assembler does not see the C type of a memory operand, and uses a default + size instead; - contains data in another section that refers to one of its labels or, for `asm goto`, to one of its C labels, other than in `.smp_locks` (the lock prefixes that the Linux kernel removes on a single processor) and the diff --git a/regression/cbmc/asm_x86_operand_size/main.i b/regression/cbmc/asm_x86_operand_size/main.i new file mode 100644 index 000000000000..815c6b5d2a04 --- /dev/null +++ b/regression/cbmc/asm_x86_operand_size/main.i @@ -0,0 +1,57 @@ +// The operand size of an x86 instruction is given by its suffix or by a +// register operand other than the count of a shift; GAS does not see the C +// type of a memory operand. The statements without a suffix and without such +// a register operand are approximated. The expected values of the others were +// observed on x86-64 hardware. + +__attribute__((noinline)) unsigned shl_mem(unsigned x, unsigned char n) +{ + __asm__("shl %%cl, %0" : "+m"(x) : "c"(n) : "cc"); + return x; +} + +__attribute__((noinline)) unsigned long add_mem(unsigned long x) +{ + __asm__("add $1, %0" : "+m"(x) : : "cc"); + return x; +} + +__attribute__((noinline)) unsigned movzx_mem(unsigned short s) +{ + unsigned r; + __asm__("movzx %1, %0" : "=r"(r) : "m"(s)); + return r; +} + +__attribute__((noinline)) unsigned shll_mem(unsigned x, unsigned char n) +{ + __asm__("shll %%cl, %0" : "+m"(x) : "c"(n) : "cc"); + return x; +} + +__attribute__((noinline)) unsigned shl_reg(unsigned x, unsigned char n) +{ + __asm__("shl %%cl, %0" : "+r"(x) : "c"(n) : "cc"); + return x; +} + +__attribute__((noinline)) unsigned long add_reg_mem(unsigned long x) +{ + unsigned long one = 1; + __asm__("add %1, %0" : "+m"(x) : "r"(one) : "cc"); + return x; +} + +int main(void) +{ + // the size of the count register (8 bits) + __CPROVER_assert(shl_mem(0x101, 4) == 0x110, "shl as 8-bit"); + // the size of the C type (64 bits); GAS uses 32 bits + __CPROVER_assert(add_mem(0xffffffffUL) == 0x100000000UL, "add as 64-bit"); + // the size of the C type (16 bits); GAS uses 8 bits + __CPROVER_assert(movzx_mem(0x1234) == 0x1234, "movzx as 16-bit"); + __CPROVER_assert(shll_mem(0x101, 4) == 0x1010, "shll"); + __CPROVER_assert(shl_reg(0x101, 4) == 0x1010, "shl of a register"); + __CPROVER_assert(add_reg_mem(0xffffffffUL) == 0x100000000UL, "add register"); + return 0; +} diff --git a/regression/cbmc/asm_x86_operand_size/test.desc b/regression/cbmc/asm_x86_operand_size/test.desc new file mode 100644 index 000000000000..06a49b94043e --- /dev/null +++ b/regression/cbmc/asm_x86_operand_size/test.desc @@ -0,0 +1,25 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 48 shl as 8-bit: FAILURE$ +^\[main\.assertion\.2\] line 50 add as 64-bit: FAILURE$ +^\[main\.assertion\.3\] line 52 movzx as 16-bit: FAILURE$ +^\[main\.assertion\.4\] line 53 shll: SUCCESS$ +^\[main\.assertion\.5\] line 54 shl of a register: SUCCESS$ +^\[main\.assertion\.6\] line 55 add register: SUCCESS$ +approximating inline assembly statement at .* line 9 function shl_mem: no suffix or register operand gives the operand size +approximating inline assembly statement at .* line 15 function add_mem: no suffix or register operand gives the operand size +approximating inline assembly statement at .* line 22 function movzx_mem: no suffix or register operand gives the operand sizes of movzx +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function (shll_mem|shl_reg|add_reg_mem) +-- +Without a suffix, the operand size is that of a register operand (other than +the count of a shift). GAS does not see the C type of a memory operand: for +the statements without a suffix and without such a register operand it uses +a default size (32 bits for shl and add, 8 bits for the source of movzx), +which hardware shows to differ from the C type (the first three assertions +fail on x86-64 hardware). These statements are approximated. diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index 46f9a3c0915e..f320dc778431 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -423,6 +423,11 @@ class asm_x86_semanticst : public asm_semanticst return op; } + /// The operand size of an instruction with suffix width \p suffix (0 if + /// none) and \p operands: as for GAS, the suffix or else the size of a + /// register operand. GAS does not see the C type of a memory operand: for + /// an instruction without suffix and register operands, it uses a default + /// size (which depends on the instruction) or rejects it. 0 in this case. static std::size_t operation_width(const std::vector &operands, std::size_t suffix) { @@ -433,11 +438,6 @@ class asm_x86_semanticst : public asm_semanticst if(op.kind == x86_operandt::kindt::REGISTER && op.width != 0) return op.width; } - for(const auto &op : operands) - { - if(op.kind == x86_operandt::kindt::MEMORY && op.natural_width != 0) - return op.natural_width; - } return 0; } @@ -1036,7 +1036,13 @@ bool asm_x86_semanticst::lower( { const std::size_t from = operation_width({operands[0]}, 0), to = operation_width({operands[1]}, 0); - if(from == 0 || to == 0 || from >= to) + if(from == 0 || to == 0) + { + return ctx.fail( + "no suffix or register operand gives the operand sizes of " + m + + " (GAS does not take them from the C type of a memory operand)"); + } + if(from >= to) return ctx.fail("unsupported " + m); const exprt src = read(ctx, operands[0], from); return write( @@ -1065,19 +1071,24 @@ bool asm_x86_semanticst::lower( if(suffix == 64 && !x86_64) return ctx.fail("64-bit operation on i386"); - // the size is that of the destination for shifts (whose count may be %cl) - // and for in (whose port may be %dx) + // the size is that of the destination for shifts (whose count may be %cl, + // which does not give the size) and for in (whose port may be %dx) std::vector by_size = operands; if( - base == "shl" || base == "sal" || base == "shr" || base == "sar" || - base == "rol" || base == "ror" || base == "in") + !by_size.empty() && (base == "shl" || base == "sal" || base == "shr" || + base == "sar" || base == "rol" || base == "ror")) { - std::reverse(by_size.begin(), by_size.end()); + by_size = {by_size.back()}; } + else if(base == "in") + std::reverse(by_size.begin(), by_size.end()); const std::size_t width = operation_width(by_size, suffix); if(width == 0 && base != "lea") + { return ctx.fail( - "cannot determine the operand size of '" + instruction.text + "'"); + "no suffix or register operand gives the operand size (GAS does not " + "take it from the C type of a memory operand)"); + } if(base == "xchg") { From 6f5c1616da93a56e28b1ec3546bc6b417ec58163 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:36:45 +0000 Subject: [PATCH 056/100] Inline assembly: model both alternatives of register-or-memory operands 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 --- doc/architectural/inline-assembly.md | 11 +- doc/cprover-manual/modeling-inline-asm.md | 12 +- .../cbmc/asm_x86_register_or_memory/main.i | 65 +++++++++ .../cbmc/asm_x86_register_or_memory/test.desc | 27 ++++ src/assembler/asm_lowering.cpp | 17 ++- src/assembler/asm_operands.cpp | 73 +++++++++-- src/assembler/asm_operands.h | 17 +++ src/assembler/asm_x86.cpp | 79 ++++++++++- src/assembler/remove_asm.cpp | 124 ++++++++++++++++++ 9 files changed, 410 insertions(+), 15 deletions(-) create mode 100644 regression/cbmc/asm_x86_register_or_memory/main.i create mode 100644 regression/cbmc/asm_x86_register_or_memory/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 66cfd84dc851..925337019556 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -46,7 +46,16 @@ The interpretation of a statement has these parts: The code of a statement consists of a prologue that evaluates the inputs, the code of the instructions, and an epilogue that assigns the register outputs. -Memory operands are accessed in place. The bits of a register above the +Memory operands are accessed in place. For an operand whose constraint +allows both a register and memory (`asm_operandt::may_be_memory`, as for +`"rm"` and `"g"`), GCC may choose either, and the instructions may have a +different effect: `remove_asmt::lower_gcc` lowers every combination of +choices (`asm_operandst::memory_alternative`; an rvalue input in memory is +a temporary object) and chooses one nondeterministically. Constraints with +several alternatives are not interpreted. Where an operand may also be an +immediate (`asm_operandt::may_be_immediate`), the semantics must fail on +uses whose effect would differ for an immediate. +The bits of a register above the width of the input operand it holds are unspecified. `prepare` determines whether they may be read: by a reference to the operand or to another operand that shares the register (an output the input is tied to, or an operand bound diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 134caba13036..8f6b2cccd356 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -64,7 +64,12 @@ are assigned after the last instruction, and memory operands are accessed in place. Values that the architecture leaves undefined (such as some flags, or the destination of `bsf` with a zero source) are nondeterministic, and so are the bits of a register above the width of the input operand it holds, when -an instruction may read them. The +an instruction may read them. For an operand whose constraint allows both a +register and memory (such as `"rm"` or `"g"`), the compiler may choose +either, and the effect of an instruction may depend on the choice (a 32-bit +write clears the upper half of a 64-bit register, but not of memory): both +choices are modeled, and one of them is chosen nondeterministically. The + checks for undefined behaviour of C (such as `--signed-overflow-check`) do not apply to the instructions, which have defined results on the hardware; the checks of memory accesses do. @@ -79,6 +84,11 @@ instructions are listed in the tables below) if it: given by a register operand (other than the count of a shift): the assembler does not see the C type of a memory operand, and uses a default size instead; +- has more than three operands that may be in a register or in memory, or a + constraint with several alternatives (such as `"r,m"`), or reads an + operand that may also be an immediate (such as `"ri"` or `"g"`) in a way + that depends on whether it is one (at a width other than its own, or as the + bit offset of `bt` into memory); - contains data in another section that refers to one of its labels or, for `asm goto`, to one of its C labels, other than in `.smp_locks` (the lock prefixes that the Linux kernel removes on a single processor) and the diff --git a/regression/cbmc/asm_x86_register_or_memory/main.i b/regression/cbmc/asm_x86_register_or_memory/main.i new file mode 100644 index 000000000000..df8753f6b5b8 --- /dev/null +++ b/regression/cbmc/asm_x86_register_or_memory/main.i @@ -0,0 +1,65 @@ +// For an operand whose constraint allows a register and memory ("rm", "g"), +// GCC chooses either (GCC 13 chooses a register for a global at -O0 and the +// global's memory at -O2), and the effect of the instructions may depend on +// the choice. "fails" marks properties that do not hold for all choices. + +long gx = -1; +long gy = -1; + +struct s +{ + unsigned word, next; +}; + +__attribute__((noinline)) int bit(struct s *p, unsigned nr) +{ + unsigned char r; + __asm__("btl %2, %1\n\tsetc %0" : "=q"(r) : "rm"(p->word), "r"(nr) : "cc"); + return r; +} + +__attribute__((noinline)) int rvalue(int x) +{ + int r; + __asm__("movl %1, %0" : "=r"(r) : "rm"(x + 1)); + return r; +} + +__attribute__((noinline)) unsigned long immediate(unsigned long x) +{ + __asm__("addq %1, %0" : "+r"(x) : "g"(-1) : "cc"); + return x; +} + +int main(void) +{ + // a 32-bit write clears the upper half of a register, not of memory + __asm__("movl $1, %k0" : "+rm"(gx)); + // fails + __CPROVER_assert(gx == 1, "register"); + // fails + __CPROVER_assert(gx == 0xffffffff00000001L, "memory"); + __CPROVER_assert(gx == 1 || gx == 0xffffffff00000001L, "register or memory"); + + // in memory, the bit offset addresses a bit string beyond the operand + static struct s v = {0, 1}; + int b = bit(&v, 32); + // fails + __CPROVER_assert(b == 0, "bit 0 of word"); + // fails + __CPROVER_assert(b == 1, "bit 0 of next"); + __CPROVER_assert(b == 0 || b == 1, "bit of word or next"); + + __CPROVER_assert(rvalue(1) == 2, "rvalue in register or memory"); + + // as an immediate, -1 is sign-extended to 64 bits; the register would not + // even be accepted by the assembler (addq %edx, %rax) + // fails + __CPROVER_assert(immediate(1) == 0x100000000UL, "immediate zero-extended"); + + // GCC may choose any alternative + __asm__("movl $1, %k0" : "+r,m"(gy)); + // fails + __CPROVER_assert(gy == 1, "first alternative"); + return 0; +} diff --git a/regression/cbmc/asm_x86_register_or_memory/test.desc b/regression/cbmc/asm_x86_register_or_memory/test.desc new file mode 100644 index 000000000000..be874051b9be --- /dev/null +++ b/regression/cbmc/asm_x86_register_or_memory/test.desc @@ -0,0 +1,27 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 39 register: FAILURE$ +^\[main\.assertion\.2\] line 41 memory: FAILURE$ +^\[main\.assertion\.3\] line 42 register or memory: SUCCESS$ +^\[main\.assertion\.4\] line 48 bit 0 of word: FAILURE$ +^\[main\.assertion\.5\] line 50 bit 0 of next: FAILURE$ +^\[main\.assertion\.6\] line 51 bit of word or next: SUCCESS$ +^\[main\.assertion\.7\] line 53 rvalue in register or memory: SUCCESS$ +^\[main\.assertion\.8\] line 58 immediate zero-extended: FAILURE$ +^\[main\.assertion\.9\] line 63 first alternative: FAILURE$ +approximating inline assembly statement at .* line 30 function immediate: operand %1, which may be an immediate, is read at a width other than its own +approximating inline assembly statement at .* line 61 function main: constraint "\+r,m" with several alternatives +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (17|25|36) +-- +Both the register and the memory alternative of "rm" operands are modelled: +the native code of GCC 13 on x86-64 violates assertions 1 and 4 at -O2 (in +memory) and assertions 2 and 5 at -O0 (in a register). Where the semantics +would differ for an immediate (assertion 8, violated by the native code), or +the constraint has several alternatives (assertion 9, violated at -O2), the +statement is approximated. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index d951f1ce795e..8ff73e013798 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -525,11 +525,20 @@ bool asm_lowering_contextt::prepare( case asm_operandt::kindt::MEMORY: { - const symbol_exprt a = temporary( - pointer_type(operand.expr.type()), "addr" + std::to_string(i)); + exprt object = operand.expr; + if(!operand.is_output && !operand.is_lvalue()) + { + // an input that GCC places in memory of its own (for a constraint + // such as "rm"), with the checks that apply to the C expression + object = temporary(operand.expr.type(), "mem" + std::to_string(i)); + prologue.add(goto_programt::make_assignment( + object, operand.expr, statement_location)); + } + const symbol_exprt a = + temporary(pointer_type(object.type()), "addr" + std::to_string(i)); addresses.emplace(i, a); - prologue.add(goto_programt::make_assignment( - a, address_of_exprt{operand.expr}, location)); + prologue.add( + goto_programt::make_assignment(a, address_of_exprt{object}, location)); break; } diff --git a/src/assembler/asm_operands.cpp b/src/assembler/asm_operands.cpp index 7556d5868da5..bc16df292123 100644 --- a/src/assembler/asm_operands.cpp +++ b/src/assembler/asm_operands.cpp @@ -41,6 +41,43 @@ std::optional asm_operandst::find_label(const irep_idt &name) const return {}; } +bool asm_operandt::is_lvalue() const +{ + return expr.get_bool(ID_C_lvalue) || expr.id() == ID_symbol || + expr.id() == ID_dereference || expr.id() == ID_index || + expr.id() == ID_member; +} + +bool asm_operandst::memory_alternative(std::size_t index, std::string &error) +{ + asm_operandt &operand = operands.at(index); + PRECONDITION( + operand.kind == asm_operandt::kindt::REGISTER && operand.may_be_memory && + !operand.tied_output.has_value()); + + operand.kind = asm_operandt::kindt::MEMORY; + operand.fixed_register.clear(); + + for(auto &input : operands) + { + if(input.tied_output == index) + { + // GCC requires the input to be the same object + if(input.expr != operand.expr) + { + error = + "input operand tied to an output that may be in memory is a " + "different object"; + return false; + } + input.kind = asm_operandt::kindt::MEMORY; + input.fixed_register.clear(); + } + } + + return true; +} + static std::string string_of(const exprt &expr) { if(expr.id() == ID_string_constant) @@ -101,7 +138,11 @@ static bool parse_constraint( const char c = constraint[pos]; if(c == ',') - break; // only the first alternative is used + { + // GCC may choose any alternative, consistently for all operands + error = "constraint \"" + constraint + "\" with several alternatives"; + return false; + } if(std::isdigit(static_cast(c))) { @@ -210,6 +251,8 @@ static bool parse_constraint( if(operand.tied_output.has_value()) { operand.kind = operands.operands[*operand.tied_output].kind; + operand.may_be_memory = false; + operand.may_be_immediate = false; // an input tied to a memory output is that memory; GCC rejects anything // else if( @@ -226,12 +269,19 @@ static bool parse_constraint( { operand.kind = asm_operandt::kindt::REGISTER; operand.fixed_register = fixed; + operand.may_be_memory = mem || any; + operand.may_be_immediate = (imm || any) && !operand.is_output; } else if(reg || any) { - // the compiler may choose a register whenever one is allowed; the effect - // on the C value is the same either way + // The compiler may choose a register whenever one is allowed. Where it + // may also choose memory (see asm_operandst::memory_alternative) or an + // immediate, the effect of the instructions may differ: the lowering + // models both register and memory, and the semantics fail where an + // immediate would make a difference. operand.kind = asm_operandt::kindt::REGISTER; + operand.may_be_memory = mem || any; + operand.may_be_immediate = (imm || any) && !operand.is_output; } else if(mem) operand.kind = asm_operandt::kindt::MEMORY; @@ -245,22 +295,29 @@ static bool parse_constraint( // as an rvalue in a register, an array decays to the address of its first // element, and a function to its address - if(operand.kind == asm_operandt::kindt::REGISTER && !operand.is_output) + if( + operand.kind == asm_operandt::kindt::REGISTER && !operand.is_output && + (operand.expr.type().id() == ID_array || + operand.expr.type().id() == ID_code)) { + if(operand.may_be_memory) + { + // in memory, the operand is the array or function itself + error = "array or function operand that may be in a register or memory"; + return false; + } if(operand.expr.type().id() == ID_array) { operand.expr = address_of_exprt{ index_exprt{operand.expr, from_integer(0, c_index_type())}}; } - else if(operand.expr.type().id() == ID_code) + else operand.expr = address_of_exprt{operand.expr}; } if( operand.kind == asm_operandt::kindt::MEMORY && !operand.is_output && - !operand.expr.get_bool(ID_C_lvalue) && operand.expr.id() != ID_symbol && - operand.expr.id() != ID_dereference && operand.expr.id() != ID_index && - operand.expr.id() != ID_member) + !operand.is_lvalue()) { error = "memory input operand is not an lvalue"; return false; diff --git a/src/assembler/asm_operands.h b/src/assembler/asm_operands.h index cb010c93d474..c3bed47c2722 100644 --- a/src/assembler/asm_operands.h +++ b/src/assembler/asm_operands.h @@ -40,6 +40,12 @@ struct asm_operandt }; kindt kind = kindt::REGISTER; + /// whether the constraint allows memory: for an operand of kind REGISTER, + /// GCC may choose either, see \ref asm_operandst::memory_alternative + bool may_be_memory = false; + /// whether the constraint allows an immediate (for inputs only): for an + /// operand of kind REGISTER, GCC may print the constant instead + bool may_be_immediate = false; bool is_output = false; /// true for inputs and for `+` outputs bool is_read = false; @@ -54,6 +60,9 @@ struct asm_operandt std::string flag_condition; /// for inputs with a matching constraint: the output they initialise std::optional tied_output; + + /// \return Whether \p expr designates an object (rather than a value) + bool is_lvalue() const; }; /// The operand interface of a GCC-style inline assembly statement, numbered as @@ -83,6 +92,14 @@ class asm_operandst /// \return the index of the label with base name \p name, if any std::optional find_label(const irep_idt &name) const; + /// Choose the memory alternative for register operand \p index, whose + /// constraint allows memory as well (see \ref asm_operandt::may_be_memory), + /// and for the inputs tied to it. + /// \param index: the operand + /// \param [out] error: why GCC cannot choose memory, if it cannot + /// \return true on success + bool memory_alternative(std::size_t index, std::string &error); + /// Interpret the operands of \p code. /// \param code: the statement /// \param semantics: for architecture-specific constraint letters; may be diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index f320dc778431..90fc1eec4006 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -58,6 +58,8 @@ struct x86_operandt std::size_t width = 0; /// true for the 8-bit registers %ah..%dh and the h modifier bool high_byte = false; + /// for a reference to an operand of the statement: its index + std::optional index; // IMMEDIATE exprt value; @@ -92,6 +94,49 @@ const std::set &condition_codes() return codes; } +/// \return Whether all immediates that the x86 constraint \p constraint +/// allows are at least 0 and less than \p limit +bool immediates_below(const std::string &constraint, std::size_t limit) +{ + for(const char c : constraint) + { + switch(c) + { + case 'I': // 0 to 31 + if(limit <= 31) + return false; + break; + case 'J': // 0 to 63 + if(limit <= 63) + return false; + break; + case 'M': // 0 to 3 + if(limit <= 3) + return false; + break; + case 'i': + case 'n': + case 's': + case 'E': + case 'F': + case 'K': + case 'L': + case 'N': + case 'O': + case 'e': + case 'Z': + case 'G': + case 'C': + case 'g': + case 'X': + return false; + default: + break; + } + } + return true; +} + std::size_t suffix_width(char c) { switch(c) @@ -480,6 +525,7 @@ bool asm_x86_semanticst::parse_register( operand.kind = x86_operandt::kindt::REGISTER; operand.storage = ctx.operand_storage(token.index); + operand.index = token.index; const std::string &m = token.modifier; if(m.empty()) { @@ -584,8 +630,14 @@ bool asm_x86_semanticst::parse_memory( asm_operandt::kindt::MEMORY) { const std::size_t index = tokens[pos].index; - if(!tokens[pos].modifier.empty()) + // GCC prints a memory operand the same way with a size modifier + const std::string &modifier = tokens[pos].modifier; + if( + !modifier.empty() && modifier != "b" && modifier != "h" && + modifier != "w" && modifier != "k" && modifier != "q") + { return ctx.fail("unsupported memory operand modifier"); + } operand.address = ctx.operand_address(index); operand.lvalue = dereference_exprt{ctx.operand_address(index)}; operand.natural_width = ctx.operand_width(index); @@ -769,6 +821,19 @@ exprt asm_x86_semanticst::read( switch(operand.kind) { case x86_operandt::kindt::REGISTER: + if( + operand.index.has_value() && + ctx.operands.operands.at(*operand.index).may_be_immediate && + (operand.offset != 0 || + width > reference_bits("", ctx.operand_width(*operand.index)))) + { + // GCC may print the constant instead of the register, and the + // instruction then extends it to the width it reads in another way + // than a register (or reads its low byte instead of bits 8 to 15) + ctx.fail( + "operand %" + std::to_string(*operand.index) + + ", which may be an immediate, is read at a width other than its own"); + } if(operand.offset == 0 && width == register_width()) return operand.storage; return extract(operand.storage, operand.offset, width); @@ -1363,6 +1428,18 @@ bool asm_x86_semanticst::lower_sized( { if(target.environment) return ctx.fail("bit string operation on segment memory"); + if( + ops[0].index.has_value() && + ctx.operands.operands.at(*ops[0].index).may_be_immediate && + !immediates_below( + ctx.operands.operands.at(*ops[0].index).constraint, w)) + { + // GCC may print the constant instead of the register: an immediate + // bit offset is taken modulo the operand size + return ctx.fail( + "the bit offset of " + base + + " may be an immediate, which may exceed the operand size"); + } // the bit offset addresses a bit string starting at the operand: // the word is at address + (offset >> log2(w)) * (w / 8) const std::size_t pw = config.ansi_c.pointer_width; diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index b74f418f1b39..0d1ed5566850 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -18,6 +18,7 @@ Date: December 2014 #include #include #include +#include #include #include #include @@ -105,6 +106,14 @@ class remove_asmt goto_programt &dest, std::string &failure); + bool lower_alternative( + const irep_idt &function_id, + const code_asm_gcct &code, + asm_operandst &operands, + const std::vector &instructions, + goto_programt &dest, + std::string &failure); + bool lower_instructions( const std::vector &instructions, asm_lowering_contextt &ctx, @@ -599,6 +608,121 @@ bool remove_asmt::lower_gcc( return false; } + // GCC may choose a register or memory for the operands whose constraint + // allows both (such as "rm" and "g"), and the effect of the instructions may + // depend on the choice: for example, a 32-bit write clears the upper half of + // a 64-bit register, but not of memory. Lower every combination of choices, + // and choose one of them nondeterministically. + std::vector choices; + for(std::size_t i = 0; i < operands.operands.size(); ++i) + { + const asm_operandt &operand = operands.operands[i]; + if( + operand.kind == asm_operandt::kindt::REGISTER && operand.may_be_memory && + !operand.tied_output.has_value()) + { + choices.push_back(i); + } + } + const std::size_t max_choices = 3; + if(choices.size() > max_choices) + { + failure = "more than " + std::to_string(max_choices) + + " operands may be in a register or in memory"; + return false; + } + + std::list alternatives; + for(std::size_t mask = 0; mask < (std::size_t{1} << choices.size()); ++mask) + { + asm_operandst alternative = operands; + for(std::size_t j = 0; j < choices.size(); ++j) + { + if( + (mask & (std::size_t{1} << j)) != 0 && + !alternative.memory_alternative(choices[j], failure)) + { + return false; + } + } + alternatives.emplace_back(); + if(!lower_alternative( + function_id, + code, + alternative, + instructions, + alternatives.back(), + failure)) + { + return false; + } + } + + if(alternatives.size() == 1) + { + dest.destructive_append(alternatives.front()); + return true; + } + + const source_locationt &location = code.source_location(); + const symbolt *function_symbol = symbol_table.lookup(function_id); + const symbol_exprt choice = + get_fresh_aux_symbol( + bool_typet{}, + id2string(function_id), + "asm_alternative", + location, + function_symbol == nullptr || function_symbol->mode.empty() + ? ID_C + : function_symbol->mode, + symbol_table) + .symbol_expr(); + goto_programt end; + const auto end_target = end.add(goto_programt::make_skip(location)); + dest.add(goto_programt::make_decl(choice, location)); + while(!alternatives.empty()) + { + if(alternatives.size() > 1) + { + // skip this alternative nondeterministically + goto_programt next; + const auto next_target = next.add(goto_programt::make_skip(location)); + dest.add(goto_programt::make_assignment( + choice, side_effect_expr_nondett{bool_typet{}, location}, location)); + dest.add(goto_programt::make_goto(next_target, choice, location)); + dest.destructive_append(alternatives.front()); + dest.add(goto_programt::make_goto(end_target, location)); + dest.destructive_append(next); + } + else + dest.destructive_append(alternatives.front()); + alternatives.pop_front(); + } + dest.destructive_append(end); + dest.add(goto_programt::make_dead(choice, location)); + + return true; +} + +/// Translates the gcc-style statement \p code, whose operands are +/// \p operands and whose template consists of \p instructions, using the +/// instruction semantics of the architecture. +/// +/// \param function_id: Name of function being processed +/// \param code: The inline assembly code statement to translate +/// \param operands: The operands of \p code, with the kind of each chosen +/// \param instructions: The instructions of the template of \p code +/// \param dest: The goto program to append the translation to +/// \param [out] failure: Why \p code is not modeled, if it is not +/// \return Whether all of \p code is modeled +bool remove_asmt::lower_alternative( + const irep_idt &function_id, + const code_asm_gcct &code, + asm_operandst &operands, + const std::vector &instructions, + goto_programt &dest, + std::string &failure) +{ asm_lowering_contextt ctx{ symbol_table, function_id, code.source_location(), operands, *semantics}; if(code.has_goto_target()) From 570bd7b9d286d668bd6f8acb24d905cf942a7b98 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:43:13 +0000 Subject: [PATCH 057/100] Inline assembly: approximate what breaks GCC's operand contract 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 --- doc/architectural/inline-assembly.md | 15 ++ doc/cprover-manual/modeling-inline-asm.md | 8 + .../cbmc/asm_x86_operand_contract/main.i | 73 +++++++++ .../cbmc/asm_x86_operand_contract/test.desc | 27 ++++ src/assembler/asm_lowering.cpp | 145 +++++++++++++++++- src/assembler/asm_operands.cpp | 4 +- src/assembler/asm_operands.h | 2 + src/assembler/asm_semantics.h | 46 ++++++ 8 files changed, 317 insertions(+), 3 deletions(-) create mode 100644 regression/cbmc/asm_x86_operand_contract/main.i create mode 100644 regression/cbmc/asm_x86_operand_contract/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 925337019556..7a238d2bf50f 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -106,6 +106,21 @@ one of them is not interpreted: forward branches to it; a backward branch must not make a value unknown that its target took as known. - An input tied to a memory output must be the same object. +- GCC's operand contract must hold, as the operand storage does not model + registers that GCC gives to several operands + (`asm_lowering_contextt::check_operand_contract`): no instruction may + write an input-only register operand (GCC assumes it unchanged, and may + hold two inputs of the same value in one register), and no instruction + may read a register input or the address of a memory operand after an + instruction (in sequence, or in an earlier iteration of a loop formed by + a backward branch) wrote an output without the earlyclobber modifier `&`, + as GCC may allocate that output to the same register. An output that + holds its own value when the statement starts (`+`, or tied to an input) + shares 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 for such an output, only operands of its width (or of + the width of an input tied to it) are considered. These checks are + independent of the architecture. An instruction that is atomic on the hardware (on x86: lock-prefixed instructions and `xchg` with a memory operand) is an atomic section of its diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 8f6b2cccd356..c99bbb1b012a 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -98,6 +98,14 @@ instructions are listed in the tables below) if it: faults, as do exception tables. The approximation of such an `asm goto` statement jumps to any of its labels. Other data in other sections is ignored; +- relies on more than GCC's operand contract guarantees: it writes an + input-only operand that is held in a register (GCC assumes the register + unchanged, and may hold two inputs with the same value in one register), + or it reads an input operand held in a register, or the address of a + memory operand, after it wrote an output operand without the earlyclobber + modifier `&` (GCC may allocate both to the same register; for an output + that holds its own value when the statement starts, as with `+`, only + operands of the same width are considered); - writes a register that is neither bound to an operand nor clobbered: as CBMC does not track register variables (`register long x asm("rax")`), such a write may change a C variable; diff --git a/regression/cbmc/asm_x86_operand_contract/main.i b/regression/cbmc/asm_x86_operand_contract/main.i new file mode 100644 index 000000000000..a19907c02d27 --- /dev/null +++ b/regression/cbmc/asm_x86_operand_contract/main.i @@ -0,0 +1,73 @@ +// GCC assumes that the instructions read all inputs before they write an +// output without the earlyclobber modifier '&', and that they do not change +// input-only operands: it may allocate such an output to the register of an +// input or of the address of a memory operand, and two inputs with the same +// value to one register. Statements that do not meet these assumptions are +// approximated. "violated" marks properties that the native code of GCC 13 on +// x86-64 violates at -O2. + +__attribute__((noinline)) int no_earlyclobber(int c) +{ + int a, b; + __asm__("movl $1, %0\n\tmovl %2, %1" : "=r"(a), "=r"(b) : "r"(c)); + return b + 0 * a; +} + +__attribute__((noinline)) int earlyclobber(int c) +{ + int a, b; + __asm__("movl $1, %0\n\tmovl %2, %1" : "=&r"(a), "=r"(b) : "r"(c)); + return b + 0 * a; +} + +__attribute__((noinline)) int input_write(int x) +{ + int a; + __asm__("incl %1\n\tmovl %2, %0" : "=r"(a) : "r"(x), "r"(x) : "cc"); + return a; +} + +__attribute__((noinline)) long shared_address(long *p) +{ + long r; + __asm__("addq $8, %0\n\tmovq %2, %1" : "+r"(p), "=r"(r) : "m"(*p) : "cc"); + return r; +} + +__attribute__((noinline)) int other_width(int x, long *p) +{ + // x and the address of *p differ in width, so GCC does not give them one + // register + long r; + __asm__("addl $8, %0\n\tmovq %2, %1" : "+r"(x), "=r"(r) : "m"(*p) : "cc"); + return x + (int)r; +} + +__attribute__((noinline)) int loop(int x) +{ + int a; + __asm__("movl $2, %%ecx\n" + "1: movl %1, %%eax\n\t" + "movl %%eax, %0\n\t" + "decl %%ecx\n\t" + "jnz 1b" + : "=r"(a) + : "r"(x) + : "eax", "ecx", "cc"); + return a; +} + +int main(void) +{ + long v[2] = {1, 2}, w[2] = {1, 2}; + // violated + __CPROVER_assert(no_earlyclobber(7) == 7, "no earlyclobber"); + __CPROVER_assert(earlyclobber(7) == 7, "earlyclobber"); + // violated + __CPROVER_assert(input_write(7) == 7, "input write"); + // violated + __CPROVER_assert(shared_address(v) == 1, "address in the output register"); + __CPROVER_assert(other_width(1, w) == 10, "different widths"); + __CPROVER_assert(loop(3) == 3, "read after write in a loop"); + return 0; +} diff --git a/regression/cbmc/asm_x86_operand_contract/test.desc b/regression/cbmc/asm_x86_operand_contract/test.desc new file mode 100644 index 000000000000..07830ffcb663 --- /dev/null +++ b/regression/cbmc/asm_x86_operand_contract/test.desc @@ -0,0 +1,27 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 64 no earlyclobber: FAILURE$ +^\[main\.assertion\.2\] line 65 earlyclobber: SUCCESS$ +^\[main\.assertion\.3\] line 67 input write: FAILURE$ +^\[main\.assertion\.4\] line 69 address in the output register: FAILURE$ +^\[main\.assertion\.5\] line 70 different widths: SUCCESS$ +^\[main\.assertion\.6\] line 71 read after write in a loop: FAILURE$ +approximating inline assembly statement at .* line 12 function no_earlyclobber: output operand %0, which has no earlyclobber modifier '&', is written before input operand %2 is read +approximating inline assembly statement at .* line 26 function input_write: writes input operand %1 +approximating inline assembly statement at .* line 33 function shared_address: output operand %0, which has no earlyclobber modifier '&', is written before the address of memory operand %2 is read +approximating inline assembly statement at .* line 49 function loop: output operand %0, which has no earlyclobber modifier '&', is written before input operand %1 is read +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function (earlyclobber|other_width) +-- +GCC may allocate an output without '&' to the register of an input or of the +address of a memory operand, and two inputs with the same value to one +register; with -O2, GCC 13 on x86-64 does so in no_earlyclobber, input_write, +and shared_address, whose native code violates assertions 1, 3, and 4. Such statements are +approximated. An output that holds its own value when the statement starts +shares a register only with an operand of the same value, and hence of the +same width; the statement in other_width is interpreted. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 8ff73e013798..716e73a9838b 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -14,6 +14,7 @@ Author: Michael Tautschnig #include #include #include +#include #include #include #include @@ -183,6 +184,25 @@ void asm_lowering_contextt::assign(const exprt &lhs, const exprt &rhs) written_registers.insert(entry.first); } + note_reads(rhs); + if(lhs.id() == ID_symbol) + { + const irep_idt &identifier = to_symbol_expr(lhs).identifier(); + const auto output = outputs_to_watch.find(identifier); + if(output != outputs_to_watch.end()) + first_write.emplace(output->second, current_instruction()); + const auto input = inputs_to_watch.find(identifier); + if(input != inputs_to_watch.end()) + { + fail( + "writes input operand %" + std::to_string(input->second) + + ", which GCC assumes to be unchanged (and may hold in the register of " + "another input with the same value)"); + } + } + else + note_reads(lhs); + const bool unknown_value = depends_on_unknown(rhs); if(lhs.id() == ID_symbol) { @@ -201,8 +221,89 @@ void asm_lowering_contextt::assign(const exprt &lhs, const exprt &rhs) body.add(goto_programt::make_assignment(lhs, rhs, location)); } +void asm_lowering_contextt::note_reads(const exprt &expr) +{ + if(inputs_to_watch.empty()) + return; + for(auto it = expr.depth_cbegin(); it != expr.depth_cend(); ++it) + { + if(it->id() != ID_symbol) + continue; + const auto input = inputs_to_watch.find(to_symbol_expr(*it).identifier()); + if(input != inputs_to_watch.end()) + last_read[input->second] = current_instruction(); + } +} + +void asm_lowering_contextt::note_branch( + std::size_t branch, + goto_programt::const_targett target) +{ + const auto entry = label_index.find(&*target); + INVARIANT(entry != label_index.end(), "branch targets are label definitions"); + if(entry->second > branch) + return; // forward + last_backward_branch = std::max(last_backward_branch.value_or(0), branch); + first_backward_target = + std::min(first_backward_target.value_or(entry->second), entry->second); +} + +bool asm_lowering_contextt::check_operand_contract() +{ + for(const auto &write : first_write) + { + const asm_operandt &output = operands.operands[write.first]; + // A live-in output (with a + constraint, or initialised by an input) + // holds its own value when the statement starts; GCC gives its register + // to another operand only if it knows that both hold the same value, which + // its register allocator only knows for values of the same machine mode. + const symbol_exprt &output_storage = storage.at(write.first); + bool live_in = output.is_read; + std::set live_in_widths{width(output.expr.type())}; + for(std::size_t i = operands.number_of_outputs; + i < operands.operands.size(); + ++i) + { + const auto s = storage.find(i); + if(s != storage.end() && s->second == output_storage) + { + live_in = true; + live_in_widths.insert(width(operands.operands[i].expr.type())); + } + } + + for(const auto &read : last_read) + { + const asm_operandt &input = operands.operands[read.first]; + const bool is_address = input.kind == asm_operandt::kindt::MEMORY; + const std::size_t input_width = + is_address ? config.ansi_c.pointer_width : width(input.expr.type()); + if(live_in && live_in_widths.count(input_width) == 0) + continue; + + // the read follows the write in sequence, or in a later iteration of a + // loop formed by a backward branch + const bool later = + read.second > write.second || (last_backward_branch.has_value() && + write.second <= *last_backward_branch && + read.second >= *first_backward_target); + if(later) + { + return fail( + "output operand %" + std::to_string(write.first) + + ", which has no earlyclobber modifier '&', is written before " + + (is_address ? "the address of memory operand %" : "input operand %") + + std::to_string(read.first) + + " is read, and GCC may allocate both to the same register"); + } + } + } + return true; +} + void asm_lowering_contextt::begin_instruction() { + ++instructions_begun; atomic = false; if(body.instructions.empty()) instruction_start.reset(); @@ -225,6 +326,7 @@ void asm_lowering_contextt::end_instruction() void asm_lowering_contextt::assume(const exprt &condition) { + note_reads(condition); body.add(goto_programt::make_assumption(condition, location)); } @@ -272,7 +374,10 @@ void asm_lowering_contextt::call( exprt::operandst args; for(const auto &arg : arguments) + { + note_reads(arg); args.push_back(typecast_exprt::conditional_cast(arg, void_pointer)); + } code_typet type{ code_typet::parameterst{args.size(), code_typet::parametert{void_pointer}}, @@ -553,6 +658,32 @@ bool asm_lowering_contextt::prepare( } } + // the operands that GCC's operand contract is about (see + // check_operand_contract) + std::set output_registers; + for(std::size_t i = 0; i < operands.number_of_outputs; ++i) + { + const asm_operandt &operand = operands.operands[i]; + if(operand.kind != asm_operandt::kindt::REGISTER) + continue; + output_registers.insert(storage.at(i).identifier()); + if(!operand.earlyclobber) + outputs_to_watch.emplace(storage.at(i).identifier(), i); + } + for(std::size_t i = 0; i < operands.operands.size(); ++i) + { + const asm_operandt &operand = operands.operands[i]; + if(operand.kind == asm_operandt::kindt::MEMORY) + inputs_to_watch.emplace(addresses.at(i).identifier(), i); + else if( + i >= operands.number_of_outputs && + operand.kind == asm_operandt::kindt::REGISTER && + output_registers.count(storage.at(i).identifier()) == 0) + { + inputs_to_watch.emplace(storage.at(i).identifier(), i); + } + } + return true; } @@ -576,6 +707,7 @@ void asm_lowering_contextt::define_label(const std::string &name) } } unknown_at_label[&*t] = unknown; + label_index[&*t] = instructions_begun; if(numeric) numeric_labels[name].push_back(t); else @@ -586,6 +718,7 @@ bool asm_lowering_contextt::branch( const asm_tokent &target, const exprt &condition) { + note_reads(condition); if(target.kind == asm_tokent::kindt::C_LABEL) { if(goto_target.is_nil()) @@ -611,6 +744,7 @@ bool asm_lowering_contextt::branch( return fail("undefined label " + target.text + "b"); if(!check_unknown_at_target(definitions.back(), unknown)) return false; + note_branch(current_instruction(), definitions.back()); body.add( goto_programt::make_goto(definitions.back(), condition, location)); return true; @@ -622,7 +756,8 @@ bool asm_lowering_contextt::branch( definitions.size(), true, true, - unknown}); + unknown, + current_instruction()}); return true; } @@ -634,7 +769,8 @@ bool asm_lowering_contextt::branch( 0, true, false, - unknown}); + unknown, + current_instruction()}); return true; } @@ -644,6 +780,7 @@ bool asm_lowering_contextt::branch( goto_programt::targett asm_lowering_contextt::begin_conditional(const exprt &condition) { + note_reads(condition); ++conditional_depth; return body.add( goto_programt::make_incomplete_goto(not_exprt{condition}, location)); @@ -679,9 +816,13 @@ bool asm_lowering_contextt::finish(goto_programt &dest) } if(!check_unknown_at_target(target, branch.unknown)) return false; + note_branch(branch.instruction_index, target); branch.instruction->complete_goto(target); } + if(!check_operand_contract()) + return false; + for(auto &branch : exit_branches) branch->complete_goto(exit_label); diff --git a/src/assembler/asm_operands.cpp b/src/assembler/asm_operands.cpp index bc16df292123..a009db945b8a 100644 --- a/src/assembler/asm_operands.cpp +++ b/src/assembler/asm_operands.cpp @@ -103,7 +103,9 @@ static bool parse_constraint( operand.is_read = false; else if(c == '+') operand.is_read = true; - else if(c == '&' || c == '%' || c == '?' || c == '!' || c == '*') + else if(c == '&') + operand.earlyclobber = true; + else if(c == '%' || c == '?' || c == '!' || c == '*') { } else diff --git a/src/assembler/asm_operands.h b/src/assembler/asm_operands.h index c3bed47c2722..2014a261a443 100644 --- a/src/assembler/asm_operands.h +++ b/src/assembler/asm_operands.h @@ -49,6 +49,8 @@ struct asm_operandt bool is_output = false; /// true for inputs and for `+` outputs bool is_read = false; + /// for outputs: whether the constraint has the earlyclobber modifier `&` + bool earlyclobber = false; /// the symbolic name used in `%[name]`, if any irep_idt name; std::string constraint; diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index 1f3aa2abb873..fa60f92046ae 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -237,6 +237,50 @@ class asm_lowering_contextt void mark_unknown(const irep_idt &identifier); + /// \name GCC's operand contract + /// GCC may allocate an output without the earlyclobber modifier `&` to the + /// register of an input, or to a register that holds the address of a + /// memory operand, assuming that the instructions read all inputs before + /// they write any output; and it assumes that the instructions do not + /// change input-only operands. The operand storage of the lowering does not + /// model such sharing, so statements that rely on either assumption are not + /// modeled. + /// \{ + + /// the number of instructions begun so far (\ref begin_instruction); the + /// index of the instruction being lowered is one less + std::size_t instructions_begun = 0; + /// the storage of outputs without `&`, by symbol, with the operand index + std::map outputs_to_watch; + /// the storage of register inputs that no output shares, and the addresses + /// of memory operands, by symbol, with the operand index + std::map inputs_to_watch; + /// for each operand in \ref outputs_to_watch: the first instruction that + /// writes it + std::map first_write; + /// for each operand in \ref inputs_to_watch: the last instruction that reads + /// it + std::map last_read; + /// the index of the first instruction after each label definition + std::map label_index; + /// the last instruction with a backward branch, and the first instruction + /// that a backward branch jumps to, if there are backward branches + std::optional last_backward_branch, first_backward_target; + + /// \return The index of the instruction being lowered + std::size_t current_instruction() const + { + return instructions_begun == 0 ? 0 : instructions_begun - 1; + } + /// Note the reads of operands in \p expr by the current instruction. + void note_reads(const exprt &expr); + /// Note a branch from instruction \p branch to \p target. + void note_branch(std::size_t branch, goto_programt::const_targett target); + /// Fail if an output may share its register with an input or an address + /// that an instruction reads after an instruction wrote the output. + bool check_operand_contract(); + /// \} + /// Fail if a branch to \p target with \ref unknown being \p at_branch /// would make a value unknown at \p target that was taken as known when /// lowering the code at \p target. @@ -265,6 +309,8 @@ class asm_lowering_contextt bool numeric; /// \ref unknown at the branch std::set unknown; + /// the instruction with the branch, see \ref instructions_begun + std::size_t instruction_index; }; std::vector pending; goto_programt::targett exit_label; From 38488f6486886a7e4669f65e12353b9e8ff7a065 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:52:45 +0000 Subject: [PATCH 058/100] Inline assembly: record the dialect and approximate Intel syntax 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 --- doc/architectural/inline-assembly.md | 7 +++++++ doc/cprover-manual/modeling-inline-asm.md | 5 +++++ regression/goto-cc-cbmc/CMakeLists.txt | 7 +++++++ regression/goto-cc-cbmc/Makefile | 6 ++++-- .../asm_intel_syntax/directive.desc | 13 ++++++++++++ .../goto-cc-cbmc/asm_intel_syntax/directive.i | 20 +++++++++++++++++++ .../goto-cc-cbmc/asm_intel_syntax/main.i | 15 ++++++++++++++ .../goto-cc-cbmc/asm_intel_syntax/test.desc | 15 ++++++++++++++ regression/goto-cc-cbmc/chain.sh | 12 +++++++++-- src/ansi-c/c_typecheck_code.cpp | 5 +++++ src/assembler/remove_asm.cpp | 16 +++++++++++++++ src/goto-cc/gcc_mode.cpp | 4 ++++ src/util/config.h | 6 ++++++ src/util/irep_ids.def | 1 + 14 files changed, 128 insertions(+), 4 deletions(-) create mode 100644 regression/goto-cc-cbmc/asm_intel_syntax/directive.desc create mode 100644 regression/goto-cc-cbmc/asm_intel_syntax/directive.i create mode 100644 regression/goto-cc-cbmc/asm_intel_syntax/main.i create mode 100644 regression/goto-cc-cbmc/asm_intel_syntax/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 7a238d2bf50f..ad50d1ca8736 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -78,6 +78,13 @@ apply to the C expressions of the operands. The following rules keep the interpretation sound. A statement that violates one of them is not interpreted: +- The template must be in the dialect that the semantics read (AT&T on + x86). `goto-cc` sets `config.ansi_c.asm_dialect` from `-masm`, and the C + front end (`c_typecheck_baset::typecheck_asm`) records it on each + GCC-style statement as `ID_asm_dialect`, so that it survives into goto + binaries; `remove_asmt::lower_gcc` does not interpret statements in + another dialect, and `lower_instructions` does not interpret templates + that switch to Intel syntax with `.intel_syntax`. - Every instruction, prefix, operand form, and directive must be understood. - Instructions in another section (`.pushsection`/`.section`) are not executed in sequence; they may be executed when another instruction faults diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index c99bbb1b012a..f74f0e540b57 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -80,6 +80,11 @@ instructions are listed in the tables below) if it: - contains an instruction, operand, prefix, or directive that the semantics do not support, or instructions in another section (such as exception fixups, which run when an instruction faults); +- is in Intel syntax: the x86 semantics read AT&T syntax only. `goto-cc` + records the dialect that `-masm=intel` selects on each statement, so that + this also applies when another tool processes the goto binary; a template + that switches to Intel syntax with `.intel_syntax` is not interpreted + either; - contains an instruction without a size suffix whose operand size is not given by a register operand (other than the count of a shift): the assembler does not see the C type of a memory operand, and uses a default diff --git a/regression/goto-cc-cbmc/CMakeLists.txt b/regression/goto-cc-cbmc/CMakeLists.txt index 53647ddb692f..8a64f81da49a 100644 --- a/regression/goto-cc-cbmc/CMakeLists.txt +++ b/regression/goto-cc-cbmc/CMakeLists.txt @@ -4,6 +4,13 @@ else() set(is_windows false) endif() +if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") + set(gcc_only -X gcc-only) +else() + set(gcc_only "") +endif() + add_test_pl_tests( "${CMAKE_CURRENT_SOURCE_DIR}/chain.sh $ $ ${is_windows}" + ${gcc_only} ) diff --git a/regression/goto-cc-cbmc/Makefile b/regression/goto-cc-cbmc/Makefile index 10734a47ff28..758398d8ee53 100644 --- a/regression/goto-cc-cbmc/Makefile +++ b/regression/goto-cc-cbmc/Makefile @@ -6,16 +6,18 @@ include ../../src/common ifeq ($(BUILD_ENV_),MSVC) exe=../../../src/goto-cc/goto-cl is_windows=true + GCC_ONLY = -X gcc-only else exe=../../../src/goto-cc/goto-cc is_windows=false + GCC_ONLY = endif test: - @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/cbmc/cbmc $(is_windows)' + @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/cbmc/cbmc $(is_windows)' $(GCC_ONLY) tests.log: - @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/cbmc/cbmc $(is_windows)' + @../test.pl -e -p -c '../chain.sh $(exe) ../../../src/cbmc/cbmc $(is_windows)' $(GCC_ONLY) clean: $(RM) tests.log diff --git a/regression/goto-cc-cbmc/asm_intel_syntax/directive.desc b/regression/goto-cc-cbmc/asm_intel_syntax/directive.desc new file mode 100644 index 000000000000..e2cac7720ef5 --- /dev/null +++ b/regression/goto-cc-cbmc/asm_intel_syntax/directive.desc @@ -0,0 +1,13 @@ +CORE gcc-only +directive.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 18 AT&T syntax: FAILURE$ +approximating inline assembly statement at .* line 7 function directive: '\.intel_syntax noprefix' switches to Intel syntax +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +A template that switches to Intel syntax (in which the statement subtracts b +from a) is approximated. diff --git a/regression/goto-cc-cbmc/asm_intel_syntax/directive.i b/regression/goto-cc-cbmc/asm_intel_syntax/directive.i new file mode 100644 index 000000000000..8af05f92e696 --- /dev/null +++ b/regression/goto-cc-cbmc/asm_intel_syntax/directive.i @@ -0,0 +1,20 @@ +// Inline assembly that switches to Intel syntax with .intel_syntax: the +// destination is the first operand. + +__attribute__((noinline)) int directive(int a, int b) +{ + // a -= b + __asm__(".intel_syntax noprefix\n\t" + "sub %0, %1\n\t" + ".att_syntax prefix" + : "+r"(a), "+r"(b) + : + : "cc"); + return a; +} + +int main(void) +{ + __CPROVER_assert(directive(10, 3) == 10, "AT&T syntax"); + return 0; +} diff --git a/regression/goto-cc-cbmc/asm_intel_syntax/main.i b/regression/goto-cc-cbmc/asm_intel_syntax/main.i new file mode 100644 index 000000000000..187d0a4853a3 --- /dev/null +++ b/regression/goto-cc-cbmc/asm_intel_syntax/main.i @@ -0,0 +1,15 @@ +// Inline assembly in Intel syntax, selected with -masm=intel: the destination +// is the first operand. + +__attribute__((noinline)) int masm(int a, int b) +{ + // with -masm=intel: a -= b; in AT&T syntax: b -= a + __asm__("sub %0, %1" : "+r"(a), "+r"(b) : : "cc"); + return a; +} + +int main(void) +{ + __CPROVER_assert(masm(10, 3) == 10, "AT&T syntax"); + return 0; +} diff --git a/regression/goto-cc-cbmc/asm_intel_syntax/test.desc b/regression/goto-cc-cbmc/asm_intel_syntax/test.desc new file mode 100644 index 000000000000..315cb38db161 --- /dev/null +++ b/regression/goto-cc-cbmc/asm_intel_syntax/test.desc @@ -0,0 +1,15 @@ +CORE gcc-only +main.i +-masm=intel _ --arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 13 AT&T syntax: FAILURE$ +approximating inline assembly statement at .* line 7 function masm: the template is in the intel dialect \(-masm=intel\) +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +goto-cc records the dialect that -masm selects on the statement, so that cbmc +does not read an Intel-syntax template as AT&T syntax (in which the statement +would leave a unchanged; with -masm=intel, it subtracts b from a). Such +statements are approximated. diff --git a/regression/goto-cc-cbmc/chain.sh b/regression/goto-cc-cbmc/chain.sh index 61ec544401e8..243923017f33 100755 --- a/regression/goto-cc-cbmc/chain.sh +++ b/regression/goto-cc-cbmc/chain.sh @@ -11,10 +11,18 @@ name=${*:$#} base_name=${name%.c} base_name=${base_name%.cpp} +# options before " _ " are passed to goto-cc, the others to cbmc +goto_cc_options="" +if [[ "$options" == *" _ "* ]] +then + goto_cc_options="${options%%" _ "*}" + options="${options#*" _ "}" +fi + if [[ "${is_windows}" == "true" ]]; then - "${goto_cc}" "${name}" "/Fe${base_name}.gb" + "${goto_cc}" ${goto_cc_options} "${name}" "/Fe${base_name}.gb" else - "${goto_cc}" "${name}" -o "${base_name}.gb" + "${goto_cc}" ${goto_cc_options} "${name}" -o "${base_name}.gb" fi "${cbmc}" "${base_name}.gb" ${options} diff --git a/src/ansi-c/c_typecheck_code.cpp b/src/ansi-c/c_typecheck_code.cpp index 1736855a7041..f94b875ccfca 100644 --- a/src/ansi-c/c_typecheck_code.cpp +++ b/src/ansi-c/c_typecheck_code.cpp @@ -172,6 +172,11 @@ void c_typecheck_baset::typecheck_asm(code_asmt &code) auto &code_asm_gcc = to_code_asm_gcc(code); + // the dialect of the template (as selected by -masm), which remove_asm + // needs when it processes the statement, possibly in another tool + if(!config.ansi_c.asm_dialect.empty()) + code_asm_gcc.set(ID_asm_dialect, config.ansi_c.asm_dialect); + typecheck_expr(code_asm_gcc.asm_text()); // the operands are lists of expressions diff --git a/src/assembler/remove_asm.cpp b/src/assembler/remove_asm.cpp index 0d1ed5566850..cc41251ee4ed 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -593,6 +593,15 @@ bool remove_asmt::lower_gcc( return false; } + // the semantics read the default dialect (AT&T on x86) + const irep_idt &dialect = code.get(ID_asm_dialect); + if(!dialect.empty() && dialect != "att") + { + failure = "the template is in the " + id2string(dialect) + + " dialect (-masm=" + id2string(dialect) + ")"; + return false; + } + asm_operandst operands; if(!operands.parse(code, semantics.get(), failure)) return false; @@ -826,6 +835,13 @@ bool remove_asmt::lower_instructions( asm_instructiont instruction = original; const std::string &m = instruction.mnemonic; + // in any section, as the syntax applies to what follows + if(m == ".intel_syntax") + { + failure = "'" + instruction.text + "' switches to Intel syntax"; + return false; + } + if(m == ".pushsection" || m == ".section") { sections.push_back(section_name(instruction)); diff --git a/src/goto-cc/gcc_mode.cpp b/src/goto-cc/gcc_mode.cpp index aa3f261f7833..76419d50656c 100644 --- a/src/goto-cc/gcc_mode.cpp +++ b/src/goto-cc/gcc_mode.cpp @@ -473,6 +473,10 @@ int gcc_modet::doit() arch_changed = true; } + // the dialect of inline assembly (x86) + if(cmdline.isset("masm")) + config.ansi_c.asm_dialect = cmdline.get_value("masm"); + // ARM-specific if(cmdline.isset("mbig-endian") || cmdline.isset("mbig")) config.ansi_c.endianness=configt::ansi_ct::endiannesst::IS_BIG_ENDIAN; diff --git a/src/util/config.h b/src/util/config.h index 527855b49521..3938aacc177b 100644 --- a/src/util/config.h +++ b/src/util/config.h @@ -278,6 +278,12 @@ class configt /// which is more specific than \ref os. irep_idt os_name; + /// The dialect of GCC-style inline assembly as selected by `-masm` (for + /// x86: "att" or "intel"); empty for the default (AT&T on x86). The C + /// front end records it on each GCC-style asm statement (as + /// `ID_asm_dialect`). + irep_idt asm_dialect; + // architecture-specific integer value of null pointer constant bool NULL_is_zero; diff --git a/src/util/irep_ids.def b/src/util/irep_ids.def index fffe6f046f6f..8cd8bd38596d 100644 --- a/src/util/irep_ids.def +++ b/src/util/irep_ids.def @@ -947,6 +947,7 @@ IREP_ID_ONE(prophecy_r_ok) IREP_ID_ONE(prophecy_w_ok) IREP_ID_ONE(prophecy_pointer_in_range) IREP_ID_ONE(bit_cast) +IREP_ID_ONE(asm_dialect) // Projects depending on this code base that wish to extend the list of // available ids should provide a file local_irep_ids.def in their source tree From a014a8d78fd9ac7f73e41f12062afbea06a11ac4 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:54:24 +0000 Subject: [PATCH 059/100] Inline assembly: approximate x86 segment stores that may change objects 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 --- doc/architectural/inline-assembly.md | 4 +++ doc/cprover-manual/modeling-inline-asm.md | 6 ++++ regression/cbmc/asm_x86_segment_store/main.i | 31 ++++++++++++++++ .../cbmc/asm_x86_segment_store/test.desc | 21 +++++++++++ src/assembler/asm_x86.cpp | 36 ++++++++++++++++--- 5 files changed, 94 insertions(+), 4 deletions(-) create mode 100644 regression/cbmc/asm_x86_segment_store/main.i create mode 100644 regression/cbmc/asm_x86_segment_store/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index ad50d1ca8736..267076c450d9 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -113,6 +113,10 @@ one of them is not interpreted: forward branches to it; a backward branch must not make a value unknown that its target took as known. - An input tied to a memory output must be the same object. +- The base of the x86 segments `%fs` and `%gs` is not modeled: a + segment-relative store may change a C object, unless it is not at a memory + operand and the statement has neither a `"memory"` clobber nor a memory + output (GCC's operand contract then excludes it). - GCC's operand contract must hold, as the operand storage does not model registers that GCC gives to several operands (`asm_lowering_contextt::check_operand_contract`): no instruction may diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index f74f0e540b57..bde6936c3392 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -111,6 +111,12 @@ instructions are listed in the tables below) if it: modifier `&` (GCC may allocate both to the same register; for an output that holds its own value when the statement starts, as with `+`, only operands of the same width are considered); +- stores to memory relative to the `%fs` or `%gs` segment, whose base CBMC + does not model (with a zero base, as for `%gs` in x86-64 Linux user space, + the store changes the object at the address), at a memory operand, or 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 segment-relative loads produce nondeterministic values; - writes a register that is neither bound to an operand nor clobbered: as CBMC does not track register variables (`register long x asm("rax")`), such a write may change a C variable; diff --git a/regression/cbmc/asm_x86_segment_store/main.i b/regression/cbmc/asm_x86_segment_store/main.i new file mode 100644 index 000000000000..eb3c944c8f14 --- /dev/null +++ b/regression/cbmc/asm_x86_segment_store/main.i @@ -0,0 +1,31 @@ +// Segment-relative accesses: the segment base is not modeled. With a base of +// zero, as for %gs in x86-64 Linux user space, a store to a C lvalue writes +// it. + +int x; +int y; + +int main(void) +{ + x = 0; + __asm__ volatile("movl $5, %%gs:%0" : "=m"(x)); + // fails: x is 5 on x86-64 Linux + __CPROVER_assert(x == 0, "segment store dropped"); + + // a store that, by GCC's operand contract, changes no C object + y = 0; + __asm__ volatile("movl $5, %%gs:0x10" : : : "cc"); + __CPROVER_assert(y == 0, "store to the environment"); + + // the "memory" clobber declares that the store may change any object + __asm__ volatile("movl $5, %%gs:0x10" : : : "memory"); + // fails + __CPROVER_assert(y == 0, "store to memory"); + + // a load is nondeterministic + int r; + __asm__ volatile("movl %%fs:0x28, %0" : "=r"(r)); + // fails + __CPROVER_assert(r == 0, "segment load"); + return 0; +} diff --git a/regression/cbmc/asm_x86_segment_store/test.desc b/regression/cbmc/asm_x86_segment_store/test.desc new file mode 100644 index 000000000000..63b87d910fae --- /dev/null +++ b/regression/cbmc/asm_x86_segment_store/test.desc @@ -0,0 +1,21 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 13 segment store dropped: FAILURE$ +^\[main\.assertion\.2\] line 18 store to the environment: SUCCESS$ +^\[main\.assertion\.3\] line 23 store to memory: FAILURE$ +^\[main\.assertion\.4\] line 29 segment load: FAILURE$ +approximating inline assembly statement at .* line 11 function main: segment-relative store to a C object +approximating inline assembly statement at .* line 21 function main: segment-relative store, which may change a C object +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (17|26) function main +-- +The segment base is not modeled: a segment-relative store to a C lvalue, or +one in a statement that declares that it may change memory, is approximated +(compiled with GCC 13 for x86-64 Linux, the first statement sets x to 5). +Other segment-relative stores change no C object, and loads are +nondeterministic. diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index 90fc1eec4006..a8f62d06fad8 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -66,10 +66,13 @@ struct x86_operandt // MEMORY exprt address; - /// segment-relative: an address space the C program does not see + /// segment-relative (%fs or %gs): relative to a segment base that is not + /// modeled, so reads are nondeterministic and stores are modeled only + /// where they change no C object (see `write`) bool environment = false; - /// for memory operands bound to a C lvalue: that lvalue, typed - exprt lvalue; + /// for memory operands bound to a C lvalue: that lvalue, typed; nil + /// otherwise + exprt lvalue = nil_exprt{}; /// width of the C lvalue, 0 if unknown std::size_t natural_width = 0; }; @@ -887,7 +890,32 @@ bool asm_x86_semanticst::write( case x86_operandt::kindt::MEMORY: if(operand.environment) - return true; // not visible to the C program + { + // The segment base is not modeled. With a base of zero (as for %gs in + // x86-64 Linux user space), a store to a C lvalue changes it. + if(operand.lvalue.is_not_nil()) + { + return ctx.fail( + "segment-relative store to a C object, which the segment base may " + "or may not offset"); + } + // Otherwise, by GCC's operand contract, the store changes no C object + // unless the statement declares that it may, by a "memory" clobber or + // a memory output. + bool may_change_objects = ctx.operands.clobbers_memory(); + for(const auto &op : ctx.operands.operands) + { + may_change_objects |= + op.is_output && op.kind == asm_operandt::kindt::MEMORY; + } + if(may_change_objects) + { + return ctx.fail( + "segment-relative store, which may change a C object (the " + "statement has a \"memory\" clobber or a memory output)"); + } + return true; + } if(operand.lvalue.is_not_nil() && operand.natural_width == width) { ctx.assign( From 8695f4d6562903b80235240f5cc2984b350b2f4b Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:55:32 +0000 Subject: [PATCH 060/100] Inline assembly: CF of x86 shl and shr by the operand width is undefined 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 --- regression/cbmc/asm_x86_shift_carry/main.i | 38 +++++++++++++++++++ regression/cbmc/asm_x86_shift_carry/test.desc | 17 +++++++++ src/assembler/asm_x86.cpp | 7 +++- 3 files changed, 60 insertions(+), 2 deletions(-) create mode 100644 regression/cbmc/asm_x86_shift_carry/main.i create mode 100644 regression/cbmc/asm_x86_shift_carry/test.desc diff --git a/regression/cbmc/asm_x86_shift_carry/main.i b/regression/cbmc/asm_x86_shift_carry/main.i new file mode 100644 index 000000000000..89ccf2c4b247 --- /dev/null +++ b/regression/cbmc/asm_x86_shift_carry/main.i @@ -0,0 +1,38 @@ +// The Intel SDM leaves CF undefined for shl and shr of 8- and 16-bit operands +// by a count of their width or more. The Intel Xeon Platinum 8124M that +// these tests were run on sets it to the last bit shifted out, but CBMC must +// not prove that. For sar by the width, CF is the sign bit. + +__attribute__((noinline)) unsigned char carry(unsigned char x, unsigned char n) +{ + unsigned char c; + __asm__("shlb %%cl, %1" : "=@ccc"(c), "+q"(x) : "c"(n)); + return c; +} + +__attribute__((noinline)) unsigned char +carry_shr(unsigned short x, unsigned char n) +{ + unsigned char c; + __asm__("shrw %%cl, %1" : "=@ccc"(c), "+r"(x) : "c"(n)); + return c; +} + +__attribute__((noinline)) unsigned char +carry_sar(unsigned char x, unsigned char n) +{ + unsigned char c; + __asm__("sarb %%cl, %1" : "=@ccc"(c), "+q"(x) : "c"(n)); + return c; +} + +int main(void) +{ + // fails: undefined + __CPROVER_assert(carry(1, 8) == 1, "shlb by 8"); + __CPROVER_assert(carry(1, 7) == 0, "shlb by 7"); + // fails: undefined + __CPROVER_assert(carry_shr(0x8000, 16) == 1, "shrw by 16"); + __CPROVER_assert(carry_sar(0x80, 8) == 1, "sarb by 8"); + return 0; +} diff --git a/regression/cbmc/asm_x86_shift_carry/test.desc b/regression/cbmc/asm_x86_shift_carry/test.desc new file mode 100644 index 000000000000..d0cd5578a67a --- /dev/null +++ b/regression/cbmc/asm_x86_shift_carry/test.desc @@ -0,0 +1,17 @@ +CORE gcc-only +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 32 shlb by 8: FAILURE$ +^\[main\.assertion\.2\] line 33 shlb by 7: SUCCESS$ +^\[main\.assertion\.3\] line 35 shrw by 16: FAILURE$ +^\[main\.assertion\.4\] line 36 sarb by 8: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +The Intel SDM leaves CF undefined for shl and shr by a count of the operand +width or more, which CBMC models as nondeterministic. All four assertions +hold on the Intel Xeon Platinum 8124M that they were run on. diff --git a/src/assembler/asm_x86.cpp b/src/assembler/asm_x86.cpp index a8f62d06fad8..bd81377787bd 100644 --- a/src/assembler/asm_x86.cpp +++ b/src/assembler/asm_x86.cpp @@ -1403,9 +1403,12 @@ bool asm_x86_semanticst::lower_sized( exprt new_carry = carry; if(beyond_possible && base != "rol" && base != "ror") { - // counts larger than the width leave CF undefined + // The Intel SDM leaves CF undefined for shl and shr with counts of the + // width or more; for sar, it is the sign bit, but counts larger than + // the width are modeled as undefined as well. new_carry = if_exprt{ - binary_relation_exprt{count, ID_gt, constant(w, 8)}, + binary_relation_exprt{ + count, base == "sar" ? ID_gt : ID_ge, constant(w, 8)}, ctx.nondet(bool_typet{}), carry}; } From efca15d66de818fc787df2ed4ebe3bfbefa35f2c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:56:08 +0000 Subject: [PATCH 061/100] Document x32 and the modeled x86 carry-flag and out instructions 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 --- doc/cprover-manual/modeling-inline-asm.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index bde6936c3392..a5ab95313ba3 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -11,11 +11,12 @@ Intel syntax and name C variables; CBMC treats them as MSVC-style blocks in all modes. Before verification, the `remove_asm` pass replaces each inline-assembly statement by goto-program instructions: -- On x86 (`--arch i386` or `--arch x86_64`, the default on x86 hosts), a - GCC-style statement is **interpreted** if CBMC's x86 instruction semantics - support all of its instructions (see "x86 Instruction Semantics" below): - it is translated into goto-program instructions with the same effect on the - C program state. +- On x86 (`--arch i386`, `--arch x86_64`, or `--arch x32`, which uses the + x86-64 instructions with 32-bit pointers; the default on x86 hosts is one + of these), a GCC-style statement is **interpreted** if CBMC's x86 + instruction semantics support all of its instructions (see "x86 + Instruction Semantics" below): it is translated into goto-program + instructions with the same effect on the C program state. - Otherwise, if CBMC models every instruction of the statement (see "Supported Instructions" below, on any architecture), the statement is translated into the corresponding fences or calls to library functions, @@ -45,7 +46,8 @@ commonly uses in inline assembly, with AT&T syntax: `xchg`, `bswap`, `cmov`, `set`, sign extensions of the accumulator (`cltq`, `cwtl`, `cltd`, `cqto`, ...); - arithmetic and logic, with the flags they set: `add`, `adc`, `sub`, `sbb`, - `and`, `or`, `xor`, `not`, `neg`, `inc`, `dec`, `cmp`, `test`; + `and`, `or`, `xor`, `not`, `neg`, `inc`, `dec`, `cmp`, `test`, and the + carry flag instructions `clc`, `stc`, and `cmc`; - shifts and rotates (`shl`, `sal`, `shr`, `sar`, `rol`, `ror`), bit tests (`bt`, `bts`, `btr`, `btc`), and bit scans and counts (`bsf`, `bsr`, `tzcnt`, `lzcnt`, `popcnt`); @@ -55,7 +57,7 @@ commonly uses in inline assembly, with AT&T syntax: (`asm goto`), and flag outputs (`=@cc`); - fences (`mfence`, `lfence`, `sfence`), the x87 control word (`fstcw`, `fnstcw`, `fldcw`), and instructions without effect on the C program state - (`nop`, `pause`, `cli`, `sti`, `hlt`, `wrmsr`); `cpuid`, `rdtsc`, + (`nop`, `pause`, `cli`, `sti`, `hlt`, `wrmsr`, `out`); `cpuid`, `rdtsc`, `rdtscp`, `rdmsr`, and `in` produce nondeterministic values. Operands follow GCC's rules: inputs are evaluated before the first From 164f5f1eb57257abd6c9a89ea74525ed45332d6c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:58:25 +0000 Subject: [PATCH 062/100] Unit tests of templates: C labels, local labels, %=, %n, and numbers 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 --- unit/assembler/asm_template.cpp | 91 +++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) diff --git a/unit/assembler/asm_template.cpp b/unit/assembler/asm_template.cpp index 8ff441796c93..eb5f3936839f 100644 --- a/unit/assembler/asm_template.cpp +++ b/unit/assembler/asm_template.cpp @@ -81,6 +81,97 @@ TEST_CASE("split_asm_template", "[core][assembler][asm_template]") REQUIRE_FALSE(error.empty()); } + SECTION("references to C labels") + { + asm_operandst operands; + operands.operands.resize(1); + operands.labels = {"main::1::done"}; + operands.label_names = {"done"}; + + REQUIRE(split_asm_template( + "jz %l1\n\tjmp %l[done]", syntax, &operands, instructions, error)); + REQUIRE(instructions.size() == 2); + for(const auto &instruction : instructions) + { + REQUIRE(instruction.operands.size() == 1); + const asm_tokent &label = instruction.operands[0][0]; + REQUIRE(label.kind == asm_tokent::kindt::C_LABEL); + REQUIRE(label.index == 0); + } + + // labels are numbered after the operands + REQUIRE_FALSE( + split_asm_template("jmp %l0", syntax, &operands, instructions, error)); + } + + SECTION("local labels") + { + REQUIRE(split_asm_template( + "1: jmp 1f\n1: jnz 1b\n0: jmp 0b", syntax, nullptr, instructions, error)); + REQUIRE(instructions.size() == 3); + + REQUIRE(instructions[0].labels == std::vector{"1"}); + const asm_tokent &forward = instructions[0].operands[0][0]; + REQUIRE(forward.kind == asm_tokent::kindt::LOCAL_LABEL); + REQUIRE(forward.text == "1"); + REQUIRE_FALSE(forward.backward); + + const asm_tokent &backward = instructions[1].operands[0][0]; + REQUIRE(backward.kind == asm_tokent::kindt::LOCAL_LABEL); + REQUIRE(backward.text == "1"); + REQUIRE(backward.backward); + + // 0b is a reference to the local label 0, not a binary number + const asm_tokent &zero = instructions[2].operands[0][0]; + REQUIRE(zero.kind == asm_tokent::kindt::LOCAL_LABEL); + REQUIRE(zero.text == "0"); + REQUIRE(zero.backward); + } + + SECTION("%= and modifiers") + { + asm_operandst operands; + operands.operands.resize(2); + + REQUIRE(split_asm_template( + "addl $%n1, %0\n\t.long %=", syntax, &operands, instructions, error)); + REQUIRE(instructions.size() == 2); + + const asm_token_listt &immediate = instructions[0].operands[0]; + REQUIRE(immediate.size() == 2); + REQUIRE(immediate[0].is_punctuation('$')); + REQUIRE(immediate[1].kind == asm_tokent::kindt::OPERAND); + REQUIRE(immediate[1].index == 1); + REQUIRE(immediate[1].modifier == "n"); + + // a number unique to the instance of the statement + REQUIRE(instructions[1].mnemonic == ".long"); + REQUIRE(instructions[1].operands[0][0].kind == asm_tokent::kindt::NUMBER); + } + + SECTION("numbers as GAS reads them") + { + REQUIRE(split_asm_template( + "movl $010, %eax; movl $0x1F, %eax; movl $0b101, %eax; movl $10, %eax", + syntax, + nullptr, + instructions, + error)); + REQUIRE(instructions.size() == 4); + const mp_integer expected[] = {8, 31, 5, 10}; + for(std::size_t i = 0; i < 4; ++i) + { + const asm_token_listt &immediate = instructions[i].operands[0]; + REQUIRE(immediate.size() == 2); + REQUIRE(immediate[1].kind == asm_tokent::kindt::NUMBER); + REQUIRE(immediate[1].number == expected[i]); + } + + // 8 is not an octal digit + REQUIRE_FALSE(split_asm_template( + "movl $08, %eax", syntax, nullptr, instructions, error)); + } + SECTION("basic assembly: % is not special") { REQUIRE( From 4ff7fa4907a3437b7bb9633fc4bab0421b9c1efe Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 21:29:48 +0000 Subject: [PATCH 063/100] Inline assembly: output addresses that depend on the other outputs 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 --- doc/cprover-manual/modeling-inline-asm.md | 4 +++ .../cbmc/asm_x86_output_addresses/main.c | 15 +++++++++++ .../cbmc/asm_x86_output_addresses/test.desc | 16 ++++++++++++ src/assembler/asm_lowering.cpp | 25 +++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 regression/cbmc/asm_x86_output_addresses/main.c create mode 100644 regression/cbmc/asm_x86_output_addresses/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a5ab95313ba3..a6575b68e6e3 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -119,6 +119,10 @@ instructions are listed in the tables below) if it: 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 segment-relative loads produce nondeterministic values; +- has more than one output operand, or a `"memory"` clobber, and a register + output whose address depends on the program state (as `arr[idx]` does): + compilers differ in whether they compute that address before the + statement or after writing the other outputs; - writes a register that is neither bound to an operand nor clobbered: as CBMC does not track register variables (`register long x asm("rax")`), such a write may change a C variable; diff --git a/regression/cbmc/asm_x86_output_addresses/main.c b/regression/cbmc/asm_x86_output_addresses/main.c new file mode 100644 index 000000000000..6a86cb994fa9 --- /dev/null +++ b/regression/cbmc/asm_x86_output_addresses/main.c @@ -0,0 +1,15 @@ +// The address of the output arr[idx] depends on the output idx. GCC at -O0 +// computes it after writing idx (arr[1] = 9), GCC at -O2 and Clang compute it +// before (arr[0] = 9), so both behaviours must be possible. +int main(void) +{ + int idx = 0, arr[2] = {0, 0}; + asm("movl $1, %0; movl $9, %1" : "=&r"(idx), "=r"(arr[idx])); + __CPROVER_assert( + !(idx == 1 && arr[0] == 9 && arr[1] == 0), + "address before writing idx"); // fails + __CPROVER_assert( + !(idx == 1 && arr[0] == 0 && arr[1] == 9), + "address after writing idx"); // fails + return 0; +} diff --git a/regression/cbmc/asm_x86_output_addresses/test.desc b/regression/cbmc/asm_x86_output_addresses/test.desc new file mode 100644 index 000000000000..3621751b39a2 --- /dev/null +++ b/regression/cbmc/asm_x86_output_addresses/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.c +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^approximating inline assembly statement at file main\.c line 7 function main: the address of output operand 1 depends on the program state, and compilers differ in whether they compute it before or after writing the other outputs, so +^\[main\.assertion\.1\] line 8 address before writing idx: FAILURE$ +^\[main\.assertion\.2\] line 11 address after writing idx: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The address of the register output arr[idx] depends on the output idx. GCC +at -O0 computes it after writing idx, GCC at -O2 and Clang before. The +interpretation of x86 instructions used to compute it after writing the +other outputs only, which excluded the behaviour of the other compilers. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 716e73a9838b..60b8d1707776 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -22,6 +22,7 @@ Author: Michael Tautschnig #include #include +#include "asm_approximation.h" #include "asm_semantics.h" #include @@ -853,6 +854,30 @@ bool asm_lowering_contextt::finish(goto_programt &dest) } } + // Register and flag outputs are assigned after the instructions. Compilers + // differ in whether they compute the address of such an output, if that + // depends on the program state (as for `a[i]`), before the statement or + // after writing the other outputs (GCC at -O0 computes it after), so the + // statement is not interpreted if another output or a "memory" clobber may + // change that address. + if(operands.number_of_outputs > 1 || operands.clobbers_memory()) + { + for(std::size_t i = 0; i < operands.number_of_outputs; ++i) + { + const asm_operandt &operand = operands.operands[i]; + if( + (operand.kind == asm_operandt::kindt::REGISTER || + operand.kind == asm_operandt::kindt::FLAG_OUTPUT) && + asm_approximationt::has_state_dependent_address(operand.expr)) + { + return fail( + "the address of output operand " + std::to_string(i) + + " depends on the program state, and compilers differ in whether " + "they compute it before or after writing the other outputs"); + } + } + } + for(std::size_t i = 0; i < operands.operands.size(); ++i) { const asm_operandt &operand = operands.operands[i]; From d6a863f8b90cc5996de49d602db32f891703994d Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Mon, 16 Nov 2026 23:16:22 +0000 Subject: [PATCH 064/100] Inline assembly: interpret AArch64 instructions 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 --- doc/architectural/inline-assembly.md | 12 +- doc/cprover-manual/modeling-inline-asm.md | 44 +- .../asm_aarch64_exclusive/main.c | 35 + .../asm_aarch64_exclusive/test.desc | 14 + regression/cbmc/asm_aarch64/main.c | 497 +++++++ regression/cbmc/asm_aarch64/test.desc | 15 + .../cbmc/asm_aarch64_corner_cases/main.c | 63 + .../cbmc/asm_aarch64_corner_cases/test.desc | 22 + .../cbmc/asm_aarch64_unknown_address/main.c | 63 + .../asm_aarch64_unknown_address/test.desc | 25 + regression/cbmc/inline_asm_hash/arm.desc | 4 +- regression/cbmc/inline_asm_hash/barriers.desc | 2 +- src/assembler/Makefile | 3 +- src/assembler/asm_aarch64.cpp | 1200 +++++++++++++++++ src/assembler/asm_aarch64.h | 21 + src/assembler/asm_arm_flags.h | 133 ++ src/assembler/asm_lowering.cpp | 42 +- src/assembler/asm_semantics.cpp | 3 + src/assembler/asm_semantics.h | 46 +- 19 files changed, 2229 insertions(+), 15 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_aarch64_exclusive/main.c create mode 100644 regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc create mode 100644 regression/cbmc/asm_aarch64/main.c create mode 100644 regression/cbmc/asm_aarch64/test.desc create mode 100644 regression/cbmc/asm_aarch64_corner_cases/main.c create mode 100644 regression/cbmc/asm_aarch64_corner_cases/test.desc create mode 100644 regression/cbmc/asm_aarch64_unknown_address/main.c create mode 100644 regression/cbmc/asm_aarch64_unknown_address/test.desc create mode 100644 src/assembler/asm_aarch64.cpp create mode 100644 src/assembler/asm_aarch64.h create mode 100644 src/assembler/asm_arm_flags.h diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 267076c450d9..9af6caba4087 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -42,7 +42,8 @@ The interpretation of a statement has these parts: block-local temporaries), labels, and helpers to read and write registers and memory, branch, and fence. - `asm_semanticst` is the interface of the per-architecture semantics; - `asm_x86.cpp` implements x86 (i386, x86-64, x32). + `asm_x86.cpp` implements x86 (i386, x86-64, x32), `asm_aarch64.cpp` + implements AArch64; `asm_arm_flags.h` has the ARM condition flags. The code of a statement consists of a prologue that evaluates the inputs, the code of the instructions, and an epilogue that assigns the register outputs. @@ -139,6 +140,15 @@ own, with a full fence; see `asm_lowering_contextt::mark_atomic`. Making the whole statement atomic would hide races on the statement's other instructions. +A load-exclusive followed by a store-exclusive is an atomic section from the +load to the store (`asm_lowering_contextt::begin_exclusive`, `end_exclusive`) +if there is no other memory access, branch, or label in between; otherwise +the statement is not interpreted. The store-exclusive succeeds +nondeterministically: the architecture permits spurious failures, and a +store-exclusive without a load-exclusive in the same statement may succeed if +a load-exclusive executed before. After `clrex` or a store-exclusive, a +store-exclusive fails. + For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the statement; the interpretation assigns it the index of the label that the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a6575b68e6e3..3fbe32741cf9 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -12,10 +12,11 @@ all modes. Before verification, the `remove_asm` pass replaces each inline-assembly statement by goto-program instructions: - On x86 (`--arch i386`, `--arch x86_64`, or `--arch x32`, which uses the - x86-64 instructions with 32-bit pointers; the default on x86 hosts is one - of these), a GCC-style statement is **interpreted** if CBMC's x86 - instruction semantics support all of its instructions (see "x86 - Instruction Semantics" below): it is translated into goto-program + x86-64 instructions with 32-bit pointers) and AArch64 (`--arch arm64`), the + default being the host architecture, a GCC-style statement is + **interpreted** if CBMC's instruction semantics for the architecture + support all of its instructions (see "x86 Instruction Semantics" and + "AArch64 Instruction Semantics" below): it is translated into goto-program instructions with the same effect on the C program state. - Otherwise, if CBMC models every instruction of the statement (see "Supported Instructions" below, on any architecture), the statement is @@ -136,6 +137,41 @@ A lock-prefixed instruction (or `xchg` with a memory operand) is an atomic section with a full fence; the other instructions of the statement are not part of that atomic section. +### AArch64 Instruction Semantics + +The AArch64 semantics cover: + +- data movement and processing on general-purpose registers, with the + condition flags: `mov`, `mvn`, `movz`, `movk`, `movn`, `neg`, `negs`, + `add`, `adds`, `sub`, `subs`, `and`, `ands`, `orr`, `eor`, `bic`, `bics`, + `orn`, `eon`, `lsl`, `lsr`, `asr`, `ror`, `cmp`, `cmn`, `tst`, and the + conditional selects (`csel`, `csinc`, `csinv`, `csneg`, `cset`, `csetm`); +- loads and stores of single registers (including acquire/release + variants), the LSE atomics + (`ldadd`, `ldclr`, `ldeor`, `ldset`, `ldsmax`, `ldsmin`, `ldumax`, + `ldumin`, their `st` forms, `swp`, `cas`), and load-exclusive/ + store-exclusive (`ldxr`, `ldaxr`, `stxr`, `stlxr`, `clrex`); +- branches within the statement and to the labels of `asm goto`, and flag + outputs (`=@cc`); +- barriers (`dmb`, `dsb`, `isb`), `mrs` and `msr` of the flags (`nzcv`), + `msr` of the interrupt masks (`daif`, `daifset`, `daifclr`), and hints + (`nop`, `yield`, `wfe`, ...); `mrs` of other system registers produces a + nondeterministic value, and `msr` of other system registers (such as + `fpcr`, which sets the rounding mode) is not modeled. + +A load-exclusive followed by a store-exclusive in the same statement, with +no other memory access, branch, or label in between, is an atomic section. +The store-exclusive succeeds or fails nondeterministically, as the +architecture permits spurious failures, and so does a store-exclusive +without a preceding load-exclusive in the statement (a load-exclusive may +have executed before). Hence symbolic execution needs an unwinding bound for +the loop that retries the sequence until the store succeeds, and unwinding +assertions for that loop fail. If the retried code has no effect when the +store fails (it only computes registers that the next attempt computes +again), the executions with more retries reach the same states, so that +bounding the loop (with `--unwindset`, without unwinding assertions) does not +miss any state. + ### Supported Instructions CBMC splits the assembler text into instructions at newlines and `;`, except diff --git a/regression/cbmc-concurrency/asm_aarch64_exclusive/main.c b/regression/cbmc-concurrency/asm_aarch64_exclusive/main.c new file mode 100644 index 000000000000..46d347b2b69e --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_exclusive/main.c @@ -0,0 +1,35 @@ +// A load-exclusive/store-exclusive sequence is atomic; plain loads and +// stores are not. +unsigned long x, y, done; + +void t(void) +{ + unsigned long tmp; + unsigned int status; + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " cbnz %w1, 1b" + : "=&r"(tmp), "=&r"(status) + : "r"(&x) + : "memory"); + __asm__ volatile( + "ldr %0, [%1]\n" + " add %0, %0, #1\n" + " str %0, [%1]" + : "=&r"(tmp) + : "r"(&y) + : "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), done = 1; + t(); + __CPROVER_assume(done); + __CPROVER_assert(x == 2, "ll/sc increment"); + __CPROVER_assert(y == 2, "plain increment"); // fails + return 0; +} diff --git a/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc b/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc new file mode 100644 index 000000000000..3935b28ec264 --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc @@ -0,0 +1,14 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 2 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 32 ll/sc increment: SUCCESS$ +^\[main\.assertion\.2\] line 33 plain increment: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +A load-exclusive/store-exclusive sequence is an atomic section; a plain +read-modify-write is not. diff --git a/regression/cbmc/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c new file mode 100644 index 000000000000..432d19b3eea1 --- /dev/null +++ b/regression/cbmc/asm_aarch64/main.c @@ -0,0 +1,497 @@ +// AArch64 inline assembly that is interpreted exactly. The expected values were +// observed with an emulator. + +// aarch64 ldxr/add/stxr set a bit (atomic_set llsc) +void asm_case_0(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int v = (unsigned int)io[1]; + unsigned int tmp = (unsigned int)io[2]; + unsigned int res = (unsigned int)io[3]; + __asm__ __volatile__( + "1: ldxr %w0, [%2]\n" + " orr %w0, %w0, %w3\n" + " stxr %w1, %w0, [%2]\n" + " cbnz %w1, 1b\n" + : "=&r"(tmp), "=&r"(res) + : "r"(&m), "r"(v) + : "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; + io[2] = (unsigned long long)tmp; + io[3] = (unsigned long long)res; +} + +// aarch64 ldadd is an atomic add (LSE) +void asm_case_1(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int v = (unsigned int)io[1]; + unsigned int old = (unsigned int)io[2]; + __asm__ __volatile__("ldadd %w2, %w0, [%1]" + : "=r"(old) + : "r"(&m), "r"(v) + : "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; + io[2] = (unsigned long long)old; +} + +// aarch64 ldset ORs into memory and returns the old value (LSE) +void asm_case_2(unsigned long long *io) +{ + unsigned long m = (unsigned long)io[0]; + unsigned long v = (unsigned long)io[1]; + unsigned long old = (unsigned long)io[2]; + __asm__ __volatile__("ldset %2, %0, [%1]" + : "=r"(old) + : "r"(&m), "r"(v) + : "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; + io[2] = (unsigned long long)old; +} + +// aarch64 swp exchanges a register and memory (LSE) +void asm_case_3(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int v = (unsigned int)io[1]; + unsigned int old = (unsigned int)io[2]; + __asm__ __volatile__("swp %w2, %w0, [%1]" + : "=r"(old) + : "r"(&m), "r"(v) + : "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; + io[2] = (unsigned long long)old; +} + +// aarch64 cas compares and swaps (LSE) +void asm_case_4(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int cmp = (unsigned int)io[1]; + unsigned int newv = (unsigned int)io[2]; + __asm__ __volatile__("cas %w0, %w2, [%1]" + : "+r"(cmp) + : "r"(&m), "r"(newv) + : "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)cmp; + io[2] = (unsigned long long)newv; +} + +// aarch64 add then subtract +void asm_case_5(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long a = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + unsigned long c = (unsigned long)io[3]; + __asm__("add %0, %1, %2\n sub %0, %0, %3" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; +} + +// aarch64 and with a shifted register +void asm_case_6(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long a = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + __asm__("and %0, %1, %2, lsl #4" : "=r"(r) : "r"(a), "r"(b)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + +// aarch64 cmp and cset compute a predicate +void asm_case_7(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long a = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + __asm__("cmp %1, %2\n cset %0, hi" : "=r"(r) : "r"(a), "r"(b) : "cc"); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + +// aarch64 ldr and str move a word through memory +void asm_case_8(unsigned long long *io) +{ + unsigned int a = (unsigned int)io[0]; + unsigned int b = (unsigned int)io[1]; + unsigned int t = (unsigned int)io[2]; + __asm__ __volatile__("ldr %w0, [%1]\n str %w0, [%2]" + : "=&r"(t) + : "r"(&a), "r"(&b) + : "memory"); + io[0] = (unsigned long long)a; + io[1] = (unsigned long long)b; + io[2] = (unsigned long long)t; +} + +// aarch64 eor and orr combine bits +void asm_case_9(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long a = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + unsigned long c = (unsigned long)io[3]; + __asm__("eor %0, %1, %2\n orr %0, %0, %3" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; +} + +// aarch64 lsl and lsr shift +void asm_case_10(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + unsigned long a = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + unsigned long c = (unsigned long)io[3]; + __asm__("lsl %0, %1, %2\n lsr %0, %0, %3" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; +} + +// aarch64 movz/movk build a constant +void asm_case_11(unsigned long long *io) +{ + unsigned long r = (unsigned long)io[0]; + __asm__("movz %0, #0x1234\n movk %0, #0xabcd, lsl #16" : "=r"(r)); + io[0] = (unsigned long long)r; +} + +int main(void) +{ + { + unsigned long long io[4] = { + 0xc2a7af9eab79b005ULL, 0xffULL, 0x2ULL, 0x6ffe6666fa72766dULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0xab79b0ffULL && io[1] == 0xffULL && io[2] == 0xab79b0ffULL && + io[3] == 0x0ULL, + "aarch64 ldxr/add/stxr set a bit (atomic_set llsc), vector 0"); + } + { + unsigned long long io[4] = { + 0x8000000000000000ULL, + 0x8000000000000000ULL, + 0xae54d49633f89bafULL, + 0xcc5604a33a481fd2ULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x0ULL && io[2] == 0x0ULL && io[3] == 0x0ULL, + "aarch64 ldxr/add/stxr set a bit (atomic_set llsc), vector 1"); + } + { + unsigned long long io[4] = { + 0xadb4bded0a6cc878ULL, + 0x248a141c7ccb3b72ULL, + 0xb5d23309b6d2590dULL, + 0x33756584e354bbe7ULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x7eeffb7aULL && io[1] == 0x7ccb3b72ULL && + io[2] == 0x7eeffb7aULL && io[3] == 0x0ULL, + "aarch64 ldxr/add/stxr set a bit (atomic_set llsc), vector 2"); + } + { + unsigned long long io[3] = { + 0xc2b9546e0f0220f3ULL, 0xf1d5effedcda26fbULL, 0x7fffffffULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xebdc47eeULL && io[1] == 0xdcda26fbULL && io[2] == 0xf0220f3ULL, + "aarch64 ldadd is an atomic add (LSE), vector 0"); + } + { + unsigned long long io[3] = { + 0xb8d3af23681c2889ULL, 0xc60f8fe0a6269527ULL, 0x32f6ffa49275dc84ULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xe42bdb0ULL && io[1] == 0xa6269527ULL && io[2] == 0x681c2889ULL, + "aarch64 ldadd is an atomic add (LSE), vector 1"); + } + { + unsigned long long io[3] = { + 0x7d7ef810cfc3dc1ULL, 0xbf30555ab55f5d1fULL, 0xb3d8c88ab7063e8dULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xc25b9ae0ULL && io[1] == 0xb55f5d1fULL && io[2] == 0xcfc3dc1ULL, + "aarch64 ldadd is an atomic add (LSE), vector 2"); + } + { + unsigned long long io[3] = {0xe638bca46bd70d89ULL, 0x2ULL, 0x2ULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0xe638bca46bd70d8bULL && io[1] == 0x2ULL && + io[2] == 0xe638bca46bd70d89ULL, + "aarch64 ldset ORs into memory and returns the old value (LSE), vector " + "0"); + } + { + unsigned long long io[3] = { + 0x17d967b89f01d73dULL, 0x82974e236f761b03ULL, 0x7fULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x97df6fbbff77df3fULL && io[1] == 0x82974e236f761b03ULL && + io[2] == 0x17d967b89f01d73dULL, + "aarch64 ldset ORs into memory and returns the old value (LSE), vector " + "1"); + } + { + unsigned long long io[3] = { + 0x6bcc7b9e0a546c01ULL, 0xffffffffULL, 0x9541937ec1bfc7abULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x6bcc7b9effffffffULL && io[1] == 0xffffffffULL && + io[2] == 0x6bcc7b9e0a546c01ULL, + "aarch64 ldset ORs into memory and returns the old value (LSE), vector " + "2"); + } + { + unsigned long long io[3] = { + 0x38b1f9a35c2855baULL, 0x8a0cb201725c5338ULL, 0xb0652c5806a310a8ULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0x725c5338ULL && io[1] == 0x725c5338ULL && + io[2] == 0x5c2855baULL, + "aarch64 swp exchanges a register and memory (LSE), vector 0"); + } + { + unsigned long long io[3] = { + 0x808332e379bd40dbULL, 0xe586f6e1167ff12eULL, 0xffULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0x167ff12eULL && io[1] == 0x167ff12eULL && + io[2] == 0x79bd40dbULL, + "aarch64 swp exchanges a register and memory (LSE), vector 1"); + } + { + unsigned long long io[3] = { + 0xb7a413d48183cf4eULL, 0x872808db18a381eULL, 0x89c40189aec7d882ULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0xb18a381eULL && io[1] == 0xb18a381eULL && + io[2] == 0x8183cf4eULL, + "aarch64 swp exchanges a register and memory (LSE), vector 2"); + } + { + unsigned long long io[3] = {0x5ULL, 0x5ULL, 0x9ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x9ULL && io[1] == 0x5ULL && io[2] == 0x9ULL, + "aarch64 cas compares and swaps (LSE), vector 0"); + } + { + unsigned long long io[3] = {0x5ULL, 0x7ULL, 0x9ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x5ULL && io[1] == 0x5ULL && io[2] == 0x9ULL, + "aarch64 cas compares and swaps (LSE), vector 1"); + } + { + unsigned long long io[3] = {0x0ULL, 0x0ULL, 0x1ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x0ULL && io[2] == 0x1ULL, + "aarch64 cas compares and swaps (LSE), vector 2"); + } + { + unsigned long long io[3] = {0xdeadbeefULL, 0xdeadbeefULL, 0x1ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0xdeadbeefULL && io[2] == 0x1ULL, + "aarch64 cas compares and swaps (LSE), vector 3"); + } + { + unsigned long long io[4] = { + 0x662e0001e6f57713ULL, + 0xf1657729e04a52fdULL, + 0x4ce92b19fe991d62ULL, + 0x2dca9d6ea967229bULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0x108404d5357c4dc4ULL && io[1] == 0xf1657729e04a52fdULL && + io[2] == 0x4ce92b19fe991d62ULL && io[3] == 0x2dca9d6ea967229bULL, + "aarch64 add then subtract, vector 0"); + } + { + unsigned long long io[4] = { + 0xe4a66e6e92989e7dULL, + 0x350b8f5dcea6fb83ULL, + 0xabc0ff65a92da05dULL, + 0x4c075f1f0b493f1aULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0x94c52fa46c8b5cc6ULL && io[1] == 0x350b8f5dcea6fb83ULL && + io[2] == 0xabc0ff65a92da05dULL && io[3] == 0x4c075f1f0b493f1aULL, + "aarch64 add then subtract, vector 1"); + } + { + unsigned long long io[4] = { + 0x7d9cf46457162242ULL, 0x7fULL, 0x8000000000000000ULL, 0x80000000ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0x7fffffff8000007fULL && io[1] == 0x7fULL && + io[2] == 0x8000000000000000ULL && io[3] == 0x80000000ULL, + "aarch64 add then subtract, vector 2"); + } + { + unsigned long long io[3] = { + 0x71985eb13a883919ULL, 0x7fffffffffffffffULL, 0xc42192ad002d93dcULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x42192ad002d93dc0ULL && io[1] == 0x7fffffffffffffffULL && + io[2] == 0xc42192ad002d93dcULL, + "aarch64 and with a shifted register, vector 0"); + } + { + unsigned long long io[3] = { + 0xffffffffULL, 0x4f18c672fa42fe7cULL, 0x120984629605b44fULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x18462060424470ULL && io[1] == 0x4f18c672fa42fe7cULL && + io[2] == 0x120984629605b44fULL, + "aarch64 and with a shifted register, vector 1"); + } + { + unsigned long long io[3] = { + 0x4eb832d5079a2474ULL, 0x0ULL, 0xfd64b9e5bd0edb5aULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x0ULL && io[2] == 0xfd64b9e5bd0edb5aULL, + "aarch64 and with a shifted register, vector 2"); + } + { + unsigned long long io[3] = { + 0xd6bc0d35ccec83e4ULL, 0x4fb0d79be3130b3fULL, 0x2d65a8a1cf4ce48eULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x4fb0d79be3130b3fULL && + io[2] == 0x2d65a8a1cf4ce48eULL, + "aarch64 cmp and cset compute a predicate, vector 0"); + } + { + unsigned long long io[3] = { + 0x0ULL, 0xdae98f58edaf5ddULL, 0xbb5f3ec2488a958cULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0xdae98f58edaf5ddULL && + io[2] == 0xbb5f3ec2488a958cULL, + "aarch64 cmp and cset compute a predicate, vector 1"); + } + { + unsigned long long io[3] = { + 0x8bcb7f1085e0c86ULL, 0x3dc7152f30428c31ULL, 0x12257820e6b755cfULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x3dc7152f30428c31ULL && + io[2] == 0x12257820e6b755cfULL, + "aarch64 cmp and cset compute a predicate, vector 2"); + } + { + unsigned long long io[3] = { + 0x71f2223ff559a0f9ULL, 0xc447a6fbb54b9c52ULL, 0xf34de6440ce23540ULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0xf559a0f9ULL && io[1] == 0xf559a0f9ULL && + io[2] == 0xf559a0f9ULL, + "aarch64 ldr and str move a word through memory, vector 0"); + } + { + unsigned long long io[3] = { + 0x2444fb01d3bdc021ULL, 0xfc66ce02975f8fb3ULL, 0xffULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0xd3bdc021ULL && io[1] == 0xd3bdc021ULL && + io[2] == 0xd3bdc021ULL, + "aarch64 ldr and str move a word through memory, vector 1"); + } + { + unsigned long long io[3] = { + 0xca7d4a778a0b60a5ULL, 0x38e3ee6142044392ULL, 0xa67f5e58956140eULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x8a0b60a5ULL && io[1] == 0x8a0b60a5ULL && + io[2] == 0x8a0b60a5ULL, + "aarch64 ldr and str move a word through memory, vector 2"); + } + { + unsigned long long io[4] = { + 0x80000000ULL, 0x85c6eecdbd37c64dULL, 0xe051fbafdcfbbb5eULL, 0x7fULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x6597156261cc7d7fULL && io[1] == 0x85c6eecdbd37c64dULL && + io[2] == 0xe051fbafdcfbbb5eULL && io[3] == 0x7fULL, + "aarch64 eor and orr combine bits, vector 0"); + } + { + unsigned long long io[4] = { + 0x1ULL, 0x7fULL, 0x7e0269edac79ca6eULL, 0xffffffffffffffffULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0xffffffffffffffffULL && io[1] == 0x7fULL && + io[2] == 0x7e0269edac79ca6eULL && io[3] == 0xffffffffffffffffULL, + "aarch64 eor and orr combine bits, vector 1"); + } + { + unsigned long long io[4] = { + 0xffULL, + 0xfc5d96cc82bdb472ULL, + 0x7fffffffffffffffULL, + 0x2355aca2a0edf46dULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0xa3f7edb3fdefffedULL && io[1] == 0xfc5d96cc82bdb472ULL && + io[2] == 0x7fffffffffffffffULL && io[3] == 0x2355aca2a0edf46dULL, + "aarch64 eor and orr combine bits, vector 2"); + } + { + unsigned long long io[4] = {0xd29b8652db47179aULL, 0x1ULL, 0x3ULL, 0x3fULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x1ULL && io[2] == 0x3ULL && io[3] == 0x3fULL, + "aarch64 lsl and lsr shift, vector 0"); + } + { + unsigned long long io[4] = { + 0xd57e59721b5c3f00ULL, 0x8161ebbba4c1b5daULL, 0x1aULL, 0x24ULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0xee9306dULL && io[1] == 0x8161ebbba4c1b5daULL && + io[2] == 0x1aULL && io[3] == 0x24ULL, + "aarch64 lsl and lsr shift, vector 1"); + } + { + unsigned long long io[4] = { + 0x5e4c1de7ba5f33e2ULL, 0x870cf5c903adeee9ULL, 0x2dULL, 0x3eULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0x2ULL && io[1] == 0x870cf5c903adeee9ULL && io[2] == 0x2dULL && + io[3] == 0x3eULL, + "aarch64 lsl and lsr shift, vector 2"); + } + { + unsigned long long io[1] = {0x6a08e48807e06ce6ULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0xabcd1234ULL, "aarch64 movz/movk build a constant, vector 0"); + } + return 0; +} diff --git a/regression/cbmc/asm_aarch64/test.desc b/regression/cbmc/asm_aarch64/test.desc new file mode 100644 index 000000000000..86f8be6dbc81 --- /dev/null +++ b/regression/cbmc/asm_aarch64/test.desc @@ -0,0 +1,15 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 2 --no-unwinding-assertions +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +The AArch64 inline assembly in main.c is interpreted exactly: if CBMC +approximated any statement, the assertions, which check values observed with +an emulator, would fail. A store-exclusive may fail spuriously, so the retry +loops of load-exclusive/store-exclusive sequences are bounded; the executions +that retry more often reach the same states. diff --git a/regression/cbmc/asm_aarch64_corner_cases/main.c b/regression/cbmc/asm_aarch64_corner_cases/main.c new file mode 100644 index 000000000000..82c1755f7bf2 --- /dev/null +++ b/regression/cbmc/asm_aarch64_corner_cases/main.c @@ -0,0 +1,63 @@ +// Corner cases of the AArch64 instruction semantics. "fails" marks +// properties that the architecture permits to be violated, so CBMC must not +// prove them. +static unsigned long add_ll_sc(unsigned long *p, unsigned long v) +{ + unsigned long result; + unsigned int status; + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, %3\n" + " stxr %w1, %0, [%2]\n" + " cbnz %w1, 1b" + : "=&r"(result), "=&r"(status) + : "r"(p), "r"(v) + : "memory"); + return result; +} + +int main(void) +{ + // msr nzcv writes the flags, mrs nzcv reads them + unsigned long a = 0, r; + __asm__ volatile("cmp %1, %1\n msr nzcv, xzr\n cset %w0, eq" + : "=r"(r) + : "r"(a) + : "cc"); + __CPROVER_assert(r == 0, "msr nzcv clears Z"); + unsigned long flags; + __asm__ volatile("cmp %1, %1\n mrs %0, nzcv" : "=r"(flags) : "r"(a) : "cc"); + __CPROVER_assert(flags == 0x60000000ul, "mrs nzcv after equality"); + + // a load-exclusive/store-exclusive loop retries until the store succeeds + unsigned long counter = 40; + __CPROVER_assert(add_ll_sc(&counter, 2) == 42, "ll/sc result"); + __CPROVER_assert(counter == 42, "ll/sc stored"); + + // a store-exclusive without a load-exclusive in the statement may succeed + // (if a load-exclusive executed before) or fail + unsigned long m = 1, v = 42; + unsigned int res; + __asm__ volatile("stxr %w0, %2, [%1]" + : "=&r"(res) + : "r"(&m), "r"(v) + : "memory"); + __CPROVER_assert(m == 42, "store-exclusive stores"); // fails + __CPROVER_assert(m == 1, "store-exclusive fails"); // fails + __CPROVER_assert((res == 0) == (m == 42), "status matches the store"); + + // after clrex, a store-exclusive fails + m = 1; + __asm__ volatile("clrex\n stxr %w0, %2, [%1]" + : "=&r"(res) + : "r"(&m), "r"(v) + : "memory"); + __CPROVER_assert(m == 1 && res == 1, "store-exclusive after clrex"); + + // a register variable bound to a register that the template writes + register unsigned long x0 __asm__("x0") = 5; + __asm__ volatile("add x0, x0, #1" : "+r"(x0)); + __CPROVER_assert(x0 == 5, "register variable"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_corner_cases/test.desc b/regression/cbmc/asm_aarch64_corner_cases/test.desc new file mode 100644 index 000000000000..9d7a25ac97b7 --- /dev/null +++ b/regression/cbmc/asm_aarch64_corner_cases/test.desc @@ -0,0 +1,22 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 3 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 27 msr nzcv clears Z: SUCCESS$ +^\[main\.assertion\.2\] line 30 mrs nzcv after equality: SUCCESS$ +^\[main\.assertion\.3\] line 34 ll/sc result: SUCCESS$ +^\[main\.assertion\.4\] line 35 ll/sc stored: SUCCESS$ +^\[main\.assertion\.5\] line 45 store-exclusive stores: FAILURE$ +^\[main\.assertion\.6\] line 46 store-exclusive fails: FAILURE$ +^\[main\.assertion\.7\] line 47 status matches the store: SUCCESS$ +^\[main\.assertion\.8\] line 55 store-exclusive after clrex: SUCCESS$ +^\[main\.assertion\.9\] line 60 register variable: FAILURE$ +approximating inline assembly statement at .* line 59 function main: writes register x0, which is neither an operand nor clobbered +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function add_ll_sc +-- +The properties marked "fails" in main.c may be violated on hardware; all +others hold on hardware. diff --git a/regression/cbmc/asm_aarch64_unknown_address/main.c b/regression/cbmc/asm_aarch64_unknown_address/main.c new file mode 100644 index 000000000000..5aff28dc3e50 --- /dev/null +++ b/regression/cbmc/asm_aarch64_unknown_address/main.c @@ -0,0 +1,63 @@ +int x, y; + +int main(void) +{ + int *px = &x; + unsigned long c, slot; + + // x1 holds the register variable p, but the statement does not + // initialise it: the store is approximated + x = 0; + { + register int *p __asm__("x1") = &x; + __asm__ volatile("str %w0, [x1]" : : "r"(5), "r"(p) : "memory"); + } + __CPROVER_assert(x == 0, "store via register variable"); + + // x1 initialised from an operand before the store: interpreted + x = 0; + __asm__ volatile("mov x1, %0\n str %w1, [x1]" + : + : "r"(px), "r"(5) + : "x1", "memory"); + __CPROVER_assert(x == 5, "store via initialised register"); + + // a forward branch skips the initialisation + x = 0; + __asm__ volatile("cbz %2, 1f\n mov x1, %0\n1: str %w1, [x1]" + : + : "r"(px), "r"(5), "r"(c) + : "x1", "memory"); + __CPROVER_assert(x == 0, "initialisation skipped by forward branch"); + + // a backward branch makes x1 unknown at the store + x = 0; + __asm__ volatile( + "mov x1, %0\n1: str %w1, [x1]\n mrs x1, tpidr_el0\n cbnz %2, 1b" + : + : "r"(px), "r"(5), "r"(c) + : "x1", "memory"); + __CPROVER_assert(x == 0, "register made unknown by backward branch"); + + // an unknown value stored to memory and loaded as an address + x = 0; + __asm__ volatile( + "mrs x1, tpidr_el0\n str x1, [%0]\n ldr x2, [%0]\n str %w1, [x2]" + : + : "r"(&slot), "r"(5) + : "x1", "x2", "memory"); + __CPROVER_assert(x == 0, "unknown address loaded from memory"); + + // a loop with known values only: interpreted + y = 0; + __asm__ volatile( + "mov x1, %0\n mov x3, #3\n" + "1: ldr w2, [x1]\n add w2, w2, #1\n str w2, [x1]\n" + " subs x3, x3, #1\n b.ne 1b" + : + : "r"(&y) + : "x1", "x2", "x3", "cc", "memory"); + __CPROVER_assert(y == 3, "loop with known addresses"); + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_unknown_address/test.desc b/regression/cbmc/asm_aarch64_unknown_address/test.desc new file mode 100644 index 000000000000..de5d1cfabe7d --- /dev/null +++ b/regression/cbmc/asm_aarch64_unknown_address/test.desc @@ -0,0 +1,25 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 4 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 15 store via register variable: FAILURE$ +^\[main\.assertion\.2\] line 23 store via initialised register: SUCCESS$ +^\[main\.assertion\.3\] line 31 initialisation skipped by forward branch: FAILURE$ +^\[main\.assertion\.4\] line 40 register made unknown by backward branch: FAILURE$ +^\[main\.assertion\.5\] line 49 unknown address loaded from memory: FAILURE$ +^\[main\.assertion\.6\] line 60 loop with known addresses: SUCCESS$ +approximating inline assembly statement at .* line 13 function main: memory access at an address computed from a value that is not modeled +approximating inline assembly statement at .* line 27 function main: memory access at an address computed from a value that is not modeled +approximating inline assembly statement at .* line 35 function main: branch with values that are not modeled to code that relies on them +approximating inline assembly statement at .* line 44 function main: memory access at an address computed from a value that is not modeled +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (19|53|54) function main +-- +A memory access at an address that may depend on a value CBMC does not model +(here: registers the statement does not initialise, or a system register read +by mrs) would change no object, as CBMC cannot relate such an address to an +object. Such statements are approximated. The assertions that fail may be violated +on hardware (x or y is then changed); the others hold on hardware. diff --git a/regression/cbmc/inline_asm_hash/arm.desc b/regression/cbmc/inline_asm_hash/arm.desc index b6b7dc970877..58ca477e1929 100644 --- a/regression/cbmc/inline_asm_hash/arm.desc +++ b/regression/cbmc/inline_asm_hash/arm.desc @@ -3,8 +3,8 @@ comments.i --arch arm64 --show-goto-functions ^EXIT=0$ ^SIGNAL=0$ -^approximating inline assembly statement at file comments\.i line 3 function main: instruction 'mfence' is not modeled -^approximating inline assembly statement at file comments\.i line 4 function main: instruction 'sync' is not modeled +^approximating inline assembly statement at file comments\.i line 3 function main: unsupported immediate in 'mfence # x86 comment' +^approximating inline assembly statement at file comments\.i line 4 function main: unsupported immediate in 'sync # Power comment' -- ^warning: ignoring ^ *CALL __asm_mfence\(\)$ diff --git a/regression/cbmc/inline_asm_hash/barriers.desc b/regression/cbmc/inline_asm_hash/barriers.desc index 700b7f4b528d..e5772b4b3666 100644 --- a/regression/cbmc/inline_asm_hash/barriers.desc +++ b/regression/cbmc/inline_asm_hash/barriers.desc @@ -7,7 +7,7 @@ barriers.i ^ *FENCE WW$ ^ *FENCE WW RR RW WR$ ^ *FENCE$ -^approximating inline assembly statement at file barriers\.i line 8 function main: instruction 'dmb' is not modeled +^approximating inline assembly statement at file barriers\.i line 8 function main: unsupported option of dmb in 'dmb #0x0' -- ^warning: ignoring ^approximating inline assembly statement at file barriers\.i line [4-7] function diff --git a/src/assembler/Makefile b/src/assembler/Makefile index d0424c455356..ec183d1edd47 100644 --- a/src/assembler/Makefile +++ b/src/assembler/Makefile @@ -1,4 +1,5 @@ -SRC = asm_approximation.cpp \ +SRC = asm_aarch64.cpp \ + asm_approximation.cpp \ asm_lowering.cpp \ asm_operands.cpp \ asm_semantics.cpp \ diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp new file mode 100644 index 000000000000..f243bd6d29d8 --- /dev/null +++ b/src/assembler/asm_aarch64.cpp @@ -0,0 +1,1200 @@ +/*******************************************************************\ + +Module: Inline assembly: AArch64 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for AArch64 (A64 instruction set, GNU syntax) + +#include "asm_aarch64.h" + +#include +#include +#include +#include +#include + +#include "asm_arm_flags.h" +#include "asm_bv_util.h" +#include "asm_semantics.h" + +#include +#include +#include +#include + +using asm_bv::bool_to_bv; +using asm_bv::borrow_sub; +using asm_bv::bv; +using asm_bv::carry_add; +using asm_bv::constant; +using asm_bv::even_parity_low_byte; +using asm_bv::extract; +using asm_bv::is_zero; +using asm_bv::msb; +using asm_bv::overflow_add; +using asm_bv::overflow_sub; +using asm_bv::replace_bits; +using asm_bv::resize; +using asm_bv::sign_extend; + +namespace +{ +struct a64_operandt +{ + enum class kindt + { + REGISTER, + IMMEDIATE, + MEMORY, + /// a condition (eq, ne, ...) or other name, in `name` + NAME + }; + + kindt kind = kindt::REGISTER; + + // REGISTER: storage (64 bits) and the width of the access + exprt storage; + std::size_t width = 64; + /// xzr/wzr: reads zero, writes are discarded + bool zero_register = false; + + // IMMEDIATE + exprt value; + + // MEMORY: the address + exprt address; + /// for memory operands bound to a C lvalue: that lvalue and its width + exprt lvalue; + std::size_t natural_width = 0; + + // NAME + std::string name; +}; + +class asm_aarch64_semanticst : public asm_semanticst +{ +public: + asm_aarch64_semanticst() + { + syntax_conventions.line_comments = {"//"}; + syntax_conventions.separators = ";"; + } + + std::string name() const override + { + return "AArch64"; + } + + const asm_syntaxt &syntax() const override + { + return syntax_conventions; + } + + std::size_t register_width() const override + { + return 64; + } + + bool reference_widens(const std::string &modifier, std::size_t natural_width) + const override + { + const std::size_t read = modifier == "w" ? 32 : 64; + return read > natural_width; + } + + constraint_classt classify_constraint( + const std::string &constraint, + std::size_t &pos, + std::string &) const override + { + switch(constraint[pos]) + { + case 'Q': + return constraint_classt::MEMORY; + case 'U': + // Ump, Utf and the like: memory operands for pair accesses + if(pos + 2 < constraint.size()) + { + pos += 2; + return constraint_classt::MEMORY; + } + return constraint_classt::UNKNOWN; + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'Z': + return constraint_classt::IMMEDIATE; + default: + // w, x, y: FP/SIMD registers are not modelled + return constraint_classt::UNKNOWN; + } + } + + bool is_flag_output_condition(const std::string &condition) const override + { + return asm_arm::condition_codes().count(condition) != 0 && + condition != "al"; + } + + exprt + condition(const std::string &cc, asm_lowering_contextt &ctx) const override + { + return asm_arm::condition(cc, ctx); + } + + bool lower(const asm_instructiont &instruction, asm_lowering_contextt &ctx) + const override; + +protected: + asm_syntaxt syntax_conventions; + + bool parse_register_name( + const std::string &name, + asm_lowering_contextt &ctx, + a64_operandt &operand) const; + + bool parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + a64_operandt &operand) const; + + bool parse_immediate_tokens( + const asm_token_listt &tokens, + std::size_t pos, + asm_lowering_contextt &ctx, + exprt &value) const; + + exprt read( + asm_lowering_contextt &ctx, + const a64_operandt &operand, + std::size_t width) const; + + bool write( + asm_lowering_contextt &ctx, + const a64_operandt &operand, + std::size_t width, + const exprt &value) const; + + bool lower_memory( + const std::string &m, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; + + bool lower_barrier( + const std::string &m, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; + +public: + std::string canonical_register(const std::string &name) const override; +}; + +std::string +asm_aarch64_semanticst::canonical_register(const std::string &raw) const +{ + std::string name = raw; + for(auto &c : name) + c = static_cast(std::tolower(static_cast(c))); + + if(name == "sp" || name == "wsp") + return "sp"; + if(name == "lr") + return "x30"; + if(name == "fp") + return "x29"; + if(name.size() >= 2 && name.size() <= 3 && (name[0] == 'x' || name[0] == 'w')) + { + const std::string digits = name.substr(1); + if(std::all_of( + digits.begin(), + digits.end(), + [](char c) { return std::isdigit(static_cast(c)); })) + { + const int n = std::stoi(digits); + if(n <= 30) + return "x" + std::to_string(n); + } + } + return {}; +} + +bool asm_aarch64_semanticst::lower_barrier( + const std::string &m, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + std::string option = "sy"; + if(!instruction.operands.empty()) + { + if( + instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || + !instruction.operands[0][0].is_identifier()) + { + return ctx.fail("unsupported option of " + m); + } + option = instruction.operands[0][0].text; + for(auto &c : option) + c = static_cast(std::tolower(static_cast(c))); + } + + if(m == "isb") + { + if(option != "sy") + return ctx.fail("unsupported option of isb"); + // orders nothing by itself, needs to be combined with a branch + ctx.fence(false, false, false, false, false); + return true; + } + + // the option selects the accesses being ordered + if(option == "sy" || option == "ish" || option == "osh" || option == "nsh") + ctx.fence(true, true, true, true, true); + else if(has_suffix(option, "ld")) // loads before loads and stores + ctx.fence(false, true, true, false, true); + else if(has_suffix(option, "st")) // stores before stores + ctx.fence(true, false, false, false, true); + else + return ctx.fail("unsupported option of " + m); + return true; +} + +bool asm_aarch64_semanticst::parse_register_name( + const std::string &raw, + asm_lowering_contextt &ctx, + a64_operandt &operand) const +{ + std::string name = raw; + for(auto &c : name) + c = static_cast(std::tolower(static_cast(c))); + + operand.kind = a64_operandt::kindt::REGISTER; + + if(name == "xzr" || name == "wzr") + { + operand.zero_register = true; + operand.width = name[0] == 'x' ? 64 : 32; + return true; + } + + if(name == "sp" || name == "wsp") + { + operand.storage = ctx.hardware_register("sp"); + operand.width = name == "sp" ? 64 : 32; + return true; + } + + if(name == "lr") + name = "x30"; + else if(name == "fp") + name = "x29"; + + if(name.size() >= 2 && (name[0] == 'x' || name[0] == 'w')) + { + const std::string digits = name.substr(1); + if( + !digits.empty() && digits.size() <= 2 && + std::all_of( + digits.begin(), + digits.end(), + [](char c) { return std::isdigit(static_cast(c)); })) + { + const int n = std::stoi(digits); + if(n <= 30) + { + operand.storage = ctx.hardware_register("x" + std::to_string(n)); + operand.width = name[0] == 'x' ? 64 : 32; + return true; + } + } + } + + return false; +} + +bool asm_aarch64_semanticst::parse_immediate_tokens( + const asm_token_listt &tokens, + std::size_t pos, + asm_lowering_contextt &ctx, + exprt &value) const +{ + bool negative = false; + if(pos < tokens.size() && tokens[pos].is_punctuation('-')) + { + negative = true; + ++pos; + } + + if(pos + 1 != tokens.size()) + return ctx.fail("unsupported immediate"); + + const asm_tokent &token = tokens[pos]; + if(token.kind == asm_tokent::kindt::NUMBER) + { + value = + from_integer(negative ? -token.number : token.number, integer_typet{}); + return true; + } + + if(token.kind == asm_tokent::kindt::OPERAND) + { + const asm_operandt &bound = ctx.operands.operands.at(token.index); + if(bound.kind == asm_operandt::kindt::IMMEDIATE) + value = ctx.operand_immediate(token.index); + else + return ctx.fail( + "operand %" + std::to_string(token.index) + " is not an immediate"); + if(negative) + value = unary_minus_exprt{value}; + return true; + } + + return ctx.fail("unsupported immediate"); +} + +bool asm_aarch64_semanticst::parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + a64_operandt &operand) const +{ + if(tokens.empty()) + return ctx.fail("empty operand"); + + const asm_tokent &first = tokens[0]; + + // immediate + if(first.is_punctuation('#')) + { + operand.kind = a64_operandt::kindt::IMMEDIATE; + return parse_immediate_tokens(tokens, 1, ctx, operand.value); + } + + if(first.kind == asm_tokent::kindt::NUMBER || first.is_punctuation('-')) + { + operand.kind = a64_operandt::kindt::IMMEDIATE; + return parse_immediate_tokens(tokens, 0, ctx, operand.value); + } + + // memory: [base] or [base, #offset] + if(first.is_punctuation('[')) + { + if(!tokens.back().is_punctuation(']')) + return ctx.fail("unsupported addressing mode (writeback?)"); + + std::vector parts{{}}; + for(std::size_t i = 1; i + 1 < tokens.size(); ++i) + { + if(tokens[i].is_punctuation(',')) + parts.emplace_back(); + else + parts.back().push_back(tokens[i]); + } + + a64_operandt base; + if( + !parse_operand(parts[0], ctx, base) || + base.kind != a64_operandt::kindt::REGISTER || base.width != 64) + { + return ctx.fail("unsupported base register"); + } + + exprt address = typecast_exprt{ + resize(read(ctx, base, 64), config.ansi_c.pointer_width), + pointer_type(char_type())}; + + if(parts.size() == 2) + { + a64_operandt offset; + if( + !parse_operand(parts[1], ctx, offset) || + offset.kind != a64_operandt::kindt::IMMEDIATE) + { + return ctx.fail("unsupported offset"); + } + address = plus_exprt{ + address, + typecast_exprt::conditional_cast( + offset.value, signedbv_typet{config.ansi_c.pointer_width})}; + } + else if(parts.size() > 2) + return ctx.fail("unsupported addressing mode"); + + operand.kind = a64_operandt::kindt::MEMORY; + operand.address = address; + return true; + } + + if(tokens.size() == 1 && first.kind == asm_tokent::kindt::OPERAND) + { + const asm_operandt &bound = ctx.operands.operands.at(first.index); + switch(bound.kind) + { + case asm_operandt::kindt::REGISTER: + operand.kind = a64_operandt::kindt::REGISTER; + operand.storage = ctx.operand_storage(first.index); + if(first.modifier.empty() || first.modifier == "x") + operand.width = 64; + else if(first.modifier == "w") + operand.width = 32; + else + return ctx.fail("unsupported operand modifier %" + first.modifier); + return true; + + case asm_operandt::kindt::MEMORY: + if(!first.modifier.empty()) + return ctx.fail("unsupported operand modifier %" + first.modifier); + operand.kind = a64_operandt::kindt::MEMORY; + operand.address = ctx.operand_address(first.index); + operand.lvalue = dereference_exprt{ctx.operand_address(first.index)}; + operand.natural_width = ctx.operand_width(first.index); + return true; + + case asm_operandt::kindt::IMMEDIATE: + operand.kind = a64_operandt::kindt::IMMEDIATE; + operand.value = ctx.operand_immediate(first.index); + return true; + + case asm_operandt::kindt::FLAG_OUTPUT: + return ctx.fail("flag output used in template"); + } + } + + if(tokens.size() == 1 && first.is_identifier()) + { + if(parse_register_name(first.text, ctx, operand)) + return true; + operand.kind = a64_operandt::kindt::NAME; + operand.name = first.text; + for(auto &c : operand.name) + c = static_cast(std::tolower(static_cast(c))); + return true; + } + + if( + tokens.size() == 1 && (first.kind == asm_tokent::kindt::LOCAL_LABEL || + first.kind == asm_tokent::kindt::C_LABEL)) + { + operand.kind = a64_operandt::kindt::NAME; + return true; + } + + return ctx.fail("unsupported operand"); +} + +exprt asm_aarch64_semanticst::read( + asm_lowering_contextt &ctx, + const a64_operandt &operand, + std::size_t width) const +{ + switch(operand.kind) + { + case a64_operandt::kindt::REGISTER: + if(operand.zero_register) + return constant(0, width); + if(width == 64) + return operand.storage; + return extract(operand.storage, 0, width); + + case a64_operandt::kindt::IMMEDIATE: + if(operand.value.type().id() == ID_integer) + { + return constant( + numeric_cast_v(to_constant_expr(operand.value)), width); + } + return typecast_exprt::conditional_cast(operand.value, bv(width)); + + case a64_operandt::kindt::MEMORY: + if(ctx.exclusive_open()) + { + ctx.fail("memory access between load-exclusive and store-exclusive"); + return ctx.nondet(bv(width)); + } + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + return ctx.to_bits(operand.lvalue, width); + return ctx.memory(operand.address, width); + + case a64_operandt::kindt::NAME: + break; + } + + ctx.fail("unsupported operand " + operand.name); + return ctx.nondet(bv(width)); +} + +bool asm_aarch64_semanticst::write( + asm_lowering_contextt &ctx, + const a64_operandt &operand, + std::size_t width, + const exprt &value) const +{ + switch(operand.kind) + { + case a64_operandt::kindt::REGISTER: + if(operand.zero_register) + return true; + // writes to w registers zero the upper half + ctx.assign(operand.storage, resize(resize(value, width), 64)); + return true; + + case a64_operandt::kindt::MEMORY: + if(ctx.exclusive_open()) + return ctx.fail( + "memory access between load-exclusive and store-exclusive"); + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + { + ctx.assign( + operand.lvalue, + ctx.from_bits(resize(value, width), operand.lvalue.type())); + } + else + ctx.assign(ctx.memory(operand.address, width), resize(value, width)); + return true; + + case a64_operandt::kindt::IMMEDIATE: + case a64_operandt::kindt::NAME: + break; + } + + return ctx.fail("invalid destination"); +} + +/// Split \p rest, the part of a mnemonic after its operation, into +/// acquire/release and size parts: e.g. "alb" is "al" and 8 bits. +static bool memory_order_and_size( + const std::string &rest, + bool allow_acquire, + bool &acquire, + bool &release, + std::size_t &size) +{ + std::string r = rest; + size = 0; + if(!r.empty() && (r.back() == 'b' || r.back() == 'h')) + { + size = r.back() == 'b' ? 8 : 16; + r.pop_back(); + } + acquire = release = false; + if(r == "a" && allow_acquire) + acquire = true; + else if(r == "l") + release = true; + else if(r == "al" && allow_acquire) + acquire = release = true; + else if(!r.empty()) + return false; + return true; +} + +bool asm_aarch64_semanticst::lower_memory( + const std::string &m, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + auto temp = [&](const exprt &value, const std::string &suffix) + { + const symbol_exprt t = ctx.temporary(value.type(), suffix); + ctx.assign(t, value); + return t; + }; + + auto memory_operand = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a64_operandt::kindt::MEMORY; }; + + auto register_operand = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a64_operandt::kindt::REGISTER; }; + + // plain loads and stores + { + static const std::map> loads = { + {"ldr", {0, false}}, {"ldrb", {8, false}}, {"ldrh", {16, false}}, + {"ldrsb", {8, true}}, {"ldrsh", {16, true}}, {"ldrsw", {32, true}}, + {"ldur", {0, false}}, {"ldurb", {8, false}}, {"ldurh", {16, false}}, + {"ldar", {0, false}}, {"ldarb", {8, false}}, {"ldarh", {16, false}}, + {"ldapr", {0, false}}, {"ldaprb", {8, false}}, {"ldaprh", {16, false}}, + {"ldxr", {0, false}}, {"ldxrb", {8, false}}, {"ldxrh", {16, false}}, + {"ldaxr", {0, false}}, {"ldaxrb", {8, false}}, {"ldaxrh", {16, false}}}; + + auto it = loads.find(m); + if(it != loads.end()) + { + if(ops.size() != 2 || !register_operand(0) || !memory_operand(1)) + return ctx.fail("unsupported operands of " + m); + const std::size_t rw = ops[0].width; + const std::size_t size = it->second.first == 0 ? rw : it->second.first; + const bool exclusive = m.find("xr") != std::string::npos; + const bool acquire = m.compare(0, 3, "lda") == 0; + const exprt loaded = read(ctx, ops[1], size); + write( + ctx, + ops[0], + rw, + it->second.second ? sign_extend(loaded, size, rw) : resize(loaded, rw)); + if(acquire) + ctx.fence(false, true, true, false, true); + if(exclusive) + ctx.begin_exclusive(); + return true; + } + } + + { + static const std::map stores = { + {"str", 0}, + {"strb", 8}, + {"strh", 16}, + {"stur", 0}, + {"sturb", 8}, + {"sturh", 16}, + {"stlr", 0}, + {"stlrb", 8}, + {"stlrh", 16}}; + auto it = stores.find(m); + if(it != stores.end()) + { + if(ops.size() != 2 || !register_operand(0) || !memory_operand(1)) + return ctx.fail("unsupported operands of " + m); + const std::size_t size = it->second == 0 ? ops[0].width : it->second; + if(m.compare(0, 4, "stlr") == 0) + ctx.fence(true, false, true, false, true); + return write(ctx, ops[1], size, read(ctx, ops[0], size)); + } + } + + // store-exclusive: Ws, Rt, [Xn] + { + static const std::map stores = { + {"stxr", 0}, + {"stxrb", 8}, + {"stxrh", 16}, + {"stlxr", 0}, + {"stlxrb", 8}, + {"stlxrh", 16}}; + auto it = stores.find(m); + if(it != stores.end()) + { + if( + ops.size() != 3 || !register_operand(0) || !register_operand(1) || + !memory_operand(2)) + { + return ctx.fail("unsupported operands of " + m); + } + const std::size_t size = it->second == 0 ? ops[1].width : it->second; + if(ctx.exclusive_cleared()) + { + // the store fails, and does not store + ctx.clear_exclusive(); + return write(ctx, ops[0], 32, constant(1, 32)); + } + // The store may fail spuriously; it can succeed without a + // load-exclusive in this statement if the monitor was set before. + if(ctx.exclusive_open()) + ctx.end_exclusive(); + if(m.compare(0, 4, "stlx") == 0) + ctx.fence(true, false, true, false, true); + const symbol_exprt success = temp(ctx.nondet(bool_typet{}), "success"); + const exprt value = read(ctx, ops[1], size); + const auto store = ctx.begin_conditional(success); + if(!write(ctx, ops[2], size, value)) + return false; + ctx.end_conditional(store); + ctx.clear_exclusive(); + return write( + ctx, ops[0], 32, if_exprt{success, constant(0, 32), constant(1, 32)}); + } + } + + // LSE atomics + static const std::vector lse_operations = { + "add", "clr", "eor", "set", "smax", "smin", "umax", "umin"}; + + for(const std::string prefix : {"ld", "st"}) + { + if(m.compare(0, 2, prefix) != 0) + continue; + for(const auto &op : lse_operations) + { + if(m.compare(2, op.size(), op) != 0) + continue; + bool acquire, release; + std::size_t size; + if(!memory_order_and_size( + m.substr(2 + op.size()), prefix == "ld", acquire, release, size)) + { + continue; + } + + const bool returns = prefix == "ld"; + if( + ops.size() != (returns ? 3u : 2u) || !register_operand(0) || + (returns && !register_operand(1)) || !memory_operand(ops.size() - 1)) + { + return ctx.fail("unsupported operands of " + m); + } + const std::size_t w = size == 0 ? ops[0].width : size; + ctx.mark_atomic(); + if(release) + ctx.fence(true, false, true, false, true); + const symbol_exprt old = temp(read(ctx, ops.back(), w), "old"); + const symbol_exprt arg = temp(read(ctx, ops[0], w), "arg"); + const signedbv_typet s{w}; + const exprt sold = typecast_exprt{old, s}, sarg = typecast_exprt{arg, s}; + exprt result; + if(op == "add") + result = plus_exprt{old, arg}; + else if(op == "clr") + result = bitand_exprt{old, bitnot_exprt{arg}}; + else if(op == "eor") + result = bitxor_exprt{old, arg}; + else if(op == "set") + result = bitor_exprt{old, arg}; + else if(op == "smax") + result = if_exprt{binary_relation_exprt{sold, ID_ge, sarg}, old, arg}; + else if(op == "smin") + result = if_exprt{binary_relation_exprt{sold, ID_le, sarg}, old, arg}; + else if(op == "umax") + result = if_exprt{binary_relation_exprt{old, ID_ge, arg}, old, arg}; + else + result = if_exprt{binary_relation_exprt{old, ID_le, arg}, old, arg}; + if(!write(ctx, ops.back(), w, result)) + return false; + if( + returns && !write(ctx, ops[1], ops[1].width, resize(old, ops[1].width))) + return false; + if(acquire) + ctx.fence(false, true, true, false, true); + return true; + } + } + + // swp and cas: Rs, Rt, [Xn] + for(const std::string op : {"swp", "cas"}) + { + if(m.compare(0, 3, op) != 0) + continue; + bool acquire, release; + std::size_t size; + if(!memory_order_and_size(m.substr(3), true, acquire, release, size)) + continue; + if( + ops.size() != 3 || !register_operand(0) || !register_operand(1) || + !memory_operand(2)) + { + return ctx.fail("unsupported operands of " + m); + } + const std::size_t w = size == 0 ? ops[0].width : size; + ctx.mark_atomic(); + if(release) + ctx.fence(true, false, true, false, true); + const symbol_exprt old = temp(read(ctx, ops[2], w), "old"); + const symbol_exprt rs = temp(read(ctx, ops[0], w), "rs"); + const symbol_exprt rt = temp(read(ctx, ops[1], w), "rt"); + if(op == "swp") + { + // swp Rs, Rt, [Xn]: store Rs, load the old value into Rt + if( + !write(ctx, ops[2], w, rs) || + !write(ctx, ops[1], ops[1].width, resize(old, ops[1].width))) + { + return false; + } + } + else + { + // cas Rs, Rt, [Xn]: if the memory equals Rs, store Rt; Rs := old value + if( + !write(ctx, ops[2], w, if_exprt{equal_exprt{old, rs}, rt, old}) || + !write(ctx, ops[0], ops[0].width, resize(old, ops[0].width))) + { + return false; + } + } + if(acquire) + ctx.fence(false, true, true, false, true); + return true; + } + + return ctx.fail("unsupported instruction " + instruction.mnemonic); +} + +bool asm_aarch64_semanticst::lower( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + const std::string &m = instruction.mnemonic; + + if(!instruction.prefixes.empty()) + return ctx.fail("unexpected prefix"); + + // hints and environment instructions without effect on the C program + // state + if( + m == "nop" || m == "yield" || m == "wfe" || m == "wfi" || m == "sev" || + m == "sevl" || m == "prfm" || m == "hint" || m == "csdb" || m == "esb" || + m == "sb") + { + return true; + } + + if(m == "clrex") + { + ctx.clear_exclusive(); + return true; + } + + if(m == "dmb" || m == "dsb" || m == "isb") + return lower_barrier(m, instruction, ctx); + + // branches: the target is the last operand + if( + m == "b" || (m.size() > 2 && m.compare(0, 2, "b.") == 0) || m == "cbz" || + m == "cbnz" || m == "tbz" || m == "tbnz") + { + if(instruction.operands.empty() || instruction.operands.back().size() != 1) + return ctx.fail("unsupported branch target"); + const asm_tokent &target = instruction.operands.back().back(); + + if(m == "b") + return ctx.branch(target, true_exprt{}); + + if(m[1] == '.') + { + const exprt cond = asm_arm::condition(m.substr(2), ctx); + if(cond.is_nil()) + return ctx.fail("unsupported condition " + m); + return ctx.branch(target, cond); + } + + asm_token_listt reg_tokens = instruction.operands[0]; + a64_operandt reg; + if( + !parse_operand(reg_tokens, ctx, reg) || + reg.kind != a64_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported register in " + m); + } + + if(m == "cbz" || m == "cbnz") + { + if(instruction.operands.size() != 2) + return ctx.fail("unsupported " + m); + const exprt zero = is_zero(read(ctx, reg, reg.width)); + return ctx.branch(target, m == "cbz" ? zero : exprt{not_exprt{zero}}); + } + + // tbz/tbnz Rt, #bit, label + if(instruction.operands.size() != 3) + return ctx.fail("unsupported " + m); + a64_operandt bit; + if( + !parse_operand(instruction.operands[1], ctx, bit) || + bit.kind != a64_operandt::kindt::IMMEDIATE) + { + return ctx.fail("unsupported bit in " + m); + } + const exprt set = + extractbit_exprt{lshr_exprt{read(ctx, reg, 64), read(ctx, bit, 64)}, 0}; + return ctx.branch(target, m == "tbnz" ? set : exprt{not_exprt{set}}); + } + + std::vector ops; + for(const auto &tokens : instruction.operands) + { + a64_operandt op; + if( + tokens.size() > 1 && tokens[0].is_identifier() && + (tokens[0].text == "lsl" || tokens[0].text == "lsr" || + tokens[0].text == "asr" || tokens[0].text == "ror")) + { + // a shift, interpreted by the instruction from the tokens + op.kind = a64_operandt::kindt::NAME; + op.name = tokens[0].text; + ops.push_back(op); + continue; + } + if(!parse_operand(tokens, ctx, op)) + return false; + ops.push_back(op); + } + + auto is_reg = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a64_operandt::kindt::REGISTER; }; + + auto temp = [&](const exprt &value, const std::string &suffix) + { + const symbol_exprt t = ctx.temporary(value.type(), suffix); + ctx.assign(t, value); + return t; + }; + + if(m == "mrs") + { + if( + ops.size() != 2 || !is_reg(0) || ops[1].kind != a64_operandt::kindt::NAME) + return ctx.fail("unsupported mrs"); + if(ops[1].name == "nzcv") + { + // N, Z, C, V are bits 31 to 28 + exprt value = constant(0, 64); + std::size_t bit = 31; + for(const char *f : {"n", "z", "c", "v"}) + { + value = bitor_exprt{ + value, + shl_exprt{typecast_exprt{ctx.flag(f), bv(64)}, constant(bit--, 64)}}; + } + return write(ctx, ops[0], 64, value); + } + // other system registers: their values are not modeled + return write(ctx, ops[0], 64, ctx.nondet(bv(64))); + } + + if(m == "msr") + { + if(ops.size() != 2 || ops[0].kind != a64_operandt::kindt::NAME) + return ctx.fail("unsupported msr"); + const std::string &target = ops[0].name; + if(target == "nzcv" && is_reg(1)) + { + const symbol_exprt value = temp(read(ctx, ops[1], 64), "nzcv"); + std::size_t bit = 31; + for(const char *f : {"n", "z", "c", "v"}) + ctx.assign(ctx.flag(f), extractbit_exprt{value, bit--}); + return true; + } + // the interrupt masks have no effect on the C program state + if(target == "daifset" || target == "daifclr" || target == "daif") + return true; + // others (such as fpcr, which sets the rounding mode) are not modeled + return ctx.fail("unsupported system register " + target); + } + + if(m == "mov" || m == "mvn") + { + if(ops.size() != 2 || !is_reg(0)) + return ctx.fail("unsupported " + m); + const std::size_t w = ops[0].width; + const exprt v = read(ctx, ops[1], w); + return write(ctx, ops[0], w, m == "mvn" ? exprt{bitnot_exprt{v}} : v); + } + + if(m == "movz" || m == "movk" || m == "movn") + { + std::size_t shift = 0; + if(ops.size() == 3) + { + // the shift arrives as a NAME "lsl" followed by an immediate, which + // the tokenizer keeps in one operand + const auto &tokens = instruction.operands[2]; + if( + tokens.size() != 3 || !tokens[0].is_identifier() || + tokens[0].text != "lsl" || !tokens[1].is_punctuation('#') || + tokens[2].kind != asm_tokent::kindt::NUMBER) + { + return ctx.fail("unsupported shift in " + m); + } + shift = numeric_cast_v(tokens[2].number); + } + else if(ops.size() != 2) + return ctx.fail("unsupported " + m); + if(!is_reg(0)) + return ctx.fail("unsupported " + m); + const std::size_t w = ops[0].width; + const exprt imm = shl_exprt{resize(read(ctx, ops[1], 16), w), shift}; + if(m == "movz") + return write(ctx, ops[0], w, imm); + if(m == "movn") + return write(ctx, ops[0], w, bitnot_exprt{imm}); + return write( + ctx, + ops[0], + w, + replace_bits(read(ctx, ops[0], w), w, shift, 16, read(ctx, ops[1], 16))); + } + + if(m == "neg" || m == "negs") + { + if(ops.size() != 2 || !is_reg(0)) + return ctx.fail("unsupported " + m); + const std::size_t w = ops[0].width; + const symbol_exprt src = temp(read(ctx, ops[1], w), "src"); + const symbol_exprt result = temp(unary_minus_exprt{src}, "result"); + if(m == "negs") + asm_arm::set_sub_flags(ctx, constant(0, w), src, result, w); + return write(ctx, ops[0], w, result); + } + + // three-operand data processing: Rd, Rn, Rm|#imm + static const std::set arithmetic = { + "add", + "adds", + "sub", + "subs", + "and", + "ands", + "orr", + "eor", + "bic", + "bics", + "orn", + "eon", + "lsl", + "lsr", + "asr", + "ror"}; + + if(arithmetic.count(m)) + { + if(ops.size() == 4) + { + // an immediate shift of the last operand: add x0, x1, x2, lsl #3 + const auto &tokens = instruction.operands[3]; + if( + tokens.size() == 3 && tokens[0].is_identifier() && + tokens[1].is_punctuation('#') && + tokens[2].kind == asm_tokent::kindt::NUMBER && + (tokens[0].text == "lsl" || tokens[0].text == "lsr" || + tokens[0].text == "asr")) + { + const std::size_t w = ops[0].width; + const exprt v = read(ctx, ops[2], w); + const std::size_t n = numeric_cast_v(tokens[2].number); + a64_operandt shifted; + shifted.kind = a64_operandt::kindt::IMMEDIATE; + shifted.value = + tokens[0].text == "lsl" ? exprt{shl_exprt{v, n}} + : tokens[0].text == "lsr" + ? exprt{lshr_exprt{v, n}} + : exprt{typecast_exprt{ + ashr_exprt{typecast_exprt{v, signedbv_typet{w}}, n}, bv(w)}}; + ops[2] = shifted; + ops.pop_back(); + } + else + return ctx.fail("unsupported operand shift"); + } + + if(ops.size() != 3 || !is_reg(0) || !is_reg(1)) + return ctx.fail("unsupported operands of " + m); + + const std::size_t w = ops[0].width; + const symbol_exprt a = temp(read(ctx, ops[1], w), "a"); + const symbol_exprt b = temp(read(ctx, ops[2], w), "b"); + exprt result; + if(m == "add" || m == "adds") + result = plus_exprt{a, b}; + else if(m == "sub" || m == "subs") + result = minus_exprt{a, b}; + else if(m == "and" || m == "ands") + result = bitand_exprt{a, b}; + else if(m == "orr") + result = bitor_exprt{a, b}; + else if(m == "eor") + result = bitxor_exprt{a, b}; + else if(m == "bic" || m == "bics") + result = bitand_exprt{a, bitnot_exprt{b}}; + else if(m == "orn") + result = bitor_exprt{a, bitnot_exprt{b}}; + else if(m == "eon") + result = bitxor_exprt{a, bitnot_exprt{b}}; + else + { + const exprt n = bitand_exprt{b, constant(w - 1, w)}; + if(m == "lsl") + result = shl_exprt{a, n}; + else if(m == "lsr") + result = lshr_exprt{a, n}; + else if(m == "asr") + result = typecast_exprt{ + ashr_exprt{typecast_exprt{a, signedbv_typet{w}}, n}, bv(w)}; + else + result = if_exprt{ + is_zero(n), + a, + bitor_exprt{ + lshr_exprt{a, n}, shl_exprt{a, minus_exprt{constant(w, w), n}}}}; + } + + const symbol_exprt r = temp(result, "result"); + if(m == "adds") + asm_arm::set_add_flags(ctx, a, b, constant(0, w), r, w); + else if(m == "subs") + asm_arm::set_sub_flags(ctx, a, b, r, w); + else if(m == "ands" || m == "bics") + asm_arm::set_logic_flags(ctx, r, w); + return write(ctx, ops[0], w, r); + } + + if(m == "cmp" || m == "cmn" || m == "tst") + { + if(ops.size() != 2 || !is_reg(0)) + return ctx.fail("unsupported " + m); + const std::size_t w = ops[0].width; + const symbol_exprt a = temp(read(ctx, ops[0], w), "a"); + const symbol_exprt b = temp(read(ctx, ops[1], w), "b"); + if(m == "cmp") + asm_arm::set_sub_flags(ctx, a, b, temp(minus_exprt{a, b}, "r"), w); + else if(m == "cmn") + { + asm_arm::set_add_flags( + ctx, a, b, constant(0, w), temp(plus_exprt{a, b}, "r"), w); + } + else + asm_arm::set_logic_flags(ctx, temp(bitand_exprt{a, b}, "r"), w); + return true; + } + + if(m == "cset" || m == "csetm") + { + if( + ops.size() != 2 || !is_reg(0) || ops[1].kind != a64_operandt::kindt::NAME) + { + return ctx.fail("unsupported " + m); + } + const exprt cond = asm_arm::condition(ops[1].name, ctx); + if(cond.is_nil()) + return ctx.fail("unsupported condition " + ops[1].name); + const std::size_t w = ops[0].width; + return write( + ctx, + ops[0], + w, + if_exprt{cond, constant(m == "cset" ? 1 : -1, w), constant(0, w)}); + } + + if(m == "csel" || m == "csinc" || m == "csinv" || m == "csneg") + { + if( + ops.size() != 4 || !is_reg(0) || ops[3].kind != a64_operandt::kindt::NAME) + { + return ctx.fail("unsupported " + m); + } + const exprt cond = asm_arm::condition(ops[3].name, ctx); + if(cond.is_nil()) + return ctx.fail("unsupported condition " + ops[3].name); + const std::size_t w = ops[0].width; + const exprt a = read(ctx, ops[1], w), b = read(ctx, ops[2], w); + const exprt alternative = m == "csel" ? b + : m == "csinc" + ? exprt{plus_exprt{b, constant(1, w)}} + : m == "csinv" ? exprt{bitnot_exprt{b}} + : exprt{unary_minus_exprt{b}}; + return write(ctx, ops[0], w, if_exprt{cond, a, alternative}); + } + + return lower_memory(m, ops, instruction, ctx); +} +} // namespace + +std::unique_ptr make_asm_aarch64_semantics() +{ + return std::make_unique(); +} diff --git a/src/assembler/asm_aarch64.h b/src/assembler/asm_aarch64.h new file mode 100644 index 000000000000..72206469bfdb --- /dev/null +++ b/src/assembler/asm_aarch64.h @@ -0,0 +1,21 @@ +/*******************************************************************\ + +Module: Inline assembly: aarch64 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for aarch64 + +#ifndef CPROVER_ASSEMBLER_ASM_AARCH64_H +#define CPROVER_ASSEMBLER_ASM_AARCH64_H + +#include + +class asm_semanticst; + +std::unique_ptr make_asm_aarch64_semantics(); + +#endif // CPROVER_ASSEMBLER_ASM_AARCH64_H diff --git a/src/assembler/asm_arm_flags.h b/src/assembler/asm_arm_flags.h new file mode 100644 index 000000000000..61503a37ef14 --- /dev/null +++ b/src/assembler/asm_arm_flags.h @@ -0,0 +1,133 @@ +/*******************************************************************\ + +Module: Inline assembly: ARM condition flags + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// The NZCV condition flags and condition codes shared by AArch64 and AArch32 + +#ifndef CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H +#define CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H + +#include "asm_bv_util.h" +#include "asm_semantics.h" + +#include + +namespace asm_arm // NOLINT +{ +inline const std::set &condition_codes() +{ + static const std::set codes = { + "eq", + "ne", + "cs", + "hs", + "cc", + "lo", + "mi", + "pl", + "vs", + "vc", + "hi", + "ls", + "ge", + "lt", + "gt", + "le", + "al"}; + return codes; +} + +inline exprt condition(const std::string &cc, asm_lowering_contextt &ctx) +{ + const exprt n = ctx.flag("n"), z = ctx.flag("z"), c = ctx.flag("c"), + v = ctx.flag("v"); + + if(cc == "eq") + return z; + if(cc == "ne") + return not_exprt{z}; + if(cc == "cs" || cc == "hs") + return c; + if(cc == "cc" || cc == "lo") + return not_exprt{c}; + if(cc == "mi") + return n; + if(cc == "pl") + return not_exprt{n}; + if(cc == "vs") + return v; + if(cc == "vc") + return not_exprt{v}; + if(cc == "hi") + return and_exprt{c, not_exprt{z}}; + if(cc == "ls") + return or_exprt{not_exprt{c}, z}; + if(cc == "ge") + return equal_exprt{n, v}; + if(cc == "lt") + return notequal_exprt{n, v}; + if(cc == "gt") + return and_exprt{not_exprt{z}, equal_exprt{n, v}}; + if(cc == "le") + return or_exprt{z, notequal_exprt{n, v}}; + if(cc == "al" || cc == "nv") + return true_exprt{}; + return nil_exprt{}; +} + +/// set N and Z from \p result +inline void +set_nz(asm_lowering_contextt &ctx, const exprt &result, std::size_t width) +{ + ctx.assign(ctx.flag("n"), asm_bv::msb(result, width)); + ctx.assign(ctx.flag("z"), asm_bv::is_zero(result)); +} + +/// flags of \p result = \p a + \p b + \p carry_in +inline void set_add_flags( + asm_lowering_contextt &ctx, + const exprt &a, + const exprt &b, + const exprt &carry_in, + const exprt &result, + std::size_t width) +{ + set_nz(ctx, result, width); + ctx.assign(ctx.flag("c"), asm_bv::carry_add(a, b, carry_in, width)); + ctx.assign(ctx.flag("v"), asm_bv::overflow_add(a, b, result, width)); +} + +/// flags of \p result = \p a - \p b, which ARM computes as +/// a + ~b + 1: C is set if there is no borrow +inline void set_sub_flags( + asm_lowering_contextt &ctx, + const exprt &a, + const exprt &b, + const exprt &result, + std::size_t width) +{ + set_nz(ctx, result, width); + ctx.assign( + ctx.flag("c"), + not_exprt{asm_bv::borrow_sub(a, b, asm_bv::constant(0, width), width)}); + ctx.assign(ctx.flag("v"), asm_bv::overflow_sub(a, b, result, width)); +} + +/// flags of a logical operation with result \p result +inline void set_logic_flags( + asm_lowering_contextt &ctx, + const exprt &result, + std::size_t width) +{ + set_nz(ctx, result, width); + ctx.assign(ctx.flag("c"), false_exprt{}); + ctx.assign(ctx.flag("v"), false_exprt{}); +} +} // namespace asm_arm + +#endif // CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 60b8d1707776..b69ccf96990e 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -314,17 +314,43 @@ void asm_lowering_contextt::begin_instruction() void asm_lowering_contextt::end_instruction() { - if(!atomic) - return; + std::optional> start; + if(exclusive_ends) + start = ended_exclusive_start; + else if(atomic) + start = instruction_start; + exclusive_ends = false; atomic = false; - const goto_programt::targett first = instruction_start.has_value() - ? std::next(*instruction_start) - : body.instructions.begin(); + if(!start.has_value()) + return; + + const goto_programt::targett first = + start->has_value() ? std::next(**start) : body.instructions.begin(); body.insert_before(first, goto_programt::make_atomic_begin(location)); body.add(goto_programt::make_atomic_end(location)); } +void asm_lowering_contextt::begin_exclusive() +{ + exclusive_start = instruction_start; + monitor_cleared = false; +} + +void asm_lowering_contextt::end_exclusive() +{ + PRECONDITION(exclusive_open()); + ended_exclusive_start = *exclusive_start; + exclusive_ends = true; + exclusive_start.reset(); +} + +void asm_lowering_contextt::clear_exclusive() +{ + exclusive_start.reset(); + monitor_cleared = true; +} + void asm_lowering_contextt::assume(const exprt &condition) { note_reads(condition); @@ -690,6 +716,9 @@ bool asm_lowering_contextt::prepare( void asm_lowering_contextt::define_label(const std::string &name) { + // a jump into an exclusive access region would bypass its start + if(exclusive_open()) + fail("label between load-exclusive and store-exclusive"); const auto t = body.add(goto_programt::make_skip(location)); // Join the forward branches to the label lowered so far. Backward branches, // lowered later, are checked against the result (check_unknown_at_target). @@ -720,6 +749,9 @@ bool asm_lowering_contextt::branch( const exprt &condition) { note_reads(condition); + if(exclusive_open()) + return fail("branch between load-exclusive and store-exclusive"); + if(target.kind == asm_tokent::kindt::C_LABEL) { if(goto_target.is_nil()) diff --git a/src/assembler/asm_semantics.cpp b/src/assembler/asm_semantics.cpp index da2900f0d97f..e2e02b74cf59 100644 --- a/src/assembler/asm_semantics.cpp +++ b/src/assembler/asm_semantics.cpp @@ -11,6 +11,7 @@ Author: Michael Tautschnig #include "asm_semantics.h" +#include "asm_aarch64.h" #include "asm_x86.h" asm_semanticst::constraint_classt asm_semanticst::classify_constraint( @@ -27,6 +28,8 @@ std::unique_ptr make_asm_semantics(const irep_idt &arch) return make_asm_x86_semantics(true); else if(arch == "i386") return make_asm_x86_semantics(false); + else if(arch == "arm64") + return make_asm_aarch64_semantics(); else return nullptr; } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index fa60f92046ae..b3f37f7b88d4 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -119,9 +119,44 @@ class asm_lowering_contextt void begin_instruction(); /// Finish lowering an instruction: if it was marked atomic (see - /// \ref mark_atomic), wrap its code in an atomic section. + /// \ref mark_atomic), wrap its code in an atomic section, and likewise + /// for an exclusive access region that the instruction ends (see + /// \ref end_exclusive). void end_instruction(); + /// \name Load-exclusive/store-exclusive sequences + /// A load-exclusive (AArch64 `ldxr`, AArch32 `ldrex`) followed, in the same + /// statement and without other memory accesses, branches, or labels in + /// between, by a store-exclusive is modeled as an atomic section that + /// spans both instructions. The store-exclusive succeeds + /// nondeterministically (the architecture permits spurious failures). + /// \{ + + /// Start an exclusive access region at the current instruction (a + /// load-exclusive). + void begin_exclusive(); + + /// \return True iff an exclusive access region is open. + bool exclusive_open() const + { + return exclusive_start.has_value(); + } + + /// End the open exclusive access region with the current instruction (a + /// store-exclusive), which makes the region an atomic section. + void end_exclusive(); + + /// The exclusive monitor is cleared (by `clrex`, or by a + /// store-exclusive): a later store-exclusive in this statement fails. + void clear_exclusive(); + + /// \return True iff the exclusive monitor is known to be cleared. + bool exclusive_cleared() const + { + return monitor_cleared; + } + /// \} + /// A call to a library function taking `void *` arguments void call(const irep_idt &function, const exprt::operandst &arguments); @@ -217,6 +252,15 @@ class asm_lowering_contextt bool atomic = false; /// the last instruction of body before the current instruction, if any std::optional instruction_start; + /// for an open exclusive access region: the last instruction of body + /// before the load-exclusive, if any + std::optional> exclusive_start; + /// whether the current instruction ends an exclusive access region + bool exclusive_ends = false; + /// where the exclusive access region ended by the current instruction + /// started + std::optional ended_exclusive_start; + bool monitor_cleared = false; /// the canonical names of the hardware registers that are written std::set written_registers; From 8c9c81d547cc36036b11d51fad3e3de130abbb49 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:10:58 +0000 Subject: [PATCH 065/100] AArch64 inline assembly: interpret only register-neutral hints 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 #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 --- doc/cprover-manual/modeling-inline-asm.md | 15 ++++-- regression/cbmc/asm_aarch64_hint/main.c | 44 ++++++++++++++++ regression/cbmc/asm_aarch64_hint/test.desc | 24 +++++++++ src/assembler/asm_aarch64.cpp | 61 +++++++++++++++++++++- 4 files changed, 138 insertions(+), 6 deletions(-) create mode 100644 regression/cbmc/asm_aarch64_hint/main.c create mode 100644 regression/cbmc/asm_aarch64_hint/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 3fbe32741cf9..1e94d8f6bdac 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -154,10 +154,17 @@ The AArch64 semantics cover: - branches within the statement and to the labels of `asm goto`, and flag outputs (`=@cc`); - barriers (`dmb`, `dsb`, `isb`), `mrs` and `msr` of the flags (`nzcv`), - `msr` of the interrupt masks (`daif`, `daifset`, `daifclr`), and hints - (`nop`, `yield`, `wfe`, ...); `mrs` of other system registers produces a - nondeterministic value, and `msr` of other system registers (such as - `fpcr`, which sets the rounding mode) is not modeled. + and `msr` of the interrupt masks (`daif`, `daifset`, `daifclr`); `mrs` of + other system registers produces a nondeterministic value, and `msr` of + other system registers (such as `fpcr`, which sets the rounding mode) is + not modeled; +- instructions without effect on the C program state: `nop`, `yield`, + `wfe`, `wfi`, `sev`, `sevl`, `csdb`, `esb`, `sb`, `prfm`, and `hint #` + with the number of one of these hints or of `dgh`, `psb csync`, + `tsb csync`, `gcsb dsync`, `clrbhb`, or a `bti` variant. Other numbers of + `hint`, such as those of the pointer authentication instructions (which + write x16, x17, or x30) and of `chkfeat` (which writes x16), are not + interpreted. A load-exclusive followed by a store-exclusive in the same statement, with no other memory access, branch, or label in between, is an atomic section. diff --git a/regression/cbmc/asm_aarch64_hint/main.c b/regression/cbmc/asm_aarch64_hint/main.c new file mode 100644 index 000000000000..96e5714c3a95 --- /dev/null +++ b/regression/cbmc/asm_aarch64_hint/main.c @@ -0,0 +1,44 @@ +// hint #imm is a no-op only for the hints that leave the registers unchanged. +// The pointer authentication hints write x16, x17, or x30, and chkfeat +// (hint #40) writes x16. "fails" marks properties that the architecture +// permits to be violated, so CBMC must not prove them. +int main(void) +{ + unsigned long in = 0x0000aaaabbbbccccul, out; + + // pacia1716 signs x17 with the modifier in x16 + __asm__ volatile("mov x17, %1\n mov x16, #0\n hint #8\n mov %0, x17" + : "=r"(out) + : "r"(in) + : "x16", "x17"); + __CPROVER_assert(out == in, "pacia1716 leaves x17 unchanged"); // fails + + // pacib1716, with the hint number in an operand + __asm__ volatile("mov x17, %1\n mov x16, #0\n hint %2\n mov %0, x17" + : "=r"(out) + : "r"(in), "i"(10) + : "x16", "x17"); + __CPROVER_assert(out == in, "pacib1716 leaves x17 unchanged"); // fails + + // xpaclri removes the authentication code from x30 + __asm__ volatile("mov x30, %1\n hint #7\n mov %0, x30" + : "=r"(out) + : "r"(0x00ff000000001234ul) + : "x30"); + __CPROVER_assert(out == 0x00ff000000001234ul, "xpaclri"); // fails + + // chkfeat x16 clears the bits of the enabled features + __asm__ volatile("mov x16, #1\n hint #40\n mov %0, x16" + : "=r"(out) + : + : "x16"); + __CPROVER_assert(out == 1, "chkfeat leaves x16 unchanged"); // fails + + // nop, csdb, bti c, bti jc + __asm__ volatile("mov %0, %1\n hint #0\n hint #20\n hint #34\n hint #0x26" + : "=r"(out) + : "r"(in)); + __CPROVER_assert(out == in, "hints without effect"); + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_hint/test.desc b/regression/cbmc/asm_aarch64_hint/test.desc new file mode 100644 index 000000000000..a5cdf8714c67 --- /dev/null +++ b/regression/cbmc/asm_aarch64_hint/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 14 pacia1716 leaves x17 unchanged: FAILURE$ +^\[main\.assertion\.2\] line 21 pacib1716 leaves x17 unchanged: FAILURE$ +^\[main\.assertion\.3\] line 28 xpaclri: FAILURE$ +^\[main\.assertion\.4\] line 35 chkfeat leaves x16 unchanged: FAILURE$ +^\[main\.assertion\.5\] line 41 hints without effect: SUCCESS$ +approximating inline assembly statement at .* line 10 function main: hint #8 may write registers +approximating inline assembly statement at .* line 17 function main: hint #10 may write registers +approximating inline assembly statement at .* line 24 function main: hint #7 may write registers +approximating inline assembly statement at .* line 31 function main: hint #40 may write registers +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line 38 +-- +The pointer authentication hints and chkfeat are not interpreted, so the +statements using them are approximated; the other hints of the test are +no-ops. On qemu-aarch64 (-cpu max), the first three properties are violated; +qemu does not implement chkfeat, which clears bit 0 of x16 if the guarded +control stack is enabled. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index f243bd6d29d8..6da67e0cee64 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -193,6 +193,10 @@ class asm_aarch64_semanticst : public asm_semanticst const asm_instructiont &instruction, asm_lowering_contextt &ctx) const; + bool lower_hint( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; + public: std::string canonical_register(const std::string &name) const override; }; @@ -266,6 +270,57 @@ bool asm_aarch64_semanticst::lower_barrier( return true; } +/// Lower `hint #imm`. The hint space also holds instructions that write +/// general-purpose registers: the pointer authentication instructions +/// (`xpaclri`, `pacia1716`, `paciasp`, ...: x16, x17, or x30) and `chkfeat` +/// (x16); numbers not allocated yet may be allocated to such instructions. +/// Hence only the numbers of the hints that leave registers and memory +/// unchanged are no-ops. +bool asm_aarch64_semanticst::lower_hint( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + a64_operandt operand; + if( + instruction.operands.size() != 1 || + !parse_operand(instruction.operands[0], ctx, operand) || + operand.kind != a64_operandt::kindt::IMMEDIATE) + { + return ctx.fail("unsupported operand of hint"); + } + + const auto number = numeric_cast(operand.value); + if(!number.has_value()) + return ctx.fail("unsupported operand of hint"); + + static const std::set no_effect = { + 0, // nop + 1, // yield + 2, // wfe + 3, // wfi + 4, // sev + 5, // sevl + 6, // dgh + 16, // esb + 17, // psb csync + 18, // tsb csync + 19, // gcsb dsync + 20, // csdb + 22, // clrbhb + 32, // bti + 34, // bti c + 36, // bti j + 38 // bti jc + }; + if(no_effect.count(*number) == 0) + { + return ctx.fail( + "hint #" + std::to_string(*number) + + " may write registers (as pointer authentication and chkfeat do)"); + } + return true; +} + bool asm_aarch64_semanticst::parse_register_name( const std::string &raw, asm_lowering_contextt &ctx, @@ -838,12 +893,14 @@ bool asm_aarch64_semanticst::lower( // state if( m == "nop" || m == "yield" || m == "wfe" || m == "wfi" || m == "sev" || - m == "sevl" || m == "prfm" || m == "hint" || m == "csdb" || m == "esb" || - m == "sb") + m == "sevl" || m == "prfm" || m == "csdb" || m == "esb" || m == "sb") { return true; } + if(m == "hint") + return lower_hint(instruction, ctx); + if(m == "clrex") { ctx.clear_exclusive(); From 228bf12a899560619aef862e4dc0bc0ae591fb45 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:12:26 +0000 Subject: [PATCH 066/100] AArch64 inline assembly: reject modifiers of immediate operands 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 --- .../asm_aarch64_immediate_modifier/main.c | 27 +++++++++++++++++++ .../asm_aarch64_immediate_modifier/test.desc | 18 +++++++++++++ src/assembler/asm_aarch64.cpp | 21 ++++++++++++--- 3 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 regression/cbmc/asm_aarch64_immediate_modifier/main.c create mode 100644 regression/cbmc/asm_aarch64_immediate_modifier/test.desc diff --git a/regression/cbmc/asm_aarch64_immediate_modifier/main.c b/regression/cbmc/asm_aarch64_immediate_modifier/main.c new file mode 100644 index 000000000000..888638139f8e --- /dev/null +++ b/regression/cbmc/asm_aarch64_immediate_modifier/main.c @@ -0,0 +1,27 @@ +// Operand modifiers of immediate operands: %c prints the constant like a +// plain reference, and %w and %x print the constant 0 as wzr and xzr. Other +// modifiers, such as %n, which prints the negated constant, are not +// interpreted. "fails" marks properties that are violated on hardware, so +// CBMC must not prove them. +int main(void) +{ + unsigned long a = 100, r; + + __asm__("add %0, %1, #%n2" : "=r"(r) : "r"(a), "i"(5)); + __CPROVER_assert(r == 105, "add #%n2 adds 5"); // fails + + __asm__("add %0, %1, #%2" : "=r"(r) : "r"(a), "i"(5)); + __CPROVER_assert(r == 105, "add #%2"); + + __asm__("add %0, %1, %c2" : "=r"(r) : "r"(a), "i"(5)); + __CPROVER_assert(r == 105, "add %c2"); + + __asm__("orr %0, %1, %x2" : "=r"(r) : "r"(a), "i"(0)); + __CPROVER_assert(r == 100, "orr with xzr"); + + r = 1; + __asm__("mov %w0, %w1" : "+r"(r) : "i"(0)); + __CPROVER_assert(r == 0, "mov from wzr"); + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_immediate_modifier/test.desc b/regression/cbmc/asm_aarch64_immediate_modifier/test.desc new file mode 100644 index 000000000000..3c6b57348687 --- /dev/null +++ b/regression/cbmc/asm_aarch64_immediate_modifier/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 11 add #%n2 adds 5: FAILURE$ +^\[main\.assertion\.2\] line 14 add #%2: SUCCESS$ +^\[main\.assertion\.3\] line 17 add %c2: SUCCESS$ +^\[main\.assertion\.4\] line 20 orr with xzr: SUCCESS$ +^\[main\.assertion\.5\] line 24 mov from wzr: SUCCESS$ +approximating inline assembly statement at .* line 10 function main: unsupported operand modifier %n +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (13|16|19|23) +-- +With %n, the first statement subtracts 5 on hardware (qemu-aarch64: r is 95); +CBMC approximates it. The other statements are interpreted. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 6da67e0cee64..1a0dfc119850 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -401,11 +401,14 @@ bool asm_aarch64_semanticst::parse_immediate_tokens( if(token.kind == asm_tokent::kindt::OPERAND) { const asm_operandt &bound = ctx.operands.operands.at(token.index); - if(bound.kind == asm_operandt::kindt::IMMEDIATE) - value = ctx.operand_immediate(token.index); - else + if(bound.kind != asm_operandt::kindt::IMMEDIATE) return ctx.fail( "operand %" + std::to_string(token.index) + " is not an immediate"); + // %c prints the constant like a plain reference; other modifiers (such + // as %n, which negates it) change what is printed + if(!token.modifier.empty() && token.modifier != "c") + return ctx.fail("unsupported operand modifier %" + token.modifier); + value = ctx.operand_immediate(token.index); if(negative) value = unary_minus_exprt{value}; return true; @@ -512,6 +515,18 @@ bool asm_aarch64_semanticst::parse_operand( return true; case asm_operandt::kindt::IMMEDIATE: + if( + (first.modifier == "w" || first.modifier == "x") && + numeric_cast(ctx.operand_immediate(first.index)) == 0) + { + // %w and %x print the constant 0 as wzr and xzr + operand.kind = a64_operandt::kindt::REGISTER; + operand.zero_register = true; + operand.width = first.modifier == "x" ? 64 : 32; + return true; + } + if(!first.modifier.empty() && first.modifier != "c") + return ctx.fail("unsupported operand modifier %" + first.modifier); operand.kind = a64_operandt::kindt::IMMEDIATE; operand.value = ctx.operand_immediate(first.index); return true; From 5c990104e435b59bba9e9cca4ada1cde3ac6107c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:13:58 +0000 Subject: [PATCH 067/100] AArch64 inline assembly: decide the monitor state along control flow 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 --- doc/architectural/inline-assembly.md | 6 ++++- doc/cprover-manual/modeling-inline-asm.md | 7 ++++++ .../cbmc/asm_aarch64_clrex_branch/main.c | 25 +++++++++++++++++++ .../cbmc/asm_aarch64_clrex_branch/test.desc | 15 +++++++++++ src/assembler/asm_lowering.cpp | 3 +++ src/assembler/asm_semantics.h | 9 +++++-- 6 files changed, 62 insertions(+), 3 deletions(-) create mode 100644 regression/cbmc/asm_aarch64_clrex_branch/main.c create mode 100644 regression/cbmc/asm_aarch64_clrex_branch/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 9af6caba4087..b0678b37a88d 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -147,7 +147,11 @@ the statement is not interpreted. The store-exclusive succeeds nondeterministically: the architecture permits spurious failures, and a store-exclusive without a load-exclusive in the same statement may succeed if a load-exclusive executed before. After `clrex` or a store-exclusive, a -store-exclusive fails. +store-exclusive fails, unless a label or a load-exclusive comes in between: +the monitor state is decided along the control flow, and a branch to the +label may skip the instruction that cleared the monitor +(`asm_lowering_contextt::define_label` forgets that the monitor is +cleared). For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 1e94d8f6bdac..87363cd0ab05 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -179,6 +179,13 @@ again), the executions with more retries reach the same states, so that bounding the loop (with `--unwindset`, without unwinding assertions) does not miss any state. +A store-exclusive fails if the exclusive monitor is cleared, by `clrex` or +by an earlier store-exclusive. CBMC decides the monitor state along the +control flow: it takes the monitor to be cleared after `clrex` or a +store-exclusive only until the next label, as a branch to the label may skip +the clearing instruction; after a label, a store-exclusive succeeds or fails +nondeterministically. + ### Supported Instructions CBMC splits the assembler text into instructions at newlines and `;`, except diff --git a/regression/cbmc/asm_aarch64_clrex_branch/main.c b/regression/cbmc/asm_aarch64_clrex_branch/main.c new file mode 100644 index 000000000000..325d3e34980e --- /dev/null +++ b/regression/cbmc/asm_aarch64_clrex_branch/main.c @@ -0,0 +1,25 @@ +// Whether the exclusive monitor is cleared depends on the path through the +// statement: a store-exclusive after a clrex that a branch skips may succeed. +// "fails" marks properties that are violated on hardware, so CBMC must not +// prove them. +unsigned long m = 1; + +int main(void) +{ + unsigned long t; + unsigned int status; + unsigned long skip = 1; + + // sets the exclusive monitor + __asm__ volatile("ldxr %0, [%1]" : "=r"(t) : "r"(&m) : "memory"); + + // the branch skips the clrex + __asm__ volatile("cbnz %3, 1f\n clrex\n1: stxr %w0, %2, [%1]" + : "=&r"(status) + : "r"(&m), "r"(42ul), "r"(skip) + : "memory"); + __CPROVER_assert(status == 1 && m == 1, "skipped clrex"); // fails + __CPROVER_assert((status == 0) == (m == 42), "status matches the store"); + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_clrex_branch/test.desc b/regression/cbmc/asm_aarch64_clrex_branch/test.desc new file mode 100644 index 000000000000..09e90813e120 --- /dev/null +++ b/regression/cbmc/asm_aarch64_clrex_branch/test.desc @@ -0,0 +1,15 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 21 skipped clrex: FAILURE$ +^\[main\.assertion\.2\] line 22 status matches the store: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +On qemu-aarch64, the store-exclusive succeeds (status 0, m is 42). CBMC takes +the exclusive monitor to be cleared only if it is cleared on all paths: after +a label, a store-exclusive succeeds or fails nondeterministically. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index b69ccf96990e..909e5870445a 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -719,6 +719,9 @@ void asm_lowering_contextt::define_label(const std::string &name) // a jump into an exclusive access region would bypass its start if(exclusive_open()) fail("label between load-exclusive and store-exclusive"); + // a branch to the label may skip the instruction that cleared the + // exclusive monitor + monitor_cleared = false; const auto t = body.add(goto_programt::make_skip(location)); // Join the forward branches to the label lowered so far. Backward branches, // lowered later, are checked against the result (check_unknown_at_target). diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index b3f37f7b88d4..914eb96dc2e1 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -147,10 +147,13 @@ class asm_lowering_contextt void end_exclusive(); /// The exclusive monitor is cleared (by `clrex`, or by a - /// store-exclusive): a later store-exclusive in this statement fails. + /// store-exclusive): a later store-exclusive fails, unless a label (which + /// a branch may reach with the monitor set) or a load-exclusive comes + /// first. void clear_exclusive(); - /// \return True iff the exclusive monitor is known to be cleared. + /// \return True iff the exclusive monitor is known to be cleared on all + /// paths to the current position. bool exclusive_cleared() const { return monitor_cleared; @@ -260,6 +263,8 @@ class asm_lowering_contextt /// where the exclusive access region ended by the current instruction /// started std::optional ended_exclusive_start; + /// whether the exclusive monitor is cleared on all paths to the current + /// position (see \ref exclusive_cleared) bool monitor_cleared = false; /// the canonical names of the hardware registers that are written std::set written_registers; From 62d7f0e0f439ed5bc2083605a200ce0aef874371 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:15:13 +0000 Subject: [PATCH 068/100] AArch64 inline assembly: dsb with an st option also orders loads `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 --- doc/cprover-manual/modeling-inline-asm.md | 14 +++++---- .../asm_aarch64_barrier_st/dmb.desc | 12 ++++++++ .../asm_aarch64_barrier_st/main.c | 29 +++++++++++++++++++ .../asm_aarch64_barrier_st/test.desc | 14 +++++++++ src/assembler/asm_aarch64.cpp | 8 +++-- 5 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_aarch64_barrier_st/dmb.desc create mode 100644 regression/cbmc-concurrency/asm_aarch64_barrier_st/main.c create mode 100644 regression/cbmc-concurrency/asm_aarch64_barrier_st/test.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 87363cd0ab05..1cacd76ba47f 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -153,11 +153,15 @@ The AArch64 semantics cover: store-exclusive (`ldxr`, `ldaxr`, `stxr`, `stlxr`, `clrex`); - branches within the statement and to the labels of `asm goto`, and flag outputs (`=@cc`); -- barriers (`dmb`, `dsb`, `isb`), `mrs` and `msr` of the flags (`nzcv`), - and `msr` of the interrupt masks (`daif`, `daifset`, `daifclr`); `mrs` of - other system registers produces a nondeterministic value, and `msr` of - other system registers (such as `fpcr`, which sets the rounding mode) is - not modeled; +- barriers: `dmb` and `dsb` order the accesses that their option selects + (no option or one of `sy`, `ish`, `osh`, `nsh` orders all accesses, an + option ending in `ld` orders loads before later loads and stores, and an + option ending in `st` orders stores before later stores and, for `dsb`, + before later loads), and `isb` orders nothing by itself; +- `mrs` and `msr` of the flags (`nzcv`), and `msr` of the interrupt masks + (`daif`, `daifset`, `daifclr`); `mrs` of other system registers produces + a nondeterministic value, and `msr` of other system registers (such as + `fpcr`, which sets the rounding mode) is not modeled; - instructions without effect on the C program state: `nop`, `yield`, `wfe`, `wfi`, `sev`, `sevl`, `csdb`, `esb`, `sb`, `prfm`, and `hint #` with the number of one of these hints or of `dgh`, `psb csync`, diff --git a/regression/cbmc-concurrency/asm_aarch64_barrier_st/dmb.desc b/regression/cbmc-concurrency/asm_aarch64_barrier_st/dmb.desc new file mode 100644 index 000000000000..f74988a44eab --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_barrier_st/dmb.desc @@ -0,0 +1,12 @@ +CORE gcc-only +main.c +--arch arm64 --mm tso -DBARRIER='"dmb ishst"' +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 27 store buffering: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +dmb ishst orders stores only before later stores, so both loads may read 0. diff --git a/regression/cbmc-concurrency/asm_aarch64_barrier_st/main.c b/regression/cbmc-concurrency/asm_aarch64_barrier_st/main.c new file mode 100644 index 000000000000..e2f0229ddc6c --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_barrier_st/main.c @@ -0,0 +1,29 @@ +// Store buffering: each thread stores to one variable and then loads the +// other. A dsb with an st option completes the stores before it before any +// later instruction executes, so the loads cannot both read 0. A dmb with an +// st option orders stores only before later stores. +#ifndef BARRIER +# define BARRIER "dsb ishst" +#endif + +int x, y, r1, r2, done; + +void t(void) +{ + x = 1; + __asm__ volatile(BARRIER ::: "memory"); + r1 = y; + done = 1; +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(); + y = 1; + __asm__ volatile(BARRIER ::: "memory"); + r2 = x; + __CPROVER_assume(done); + __CPROVER_assert(r1 == 1 || r2 == 1, "store buffering"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_aarch64_barrier_st/test.desc b/regression/cbmc-concurrency/asm_aarch64_barrier_st/test.desc new file mode 100644 index 000000000000..4139d0c8b0ae --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_barrier_st/test.desc @@ -0,0 +1,14 @@ +CORE gcc-only +main.c +--arch arm64 --mm tso +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 27 store buffering: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +dsb ishst orders the stores before it before the loads after it, as no +instruction after a dsb executes before the dsb completes (Arm ARM, "Data +Synchronization Barrier"). The memory model tso relaxes only that order. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 1a0dfc119850..5bfe7b1f7a48 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -263,8 +263,12 @@ bool asm_aarch64_semanticst::lower_barrier( ctx.fence(true, true, true, true, true); else if(has_suffix(option, "ld")) // loads before loads and stores ctx.fence(false, true, true, false, true); - else if(has_suffix(option, "st")) // stores before stores - ctx.fence(true, false, false, false, true); + else if(has_suffix(option, "st")) + { + // dmb: stores before stores. No instruction after a dsb executes before + // the dsb completes, so a dsb also orders the stores before later loads. + ctx.fence(true, false, false, m == "dsb", true); + } else return ctx.fail("unsupported option of " + m); return true; From d84e097057013d7de7be18518cbc6180aa10e469 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:19:04 +0000 Subject: [PATCH 069/100] AArch64 inline assembly: abandon exclusive regions instead of failing 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 --- doc/architectural/inline-assembly.md | 22 +++--- doc/cprover-manual/modeling-inline-asm.md | 5 ++ .../asm_aarch64_exclusive_abandoned/main.c | 72 +++++++++++++++++++ .../asm_aarch64_exclusive_abandoned/test.desc | 21 ++++++ src/assembler/asm_aarch64.cpp | 10 +-- src/assembler/asm_lowering.cpp | 11 +-- src/assembler/asm_semantics.h | 13 ++++ 7 files changed, 131 insertions(+), 23 deletions(-) create mode 100644 regression/cbmc/asm_aarch64_exclusive_abandoned/main.c create mode 100644 regression/cbmc/asm_aarch64_exclusive_abandoned/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index b0678b37a88d..06a7fa6097eb 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -142,16 +142,18 @@ instructions. A load-exclusive followed by a store-exclusive is an atomic section from the load to the store (`asm_lowering_contextt::begin_exclusive`, `end_exclusive`) -if there is no other memory access, branch, or label in between; otherwise -the statement is not interpreted. The store-exclusive succeeds -nondeterministically: the architecture permits spurious failures, and a -store-exclusive without a load-exclusive in the same statement may succeed if -a load-exclusive executed before. After `clrex` or a store-exclusive, a -store-exclusive fails, unless a label or a load-exclusive comes in between: -the monitor state is decided along the control flow, and a branch to the -label may skip the instruction that cleared the monitor -(`asm_lowering_contextt::define_label` forgets that the monitor is -cleared). +if there is no other memory access, branch, or label in between. Such an +access, branch, or label abandons the region +(`asm_lowering_contextt::abandon_exclusive`): the load-exclusive is then a +plain load, and a later store-exclusive is not atomic with it. Without the +atomic section the model admits more interleavings, so this is sound. The +store-exclusive succeeds nondeterministically: the architecture permits +spurious failures, and a store-exclusive without a load-exclusive in the same +statement may succeed if a load-exclusive executed before. After `clrex` or a +store-exclusive, a store-exclusive fails, unless a label or a load-exclusive +comes in between: the monitor state is decided along the control flow, and a +branch to the label may skip the instruction that cleared the monitor +(`asm_lowering_contextt::define_label` forgets that the monitor is cleared). For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 1cacd76ba47f..b61a4c4e91ab 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -172,6 +172,11 @@ The AArch64 semantics cover: A load-exclusive followed by a store-exclusive in the same statement, with no other memory access, branch, or label in between, is an atomic section. +Otherwise the load-exclusive is a plain load, and a later store-exclusive is +not atomic with it (for example, in a compare-and-swap loop that branches +past the store-exclusive if the values differ): the architecture does not +guarantee the reservation across another memory access, and a branch to a +label between the two may bypass the load-exclusive. The store-exclusive succeeds or fails nondeterministically, as the architecture permits spurious failures, and so does a store-exclusive without a preceding load-exclusive in the statement (a load-exclusive may diff --git a/regression/cbmc/asm_aarch64_exclusive_abandoned/main.c b/regression/cbmc/asm_aarch64_exclusive_abandoned/main.c new file mode 100644 index 000000000000..0b71f82382f7 --- /dev/null +++ b/regression/cbmc/asm_aarch64_exclusive_abandoned/main.c @@ -0,0 +1,72 @@ +// A branch, a label, or another memory access after a load-exclusive ends the +// exclusive access region: the load-exclusive is then a plain load, and a +// store-exclusive after it succeeds or fails nondeterministically without +// being atomic with the load. "fails" marks properties that the architecture +// permits to be violated, so CBMC must not prove them. + +// Linux arm64 __cmpwait_case_32: the load-exclusive only arms the monitor for +// wfe, and there is no store-exclusive +static void cmpwait(volatile void *ptr, unsigned long val) +{ + unsigned long tmp; + __asm__ volatile( + "sevl\n" + " wfe\n" + " ldxr %w[tmp], %[v]\n" + " eor %w[tmp], %w[tmp], %w[val]\n" + " cbnz %w[tmp], 1f\n" + " wfe\n" + "1:" + : [tmp] "=&r"(tmp), [v] "+Q"(*(unsigned int *)ptr) + : [val] "r"(val)); +} + +// Linux arm64 __ll_sc__cmpxchg_case_64, without barriers: the branch to 2f +// leaves the exclusive access region +static unsigned long +cmpxchg(unsigned long *ptr, unsigned long old, unsigned long new) +{ + unsigned long tmp, oldval; + __asm__ volatile( + "1: ldxr %[oldval], %[v]\n" + " eor %[tmp], %[oldval], %[old]\n" + " cbnz %[tmp], 2f\n" + " stxr %w[tmp], %[new], %[v]\n" + " cbnz %w[tmp], 1b\n" + "2:" + : [tmp] "=&r"(tmp), [oldval] "=&r"(oldval), [v] "+Q"(*ptr) + : [old] "r"(old), [new] "r"(new) + : "memory"); + return oldval; +} + +unsigned int flag = 3; +unsigned long m = 5, n = 1; + +int main(void) +{ + cmpwait(&flag, 3); + __CPROVER_assert(flag == 3, "cmpwait does not write"); + + __CPROVER_assert(cmpxchg(&m, 5, 7) == 5, "cmpxchg returns the old value"); + __CPROVER_assert(m == 7, "cmpxchg stores if equal"); + __CPROVER_assert(cmpxchg(&m, 3, 9) == 7, "cmpxchg returns the value"); + __CPROVER_assert(m == 7, "cmpxchg does not store if different"); + + // a store between the load-exclusive and the store-exclusive + unsigned long t; + unsigned int status; + __asm__ volatile( + "ldxr %0, [%2]\n" + " str %0, [%3]\n" + " stxr %w1, %4, [%2]" + : "=&r"(t), "=&r"(status) + : "r"(&m), "r"(&n), "r"(8ul) + : "memory"); + __CPROVER_assert(n == 7, "plain store"); + __CPROVER_assert((status == 0) == (m == 8), "status matches the store"); + __CPROVER_assert(status == 0, "store-exclusive succeeds"); // fails + __CPROVER_assert(status == 1, "store-exclusive fails"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_exclusive_abandoned/test.desc b/regression/cbmc/asm_aarch64_exclusive_abandoned/test.desc new file mode 100644 index 000000000000..75a8017a50f1 --- /dev/null +++ b/regression/cbmc/asm_aarch64_exclusive_abandoned/test.desc @@ -0,0 +1,21 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 2 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 49 cmpwait does not write: SUCCESS$ +^\[main\.assertion\.2\] line 51 cmpxchg returns the old value: SUCCESS$ +^\[main\.assertion\.3\] line 52 cmpxchg stores if equal: SUCCESS$ +^\[main\.assertion\.4\] line 53 cmpxchg returns the value: SUCCESS$ +^\[main\.assertion\.5\] line 54 cmpxchg does not store if different: SUCCESS$ +^\[main\.assertion\.6\] line 66 plain store: SUCCESS$ +^\[main\.assertion\.7\] line 67 status matches the store: SUCCESS$ +^\[main\.assertion\.8\] line 68 store-exclusive succeeds: FAILURE$ +^\[main\.assertion\.9\] line 69 store-exclusive fails: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +The statements are interpreted. On qemu-aarch64, the store-exclusive after the +plain store succeeds; the architecture permits it to fail. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 5bfe7b1f7a48..165266018509 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -585,11 +585,7 @@ exprt asm_aarch64_semanticst::read( return typecast_exprt::conditional_cast(operand.value, bv(width)); case a64_operandt::kindt::MEMORY: - if(ctx.exclusive_open()) - { - ctx.fail("memory access between load-exclusive and store-exclusive"); - return ctx.nondet(bv(width)); - } + ctx.abandon_exclusive(); if(operand.lvalue.is_not_nil() && operand.natural_width == width) return ctx.to_bits(operand.lvalue, width); return ctx.memory(operand.address, width); @@ -618,9 +614,7 @@ bool asm_aarch64_semanticst::write( return true; case a64_operandt::kindt::MEMORY: - if(ctx.exclusive_open()) - return ctx.fail( - "memory access between load-exclusive and store-exclusive"); + ctx.abandon_exclusive(); if(operand.lvalue.is_not_nil() && operand.natural_width == width) { ctx.assign( diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 909e5870445a..a5faced06596 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -716,9 +716,9 @@ bool asm_lowering_contextt::prepare( void asm_lowering_contextt::define_label(const std::string &name) { - // a jump into an exclusive access region would bypass its start - if(exclusive_open()) - fail("label between load-exclusive and store-exclusive"); + // a jump to the label would bypass the start of an open exclusive access + // region + abandon_exclusive(); // a branch to the label may skip the instruction that cleared the // exclusive monitor monitor_cleared = false; @@ -752,8 +752,9 @@ bool asm_lowering_contextt::branch( const exprt &condition) { note_reads(condition); - if(exclusive_open()) - return fail("branch between load-exclusive and store-exclusive"); + // the atomic section of an exclusive access region cannot extend to the + // branch target + abandon_exclusive(); if(target.kind == asm_tokent::kindt::C_LABEL) { diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index 914eb96dc2e1..6ef79423e3ca 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -130,6 +130,8 @@ class asm_lowering_contextt /// between, by a store-exclusive is modeled as an atomic section that /// spans both instructions. The store-exclusive succeeds /// nondeterministically (the architecture permits spurious failures). + /// Another memory access, branch, or label abandons the region (see + /// \ref abandon_exclusive). /// \{ /// Start an exclusive access region at the current instruction (a @@ -146,6 +148,17 @@ class asm_lowering_contextt /// store-exclusive), which makes the region an atomic section. void end_exclusive(); + /// End the open exclusive access region, if any, without making it an + /// atomic section, at another memory access, a branch, or a label: the + /// architecture does not guarantee the reservation then, or a branch may + /// bypass the load-exclusive. The load-exclusive is a plain load, and a + /// later store-exclusive succeeds or fails nondeterministically, without + /// being atomic with the load. + void abandon_exclusive() + { + exclusive_start.reset(); + } + /// The exclusive monitor is cleared (by `clrex`, or by a /// store-exclusive): a later store-exclusive fails, unless a label (which /// a branch may reach with the monitor set) or a load-exclusive comes From 9253e0ce097a5afcc050309e2978ea70224432d4 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:19:24 +0000 Subject: [PATCH 070/100] AArch64 inline assembly: remove unused using-declarations 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 --- src/assembler/asm_aarch64.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 165266018509..bc65fd0ee3bb 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -26,17 +26,10 @@ Author: Michael Tautschnig #include #include -using asm_bv::bool_to_bv; -using asm_bv::borrow_sub; using asm_bv::bv; -using asm_bv::carry_add; using asm_bv::constant; -using asm_bv::even_parity_low_byte; using asm_bv::extract; using asm_bv::is_zero; -using asm_bv::msb; -using asm_bv::overflow_add; -using asm_bv::overflow_sub; using asm_bv::replace_bits; using asm_bv::resize; using asm_bv::sign_extend; From 7354c9a777b5a274a18ff569021f8c2b0f6c597b Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:25:01 +0000 Subject: [PATCH 071/100] AArch64 inline assembly: test data processing and memory accesses 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 --- regression/cbmc/asm_aarch64_alu/main.c | 451 +++++++++++++++++++ regression/cbmc/asm_aarch64_alu/test.desc | 17 + regression/cbmc/asm_aarch64_memory/main.c | 306 +++++++++++++ regression/cbmc/asm_aarch64_memory/test.desc | 16 + 4 files changed, 790 insertions(+) create mode 100644 regression/cbmc/asm_aarch64_alu/main.c create mode 100644 regression/cbmc/asm_aarch64_alu/test.desc create mode 100644 regression/cbmc/asm_aarch64_memory/main.c create mode 100644 regression/cbmc/asm_aarch64_memory/test.desc diff --git a/regression/cbmc/asm_aarch64_alu/main.c b/regression/cbmc/asm_aarch64_alu/main.c new file mode 100644 index 000000000000..af2fd57bb9a6 --- /dev/null +++ b/regression/cbmc/asm_aarch64_alu/main.c @@ -0,0 +1,451 @@ +// AArch64 data processing, condition codes, and branches, each compared with +// a C reference on concrete inputs. All assertions hold on qemu-aarch64. +typedef unsigned long u64; +typedef unsigned int u32; + +static u64 mk_nzcv(int n, int z, int c, int v) +{ + return ((u64)n << 31) | ((u64)z << 30) | ((u64)c << 29) | ((u64)v << 28); +} + +static u64 mask_of(int w) +{ + return w == 64 ? ~0ul : ((1ul << w) - 1); +} + +// the flags computed by the last call of ref_add, ref_sub, or ref_logic +static u64 ref_flags; + +// a + b in w bits, with the flags of adds +static u64 ref_add(u64 a, u64 b, int w) +{ + u64 m = mask_of(w); + a &= m; + b &= m; + u64 r = (a + b) & m; + int c = r < a; + int v = (((a ^ r) & (b ^ r)) >> (w - 1)) & 1; + ref_flags = mk_nzcv((r >> (w - 1)) & 1, r == 0, c, v); + return r; +} + +// a - b in w bits, with the flags of subs +static u64 ref_sub(u64 a, u64 b, int w) +{ + u64 m = mask_of(w); + a &= m; + b &= m; + u64 r = (a - b) & m; + int c = a >= b; + int v = (((a ^ b) & (a ^ r)) >> (w - 1)) & 1; + ref_flags = mk_nzcv((r >> (w - 1)) & 1, r == 0, c, v); + return r; +} + +static u64 ref_logic(u64 r, int w) +{ + r &= mask_of(w); + ref_flags = mk_nzcv((r >> (w - 1)) & 1, r == 0, 0, 0); + return r; +} + +// the flags read by mrs after the last FLAGOP function +static u64 asm_flags; + +// the result and the flags (via mrs) of an instruction +#define FLAGOP(name, insn) \ + static u64 name(u64 a, u64 b) \ + { \ + u64 r, g; \ + __asm__(insn "\n mrs %1, nzcv" \ + : "=&r"(r), "=&r"(g) \ + : "r"(a), "r"(b) \ + : "cc"); \ + asm_flags = g; \ + return r; \ + } + +FLAGOP(adds_x, "adds %0, %2, %3") +FLAGOP(adds_w, "adds %w0, %w2, %w3") +FLAGOP(subs_x, "subs %0, %2, %3") +FLAGOP(subs_w, "subs %w0, %w2, %w3") +FLAGOP(adds_x_lsl, "adds %0, %2, %3, lsl #7") +FLAGOP(subs_w_asr, "subs %w0, %w2, %w3, asr #5") +FLAGOP(subs_imm, "subs %w0, %w2, #4095") +FLAGOP(adds_imm_neg, "adds %w0, %w2, #-1") +FLAGOP(cmp_x, "cmp %2, %3\n mov %0, #0") +FLAGOP(cmp_w, "cmp %w2, %w3\n mov %0, #0") +FLAGOP(cmp_imm_neg, "cmp %2, #-5\n mov %0, #0") +FLAGOP(cmn_x, "cmn %2, %3\n mov %0, #0") +FLAGOP(cmn_w, "cmn %w2, %w3\n mov %0, #0") +FLAGOP(negs_x, "negs %0, %3") +FLAGOP(negs_w, "negs %w0, %w3") +FLAGOP(ands_w, "ands %w0, %w2, %w3, lsl #3") +FLAGOP(bics_x, "bics %0, %2, %3") +FLAGOP(tst_x, "tst %2, %3\n mov %0, #0") + +#define CHECKFLAG(name, refexpr) \ + do \ + { \ + u64 r1 = name(a, b); \ + u64 r2 = refexpr; \ + __CPROVER_assert(r1 == r2 && asm_flags == ref_flags, #name); \ + } while(0) + +static void check_flags(u64 a, u64 b) +{ + CHECKFLAG(adds_x, ref_add(a, b, 64)); + CHECKFLAG(adds_w, ref_add(a, b, 32)); + CHECKFLAG(subs_x, ref_sub(a, b, 64)); + CHECKFLAG(subs_w, ref_sub(a, b, 32)); + CHECKFLAG(adds_x_lsl, ref_add(a, b << 7, 64)); + CHECKFLAG(subs_w_asr, ref_sub(a, (u64)(u32)((int)(u32)b >> 5), 32)); + CHECKFLAG(subs_imm, ref_sub(a, 4095, 32)); + CHECKFLAG(adds_imm_neg, ref_add(a, 0xffffffff, 32)); + CHECKFLAG(cmp_x, (ref_sub(a, b, 64), 0)); + CHECKFLAG(cmp_w, (ref_sub(a, b, 32), 0)); + CHECKFLAG(cmp_imm_neg, (ref_add(a, 5, 64), 0)); + CHECKFLAG(cmn_x, (ref_add(a, b, 64), 0)); + CHECKFLAG(cmn_w, (ref_add(a, b, 32), 0)); + CHECKFLAG(negs_x, ref_sub(0, b, 64)); + CHECKFLAG(negs_w, ref_sub(0, b, 32)); + CHECKFLAG(ands_w, ref_logic(a & (b << 3), 32)); + CHECKFLAG(bics_x, ref_logic(a & ~b, 64)); + CHECKFLAG(tst_x, (ref_logic(a & b, 64), 0)); +} + +// condition codes: cset after cmp, csetm after cmn, b.cond, and flag outputs +static int ref_cond(int cc, u64 f) +{ + int n = (f >> 31) & 1, z = (f >> 30) & 1, c = (f >> 29) & 1, + v = (f >> 28) & 1; + switch(cc) + { + case 0: + return z; + case 1: + return !z; + case 2: + return c; + case 3: + return !c; + case 4: + return n; + case 5: + return !n; + case 6: + return v; + case 7: + return !v; + case 8: + return c && !z; + case 9: + return !c || z; + case 10: + return n == v; + case 11: + return n != v; + case 12: + return !z && n == v; + default: + return z || n != v; + } +} + +#define COND(cc, idx) \ + static u64 cset_##cc(u64 a, u64 b) \ + { \ + u64 r; \ + __asm__("cmp %1, %2\n cset %0, " #cc : "=r"(r) : "r"(a), "r"(b) : "cc"); \ + return r; \ + } \ + static u64 csetm_##cc(u64 a, u64 b) \ + { \ + u64 r; \ + __asm__("cmn %w1, %w2\n csetm %w0, " #cc \ + : "=r"(r) \ + : "r"(a), "r"(b) \ + : "cc"); \ + return r; \ + } \ + static u64 bcc_##cc(u64 a, u64 b) \ + { \ + u64 r; \ + __asm__("subs %0, %1, %2\n mov %0, #1\n b." #cc " 1f\n mov %0, #0\n1:" \ + : "=&r"(r) \ + : "r"(a), "r"(b) \ + : "cc"); \ + return r; \ + } \ + static int flag_output_##cc(u64 a, u64 b) \ + { \ + int r; \ + __asm__("cmp %1, %2" : "=@cc" #cc(r) : "r"(a), "r"(b)); \ + return r; \ + } \ + static void check_cond_##cc(u64 a, u64 b) \ + { \ + ref_sub(a, b, 64); \ + u64 f = ref_flags; \ + ref_add(a, b, 32); \ + u64 g = ref_flags; \ + __CPROVER_assert(cset_##cc(a, b) == (u64)ref_cond(idx, f), "cset " #cc); \ + __CPROVER_assert( \ + csetm_##cc(a, b) == (ref_cond(idx, g) ? 0xfffffffful : 0), \ + "csetm " #cc); \ + __CPROVER_assert(bcc_##cc(a, b) == (u64)ref_cond(idx, f), "b." #cc); \ + __CPROVER_assert(flag_output_##cc(a, b) == ref_cond(idx, f), "@cc" #cc); \ + } + +COND(eq, 0) +COND(ne, 1) +COND(hs, 2) +COND(lo, 3) +COND(mi, 4) +COND(pl, 5) +COND(vs, 6) +COND(vc, 7) +COND(hi, 8) +COND(ls, 9) +COND(ge, 10) +COND(lt, 11) +COND(gt, 12) +COND(le, 13) + +static void check_conds(u64 a, u64 b) +{ + check_cond_eq(a, b); + check_cond_ne(a, b); + check_cond_hs(a, b); + check_cond_lo(a, b); + check_cond_mi(a, b); + check_cond_pl(a, b); + check_cond_vs(a, b); + check_cond_vc(a, b); + check_cond_hi(a, b); + check_cond_ls(a, b); + check_cond_ge(a, b); + check_cond_lt(a, b); + check_cond_gt(a, b); + check_cond_le(a, b); +} + +// conditional selects +#define CSELOP(name, insn) \ + static u64 name(u64 a, u64 b, u64 c, u64 d) \ + { \ + u64 r; \ + __asm__("cmp %1, %2\n" insn \ + : "=&r"(r) \ + : "r"(a), "r"(b), "r"(c), "r"(d) \ + : "cc"); \ + return r; \ + } + +CSELOP(csel_gt, "csel %0, %3, %4, gt") +CSELOP(csinc_lt, "csinc %0, %3, %4, lt") +CSELOP(csinv_w_hi, "csinv %w0, %w3, %w4, hi") +CSELOP(csneg_ls, "csneg %0, %3, %4, ls") +CSELOP(csneg_w_eq, "csneg %w0, %w3, %w4, eq") +CSELOP(csinc_nv, "csinc %0, %3, %4, nv") +CSELOP(csetm_x_vs, "csetm %0, vs") + +static void check_csel(u64 a, u64 b, u64 c, u64 d) +{ + ref_sub(a, b, 64); + u64 f = ref_flags; + __CPROVER_assert(csel_gt(a, b, c, d) == (ref_cond(12, f) ? c : d), "csel gt"); + __CPROVER_assert( + csinc_lt(a, b, c, d) == (ref_cond(11, f) ? c : d + 1), "csinc lt"); + __CPROVER_assert( + csinv_w_hi(a, b, c, d) == (u64)(u32)(ref_cond(8, f) ? c : ~d), + "csinv w hi"); + __CPROVER_assert( + csneg_ls(a, b, c, d) == (ref_cond(9, f) ? c : -d), "csneg ls"); + __CPROVER_assert( + csneg_w_eq(a, b, c, d) == (u64)(u32)(ref_cond(0, f) ? c : -d), + "csneg w eq"); + __CPROVER_assert(csinc_nv(a, b, c, d) == c, "csinc nv"); + __CPROVER_assert( + csetm_x_vs(a, b, c, d) == (ref_cond(6, f) ? ~0ul : 0), "csetm x vs"); +} + +// shifts, rotates, and moves +#define BINOP(name, insn) \ + static u64 name(u64 a, u64 b) \ + { \ + u64 r; \ + __asm__(insn : "=&r"(r) : "r"(a), "r"(b)); \ + return r; \ + } + +BINOP(lsl_x, "lsl %0, %1, %2") +BINOP(lsr_x, "lsr %0, %1, %2") +BINOP(asr_x, "asr %0, %1, %2") +BINOP(ror_x, "ror %0, %1, %2") +BINOP(lsl_w, "lsl %w0, %w1, %w2") +BINOP(lsr_w, "lsr %w0, %w1, %w2") +BINOP(asr_w, "asr %w0, %w1, %w2") +BINOP(ror_w, "ror %w0, %w1, %w2") +BINOP(ror_x_imm, "ror %0, %1, #13") +BINOP(ror_w_imm, "ror %w0, %w1, #31") +BINOP(asr_x_imm, "asr %0, %1, #63") +BINOP(asr_w_imm, "asr %w0, %w1, #7") +BINOP(orn_x, "orn %0, %1, %2, lsr #3") +BINOP(bic_w, "bic %w0, %w1, %w2, asr #2") +BINOP(mvn_w, "mvn %w0, %w1") +BINOP(mvn_x, "mvn %0, %2") +BINOP(neg_x, "neg %0, %1") +BINOP(neg_w, "neg %w0, %w1") +BINOP(movk_x, "mov %0, %1\n movk %0, #0xbeef, lsl #32") +BINOP(movn_x, "movn %0, #0x1234, lsl #48") +BINOP(movn_w, "movn %w0, #0x1234, lsl #16") +BINOP(movz_w, "mov %0, %1\n movz %w0, #0xffff") + +static u64 ror64(u64 x, unsigned n) +{ + n &= 63; + return n ? (x >> n) | (x << (64 - n)) : x; +} + +static u32 ror32(u32 x, unsigned n) +{ + n &= 31; + return n ? (x >> n) | (x << (32 - n)) : x; +} + +static void check_shifts(u64 a, u64 b) +{ + __CPROVER_assert(lsl_x(a, b) == a << (b & 63), "lsl x"); + __CPROVER_assert(lsr_x(a, b) == a >> (b & 63), "lsr x"); + __CPROVER_assert(asr_x(a, b) == (u64)((long)a >> (b & 63)), "asr x"); + __CPROVER_assert(ror_x(a, b) == ror64(a, b), "ror x"); + __CPROVER_assert(lsl_w(a, b) == (u64)(u32)((u32)a << (b & 31)), "lsl w"); + __CPROVER_assert(lsr_w(a, b) == (u64)((u32)a >> (b & 31)), "lsr w"); + __CPROVER_assert(asr_w(a, b) == (u64)(u32)((int)(u32)a >> (b & 31)), "asr w"); + __CPROVER_assert(ror_w(a, b) == (u64)ror32((u32)a, b), "ror w"); + __CPROVER_assert(ror_x_imm(a, b) == ror64(a, 13), "ror x imm"); + __CPROVER_assert(ror_w_imm(a, b) == (u64)ror32((u32)a, 31), "ror w imm"); + __CPROVER_assert(asr_x_imm(a, b) == (u64)((long)a >> 63), "asr x imm"); + __CPROVER_assert( + asr_w_imm(a, b) == (u64)(u32)((int)(u32)a >> 7), "asr w imm"); + __CPROVER_assert(orn_x(a, b) == (a | ~(b >> 3)), "orn x"); + __CPROVER_assert( + bic_w(a, b) == (u64)(u32)(a & ~(u32)((int)(u32)b >> 2)), "bic w"); + __CPROVER_assert(mvn_w(a, b) == (u64)(u32)~a, "mvn w"); + __CPROVER_assert(mvn_x(a, b) == ~b, "mvn x"); + __CPROVER_assert(neg_x(a, b) == -a, "neg x"); + __CPROVER_assert(neg_w(a, b) == (u64)(u32)-a, "neg w"); + __CPROVER_assert( + movk_x(a, b) == ((a & ~0xffff00000000ul) | 0xbeef00000000ul), "movk x"); + __CPROVER_assert(movn_x(a, b) == ~0x1234000000000000ul, "movn x"); + __CPROVER_assert(movn_w(a, b) == (u64)(u32)~0x12340000u, "movn w"); + __CPROVER_assert(movz_w(a, b) == 0xffff, "movz w"); +} + +// branches on registers +#define BRANCH(name, insn) \ + static u64 name(u64 a) \ + { \ + u64 r; \ + __asm__("mov %0, #1\n " insn " 1f\n mov %0, #0\n1:" : "=&r"(r) : "r"(a)); \ + return r; \ + } + +BRANCH(cbz_w, "cbz %w1,") +BRANCH(cbnz_x, "cbnz %1,") +BRANCH(tbz_63, "tbz %1, #63,") +BRANCH(tbnz_31, "tbnz %w1, #31,") +BRANCH(tbnz_40, "tbnz %1, #40,") +BRANCH(tbz_0, "tbz %w1, #0,") + +static void check_branches(u64 a) +{ + __CPROVER_assert(cbz_w(a) == ((u32)a == 0), "cbz w"); + __CPROVER_assert(cbnz_x(a) == (a != 0), "cbnz x"); + __CPROVER_assert(tbz_63(a) == !((a >> 63) & 1), "tbz 63"); + __CPROVER_assert(tbnz_31(a) == ((a >> 31) & 1), "tbnz 31"); + __CPROVER_assert(tbnz_40(a) == ((a >> 40) & 1), "tbnz 40"); + __CPROVER_assert(tbz_0(a) == !(a & 1), "tbz 0"); +} + +// asm goto +static int lt_signed(u64 a, u64 b) +{ + __asm__ goto("cmp %0, %1\n b.lt %l[yes]" : : "r"(a), "r"(b) : "cc" : yes); + return 0; +yes: + return 1; +} + +static int classify(u64 a) +{ + __asm__ goto("cbz %0, %l[zero]\n tbnz %0, #63, %l[negative]" + : + : "r"(a) + : + : zero, negative); + return 2; +zero: + return 0; +negative: + return 1; +} + +static void check_asm_goto(u64 a, u64 b) +{ + __CPROVER_assert(lt_signed(a, b) == ((long)a < (long)b), "b.lt to C label"); + __CPROVER_assert( + classify(a) == (a == 0 ? 0 + : (long)a < 0 ? 1 + : 2), + "cbz, tbnz to C labels"); +} + +int main(void) +{ + // carry, overflow, zero, and negative results in 64 and 32 bits + check_flags(5, 7); + check_flags(0x7ffffffffffffffful, 1); + check_flags(0xfffffffffffffffful, 1); + check_flags(0x8000000000000000ul, 0x8000000000000000ul); + check_flags(0, 1); + check_flags(0, 0); + check_flags(1, 0x8000000000000000ul); + check_flags(0x7fffffff, 1); + check_flags(0xffffffff, 0x80000001); + check_flags(0x80000000, 1); + check_flags(0xfffffffffffffffbul, 0x00000000fffffffful); + + // each condition holds for some of the inputs and fails for others + check_conds(5, 7); + check_conds(7, 5); + check_conds(5, 5); + check_conds(0x8000000000000000ul, 1); + check_conds(1, 0x8000000000000000ul); + check_conds(0x7fffffff, 1); + + check_csel(5, 7, 0x1234, 0x8000000000000001ul); + check_csel(7, 5, 0x1234, 0x8000000000000001ul); + check_csel(5, 5, 0x1234, 0x8000000000000001ul); + check_csel(0x8000000000000000ul, 1, 0xfffffffffffffffful, 3); + check_csel(1, 0x8000000000000000ul, 0xfffffffffffffffful, 3); + + check_shifts(0x8000000000000001ul, 0); + check_shifts(0xf0f0f0f08f0f0f0ful, 1); + check_shifts(0xf0f0f0f08f0f0f0ful, 31); + check_shifts(0x8000000000000001ul, 32); + check_shifts(0x7ffffffffffffffful, 63); + check_shifts(0x123456789abcdef0ul, 65); + + check_branches(0); + check_branches(0x8000000000000000ul); + check_branches(0x80000000); + check_branches(0x10000000001ul); + + check_asm_goto(0, 1); + check_asm_goto(0x8000000000000000ul, 0x7ffffffffffffffful); + check_asm_goto(5, 3); + + return 0; +} diff --git a/regression/cbmc/asm_aarch64_alu/test.desc b/regression/cbmc/asm_aarch64_alu/test.desc new file mode 100644 index 000000000000..7e8f73a76f99 --- /dev/null +++ b/regression/cbmc/asm_aarch64_alu/test.desc @@ -0,0 +1,17 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +Covers the C and V flags of adds, subs, cmp, cmn, and negs, all condition +codes (cset, csetm, b.cond, =@cc outputs), the conditional selects, shifts +and rotates, mvn, movn, movk, movz, neg, cbz, cbnz, tbz, tbnz, and asm goto. +The assertions compare each statement with a C reference; they all hold when +main.c is compiled with clang -O1 --target=aarch64-linux-gnu -march=armv8.4-a +(with __CPROVER_assert defined to check its condition) and run on +qemu-aarch64 -cpu max. diff --git a/regression/cbmc/asm_aarch64_memory/main.c b/regression/cbmc/asm_aarch64_memory/main.c new file mode 100644 index 000000000000..920fa29ec655 --- /dev/null +++ b/regression/cbmc/asm_aarch64_memory/main.c @@ -0,0 +1,306 @@ +// AArch64 loads, stores, and atomics, each compared with a C reference on +// concrete inputs. All assertions hold on qemu-aarch64. +typedef unsigned long u64; +typedef unsigned int u32; + +u64 buf[2]; +u64 expected[2]; + +static u64 mask_of(int w) +{ + return w == 64 ? ~0ul : ((1ul << w) - 1); +} + +// the size bytes at byte offset off of buf, sign-extended if sgn +static u64 rd(int off, int size, int sgn) +{ + u64 v = buf[off / 8] >> ((off % 8) * 8); + if(size < 8) + { + v &= mask_of(size * 8); + if(sgn && ((v >> (size * 8 - 1)) & 1)) + v |= ~0ul << (size * 8); + } + return v; +} + +#define LD(name, insn) \ + static u64 name(u64 *p) \ + { \ + u64 r; \ + __asm__ volatile(insn : "=&r"(r) : "r"(p) : "memory"); \ + return r; \ + } + +LD(ldrb_w, "mov %0, #-1\n ldrb %w0, [%1, #1]") +LD(ldrh_w, "mov %0, #-1\n ldrh %w0, [%1, #2]") +LD(ldrsb_w, "mov %0, #-1\n ldrsb %w0, [%1, #3]") +LD(ldrsb_x, "ldrsb %0, [%1, #7]") +LD(ldrsh_w, "mov %0, #-1\n ldrsh %w0, [%1, #6]") +LD(ldrsh_x, "ldrsh %0, [%1, #4]") +LD(ldrsw_x, "ldrsw %0, [%1, #4]") +LD(ldr_w, "mov %0, #-1\n ldr %w0, [%1, #4]") +LD(ldr_x, "ldr %0, [%1, #8]") +LD(ldur_x, "add %0, %1, #12\n ldur %0, [%0, #-4]") +LD(ldurb_w, "add %0, %1, #9\n ldurb %w0, [%0, #-2]") +LD(ldurh_w, "ldurh %w0, [%1, #3]") +LD(ldar_w, "ldar %w0, [%1]") +LD(ldar_x, "ldar %0, [%1]") +LD(ldarb, "ldarb %w0, [%1]") +LD(ldarh, "ldarh %w0, [%1]") +LD(ldapr_x, "ldapr %0, [%1]") +LD(ldxrb, "ldxrb %w0, [%1]\n clrex") +LD(ldaxrh, "ldaxrh %w0, [%1]\n clrex") + +static void check_loads(void) +{ + __CPROVER_assert(ldrb_w(buf) == rd(1, 1, 0), "ldrb w"); + __CPROVER_assert(ldrh_w(buf) == rd(2, 2, 0), "ldrh w"); + __CPROVER_assert(ldrsb_w(buf) == (u32)rd(3, 1, 1), "ldrsb w"); + __CPROVER_assert(ldrsb_x(buf) == rd(7, 1, 1), "ldrsb x"); + __CPROVER_assert(ldrsh_w(buf) == (u32)rd(6, 2, 1), "ldrsh w"); + __CPROVER_assert(ldrsh_x(buf) == rd(4, 2, 1), "ldrsh x"); + __CPROVER_assert(ldrsw_x(buf) == rd(4, 4, 1), "ldrsw x"); + __CPROVER_assert(ldr_w(buf) == rd(4, 4, 0), "ldr w"); + __CPROVER_assert(ldr_x(buf) == rd(8, 8, 0), "ldr x"); + __CPROVER_assert(ldur_x(buf) == rd(8, 8, 0), "ldur x"); + __CPROVER_assert(ldurb_w(buf) == rd(7, 1, 0), "ldurb w"); + __CPROVER_assert(ldurh_w(buf) == rd(3, 2, 0), "ldurh w"); + __CPROVER_assert(ldar_w(buf) == rd(0, 4, 0), "ldar w"); + __CPROVER_assert(ldar_x(buf + 1) == rd(8, 8, 0), "ldar x"); + __CPROVER_assert(ldarb(buf) == rd(0, 1, 0), "ldarb"); + __CPROVER_assert(ldarh(buf + 1) == rd(8, 2, 0), "ldarh"); + __CPROVER_assert(ldapr_x(buf) == rd(0, 8, 0), "ldapr x"); + __CPROVER_assert(ldxrb(buf) == rd(0, 1, 0), "ldxrb"); + __CPROVER_assert(ldaxrh(buf) == rd(0, 2, 0), "ldaxrh"); +} + +#define ST(name, insn) \ + static void name(u64 *p, u64 v) \ + { \ + __asm__ volatile(insn : : "r"(p), "r"(v) : "memory"); \ + } + +ST(strb_w, "strb %w1, [%0, #3]") +ST(strh_w, "strh %w1, [%0, #6]") +ST(str_w, "str %w1, [%0, #4]") +ST(str_x, "str %1, [%0, #8]") +ST(stlr_x, "stlr %1, [%0]") +ST(stlr_w, "stlr %w1, [%0]") +ST(stlrb, "stlrb %w1, [%0]") +ST(stlrh, "stlrh %w1, [%0]") +ST(stur_w, "stur %w1, [%0, #-4]") +ST(sturb, "sturb %w1, [%0, #-1]") +ST(sturh, "sturh %w1, [%0, #5]") + +// the st forms of the LSE atomics do not return the old value +ST(stadd_x, "stadd %1, [%0]") +ST(staddlb, "staddlb %w1, [%0]") +ST(stclrh, "stclrh %w1, [%0]") +ST(steor_w, "steor %w1, [%0]") +ST(stsetlb, "stsetlb %w1, [%0]") +ST(stsmaxlh, "stsmaxlh %w1, [%0]") +ST(stsmin_x, "stsmin %1, [%0]") +ST(stumaxb, "stumaxb %w1, [%0]") +ST(stuminl_w, "stuminl %w1, [%0]") + +// LSE atomics: the old value is returned, the new value is in memory +#define LSE(name, insn) \ + static u64 name(u64 *p, u64 v) \ + { \ + u64 old; \ + __asm__ volatile(insn : "=&r"(old) : "r"(p), "r"(v) : "memory"); \ + return old; \ + } + +LSE(ldadd_x, "ldadd %2, %0, [%1]") +LSE(ldaddal_w, "ldaddal %w2, %w0, [%1]") +LSE(ldaddb, "ldaddb %w2, %w0, [%1]") +LSE(ldaddlh, "ldaddlh %w2, %w0, [%1]") +LSE(ldclra_x, "ldclra %2, %0, [%1]") +LSE(ldclrb, "ldclrb %w2, %w0, [%1]") +LSE(ldeorlh, "ldeorlh %w2, %w0, [%1]") +LSE(ldeorab, "ldeorab %w2, %w0, [%1]") +LSE(ldsetb, "ldsetb %w2, %w0, [%1]") +LSE(ldseth, "ldseth %w2, %w0, [%1]") +LSE(ldsmax_x, "ldsmax %2, %0, [%1]") +LSE(ldsmaxb, "ldsmaxb %w2, %w0, [%1]") +LSE(ldsminal_w, "ldsminal %w2, %w0, [%1]") +LSE(ldsminah, "ldsminah %w2, %w0, [%1]") +LSE(ldumax_w, "ldumax %w2, %w0, [%1]") +LSE(ldumaxb, "ldumaxb %w2, %w0, [%1]") +LSE(lduminl_x, "lduminl %2, %0, [%1]") +LSE(lduminh, "lduminh %w2, %w0, [%1]") +LSE(swpal_x, "swpal %2, %0, [%1]") +LSE(swph, "swph %w2, %w0, [%1]") +LSE(swpb, "swpb %w2, %w0, [%1]") + +// cas: Rs is compared with memory and receives the old value +#define CAS(name, insn) \ + static u64 name(u64 *p, u64 cmp, u64 nv) \ + { \ + __asm__ volatile(insn : "+&r"(cmp) : "r"(p), "r"(nv) : "memory"); \ + return cmp; \ + } + +CAS(casal_x, "casal %0, %2, [%1]") +CAS(cas_w, "cas %w0, %w2, [%1]") +CAS(casab, "casab %w0, %w2, [%1]") +CAS(caslh, "caslh %w0, %w2, [%1]") +CAS(casb, "casb %w0, %w2, [%1]") + +// replace the size bytes at byte offset off of expected by v +static void wr(int off, int size, u64 v) +{ + u64 m = mask_of(size * 8) << ((off % 8) * 8); + expected[off / 8] = (expected[off / 8] & ~m) | ((v << ((off % 8) * 8)) & m); +} + +#define CHECK_STORE(call, off, size, v, msg) \ + do \ + { \ + expected[0] = buf[0]; \ + expected[1] = buf[1]; \ + call; \ + wr(off, size, v); \ + __CPROVER_assert(buf[0] == expected[0] && buf[1] == expected[1], msg); \ + } while(0) + +static void check_stores(u64 v) +{ + CHECK_STORE(strb_w(buf, v), 3, 1, v, "strb w"); + CHECK_STORE(strh_w(buf, v), 6, 2, v, "strh w"); + CHECK_STORE(str_w(buf, v), 4, 4, v, "str w"); + CHECK_STORE(str_x(buf, v), 8, 8, v, "str x"); + CHECK_STORE(stlr_x(buf + 1, ~v), 8, 8, ~v, "stlr x"); + CHECK_STORE(stlr_w(buf, v), 0, 4, v, "stlr w"); + CHECK_STORE(stlrb(buf + 1, v), 8, 1, v, "stlrb"); + CHECK_STORE(stlrh(buf + 1, ~v), 8, 2, ~v, "stlrh"); + CHECK_STORE(stur_w(buf + 1, v), 4, 4, v, "stur w"); + CHECK_STORE(sturb(buf + 1, ~v), 7, 1, ~v, "sturb"); + CHECK_STORE(sturh(buf, v), 5, 2, v, "sturh"); +} + +static u64 smax(u64 a, u64 b, int w) +{ + long sa = (long)(a << (64 - w)) >> (64 - w), + sb = (long)(b << (64 - w)) >> (64 - w); + return sa >= sb ? a : b; +} + +static u64 smin(u64 a, u64 b, int w) +{ + long sa = (long)(a << (64 - w)) >> (64 - w), + sb = (long)(b << (64 - w)) >> (64 - w); + return sa <= sb ? a : b; +} + +// the old value o and the operand a, both of w bits, determine the new value +// new_value of the w bits of buf[0] +#define LSECHECK(fn, w, new_value) \ + do \ + { \ + u64 m = mask_of(w); \ + u64 before = buf[0]; \ + u64 o = before & m, a = v & m; \ + u64 got = fn(buf, v); \ + u64 want = (before & ~m) | (m & (new_value)); \ + __CPROVER_assert(got == o && buf[0] == want, #fn); \ + buf[0] = before; \ + } while(0) + +static void check_lse(u64 v) +{ + LSECHECK(ldadd_x, 64, o + a); + LSECHECK(ldaddal_w, 32, o + a); + LSECHECK(ldaddb, 8, o + a); + LSECHECK(ldaddlh, 16, o + a); + LSECHECK(ldclra_x, 64, o & ~a); + LSECHECK(ldclrb, 8, o & ~a); + LSECHECK(ldeorlh, 16, o ^ a); + LSECHECK(ldeorab, 8, o ^ a); + LSECHECK(ldsetb, 8, o | a); + LSECHECK(ldseth, 16, o | a); + LSECHECK(ldsmax_x, 64, smax(o, a, 64)); + LSECHECK(ldsmaxb, 8, smax(o, a, 8)); + LSECHECK(ldsminal_w, 32, smin(o, a, 32)); + LSECHECK(ldsminah, 16, smin(o, a, 16)); + LSECHECK(ldumax_w, 32, o >= a ? o : a); + LSECHECK(ldumaxb, 8, o >= a ? o : a); + LSECHECK(lduminl_x, 64, o <= a ? o : a); + LSECHECK(lduminh, 16, o <= a ? o : a); + LSECHECK(swpal_x, 64, a); + LSECHECK(swph, 16, a); + LSECHECK(swpb, 8, a); +} + +#define STCHECK(fn, w, new_value) \ + do \ + { \ + u64 m = mask_of(w); \ + u64 before = buf[0]; \ + u64 o = before & m, a = v & m; \ + fn(buf, v); \ + __CPROVER_assert(buf[0] == ((before & ~m) | (m & (new_value))), #fn); \ + buf[0] = before; \ + } while(0) + +static void check_lse_st(u64 v) +{ + STCHECK(stadd_x, 64, o + a); + STCHECK(staddlb, 8, o + a); + STCHECK(stclrh, 16, o & ~a); + STCHECK(steor_w, 32, o ^ a); + STCHECK(stsetlb, 8, o | a); + STCHECK(stsmaxlh, 16, smax(o, a, 16)); + STCHECK(stsmin_x, 64, smin(o, a, 64)); + STCHECK(stumaxb, 8, o >= a ? o : a); + STCHECK(stuminl_w, 32, o <= a ? o : a); +} + +#define CASCHECK(fn, w) \ + do \ + { \ + u64 m = mask_of(w); \ + u64 before = buf[0]; \ + u64 got = fn(buf, c, v); \ + int eq = (before & m) == (c & m); \ + u64 want = eq ? (before & ~m) | (v & m) : before; \ + __CPROVER_assert(got == (before & m) && buf[0] == want, #fn); \ + buf[0] = before; \ + } while(0) + +static void check_cas(u64 c, u64 v) +{ + CASCHECK(casal_x, 64); + CASCHECK(cas_w, 32); + CASCHECK(casab, 8); + CASCHECK(caslh, 16); + CASCHECK(casb, 8); +} + +static void run(u64 b0, u64 b1, u64 v, u64 c) +{ + buf[0] = b0; + buf[1] = b1; + check_loads(); + check_stores(v); + buf[0] = b0; + buf[1] = b1; + check_lse(v); + check_lse_st(v); + check_cas(c, v); +} + +int main(void) +{ + run(0x8182838485868788ul, 0x7f00ff017e02fd03ul, 0x80ff7f0180ff7f01ul, 0); + run( + 0x0123456789abcdeful, + 0xfedcba9876543210ul, + 0xfedcba9876543210ul, + 0x0123456789abcdeful); + run(0x7f7f7f7f7f7f7f7ful, 0x8080808080808080ul, 0x8080808080808080ul, 0); + run(0, 0xfffffffffffffffful, 0xfffffffffffffffful, 0x00000000ffffff00ul); + return 0; +} diff --git a/regression/cbmc/asm_aarch64_memory/test.desc b/regression/cbmc/asm_aarch64_memory/test.desc new file mode 100644 index 000000000000..2272fcff87b5 --- /dev/null +++ b/regression/cbmc/asm_aarch64_memory/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +Covers loads (including the sign-extending loads, ldur, ldar, and ldapr), +stores (including stur and stlr), the LSE atomics in their b, h, and st +forms, swp, and cas. The assertions compare each statement with a C +reference; they all hold when main.c is compiled with clang -O1 +--target=aarch64-linux-gnu -march=armv8.4-a (with __CPROVER_assert defined to +check its condition) and run on qemu-aarch64 -cpu max. From fd43f649b9687f3920dce1f06d45d62dadd15746 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 08:07:39 +0000 Subject: [PATCH 072/100] Inline assembly: share the ARM barrier semantics dmb, dsb, and isb, with their options, are the same in AArch64 and AArch32. Move their lowering from the AArch64 semantics to asm_arm_flags.h, which already holds the condition flags that both share, so that the AArch32 semantics can use it. Co-authored-by: Kiro --- src/assembler/asm_aarch64.cpp | 52 +--------------------------------- src/assembler/asm_arm_flags.h | 53 ++++++++++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 52 deletions(-) diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index bc65fd0ee3bb..856a68ed2d6d 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -15,7 +15,6 @@ Author: Michael Tautschnig #include #include #include -#include #include "asm_arm_flags.h" #include "asm_bv_util.h" @@ -181,11 +180,6 @@ class asm_aarch64_semanticst : public asm_semanticst const asm_instructiont &instruction, asm_lowering_contextt &ctx) const; - bool lower_barrier( - const std::string &m, - const asm_instructiont &instruction, - asm_lowering_contextt &ctx) const; - bool lower_hint( const asm_instructiont &instruction, asm_lowering_contextt &ctx) const; @@ -223,50 +217,6 @@ asm_aarch64_semanticst::canonical_register(const std::string &raw) const return {}; } -bool asm_aarch64_semanticst::lower_barrier( - const std::string &m, - const asm_instructiont &instruction, - asm_lowering_contextt &ctx) const -{ - std::string option = "sy"; - if(!instruction.operands.empty()) - { - if( - instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || - !instruction.operands[0][0].is_identifier()) - { - return ctx.fail("unsupported option of " + m); - } - option = instruction.operands[0][0].text; - for(auto &c : option) - c = static_cast(std::tolower(static_cast(c))); - } - - if(m == "isb") - { - if(option != "sy") - return ctx.fail("unsupported option of isb"); - // orders nothing by itself, needs to be combined with a branch - ctx.fence(false, false, false, false, false); - return true; - } - - // the option selects the accesses being ordered - if(option == "sy" || option == "ish" || option == "osh" || option == "nsh") - ctx.fence(true, true, true, true, true); - else if(has_suffix(option, "ld")) // loads before loads and stores - ctx.fence(false, true, true, false, true); - else if(has_suffix(option, "st")) - { - // dmb: stores before stores. No instruction after a dsb executes before - // the dsb completes, so a dsb also orders the stores before later loads. - ctx.fence(true, false, false, m == "dsb", true); - } - else - return ctx.fail("unsupported option of " + m); - return true; -} - /// Lower `hint #imm`. The hint space also holds instructions that write /// general-purpose registers: the pointer authentication instructions /// (`xpaclri`, `pacia1716`, `paciasp`, ...: x16, x17, or x30) and `chkfeat` @@ -914,7 +864,7 @@ bool asm_aarch64_semanticst::lower( } if(m == "dmb" || m == "dsb" || m == "isb") - return lower_barrier(m, instruction, ctx); + return asm_arm::lower_barrier(m, instruction, ctx); // branches: the target is the last operand if( diff --git a/src/assembler/asm_arm_flags.h b/src/assembler/asm_arm_flags.h index 61503a37ef14..8da5bb2252e3 100644 --- a/src/assembler/asm_arm_flags.h +++ b/src/assembler/asm_arm_flags.h @@ -7,14 +7,18 @@ Author: Michael Tautschnig \*******************************************************************/ /// \file -/// The NZCV condition flags and condition codes shared by AArch64 and AArch32 +/// The NZCV condition flags, condition codes, and barriers shared by AArch64 +/// and AArch32 #ifndef CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H #define CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H +#include + #include "asm_bv_util.h" #include "asm_semantics.h" +#include #include namespace asm_arm // NOLINT @@ -128,6 +132,53 @@ inline void set_logic_flags( ctx.assign(ctx.flag("c"), false_exprt{}); ctx.assign(ctx.flag("v"), false_exprt{}); } + +/// Lower the barrier \p m (`dmb`, `dsb`, or `isb`) of \p instruction, whose +/// option (if any) selects the accesses that are ordered. +/// \return false if the option is not understood +inline bool lower_barrier( + const std::string &m, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) +{ + std::string option = "sy"; + if(!instruction.operands.empty()) + { + if( + instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || + !instruction.operands[0][0].is_identifier()) + { + return ctx.fail("unsupported option of " + m); + } + option = instruction.operands[0][0].text; + for(auto &c : option) + c = static_cast(std::tolower(static_cast(c))); + } + + if(m == "isb") + { + if(option != "sy") + return ctx.fail("unsupported option of isb"); + // orders nothing by itself, needs to be combined with a branch + ctx.fence(false, false, false, false, false); + return true; + } + + // the option selects the accesses being ordered + if(option == "sy" || option == "ish" || option == "osh" || option == "nsh") + ctx.fence(true, true, true, true, true); + else if(has_suffix(option, "ld")) // loads before loads and stores + ctx.fence(false, true, true, false, true); + else if(has_suffix(option, "st")) + { + // dmb: stores before stores. No instruction after a dsb executes before + // the dsb completes, so a dsb also orders the stores before later loads. + ctx.fence(true, false, false, m == "dsb", true); + } + else + return ctx.fail("unsupported option of " + m); + return true; +} } // namespace asm_arm #endif // CPROVER_ASSEMBLER_ASM_ARM_FLAGS_H From 3c6a079d85c130aabf3a08ca1f430675042dc639 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 08:07:52 +0000 Subject: [PATCH 073/100] Inline assembly: interpret AArch32 instructions On AArch32 (--arch arm, armel, or armhf), remove_asm approximated every inline assembly statement other than fences and no-ops. Kernel and library code uses inline assembly for atomics (ldrex/strex), barriers, bit operations, and the interrupt masks, all of which thus became nondeterministic. Add AArch32 instruction semantics for A32 and T32 code, in unified and divided syntax: data processing with the flags (s suffix) and conditional execution (condition suffixes; it, whose conditions the instructions repeat as suffixes that the assemblers check), multiplication, bit and byte manipulation, movw/movt, loads and stores of single registers with an immediate or register offset, branches within the statement and to the labels of asm goto, flag outputs, barriers (dmb/dsb/isb and their CP15 forms), mrs/msr of the flags, the interrupt masks, hints, and CP15 cache, TLB, and thread ID operations. Load-exclusive/store-exclusive sequences follow the AArch64 model: ldrex opens an exclusive region, which ends at strex and is atomic; strex succeeds nondeterministically; after clrex or strex, a strex fails. A conditional strex may not execute, and then does not clear the monitor. To be sound, as found by validating against qemu-arm: - In divided syntax, which GCC uses for inline assembly in A32 code and for Thumb-1 targets, Thumb-1 add, mov, and the like set the flags without an s suffix. Unless the statement starts with .syntax unified or uses an instruction or form that Thumb-1 lacks, the flags are nondeterministic after a data-processing instruction without s suffix. - msr of the control field may change the processor mode, which banks r8 to r14: a statement that does so and names any of them is not interpreted. - pc (whose value is the address of the instruction), coprocessor writes other than the CP15 ones above, and other special registers are not modeled. Semantics that depend on the statement as a whole, as these two rules do, now create an asm_semantics_statet via asm_semanticst::make_state. This fixes the reviewer reproducers for a crash on mov from pc, the approximation of four-instruction IT blocks, and strex always succeeding. The fork's Unicorn-validated test (asm_arm) passes unchanged in its expected values; asm_arm_corner_cases was validated with qemu-arm for A32 and T32 code compiled by GCC and Clang. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 20 +- doc/cprover-manual/modeling-inline-asm.md | 50 +- .../cbmc-concurrency/asm_arm_exclusive/main.c | 35 + .../asm_arm_exclusive/test.desc | 14 + regression/cbmc/asm_arm/main.c | 437 ++++++ regression/cbmc/asm_arm/test.desc | 16 + regression/cbmc/asm_arm_corner_cases/main.c | 157 ++ .../cbmc/asm_arm_corner_cases/test.desc | 39 + src/assembler/Makefile | 1 + src/assembler/asm_arm.cpp | 1331 +++++++++++++++++ src/assembler/asm_arm.h | 21 + src/assembler/asm_lowering.cpp | 2 + src/assembler/asm_semantics.cpp | 3 + src/assembler/asm_semantics.h | 22 + 14 files changed, 2141 insertions(+), 7 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_arm_exclusive/main.c create mode 100644 regression/cbmc-concurrency/asm_arm_exclusive/test.desc create mode 100644 regression/cbmc/asm_arm/main.c create mode 100644 regression/cbmc/asm_arm/test.desc create mode 100644 regression/cbmc/asm_arm_corner_cases/main.c create mode 100644 regression/cbmc/asm_arm_corner_cases/test.desc create mode 100644 src/assembler/asm_arm.cpp create mode 100644 src/assembler/asm_arm.h diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 06a7fa6097eb..f2d8512c4280 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -43,7 +43,10 @@ The interpretation of a statement has these parts: and memory, branch, and fence. - `asm_semanticst` is the interface of the per-architecture semantics; `asm_x86.cpp` implements x86 (i386, x86-64, x32), `asm_aarch64.cpp` - implements AArch64; `asm_arm_flags.h` has the ARM condition flags. + implements AArch64, `asm_arm.cpp` implements AArch32; `asm_arm_flags.h` + has the ARM condition flags and barriers. Semantics that depend on the + statement as a whole create an `asm_semantics_statet` (`make_state`), which + `lower` reads from `asm_lowering_contextt::semantics_state`. The code of a statement consists of a prologue that evaluates the inputs, the code of the instructions, and an epilogue that assigns the register outputs. @@ -155,6 +158,21 @@ comes in between: the monitor state is decided along the control flow, and a branch to the label may skip the instruction that cleared the monitor (`asm_lowering_contextt::define_label` forgets that the monitor is cleared). +AArch32 needs two statement-wide properties (`make_a32_state` in +`asm_arm.cpp`). In divided syntax, which GCC uses for inline assembly in A32 +code and for Thumb-1 targets, the Thumb-1 data-processing instructions set +the flags without an `s` suffix (`add r0, r1, #1` is `adds`), depending on +their registers. Unless the statement starts with `.syntax unified` or uses +an instruction or form that Thumb-1 lacks (conditional execution other than +of branches, `it`, `s` suffixes other than `movs`, `ldrex`, `teq`, ...), the +flags are nondeterministic after such an instruction. And `msr` of the +control field may change the processor mode, which banks r8 to r14, so a +statement that does so and names any of these registers is not interpreted. +An `it` instruction has no effect: the instructions of the IT block carry +their conditions as suffixes, which the assemblers check against it. +A conditional store-exclusive may not execute, so it does not clear the +exclusive monitor. + For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the statement; the interpretation assigns it the index of the label that the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index b61a4c4e91ab..12c0d73b2e00 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -12,12 +12,14 @@ all modes. Before verification, the `remove_asm` pass replaces each inline-assembly statement by goto-program instructions: - On x86 (`--arch i386`, `--arch x86_64`, or `--arch x32`, which uses the - x86-64 instructions with 32-bit pointers) and AArch64 (`--arch arm64`), the - default being the host architecture, a GCC-style statement is - **interpreted** if CBMC's instruction semantics for the architecture - support all of its instructions (see "x86 Instruction Semantics" and - "AArch64 Instruction Semantics" below): it is translated into goto-program - instructions with the same effect on the C program state. + x86-64 instructions with 32-bit pointers), AArch64 (`--arch arm64`), and + AArch32 (`--arch arm`, `armel`, or `armhf`), the default being the host + architecture, a GCC-style statement is **interpreted** if CBMC's + instruction semantics for the architecture support all of its + instructions (see "x86 Instruction Semantics", "AArch64 Instruction + Semantics", and "AArch32 Instruction Semantics" below): it is translated + into goto-program instructions with the same effect on the C program + state. - Otherwise, if CBMC models every instruction of the statement (see "Supported Instructions" below, on any architecture), the statement is translated into the corresponding fences or calls to library functions, @@ -195,6 +197,42 @@ store-exclusive only until the next label, as a branch to the label may skip the clearing instruction; after a label, a store-exclusive succeeds or fails nondeterministically. +### AArch32 Instruction Semantics + +The AArch32 semantics cover A32 and T32 (Thumb) code in unified or divided +syntax: + +- data processing on general-purpose registers, with the condition flags + (`s` suffix) and conditional execution (condition suffixes, and `it` + blocks): `mov`, `mvn`, `movw`, `movt`, `add`, `adc`, `sub`, `sbc`, `rsb`, + `neg`, `and`, `orr`, `eor`, `bic`, `lsl`, `lsr`, `asr`, `ror`, `mul`, + `cmp`, `cmn`, `tst`, `teq`, `clz`, `rev`, `rev16`, `rbit`, `uxtb`, `uxth`, + `sxtb`, `sxth`, with register or immediate operands (not shifted + registers); +- loads and stores of single registers (`ldr`, `ldrb`, `ldrh`, `ldrsb`, + `ldrsh`, `str`, `strb`, `strh`) with an immediate or register offset (not + with writeback), and load-exclusive/store-exclusive (`ldrex`, `strex`, + their byte and halfword forms, and `clrex`), as on AArch64 (see above); + a conditional store-exclusive that does not execute leaves the exclusive + monitor as it was; +- branches within the statement and to the labels of `asm goto` (`b`, + `b`, `cbz`, `cbnz`), and flag outputs (`=@cc`); +- barriers (`dmb`, `dsb`, `isb`, and their CP15 forms), `mrs` and `msr` of + the flags (`apsr`, `cpsr`), the interrupt masks (`msr` of `cpsr_c`, + `cpsid`, `cpsie`), hints (`nop`, `yield`, `wfe`, `pld`, ...), and CP15 + cache and TLB maintenance and thread ID registers (`mcr`); `mrs` of other + special registers and `mrc` produce nondeterministic values. + +In divided syntax, which GCC uses for inline assembly in A32 code and for +Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an +`s` suffix. Unless the statement starts with `.syntax unified`, or uses an +instruction or form that Thumb-1 does not have (such as conditional +execution, `it`, or `ldrex`), the flags are nondeterministic after a +data-processing instruction without `s` suffix. A statement that changes the +interrupt masks or the processor mode with `msr` and names any of the +registers r8 to r14, which are banked by mode, is not interpreted. Reading or +writing `pc` is not modeled. + ### Supported Instructions CBMC splits the assembler text into instructions at newlines and `;`, except diff --git a/regression/cbmc-concurrency/asm_arm_exclusive/main.c b/regression/cbmc-concurrency/asm_arm_exclusive/main.c new file mode 100644 index 000000000000..ba9a10b181af --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_exclusive/main.c @@ -0,0 +1,35 @@ +// A load-exclusive/store-exclusive sequence is atomic; plain loads and +// stores are not. +unsigned x, y, done; + +void t(void) +{ + unsigned tmp, status; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, #1\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(tmp), "=&r"(status) + : "r"(&x) + : "cc", "memory"); + __asm__ volatile( + "ldr %0, [%1]\n" + " add %0, %0, #1\n" + " str %0, [%1]" + : "=&r"(tmp) + : "r"(&y) + : "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), done = 1; + t(); + __CPROVER_assume(done); + __CPROVER_assert(x == 2, "ll/sc increment"); + __CPROVER_assert(y == 2, "plain increment"); // fails + return 0; +} diff --git a/regression/cbmc-concurrency/asm_arm_exclusive/test.desc b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc new file mode 100644 index 000000000000..7938e8bb07f5 --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc @@ -0,0 +1,14 @@ +CORE gcc-only +main.c +--arch arm --unwind 2 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 32 ll/sc increment: SUCCESS$ +^\[main\.assertion\.2\] line 33 plain increment: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +A load-exclusive/store-exclusive sequence is an atomic section; a plain +read-modify-write is not. diff --git a/regression/cbmc/asm_arm/main.c b/regression/cbmc/asm_arm/main.c new file mode 100644 index 000000000000..5ff309c8f15e --- /dev/null +++ b/regression/cbmc/asm_arm/main.c @@ -0,0 +1,437 @@ +// AArch32 inline assembly (A32 code) that is interpreted exactly. The expected +// values were observed with an emulator. + +// arm ldrex/orr/strex set a bit (atomic set) +void asm_case_0(unsigned long long *io) +{ + unsigned int m = (unsigned int)io[0]; + unsigned int v = (unsigned int)io[1]; + unsigned int tmp = (unsigned int)io[2]; + unsigned int res = (unsigned int)io[3]; + __asm__ __volatile__( + "1: ldrex %0, [%2]\n" + " orr %0, %0, %3\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " bne 1b\n" + : "=&r"(tmp), "=&r"(res) + : "r"(&m), "r"(v) + : "cc", "memory"); + io[0] = (unsigned long long)m; + io[1] = (unsigned long long)v; + io[2] = (unsigned long long)tmp; + io[3] = (unsigned long long)res; +} + +// arm add and subtract +void asm_case_1(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + unsigned int c = (unsigned int)io[3]; + __asm__("add %0, %1, %2\n sub %0, %0, %3" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; +} + +// arm adds/adc is a 64-bit add +void asm_case_2(unsigned long long *io) +{ + unsigned int lo = (unsigned int)io[0]; + unsigned int hi = (unsigned int)io[1]; + unsigned int alo = (unsigned int)io[2]; + unsigned int ahi = (unsigned int)io[3]; + unsigned int blo = (unsigned int)io[4]; + unsigned int bhi = (unsigned int)io[5]; + __asm__("adds %0, %2, %4\n adc %1, %3, %5" + : "=&r"(lo), "=&r"(hi) + : "r"(alo), "r"(ahi), "r"(blo), "r"(bhi) + : "cc"); + io[0] = (unsigned long long)lo; + io[1] = (unsigned long long)hi; + io[2] = (unsigned long long)alo; + io[3] = (unsigned long long)ahi; + io[4] = (unsigned long long)blo; + io[5] = (unsigned long long)bhi; +} + +// arm and/orr/eor combine bits +void asm_case_3(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + unsigned int c = (unsigned int)io[3]; + unsigned int d = (unsigned int)io[4]; + __asm__("and %0, %1, %2\n orr %0, %0, %3\n eor %0, %0, %4" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c), "r"(d)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; + io[4] = (unsigned long long)d; +} + +// arm cmp and conditional move +void asm_case_4(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__("cmp %1, %2\n movhi %0, #1\n movls %0, #0" + : "=r"(r) + : "r"(a), "r"(b) + : "cc"); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + +// arm ldr and str move a word +void asm_case_5(unsigned long long *io) +{ + unsigned int a = (unsigned int)io[0]; + unsigned int b = (unsigned int)io[1]; + unsigned int t = (unsigned int)io[2]; + __asm__ __volatile__("ldr %0, [%1]\n str %0, [%2]" + : "=&r"(t) + : "r"(&a), "r"(&b) + : "memory"); + io[0] = (unsigned long long)a; + io[1] = (unsigned long long)b; + io[2] = (unsigned long long)t; +} + +// arm lsl/lsr shift +void asm_case_6(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + unsigned int c = (unsigned int)io[3]; + __asm__("lsl %0, %1, %2\n lsr %0, %0, %3" + : "=&r"(r) + : "r"(a), "r"(b), "r"(c)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; + io[3] = (unsigned long long)c; +} + +// arm bic clears bits +void asm_case_7(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__("bic %0, %1, %2" : "=r"(r) : "r"(a), "r"(b)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + +// arm rsb reverse-subtracts +void asm_case_8(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__("rsb %0, %1, %2" : "=r"(r) : "r"(a), "r"(b)); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + +int main(void) +{ + { + unsigned long long io[4] = { + 0xc2a7af9eab79b005ULL, 0xffULL, 0x2ULL, 0x6ffe6666fa72766dULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0xab79b0ffULL && io[1] == 0xffULL && io[2] == 0xab79b0ffULL && + io[3] == 0x0ULL, + "arm ldrex/orr/strex set a bit (atomic set), vector 0"); + } + { + unsigned long long io[4] = { + 0x8000000000000000ULL, + 0x8000000000000000ULL, + 0xae54d49633f89bafULL, + 0xcc5604a33a481fd2ULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x0ULL && io[2] == 0x0ULL && io[3] == 0x0ULL, + "arm ldrex/orr/strex set a bit (atomic set), vector 1"); + } + { + unsigned long long io[4] = { + 0xadb4bded0a6cc878ULL, + 0x248a141c7ccb3b72ULL, + 0xb5d23309b6d2590dULL, + 0x33756584e354bbe7ULL}; + asm_case_0(io); + __CPROVER_assert( + io[0] == 0x7eeffb7aULL && io[1] == 0x7ccb3b72ULL && + io[2] == 0x7eeffb7aULL && io[3] == 0x0ULL, + "arm ldrex/orr/strex set a bit (atomic set), vector 2"); + } + { + unsigned long long io[4] = { + 0xc2b9546e0f0220f3ULL, + 0xf1d5effedcda26fbULL, + 0x7fffffffULL, + 0xb8d3af23681c2889ULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xf4bdfe71ULL && io[1] == 0xdcda26fbULL && + io[2] == 0x7fffffffULL && io[3] == 0x681c2889ULL, + "arm add and subtract, vector 0"); + } + { + unsigned long long io[4] = { + 0xc60f8fe0a6269527ULL, + 0x32f6ffa49275dc84ULL, + 0x7d7ef810cfc3dc1ULL, + 0xbf30555ab55f5d1fULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0xea12bd26ULL && io[1] == 0x9275dc84ULL && + io[2] == 0xcfc3dc1ULL && io[3] == 0xb55f5d1fULL, + "arm add and subtract, vector 1"); + } + { + unsigned long long io[4] = { + 0xb3d8c88ab7063e8dULL, + 0xefe90ebcbcb30e03ULL, + 0xffffffffULL, + 0xed25d1989c8d81a9ULL}; + asm_case_1(io); + __CPROVER_assert( + io[0] == 0x20258c59ULL && io[1] == 0xbcb30e03ULL && + io[2] == 0xffffffffULL && io[3] == 0x9c8d81a9ULL, + "arm add and subtract, vector 2"); + } + { + unsigned long long io[6] = { + 0xe638bca46bd70d89ULL, + 0x2ULL, + 0x2ULL, + 0x17d967b89f01d73dULL, + 0x82974e236f761b03ULL, + 0x7fULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x6f761b05ULL && io[1] == 0x9f01d7bcULL && io[2] == 0x2ULL && + io[3] == 0x9f01d73dULL && io[4] == 0x6f761b03ULL && io[5] == 0x7fULL, + "arm adds/adc is a 64-bit add, vector 0"); + } + { + unsigned long long io[6] = { + 0x6bcc7b9e0a546c01ULL, + 0xffffffffULL, + 0x9541937ec1bfc7abULL, + 0x80000000ULL, + 0xef512c58c835156fULL, + 0xe685acb714786e96ULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0x89f4dd1aULL && io[1] == 0x94786e97ULL && + io[2] == 0xc1bfc7abULL && io[3] == 0x80000000ULL && + io[4] == 0xc835156fULL && io[5] == 0x14786e96ULL, + "arm adds/adc is a 64-bit add, vector 1"); + } + { + unsigned long long io[6] = { + 0x8644a1e6d2818addULL, + 0xef828079a78b6244ULL, + 0x4a13b9da9f4e53bbULL, + 0x19ec4413125e5cfbULL, + 0xa51bdbee16d2b9aeULL, + 0xffULL}; + asm_case_2(io); + __CPROVER_assert( + io[0] == 0xb6210d69ULL && io[1] == 0x125e5dfaULL && + io[2] == 0x9f4e53bbULL && io[3] == 0x125e5cfbULL && + io[4] == 0x16d2b9aeULL && io[5] == 0xffULL, + "arm adds/adc is a 64-bit add, vector 2"); + } + { + unsigned long long io[5] = { + 0x38b1f9a35c2855baULL, + 0x8a0cb201725c5338ULL, + 0xb0652c5806a310a8ULL, + 0x808332e379bd40dbULL, + 0xe586f6e1167ff12eULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0x6dc2a1d5ULL && io[1] == 0x725c5338ULL && + io[2] == 0x6a310a8ULL && io[3] == 0x79bd40dbULL && + io[4] == 0x167ff12eULL, + "arm and/orr/eor combine bits, vector 0"); + } + { + unsigned long long io[5] = { + 0xffULL, + 0xb7a413d48183cf4eULL, + 0x872808db18a381eULL, + 0x89c40189aec7d882ULL, + 0x3ab70d7151d4fc15ULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0xfe13249bULL && io[1] == 0x8183cf4eULL && + io[2] == 0xb18a381eULL && io[3] == 0xaec7d882ULL && + io[4] == 0x51d4fc15ULL, + "arm and/orr/eor combine bits, vector 1"); + } + { + unsigned long long io[5] = { + 0x3785478d706735ULL, + 0xffULL, + 0x7fULL, + 0x62fbfdc8c535c306ULL, + 0x7fffffffULL}; + asm_case_3(io); + __CPROVER_assert( + io[0] == 0xbaca3c80ULL && io[1] == 0xffULL && io[2] == 0x7fULL && + io[3] == 0xc535c306ULL && io[4] == 0x7fffffffULL, + "arm and/orr/eor combine bits, vector 2"); + } + { + unsigned long long io[3] = { + 0xb8004092f9e22b92ULL, 0xab4d6d46b16b38cbULL, 0xc5cc618b30146b25ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0xb16b38cbULL && io[2] == 0x30146b25ULL, + "arm cmp and conditional move, vector 0"); + } + { + unsigned long long io[3] = { + 0xc662866ad84cf328ULL, 0x8000000000000000ULL, 0xffffffffffffffffULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x0ULL && io[2] == 0xffffffffULL, + "arm cmp and conditional move, vector 1"); + } + { + unsigned long long io[3] = { + 0xd85ee36626a12990ULL, 0x816ffbff11966d8bULL, 0x0ULL}; + asm_case_4(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x11966d8bULL && io[2] == 0x0ULL, + "arm cmp and conditional move, vector 2"); + } + { + unsigned long long io[3] = { + 0x662e0001e6f57713ULL, 0xf1657729e04a52fdULL, 0x4ce92b19fe991d62ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0xe6f57713ULL && io[1] == 0xe6f57713ULL && + io[2] == 0xe6f57713ULL, + "arm ldr and str move a word, vector 0"); + } + { + unsigned long long io[3] = { + 0x2dca9d6ea967229bULL, 0xe4a66e6e92989e7dULL, 0x350b8f5dcea6fb83ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0xa967229bULL && io[1] == 0xa967229bULL && + io[2] == 0xa967229bULL, + "arm ldr and str move a word, vector 1"); + } + { + unsigned long long io[3] = { + 0xabc0ff65a92da05dULL, 0x4c075f1f0b493f1aULL, 0x7d9cf46457162242ULL}; + asm_case_5(io); + __CPROVER_assert( + io[0] == 0xa92da05dULL && io[1] == 0xa92da05dULL && + io[2] == 0xa92da05dULL, + "arm ldr and str move a word, vector 2"); + } + { + unsigned long long io[4] = { + 0x71985eb13a883919ULL, 0x7fffffffffffffffULL, 0x1cULL, 0x1fULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0xffffffffULL && io[2] == 0x1cULL && + io[3] == 0x1fULL, + "arm lsl/lsr shift, vector 0"); + } + { + unsigned long long io[4] = { + 0x4f18c672fa42fe7cULL, 0x120984629605b44fULL, 0x14ULL, 0x0ULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x44f00000ULL && io[1] == 0x9605b44fULL && io[2] == 0x14ULL && + io[3] == 0x0ULL, + "arm lsl/lsr shift, vector 1"); + } + { + unsigned long long io[4] = { + 0xfd64b9e5bd0edb5aULL, 0x25406c9bc1a6364ULL, 0x0ULL, 0x12ULL}; + asm_case_6(io); + __CPROVER_assert( + io[0] == 0x2f06ULL && io[1] == 0xbc1a6364ULL && io[2] == 0x0ULL && + io[3] == 0x12ULL, + "arm lsl/lsr shift, vector 2"); + } + { + unsigned long long io[3] = { + 0xd6bc0d35ccec83e4ULL, 0x4fb0d79be3130b3fULL, 0x2d65a8a1cf4ce48eULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x20130b31ULL && io[1] == 0xe3130b3fULL && + io[2] == 0xcf4ce48eULL, + "arm bic clears bits, vector 0"); + } + { + unsigned long long io[3] = { + 0x0ULL, 0xdae98f58edaf5ddULL, 0xbb5f3ec2488a958cULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x86506051ULL && io[1] == 0x8edaf5ddULL && + io[2] == 0x488a958cULL, + "arm bic clears bits, vector 1"); + } + { + unsigned long long io[3] = { + 0x8bcb7f1085e0c86ULL, 0x3dc7152f30428c31ULL, 0x12257820e6b755cfULL}; + asm_case_7(io); + __CPROVER_assert( + io[0] == 0x10408830ULL && io[1] == 0x30428c31ULL && + io[2] == 0xe6b755cfULL, + "arm bic clears bits, vector 2"); + } + { + unsigned long long io[3] = { + 0x71f2223ff559a0f9ULL, 0xc447a6fbb54b9c52ULL, 0xf34de6440ce23540ULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x579698eeULL && io[1] == 0xb54b9c52ULL && io[2] == 0xce23540ULL, + "arm rsb reverse-subtracts, vector 0"); + } + { + unsigned long long io[3] = { + 0x2444fb01d3bdc021ULL, 0xfc66ce02975f8fb3ULL, 0xffULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x68a0714cULL && io[1] == 0x975f8fb3ULL && io[2] == 0xffULL, + "arm rsb reverse-subtracts, vector 1"); + } + { + unsigned long long io[3] = { + 0xca7d4a778a0b60a5ULL, 0x38e3ee6142044392ULL, 0xa67f5e58956140eULL}; + asm_case_8(io); + __CPROVER_assert( + io[0] == 0x4751d07cULL && io[1] == 0x42044392ULL && + io[2] == 0x8956140eULL, + "arm rsb reverse-subtracts, vector 2"); + } + return 0; +} diff --git a/regression/cbmc/asm_arm/test.desc b/regression/cbmc/asm_arm/test.desc new file mode 100644 index 000000000000..0f22d6f1ab4a --- /dev/null +++ b/regression/cbmc/asm_arm/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only no-new-smt +main.c +--arch arm --unwind 2 --no-unwinding-assertions +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +-- +The AArch32 inline assembly in main.c is interpreted exactly: if CBMC +approximated any statement, the assertions, which check values observed with +an emulator (Unicorn, and qemu-arm for A32 code compiled by GCC and Clang), +would fail. A store-exclusive may fail spuriously, so the retry loops of +load-exclusive/store-exclusive sequences are bounded; the executions that +retry more often reach the same states. diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c new file mode 100644 index 000000000000..9c8a14499747 --- /dev/null +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -0,0 +1,157 @@ +// Corner cases of the AArch32 instruction semantics. "fails" marks +// properties that the architecture permits to be violated, so CBMC must not +// prove them. +static unsigned add_ll_sc(unsigned *p, unsigned v) +{ + unsigned result, status; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, %3\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(result), "=&r"(status) + : "r"(p), "r"(v) + : "cc", "memory"); + return result; +} + +int x; + +int main(void) +{ + unsigned a = 0, r, zero = 0; + + // msr writes the flags, mrs reads them + r = 0; + __asm__ volatile("cmp %1, %1\n msr APSR_nzcvq, %2\n it eq\n moveq %0, #1" + : "+r"(r) + : "r"(a), "r"(zero) + : "cc"); + __CPROVER_assert(r == 0, "msr clears Z"); + unsigned flags; + __asm__ volatile("cmp %1, %1\n mrs %0, APSR" : "=r"(flags) : "r"(a) : "cc"); + __CPROVER_assert((flags & 0xf0000000u) == 0x60000000u, "mrs after equality"); + + // an IT block of four instructions + r = 0; + __asm__ volatile( + "cmp %1, #0\n itttt eq\n addeq %0, %0, #1\n addeq %0, %0, #1\n" + " addeq %0, %0, #1\n addeq %0, %0, #1" + : "+r"(r) + : "r"(a) + : "cc"); + __CPROVER_assert(r == 4, "it block"); + + // a load-exclusive/store-exclusive loop retries until the store succeeds + unsigned counter = 40; + __CPROVER_assert(add_ll_sc(&counter, 2) == 42, "ll/sc result"); + __CPROVER_assert(counter == 42, "ll/sc stored"); + + // a store-exclusive without a load-exclusive in the statement may succeed + // (if a load-exclusive executed before) or fail + unsigned m = 1, v = 42, res; + __asm__ volatile("strex %0, %2, [%1]" + : "=&r"(res) + : "r"(&m), "r"(v) + : "memory"); + __CPROVER_assert(m == 42, "store-exclusive stores"); // fails + __CPROVER_assert(m == 1, "store-exclusive fails"); // fails + __CPROVER_assert((res == 0) == (m == 42), "status matches the store"); + + // after clrex, a store-exclusive fails + m = 1; + __asm__ volatile("clrex\n strex %0, %2, [%1]" + : "=&r"(res) + : "r"(&m), "r"(v) + : "memory"); + __CPROVER_assert(m == 1 && res == 1, "store-exclusive after clrex"); + + // a conditional store-exclusive that does not execute leaves the monitor + // set, so that the next one may succeed + m = 1; + __asm__ volatile( + "ldrex %0, [%1]\n cmp %3, #0\n ite eq\n strexeq %0, %2, [%1]\n" + " strexne %0, %2, [%1]" + : "=&r"(res) + : "r"(&m), "r"(v), "r"(v) + : "cc", "memory"); + __CPROVER_assert(res == 1, "conditional store-exclusive"); // fails + __CPROVER_assert( + (res == 0) == (m == 42), "status matches the conditional store"); + + // shifts by register use the bottom byte of the register + unsigned s32 = 32, s33 = 0x121, s40 = 40, big = 0x80000001u; + unsigned lsl, lsr, asr, ror; + __asm__("lsl %0, %4, %5\n lsr %1, %4, %6\n asr %2, %4, %7\n ror %3, %4, %5" + : "=&r"(lsl), "=&r"(lsr), "=&r"(asr), "=&r"(ror) + : "r"(big), "r"(s32), "r"(s33), "r"(s40)); + __CPROVER_assert( + lsl == 0 && lsr == 0 && asr == 0xffffffffu && ror == big, "shifts"); + + // 64-bit subtraction with borrow + unsigned lo, hi; + __asm__("subs %0, %2, %4\n sbc %1, %3, %5" + : "=&r"(lo), "=&r"(hi) + : "r"(0u), "r"(1u), "r"(1u), "r"(0u) + : "cc"); + __CPROVER_assert(lo == 0xffffffffu && hi == 0, "subs/sbc"); + + // bit and byte manipulation + unsigned w = 0x12345680u, rv16, rb, cz, sb, uh, mw; + __asm__( + "rev16 %0, %6\n rbit %1, %6\n clz %2, %7\n sxtb %3, %6\n" + " uxth %4, %6\n movw %5, #0xbeef\n movt %5, #0xdead" + : "=&r"(rv16), "=&r"(rb), "=&r"(cz), "=&r"(sb), "=&r"(uh), "=&r"(mw) + : "r"(w), "r"(0u)); + __CPROVER_assert( + rv16 == 0x34128056u && rb == 0x016a2c48u && cz == 32, "rev16 rbit clz"); + __CPROVER_assert( + sb == 0xffffff80u && uh == 0x5680u && mw == 0xdeadbeefu, "ext movw"); + + // loads and stores of bytes and halfwords + unsigned char bytes[4] = {0x80, 0x7f, 0x01, 0x02}; + unsigned lb, lh; + __asm__ volatile("ldrsb %0, [%2]\n ldrh %1, [%2, #2]\n strb %1, [%2, #1]" + : "=&r"(lb), "=&r"(lh) + : "r"(bytes) + : "memory"); + __CPROVER_assert( + lb == 0xffffff80u && lh == 0x0201u && bytes[1] == 1, "ldrsb ldrh strb"); + + // reading pc is not modeled + __asm__ volatile("mov %0, pc" : "=r"(r)); + __CPROVER_assert(r == 0, "pc"); // fails + + // In divided syntax (GCC's default for inline assembly in A32 code and + // for Thumb-1 targets), Thumb-1 add sets the flags; in A32 code and in + // unified syntax, it does not. + __asm__("cmp %1, %1\n add %0, %1, #1\n beq 1f\n mov %0, #7\n1:" + : "=&r"(r) + : "r"(a) + : "cc"); + __CPROVER_assert(r == 1, "flags after add in divided syntax"); // fails + __asm__( + ".syntax unified\n cmp %1, %1\n add %0, %1, #1\n beq 1f\n" + " mov %0, #7\n1:" + : "=&r"(r) + : "r"(a) + : "cc"); + __CPROVER_assert(r == 1, "flags after add in unified syntax"); + + // a register variable held in a register that the statement does not + // initialise + x = 0; + { + register int *p __asm__("r1") = &x; + __asm__ volatile("str %0, [r1]" : : "r"(5), "r"(p) : "memory"); + } + __CPROVER_assert(x == 0, "store via register variable"); // fails + + // a register variable bound to a register that the template writes + register unsigned r0 __asm__("r0") = 5; + __asm__ volatile("add r0, r0, #1" : "+r"(r0)); + __CPROVER_assert(r0 == 5, "register variable"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc new file mode 100644 index 000000000000..d7073332cd6c --- /dev/null +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -0,0 +1,39 @@ +CORE gcc-only no-new-smt +main.c +--arch arm --unwind 3 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 31 msr clears Z: SUCCESS$ +^\[main\.assertion\.2\] line 34 mrs after equality: SUCCESS$ +^\[main\.assertion\.3\] line 44 it block: SUCCESS$ +^\[main\.assertion\.4\] line 48 ll/sc result: SUCCESS$ +^\[main\.assertion\.5\] line 49 ll/sc stored: SUCCESS$ +^\[main\.assertion\.6\] line 58 store-exclusive stores: FAILURE$ +^\[main\.assertion\.7\] line 59 store-exclusive fails: FAILURE$ +^\[main\.assertion\.8\] line 60 status matches the store: SUCCESS$ +^\[main\.assertion\.9\] line 68 store-exclusive after clrex: SUCCESS$ +^\[main\.assertion\.10\] line 79 conditional store-exclusive: FAILURE$ +^\[main\.assertion\.11\] line 80 status matches the conditional store: SUCCESS$ +^\[main\.assertion\.12\] line 89 shifts: SUCCESS$ +^\[main\.assertion\.13\] line 98 subs/sbc: SUCCESS$ +^\[main\.assertion\.14\] line 107 rev16 rbit clz: SUCCESS$ +^\[main\.assertion\.15\] line 109 ext movw: SUCCESS$ +^\[main\.assertion\.16\] line 119 ldrsb ldrh strb: SUCCESS$ +^\[main\.assertion\.17\] line 124 pc: FAILURE$ +^\[main\.assertion\.18\] line 133 flags after add in divided syntax: FAILURE$ +^\[main\.assertion\.19\] line 140 flags after add in unified syntax: SUCCESS$ +^\[main\.assertion\.20\] line 149 store via register variable: FAILURE$ +^\[main\.assertion\.21\] line 154 register variable: FAILURE$ +approximating inline assembly statement at .* line 123 function main: unsupported operands of mov +approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled +approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function add_ll_sc +-- +The properties marked "fails" in main.c may be violated on hardware; all +others hold on hardware. The results were validated with qemu-arm, for A32 +and T32 code compiled by GCC and Clang. "flags after add in divided syntax" +holds in A32 and T32 code, but is violated for Thumb-1 targets, where the add +sets the flags. diff --git a/src/assembler/Makefile b/src/assembler/Makefile index ec183d1edd47..b30322441b85 100644 --- a/src/assembler/Makefile +++ b/src/assembler/Makefile @@ -1,5 +1,6 @@ SRC = asm_aarch64.cpp \ asm_approximation.cpp \ + asm_arm.cpp \ asm_lowering.cpp \ asm_operands.cpp \ asm_semantics.cpp \ diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp new file mode 100644 index 000000000000..b6792f59bcf3 --- /dev/null +++ b/src/assembler/asm_arm.cpp @@ -0,0 +1,1331 @@ +/*******************************************************************\ + +Module: Inline assembly: AArch32 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for AArch32 (A32 and T32 instruction sets, GNU +/// syntax) + +#include "asm_arm.h" + +#include +#include +#include +#include +#include + +#include "asm_arm_flags.h" +#include "asm_bv_util.h" +#include "asm_semantics.h" + +#include +#include +#include +#include + +using asm_bv::bool_to_bv; +using asm_bv::bv; +using asm_bv::constant; +using asm_bv::extract; +using asm_bv::is_zero; +using asm_bv::resize; +using asm_bv::sign_extend; + +namespace +{ +struct a32_operandt +{ + enum class kindt + { + REGISTER, + IMMEDIATE, + MEMORY, + /// a coprocessor, system register, or other name, in `name` + NAME + }; + + kindt kind = kindt::REGISTER; + + // REGISTER: storage (32 bits) + exprt storage; + + // IMMEDIATE + exprt value; + + // MEMORY: the address + exprt address; + /// for memory operands bound to a C lvalue: that lvalue and its width + exprt lvalue; + std::size_t natural_width = 0; + + // NAME (lower case) + std::string name; +}; + +/// An instruction mnemonic split into its operation, the flag-setting `s` +/// suffix, and the condition +struct a32_mnemonict +{ + std::string base; + bool sets_flags = false; + std::string condition = "al"; +}; + +/// The operations, longest first, so that, for example, `bics` is not read +/// as `b` with condition `ics` +const std::vector &operations() +{ + static const std::vector result = [] + { + std::vector b = { + "mov", "mvn", "add", "adc", "sub", "sbc", "rsb", "and", + "orr", "eor", "bic", "cmp", "cmn", "tst", "teq", "lsl", + "lsr", "asr", "ror", "neg", "mul", "b", "cbz", "cbnz", + "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "str", "strb", "strh", + "ldrex", "ldrexb", "ldrexh", "strex", "strexb", "strexh", "clz", "rev", + "rev16", "rbit", "uxtb", "uxth", "sxtb", "sxth", "movw", "movt", + "mrs", "msr", "mrc", "mcr", "nop", "yield", "wfe", "wfi", + "sev", "sevl"}; + std::stable_sort( + b.begin(), + b.end(), + [](const std::string &x, const std::string &y) + { return x.size() > y.size(); }); + return b; + }(); + return result; +} + +/// The operations that take an `s` suffix +const std::set &flag_setting_operations() +{ + static const std::set result = { + "mov", + "mvn", + "add", + "adc", + "sub", + "sbc", + "rsb", + "and", + "orr", + "eor", + "bic", + "lsl", + "lsr", + "asr", + "ror", + "neg", + "mul"}; + return result; +} + +/// Split \p m into operation, `s` suffix, and condition, in the order of +/// unified syntax (`addseq`) or of divided syntax (`addeqs`). +bool decode(const std::string &m, a32_mnemonict &result) +{ + for(const auto &base : operations()) + { + if(m.compare(0, base.size(), base) != 0) + continue; + std::string rest = m.substr(base.size()); + bool s = false; + if(flag_setting_operations().count(base) != 0) + { + if(!rest.empty() && rest.front() == 's') + { + s = true; + rest.erase(0, 1); + } + else if(rest.size() == 3 && rest.back() == 's') + { + s = true; + rest.pop_back(); + } + } + if(!rest.empty() && asm_arm::condition_codes().count(rest) == 0) + continue; + result.base = base; + result.sets_flags = s; + result.condition = rest.empty() ? "al" : rest; + return true; + } + return false; +} + +/// What the instruction semantics need to know about the statement as a +/// whole +class a32_statet : public asm_semantics_statet +{ +public: + /// Whether the statement may be in divided syntax for a Thumb-1 target + /// (see \ref make_a32_state) + bool maybe_thumb1_divided = true; + /// If not empty, why the statement is not modeled + std::string failure; +}; + +/// \return The canonical name of the general-purpose register \p raw, or the +/// empty string if \p raw is not one (`pc` is not modeled) +std::string canonical_a32_register(const std::string &raw) +{ + std::string name = raw; + for(auto &c : name) + c = static_cast(std::tolower(static_cast(c))); + + static const std::map aliases = { + {"sb", "r9"}, + {"sl", "r10"}, + {"fp", "r11"}, + {"ip", "r12"}, + {"sp", "r13"}, + {"lr", "r14"}}; + auto alias = aliases.find(name); + if(alias != aliases.end()) + return alias->second; + + if(name.size() >= 2 && name.size() <= 3 && name[0] == 'r') + { + const std::string digits = name.substr(1); + if(std::all_of( + digits.begin(), + digits.end(), + [](char c) { return std::isdigit(static_cast(c)); })) + { + const int n = std::stoi(digits); + if(n <= 14 && std::to_string(n) == digits) + return "r" + std::to_string(n); + } + } + return {}; +} + +/// The fields of the special register \p target of `msr`. +/// \param target: the special register, in lower case, e.g. `cpsr_fc` +/// \param [out] known: whether \p target is understood, and writing it has +/// no effect on the modeled state other than on \p flags +/// \param [out] flags: whether the write sets the condition flags +/// \param [out] control: whether the write sets the control field (the +/// interrupt masks and the processor mode) +void msr_fields( + const std::string &target, + bool &known, + bool &flags, + bool &control) +{ + known = true; + flags = control = false; + if(target == "cpsr") // cpsr_fc + { + flags = control = true; + return; + } + if(target == "apsr_nzcvq" || target == "apsr_nzcvqg" || target == "apsr_nzcv") + { + flags = true; + return; + } + if(target == "apsr_g") + return; + if(target.compare(0, 5, "cpsr_") == 0 && target.size() > 5) + { + for(std::size_t i = 5; i < target.size(); ++i) + { + switch(target[i]) + { + case 'f': + flags = true; + break; + case 'c': + control = true; + break; + case 's': + // the GE flags, which are not modeled + break; + default: + // the x field includes the endianness of data accesses + known = false; + return; + } + } + return; + } + known = false; +} + +/// The statement-wide properties of \p instructions: +/// - In divided syntax, which GCC uses for inline assembly in A32 code and +/// for Thumb-1 targets, Thumb-1 data-processing instructions without an `s` +/// suffix may set the flags (`add r0, r1, r2` is `adds`). The statement is +/// known not to be such code if it starts with `.syntax unified`, or if it +/// uses an instruction or form that Thumb-1 does not have. +/// - `msr` of the control field may change the processor mode, and with it +/// the registers r8 to r14 that are named, which is not modeled. +std::unique_ptr +make_a32_state(const std::vector &instructions) +{ + auto state = std::make_unique(); + + static const std::set not_thumb1 = { + "teq", + "clz", + "rbit", + "movw", + "movt", + "cbz", + "cbnz", + "ldrex", + "ldrexb", + "ldrexh", + "strex", + "strexb", + "strexh", + "mrc", + "mcr"}; + + bool unified_at_start = false, before_first_instruction = true; + bool divided = false, changes_mode = false, names_banked = false; + for(const auto &instruction : instructions) + { + const std::string &m = instruction.mnemonic; + if(m == ".syntax") + { + const bool unified = instruction.operands.size() == 1 && + instruction.operands[0].size() == 1 && + instruction.operands[0][0].text == "unified"; + if(unified && before_first_instruction) + unified_at_start = true; + if(!unified) + divided = true; + continue; + } + if(m.empty() || instruction.is_directive()) + continue; + before_first_instruction = false; + + for(const auto &operand : instruction.operands) + { + for(const auto &token : operand) + { + if(!token.is_identifier()) + continue; + const std::string reg = canonical_a32_register(token.text); + if(!reg.empty() && std::stoi(reg.substr(1)) >= 8) + names_banked = true; + } + } + + if( + m.size() >= 2 && m.size() <= 5 && m[0] == 'i' && m[1] == 't' && + std::all_of( + m.begin() + 2, m.end(), [](char c) { return c == 't' || c == 'e'; })) + { + state->maybe_thumb1_divided = false; + continue; + } + + a32_mnemonict decoded; + if(!decode(m, decoded)) + continue; + if( + not_thumb1.count(decoded.base) != 0 || + (decoded.condition != "al" && decoded.base != "b") || + (decoded.sets_flags && decoded.base != "mov")) + { + state->maybe_thumb1_divided = false; + } + + if( + decoded.base == "msr" && !instruction.operands.empty() && + instruction.operands[0].size() == 1) + { + std::string target = instruction.operands[0][0].text; + for(auto &c : target) + c = static_cast(std::tolower(static_cast(c))); + bool known, flags, control; + msr_fields(target, known, flags, control); + if(!known || control) + changes_mode = true; + } + } + + if(unified_at_start && !divided) + state->maybe_thumb1_divided = false; + + if(changes_mode && names_banked) + { + state->failure = + "msr of the processor mode with named registers r8 to r14, which may be " + "banked"; + } + + return state; +} + +class asm_arm_semanticst : public asm_semanticst +{ +public: + asm_arm_semanticst() + { + syntax_conventions.line_comments = {"@"}; + syntax_conventions.separators = ";"; + } + + std::string name() const override + { + return "AArch32"; + } + + const asm_syntaxt &syntax() const override + { + return syntax_conventions; + } + + std::size_t register_width() const override + { + return 32; + } + + std::string canonical_register(const std::string &name) const override + { + return canonical_a32_register(name); + } + + bool reference_widens(const std::string &, std::size_t natural_width) + const override + { + // references read the full register + return natural_width < 32; + } + + constraint_classt classify_constraint( + const std::string &constraint, + std::size_t &pos, + std::string &) const override + { + switch(constraint[pos]) + { + case 'l': // r0 to r7 + case 'h': // r8 to r15 (Thumb-1) + return constraint_classt::REGISTER; + case 'Q': + return constraint_classt::MEMORY; + case 'U': + // Uv, Uy, Uq, ...: memory operands for particular instructions + if(pos + 1 < constraint.size()) + { + ++pos; + return constraint_classt::MEMORY; + } + return constraint_classt::UNKNOWN; + case 'I': + case 'J': + case 'K': + case 'L': + case 'M': + case 'N': + case 'O': + return constraint_classt::IMMEDIATE; + case 'P': + if(pos + 1 < constraint.size()) + { + ++pos; + return constraint_classt::IMMEDIATE; + } + return constraint_classt::UNKNOWN; + default: + // k (the stack pointer), t, w, x (floating-point and vector + // registers), ...: not modeled + return constraint_classt::UNKNOWN; + } + } + + bool is_flag_output_condition(const std::string &condition) const override + { + return asm_arm::condition_codes().count(condition) != 0 && + condition != "al"; + } + + exprt + condition(const std::string &cc, asm_lowering_contextt &ctx) const override + { + return asm_arm::condition(cc, ctx); + } + + bool lower(const asm_instructiont &instruction, asm_lowering_contextt &ctx) + const override; + + std::unique_ptr + make_state(const std::vector &instructions) const override + { + return make_a32_state(instructions); + } + +protected: + asm_syntaxt syntax_conventions; + + bool parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + a32_operandt &operand) const; + + exprt read( + asm_lowering_contextt &ctx, + const a32_operandt &operand, + std::size_t width) const; + + bool write( + asm_lowering_contextt &ctx, + const a32_operandt &operand, + std::size_t width, + const exprt &value) const; + + bool lower_operation( + const a32_mnemonict &decoded, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; + + bool lower_memory( + const a32_mnemonict &decoded, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const; + + bool lower_system( + const a32_mnemonict &decoded, + std::vector &ops, + asm_lowering_contextt &ctx) const; +}; + +bool asm_arm_semanticst::parse_operand( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + a32_operandt &operand) const +{ + if(tokens.empty()) + return ctx.fail("empty operand"); + + const asm_tokent &first = tokens[0]; + + // immediate: #n, #-n, n, #%N + if( + first.is_punctuation('#') || first.kind == asm_tokent::kindt::NUMBER || + first.is_punctuation('-')) + { + std::size_t pos = first.is_punctuation('#') ? 1 : 0; + bool negative = false; + if(pos < tokens.size() && tokens[pos].is_punctuation('-')) + { + negative = true; + ++pos; + } + if(pos + 1 != tokens.size()) + return ctx.fail("unsupported immediate"); + operand.kind = a32_operandt::kindt::IMMEDIATE; + const asm_tokent &token = tokens[pos]; + if(token.kind == asm_tokent::kindt::NUMBER) + { + operand.value = + from_integer(negative ? -token.number : token.number, integer_typet{}); + return true; + } + if( + token.kind == asm_tokent::kindt::OPERAND && token.modifier.empty() && + ctx.operands.operands.at(token.index).kind == + asm_operandt::kindt::IMMEDIATE) + { + operand.value = ctx.operand_immediate(token.index); + if(negative) + operand.value = unary_minus_exprt{operand.value}; + return true; + } + return ctx.fail("unsupported immediate"); + } + + // memory: [Rn], [Rn, #imm], [Rn, Rm] + if(first.is_punctuation('[')) + { + if(!tokens.back().is_punctuation(']')) + return ctx.fail("unsupported addressing mode (writeback?)"); + std::vector parts{{}}; + for(std::size_t i = 1; i + 1 < tokens.size(); ++i) + { + if(tokens[i].is_punctuation(',')) + parts.emplace_back(); + else + parts.back().push_back(tokens[i]); + } + a32_operandt base; + if( + !parse_operand(parts[0], ctx, base) || + base.kind != a32_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported base register"); + } + exprt address = typecast_exprt{ + resize(read(ctx, base, 32), config.ansi_c.pointer_width), + pointer_type(char_type())}; + if(parts.size() == 2) + { + a32_operandt offset; + if(!parse_operand(parts[1], ctx, offset)) + return false; + if(offset.kind == a32_operandt::kindt::IMMEDIATE) + { + address = plus_exprt{ + address, + typecast_exprt::conditional_cast( + offset.value, signedbv_typet{config.ansi_c.pointer_width})}; + } + else if(offset.kind == a32_operandt::kindt::REGISTER) + { + address = plus_exprt{ + address, + typecast_exprt{ + resize(read(ctx, offset, 32), config.ansi_c.pointer_width), + signedbv_typet{config.ansi_c.pointer_width}}}; + } + else + return ctx.fail("unsupported offset"); + } + else if(parts.size() > 2) + return ctx.fail("unsupported addressing mode"); + operand.kind = a32_operandt::kindt::MEMORY; + operand.address = address; + return true; + } + + if(tokens.size() == 1 && first.kind == asm_tokent::kindt::OPERAND) + { + if(!first.modifier.empty()) + return ctx.fail("unsupported operand modifier %" + first.modifier); + const asm_operandt &bound = ctx.operands.operands.at(first.index); + switch(bound.kind) + { + case asm_operandt::kindt::REGISTER: + operand.kind = a32_operandt::kindt::REGISTER; + operand.storage = ctx.operand_storage(first.index); + return true; + case asm_operandt::kindt::MEMORY: + operand.kind = a32_operandt::kindt::MEMORY; + operand.address = ctx.operand_address(first.index); + operand.lvalue = dereference_exprt{ctx.operand_address(first.index)}; + operand.natural_width = ctx.operand_width(first.index); + return true; + case asm_operandt::kindt::IMMEDIATE: + operand.kind = a32_operandt::kindt::IMMEDIATE; + operand.value = ctx.operand_immediate(first.index); + return true; + case asm_operandt::kindt::FLAG_OUTPUT: + break; + } + return ctx.fail("flag output used in template"); + } + + if(tokens.size() == 1 && first.is_identifier()) + { + const std::string reg = canonical_a32_register(first.text); + if(!reg.empty()) + { + operand.kind = a32_operandt::kindt::REGISTER; + operand.storage = ctx.hardware_register(reg); + return true; + } + operand.kind = a32_operandt::kindt::NAME; + operand.name = first.text; + for(auto &c : operand.name) + c = static_cast(std::tolower(static_cast(c))); + return true; + } + + return ctx.fail("unsupported operand"); +} + +exprt asm_arm_semanticst::read( + asm_lowering_contextt &ctx, + const a32_operandt &operand, + std::size_t width) const +{ + switch(operand.kind) + { + case a32_operandt::kindt::REGISTER: + return width == 32 ? operand.storage : extract(operand.storage, 0, width); + + case a32_operandt::kindt::IMMEDIATE: + if(operand.value.type().id() == ID_integer) + { + return constant( + numeric_cast_v(to_constant_expr(operand.value)), width); + } + return typecast_exprt::conditional_cast(operand.value, bv(width)); + + case a32_operandt::kindt::MEMORY: + if(ctx.exclusive_open()) + { + ctx.fail("memory access between load-exclusive and store-exclusive"); + return ctx.nondet(bv(width)); + } + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + return ctx.to_bits(operand.lvalue, width); + return ctx.memory(operand.address, width); + + case a32_operandt::kindt::NAME: + break; + } + + // includes pc, whose value is the address of the instruction + ctx.fail("unsupported operand " + operand.name); + return ctx.nondet(bv(width)); +} + +bool asm_arm_semanticst::write( + asm_lowering_contextt &ctx, + const a32_operandt &operand, + std::size_t width, + const exprt &value) const +{ + switch(operand.kind) + { + case a32_operandt::kindt::REGISTER: + ctx.assign(operand.storage, resize(resize(value, width), 32)); + return true; + + case a32_operandt::kindt::MEMORY: + if(ctx.exclusive_open()) + return ctx.fail( + "memory access between load-exclusive and store-exclusive"); + if(operand.lvalue.is_not_nil() && operand.natural_width == width) + { + ctx.assign( + operand.lvalue, + ctx.from_bits(resize(value, width), operand.lvalue.type())); + } + else + ctx.assign(ctx.memory(operand.address, width), resize(value, width)); + return true; + + case a32_operandt::kindt::IMMEDIATE: + case a32_operandt::kindt::NAME: + break; + } + + // includes pc, a write to which is a branch + return ctx.fail("invalid destination " + operand.name); +} + +bool asm_arm_semanticst::lower( + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + const auto *state = + dynamic_cast(ctx.semantics_state.get()); + INVARIANT(state != nullptr, "the state is created by make_state"); + if(!state->failure.empty()) + return ctx.fail(state->failure); + + std::string m = instruction.mnemonic; + + if(!instruction.prefixes.empty()) + return ctx.fail("unexpected prefix"); + + // the width qualifiers of unified syntax select an encoding + if( + m.size() > 2 && (m.compare(m.size() - 2, 2, ".n") == 0 || + m.compare(m.size() - 2, 2, ".w") == 0)) + { + m.erase(m.size() - 2); + } + + // An IT block makes the next (up to four) instructions conditional. Each + // of these carries its condition as a suffix, which the assemblers check + // against the IT instruction, so that the IT instruction itself has no + // further effect. + if( + m.size() >= 2 && m.size() <= 5 && m[0] == 'i' && m[1] == 't' && + std::all_of( + m.begin() + 2, m.end(), [](char c) { return c == 't' || c == 'e'; })) + { + if( + instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || + !instruction.operands[0][0].is_identifier()) + { + return ctx.fail("unsupported " + m); + } + std::string condition = instruction.operands[0][0].text; + for(auto &c : condition) + c = static_cast(std::tolower(static_cast(c))); + if(asm_arm::condition_codes().count(condition) == 0) + return ctx.fail("unsupported " + m); + return true; + } + + // interrupt masks, which have no effect on the C program state; with a + // mode operand, they change the processor mode, which is not modeled + if(m == "cpsid" || m == "cpsie") + { + if( + instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || + !instruction.operands[0][0].is_identifier()) + { + return ctx.fail("unsupported operands of " + m); + } + return true; + } + + // preload hints do not access memory + if(m == "pld" || m == "pldw" || m == "pli") + return true; + + if(m == "clrex") + { + ctx.clear_exclusive(); + return true; + } + + if(m == "dmb" || m == "dsb" || m == "isb") + return asm_arm::lower_barrier(m, instruction, ctx); + + a32_mnemonict decoded; + if(!decode(m, decoded)) + return ctx.fail("unsupported instruction " + m); + + // branches: the target is the last operand + if(decoded.base == "b" || decoded.base == "cbz" || decoded.base == "cbnz") + { + if(instruction.operands.empty() || instruction.operands.back().size() != 1) + return ctx.fail("unsupported branch target"); + const asm_tokent &target = instruction.operands.back().back(); + if(decoded.base == "b") + { + if(instruction.operands.size() != 1) + return ctx.fail("unsupported branch"); + return ctx.branch(target, asm_arm::condition(decoded.condition, ctx)); + } + a32_operandt reg; + if( + instruction.operands.size() != 2 || decoded.condition != "al" || + !parse_operand(instruction.operands[0], ctx, reg) || + reg.kind != a32_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported " + decoded.base); + } + const exprt zero = is_zero(read(ctx, reg, 32)); + return ctx.branch( + target, decoded.base == "cbz" ? zero : exprt{not_exprt{zero}}); + } + + std::vector ops; + for(const auto &tokens : instruction.operands) + { + a32_operandt op; + if(!parse_operand(tokens, ctx, op)) + return false; + ops.push_back(op); + } + + if(decoded.condition == "al") + { + if(!lower_operation(decoded, ops, instruction, ctx)) + return false; + + // In divided syntax for Thumb-1, data-processing instructions without + // an `s` suffix may set the flags (depending on the registers). + if( + state->maybe_thumb1_divided && !decoded.sets_flags && + flag_setting_operations().count(decoded.base) != 0) + { + for(const char *f : {"n", "z", "c", "v"}) + ctx.assign(ctx.flag(f), ctx.nondet(bool_typet{})); + } + return true; + } + + // conditional execution + const auto skip = + ctx.begin_conditional(asm_arm::condition(decoded.condition, ctx)); + if(!lower_operation(decoded, ops, instruction, ctx)) + return false; + ctx.end_conditional(skip); + return true; +} + +bool asm_arm_semanticst::lower_operation( + const a32_mnemonict &decoded, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + const std::string &b = decoded.base; + + auto is_reg = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a32_operandt::kindt::REGISTER; }; + // a register or an immediate: the flexible second operand + auto is_value = [&](std::size_t i) + { + return i < ops.size() && (ops[i].kind == a32_operandt::kindt::REGISTER || + ops[i].kind == a32_operandt::kindt::IMMEDIATE); + }; + auto temp = [&](const exprt &value, const std::string &suffix) + { + const symbol_exprt t = ctx.temporary(value.type(), suffix); + ctx.assign(t, value); + return t; + }; + // the carry out of the shifter for an immediate depends on its encoding + auto nondet_carry = [&]() + { ctx.assign(ctx.flag("c"), ctx.nondet(bool_typet{})); }; + + if( + b == "nop" || b == "yield" || b == "wfe" || b == "wfi" || b == "sev" || + b == "sevl") + { + return true; + } + + if(b == "mrs" || b == "msr" || b == "mrc" || b == "mcr") + return lower_system(decoded, ops, ctx); + + if(b == "mov" || b == "mvn") + { + if(ops.size() != 2 || !is_reg(0) || !is_value(1)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const symbol_exprt v = temp(read(ctx, ops[1], 32), "v"); + const symbol_exprt r = b == "mvn" ? temp(bitnot_exprt{v}, "r") : v; + if(decoded.sets_flags) + { + asm_arm::set_nz(ctx, r, 32); + if(ops[1].kind == a32_operandt::kindt::IMMEDIATE) + nondet_carry(); + } + return write(ctx, ops[0], 32, r); + } + + if(b == "movw" || b == "movt") + { + if( + ops.size() != 2 || !is_reg(0) || + ops[1].kind != a32_operandt::kindt::IMMEDIATE) + { + return ctx.fail("unsupported operands of " + instruction.mnemonic); + } + const exprt imm = read(ctx, ops[1], 16); + if(b == "movw") + return write(ctx, ops[0], 32, resize(imm, 32)); + return write( + ctx, + ops[0], + 32, + concatenation_exprt{imm, extract(read(ctx, ops[0], 32), 0, 16), bv(32)}); + } + + static const std::set unary = { + "neg", "clz", "rev", "rev16", "rbit", "uxtb", "uxth", "sxtb", "sxth"}; + if(unary.count(b) != 0) + { + if(ops.size() != 2 || !is_reg(0) || !is_reg(1)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const symbol_exprt v = temp(read(ctx, ops[1], 32), "v"); + exprt r; + if(b == "neg") + r = unary_minus_exprt{v}; + else if(b == "clz") + r = count_leading_zeros_exprt{v, true, bv(32)}; + else if(b == "rev") + r = bswap_exprt{v, 8}; + else if(b == "rev16") + { + r = bitor_exprt{ + bitand_exprt{lshr_exprt{v, 8}, constant(0x00ff00ff, 32)}, + bitand_exprt{shl_exprt{v, 8}, constant(0xff00ff00, 32)}}; + } + else if(b == "rbit") + r = bitreverse_exprt{v}; + else if(b == "uxtb" || b == "uxth") + r = resize(extract(v, 0, b == "uxtb" ? 8 : 16), 32); + else + r = sign_extend(v, b == "sxtb" ? 8 : 16, 32); + const symbol_exprt result = temp(r, "r"); + if(decoded.sets_flags) // negs + asm_arm::set_sub_flags(ctx, constant(0, 32), v, result, 32); + return write(ctx, ops[0], 32, result); + } + + if(b == "mul") + { + // two-operand form: Rd, Rm means Rd, Rd, Rm + if(ops.size() == 2) + ops.insert(ops.begin() + 1, ops[0]); + if(ops.size() != 3 || !is_reg(0) || !is_reg(1) || !is_reg(2)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const symbol_exprt result = + temp(mult_exprt{read(ctx, ops[1], 32), read(ctx, ops[2], 32)}, "r"); + if(decoded.sets_flags) + { + // C is unchanged from ARMv5 on, but unpredictable before + asm_arm::set_nz(ctx, result, 32); + nondet_carry(); + } + return write(ctx, ops[0], 32, result); + } + + static const std::set binary = { + "add", + "adc", + "sub", + "sbc", + "rsb", + "and", + "orr", + "eor", + "bic", + "lsl", + "lsr", + "asr", + "ror"}; + + if(binary.count(b) != 0) + { + // two-operand form: Rd, Op2 means Rd, Rd, Op2 + if(ops.size() == 2) + ops.insert(ops.begin() + 1, ops[0]); + if(ops.size() != 3 || !is_reg(0) || !is_reg(1) || !is_value(2)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + + const symbol_exprt x = temp(read(ctx, ops[1], 32), "a"); + const symbol_exprt y = temp(read(ctx, ops[2], 32), "b"); + const exprt carry = bool_to_bv(ctx.flag("c"), 32); + exprt r; + if(b == "add") + r = plus_exprt{x, y}; + else if(b == "adc") + r = plus_exprt{plus_exprt{x, y}, carry}; + else if(b == "sub") + r = minus_exprt{x, y}; + else if(b == "sbc") // x - y - !C + r = minus_exprt{minus_exprt{x, y}, minus_exprt{constant(1, 32), carry}}; + else if(b == "rsb") + r = minus_exprt{y, x}; + else if(b == "and") + r = bitand_exprt{x, y}; + else if(b == "orr") + r = bitor_exprt{x, y}; + else if(b == "eor") + r = bitxor_exprt{x, y}; + else if(b == "bic") + r = bitand_exprt{x, bitnot_exprt{y}}; + else + { + // A shift by a register uses its bottom byte; shifts by 32 or more + // yield 0 (or the sign for asr). An immediate is 0 to 32. + const exprt n = bitand_exprt{y, constant(255, 32)}; + const exprt big = binary_relation_exprt{n, ID_ge, constant(32, 32)}; + if(b == "lsl") + r = if_exprt{big, constant(0, 32), shl_exprt{x, n}}; + else if(b == "lsr") + r = if_exprt{big, constant(0, 32), lshr_exprt{x, n}}; + else if(b == "asr") + { + r = typecast_exprt{ + ashr_exprt{ + typecast_exprt{x, signedbv_typet{32}}, + if_exprt{big, constant(31, 32), n}}, + bv(32)}; + } + else + { + const exprt k = bitand_exprt{n, constant(31, 32)}; + r = if_exprt{ + is_zero(k), + x, + bitor_exprt{ + lshr_exprt{x, k}, shl_exprt{x, minus_exprt{constant(32, 32), k}}}}; + } + } + + const symbol_exprt result = temp(r, "r"); + if(decoded.sets_flags) + { + if(b == "add") + asm_arm::set_add_flags(ctx, x, y, constant(0, 32), result, 32); + else if(b == "adc") + asm_arm::set_add_flags(ctx, x, y, carry, result, 32); + else if(b == "sub") + asm_arm::set_sub_flags(ctx, x, y, result, 32); + else if(b == "rsb") + asm_arm::set_sub_flags(ctx, y, x, result, 32); + else if(b == "sbc") + { + // the flags of x + ~y + C + asm_arm::set_add_flags(ctx, x, bitnot_exprt{y}, carry, result, 32); + } + else + { + // Logical operations and shifts: C is the carry out of the + // shifter, which is not modeled (unchanged for a register operand + // without shift); V is unchanged. + asm_arm::set_nz(ctx, result, 32); + if( + ops[2].kind == a32_operandt::kindt::IMMEDIATE || b == "lsl" || + b == "lsr" || b == "asr" || b == "ror") + { + nondet_carry(); + } + } + } + return write(ctx, ops[0], 32, result); + } + + if(b == "cmp" || b == "cmn" || b == "tst" || b == "teq") + { + if(ops.size() != 2 || !is_reg(0) || !is_value(1)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const symbol_exprt x = temp(read(ctx, ops[0], 32), "a"); + const symbol_exprt y = temp(read(ctx, ops[1], 32), "b"); + if(b == "cmp") + asm_arm::set_sub_flags(ctx, x, y, temp(minus_exprt{x, y}, "r"), 32); + else if(b == "cmn") + { + asm_arm::set_add_flags( + ctx, x, y, constant(0, 32), temp(plus_exprt{x, y}, "r"), 32); + } + else + { + asm_arm::set_nz( + ctx, + temp( + b == "tst" ? exprt{bitand_exprt{x, y}} : exprt{bitxor_exprt{x, y}}, + "r"), + 32); + if(ops[1].kind == a32_operandt::kindt::IMMEDIATE) + nondet_carry(); + } + return true; + } + + return lower_memory(decoded, ops, instruction, ctx); +} + +bool asm_arm_semanticst::lower_memory( + const a32_mnemonict &decoded, + std::vector &ops, + const asm_instructiont &instruction, + asm_lowering_contextt &ctx) const +{ + const std::string &b = decoded.base; + const bool conditional = decoded.condition != "al"; + + auto is_reg = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a32_operandt::kindt::REGISTER; }; + auto is_mem = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a32_operandt::kindt::MEMORY; }; + + static const std::map> loads = { + {"ldr", {32, false}}, + {"ldrb", {8, false}}, + {"ldrh", {16, false}}, + {"ldrsb", {8, true}}, + {"ldrsh", {16, true}}, + {"ldrex", {32, false}}, + {"ldrexb", {8, false}}, + {"ldrexh", {16, false}}}; + auto load = loads.find(b); + if(load != loads.end()) + { + if(ops.size() != 2 || !is_reg(0) || !is_mem(1)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const std::size_t size = load->second.first; + const exprt v = read(ctx, ops[1], size); + if(!write( + ctx, + ops[0], + 32, + load->second.second ? sign_extend(v, size, 32) : resize(v, 32))) + { + return false; + } + if(b.compare(0, 5, "ldrex") == 0) + ctx.begin_exclusive(); + return true; + } + + static const std::map stores = { + {"str", 32}, {"strb", 8}, {"strh", 16}}; + auto store = stores.find(b); + if(store != stores.end()) + { + if(ops.size() != 2 || !is_reg(0) || !is_mem(1)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + return write(ctx, ops[1], store->second, read(ctx, ops[0], store->second)); + } + + // store-exclusive: Rd, Rt, [Rn] + static const std::map exclusive_stores = { + {"strex", 32}, {"strexb", 8}, {"strexh", 16}}; + auto xstore = exclusive_stores.find(b); + if(xstore != exclusive_stores.end()) + { + if(ops.size() != 3 || !is_reg(0) || !is_reg(1) || !is_mem(2)) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + const std::size_t size = xstore->second; + if(ctx.exclusive_cleared()) + { + // the store fails, and does not store + return write(ctx, ops[0], 32, constant(1, 32)); + } + // The store may fail spuriously; it can succeed without a load-exclusive + // in this statement if the monitor was set before. + if(ctx.exclusive_open()) + ctx.end_exclusive(); + const symbol_exprt success = ctx.temporary(bool_typet{}, "success"); + ctx.assign(success, ctx.nondet(bool_typet{})); + const exprt value = read(ctx, ops[1], size); + const auto skip = ctx.begin_conditional(success); + if(!write(ctx, ops[2], size, value)) + return false; + ctx.end_conditional(skip); + // If the instruction is conditional, it may not execute, and the monitor + // keeps its state. + if(!conditional) + ctx.clear_exclusive(); + return write( + ctx, ops[0], 32, if_exprt{success, constant(0, 32), constant(1, 32)}); + } + + return ctx.fail("unsupported instruction " + instruction.mnemonic); +} + +bool asm_arm_semanticst::lower_system( + const a32_mnemonict &decoded, + std::vector &ops, + asm_lowering_contextt &ctx) const +{ + const std::string &b = decoded.base; + + auto is_reg = [&](std::size_t i) + { return i < ops.size() && ops[i].kind == a32_operandt::kindt::REGISTER; }; + auto is_name = [&](std::size_t i, const std::string &prefix) + { + return i < ops.size() && ops[i].kind == a32_operandt::kindt::NAME && + ops[i].name.compare(0, prefix.size(), prefix) == 0; + }; + + if(b == "mrs") + { + if(ops.size() != 2 || !is_reg(0) || !is_name(1, "")) + return ctx.fail("unsupported mrs"); + const std::string &source = ops[1].name; + if(source == "apsr" || source == "cpsr") + { + // N, Z, C, V are bits 31 to 28; the other bits are not modeled + exprt value = bitand_exprt{ctx.nondet(bv(32)), constant(0x0fffffff, 32)}; + std::size_t bit = 31; + for(const char *f : {"n", "z", "c", "v"}) + { + value = bitor_exprt{ + value, + shl_exprt{typecast_exprt{ctx.flag(f), bv(32)}, constant(bit--, 32)}}; + } + return write(ctx, ops[0], 32, value); + } + // other special registers: their values are not modeled + return write(ctx, ops[0], 32, ctx.nondet(bv(32))); + } + + if(b == "msr") + { + if(ops.size() != 2 || !is_name(0, "")) + return ctx.fail("unsupported msr"); + bool known, flags, control; + msr_fields(ops[0].name, known, flags, control); + if(!known) + return ctx.fail("unsupported special register " + ops[0].name); + if( + ops[1].kind != a32_operandt::kindt::REGISTER && + ops[1].kind != a32_operandt::kindt::IMMEDIATE) + { + return ctx.fail("unsupported operands of msr"); + } + if(flags) + { + const exprt value = read(ctx, ops[1], 32); + const symbol_exprt v = ctx.temporary(value.type(), "psr"); + ctx.assign(v, value); + std::size_t bit = 31; + for(const char *f : {"n", "z", "c", "v"}) + ctx.assign(ctx.flag(f), extractbit_exprt{v, bit--}); + } + // The other fields (the Q and GE flags, the interrupt masks, and the + // processor mode) have no effect on the modeled state; see make_a32_state + // for the registers that a change of mode affects. + return true; + } + + // mrc/mcr coproc, opc1, Rt, CRn, CRm[, opc2] + if( + ops.size() < 5 || ops.size() > 6 || !is_name(0, "p") || !is_reg(2) || + !is_name(3, "c") || !is_name(4, "c")) + { + return ctx.fail("unsupported operands of " + b); + } + + if(b == "mrc") + { + // the value of a coprocessor register is not modeled + return write(ctx, ops[2], 32, ctx.nondet(bv(32))); + } + + // mcr: only CP15 operations without effect on the modeled state + auto immediate = [&](std::size_t i) -> mp_integer + { + if(i >= ops.size()) + return 0; + if( + ops[i].kind != a32_operandt::kindt::IMMEDIATE || + ops[i].value.type().id() != ID_integer) + { + return -1; + } + return numeric_cast_v(to_constant_expr(ops[i].value)); + }; + const std::string &crn = ops[3].name, &crm = ops[4].name; + const mp_integer opc1 = immediate(1), opc2 = immediate(5); + if(ops[0].name != "p15" || opc1 != 0) + return ctx.fail("unsupported coprocessor operation"); + + if(crn == "c7") + { + if(crm == "c10" && (opc2 == 4 || opc2 == 5)) + { + // CP15DSB, CP15DMB + ctx.fence(true, true, true, true, true); + return true; + } + if(crm == "c5" && opc2 == 4) + { + // CP15ISB + ctx.fence(false, false, false, false, false); + return true; + } + // cache maintenance + return true; + } + // TLB maintenance + if(crn == "c8") + return true; + // the software thread ID registers + if(crn == "c13" && crm == "c0" && opc2 >= 2 && opc2 <= 4) + return true; + + return ctx.fail("unsupported coprocessor operation"); +} +} // namespace + +std::unique_ptr make_asm_arm_semantics() +{ + return std::make_unique(); +} diff --git a/src/assembler/asm_arm.h b/src/assembler/asm_arm.h new file mode 100644 index 000000000000..9ededa668d14 --- /dev/null +++ b/src/assembler/asm_arm.h @@ -0,0 +1,21 @@ +/*******************************************************************\ + +Module: Inline assembly: AArch32 instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Instruction semantics for AArch32 + +#ifndef CPROVER_ASSEMBLER_ASM_ARM_H +#define CPROVER_ASSEMBLER_ASM_ARM_H + +#include + +class asm_semanticst; + +std::unique_ptr make_asm_arm_semantics(); + +#endif // CPROVER_ASSEMBLER_ASM_ARM_H diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index a5faced06596..a4de0e55d5d5 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -518,6 +518,8 @@ bool asm_lowering_contextt::prepare( { const std::size_t register_width = semantics.register_width(); + semantics_state = semantics.make_state(instructions); + // The register that holds operand i: that of the output it is tied to, if // any, and that of operands bound to the same register by their constraint. auto register_of = [this](std::size_t i) diff --git a/src/assembler/asm_semantics.cpp b/src/assembler/asm_semantics.cpp index e2e02b74cf59..33721ae7302c 100644 --- a/src/assembler/asm_semantics.cpp +++ b/src/assembler/asm_semantics.cpp @@ -12,6 +12,7 @@ Author: Michael Tautschnig #include "asm_semantics.h" #include "asm_aarch64.h" +#include "asm_arm.h" #include "asm_x86.h" asm_semanticst::constraint_classt asm_semanticst::classify_constraint( @@ -30,6 +31,8 @@ std::unique_ptr make_asm_semantics(const irep_idt &arch) return make_asm_x86_semantics(false); else if(arch == "arm64") return make_asm_aarch64_semantics(); + else if(arch == "arm" || arch == "armel" || arch == "armhf") + return make_asm_arm_semantics(); else return nullptr; } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index 6ef79423e3ca..a1c261d5387e 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -32,6 +32,14 @@ Author: Michael Tautschnig class symbol_table_baset; class asm_semanticst; +/// State of the instruction semantics for one statement, for semantics that +/// depend on the statement as a whole (see \ref asm_semanticst::make_state) +class asm_semantics_statet +{ +public: + virtual ~asm_semantics_statet() = default; +}; + /// The state of lowering one inline assembly statement: the goto code being /// built, the storage of register operands, hardware registers and flags, and /// labels. Architecture semantics use it to emit the effect of instructions. @@ -239,6 +247,10 @@ class asm_lowering_contextt /// for label k), or nil if the statement has no labels exprt goto_target; + /// The state of the semantics for this statement, created by \ref prepare + /// (see \ref asm_semanticst::make_state); may be nullptr + std::unique_ptr semantics_state; + /// \name Conversion between C values and bit-vectors /// \{ @@ -501,6 +513,16 @@ class asm_semanticst virtual bool lower( const asm_instructiont &instruction, asm_lowering_contextt &ctx) const = 0; + + /// \return The state of the semantics for a statement with \p + /// instructions, available to \ref lower as + /// \ref asm_lowering_contextt::semantics_state, or nullptr if the + /// semantics need none + virtual std::unique_ptr + make_state(const std::vector &instructions) const + { + return nullptr; + } }; /// \return The instruction semantics for architecture \p arch (as in From 33b3b55c423f2a126e78e201dde0263199b73207 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:33:42 +0000 Subject: [PATCH 074/100] Inline assembly: AArch32 mode changes and operands in r8 to r14 msr of the control field may change the processor mode, which banks r8 to r14. make_a32_state refused statements that do so only if they name one of these registers, but it looked at identifier tokens only, so operand references were missed although the compiler may allocate them to r8 to r14. CBMC thus proved register unsigned x __asm__("r8") = 1; __asm__ volatile("msr cpsr_c, %1\n mov %0, #2\n msr cpsr_c, %2" : "+r"(x) : "r"(0x11), "r"(0x13)); assert(x == 2); whereas in FIQ mode the mov writes r8_fiq, and the assertion fails. A statement that changes the mode is now also approximated if it uses an operand after the first such msr (whose source may be an operand), or at all if a label precedes that msr, as a later branch could return to it. Operands used before the mode changes, as in the ARMv5 local_irq_save sequence "mrs %0, cpsr; orr %1, %0, #128; msr cpsr_c, %1", remain modeled. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 8 ++- doc/cprover-manual/modeling-inline-asm.md | 6 +- regression/cbmc/asm_arm_corner_cases/main.c | 17 +++++ .../cbmc/asm_arm_corner_cases/test.desc | 3 + src/assembler/asm_arm.cpp | 68 ++++++++++++++----- 5 files changed, 80 insertions(+), 22 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index f2d8512c4280..8410d1959781 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -166,8 +166,12 @@ their registers. Unless the statement starts with `.syntax unified` or uses an instruction or form that Thumb-1 lacks (conditional execution other than of branches, `it`, `s` suffixes other than `movs`, `ldrex`, `teq`, ...), the flags are nondeterministic after such an instruction. And `msr` of the -control field may change the processor mode, which banks r8 to r14, so a -statement that does so and names any of these registers is not interpreted. +control field may change the processor mode, which banks r8 to r14. A +statement that does so is not interpreted if it names any of these +registers, or if it uses an operand, which the compiler may allocate to one +of them, after the first such `msr`. Operands may be used before it, and as +its source, unless a label precedes it, to which a later branch could +return. An `it` instruction has no effect: the instructions of the IT block carry their conditions as suffixes, which the assemblers check against it. A conditional store-exclusive may not execute, so it does not clear the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 12c0d73b2e00..87511547d85f 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -229,8 +229,10 @@ Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an instruction or form that Thumb-1 does not have (such as conditional execution, `it`, or `ldrex`), the flags are nondeterministic after a data-processing instruction without `s` suffix. A statement that changes the -interrupt masks or the processor mode with `msr` and names any of the -registers r8 to r14, which are banked by mode, is not interpreted. Reading or +interrupt masks or the processor mode with `msr` is not interpreted if it +names any of the registers r8 to r14, which are banked by mode, or if it uses +an operand, which the compiler may allocate to one of these registers, after +the first such `msr` (the source of that `msr` may be an operand). Reading or writing `pc` is not modeled. ### Supported Instructions diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index 9c8a14499747..0e30122b6e31 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -153,5 +153,22 @@ int main(void) __asm__ volatile("add r0, r0, #1" : "+r"(r0)); __CPROVER_assert(r0 == 5, "register variable"); // fails + // A change of the processor mode banks r8 to r14, to which the compiler + // may allocate operands: here the mov writes r8_fiq, not the operand. + { + register unsigned banked __asm__("r8") = 1; + unsigned fiq = 0x11, svc = 0x13; + __asm__ volatile("msr cpsr_c, %1\n mov %0, #2\n msr cpsr_c, %2" + : "+r"(banked) + : "r"(fiq), "r"(svc)); + __CPROVER_assert(banked == 2, "operand after mode change"); // fails + } + // operands used before the mode changes are modeled + __asm__ volatile("mov %0, #1\n msr cpsr_c, %1" + : "=&r"(r) + : "r"(0x13) + : "memory"); + __CPROVER_assert(r == 1, "operand before mode change"); + return 0; } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index d7073332cd6c..ee2ee7f056f1 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -24,9 +24,12 @@ main.c ^\[main\.assertion\.19\] line 140 flags after add in unified syntax: SUCCESS$ ^\[main\.assertion\.20\] line 149 store via register variable: FAILURE$ ^\[main\.assertion\.21\] line 154 register variable: FAILURE$ +^\[main\.assertion\.22\] line 164 operand after mode change: FAILURE$ +^\[main\.assertion\.23\] line 171 operand before mode change: SUCCESS$ approximating inline assembly statement at .* line 123 function main: unsupported operands of mov approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered +approximating inline assembly statement at .* line 161 function main: msr of the processor mode, which banks r8 to r14, and operands used after it ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index b6792f59bcf3..1bdb387dfc3f 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -264,7 +264,12 @@ void msr_fields( /// known not to be such code if it starts with `.syntax unified`, or if it /// uses an instruction or form that Thumb-1 does not have. /// - `msr` of the control field may change the processor mode, and with it -/// the registers r8 to r14 that are named, which is not modeled. +/// the registers r8 to r14, which is not modeled. Such a statement must +/// not name these registers, and it must not use operands, which the +/// compiler may allocate to them, after the mode may have changed: it may +/// only use them before the first such `msr`, including as its source, and +/// only if no label precedes that `msr`, to which a later branch could +/// return. std::unique_ptr make_a32_state(const std::vector &instructions) { @@ -289,8 +294,15 @@ make_a32_state(const std::vector &instructions) bool unified_at_start = false, before_first_instruction = true; bool divided = false, changes_mode = false, names_banked = false; + // whether operands are used before or after the mode may have changed, and + // whether a label precedes the first change + bool operand_before_change = false, operand_after_change = false; + bool label_before_change = false; for(const auto &instruction : instructions) { + if(!instruction.labels.empty() && !changes_mode) + label_before_change = true; + const std::string &m = instruction.mnemonic; if(m == ".syntax") { @@ -307,10 +319,34 @@ make_a32_state(const std::vector &instructions) continue; before_first_instruction = false; - for(const auto &operand : instruction.operands) + a32_mnemonict decoded; + const bool is_decoded = decode(m, decoded); + + bool changes_mode_here = false; + if( + is_decoded && decoded.base == "msr" && !instruction.operands.empty() && + instruction.operands[0].size() == 1) { - for(const auto &token : operand) + std::string target = instruction.operands[0][0].text; + for(auto &c : target) + c = static_cast(std::tolower(static_cast(c))); + bool known, flags, control; + msr_fields(target, known, flags, control); + changes_mode_here = !known || control; + } + + for(std::size_t i = 0; i < instruction.operands.size(); ++i) + { + for(const auto &token : instruction.operands[i]) { + if(token.kind == asm_tokent::kindt::OPERAND) + { + // the source of msr is read before the mode changes + if(changes_mode || (changes_mode_here && i != 1)) + operand_after_change = true; + else + operand_before_change = true; + } if(!token.is_identifier()) continue; const std::string reg = canonical_a32_register(token.text); @@ -318,6 +354,8 @@ make_a32_state(const std::vector &instructions) names_banked = true; } } + if(changes_mode_here) + changes_mode = true; if( m.size() >= 2 && m.size() <= 5 && m[0] == 'i' && m[1] == 't' && @@ -328,8 +366,7 @@ make_a32_state(const std::vector &instructions) continue; } - a32_mnemonict decoded; - if(!decode(m, decoded)) + if(!is_decoded) continue; if( not_thumb1.count(decoded.base) != 0 || @@ -338,19 +375,6 @@ make_a32_state(const std::vector &instructions) { state->maybe_thumb1_divided = false; } - - if( - decoded.base == "msr" && !instruction.operands.empty() && - instruction.operands[0].size() == 1) - { - std::string target = instruction.operands[0][0].text; - for(auto &c : target) - c = static_cast(std::tolower(static_cast(c))); - bool known, flags, control; - msr_fields(target, known, flags, control); - if(!known || control) - changes_mode = true; - } } if(unified_at_start && !divided) @@ -362,6 +386,14 @@ make_a32_state(const std::vector &instructions) "msr of the processor mode with named registers r8 to r14, which may be " "banked"; } + else if( + changes_mode && + (operand_after_change || (label_before_change && operand_before_change))) + { + state->failure = + "msr of the processor mode, which banks r8 to r14, and operands used " + "after it, which may be allocated to these registers"; + } return state; } From c34a049ff01480277d073c47b97065ae8bb97eab Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:37:50 +0000 Subject: [PATCH 075/100] Inline assembly: AArch32 Thumb-1 divided syntax with Thumb-2 forms In divided syntax, which GCC uses for inline assembly for Thumb-1 targets, the 16-bit add is adds. make_a32_state took movw, movt, cbz, cbnz, and the exclusive loads and stores as evidence that a statement is not such code, and kept the flags exact. ARMv8-M Baseline, a Thumb-1 target, has all of these, so CBMC proved, for example, r == 2 after cmp %1, %1; movw %0, #1; add %0, %0, #1; beq 1f; mov %0, #7; 1: which GCC assembles for -march=armv8-m.base as adds; the code then returns 7 on qemu-arm. Likewise for an ldrex after the add. Moreover, an explicit .syntax divided in Thumb-2 code selects the Thumb-1 forms of add and the like, while GNU as accepts clz, rbit, rsbs, and so on, so that these instructions are no evidence either. These instructions no longer count as evidence, and the flags are nondeterministic after a data-processing instruction without s suffix in any statement that contains .syntax divided. The remaining evidence (conditional execution other than of branches, it, s suffixes other than movs, teq, clz, rbit, mrc, mcr) is rejected by GNU as in divided syntax for armv4t, armv5t, armv6, armv6-m, and armv8-m.base. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 16 +++++++--- doc/cprover-manual/modeling-inline-asm.md | 20 +++++++----- regression/cbmc/asm_arm_corner_cases/main.c | 32 +++++++++++++++++++ .../cbmc/asm_arm_corner_cases/test.desc | 15 +++++++-- src/assembler/asm_arm.cpp | 26 ++++++--------- 5 files changed, 77 insertions(+), 32 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 8410d1959781..b35d258cf144 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -163,11 +163,17 @@ AArch32 needs two statement-wide properties (`make_a32_state` in code and for Thumb-1 targets, the Thumb-1 data-processing instructions set the flags without an `s` suffix (`add r0, r1, #1` is `adds`), depending on their registers. Unless the statement starts with `.syntax unified` or uses -an instruction or form that Thumb-1 lacks (conditional execution other than -of branches, `it`, `s` suffixes other than `movs`, `ldrex`, `teq`, ...), the -flags are nondeterministic after such an instruction. And `msr` of the -control field may change the processor mode, which banks r8 to r14. A -statement that does so is not interpreted if it names any of these +an instruction or form that GNU as does not accept in divided syntax for +Thumb-1 targets (conditional execution other than of branches, `it`, `s` +suffixes other than `movs`, `teq`, `clz`, ...), the flags are +nondeterministic after such an instruction; `movw`, `movt`, `cbz`, `cbnz`, +and the exclusive loads and stores are no such evidence, as ARMv8-M Baseline +has them. An explicit `.syntax divided` anywhere in the statement selects +these forms in Thumb-2 code too, where the assembler also accepts the other +instructions, so the flags are then nondeterministic in any case. + +And `msr` of the control field may change the processor mode, which banks r8 +to r14. A statement that does so is not interpreted if it names any of these registers, or if it uses an operand, which the compiler may allocate to one of them, after the first such `msr`. Operands may be used before it, and as its source, unless a label precedes it, to which a later branch could diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 87511547d85f..f3eb56fdb194 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -226,14 +226,18 @@ syntax: In divided syntax, which GCC uses for inline assembly in A32 code and for Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an `s` suffix. Unless the statement starts with `.syntax unified`, or uses an -instruction or form that Thumb-1 does not have (such as conditional -execution, `it`, or `ldrex`), the flags are nondeterministic after a -data-processing instruction without `s` suffix. A statement that changes the -interrupt masks or the processor mode with `msr` is not interpreted if it -names any of the registers r8 to r14, which are banked by mode, or if it uses -an operand, which the compiler may allocate to one of these registers, after -the first such `msr` (the source of that `msr` may be an operand). Reading or -writing `pc` is not modeled. +instruction or form that the assembler does not accept in divided syntax for +Thumb-1 targets (such as conditional execution, `it`, or `clz`; ARMv8-M +Baseline has `movw`, `movt`, `cbz`, `cbnz`, and `ldrex`), the flags are +nondeterministic after a data-processing instruction without `s` suffix. They +are so in any case if the statement selects divided syntax with +`.syntax divided`, which applies to Thumb-2 code as well. + +A statement that changes the interrupt masks or the processor mode with `msr` +is not interpreted if it names any of the registers r8 to r14, which are +banked by mode, or if it uses an operand, which the compiler may allocate to +one of these registers, after the first such `msr` (the source of that `msr` +may be an operand). Reading or writing `pc` is not modeled. ### Supported Instructions diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index 0e30122b6e31..67c97802b390 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -170,5 +170,37 @@ int main(void) : "memory"); __CPROVER_assert(r == 1, "operand before mode change"); + // ARMv8-M Baseline is a Thumb-1 target, for which GCC uses divided syntax, + // but it has movw and ldrex: the add may still be adds. + unsigned t; + __asm__("cmp %1, %1\n movw %0, #1\n add %0, %0, #1\n beq 1f\n mov %0, #7\n1:" + : "=&l"(r) + : "l"(0) + : "cc"); + __CPROVER_assert(r == 2, "flags after add with movw"); // fails + __asm__( + "cmp %2, %2\n add %0, %2, #1\n beq 1f\n mov %0, #7\n" + "1: ldrex %1, [%3]" + : "=&l"(r), "=&l"(t) + : "l"(0), "l"(&x) + : "memory", "cc"); + __CPROVER_assert(r == 1, "flags after add with ldrex"); // fails + // with explicit divided syntax, Thumb-2 code uses the Thumb-1 forms too, + // and the assembler accepts clz and rsbs + __asm__( + ".syntax divided\n cmp %1, %1\n clz %0, %1\n add %0, %0, #1\n" + " beq 1f\n mov %0, #7\n1:\n.syntax unified" + : "=&l"(r) + : "l"(0) + : "cc"); + __CPROVER_assert(r == 33, "flags after add with clz"); // fails + __asm__( + ".syntax divided\n rsbs %1, %2, #0\n cmp %2, %2\n add %0, %2, #1\n" + " beq 1f\n mov %0, #7\n1:\n.syntax unified" + : "=&l"(r), "=&l"(t) + : "l"(0) + : "cc"); + __CPROVER_assert(r == 1, "flags after add with rsbs"); // fails + return 0; } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index ee2ee7f056f1..b17ced26943f 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -26,6 +26,10 @@ main.c ^\[main\.assertion\.21\] line 154 register variable: FAILURE$ ^\[main\.assertion\.22\] line 164 operand after mode change: FAILURE$ ^\[main\.assertion\.23\] line 171 operand before mode change: SUCCESS$ +^\[main\.assertion\.24\] line 180 flags after add with movw: FAILURE$ +^\[main\.assertion\.25\] line 187 flags after add with ldrex: FAILURE$ +^\[main\.assertion\.26\] line 196 flags after add with clz: FAILURE$ +^\[main\.assertion\.27\] line 203 flags after add with rsbs: FAILURE$ approximating inline assembly statement at .* line 123 function main: unsupported operands of mov approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered @@ -34,9 +38,14 @@ approximating inline assembly statement at .* line 161 function main: msr of the -- ^warning: ignoring approximating inline assembly statement at .* function add_ll_sc +approximating inline assembly statement at .* line (167|176|181|190|197) -- The properties marked "fails" in main.c may be violated on hardware; all others hold on hardware. The results were validated with qemu-arm, for A32 -and T32 code compiled by GCC and Clang. "flags after add in divided syntax" -holds in A32 and T32 code, but is violated for Thumb-1 targets, where the add -sets the flags. +and T32 code compiled by GCC and Clang (from "operand after mode change" on, +by GCC only, as Clang does not support divided syntax). "flags after add in +divided syntax" holds in A32 and T32 code, but is violated for Thumb-1 +targets, where the add sets the flags. So are "flags after add with movw" and +"flags after add with ldrex", as validated with code compiled by GCC for +-march=armv8-m.base, while "flags after add with clz" and "flags after add +with rsbs" are violated in T32 code. diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 1bdb387dfc3f..2cf6afa34481 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -262,7 +262,10 @@ void msr_fields( /// for Thumb-1 targets, Thumb-1 data-processing instructions without an `s` /// suffix may set the flags (`add r0, r1, r2` is `adds`). The statement is /// known not to be such code if it starts with `.syntax unified`, or if it -/// uses an instruction or form that Thumb-1 does not have. +/// uses an instruction or form that GNU as does not accept in divided +/// syntax for Thumb-1 targets, unless the statement selects divided syntax +/// explicitly. ARMv8-M Baseline, a Thumb-1 target, has `movw`, `movt`, +/// `cbz`, `cbnz`, and the exclusive loads and stores. /// - `msr` of the control field may change the processor mode, and with it /// the registers r8 to r14, which is not modeled. Such a statement must /// not name these registers, and it must not use operands, which the @@ -276,21 +279,7 @@ make_a32_state(const std::vector &instructions) auto state = std::make_unique(); static const std::set not_thumb1 = { - "teq", - "clz", - "rbit", - "movw", - "movt", - "cbz", - "cbnz", - "ldrex", - "ldrexb", - "ldrexh", - "strex", - "strexb", - "strexh", - "mrc", - "mcr"}; + "teq", "clz", "rbit", "mrc", "mcr"}; bool unified_at_start = false, before_first_instruction = true; bool divided = false, changes_mode = false, names_banked = false; @@ -379,6 +368,11 @@ make_a32_state(const std::vector &instructions) if(unified_at_start && !divided) state->maybe_thumb1_divided = false; + // In Thumb code, an explicit .syntax divided selects the Thumb-1 forms + // even on a Thumb-2 target, where the assembler also accepts instructions + // and forms that Thumb-1 lacks. + if(divided) + state->maybe_thumb1_divided = true; if(changes_mode && names_banked) { From 6fb000e18dd9fd3df2d1590e1c004c34c08419d2 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:39:18 +0000 Subject: [PATCH 076/100] Inline assembly: AArch32 movs in Thumb-1 divided syntax In divided syntax for Thumb-1 targets, GNU as assembles movs between low registers as adds with #0, which clears C and V, and movs with a high register as mov, which keeps the flags. CBMC modeled movs as in unified syntax (N and Z set, C and V unchanged), and so proved r == 5 after cmp %1, %1; movs %0, %2; bcs 1f; mov %0, #7; 1: with %2 holding 5, whereas the code that GCC generates for -march=armv5t or -march=armv8-m.base yields 7 on qemu-arm. Where the statement may be divided Thumb-1 code, the flags are now nondeterministic after movs, as after the data-processing instructions without s suffix. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 4 +++- doc/cprover-manual/modeling-inline-asm.md | 7 ++++--- regression/cbmc/asm_arm_corner_cases/main.c | 8 ++++++++ regression/cbmc/asm_arm_corner_cases/test.desc | 6 ++++-- src/assembler/asm_arm.cpp | 7 +++++-- 5 files changed, 24 insertions(+), 8 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index b35d258cf144..a0246b5a9988 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -170,7 +170,9 @@ nondeterministic after such an instruction; `movw`, `movt`, `cbz`, `cbnz`, and the exclusive loads and stores are no such evidence, as ARMv8-M Baseline has them. An explicit `.syntax divided` anywhere in the statement selects these forms in Thumb-2 code too, where the assembler also accepts the other -instructions, so the flags are then nondeterministic in any case. +instructions, so the flags are then nondeterministic in any case. In such +code, `movs` between low registers is `adds` with `#0`, which clears C and V, +so the flags are nondeterministic after `movs` as well. And `msr` of the control field may change the processor mode, which banks r8 to r14. A statement that does so is not interpreted if it names any of these diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index f3eb56fdb194..b11c9fce9b93 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -229,9 +229,10 @@ Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an instruction or form that the assembler does not accept in divided syntax for Thumb-1 targets (such as conditional execution, `it`, or `clz`; ARMv8-M Baseline has `movw`, `movt`, `cbz`, `cbnz`, and `ldrex`), the flags are -nondeterministic after a data-processing instruction without `s` suffix. They -are so in any case if the statement selects divided syntax with -`.syntax divided`, which applies to Thumb-2 code as well. +nondeterministic after a data-processing instruction without `s` suffix, and +after `movs`, which is then `adds` with `#0`. They are so in any case if the +statement selects divided syntax with `.syntax divided`, which applies to +Thumb-2 code as well. A statement that changes the interrupt masks or the processor mode with `msr` is not interpreted if it names any of the registers r8 to r14, which are diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index 67c97802b390..64e9a81dd50b 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -202,5 +202,13 @@ int main(void) : "cc"); __CPROVER_assert(r == 1, "flags after add with rsbs"); // fails + // in divided syntax for Thumb-1 targets, movs is adds with #0, which + // clears C + __asm__("cmp %1, %1\n movs %0, %2\n bcs 1f\n mov %0, #7\n1:" + : "=&l"(r) + : "l"(0), "l"(5) + : "cc"); + __CPROVER_assert(r == 5, "carry after movs"); // fails + return 0; } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index b17ced26943f..cc4383672e61 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -30,6 +30,7 @@ main.c ^\[main\.assertion\.25\] line 187 flags after add with ldrex: FAILURE$ ^\[main\.assertion\.26\] line 196 flags after add with clz: FAILURE$ ^\[main\.assertion\.27\] line 203 flags after add with rsbs: FAILURE$ +^\[main\.assertion\.28\] line 211 carry after movs: FAILURE$ approximating inline assembly statement at .* line 123 function main: unsupported operands of mov approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered @@ -38,7 +39,7 @@ approximating inline assembly statement at .* line 161 function main: msr of the -- ^warning: ignoring approximating inline assembly statement at .* function add_ll_sc -approximating inline assembly statement at .* line (167|176|181|190|197) +approximating inline assembly statement at .* line (167|176|181|190|197|207) -- The properties marked "fails" in main.c may be violated on hardware; all others hold on hardware. The results were validated with qemu-arm, for A32 @@ -48,4 +49,5 @@ divided syntax" holds in A32 and T32 code, but is violated for Thumb-1 targets, where the add sets the flags. So are "flags after add with movw" and "flags after add with ldrex", as validated with code compiled by GCC for -march=armv8-m.base, while "flags after add with clz" and "flags after add -with rsbs" are violated in T32 code. +with rsbs" are violated in T32 code. "carry after movs" is violated in code +compiled by GCC for -march=armv5t or -march=armv8-m.base. diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 2cf6afa34481..2ff63ba8ffb3 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -860,9 +860,12 @@ bool asm_arm_semanticst::lower( return false; // In divided syntax for Thumb-1, data-processing instructions without - // an `s` suffix may set the flags (depending on the registers). + // an `s` suffix may set the flags (depending on the registers), and + // `movs` is `adds` with #0 (which clears C and V) or, if a register is + // r8 or above, `mov`, which keeps the flags. if( - state->maybe_thumb1_divided && !decoded.sets_flags && + state->maybe_thumb1_divided && + (!decoded.sets_flags || decoded.base == "mov") && flag_setting_operations().count(decoded.base) != 0) { for(const char *f : {"n", "z", "c", "v"}) From 095128b735b8d47640a7a221ca0a4462d1e222b2 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:40:34 +0000 Subject: [PATCH 077/100] Inline assembly: AArch32 cache invalidation without cleaning lower_system treated every CP15 operation with CRn c7 other than the barriers as cache maintenance without effect on the modeled state. The operations that invalidate data or unified caches without cleaning them (CRm c6 and c7: DCIMVAC, DCISW, and the ARMv5/ARMv6 whole-cache and unified forms) may discard dirty lines, so that memory reverts to an older value. CBMC thus proved x = 1; __asm__ volatile("mcr p15, 0, %0, c7, c6, 1" : : "r"(&x) : "memory"); assert(x == 1); Only the c7 operations known not to change memory are now interpreted: invalidating instruction caches and branch predictors, cleaning, and cleaning and invalidating data or unified caches, as well as the ARMv6 CP15 wait for interrupt and the barriers. Invalidation without cleaning, and any other c7 operation (such as the address translation operations), makes the statement approximated. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 5 ++- regression/cbmc/asm_arm_corner_cases/main.c | 10 ++++++ .../cbmc/asm_arm_corner_cases/test.desc | 5 ++- src/assembler/asm_arm.cpp | 31 +++++++++++++++++-- 4 files changed, 47 insertions(+), 4 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index b11c9fce9b93..c9bb56a99f51 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -221,7 +221,10 @@ syntax: the flags (`apsr`, `cpsr`), the interrupt masks (`msr` of `cpsr_c`, `cpsid`, `cpsie`), hints (`nop`, `yield`, `wfe`, `pld`, ...), and CP15 cache and TLB maintenance and thread ID registers (`mcr`); `mrs` of other - special registers and `mrc` produce nondeterministic values. + special registers and `mrc` produce nondeterministic values. Of the cache + maintenance operations, those that invalidate data or unified caches + without cleaning them (`mcr p15, 0, Rt, c7, c6, 1`, for example) are not + modeled, as they may discard data that is not written back to memory. In divided syntax, which GCC uses for inline assembly in A32 code and for Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index 64e9a81dd50b..e7d675b925f6 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -210,5 +210,15 @@ int main(void) : "cc"); __CPROVER_assert(r == 5, "carry after movs"); // fails + // Invalidating a data cache line without cleaning it may discard a dirty + // line, so that memory reverts to an older value, unlike cleaning and + // invalidating it. + x = 1; + __asm__ volatile("mcr p15, 0, %0, c7, c6, 1" : : "r"(&x) : "memory"); + __CPROVER_assert(x == 1, "invalidate data cache line"); // fails + x = 1; + __asm__ volatile("mcr p15, 0, %0, c7, c14, 1" : : "r"(&x) : "memory"); + __CPROVER_assert(x == 1, "clean and invalidate data cache line"); + return 0; } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index cc4383672e61..f81c16c29ac2 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -31,15 +31,18 @@ main.c ^\[main\.assertion\.26\] line 196 flags after add with clz: FAILURE$ ^\[main\.assertion\.27\] line 203 flags after add with rsbs: FAILURE$ ^\[main\.assertion\.28\] line 211 carry after movs: FAILURE$ +^\[main\.assertion\.29\] line 218 invalidate data cache line: FAILURE$ +^\[main\.assertion\.30\] line 221 clean and invalidate data cache line: SUCCESS$ approximating inline assembly statement at .* line 123 function main: unsupported operands of mov approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered approximating inline assembly statement at .* line 161 function main: msr of the processor mode, which banks r8 to r14, and operands used after it +approximating inline assembly statement at .* line 217 function main: cache invalidation without cleaning ^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly statement at .* function add_ll_sc -approximating inline assembly statement at .* line (167|176|181|190|197|207) +approximating inline assembly statement at .* line (167|176|181|190|197|207|220) -- The properties marked "fails" in main.c may be violated on hardware; all others hold on hardware. The results were validated with qemu-arm, for A32 diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 2ff63ba8ffb3..4685d707c431 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -1340,8 +1340,35 @@ bool asm_arm_semanticst::lower_system( ctx.fence(false, false, false, false, false); return true; } - // cache maintenance - return true; + // Cache maintenance that does not change memory: invalidating + // instruction caches and branch predictors, and cleaning, or cleaning + // and invalidating, data or unified caches (and the CP15 wait for + // interrupt of ARMv6). Invalidating data or unified caches without + // cleaning them (c6 and c7) may discard data that is not written back, + // so that memory reverts to older values. + static const std::map> no_effect = { + {"c0", {4}}, + {"c1", {0, 6}}, + {"c5", {0, 1, 2, 6, 7}}, + {"c10", {0, 1, 2}}, + {"c11", {0, 1, 2}}, + {"c13", {1}}, + {"c14", {0, 1, 2}}, + {"c15", {0, 1, 2}}}; + const auto operation = no_effect.find(crm); + if( + operation != no_effect.end() && opc2 >= 0 && opc2 <= 7 && + operation->second.count(numeric_cast_v(opc2)) != 0) + { + return true; + } + if(crm == "c6" || crm == "c7") + { + return ctx.fail( + "cache invalidation without cleaning, which may discard data that is " + "not written back"); + } + return ctx.fail("unsupported coprocessor operation"); } // TLB maintenance if(crn == "c8") From 7add8e9822a3e7cef431c9bb2351e78103b07646 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:43:06 +0000 Subject: [PATCH 078/100] Inline assembly: AArch32 width qualifiers in the statement-wide scan lower strips the width qualifiers .n and .w before decoding a mnemonic, but make_a32_state decoded the raw mnemonic, so add.w was skipped. The qualifiers exist in unified syntax only, yet without other evidence the statement was taken as possibly divided Thumb-1 code, and the flags were nondeterministic after the add.w. CBMC thus reported a spurious failure of r == x + 1 after cmp %1, %1; add.w %0, %1, #1; beq 1f; mov %0, #7; 1: The statement-wide scan and lower now share helpers that strip the width qualifiers (normalise_mnemonic) and recognise IT instructions (is_it_mnemonic), so that the two cannot drift apart, and a width qualifier shows that the statement is not divided Thumb-1 code. A single to_lower helper replaces the four lower-casing loops. The new test asm_arm_instructions holds cases that exist in one instruction set only, each in a function with a target attribute. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 5 +- doc/cprover-manual/modeling-inline-asm.md | 10 +-- regression/cbmc/asm_arm_instructions/main.c | 24 ++++++ .../cbmc/asm_arm_instructions/test.desc | 15 ++++ src/assembler/asm_arm.cpp | 85 ++++++++++++------- 5 files changed, 100 insertions(+), 39 deletions(-) create mode 100644 regression/cbmc/asm_arm_instructions/main.c create mode 100644 regression/cbmc/asm_arm_instructions/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index a0246b5a9988..7edd2763e113 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -165,8 +165,9 @@ the flags without an `s` suffix (`add r0, r1, #1` is `adds`), depending on their registers. Unless the statement starts with `.syntax unified` or uses an instruction or form that GNU as does not accept in divided syntax for Thumb-1 targets (conditional execution other than of branches, `it`, `s` -suffixes other than `movs`, `teq`, `clz`, ...), the flags are -nondeterministic after such an instruction; `movw`, `movt`, `cbz`, `cbnz`, +suffixes other than `movs`, the width qualifiers `.n` and `.w`, `teq`, +`clz`, ...), the flags are nondeterministic after such an instruction; +`movw`, `movt`, `cbz`, `cbnz`, and the exclusive loads and stores are no such evidence, as ARMv8-M Baseline has them. An explicit `.syntax divided` anywhere in the statement selects these forms in Thumb-2 code too, where the assembler also accepts the other diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index c9bb56a99f51..cc3ce439a2c7 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -230,11 +230,11 @@ In divided syntax, which GCC uses for inline assembly in A32 code and for Thumb-1 targets, Thumb-1 instructions such as `add` set the flags without an `s` suffix. Unless the statement starts with `.syntax unified`, or uses an instruction or form that the assembler does not accept in divided syntax for -Thumb-1 targets (such as conditional execution, `it`, or `clz`; ARMv8-M -Baseline has `movw`, `movt`, `cbz`, `cbnz`, and `ldrex`), the flags are -nondeterministic after a data-processing instruction without `s` suffix, and -after `movs`, which is then `adds` with `#0`. They are so in any case if the -statement selects divided syntax with `.syntax divided`, which applies to +Thumb-1 targets (such as conditional execution, `it`, `.w`, or `clz`; +ARMv8-M Baseline has `movw`, `movt`, `cbz`, `cbnz`, and `ldrex`), the flags +are nondeterministic after a data-processing instruction without `s` suffix, +and after `movs`, which is then `adds` with `#0`. They are so in any case if +the statement selects divided syntax with `.syntax divided`, which applies to Thumb-2 code as well. A statement that changes the interrupt masks or the processor mode with `msr` diff --git a/regression/cbmc/asm_arm_instructions/main.c b/regression/cbmc/asm_arm_instructions/main.c new file mode 100644 index 000000000000..f33f7f742be0 --- /dev/null +++ b/regression/cbmc/asm_arm_instructions/main.c @@ -0,0 +1,24 @@ +// Instructions and forms of the AArch32 semantics, each case in a function of +// its own; a target attribute marks cases that exist in one instruction set +// only. "fails" marks properties that the architecture permits to be +// violated, so CBMC must not prove them. + +unsigned nondet_unsigned(void); + +// The width qualifiers .w and .n exist in unified syntax only, so that the +// add does not set the flags. +__attribute__((target("thumb"), noinline)) static void width_qualifiers(void) +{ + unsigned x = nondet_unsigned(), r; + __asm__("cmp %1, %1\n add.w %0, %1, #1\n beq.n 1f\n mov %0, #7\n1:" + : "=&r"(r) + : "r"(x) + : "cc"); + __CPROVER_assert(r == x + 1, "add.w"); +} + +int main(void) +{ + width_qualifiers(); + return 0; +} diff --git a/regression/cbmc/asm_arm_instructions/test.desc b/regression/cbmc/asm_arm_instructions/test.desc new file mode 100644 index 000000000000..b096cf16ab48 --- /dev/null +++ b/regression/cbmc/asm_arm_instructions/test.desc @@ -0,0 +1,15 @@ +CORE gcc-only no-new-smt +main.c +--arch arm +^EXIT=0$ +^SIGNAL=0$ +^\[width_qualifiers\.assertion\.1\] line 17 add\.w: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly statement +-- +The properties marked "fails" in main.c may be violated on hardware; all +others hold on hardware. The results were validated with qemu-arm, for code +compiled by GCC for A32 and T32 (-marm and -mthumb, with the functions that +have a target attribute in that instruction set only). diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 4685d707c431..f35d1d371fea 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -17,6 +17,7 @@ Author: Michael Tautschnig #include #include #include +#include #include "asm_arm_flags.h" #include "asm_bv_util.h" @@ -157,6 +158,42 @@ bool decode(const std::string &m, a32_mnemonict &result) return false; } +/// \return \p s in lower case +std::string to_lower(std::string s) +{ + std::transform( + s.begin(), + s.end(), + s.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return s; +} + +/// \return \p mnemonic without a width qualifier (`.n` or `.w`), which +/// selects an encoding in unified syntax +std::string normalise_mnemonic(const std::string &mnemonic) +{ + if( + mnemonic.size() > 2 && + (has_suffix(mnemonic, ".n") || has_suffix(mnemonic, ".w"))) + { + return mnemonic.substr(0, mnemonic.size() - 2); + } + return mnemonic; +} + +/// \return True iff \p mnemonic is that of an IT instruction (`it`, `itt`, +/// `ite`, ..., up to four conditional instructions) +bool is_it_mnemonic(const std::string &mnemonic) +{ + return mnemonic.size() >= 2 && mnemonic.size() <= 5 && mnemonic[0] == 'i' && + mnemonic[1] == 't' && + std::all_of( + mnemonic.begin() + 2, + mnemonic.end(), + [](char c) { return c == 't' || c == 'e'; }); +} + /// What the instruction semantics need to know about the statement as a /// whole class a32_statet : public asm_semantics_statet @@ -173,9 +210,7 @@ class a32_statet : public asm_semantics_statet /// empty string if \p raw is not one (`pc` is not modeled) std::string canonical_a32_register(const std::string &raw) { - std::string name = raw; - for(auto &c : name) - c = static_cast(std::tolower(static_cast(c))); + const std::string name = to_lower(raw); static const std::map aliases = { {"sb", "r9"}, @@ -292,8 +327,8 @@ make_a32_state(const std::vector &instructions) if(!instruction.labels.empty() && !changes_mode) label_before_change = true; - const std::string &m = instruction.mnemonic; - if(m == ".syntax") + const std::string &raw = instruction.mnemonic; + if(raw == ".syntax") { const bool unified = instruction.operands.size() == 1 && instruction.operands[0].size() == 1 && @@ -304,10 +339,15 @@ make_a32_state(const std::vector &instructions) divided = true; continue; } - if(m.empty() || instruction.is_directive()) + if(raw.empty() || instruction.is_directive()) continue; before_first_instruction = false; + // the width qualifiers exist in unified syntax only + const std::string m = normalise_mnemonic(raw); + if(m != raw) + state->maybe_thumb1_divided = false; + a32_mnemonict decoded; const bool is_decoded = decode(m, decoded); @@ -316,11 +356,9 @@ make_a32_state(const std::vector &instructions) is_decoded && decoded.base == "msr" && !instruction.operands.empty() && instruction.operands[0].size() == 1) { - std::string target = instruction.operands[0][0].text; - for(auto &c : target) - c = static_cast(std::tolower(static_cast(c))); bool known, flags, control; - msr_fields(target, known, flags, control); + msr_fields( + to_lower(instruction.operands[0][0].text), known, flags, control); changes_mode_here = !known || control; } @@ -346,10 +384,7 @@ make_a32_state(const std::vector &instructions) if(changes_mode_here) changes_mode = true; - if( - m.size() >= 2 && m.size() <= 5 && m[0] == 'i' && m[1] == 't' && - std::all_of( - m.begin() + 2, m.end(), [](char c) { return c == 't' || c == 'e'; })) + if(is_it_mnemonic(m)) { state->maybe_thumb1_divided = false; continue; @@ -663,9 +698,7 @@ bool asm_arm_semanticst::parse_operand( return true; } operand.kind = a32_operandt::kindt::NAME; - operand.name = first.text; - for(auto &c : operand.name) - c = static_cast(std::tolower(static_cast(c))); + operand.name = to_lower(first.text); return true; } @@ -754,27 +787,17 @@ bool asm_arm_semanticst::lower( if(!state->failure.empty()) return ctx.fail(state->failure); - std::string m = instruction.mnemonic; - if(!instruction.prefixes.empty()) return ctx.fail("unexpected prefix"); // the width qualifiers of unified syntax select an encoding - if( - m.size() > 2 && (m.compare(m.size() - 2, 2, ".n") == 0 || - m.compare(m.size() - 2, 2, ".w") == 0)) - { - m.erase(m.size() - 2); - } + const std::string m = normalise_mnemonic(instruction.mnemonic); // An IT block makes the next (up to four) instructions conditional. Each // of these carries its condition as a suffix, which the assemblers check // against the IT instruction, so that the IT instruction itself has no // further effect. - if( - m.size() >= 2 && m.size() <= 5 && m[0] == 'i' && m[1] == 't' && - std::all_of( - m.begin() + 2, m.end(), [](char c) { return c == 't' || c == 'e'; })) + if(is_it_mnemonic(m)) { if( instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || @@ -782,9 +805,7 @@ bool asm_arm_semanticst::lower( { return ctx.fail("unsupported " + m); } - std::string condition = instruction.operands[0][0].text; - for(auto &c : condition) - c = static_cast(std::tolower(static_cast(c))); + const std::string condition = to_lower(instruction.operands[0][0].text); if(asm_arm::condition_codes().count(condition) == 0) return ctx.fail("unsupported " + m); return true; From 12c60f23c578899879c4684cfcfcd25f1a8d28f2 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:47:31 +0000 Subject: [PATCH 079/100] Inline assembly: AArch32 conditional exclusive loads and stores The exclusive access region and the exclusive monitor are tracked while lowering, not on the paths that execute the instructions, but the condition of an instruction only guards its code. Hence a conditional ldrex opened the region also on the path where it does not execute, and a conditional strex ended the region on both paths. For clrex; cmp one, #0; ldrexeq v, [p]; strex st, rep, [p] with one == 1, the strex fails on hardware, while CBMC let it succeed. In "ldrex; add; cmp nz, #0; strexeq; strexne" the strexne that executes succeeded outside any atomic section, so that CBMC reported a lost update in a two-thread increment. Both are over-approximations, but they were not reported as approximations. A statement with a conditional load-exclusive, or with a conditional store-exclusive and another store-exclusive, is now approximated. A conditional store-exclusive that is the only one of its statement, as in the compare-and-swap sequence "ldrex; mov; teq; strexeq" of Linux, is modeled exactly: the atomic section from the load-exclusive includes it, and no other store-exclusive observes the monitor that it leaves set if it does not execute. asm_arm_exclusive now checks that such a compare-and-swap is atomic. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 7 ++++- doc/cprover-manual/modeling-inline-asm.md | 6 ++-- .../asm_arm_conditional_exclusive/main.c | 30 +++++++++++++++++++ .../asm_arm_conditional_exclusive/test.desc | 15 ++++++++++ .../cbmc-concurrency/asm_arm_exclusive/main.c | 22 +++++++++++++- .../asm_arm_exclusive/test.desc | 8 +++-- regression/cbmc/asm_arm_corner_cases/main.c | 26 ++++++++++++++-- .../cbmc/asm_arm_corner_cases/test.desc | 14 +++++++-- src/assembler/asm_arm.cpp | 29 ++++++++++++++++++ 9 files changed, 145 insertions(+), 12 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_arm_conditional_exclusive/main.c create mode 100644 regression/cbmc-concurrency/asm_arm_conditional_exclusive/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 7edd2763e113..0a17dd1a14d5 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -184,7 +184,12 @@ return. An `it` instruction has no effect: the instructions of the IT block carry their conditions as suffixes, which the assemblers check against it. A conditional store-exclusive may not execute, so it does not clear the -exclusive monitor. +exclusive monitor. As the exclusive access region and the monitor are +tracked while lowering, not on the paths that execute the instructions, a +statement with a conditional load-exclusive, or with a conditional +store-exclusive and another store-exclusive, is not interpreted (a +conditional load-exclusive would open the region on both paths, and a +conditional store-exclusive ends it on both). For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index cc3ce439a2c7..332a1421ba74 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -213,8 +213,10 @@ syntax: `ldrsh`, `str`, `strb`, `strh`) with an immediate or register offset (not with writeback), and load-exclusive/store-exclusive (`ldrex`, `strex`, their byte and halfword forms, and `clrex`), as on AArch64 (see above); - a conditional store-exclusive that does not execute leaves the exclusive - monitor as it was; + a conditional store-exclusive, as in compare-and-swap sequences, is + modeled if it is the only store-exclusive of the statement, but a + statement with a conditional load-exclusive, or with a conditional + store-exclusive and another store-exclusive, is not interpreted; - branches within the statement and to the labels of `asm goto` (`b`, `b`, `cbz`, `cbnz`), and flag outputs (`=@cc`); - barriers (`dmb`, `dsb`, `isb`, and their CP15 forms), `mrs` and `msr` of diff --git a/regression/cbmc-concurrency/asm_arm_conditional_exclusive/main.c b/regression/cbmc-concurrency/asm_arm_conditional_exclusive/main.c new file mode 100644 index 000000000000..72d5b4ac6261 --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_conditional_exclusive/main.c @@ -0,0 +1,30 @@ +// A load-exclusive, then a strexeq that does not execute and a strexne that +// does, which hardware makes atomic with the load-exclusive. The statement is +// approximated. +unsigned x, done; + +void two_stores(unsigned nz) +{ + unsigned tmp, status; + __asm__ volatile( + "ldrex %0, [%2]\n" + " add %0, %0, #1\n" + " cmp %3, #0\n" + " ite eq\n" + " strexeq %1, %0, [%2]\n" + " strexne %1, %0, [%2]" + : "=&r"(tmp), "=&r"(status) + : "r"(&x), "r"(nz) + : "cc", "memory"); + __CPROVER_assume(status == 0); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + two_stores(1), done = 1; + two_stores(1); + __CPROVER_assume(done); + __CPROVER_assert(x == 2, "two store-exclusives"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_arm_conditional_exclusive/test.desc b/regression/cbmc-concurrency/asm_arm_conditional_exclusive/test.desc new file mode 100644 index 000000000000..bcfd3bf47d7f --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_conditional_exclusive/test.desc @@ -0,0 +1,15 @@ +CORE gcc-only +main.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 28 two store-exclusives: FAILURE$ +approximating inline assembly statement at .* function two_stores: conditional load-exclusive, or conditional store-exclusive and another store-exclusive +^VERIFICATION FAILED$ +-- +^warning: ignoring +-- +The property holds on hardware, but the statement is approximated, as its +lowering would not make the store-exclusive that executes atomic with the +load-exclusive. A conditional store-exclusive that is the only one of its +statement is modeled (see asm_arm_exclusive). diff --git a/regression/cbmc-concurrency/asm_arm_exclusive/main.c b/regression/cbmc-concurrency/asm_arm_exclusive/main.c index ba9a10b181af..d256d9c51874 100644 --- a/regression/cbmc-concurrency/asm_arm_exclusive/main.c +++ b/regression/cbmc-concurrency/asm_arm_exclusive/main.c @@ -1,6 +1,23 @@ // A load-exclusive/store-exclusive sequence is atomic; plain loads and // stores are not. -unsigned x, y, done; +unsigned x, y, z, done; + +// compare and swap with a conditional store-exclusive, as in Linux +unsigned cmpxchg(unsigned *p, unsigned old, unsigned new) +{ + unsigned res, prev; + __asm__ volatile( + "ldrex %1, [%2]\n" + " mov %0, #0\n" + " teq %1, %3\n" + " it eq\n" + " strexeq %0, %4, [%2]" + : "=&r"(res), "=&r"(prev) + : "r"(p), "r"(old), "r"(new) + : "cc", "memory"); + __CPROVER_assume(res == 0); + return prev; +} void t(void) { @@ -21,6 +38,8 @@ void t(void) : "=&r"(tmp) : "r"(&y) : "memory"); + unsigned old = z; + __CPROVER_assume(cmpxchg(&z, old, old + 1) == old); } int main(void) @@ -31,5 +50,6 @@ int main(void) __CPROVER_assume(done); __CPROVER_assert(x == 2, "ll/sc increment"); __CPROVER_assert(y == 2, "plain increment"); // fails + __CPROVER_assert(z == 2, "compare and swap increment"); return 0; } diff --git a/regression/cbmc-concurrency/asm_arm_exclusive/test.desc b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc index 7938e8bb07f5..a0ddf6ab0830 100644 --- a/regression/cbmc-concurrency/asm_arm_exclusive/test.desc +++ b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc @@ -3,12 +3,14 @@ main.c --arch arm --unwind 2 --no-unwinding-assertions ^EXIT=10$ ^SIGNAL=0$ -^\[main\.assertion\.1\] line 32 ll/sc increment: SUCCESS$ -^\[main\.assertion\.2\] line 33 plain increment: FAILURE$ +^\[main\.assertion\.1\] line 51 ll/sc increment: SUCCESS$ +^\[main\.assertion\.2\] line 52 plain increment: FAILURE$ +^\[main\.assertion\.3\] line 53 compare and swap increment: SUCCESS$ ^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly -- A load-exclusive/store-exclusive sequence is an atomic section; a plain -read-modify-write is not. +read-modify-write is not. A conditional store-exclusive that is the only +store-exclusive of its statement is part of the atomic section. diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index e7d675b925f6..a816a5fef946 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -67,8 +67,8 @@ int main(void) : "memory"); __CPROVER_assert(m == 1 && res == 1, "store-exclusive after clrex"); - // a conditional store-exclusive that does not execute leaves the monitor - // set, so that the next one may succeed + // a conditional store-exclusive followed by another one is not modeled: if + // the first does not execute, the monitor stays set for the second one m = 1; __asm__ volatile( "ldrex %0, [%1]\n cmp %3, #0\n ite eq\n strexeq %0, %2, [%1]\n" @@ -220,5 +220,27 @@ int main(void) __asm__ volatile("mcr p15, 0, %0, c7, c14, 1" : : "r"(&x) : "memory"); __CPROVER_assert(x == 1, "clean and invalidate data cache line"); + // A conditional load-exclusive is not modeled: if it does not execute, the + // monitor stays clear, so that the store-exclusive fails. + m = 1; + __asm__ volatile( + "clrex\n cmp %3, #0\n it eq\n ldrexeq %0, [%2]\n strex %1, %4, [%2]" + : "+&r"(r), "=&r"(res) + : "r"(&m), "r"(1), "r"(2) + : "memory", "cc"); + __CPROVER_assert(m == 1 && res == 1, "conditional load-exclusive"); + // compare and swap with a conditional store-exclusive, which is the only + // store-exclusive of the statement + m = 1; + __asm__ volatile( + "ldrex %1, [%2]\n mov %0, #0\n teq %1, %3\n it eq\n" + " strexeq %0, %4, [%2]" + : "=&r"(res), "=&r"(r) + : "r"(&m), "r"(1), "r"(42) + : "memory", "cc"); + __CPROVER_assert(r == 1, "compare and swap reads"); + __CPROVER_assert((res == 0) == (m == 42), "compare and swap status"); + __CPROVER_assert(m == 42, "compare and swap stores"); // fails + return 0; } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index f81c16c29ac2..26861023d6d5 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -13,7 +13,7 @@ main.c ^\[main\.assertion\.8\] line 60 status matches the store: SUCCESS$ ^\[main\.assertion\.9\] line 68 store-exclusive after clrex: SUCCESS$ ^\[main\.assertion\.10\] line 79 conditional store-exclusive: FAILURE$ -^\[main\.assertion\.11\] line 80 status matches the conditional store: SUCCESS$ +^\[main\.assertion\.11\] line 80 status matches the conditional store: FAILURE$ ^\[main\.assertion\.12\] line 89 shifts: SUCCESS$ ^\[main\.assertion\.13\] line 98 subs/sbc: SUCCESS$ ^\[main\.assertion\.14\] line 107 rev16 rbit clz: SUCCESS$ @@ -33,16 +33,22 @@ main.c ^\[main\.assertion\.28\] line 211 carry after movs: FAILURE$ ^\[main\.assertion\.29\] line 218 invalidate data cache line: FAILURE$ ^\[main\.assertion\.30\] line 221 clean and invalidate data cache line: SUCCESS$ +^\[main\.assertion\.31\] line 231 conditional load-exclusive: FAILURE$ +^\[main\.assertion\.32\] line 241 compare and swap reads: SUCCESS$ +^\[main\.assertion\.33\] line 242 compare and swap status: SUCCESS$ +^\[main\.assertion\.34\] line 243 compare and swap stores: FAILURE$ +approximating inline assembly statement at .* line 73 function main: conditional load-exclusive, or conditional store-exclusive and another store-exclusive approximating inline assembly statement at .* line 123 function main: unsupported operands of mov approximating inline assembly statement at .* line 147 function main: memory access at an address computed from a value that is not modeled approximating inline assembly statement at .* line 153 function main: writes register r0, which is neither an operand nor clobbered approximating inline assembly statement at .* line 161 function main: msr of the processor mode, which banks r8 to r14, and operands used after it approximating inline assembly statement at .* line 217 function main: cache invalidation without cleaning +approximating inline assembly statement at .* line 226 function main: conditional load-exclusive, or conditional store-exclusive and another store-exclusive ^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly statement at .* function add_ll_sc -approximating inline assembly statement at .* line (167|176|181|190|197|207|220) +approximating inline assembly statement at .* line (167|176|181|190|197|207|220|235) -- The properties marked "fails" in main.c may be violated on hardware; all others hold on hardware. The results were validated with qemu-arm, for A32 @@ -53,4 +59,6 @@ targets, where the add sets the flags. So are "flags after add with movw" and "flags after add with ldrex", as validated with code compiled by GCC for -march=armv8-m.base, while "flags after add with clz" and "flags after add with rsbs" are violated in T32 code. "carry after movs" is violated in code -compiled by GCC for -march=armv5t or -march=armv8-m.base. +compiled by GCC for -march=armv5t or -march=armv8-m.base. "status matches the +conditional store" and "conditional load-exclusive" hold on hardware, but the +statements are approximated. diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index f35d1d371fea..e080fcddeef2 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -308,6 +308,11 @@ void msr_fields( /// only use them before the first such `msr`, including as its source, and /// only if no label precedes that `msr`, to which a later branch could /// return. +/// - The exclusive access region and the exclusive monitor are tracked while +/// lowering (see \ref asm_lowering_contextt::begin_exclusive), which is +/// exact for a conditional store-exclusive only if it is the only +/// store-exclusive of the statement, and never for a conditional +/// load-exclusive. std::unique_ptr make_a32_state(const std::vector &instructions) { @@ -322,6 +327,8 @@ make_a32_state(const std::vector &instructions) // whether a label precedes the first change bool operand_before_change = false, operand_after_change = false; bool label_before_change = false; + bool conditional_load_exclusive = false, conditional_store_exclusive = false; + std::size_t store_exclusives = 0; for(const auto &instruction : instructions) { if(!instruction.labels.empty() && !changes_mode) @@ -399,6 +406,15 @@ make_a32_state(const std::vector &instructions) { state->maybe_thumb1_divided = false; } + + if(decoded.base.compare(0, 5, "ldrex") == 0 && decoded.condition != "al") + conditional_load_exclusive = true; + if(decoded.base.compare(0, 5, "strex") == 0) + { + ++store_exclusives; + if(decoded.condition != "al") + conditional_store_exclusive = true; + } } if(unified_at_start && !divided) @@ -423,6 +439,19 @@ make_a32_state(const std::vector &instructions) "msr of the processor mode, which banks r8 to r14, and operands used " "after it, which may be allocated to these registers"; } + else if( + conditional_load_exclusive || + (conditional_store_exclusive && store_exclusives > 1)) + { + // The exclusive access region and the exclusive monitor are tracked + // while lowering, not on the paths that execute the instructions: a + // conditional load-exclusive opens the region on both paths, and a + // conditional store-exclusive ends it on both paths, without clearing + // the monitor, which another store-exclusive of the statement observes. + state->failure = + "conditional load-exclusive, or conditional store-exclusive and " + "another store-exclusive"; + } return state; } From 9abd360db8e973d7f7b78f508d4fb692ef14eb83 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:51:42 +0000 Subject: [PATCH 080/100] Inline assembly: AArch32 carry out of shifts The shifts with an s suffix (lsls, lsrs, asrs, rors) left the carry flag nondeterministic, so that CBMC could not prove, for example, that C is bit 31 of x after "lsls r, x, #1". The differential test against qemu-arm reported every vector of the shift forms as imprecise. C is now the last bit shifted out, for a shift by an immediate or by the bottom byte of a register: bit 32 - n for lsl and bit n - 1 for lsr (0 for n > 32), bit min(n, 32) - 1 for asr, and for ror bit (n - 1) mod 32. A shift by 0 keeps C; GNU as assembles shifts by #0 as movs. With this, the review's differential test (A32 and T32, 280 vectors for each register form and 28 for each immediate form) reports all shift forms exact and sound. C remains nondeterministic after logical operations with an immediate operand, where it depends on the encoding that the assembler chooses. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 5 +- regression/cbmc/asm_arm_instructions/main.c | 30 +++++++++ .../cbmc/asm_arm_instructions/test.desc | 9 +++ src/assembler/asm_arm.cpp | 64 ++++++++++++++++--- 4 files changed, 99 insertions(+), 9 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 332a1421ba74..a182bbe1db55 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -208,7 +208,10 @@ syntax: `neg`, `and`, `orr`, `eor`, `bic`, `lsl`, `lsr`, `asr`, `ror`, `mul`, `cmp`, `cmn`, `tst`, `teq`, `clz`, `rev`, `rev16`, `rbit`, `uxtb`, `uxth`, `sxtb`, `sxth`, with register or immediate operands (not shifted - registers); + registers); the shifts with an `s` suffix set C to the last bit shifted + out, while C is nondeterministic after `muls`, and after `movs`, `mvns`, + and the logical operations with an immediate operand (for which C depends + on the encoding of the immediate); - loads and stores of single registers (`ldr`, `ldrb`, `ldrh`, `ldrsb`, `ldrsh`, `str`, `strb`, `strh`) with an immediate or register offset (not with writeback), and load-exclusive/store-exclusive (`ldrex`, `strex`, diff --git a/regression/cbmc/asm_arm_instructions/main.c b/regression/cbmc/asm_arm_instructions/main.c index f33f7f742be0..f93c05a491b2 100644 --- a/regression/cbmc/asm_arm_instructions/main.c +++ b/regression/cbmc/asm_arm_instructions/main.c @@ -17,8 +17,38 @@ __attribute__((target("thumb"), noinline)) static void width_qualifiers(void) __CPROVER_assert(r == x + 1, "add.w"); } +// The shifts with an s suffix set C to the last bit shifted out, which is 0 +// for lsl and lsr by more than 32; a shift by 0 keeps C. +static void shift_carry(void) +{ + unsigned x = nondet_unsigned(), r; + _Bool c; + __asm__("lsls %0, %2, #1" : "=r"(r), "=@cccs"(c) : "r"(x)); + __CPROVER_assert(c == x >> 31, "lsls #1"); + __asm__("lsrs %0, %2, #32" : "=r"(r), "=@cccs"(c) : "r"(x)); + __CPROVER_assert(c == x >> 31, "lsrs #32"); + __asm__("asrs %0, %2, #3" : "=r"(r), "=@cccs"(c) : "r"(x)); + __CPROVER_assert(c == ((x >> 2) & 1), "asrs #3"); + __asm__("rors %0, %2, #1" : "=r"(r), "=@cccs"(c) : "r"(x)); + __CPROVER_assert(c == (x & 1), "rors #1"); + // shifts by a register use its bottom byte + __asm__("lsls %0, %2, %3" : "=r"(r), "=@cccs"(c) : "r"(x), "r"(0x120)); + __CPROVER_assert(c == (x & 1), "lsls by 32"); + __asm__("lsrs %0, %2, %3" : "=r"(r), "=@cccs"(c) : "r"(x), "r"(33)); + __CPROVER_assert(!c && r == 0, "lsrs by 33"); + __asm__("asrs %0, %2, %3" : "=r"(r), "=@cccs"(c) : "r"(x), "r"(200)); + __CPROVER_assert(c == x >> 31, "asrs by 200"); + __asm__("rors %0, %2, %3" : "=r"(r), "=@cccs"(c) : "r"(x), "r"(64)); + __CPROVER_assert(c == x >> 31 && r == x, "rors by 64"); + __asm__("cmp %2, %2\n lsrs %0, %2, %3" + : "=r"(r), "=@cccs"(c) + : "r"(x), "r"(0x100)); + __CPROVER_assert(c && r == x, "lsrs by 0"); +} + int main(void) { width_qualifiers(); + shift_carry(); return 0; } diff --git a/regression/cbmc/asm_arm_instructions/test.desc b/regression/cbmc/asm_arm_instructions/test.desc index b096cf16ab48..e154b541edc3 100644 --- a/regression/cbmc/asm_arm_instructions/test.desc +++ b/regression/cbmc/asm_arm_instructions/test.desc @@ -4,6 +4,15 @@ main.c ^EXIT=0$ ^SIGNAL=0$ ^\[width_qualifiers\.assertion\.1\] line 17 add\.w: SUCCESS$ +^\[shift_carry\.assertion\.1\] line 27 lsls #1: SUCCESS$ +^\[shift_carry\.assertion\.2\] line 29 lsrs #32: SUCCESS$ +^\[shift_carry\.assertion\.3\] line 31 asrs #3: SUCCESS$ +^\[shift_carry\.assertion\.4\] line 33 rors #1: SUCCESS$ +^\[shift_carry\.assertion\.5\] line 36 lsls by 32: SUCCESS$ +^\[shift_carry\.assertion\.6\] line 38 lsrs by 33: SUCCESS$ +^\[shift_carry\.assertion\.7\] line 40 asrs by 200: SUCCESS$ +^\[shift_carry\.assertion\.8\] line 42 rors by 64: SUCCESS$ +^\[shift_carry\.assertion\.9\] line 46 lsrs by 0: SUCCESS$ ^VERIFICATION SUCCESSFUL$ -- ^warning: ignoring diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index e080fcddeef2..aa6758511664 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -194,6 +194,52 @@ bool is_it_mnemonic(const std::string &mnemonic) [](char c) { return c == 't' || c == 'e'; }); } +/// \return Bit \p index of \p x, where \p index is a value less than the +/// width of \p x +exprt bit_at(const exprt &x, const exprt &index) +{ + return extractbit_exprt{lshr_exprt{x, index}, 0}; +} + +/// The carry out of the shifter for a shift with an `s` suffix +/// \param op: `lsl`, `lsr`, `asr`, or `ror` +/// \param x: the value shifted (32 bits) +/// \param amount: the shift amount (32 bits), of which the bottom byte counts +/// (an immediate amount is 0 to 32) +/// \param carry: the carry flag before the shift, which a shift by 0 keeps +/// \return The carry flag after the shift: the last bit shifted out, which +/// is 0 for `lsl` and `lsr` by more than 32 +exprt shift_carry( + const std::string &op, + const exprt &x, + const exprt &amount, + const exprt &carry) +{ + const exprt n = bitand_exprt{amount, constant(255, 32)}; + const exprt at_most_32 = binary_relation_exprt{n, ID_le, constant(32, 32)}; + exprt out; + if(op == "lsl") + out = and_exprt{at_most_32, bit_at(x, minus_exprt{constant(32, 32), n})}; + else if(op == "lsr") + out = and_exprt{at_most_32, bit_at(x, minus_exprt{n, constant(1, 32)})}; + else if(op == "asr") + { + // the sign for shifts by 32 or more + out = bit_at( + x, + minus_exprt{if_exprt{at_most_32, n, constant(32, 32)}, constant(1, 32)}); + } + else + { + // bit 31 for nonzero multiples of 32 + const exprt k = bitand_exprt{n, constant(31, 32)}; + out = bit_at( + x, + minus_exprt{if_exprt{is_zero(k), constant(32, 32), k}, constant(1, 32)}); + } + return if_exprt{is_zero(n), carry, out}; +} + /// What the instruction semantics need to know about the statement as a /// whole class a32_statet : public asm_semantics_statet @@ -1142,18 +1188,20 @@ bool asm_arm_semanticst::lower_operation( // the flags of x + ~y + C asm_arm::set_add_flags(ctx, x, bitnot_exprt{y}, carry, result, 32); } + else if(b == "lsl" || b == "lsr" || b == "asr" || b == "ror") + { + // V is unchanged + asm_arm::set_nz(ctx, result, 32); + ctx.assign(ctx.flag("c"), shift_carry(b, x, y, ctx.flag("c"))); + } else { - // Logical operations and shifts: C is the carry out of the - // shifter, which is not modeled (unchanged for a register operand - // without shift); V is unchanged. + // Logical operations: C is the carry out of the shifter, which is + // unchanged for a register operand without shift and depends on the + // encoding of an immediate; V is unchanged. asm_arm::set_nz(ctx, result, 32); - if( - ops[2].kind == a32_operandt::kindt::IMMEDIATE || b == "lsl" || - b == "lsr" || b == "asr" || b == "ror") - { + if(ops[2].kind == a32_operandt::kindt::IMMEDIATE) nondet_carry(); - } } } return write(ctx, ops[0], 32, result); From 811cb9cd4f42842c344bd6709a7906cca6fd8104 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:52:23 +0000 Subject: [PATCH 081/100] Inline assembly: document that the AArch32 processor mode is not modeled msr of the control field may leave the processor in another mode, as in msr cpsr_c, #0x1f. The interpretation treats the mode bits as having no effect, so the C code after such a statement is modeled as running in the original mode, although it uses the banked sp and lr of the new mode (and r8 to r12 in FIQ mode), and so are the output operands that the compiler then reads from banked registers. Say so in the user and the architecture documentation. Whether a register source of msr changes the mode cannot be decided statically, so approximating the statement would not help: the approximation does not model the mode either. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 6 +++++- doc/cprover-manual/modeling-inline-asm.md | 7 ++++++- src/assembler/asm_arm.cpp | 3 ++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 0a17dd1a14d5..55f86a2b6134 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -180,7 +180,11 @@ to r14. A statement that does so is not interpreted if it names any of these registers, or if it uses an operand, which the compiler may allocate to one of them, after the first such `msr`. Operands may be used before it, and as its source, unless a label precedes it, to which a later branch could -return. +return. The mode itself is not modeled, so that a statement that leaves the +processor in another mode (`msr cpsr_c, #0x1f`, say) is interpreted as if +the mode were unchanged: the C code after it, which uses the banked `sp` and +`lr` of the new mode, and the output operands, which the compiler may read +from banked registers, are modeled as in the original mode. An `it` instruction has no effect: the instructions of the IT block carry their conditions as suffixes, which the assemblers check against it. A conditional store-exclusive may not execute, so it does not clear the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index a182bbe1db55..efb318a2ca4e 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -246,7 +246,12 @@ A statement that changes the interrupt masks or the processor mode with `msr` is not interpreted if it names any of the registers r8 to r14, which are banked by mode, or if it uses an operand, which the compiler may allocate to one of these registers, after the first such `msr` (the source of that `msr` -may be an operand). Reading or writing `pc` is not modeled. +may be an operand). The processor mode itself is not modeled: a statement +that leaves the processor in another mode, such as `msr cpsr_c, #0x1f`, is +interpreted as if the mode were unchanged, although the code after it uses +the banked registers of the new mode (`sp` and `lr`, and r8 to r12 in FIQ +mode), including the registers from which the compiler reads output +operands. Reading or writing `pc` is not modeled. ### Supported Instructions diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index aa6758511664..f2efffa4a6cd 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -1388,7 +1388,8 @@ bool asm_arm_semanticst::lower_system( } // The other fields (the Q and GE flags, the interrupt masks, and the // processor mode) have no effect on the modeled state; see make_a32_state - // for the registers that a change of mode affects. + // for the registers that a change of mode affects. A mode that persists + // after the statement, with its banked sp and lr, is not modeled. return true; } From 55cdac933a47fe0a3662c77f2327e9e7fad1845e Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:56:26 +0000 Subject: [PATCH 082/100] Inline assembly: test more AArch32 instructions and system operations The AArch32 tests did not exercise lower_system at all, nor cbz/cbnz, divided-syntax suffix order, several data-processing instructions, the byte and halfword exclusives, register offsets, pld, or asm goto. asm_arm_system covers each branch of lower_system: cpsid/cpsie (and cps with a mode, which is approximated), msr of cpsr_c and cpsr_fc with the flags they keep or set, the rejection of a mode change in a statement that names r8, mrs and msr of other special registers, mrc, the CP15 barriers (fences.desc checks the fences), cache cleaning and invalidation of instruction caches (no effect), invalidation without cleaning by set/way and of both caches, other c7 operations, TLB maintenance, the thread ID registers, and CP15 registers, opc1 values, and coprocessors (p14) that are not modeled. asm_arm_instructions gains cbz and cbnz (T32), addeqs (A32, divided syntax), mvn, neg, sxth, uxtb, cmn, tst, ldrsh, strh, ldrb and strb with register offsets, pld, ldrexb/strexb, ldrexh/strexh, and asm goto. Both tests were validated with qemu-arm for A32 and T32 code compiled by GCC; privileged instructions were skipped by a SIGILL handler there. Co-authored-by: Kiro --- regression/cbmc/asm_arm_instructions/main.c | 100 ++++++++++++++++++ .../cbmc/asm_arm_instructions/test.desc | 22 +++- regression/cbmc/asm_arm_system/fences.desc | 12 +++ regression/cbmc/asm_arm_system/main.c | 96 +++++++++++++++++ regression/cbmc/asm_arm_system/test.desc | 35 ++++++ regression/validate-trace-xml-schema/check.py | 1 + 6 files changed, 263 insertions(+), 3 deletions(-) create mode 100644 regression/cbmc/asm_arm_system/fences.desc create mode 100644 regression/cbmc/asm_arm_system/main.c create mode 100644 regression/cbmc/asm_arm_system/test.desc diff --git a/regression/cbmc/asm_arm_instructions/main.c b/regression/cbmc/asm_arm_instructions/main.c index f93c05a491b2..84acfb9e47b4 100644 --- a/regression/cbmc/asm_arm_instructions/main.c +++ b/regression/cbmc/asm_arm_instructions/main.c @@ -46,9 +46,109 @@ static void shift_carry(void) __CPROVER_assert(c && r == x, "lsrs by 0"); } +// cbz and cbnz (T32 only) branch if a register is zero, or is not zero +__attribute__((target("thumb"), noinline)) static void compare_and_branch(void) +{ + unsigned x = nondet_unsigned(), r, s; + __asm__( + "mov %0, #1\n cbz %2, 1f\n mov %0, #2\n1: mov %1, #1\n" + " cbnz %2, 2f\n mov %1, #2\n2:" + : "=&l"(r), "=&l"(s) + : "l"(x)); + __CPROVER_assert(r == (x == 0 ? 1 : 2), "cbz"); + __CPROVER_assert(s == (x == 0 ? 2 : 1), "cbnz"); +} + +// in divided syntax (A32 only), the s suffix may follow the condition +__attribute__((target("arm"), noinline)) static void divided_suffixes(void) +{ + unsigned x = nondet_unsigned(), r = 0; + _Bool z; + __asm__("cmp %2, #0\n addeqs %0, %0, #1" : "+r"(r), "=@cceq"(z) : "r"(x)); + __CPROVER_assert(r == (x == 0) && !z, "addeqs"); +} + +static void data_processing(void) +{ + unsigned x = nondet_unsigned(), y = nondet_unsigned(), mv, ng, sh, ub; + __asm__("mvn %0, %4\n neg %1, %4\n sxth %2, %4\n uxtb %3, %4" + : "=&r"(mv), "=&r"(ng), "=&r"(sh), "=&r"(ub) + : "r"(x)); + __CPROVER_assert(mv == ~x && ng == -x, "mvn neg"); + __CPROVER_assert( + sh == (unsigned)(int)(short)x && ub == (x & 0xff), "sxth uxtb"); + _Bool z, c, n; + __asm__("cmn %3, %4" + : "=@cceq"(z), "=@cccs"(c), "=@ccmi"(n) + : "r"(x), "r"(y)); + __CPROVER_assert( + z == (x + y == 0) && c == (x + y < x) && n == (x + y) >> 31, "cmn"); + __asm__("tst %2, %3" : "=@cceq"(z), "=@ccmi"(n) : "r"(x), "r"(y)); + __CPROVER_assert(z == ((x & y) == 0) && n == (x & y) >> 31, "tst"); +} + +// loads and stores with immediate and register offsets, and preload hints +static void loads_and_stores(void) +{ + short h[3] = {-2, 0x1234, 0}; + unsigned char b[4] = {1, 2, 3, 4}; + unsigned v, w; + __asm__ volatile( + "ldrsh %0, [%2]\n strh %0, [%2, #4]\n ldrb %1, [%3, %4]\n" + " strb %1, [%3, %5]" + : "=&r"(v), "=&r"(w) + : "r"(h), "r"(b), "r"(2), "r"(0) + : "memory"); + __CPROVER_assert(v == 0xfffffffeu && h[2] == -2, "ldrsh strh"); + __CPROVER_assert(w == 3 && b[0] == 3 && b[1] == 2, "register offsets"); + // preload hints do not access memory + __asm__ volatile("pld [%0]\n pld [%0, #64]" : : "r"(b)); + __CPROVER_assert(b[0] == 3, "pld"); +} + +// exclusive loads and stores of bytes and halfwords +static void exclusive_bytes_and_halfwords(void) +{ + unsigned char b = 0xff; + unsigned short h = 0xffff; + unsigned v, s, w, t; + __asm__ volatile( + "ldrexb %0, [%4]\n add %0, %0, #1\n strexb %1, %0, [%4]\n" + " ldrexh %2, [%5]\n add %2, %2, #2\n strexh %3, %2, [%5]" + : "=&r"(v), "=&r"(s), "=&r"(w), "=&r"(t) + : "r"(&b), "r"(&h) + : "memory"); + __CPROVER_assert(v == 0x100 && w == 0x10001, "ldrexb ldrexh"); + __CPROVER_assert((s == 0) == (b == 0), "strexb"); + __CPROVER_assert((t == 0) == (h == 1), "strexh"); + // the store-exclusive may fail spuriously + __CPROVER_assert(b == 0, "strexb stores"); // fails +} + +// asm goto jumps to a label of its label list +static int is_nonzero(unsigned x) +{ + __asm__ goto("cmp %0, #0\n beq %l[zero]" : : "r"(x) : "cc" : zero); + return 1; +zero: + return 0; +} + +static void asm_goto(void) +{ + unsigned x = nondet_unsigned(); + __CPROVER_assert(is_nonzero(x) == (x != 0), "asm goto"); +} + int main(void) { width_qualifiers(); shift_carry(); + compare_and_branch(); + divided_suffixes(); + data_processing(); + loads_and_stores(); + exclusive_bytes_and_halfwords(); + asm_goto(); return 0; } diff --git a/regression/cbmc/asm_arm_instructions/test.desc b/regression/cbmc/asm_arm_instructions/test.desc index e154b541edc3..8162ffdfe756 100644 --- a/regression/cbmc/asm_arm_instructions/test.desc +++ b/regression/cbmc/asm_arm_instructions/test.desc @@ -1,7 +1,7 @@ CORE gcc-only no-new-smt main.c --arch arm -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^\[width_qualifiers\.assertion\.1\] line 17 add\.w: SUCCESS$ ^\[shift_carry\.assertion\.1\] line 27 lsls #1: SUCCESS$ @@ -13,7 +13,22 @@ main.c ^\[shift_carry\.assertion\.7\] line 40 asrs by 200: SUCCESS$ ^\[shift_carry\.assertion\.8\] line 42 rors by 64: SUCCESS$ ^\[shift_carry\.assertion\.9\] line 46 lsrs by 0: SUCCESS$ -^VERIFICATION SUCCESSFUL$ +^\[compare_and_branch\.assertion\.1\] line 58 cbz: SUCCESS$ +^\[compare_and_branch\.assertion\.2\] line 59 cbnz: SUCCESS$ +^\[divided_suffixes\.assertion\.1\] line 68 addeqs: SUCCESS$ +^\[data_processing\.assertion\.1\] line 77 mvn neg: SUCCESS$ +^\[data_processing\.assertion\.2\] line 78 sxth uxtb: SUCCESS$ +^\[data_processing\.assertion\.3\] line 84 cmn: SUCCESS$ +^\[data_processing\.assertion\.4\] line 87 tst: SUCCESS$ +^\[loads_and_stores\.assertion\.1\] line 102 ldrsh strh: SUCCESS$ +^\[loads_and_stores\.assertion\.2\] line 103 register offsets: SUCCESS$ +^\[loads_and_stores\.assertion\.3\] line 106 pld: SUCCESS$ +^\[exclusive_bytes_and_halfwords\.assertion\.1\] line 121 ldrexb ldrexh: SUCCESS$ +^\[exclusive_bytes_and_halfwords\.assertion\.2\] line 122 strexb: SUCCESS$ +^\[exclusive_bytes_and_halfwords\.assertion\.3\] line 123 strexh: SUCCESS$ +^\[exclusive_bytes_and_halfwords\.assertion\.4\] line 125 strexb stores: FAILURE$ +^\[asm_goto\.assertion\.1\] line 140 asm goto: SUCCESS$ +^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly statement @@ -21,4 +36,5 @@ approximating inline assembly statement The properties marked "fails" in main.c may be violated on hardware; all others hold on hardware. The results were validated with qemu-arm, for code compiled by GCC for A32 and T32 (-marm and -mthumb, with the functions that -have a target attribute in that instruction set only). +have a target attribute in that instruction set only), with nondet_unsigned +returning each of eight values (0, 1, 41, 0x7fffffff, 0x80000001, ...) first. diff --git a/regression/cbmc/asm_arm_system/fences.desc b/regression/cbmc/asm_arm_system/fences.desc new file mode 100644 index 000000000000..3bce46579efd --- /dev/null +++ b/regression/cbmc/asm_arm_system/fences.desc @@ -0,0 +1,12 @@ +CORE gcc-only +main.c +--arch arm --show-goto-functions +^EXIT=0$ +^SIGNAL=0$ +^ *FENCE WW RR RW WR$ +^ *FENCE$ +-- +^warning: ignoring +-- +The CP15 forms of dmb and dsb are full fences, and that of isb is an empty +fence. diff --git a/regression/cbmc/asm_arm_system/main.c b/regression/cbmc/asm_arm_system/main.c new file mode 100644 index 000000000000..84374a3cec69 --- /dev/null +++ b/regression/cbmc/asm_arm_system/main.c @@ -0,0 +1,96 @@ +// System instructions of the AArch32 semantics: the special registers, the +// interrupt masks, and the coprocessor operations. "fails" marks properties +// that the architecture permits to be violated, so CBMC must not prove them. + +unsigned x; + +int main(void) +{ + unsigned r = 0, t; + _Bool z; + + // the interrupt masks have no effect on the modeled state + __asm__ volatile("cmp %1, %1\n cpsid i\n cpsie if" + : "=@cceq"(z) + : "r"(x) + : "memory"); + __CPROVER_assert(z, "cpsid and cpsie"); + // with a mode operand, cps changes the processor mode + __asm__ volatile("cpsid i, #0x13"); + + // msr of the control field keeps the flags, msr of cpsr_fc sets them + __asm__ volatile("cmp %2, %2\n mrs %1, cpsr\n msr cpsr_c, %1" + : "=@cceq"(z), "=&r"(t) + : "r"(x) + : "memory"); + __CPROVER_assert(z, "msr cpsr_c"); + __asm__ volatile("cmp %1, %1\n msr cpsr_c, %2" + : "=@cceq"(z) + : "r"(x), "r"(0x10)); + __CPROVER_assert(z, "msr cpsr_c of user mode"); + __asm__ volatile( + "mrs %0, cpsr\n bic %0, %0, #0xf0000000\n" + " orr %0, %0, #0x40000000\n msr cpsr_fc, %0" + : "=&r"(t), "=@cceq"(z)); + __CPROVER_assert(z, "msr cpsr_fc"); + // a statement that changes the mode must not name r8 to r14, which are + // banked + __asm__ volatile("mrs %0, cpsr\n msr cpsr_c, %0\n mov r8, #1" + : "=&r"(t) + : + : "r8"); + // other special registers are not modeled + __asm__ volatile("mrs %0, spsr" : "=r"(r)); + __CPROVER_assert(r == 0, "mrs spsr"); // fails + __asm__ volatile("msr spsr_c, %0" : : "r"(0)); + + // the value of a coprocessor register is not modeled + __asm__ volatile("mrc p15, 0, %0, c13, c0, 3" : "=r"(r)); + __CPROVER_assert(r == 0, "mrc"); // fails + + // CP15 barriers (DMB, DSB, ISB) + x = 1; + __asm__ volatile( + "mcr p15, 0, %0, c7, c10, 5\n mcr p15, 0, %0, c7, c10, 4\n" + " mcr p15, 0, %0, c7, c5, 4" + : + : "r"(0) + : "memory"); + __CPROVER_assert(x == 1, "CP15 barriers"); + // Cleaning data caches, cleaning and invalidating them, and invalidating + // instruction caches and branch predictors do not change memory. + __asm__ volatile( + "mcr p15, 0, %0, c7, c10, 1\n mcr p15, 0, %0, c7, c14, 1\n" + " mcr p15, 0, %0, c7, c11, 1\n mcr p15, 0, %0, c7, c5, 0\n" + " mcr p15, 0, %0, c7, c5, 6" + : + : "r"(&x) + : "memory"); + __CPROVER_assert(x == 1, "cache clean"); + // Invalidating data or unified caches without cleaning them may discard + // dirty lines, so that memory reverts to older values. + __asm__ volatile("mcr p15, 0, %0, c7, c6, 2" : : "r"(0) : "memory"); + __CPROVER_assert(x == 1, "invalidate by set/way"); // fails + x = 1; + __asm__ volatile("mcr p15, 0, %0, c7, c7, 0" : : "r"(0) : "memory"); + __CPROVER_assert(x == 1, "invalidate both caches"); // fails + x = 1; + // other c7 operations, such as address translation, are not modeled + __asm__ volatile("mcr p15, 0, %0, c7, c8, 0" : : "r"(0)); + // TLB maintenance does not change memory + __asm__ volatile("mcr p15, 0, %0, c8, c7, 0" : : "r"(0) : "memory"); + __CPROVER_assert(x == 1, "TLB maintenance"); + // nor do the thread ID registers + __asm__ volatile("mrc p15, 0, %0, c13, c0, 2\n mcr p15, 0, %0, c13, c0, 2" + : "=&r"(t) + : + : "memory"); + __CPROVER_assert(x == 1, "thread ID"); + // other CP15 registers, other values of opc1, and other coprocessors are + // not modeled + __asm__ volatile("mcr p15, 0, %0, c1, c0, 0" : : "r"(0)); + __asm__ volatile("mcr p15, 2, %0, c0, c0, 0" : : "r"(0)); + __asm__ volatile("mcr p14, 0, %0, c0, c5, 0" : : "r"(0)); + + return 0; +} diff --git a/regression/cbmc/asm_arm_system/test.desc b/regression/cbmc/asm_arm_system/test.desc new file mode 100644 index 000000000000..5e685030d23b --- /dev/null +++ b/regression/cbmc/asm_arm_system/test.desc @@ -0,0 +1,35 @@ +CORE gcc-only no-new-smt +main.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 17 cpsid and cpsie: SUCCESS$ +^\[main\.assertion\.2\] line 26 msr cpsr_c: SUCCESS$ +^\[main\.assertion\.3\] line 30 msr cpsr_c of user mode: SUCCESS$ +^\[main\.assertion\.4\] line 35 msr cpsr_fc: SUCCESS$ +^\[main\.assertion\.5\] line 44 mrs spsr: FAILURE$ +^\[main\.assertion\.6\] line 49 mrc: FAILURE$ +^\[main\.assertion\.7\] line 59 CP15 barriers: SUCCESS$ +^\[main\.assertion\.8\] line 69 cache clean: SUCCESS$ +^\[main\.assertion\.9\] line 73 invalidate by set/way: FAILURE$ +^\[main\.assertion\.10\] line 76 invalidate both caches: FAILURE$ +^\[main\.assertion\.11\] line 82 TLB maintenance: SUCCESS$ +^\[main\.assertion\.12\] line 88 thread ID: SUCCESS$ +approximating inline assembly statement at .* line 19 function main: unsupported operands of cpsid +approximating inline assembly statement at .* line 38 function main: msr of the processor mode with named registers r8 to r14 +approximating inline assembly statement at .* line 45 function main: unsupported special register spsr_c +approximating inline assembly statement at .* line 72 function main: cache invalidation without cleaning +approximating inline assembly statement at .* line 75 function main: cache invalidation without cleaning +approximating inline assembly statement at .* line 79 function main: unsupported coprocessor operation +approximating inline assembly statement at .* line 91 function main: unsupported coprocessor operation +approximating inline assembly statement at .* line 92 function main: unsupported coprocessor operation +approximating inline assembly statement at .* line 93 function main: unsupported coprocessor operation +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* line (13|22|27|31|43|48|53|62|81|84) +-- +The properties marked "fails" in main.c may be violated on hardware; all +others hold on hardware. The results were validated with qemu-arm in user +mode, for A32 and T32 code compiled by GCC, where the privileged instructions +(including the CP15 cache and TLB maintenance) were skipped. diff --git a/regression/validate-trace-xml-schema/check.py b/regression/validate-trace-xml-schema/check.py index 3f50f623cb45..5e55936819ae 100644 --- a/regression/validate-trace-xml-schema/check.py +++ b/regression/validate-trace-xml-schema/check.py @@ -25,6 +25,7 @@ ['xml-interface1', 'test.desc'], ['xml-interface1', 'test_wrong_flag.desc'], # these want --show-goto-functions instead of producing a trace + ['asm_arm_system', 'fences.desc'], ['declaration-goto', 'no-duplicate-decl.desc'], ['destructors', 'compound_literal.desc'], ['destructors', 'enter_lexical_block.desc'], From 798bcb9472ab91fa957b9a6dc40fe4998f8b341f Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 21:43:36 +0000 Subject: [PATCH 083/100] AArch32 inline assembly: abandon exclusive regions instead of failing A memory access between a load-exclusive and a store-exclusive made the whole AArch32 statement uninterpreted, and hence approximated, while the AArch64 semantics abandon the exclusive access region at that point, as the shared lowering does at branches and labels. Do the same for AArch32: the load-exclusive is then a plain load, and a later store-exclusive succeeds or fails nondeterministically, but is not atomic with the load. The manual already describes AArch32 exclusive accesses as following the AArch64 model. The new test, with Linux's arch_atomic_fetch_add_unless (a branch past the store-exclusive) and a plain store between the two exclusive accesses, passes on qemu-arm when built by arm-linux-gnueabihf-gcc for A32 and T32 code. Co-authored-by: Kiro --- .../cbmc/asm_arm_exclusive_abandoned/main.c | 60 +++++++++++++++++++ .../asm_arm_exclusive_abandoned/test.desc | 22 +++++++ src/assembler/asm_arm.cpp | 10 +--- 3 files changed, 84 insertions(+), 8 deletions(-) create mode 100644 regression/cbmc/asm_arm_exclusive_abandoned/main.c create mode 100644 regression/cbmc/asm_arm_exclusive_abandoned/test.desc diff --git a/regression/cbmc/asm_arm_exclusive_abandoned/main.c b/regression/cbmc/asm_arm_exclusive_abandoned/main.c new file mode 100644 index 000000000000..b0219b8a29c9 --- /dev/null +++ b/regression/cbmc/asm_arm_exclusive_abandoned/main.c @@ -0,0 +1,60 @@ +// A branch, a label, or another memory access after a load-exclusive ends the +// exclusive access region: the load-exclusive is then a plain load, and a +// store-exclusive after it succeeds or fails nondeterministically without +// being atomic with the load. "fails" marks properties that the architecture +// permits to be violated, so CBMC must not prove them. + +#ifndef __CPROVER__ +# include +# define __CPROVER_assert(c, m) assert(c) +#endif + +// Linux arm arch_atomic_fetch_add_unless: the branch to 2f leaves the +// exclusive access region +static int fetch_add_unless(int *counter, int a, int u) +{ + int oldval, newval; + unsigned int tmp; + __asm__ volatile( + "1: ldrex %0, [%4]\n" + " teq %0, %5\n" + " beq 2f\n" + " add %1, %0, %6\n" + " strex %2, %1, [%4]\n" + " teq %2, #0\n" + " bne 1b\n" + "2:" + : "=&r"(oldval), "=&r"(newval), "=&r"(tmp), "+Qo"(*counter) + : "r"(counter), "r"(u), "r"(a) + : "cc"); + return oldval; +} + +int m = 5, n = 1; + +int main(void) +{ + __CPROVER_assert(fetch_add_unless(&m, 2, 0) == 5, "returns the old value"); + __CPROVER_assert(m == 7, "adds unless equal"); + __CPROVER_assert(fetch_add_unless(&m, 2, 7) == 7, "returns the value"); + __CPROVER_assert(m == 7, "does not add if equal"); + + // a store between the load-exclusive and the store-exclusive + int t; + unsigned int status; + __asm__ volatile( + "ldrex %0, [%2]\n" + " str %0, [%3]\n" + " strex %1, %4, [%2]" + : "=&r"(t), "=&r"(status) + : "r"(&m), "r"(&n), "r"(8) + : "memory"); + __CPROVER_assert(n == 7, "plain store"); + __CPROVER_assert((status == 0) == (m == 8), "status matches the store"); +#ifdef __CPROVER__ + __CPROVER_assert(status == 0, "store-exclusive succeeds"); // fails + __CPROVER_assert(status == 1, "store-exclusive fails"); // fails +#endif + + return 0; +} diff --git a/regression/cbmc/asm_arm_exclusive_abandoned/test.desc b/regression/cbmc/asm_arm_exclusive_abandoned/test.desc new file mode 100644 index 000000000000..54aa844916e1 --- /dev/null +++ b/regression/cbmc/asm_arm_exclusive_abandoned/test.desc @@ -0,0 +1,22 @@ +CORE gcc-only no-new-smt +main.c +--arch arm --unwind 2 --no-unwinding-assertions +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 37 returns the old value: SUCCESS$ +^\[main\.assertion\.2\] line 38 adds unless equal: SUCCESS$ +^\[main\.assertion\.3\] line 39 returns the value: SUCCESS$ +^\[main\.assertion\.4\] line 40 does not add if equal: SUCCESS$ +^\[main\.assertion\.5\] line 52 plain store: SUCCESS$ +^\[main\.assertion\.6\] line 53 status matches the store: SUCCESS$ +^\[main\.assertion\.7\] line 55 store-exclusive succeeds: FAILURE$ +^\[main\.assertion\.8\] line 56 store-exclusive fails: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +The statements are interpreted. The program, built without __CPROVER__ by +arm-linux-gnueabihf-gcc -O2 (-marm and -mthumb), passes on qemu-arm, where the +store-exclusive after the plain store succeeds; the architecture permits it to +fail. diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index f2efffa4a6cd..0c97ce11cc5b 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -799,11 +799,7 @@ exprt asm_arm_semanticst::read( return typecast_exprt::conditional_cast(operand.value, bv(width)); case a32_operandt::kindt::MEMORY: - if(ctx.exclusive_open()) - { - ctx.fail("memory access between load-exclusive and store-exclusive"); - return ctx.nondet(bv(width)); - } + ctx.abandon_exclusive(); if(operand.lvalue.is_not_nil() && operand.natural_width == width) return ctx.to_bits(operand.lvalue, width); return ctx.memory(operand.address, width); @@ -830,9 +826,7 @@ bool asm_arm_semanticst::write( return true; case a32_operandt::kindt::MEMORY: - if(ctx.exclusive_open()) - return ctx.fail( - "memory access between load-exclusive and store-exclusive"); + ctx.abandon_exclusive(); if(operand.lvalue.is_not_nil() && operand.natural_width == width) { ctx.assign( From ab56911d25411ada661ab7ca53e58c6fb107f8aa Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 11:08:27 +0000 Subject: [PATCH 084/100] Inline assembly: a differential test harness against hardware The asm_x86, asm_aarch64, and asm_arm regression tests pin results of inline assembly statements that were observed on hardware (x86-64) or with the Unicorn emulator (AArch64, AArch32), so that a wrong instruction semantics, or a statement that is approximated rather than interpreted, makes an assertion fail. The tests were generated by a script that was not part of the repository, so they could neither be reproduced nor extended. Add that script, scripts/asm_differential: it compiles each case (a C function with one inline assembly statement) natively or with a cross compiler, runs it on pseudo-random input vectors with fixed seeds, and writes a test whose assertions are the observed results. Over the version used to create the tests, it formats the output with the repository's clang-format style also when the output directory is elsewhere, uses clang for AArch64 when aarch64-linux-gnu-gcc is not available, and writes the headers of the committed tests, which now name the generator. Regenerating the three tests with ASM_DIFF_MAX_VECTORS=3 reproduces them byte for byte. Co-authored-by: Kiro --- regression/cbmc/asm_aarch64/main.c | 1 + regression/cbmc/asm_arm/main.c | 1 + regression/cbmc/asm_x86/main.i | 1 + scripts/asm_differential/README.md | 57 ++++ scripts/asm_differential/asm_differential.py | 281 ++++++++++++++++++ .../asm_differential_cases.py | 197 ++++++++++++ 6 files changed, 538 insertions(+) create mode 100644 scripts/asm_differential/README.md create mode 100644 scripts/asm_differential/asm_differential.py create mode 100644 scripts/asm_differential/asm_differential_cases.py diff --git a/regression/cbmc/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c index 432d19b3eea1..f618b33cc9c9 100644 --- a/regression/cbmc/asm_aarch64/main.c +++ b/regression/cbmc/asm_aarch64/main.c @@ -1,5 +1,6 @@ // AArch64 inline assembly that is interpreted exactly. The expected values were // observed with an emulator. +// Generated by scripts/asm_differential/asm_differential.py aarch64. // aarch64 ldxr/add/stxr set a bit (atomic_set llsc) void asm_case_0(unsigned long long *io) diff --git a/regression/cbmc/asm_arm/main.c b/regression/cbmc/asm_arm/main.c index 5ff309c8f15e..fdff0b81f763 100644 --- a/regression/cbmc/asm_arm/main.c +++ b/regression/cbmc/asm_arm/main.c @@ -1,5 +1,6 @@ // AArch32 inline assembly (A32 code) that is interpreted exactly. The expected // values were observed with an emulator. +// Generated by scripts/asm_differential/asm_differential.py arm. // arm ldrex/orr/strex set a bit (atomic set) void asm_case_0(unsigned long long *io) diff --git a/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i index adbb5e869138..48a214a9348e 100644 --- a/regression/cbmc/asm_x86/main.i +++ b/regression/cbmc/asm_x86/main.i @@ -1,5 +1,6 @@ // x86 inline assembly that is interpreted exactly. The expected values were // observed on x86-64 hardware. +// Generated by scripts/asm_differential/asm_differential.py x86_64. // x86 lock-or sets a bit (atomic_set_long) void asm_case_0(unsigned long long *io) diff --git a/scripts/asm_differential/README.md b/scripts/asm_differential/README.md new file mode 100644 index 000000000000..364bb0ca7726 --- /dev/null +++ b/scripts/asm_differential/README.md @@ -0,0 +1,57 @@ +# Differential testing of the inline-assembly semantics + +These scripts generate the `regression/cbmc/asm_{x86,aarch64,arm}` tests and +can be used to extend them. Each test case (in `asm_differential_cases.py`) is +a small C function with one inline assembly statement. The harness compiles +and runs it on several input vectors, on real hardware for x86-64 and with the +[Unicorn](https://www.unicorn-engine.org/) emulator for AArch64 and AArch32 +(A32 code), then writes a CBMC regression test whose assertions pin the +observed results. + +If CBMC's semantics for any instruction were wrong, or if a statement were +approximated (its outputs assigned nondeterministic values) rather than +interpreted, the generated assertions would no longer hold, so running the +test under CBMC checks the semantics against the real machine. + +## Requirements + +* an x86-64 host with `gcc` (x86-64 cases, run natively); +* `aarch64-linux-gnu-gcc`, or else `clang` (AArch64 cases); +* `clang` targeting `armv7a-none-eabi` (AArch32 cases); +* Python packages `unicorn` and `pyelftools` for the emulated architectures. + +## Use + +```sh +python3 -m venv .venv && .venv/bin/pip install unicorn pyelftools +export ASM_DIFF_MAX_VECTORS=3 +.venv/bin/python scripts/asm_differential/asm_differential.py x86_64 regression/cbmc/asm_x86 +.venv/bin/python scripts/asm_differential/asm_differential.py aarch64 regression/cbmc/asm_aarch64 +.venv/bin/python scripts/asm_differential/asm_differential.py arm regression/cbmc/asm_arm +``` + +The x86 test is written as `main.i` (preprocessed source), as CBMC's +preprocessing for x86 passes `-m64` to the host's compiler, which fails on +hosts of other architectures. + +`ASM_DIFF_MAX_VECTORS` caps the number of input vectors per case; the +committed tests use 3. The input vectors are pseudo-random with fixed seeds, +and the output is passed through `clang-format` with the repository's style +when it is available, so regenerating in a checkout reproduces the committed +files. + +## Adding a case + +Add a `Case` to the relevant list in `asm_differential_cases.py`: the +statement, the C variables it reads and writes (in the order the harness +stores them), and optionally fixed input vectors or a `constrain` callback for +inputs that must satisfy a precondition (for example a shift count below the +width). A case must be deterministic: it must not read uninitialised storage, +a timer, or I/O. Regenerate the test and check that CBMC verifies it (see the +`test.desc` next to it); a failing assertion is a bug in CBMC's semantics or a +statement that CBMC approximates. + +The generated tests only cover statements that CBMC interprets exactly. +Properties that the architecture permits to be violated (such as a +store-exclusive that may fail spuriously) belong in the hand-written +`asm_*_corner_cases` tests. diff --git a/scripts/asm_differential/asm_differential.py b/scripts/asm_differential/asm_differential.py new file mode 100644 index 000000000000..35b47e34db95 --- /dev/null +++ b/scripts/asm_differential/asm_differential.py @@ -0,0 +1,281 @@ +#!/usr/bin/env python3 +"""Differential tests of CBMC's inline-assembly semantics against hardware. + +Each test case is a small C function containing one inline assembly +statement. The function is compiled with the native or a cross compiler and +executed (natively on x86-64, with the Unicorn emulator for AArch64 and +AArch32) on several input vectors. The observed results become the expected +values of a CBMC regression test, which asserts that CBMC computes exactly +those results, i.e. that the statement is interpreted, not approximated. + +Usage: + asm_differential.py ARCH OUTPUT_DIR + +ARCH is x86_64, aarch64 or arm. Requirements: gcc (x86_64), +aarch64-linux-gnu-gcc (aarch64), clang (arm), and the Python package unicorn +(pip install unicorn) for the emulated architectures. +""" + +import os +import random +import shutil +import struct +import subprocess +import sys +import tempfile + +import asm_differential_cases as cases_module + +MASK64 = (1 << 64) - 1 + +# the first lines of the generated test, by architecture +HEADERS = { + 'x86_64': [ + '// x86 inline assembly that is interpreted exactly. The expected ' + 'values were', + '// observed on x86-64 hardware.'], + 'aarch64': [ + '// AArch64 inline assembly that is interpreted exactly. The expected ' + 'values were', + '// observed with an emulator.'], + 'arm': [ + '// AArch32 inline assembly (A32 code) that is interpreted exactly. ' + 'The expected', + '// values were observed with an emulator.'], +} + + +def have(tool): + """Whether tool is on the PATH.""" + return shutil.which(tool) is not None + + +def c_literal(value): + return '0x%xULL' % (value & MASK64) + + +def function_source(index, case): + """The C function of a test case: load variables from io, run the + statement, store them back.""" + lines = ['void asm_case_%d(unsigned long long *io)' % index, '{'] + k = 0 + for ctype, name, length in case.variables: + if length is None: + lines.append(' %s %s = (%s)io[%d];' % (ctype, name, ctype, k)) + k += 1 + else: + lines.append(' %s %s[%d];' % (ctype, name, length)) + for i in range(length): + lines.append(' %s[%d] = (%s)io[%d];' % (name, i, ctype, k)) + k += 1 + if case.prologue: + lines.append(' ' + case.prologue) + lines.append(' ' + case.statement) + k = 0 + for ctype, name, length in case.variables: + if length is None: + lines.append(' io[%d] = (unsigned long long)%s;' % (k, name)) + k += 1 + else: + for i in range(length): + lines.append( + ' io[%d] = (unsigned long long)%s[%d];' % (k, name, i)) + k += 1 + lines.append('}') + return '\n'.join(lines) + '\n' + + +def slots(case): + return sum(1 if length is None else length + for _, _, length in case.variables) + + +def input_vectors(case, count, seed): + cap = os.environ.get('ASM_DIFF_MAX_VECTORS') + if cap is not None: + count = min(count, int(cap)) + rng = random.Random(seed) + vectors = list(case.inputs) + edges = [0, 1, 2, 0x7f, 0x80, 0xff, 0x7fffffff, 0x80000000, 0xffffffff, + 0x7fffffffffffffff, 0x8000000000000000, MASK64] + while len(vectors) < count: + vector = [] + for _ in range(slots(case)): + vector.append(rng.choice(edges) if rng.random() < 0.3 + else rng.getrandbits(64)) + if case.constrain is not None: + vector = case.constrain(vector) + vectors.append(vector) + return vectors + + +def run_x86_64(sources, vectors, workdir): + driver = ['#include '] + driver += sources + driver.append('int main(void)\n{') + driver.append(' unsigned long long io[64];') + for index, case_vectors in enumerate(vectors): + for vector in case_vectors: + for k, value in enumerate(vector): + driver.append(' io[%d] = %s;' % (k, c_literal(value))) + driver.append(' asm_case_%d(io);' % index) + driver.append( + ' for(int i = 0; i < %d; ++i) printf("%%llx ", io[i]);' + % len(vector)) + driver.append(' printf("\\n");') + driver.append(' return 0;\n}') + path = os.path.join(workdir, 'native.c') + with open(path, 'w') as f: + f.write('\n'.join(driver)) + exe = os.path.join(workdir, 'native') + subprocess.check_call(['gcc', '-O1', '-o', exe, path]) + out = subprocess.check_output([exe], text=True).split('\n') + results = [] + line = 0 + for case_vectors in vectors: + case_results = [] + for _ in case_vectors: + case_results.append([int(x, 16) for x in out[line].split()]) + line += 1 + results.append(case_results) + return results + + +def run_emulated(arch, cases, sources, vectors, workdir): + import unicorn + from unicorn import arm64_const, arm_const + from elftools.elf.elffile import ELFFile + + path = os.path.join(workdir, 'cases.c') + with open(path, 'w') as f: + f.write('\n'.join(sources)) + obj = os.path.join(workdir, 'cases.o') + if arch == 'aarch64': + flags = ['-O1', '-ffreestanding', '-fno-pic', '-march=armv8.1-a', '-c', + '-o', obj, path] + if have('aarch64-linux-gnu-gcc'): + subprocess.check_call(['aarch64-linux-gnu-gcc'] + flags) + else: + subprocess.check_call( + ['clang', '--target=aarch64-linux-gnu'] + flags) + else: + subprocess.check_call( + ['clang', '--target=armv7a-none-eabi', '-marm', '-O1', + '-ffreestanding', '-mfloat-abi=soft', '-c', '-o', obj, path]) + + # Read the code and the function offsets straight from the ELF object, so + # that no architecture-specific objcopy/nm is needed. + with open(obj, 'rb') as f: + elf = ELFFile(f) + text_section = elf.get_section_by_name('.text') + # the code is used as it is, so it must not need relocation + for name in ('.rel.text', '.rela.text'): + relocations = elf.get_section_by_name(name) + if relocations is not None and relocations.num_relocations(): + sys.exit('the cases need relocations, which are not applied') + code = text_section.data() + text_addr = text_section['sh_addr'] + symbols = {} + symtab = elf.get_section_by_name('.symtab') + for symbol in symtab.iter_symbols(): + if symbol['st_info']['type'] == 'STT_FUNC': + symbols[symbol.name] = symbol['st_value'] - text_addr + + code_base, data_base, stack_base, stop = 0x100000, 0x200000, 0x300000, \ + 0x400000 + results = [] + for index, case_vectors in enumerate(vectors): + case_results = [] + for vector in case_vectors: + if arch == 'aarch64': + uc = unicorn.Uc(unicorn.UC_ARCH_ARM64, unicorn.UC_MODE_ARM) + uc.ctl_set_cpu_model(arm64_const.UC_CPU_ARM64_MAX) + else: + uc = unicorn.Uc(unicorn.UC_ARCH_ARM, unicorn.UC_MODE_ARM) + uc.mem_map(code_base, 0x100000) + uc.mem_map(data_base, 0x10000) + uc.mem_map(stack_base, 0x10000) + uc.mem_map(stop, 0x1000) + uc.mem_write(code_base, code) + uc.mem_write(data_base, b''.join( + struct.pack(' Date: Tue, 1 Dec 2026 16:35:08 +0000 Subject: [PATCH 085/100] asm_differential: observe the result of the struct field case The case "x86 memory operand with a struct field offset" runs orl %1,%0 with s.hi as its memory operand, but its function copies the unchanged locals lo and hi back to io, not the fields of s. The generated assertions therefore did not depend on what the statement does: with the statement replaced by "xorl %1,%0; notl %0", asm_x86 still verified. Give a case an optional epilogue that runs after the statement, and copy s.lo and s.hi to lo and hi in this case's epilogue, so that the result of the statement is observed. asm_x86 is regenerated (its expected values for hi change); with the replaced statement, the three assertions of the case now fail. Co-authored-by: Kiro --- regression/cbmc/asm_x86/main.i | 9 ++++++--- scripts/asm_differential/asm_differential.py | 2 ++ scripts/asm_differential/asm_differential_cases.py | 4 ++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i index 48a214a9348e..52e8d466c1ee 100644 --- a/regression/cbmc/asm_x86/main.i +++ b/regression/cbmc/asm_x86/main.i @@ -147,6 +147,8 @@ void asm_case_12(unsigned long long *io) unsigned int lo, hi; } s = {(unsigned)io[0], (unsigned)io[1]}; __asm__ __volatile__("orl %1,%0" : "+m"(s.hi) : "r"(v) : "cc"); + lo = s.lo; + hi = s.hi; io[0] = (unsigned long long)lo; io[1] = (unsigned long long)hi; io[2] = (unsigned long long)v; @@ -430,7 +432,8 @@ int main(void) 0x67474bfe2512affeULL, 0x0ULL, 0xd9b9851fa699e71cULL}; asm_case_12(io); __CPROVER_assert( - io[0] == 0x2512affeULL && io[1] == 0x0ULL && io[2] == 0xa699e71cULL, + io[0] == 0x2512affeULL && io[1] == 0xa699e71cULL && + io[2] == 0xa699e71cULL, "x86 memory operand with a struct field offset, vector 0"); } { @@ -438,7 +441,7 @@ int main(void) 0x32c9fc24972fa9f7ULL, 0x6a5b23a370b4c97bULL, 0x80000000ULL}; asm_case_12(io); __CPROVER_assert( - io[0] == 0x972fa9f7ULL && io[1] == 0x70b4c97bULL && + io[0] == 0x972fa9f7ULL && io[1] == 0xf0b4c97bULL && io[2] == 0x80000000ULL, "x86 memory operand with a struct field offset, vector 1"); } @@ -447,7 +450,7 @@ int main(void) 0x9c5bc4ac7a21b60aULL, 0x63ce12b6f4f5b47cULL, 0xd2f4c3415c4eb1fdULL}; asm_case_12(io); __CPROVER_assert( - io[0] == 0x7a21b60aULL && io[1] == 0xf4f5b47cULL && + io[0] == 0x7a21b60aULL && io[1] == 0xfcffb5fdULL && io[2] == 0x5c4eb1fdULL, "x86 memory operand with a struct field offset, vector 2"); } diff --git a/scripts/asm_differential/asm_differential.py b/scripts/asm_differential/asm_differential.py index 35b47e34db95..8c37157f1443 100644 --- a/scripts/asm_differential/asm_differential.py +++ b/scripts/asm_differential/asm_differential.py @@ -71,6 +71,8 @@ def function_source(index, case): if case.prologue: lines.append(' ' + case.prologue) lines.append(' ' + case.statement) + if case.epilogue: + lines.append(' ' + case.epilogue) k = 0 for ctype, name, length in case.variables: if length is None: diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index 818e959d9997..b3e88490118f 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -23,6 +23,9 @@ class Case: # number of input vectors (explicit plus random) vectors: int = 8 prologue: str = '' + # code after the statement, for example to copy a result that the + # statement wrote to a variable that is not in io into one that is + epilogue: str = '' # optionally adjust a random vector so the case stays deterministic constrain: Optional[Callable[[List[int]], List[int]]] = None @@ -80,6 +83,7 @@ class Case: [(U32, 'lo', None), (U32, 'hi', None), (U32, 'v', None)], prologue='struct { unsigned int lo, hi; } s = {(unsigned)io[0], ' '(unsigned)io[1]};', + epilogue='lo = s.lo; hi = s.hi;', vectors=4), ] From 6fa102ee899848cc995c843739020ed03e9eb0f6 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:36:03 +0000 Subject: [PATCH 086/100] asm_differential: check that the end of main is reachable The generated tests expected VERIFICATION SUCCESSFUL, which also holds if an assumption makes the assertions unreachable. For example, replacing ldxr/stxr in the first AArch64 case by ldr and "mov %w1, #1" makes its retry loop never exit, which with --unwind 2 --no-unwinding-assertions leaves no path to the following assertions: asm_aarch64 still verified, even with a wrong expected value for a later case. End main with __CPROVER_assert(0, "end of main is reachable"), and expect in test.desc that this assertion fails and is the only one that fails (EXIT=10, its FAILURE line, and ** 1 of N failed). The number of properties is not pinned, so that adding a case only requires regenerating main. The three tests are regenerated; with the mutation above, the sentinel now holds and asm_aarch64 fails. Co-authored-by: Kiro --- regression/cbmc/asm_aarch64/main.c | 2 ++ regression/cbmc/asm_aarch64/test.desc | 10 +++++++--- regression/cbmc/asm_arm/main.c | 2 ++ regression/cbmc/asm_arm/test.desc | 10 +++++++--- regression/cbmc/asm_x86/main.i | 2 ++ regression/cbmc/asm_x86/test.desc | 12 ++++++++---- scripts/asm_differential/README.md | 6 ++++-- scripts/asm_differential/asm_differential.py | 7 +++++++ 8 files changed, 39 insertions(+), 12 deletions(-) diff --git a/regression/cbmc/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c index f618b33cc9c9..07931ee4c639 100644 --- a/regression/cbmc/asm_aarch64/main.c +++ b/regression/cbmc/asm_aarch64/main.c @@ -494,5 +494,7 @@ int main(void) __CPROVER_assert( io[0] == 0xabcd1234ULL, "aarch64 movz/movk build a constant, vector 0"); } + // the only assertion that fails: the end of main is reachable + __CPROVER_assert(0, "end of main is reachable"); return 0; } diff --git a/regression/cbmc/asm_aarch64/test.desc b/regression/cbmc/asm_aarch64/test.desc index 86f8be6dbc81..bdbb07f358a4 100644 --- a/regression/cbmc/asm_aarch64/test.desc +++ b/regression/cbmc/asm_aarch64/test.desc @@ -1,9 +1,11 @@ CORE gcc-only main.c --arch arm64 --unwind 2 --no-unwinding-assertions -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ +^\*\* 1 of \d+ failed +^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly @@ -12,4 +14,6 @@ The AArch64 inline assembly in main.c is interpreted exactly: if CBMC approximated any statement, the assertions, which check values observed with an emulator, would fail. A store-exclusive may fail spuriously, so the retry loops of load-exclusive/store-exclusive sequences are bounded; the executions -that retry more often reach the same states. +that retry more often reach the same states. The assertion at the end of main +is the only one that fails: it shows that the end of main is reachable, so +that the other assertions do not hold vacuously. diff --git a/regression/cbmc/asm_arm/main.c b/regression/cbmc/asm_arm/main.c index fdff0b81f763..8ad339b41809 100644 --- a/regression/cbmc/asm_arm/main.c +++ b/regression/cbmc/asm_arm/main.c @@ -434,5 +434,7 @@ int main(void) io[2] == 0x8956140eULL, "arm rsb reverse-subtracts, vector 2"); } + // the only assertion that fails: the end of main is reachable + __CPROVER_assert(0, "end of main is reachable"); return 0; } diff --git a/regression/cbmc/asm_arm/test.desc b/regression/cbmc/asm_arm/test.desc index 0f22d6f1ab4a..5515e05aa947 100644 --- a/regression/cbmc/asm_arm/test.desc +++ b/regression/cbmc/asm_arm/test.desc @@ -1,9 +1,11 @@ CORE gcc-only no-new-smt main.c --arch arm --unwind 2 --no-unwinding-assertions -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ +^\*\* 1 of \d+ failed +^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly @@ -13,4 +15,6 @@ approximated any statement, the assertions, which check values observed with an emulator (Unicorn, and qemu-arm for A32 code compiled by GCC and Clang), would fail. A store-exclusive may fail spuriously, so the retry loops of load-exclusive/store-exclusive sequences are bounded; the executions that -retry more often reach the same states. +retry more often reach the same states. The assertion at the end of main is +the only one that fails: it shows that the end of main is reachable, so that +the other assertions do not hold vacuously. diff --git a/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i index 52e8d466c1ee..6b6efc9f5ec8 100644 --- a/regression/cbmc/asm_x86/main.i +++ b/regression/cbmc/asm_x86/main.i @@ -454,5 +454,7 @@ int main(void) io[2] == 0x5c4eb1fdULL, "x86 memory operand with a struct field offset, vector 2"); } + // the only assertion that fails: the end of main is reachable + __CPROVER_assert(0, "end of main is reachable"); return 0; } diff --git a/regression/cbmc/asm_x86/test.desc b/regression/cbmc/asm_x86/test.desc index 6aa55e0b613a..c0115026079e 100644 --- a/regression/cbmc/asm_x86/test.desc +++ b/regression/cbmc/asm_x86/test.desc @@ -1,13 +1,17 @@ CORE gcc-only no-new-smt main.i --arch x86_64 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ -^VERIFICATION SUCCESSFUL$ +^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ +^\*\* 1 of \d+ failed +^VERIFICATION FAILED$ -- ^warning: ignoring approximating inline assembly -- -The x86 inline assembly in main.c is interpreted exactly: if CBMC approximated +The x86 inline assembly in main.i is interpreted exactly: if CBMC approximated any statement (assigning nondeterministic values to its outputs), the -assertions, which check values observed on x86-64 hardware, would fail. +assertions, which check values observed on x86-64 hardware, would fail. The +assertion at the end of main is the only one that fails: it shows that the end +of main is reachable, so that the other assertions do not hold vacuously. diff --git a/scripts/asm_differential/README.md b/scripts/asm_differential/README.md index 364bb0ca7726..5a867ca8125f 100644 --- a/scripts/asm_differential/README.md +++ b/scripts/asm_differential/README.md @@ -47,8 +47,10 @@ statement, the C variables it reads and writes (in the order the harness stores them), and optionally fixed input vectors or a `constrain` callback for inputs that must satisfy a precondition (for example a shift count below the width). A case must be deterministic: it must not read uninitialised storage, -a timer, or I/O. Regenerate the test and check that CBMC verifies it (see the -`test.desc` next to it); a failing assertion is a bug in CBMC's semantics or a +a timer, or I/O. Regenerate the test and run it (see the `test.desc` next to +it). The assertion at the end of `main` must be the only one that fails: it +shows that the end of `main` is reachable, so that the other assertions do not +hold vacuously. Any other failing assertion is a bug in CBMC's semantics or a statement that CBMC approximates. The generated tests only cover statements that CBMC interprets exactly. diff --git a/scripts/asm_differential/asm_differential.py b/scripts/asm_differential/asm_differential.py index 8c37157f1443..ebdc378b3d87 100644 --- a/scripts/asm_differential/asm_differential.py +++ b/scripts/asm_differential/asm_differential.py @@ -258,6 +258,13 @@ def main(): lines.append(' __CPROVER_assert(%s, "%s, vector %d");' % ( checks, case.name, j)) lines.append(' }') + # Without this assertion, an assumption that made the end of main + # unreachable (for example, a retry loop that never exits) would make all + # assertions above hold vacuously. test.desc expects it to fail, and to be + # the only one that fails. + lines.append(' // the only assertion that fails: the end of main is ' + 'reachable') + lines.append(' __CPROVER_assert(0, "end of main is reachable");') lines.append(' return 0;\n}') # The x86 test is preprocessed source: preprocessing it for x86 would # fail on hosts of other architectures. From a57346b5d64bbe0f29e6f5f663cd0fa06be9c396 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:36:50 +0000 Subject: [PATCH 087/100] asm_differential: exercise the exchange of the x86 cmpxchg case The case "x86 cmpxchg exchanges on a match" only had random input vectors, whose 32-bit memory and expected values never matched, so the generated assertions only covered the path that loads the memory value into eax. Replacing "lock; cmpxchgl %3,%1" by "cmpl %1,%2; movl %1,%2", which never exchanges, still verified. Give the case explicit inputs, as the AArch64 cas case has: two that match (and exchange) and one that does not. asm_x86 is regenerated; with the replaced statement, the assertions of the two matching vectors fail. Co-authored-by: Kiro --- regression/cbmc/asm_x86/main.i | 22 ++++++------------- .../asm_differential_cases.py | 4 +++- 2 files changed, 10 insertions(+), 16 deletions(-) diff --git a/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i index 6b6efc9f5ec8..deb0798dfe02 100644 --- a/regression/cbmc/asm_x86/main.i +++ b/regression/cbmc/asm_x86/main.i @@ -353,33 +353,25 @@ int main(void) "x86 bswap reverses byte order, vector 2"); } { - unsigned long long io[4] = { - 0x80000000ULL, 0x85c6eecdbd37c64dULL, 0xe051fbafdcfbbb5eULL, 0x7fULL}; + unsigned long long io[4] = {0x7ULL, 0x5ULL, 0x5ULL, 0x9ULL}; asm_case_9(io); __CPROVER_assert( - io[0] == 0x0ULL && io[1] == 0xbd37c64dULL && io[2] == 0xbd37c64dULL && - io[3] == 0x7fULL, + io[0] == 0x1ULL && io[1] == 0x9ULL && io[2] == 0x5ULL && io[3] == 0x9ULL, "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 0"); } { - unsigned long long io[4] = { - 0x1ULL, 0x7fULL, 0x7e0269edac79ca6eULL, 0xffffffffffffffffULL}; + unsigned long long io[4] = {0x7ULL, 0xdeadbeefULL, 0xdeadbeefULL, 0x0ULL}; asm_case_9(io); __CPROVER_assert( - io[0] == 0x0ULL && io[1] == 0x7fULL && io[2] == 0x7fULL && - io[3] == 0xffffffffULL, + io[0] == 0x1ULL && io[1] == 0x0ULL && io[2] == 0xdeadbeefULL && + io[3] == 0x0ULL, "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 1"); } { - unsigned long long io[4] = { - 0xffULL, - 0xfc5d96cc82bdb472ULL, - 0x7fffffffffffffffULL, - 0x2355aca2a0edf46dULL}; + unsigned long long io[4] = {0x7ULL, 0x5ULL, 0x6ULL, 0x9ULL}; asm_case_9(io); __CPROVER_assert( - io[0] == 0x0ULL && io[1] == 0x82bdb472ULL && io[2] == 0x82bdb472ULL && - io[3] == 0xa0edf46dULL, + io[0] == 0x0ULL && io[1] == 0x5ULL && io[2] == 0x5ULL && io[3] == 0x9ULL, "x86 cmpxchg exchanges on a match (atomic_cmpset), vector 2"); } { diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index b3e88490118f..3776f4519c48 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -71,7 +71,9 @@ class Case: '__asm__ __volatile__("lock; cmpxchgl %3,%1" : "=@ccz"(ok), "+m"(m), ' '"+a"(expected) : "r"(desired) : "cc");', [(U32, 'ok', None), (U32, 'm', None), (U32, 'expected', None), - (U32, 'desired', None)]), + (U32, 'desired', None)], + # random values almost never match: exchange in the first two + inputs=[[7, 5, 5, 9], [7, 0xdeadbeef, 0xdeadbeef, 0], [7, 5, 6, 9]]), Case('x86 xchg swaps a register and memory', '__asm__ __volatile__("xchgl %0,%1" : "+r"(r), "+m"(m));', [(U32, 'r', None), (U32, 'm', None)]), From 43824920ecb18d72ad68ab4b6d5eb294a139751b Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:38:04 +0000 Subject: [PATCH 088/100] asm_differential: document the limits and conventions of the harness The README claimed that a wrong semantics of any instruction would make the generated assertions fail, but only the outputs that a case copies back to io are checked, and only for the sampled inputs. It also did not say that cases must not observe results that the architecture leaves undefined, that new cases must be appended (the seed of a case's random vectors is 1000 plus its index), or that ASM_DIFF_MAX_VECTORS does not cap the explicit inputs of a case. The module docstring did not mention pyelftools or the clang fallback for AArch64. Document these, and format the output with clang-format-18, the version that CI uses, in preference to clang-format-15. Regenerating the three tests with ASM_DIFF_MAX_VECTORS=3 still reproduces them byte for byte. Co-authored-by: Kiro --- scripts/asm_differential/README.md | 47 ++++++++++++------- scripts/asm_differential/asm_differential.py | 16 +++++-- .../asm_differential_cases.py | 15 ++++-- 3 files changed, 54 insertions(+), 24 deletions(-) diff --git a/scripts/asm_differential/README.md b/scripts/asm_differential/README.md index 5a867ca8125f..07a1e2d8184d 100644 --- a/scripts/asm_differential/README.md +++ b/scripts/asm_differential/README.md @@ -8,17 +8,21 @@ and runs it on several input vectors, on real hardware for x86-64 and with the (A32 code), then writes a CBMC regression test whose assertions pin the observed results. -If CBMC's semantics for any instruction were wrong, or if a statement were -approximated (its outputs assigned nondeterministic values) rather than -interpreted, the generated assertions would no longer hold, so running the -test under CBMC checks the semantics against the real machine. +A wrong semantics of an instruction, or a statement that CBMC approximates +(assigning nondeterministic values to its outputs) rather than interprets, +makes a generated assertion fail, so running the test under CBMC checks the +semantics against the real machine. This only holds for the outputs that a +case observes (the variables it copies back to `io`) and for the sampled +input vectors: a wrong result in a register or flag that the case does not +copy back, or for inputs that were not sampled, goes unnoticed. ## Requirements * an x86-64 host with `gcc` (x86-64 cases, run natively); * `aarch64-linux-gnu-gcc`, or else `clang` (AArch64 cases); * `clang` targeting `armv7a-none-eabi` (AArch32 cases); -* Python packages `unicorn` and `pyelftools` for the emulated architectures. +* Python packages `unicorn` and `pyelftools` for the emulated architectures; +* optionally `clang-format-18` (see below). ## Use @@ -35,23 +39,32 @@ preprocessing for x86 passes `-m64` to the host's compiler, which fails on hosts of other architectures. `ASM_DIFF_MAX_VECTORS` caps the number of input vectors per case; the -committed tests use 3. The input vectors are pseudo-random with fixed seeds, -and the output is passed through `clang-format` with the repository's style -when it is available, so regenerating in a checkout reproduces the committed -files. +committed tests use 3. The cap does not apply to the explicit inputs of a case: +a case gets all of them, and random vectors are only added while it has fewer +vectors than the cap. The random vectors are pseudo-random with fixed seeds, +and the output is passed through `clang-format-18` (the version that CI uses), +or else through `clang-format`, with the repository's style, so regenerating +in a checkout reproduces the committed files. ## Adding a case -Add a `Case` to the relevant list in `asm_differential_cases.py`: the -statement, the C variables it reads and writes (in the order the harness -stores them), and optionally fixed input vectors or a `constrain` callback for +Append a `Case` to the end of the relevant list in +`asm_differential_cases.py`. The seed of the random vectors of a case is 1000 +plus its index in the list, so inserting a case elsewhere would change the +vectors (and the expected values) of all cases after it. A case consists of +the statement, the C variables it reads and writes (in the order the harness +stores them), and optionally code to run before and after the statement +(`prologue`, `epilogue`), fixed input vectors, or a `constrain` callback for inputs that must satisfy a precondition (for example a shift count below the width). A case must be deterministic: it must not read uninitialised storage, -a timer, or I/O. Regenerate the test and run it (see the `test.desc` next to -it). The assertion at the end of `main` must be the only one that fails: it -shows that the end of `main` is reachable, so that the other assertions do not -hold vacuously. Any other failing assertion is a bug in CBMC's semantics or a -statement that CBMC approximates. +a timer, or I/O. It must also not observe results that the architecture leaves +undefined, such as flags that an instruction leaves undefined, or the +destination of x86 `bsr` when the source is 0: constrain the inputs, or do not +copy such a result back to `io`. Regenerate the test and run it (see the +`test.desc` next to it). The assertion at the end of `main` must be the only +one that fails: it shows that the end of `main` is reachable, so that the +other assertions do not hold vacuously. Any other failing assertion is a bug +in CBMC's semantics or a statement that CBMC approximates. The generated tests only cover statements that CBMC interprets exactly. Properties that the architecture permits to be violated (such as a diff --git a/scripts/asm_differential/asm_differential.py b/scripts/asm_differential/asm_differential.py index ebdc378b3d87..af513cd6fd4a 100644 --- a/scripts/asm_differential/asm_differential.py +++ b/scripts/asm_differential/asm_differential.py @@ -12,8 +12,15 @@ asm_differential.py ARCH OUTPUT_DIR ARCH is x86_64, aarch64 or arm. Requirements: gcc (x86_64), -aarch64-linux-gnu-gcc (aarch64), clang (arm), and the Python package unicorn -(pip install unicorn) for the emulated architectures. +aarch64-linux-gnu-gcc or else clang (aarch64), clang (arm), and the Python +packages unicorn and pyelftools (pip install unicorn pyelftools) for the +emulated architectures. The output is formatted with clang-format-18, or else +clang-format, if one of them is available. + +The random input vectors of the case with index i in its list are seeded with +1000 + i, so new cases must be appended to keep the vectors of the existing +ones. ASM_DIFF_MAX_VECTORS, if set, caps the number of vectors of each case, +but explicit inputs are always used. """ import os @@ -274,11 +281,12 @@ def main(): f.write('\n'.join(lines) + '\n') # keep the committed test clang-format clean, if the formatter is present, - # using the style of the repository (the output may be outside of it) + # using the style of the repository (the output may be outside of it); + # prefer the version that CI uses style = os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', '..', '.clang-format') - for formatter in ('clang-format-15', 'clang-format'): + for formatter in ('clang-format-18', 'clang-format'): if have(formatter): subprocess.check_call( [formatter, '--style=file:' + os.path.normpath(style), '-i', diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index 3776f4519c48..62e79d03610d 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -5,7 +5,14 @@ writes. The harness compiles and runs it on hardware (or an emulator) to discover the expected results, then emits a CBMC regression test that pins them. A case must therefore be deterministic: no reads of uninitialised -storage, timers, or I/O. +storage, timers, or I/O, and no results that the architecture leaves undefined +(such as undefined flags, or the result of x86 bsr of 0). A wrong semantics is +only detected for the outputs that a case copies back to io, and for the +sampled inputs. + +The random input vectors of a case are seeded with 1000 plus its index in its +list: append new cases, so that the vectors of the existing cases stay the +same. """ from dataclasses import dataclass, field @@ -18,9 +25,11 @@ class Case: statement: str # (C type, name, array length or None) for each variable, in io order variables: List[Tuple[str, str, Optional[int]]] - # explicit input vectors (each a list of values, in io order) + # explicit input vectors (each a list of values, in io order), which are + # all used, whatever ASM_DIFF_MAX_VECTORS is inputs: List[List[int]] = field(default_factory=list) - # number of input vectors (explicit plus random) + # number of input vectors: random ones are added to the explicit ones up + # to this number, or up to ASM_DIFF_MAX_VECTORS if that is lower vectors: int = 8 prologue: str = '' # code after the statement, for example to copy a result that the From 96627876a8d281f396bd3fb0e9750887b54d4ce2 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 11:12:37 +0000 Subject: [PATCH 089/100] Inline assembly: interpret AArch64 load/store pairs ldp and stp are the common way to move two registers to or from memory (for example in memcpy-like code and in 128-bit atomics fallbacks), but they were not interpreted, so statements using them were approximated. Interpret ldp, ldnp, ldpsw, stp, and stnp with an offset addressing mode (without writeback): two accesses of the register width (32 bits for the sign-extended words of ldpsw) at the address and right after it. Both loads of ldp use the address before either register is written, as the base register may be one of them. ldp of the same register twice is constrained unpredictable and makes the statement uninterpreted. The two accesses are not modeled as one atomic access, which is sound: they are not single-copy atomic as a pair before FEAT_LSE2. New cases of the differential harness cover the instructions; their expected values were observed with Unicorn and agree with qemu-aarch64. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 9 +- regression/cbmc/asm_aarch64/main.c | 260 ++++++++++++++++++ .../asm_differential_cases.py | 20 ++ src/assembler/asm_aarch64.cpp | 46 ++++ 4 files changed, 331 insertions(+), 4 deletions(-) diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index efb318a2ca4e..9772a30e28df 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -149,10 +149,11 @@ The AArch64 semantics cover: `orn`, `eon`, `lsl`, `lsr`, `asr`, `ror`, `cmp`, `cmn`, `tst`, and the conditional selects (`csel`, `csinc`, `csinv`, `csneg`, `cset`, `csetm`); - loads and stores of single registers (including acquire/release - variants), the LSE atomics - (`ldadd`, `ldclr`, `ldeor`, `ldset`, `ldsmax`, `ldsmin`, `ldumax`, - `ldumin`, their `st` forms, `swp`, `cas`), and load-exclusive/ - store-exclusive (`ldxr`, `ldaxr`, `stxr`, `stlxr`, `clrex`); + variants) and of register pairs (`ldp`, `ldnp`, `ldpsw`, `stp`, `stnp`), + without writeback, the LSE atomics (`ldadd`, `ldclr`, `ldeor`, `ldset`, + `ldsmax`, `ldsmin`, `ldumax`, `ldumin`, their `st` forms, `swp`, `cas`), + and load-exclusive/store-exclusive (`ldxr`, `ldaxr`, `stxr`, `stlxr`, + `clrex`); the two accesses of a pair are not one atomic access; - branches within the statement and to the labels of `asm goto`, and flag outputs (`=@cc`); - barriers: `dmb` and `dsb` order the accesses that their option selects diff --git a/regression/cbmc/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c index 07931ee4c639..348fb948d8c5 100644 --- a/regression/cbmc/asm_aarch64/main.c +++ b/regression/cbmc/asm_aarch64/main.c @@ -178,6 +178,94 @@ void asm_case_11(unsigned long long *io) io[0] = (unsigned long long)r; } +// aarch64 ldp loads two adjacent doublewords +void asm_case_12(unsigned long long *io) +{ + unsigned long m[2]; + m[0] = (unsigned long)io[0]; + m[1] = (unsigned long)io[1]; + unsigned long a = (unsigned long)io[2]; + unsigned long b = (unsigned long)io[3]; + __asm__ __volatile__("ldp %0, %1, [%2]" + : "=r"(a), "=r"(b) + : "r"(m) + : "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)a; + io[3] = (unsigned long long)b; +} + +// aarch64 stp stores two adjacent doublewords +void asm_case_13(unsigned long long *io) +{ + unsigned long m[2]; + m[0] = (unsigned long)io[0]; + m[1] = (unsigned long)io[1]; + unsigned long a = (unsigned long)io[2]; + unsigned long b = (unsigned long)io[3]; + __asm__ __volatile__("stp %1, %2, [%0]" + : + : "r"(m), "r"(a), "r"(b) + : "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)a; + io[3] = (unsigned long long)b; +} + +// aarch64 ldp of words with an offset +void asm_case_14(unsigned long long *io) +{ + unsigned int m[3]; + m[0] = (unsigned int)io[0]; + m[1] = (unsigned int)io[1]; + m[2] = (unsigned int)io[2]; + unsigned int a = (unsigned int)io[3]; + unsigned int b = (unsigned int)io[4]; + __asm__ __volatile__("ldp %w0, %w1, [%2, #4]" + : "=r"(a), "=r"(b) + : "r"(m) + : "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)m[2]; + io[3] = (unsigned long long)a; + io[4] = (unsigned long long)b; +} + +// aarch64 ldpsw sign-extends two words +void asm_case_15(unsigned long long *io) +{ + unsigned int m[2]; + m[0] = (unsigned int)io[0]; + m[1] = (unsigned int)io[1]; + unsigned long a = (unsigned long)io[2]; + unsigned long b = (unsigned long)io[3]; + __asm__ __volatile__("ldpsw %0, %1, [%2]" + : "=r"(a), "=r"(b) + : "r"(m) + : "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)a; + io[3] = (unsigned long long)b; +} + +// aarch64 ldp into the base register +void asm_case_16(unsigned long long *io) +{ + unsigned long m[2]; + m[0] = (unsigned long)io[0]; + m[1] = (unsigned long)io[1]; + unsigned long b = (unsigned long)io[2]; + unsigned long *p = m; + __asm__ __volatile__("ldp %0, %1, [%0]" : "+r"(p), "=r"(b) : : "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)b; +} + int main(void) { { @@ -494,6 +582,178 @@ int main(void) __CPROVER_assert( io[0] == 0xabcd1234ULL, "aarch64 movz/movk build a constant, vector 0"); } + { + unsigned long long io[4] = { + 0x67474bfe2512affeULL, + 0x0ULL, + 0xd9b9851fa699e71cULL, + 0x32c9fc24972fa9f7ULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x67474bfe2512affeULL && io[1] == 0x0ULL && + io[2] == 0x67474bfe2512affeULL && io[3] == 0x0ULL, + "aarch64 ldp loads two adjacent doublewords, vector 0"); + } + { + unsigned long long io[4] = { + 0x6a5b23a370b4c97bULL, + 0x80000000ULL, + 0x9c5bc4ac7a21b60aULL, + 0x63ce12b6f4f5b47cULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x6a5b23a370b4c97bULL && io[1] == 0x80000000ULL && + io[2] == 0x6a5b23a370b4c97bULL && io[3] == 0x80000000ULL, + "aarch64 ldp loads two adjacent doublewords, vector 1"); + } + { + unsigned long long io[4] = { + 0xd2f4c3415c4eb1fdULL, + 0x7fffffffffffffffULL, + 0x8f6b402bd0d62394ULL, + 0xa34ba2d37b54dc20ULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0xd2f4c3415c4eb1fdULL && io[1] == 0x7fffffffffffffffULL && + io[2] == 0xd2f4c3415c4eb1fdULL && io[3] == 0x7fffffffffffffffULL, + "aarch64 ldp loads two adjacent doublewords, vector 2"); + } + { + unsigned long long io[4] = { + 0x414e0d53c3fd25cdULL, + 0xc2419663b9c3f00dULL, + 0x2f0044d6b297f10dULL, + 0x6269dc3d06f39618ULL}; + asm_case_13(io); + __CPROVER_assert( + io[0] == 0x2f0044d6b297f10dULL && io[1] == 0x6269dc3d06f39618ULL && + io[2] == 0x2f0044d6b297f10dULL && io[3] == 0x6269dc3d06f39618ULL, + "aarch64 stp stores two adjacent doublewords, vector 0"); + } + { + unsigned long long io[4] = { + 0x627a2dc40e3b9e5aULL, 0x80ULL, 0xffULL, 0x80000000ULL}; + asm_case_13(io); + __CPROVER_assert( + io[0] == 0xffULL && io[1] == 0x80000000ULL && io[2] == 0xffULL && + io[3] == 0x80000000ULL, + "aarch64 stp stores two adjacent doublewords, vector 1"); + } + { + unsigned long long io[4] = { + 0x35d1dd8f11de1b36ULL, + 0xffffffffffffffffULL, + 0x64213bdf295fa7abULL, + 0xa075d926532fb08dULL}; + asm_case_13(io); + __CPROVER_assert( + io[0] == 0x64213bdf295fa7abULL && io[1] == 0xa075d926532fb08dULL && + io[2] == 0x64213bdf295fa7abULL && io[3] == 0xa075d926532fb08dULL, + "aarch64 stp stores two adjacent doublewords, vector 2"); + } + { + unsigned long long io[5] = { + 0x4107a0603d40960aULL, + 0x7fffffffULL, + 0x9f389f989e267f72ULL, + 0xffffffffULL, + 0xb358d371cf123e51ULL}; + asm_case_14(io); + __CPROVER_assert( + io[0] == 0x3d40960aULL && io[1] == 0x7fffffffULL && + io[2] == 0x9e267f72ULL && io[3] == 0x7fffffffULL && + io[4] == 0x9e267f72ULL, + "aarch64 ldp of words with an offset, vector 0"); + } + { + unsigned long long io[5] = { + 0x1a45527e7835f76aULL, + 0x7fULL, + 0x25e5bf65b96f18deULL, + 0x2ULL, + 0x868aac5454c3cd50ULL}; + asm_case_14(io); + __CPROVER_assert( + io[0] == 0x7835f76aULL && io[1] == 0x7fULL && io[2] == 0xb96f18deULL && + io[3] == 0x7fULL && io[4] == 0xb96f18deULL, + "aarch64 ldp of words with an offset, vector 1"); + } + { + unsigned long long io[5] = { + 0x2f9e118a3edb74c3ULL, + 0xc2257f5d0e04ac3aULL, + 0x8000000000000000ULL, + 0x6c2abfb9825b0341ULL, + 0xffULL}; + asm_case_14(io); + __CPROVER_assert( + io[0] == 0x3edb74c3ULL && io[1] == 0xe04ac3aULL && io[2] == 0x0ULL && + io[3] == 0xe04ac3aULL && io[4] == 0x0ULL, + "aarch64 ldp of words with an offset, vector 2"); + } + { + unsigned long long io[4] = { + 0x80ULL, + 0x7c923e8bf724e295ULL, + 0xc29563a4ce21629fULL, + 0x6fb9eec747852fd7ULL}; + asm_case_15(io); + __CPROVER_assert( + io[0] == 0x80ULL && io[1] == 0xf724e295ULL && io[2] == 0x80ULL && + io[3] == 0xfffffffff724e295ULL, + "aarch64 ldpsw sign-extends two words, vector 0"); + } + { + unsigned long long io[4] = { + 0x4e794b8fd3415364ULL, + 0x9f9fe266e5391903ULL, + 0xe81bd75796170b1eULL, + 0x6988bebfdb954dcaULL}; + asm_case_15(io); + __CPROVER_assert( + io[0] == 0xd3415364ULL && io[1] == 0xe5391903ULL && + io[2] == 0xffffffffd3415364ULL && io[3] == 0xffffffffe5391903ULL, + "aarch64 ldpsw sign-extends two words, vector 1"); + } + { + unsigned long long io[4] = { + 0x694f0df1e249a224ULL, + 0xa5288feea0dd6dedULL, + 0x3b5ccfa5b7d38265ULL, + 0x9c6db6df3add95e3ULL}; + asm_case_15(io); + __CPROVER_assert( + io[0] == 0xe249a224ULL && io[1] == 0xa0dd6dedULL && + io[2] == 0xffffffffe249a224ULL && io[3] == 0xffffffffa0dd6dedULL, + "aarch64 ldpsw sign-extends two words, vector 2"); + } + { + unsigned long long io[3] = { + 0x8bb0203c63f4822eULL, 0x2bc27e528f6dfd28ULL, 0x105c864ba75fa96aULL}; + asm_case_16(io); + __CPROVER_assert( + io[0] == 0x8bb0203c63f4822eULL && io[1] == 0x2bc27e528f6dfd28ULL && + io[2] == 0x2bc27e528f6dfd28ULL, + "aarch64 ldp into the base register, vector 0"); + } + { + unsigned long long io[3] = { + 0x8f43bdf7e2b5b16ULL, 0xc301696ae878eea2ULL, 0x653e09f78221d081ULL}; + asm_case_16(io); + __CPROVER_assert( + io[0] == 0x8f43bdf7e2b5b16ULL && io[1] == 0xc301696ae878eea2ULL && + io[2] == 0xc301696ae878eea2ULL, + "aarch64 ldp into the base register, vector 1"); + } + { + unsigned long long io[3] = { + 0x7fd174cb93801745ULL, 0x7fffffffffffffffULL, 0xffULL}; + asm_case_16(io); + __CPROVER_assert( + io[0] == 0x7fd174cb93801745ULL && io[1] == 0x7fffffffffffffffULL && + io[2] == 0x7fffffffffffffffULL, + "aarch64 ldp into the base register, vector 2"); + } // the only assertion that fails: the end of main is reachable __CPROVER_assert(0, "end of main is reachable"); return 0; diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index 62e79d03610d..5efeb80b5e1f 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -155,6 +155,26 @@ class Case: Case('aarch64 movz/movk build a constant', '__asm__("movz %0, #0x1234\\n movk %0, #0xabcd, lsl #16" : "=r"(r));', [(U64, 'r', None)], vectors=1), + Case('aarch64 ldp loads two adjacent doublewords', + '__asm__ __volatile__("ldp %0, %1, [%2]" : "=r"(a), "=r"(b) : ' + '"r"(m) : "memory");', + [(U64, 'm', 2), (U64, 'a', None), (U64, 'b', None)]), + Case('aarch64 stp stores two adjacent doublewords', + '__asm__ __volatile__("stp %1, %2, [%0]" : : "r"(m), "r"(a), ' + '"r"(b) : "memory");', + [(U64, 'm', 2), (U64, 'a', None), (U64, 'b', None)]), + Case('aarch64 ldp of words with an offset', + '__asm__ __volatile__("ldp %w0, %w1, [%2, #4]" : "=r"(a), "=r"(b) : ' + '"r"(m) : "memory");', + [(U32, 'm', 3), (U32, 'a', None), (U32, 'b', None)]), + Case('aarch64 ldpsw sign-extends two words', + '__asm__ __volatile__("ldpsw %0, %1, [%2]" : "=r"(a), "=r"(b) : ' + '"r"(m) : "memory");', + [(U32, 'm', 2), (U64, 'a', None), (U64, 'b', None)]), + Case('aarch64 ldp into the base register', + '__asm__ __volatile__("ldp %0, %1, [%0]" : "+r"(p), "=r"(b) : : ' + '"memory");', + [(U64, 'm', 2), (U64, 'b', None)], prologue='unsigned long *p = m;'), ] # cas needs its compare value to sometimes match memory; supply fixed vectors diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 856a68ed2d6d..33947f383f11 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -680,6 +680,52 @@ bool asm_aarch64_semanticst::lower_memory( } } + // pairs: Rt, Rt2, [Xn, #imm], accessing two adjacent elements + if(m == "ldp" || m == "ldnp" || m == "ldpsw" || m == "stp" || m == "stnp") + { + if( + ops.size() != 3 || !register_operand(0) || !register_operand(1) || + !memory_operand(2) || ops[0].width != ops[1].width || + (m == "ldpsw" && ops[0].width != 64)) + { + return ctx.fail("unsupported operands of " + m); + } + const bool load = m[0] == 'l'; + const std::size_t size = m == "ldpsw" ? 32 : ops[0].width; + // the elements, at the address and size/8 bytes after it + std::vector elements{2, ops[2]}; + for(std::size_t i = 0; i < 2; ++i) + { + elements[i].lvalue = nil_exprt{}; + elements[i].address = plus_exprt{ + typecast_exprt::conditional_cast( + ops[2].address, pointer_type(char_type())), + from_integer(i * size / 8, signed_size_type())}; + } + if(!load) + { + const symbol_exprt first = temp(read(ctx, ops[0], size), "first"); + const symbol_exprt second = temp(read(ctx, ops[1], size), "second"); + return write(ctx, elements[0], size, first) && + write(ctx, elements[1], size, second); + } + // a load of the same register twice is unpredictable + if( + ops[0].zero_register == ops[1].zero_register && + (ops[0].zero_register || ops[0].storage == ops[1].storage)) + { + return ctx.fail("ldp of the same register twice"); + } + // both loads use the address before either register is written + const symbol_exprt first = temp(read(ctx, elements[0], size), "first"); + const symbol_exprt second = temp(read(ctx, elements[1], size), "second"); + const std::size_t rw = ops[0].width; + auto extend = [&](const exprt &v) + { return m == "ldpsw" ? sign_extend(v, size, rw) : resize(v, rw); }; + return write(ctx, ops[0], rw, extend(first)) && + write(ctx, ops[1], rw, extend(second)); + } + // store-exclusive: Ws, Rt, [Xn] { static const std::map stores = { From 2fb714b07531f396ba89a5dbba258bc58a49b170 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 11:19:32 +0000 Subject: [PATCH 090/100] Inline assembly: interpret AArch32 loads and stores of multiple registers ldm and stm, and push and pop, which save and restore registers around code that needs them, were not interpreted, so statements using them were approximated. The template splitter also split register lists such as {r4, r5} at their commas. Interpret ldm and stm with the address modes ia, ib, da, db (and their stack aliases fd, fa, ed, ea), with or without writeback: all values are read before any register or memory is written, as the base register may be in the list. The registers are stored in the order of their numbers, which is not known for operand references, so a list with an operand reference must have no other register. A list with sp or pc, and writeback of a base register in the list (unpredictable for ldm, and storing an unknown value for stm), make the statement uninterpreted. In divided syntax for Thumb-1, ldmia and stmia without ! are assembled with writeback, so without a sign that the statement is not Thumb-1 code (such as .syntax unified, or an address mode other than ia), ldm and stm without writeback are not interpreted. push and pop (and stmdb sp!, ldmia sp!) use the memory below the stack pointer, which belongs to no C object, while sp is an unknown value whose use as an address is not interpreted. Model them with a stack of the statement's own, which make_a32_state checks to be balanced, unconditional, and without a label or branch while registers are pushed. As the model does not change sp, a statement that uses sp, or a memory operand (which the compiler may address relative to sp), while registers are pushed is not interpreted. New cases of the differential harness, and of asm_arm_corner_cases, cover the instructions; the expected values were observed with Unicorn and agree with qemu-arm for A32 code compiled by GCC and Clang (and for T32 code in the corner cases). Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 5 + doc/cprover-manual/modeling-inline-asm.md | 16 + regression/cbmc/asm_arm/main.c | 223 ++++++++ regression/cbmc/asm_arm_corner_cases/main.c | 9 + .../cbmc/asm_arm_corner_cases/test.desc | 3 + .../asm_differential_cases.py | 22 + src/assembler/asm_arm.cpp | 500 +++++++++++++++++- src/assembler/asm_template.cpp | 15 +- 8 files changed, 767 insertions(+), 26 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 55f86a2b6134..b793e39df331 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -194,6 +194,11 @@ statement with a conditional load-exclusive, or with a conditional store-exclusive and another store-exclusive, is not interpreted (a conditional load-exclusive would open the region on both paths, and a conditional store-exclusive ends it on both). +`push` and `pop` use a stack in the statement's state (`a32_statet::stack`) +rather than memory, and do not change `sp`. `make_a32_state` checks that they +are balanced in straight-line code and that `sp` is not used while registers +are pushed, and `lower` fails on memory operands while registers are pushed, +as the compiler may address them relative to `sp`. For `asm goto`, goto conversion creates a variable that selects the label to jump to (`code_asm_gcct::goto_target`) and dispatches on it after the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 9772a30e28df..1139402cc5f6 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -221,6 +221,10 @@ syntax: modeled if it is the only store-exclusive of the statement, but a statement with a conditional load-exclusive, or with a conditional store-exclusive and another store-exclusive, is not interpreted; +- loads and stores of multiple registers (`ldm`, `stm`, with the address + modes `ia`, `ib`, `da`, `db` and their stack aliases, with or without + writeback) of registers named in the list, or of a single operand + reference, and `push` and `pop` (also as `stmdb sp!` and `ldmia sp!`); - branches within the statement and to the labels of `asm goto` (`b`, `b`, `cbz`, `cbnz`), and flag outputs (`=@cc`); - barriers (`dmb`, `dsb`, `isb`, and their CP15 forms), `mrs` and `msr` of @@ -254,6 +258,18 @@ the banked registers of the new mode (`sp` and `lr`, and r8 to r12 in FIQ mode), including the registers from which the compiler reads output operands. Reading or writing `pc` is not modeled. +The registers that `push` saves are kept on a stack of the statement's own: +the memory below the stack pointer belongs to no C object. This requires the +pushes and pops of a statement to be balanced, unconditional, and without a +label or branch between a push and its pop, and the statement not to use `sp` +or a memory operand (which the compiler may address relative to `sp`) while +registers are pushed; other statements with `push` or `pop` are not +interpreted. A register that is saved and restored must still be clobbered +if the statement writes it in between, as the compiler may place an operand +in it. Without `.syntax unified` or another sign that the statement is not +Thumb-1 code, `ldm` and `stm` without writeback are not interpreted: in +divided syntax for Thumb-1, `ldmia r0, {r1}` is assembled with writeback. + ### Supported Instructions CBMC splits the assembler text into instructions at newlines and `;`, except diff --git a/regression/cbmc/asm_arm/main.c b/regression/cbmc/asm_arm/main.c index 8ad339b41809..ccc90e534d4f 100644 --- a/regression/cbmc/asm_arm/main.c +++ b/regression/cbmc/asm_arm/main.c @@ -149,6 +149,87 @@ void asm_case_8(unsigned long long *io) io[2] = (unsigned long long)b; } +// arm ldm loads consecutive words +void asm_case_9(unsigned long long *io) +{ + unsigned int m[2]; + m[0] = (unsigned int)io[0]; + m[1] = (unsigned int)io[1]; + unsigned int a = (unsigned int)io[2]; + unsigned int b = (unsigned int)io[3]; + __asm__ __volatile__( + ".syntax unified\n ldm %2, {r4, r5}\n mov %0, r4\n mov %1, r5" + : "=r"(a), "=r"(b) + : "r"(m) + : "r4", "r5", "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)a; + io[3] = (unsigned long long)b; +} + +// arm ldmib and ldmda +void asm_case_10(unsigned long long *io) +{ + unsigned int m[4]; + m[0] = (unsigned int)io[0]; + m[1] = (unsigned int)io[1]; + m[2] = (unsigned int)io[2]; + m[3] = (unsigned int)io[3]; + unsigned int a = (unsigned int)io[4]; + unsigned int b = (unsigned int)io[5]; + __asm__ __volatile__( + "ldmib %2, {r4, r5}\n ldmda %3, {r6, r7}\n sub %0, r4, r6\n sub %1, r5, r7" + : "=r"(a), "=r"(b) + : "r"(m), "r"(m + 3) + : "r4", "r5", "r6", "r7", "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)m[2]; + io[3] = (unsigned long long)m[3]; + io[4] = (unsigned long long)a; + io[5] = (unsigned long long)b; +} + +// arm stmdb with writeback +void asm_case_11(unsigned long long *io) +{ + unsigned int m[2]; + m[0] = (unsigned int)io[0]; + m[1] = (unsigned int)io[1]; + unsigned int a = (unsigned int)io[2]; + unsigned int b = (unsigned int)io[3]; + unsigned int c = (unsigned int)io[4]; + unsigned int *p = m + 2; + __asm__ __volatile__( + "mov r4, %2\n mov r5, %3\n stmdb %0!, {r4, r5}\n ldr %1, [%0, #4]" + : "+r"(p), "=r"(c) + : "r"(a), "r"(b) + : "r4", "r5", "memory"); + io[0] = (unsigned long long)m[0]; + io[1] = (unsigned long long)m[1]; + io[2] = (unsigned long long)a; + io[3] = (unsigned long long)b; + io[4] = (unsigned long long)c; +} + +// arm push and pop move values through the stack +void asm_case_12(unsigned long long *io) +{ + unsigned int r = (unsigned int)io[0]; + unsigned int a = (unsigned int)io[1]; + unsigned int b = (unsigned int)io[2]; + __asm__ __volatile__( + "mov r4, %1\n mov r5, %2\n push {r4, r5}\n pop {r6}\n pop {r7}\n sub %0, " + "r6, r7" + : "=r"(r) + : "r"(a), "r"(b) + : "r4", "r5", "r6", "r7", "memory"); + io[0] = (unsigned long long)r; + io[1] = (unsigned long long)a; + io[2] = (unsigned long long)b; +} + int main(void) { { @@ -434,6 +515,148 @@ int main(void) io[2] == 0x8956140eULL, "arm rsb reverse-subtracts, vector 2"); } + { + unsigned long long io[4] = { + 0x80000000ULL, 0x85c6eecdbd37c64dULL, 0xe051fbafdcfbbb5eULL, 0x7fULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x80000000ULL && io[1] == 0xbd37c64dULL && + io[2] == 0x80000000ULL && io[3] == 0xbd37c64dULL, + "arm ldm loads consecutive words, vector 0"); + } + { + unsigned long long io[4] = { + 0x1ULL, 0x7fULL, 0x7e0269edac79ca6eULL, 0xffffffffffffffffULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x1ULL && io[1] == 0x7fULL && io[2] == 0x1ULL && + io[3] == 0x7fULL, + "arm ldm loads consecutive words, vector 1"); + } + { + unsigned long long io[4] = { + 0xffULL, + 0xfc5d96cc82bdb472ULL, + 0x7fffffffffffffffULL, + 0x2355aca2a0edf46dULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0xffULL && io[1] == 0x82bdb472ULL && io[2] == 0xffULL && + io[3] == 0x82bdb472ULL, + "arm ldm loads consecutive words, vector 2"); + } + { + unsigned long long io[6] = { + 0xd29b8652db47179aULL, + 0x1ULL, + 0x2a12166c6984b1c3ULL, + 0xffffffffffffffffULL, + 0xd57e59721b5c3f00ULL, + 0x8161ebbba4c1b5daULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0xdb47179aULL && io[1] == 0x1ULL && io[2] == 0x6984b1c3ULL && + io[3] == 0xffffffffULL && io[4] == 0x967b4e3eULL && + io[5] == 0x6984b1c4ULL, + "arm ldmib and ldmda, vector 0"); + } + { + unsigned long long io[6] = { + 0x935751a544d88a1aULL, + 0x7a41298a64568e24ULL, + 0x5e4c1de7ba5f33e2ULL, + 0x870cf5c903adeee9ULL, + 0x4913351bbe5f646dULL, + 0x25f4ba50fe38643eULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0x44d88a1aULL && io[1] == 0x64568e24ULL && + io[2] == 0xba5f33e2ULL && io[3] == 0x3adeee9ULL && + io[4] == 0xa9f75a42ULL && io[5] == 0xb6b144f9ULL, + "arm ldmib and ldmda, vector 1"); + } + { + unsigned long long io[6] = { + 0x2ULL, + 0xd59b3a6ec98b8b59ULL, + 0x6830ad2bbf10bb2ULL, + 0x7fffffffULL, + 0x0ULL, + 0xed1f3299a142c10eULL}; + asm_case_10(io); + __CPROVER_assert( + io[0] == 0x2ULL && io[1] == 0xc98b8b59ULL && io[2] == 0xbbf10bb2ULL && + io[3] == 0x7fffffffULL && io[4] == 0xd9a7fa7ULL && + io[5] == 0x3bf10bb3ULL, + "arm ldmib and ldmda, vector 2"); + } + { + unsigned long long io[5] = { + 0x6a08e48807e06ce6ULL, + 0x80000000ULL, + 0x715314e0aeb3b1f3ULL, + 0x2dac4420420cf8f6ULL, + 0x8000000000000000ULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0xaeb3b1f3ULL && io[1] == 0x420cf8f6ULL && + io[2] == 0xaeb3b1f3ULL && io[3] == 0x420cf8f6ULL && + io[4] == 0x420cf8f6ULL, + "arm stmdb with writeback, vector 0"); + } + { + unsigned long long io[5] = { + 0xffffffffffffffffULL, + 0xff19d85a9e12e041ULL, + 0x7fULL, + 0x7fffffffffffffffULL, + 0x4fb5e44fdd1fc0bULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0x7fULL && io[1] == 0xffffffffULL && io[2] == 0x7fULL && + io[3] == 0xffffffffULL && io[4] == 0xffffffffULL, + "arm stmdb with writeback, vector 1"); + } + { + unsigned long long io[5] = { + 0xd3f4de8fd7d4ac31ULL, + 0x0ULL, + 0x8a2e574287b8a8fcULL, + 0xffffffffffffffffULL, + 0xef565c1b436863dfULL}; + asm_case_11(io); + __CPROVER_assert( + io[0] == 0x87b8a8fcULL && io[1] == 0xffffffffULL && + io[2] == 0x87b8a8fcULL && io[3] == 0xffffffffULL && + io[4] == 0xffffffffULL, + "arm stmdb with writeback, vector 2"); + } + { + unsigned long long io[3] = { + 0x67474bfe2512affeULL, 0x0ULL, 0xd9b9851fa699e71cULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x596618e4ULL && io[1] == 0x0ULL && io[2] == 0xa699e71cULL, + "arm push and pop move values through the stack, vector 0"); + } + { + unsigned long long io[3] = { + 0x32c9fc24972fa9f7ULL, 0x6a5b23a370b4c97bULL, 0x80000000ULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0xf0b4c97bULL && io[1] == 0x70b4c97bULL && + io[2] == 0x80000000ULL, + "arm push and pop move values through the stack, vector 1"); + } + { + unsigned long long io[3] = { + 0x9c5bc4ac7a21b60aULL, 0x63ce12b6f4f5b47cULL, 0xd2f4c3415c4eb1fdULL}; + asm_case_12(io); + __CPROVER_assert( + io[0] == 0x98a7027fULL && io[1] == 0xf4f5b47cULL && + io[2] == 0x5c4eb1fdULL, + "arm push and pop move values through the stack, vector 2"); + } // the only assertion that fails: the end of main is reachable __CPROVER_assert(0, "end of main is reachable"); return 0; diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index a816a5fef946..042c934f21d0 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -244,3 +244,12 @@ int main(void) return 0; } + +// Statements whose use of the stack is not modeled. They are not executed, +// as they would break the program. +void unbalanced(void) +{ + __asm__ volatile("push {r4}"); + __asm__ volatile("push {r4}\n1: pop {r4}"); + __asm__ volatile("pop {pc}"); +} diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index 26861023d6d5..2454896a604c 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -44,6 +44,9 @@ approximating inline assembly statement at .* line 153 function main: writes reg approximating inline assembly statement at .* line 161 function main: msr of the processor mode, which banks r8 to r14, and operands used after it approximating inline assembly statement at .* line 217 function main: cache invalidation without cleaning approximating inline assembly statement at .* line 226 function main: conditional load-exclusive, or conditional store-exclusive and another store-exclusive +approximating inline assembly statement at .* line 252 function unbalanced: registers pushed and not popped +approximating inline assembly statement at .* line 253 function unbalanced: label while registers are pushed +approximating inline assembly statement at .* line 254 function unbalanced: push or pop that is conditional or of registers that are not modeled ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index 5efeb80b5e1f..525d17d505d6 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -227,6 +227,28 @@ class Case: Case('arm rsb reverse-subtracts', '__asm__("rsb %0, %1, %2" : "=r"(r) : "r"(a), "r"(b));', [(U32, 'r', None), (U32, 'a', None), (U32, 'b', None)]), + Case('arm ldm loads consecutive words', + '__asm__ __volatile__(".syntax unified\\n ldm %2, {r4, r5}\\n' + ' mov %0, r4\\n' + ' mov %1, r5" : "=r"(a), "=r"(b) : "r"(m) : "r4", "r5", "memory");', + [(U32, 'm', 2), (U32, 'a', None), (U32, 'b', None)]), + Case('arm ldmib and ldmda', + '__asm__ __volatile__("ldmib %2, {r4, r5}\\n ldmda %3, {r6, r7}\\n' + ' sub %0, r4, r6\\n sub %1, r5, r7" : "=r"(a), "=r"(b) : "r"(m), ' + '"r"(m + 3) : "r4", "r5", "r6", "r7", "memory");', + [(U32, 'm', 4), (U32, 'a', None), (U32, 'b', None)]), + Case('arm stmdb with writeback', + '__asm__ __volatile__("mov r4, %2\\n mov r5, %3\\n' + ' stmdb %0!, {r4, r5}\\n ldr %1, [%0, #4]" : "+r"(p), "=r"(c) : ' + '"r"(a), "r"(b) : "r4", "r5", "memory");', + [(U32, 'm', 2), (U32, 'a', None), (U32, 'b', None), + (U32, 'c', None)], + prologue='unsigned int *p = m + 2;'), + Case('arm push and pop move values through the stack', + '__asm__ __volatile__("mov r4, %1\\n mov r5, %2\\n' + ' push {r4, r5}\\n pop {r6}\\n pop {r7}\\n sub %0, r6, r7" : ' + '"=r"(r) : "r"(a), "r"(b) : "r4", "r5", "r6", "r7", "memory");', + [(U32, 'r', None), (U32, 'a', None), (U32, 'b', None)]), ] CASES = {'x86_64': X86_64, 'aarch64': AARCH64, 'arm': ARM} diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 0c97ce11cc5b..ae716b8f66a8 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -83,14 +83,18 @@ const std::vector &operations() static const std::vector result = [] { std::vector b = { - "mov", "mvn", "add", "adc", "sub", "sbc", "rsb", "and", - "orr", "eor", "bic", "cmp", "cmn", "tst", "teq", "lsl", - "lsr", "asr", "ror", "neg", "mul", "b", "cbz", "cbnz", - "ldr", "ldrb", "ldrh", "ldrsb", "ldrsh", "str", "strb", "strh", - "ldrex", "ldrexb", "ldrexh", "strex", "strexb", "strexh", "clz", "rev", - "rev16", "rbit", "uxtb", "uxth", "sxtb", "sxth", "movw", "movt", - "mrs", "msr", "mrc", "mcr", "nop", "yield", "wfe", "wfi", - "sev", "sevl"}; + "mov", "mvn", "add", "adc", "sub", "sbc", "rsb", + "and", "orr", "eor", "bic", "cmp", "cmn", "tst", + "teq", "lsl", "lsr", "asr", "ror", "neg", "mul", + "b", "cbz", "cbnz", "ldr", "ldrb", "ldrh", "ldrsb", + "ldrsh", "str", "strb", "strh", "ldrex", "ldrexb", "ldrexh", + "strex", "strexb", "strexh", "clz", "rev", "rev16", "rbit", + "uxtb", "uxth", "sxtb", "sxth", "movw", "movt", "mrs", + "msr", "mrc", "mcr", "nop", "yield", "wfe", "wfi", + "sev", "sevl", "push", "pop", "ldm", "ldmia", "ldmib", + "ldmda", "ldmdb", "ldmfd", "ldmfa", "ldmed", "ldmea", "stm", + "stmia", "stmib", "stmda", "stmdb", "stmfd", "stmfa", "stmed", + "stmea"}; std::stable_sort( b.begin(), b.end(), @@ -240,18 +244,6 @@ exprt shift_carry( return if_exprt{is_zero(n), carry, out}; } -/// What the instruction semantics need to know about the statement as a -/// whole -class a32_statet : public asm_semantics_statet -{ -public: - /// Whether the statement may be in divided syntax for a Thumb-1 target - /// (see \ref make_a32_state) - bool maybe_thumb1_divided = true; - /// If not empty, why the statement is not modeled - std::string failure; -}; - /// \return The canonical name of the general-purpose register \p raw, or the /// empty string if \p raw is not one (`pc` is not modeled) std::string canonical_a32_register(const std::string &raw) @@ -285,6 +277,136 @@ std::string canonical_a32_register(const std::string &raw) return {}; } +/// A load or store of multiple registers (ldm, stm, push, pop) +struct a32_multiplet +{ + bool load = false; + /// the first address is the base (increment after), the base plus 4 + /// (increment before), or the base minus 4 times the number of registers + /// plus 4 (decrement after) or without the plus 4 (decrement before) + enum class modet + { + INCREMENT_AFTER, + INCREMENT_BEFORE, + DECREMENT_AFTER, + DECREMENT_BEFORE + } mode = modet::INCREMENT_AFTER; + /// push and pop, which have the stack pointer as implicit base with + /// writeback + bool push_pop = false; +}; + +/// \return Whether \p base is a load or store of multiple registers, which +/// is then described by \p result. +bool multiple(const std::string &base, a32_multiplet &result) +{ + using modet = a32_multiplet::modet; + static const std::map> forms = { + {"ldm", {true, modet::INCREMENT_AFTER}}, + {"ldmia", {true, modet::INCREMENT_AFTER}}, + {"ldmfd", {true, modet::INCREMENT_AFTER}}, + {"ldmib", {true, modet::INCREMENT_BEFORE}}, + {"ldmed", {true, modet::INCREMENT_BEFORE}}, + {"ldmda", {true, modet::DECREMENT_AFTER}}, + {"ldmfa", {true, modet::DECREMENT_AFTER}}, + {"ldmdb", {true, modet::DECREMENT_BEFORE}}, + {"ldmea", {true, modet::DECREMENT_BEFORE}}, + {"stm", {false, modet::INCREMENT_AFTER}}, + {"stmia", {false, modet::INCREMENT_AFTER}}, + {"stmea", {false, modet::INCREMENT_AFTER}}, + {"stmib", {false, modet::INCREMENT_BEFORE}}, + {"stmfa", {false, modet::INCREMENT_BEFORE}}, + {"stmda", {false, modet::DECREMENT_AFTER}}, + {"stmed", {false, modet::DECREMENT_AFTER}}, + {"stmdb", {false, modet::DECREMENT_BEFORE}}, + {"stmfd", {false, modet::DECREMENT_BEFORE}}, + {"pop", {true, modet::INCREMENT_AFTER}}, + {"push", {false, modet::DECREMENT_BEFORE}}}; + auto it = forms.find(base); + if(it == forms.end()) + return false; + result.load = it->second.first; + result.mode = it->second.second; + result.push_pop = base == "push" || base == "pop"; + return true; +} + +/// One register of a register list: its number (-1 for an operand +/// reference, whose register is not known) and its tokens +struct a32_list_entryt +{ + int number; + asm_token_listt tokens; +}; + +/// Parse the register list \p tokens (`{r4, r6-r8}`). +/// \return false if \p tokens is not a register list +bool register_list( + const asm_token_listt &tokens, + std::vector &entries) +{ + if( + tokens.size() < 3 || !tokens.front().is_punctuation('{') || + !tokens.back().is_punctuation('}')) + { + return false; + } + auto number = [](const asm_tokent &token) + { + if(!token.is_identifier()) + return -1; + const std::string canonical = canonical_a32_register(token.text); + return canonical.empty() ? -1 : std::stoi(canonical.substr(1)); + }; + for(std::size_t i = 1; i + 1 < tokens.size(); ++i) + { + const asm_tokent &token = tokens[i]; + if(token.is_punctuation(',')) + continue; + if(token.kind == asm_tokent::kindt::OPERAND) + { + entries.push_back({-1, {token}}); + continue; + } + const int first = number(token); + if(first < 0) + return false; + if(i + 2 < tokens.size() - 1 && tokens[i + 1].is_punctuation('-')) + { + // a range rA-rB + const int last = number(tokens[i + 2]); + if(last < first) + return false; + for(int n = first; n <= last; ++n) + { + entries.push_back( + {n, {{asm_tokent::kindt::IDENTIFIER, "r" + std::to_string(n)}}}); + } + i += 2; + } + else + entries.push_back({first, {token}}); + } + return !entries.empty(); +} + +/// What the instruction semantics need to know about the statement as a +/// whole +class a32_statet : public asm_semantics_statet +{ +public: + /// Whether the statement may be in divided syntax for a Thumb-1 target + /// (see \ref make_a32_state) + bool maybe_thumb1_divided = true; + /// If not empty, why the statement is not modeled + std::string failure; + /// The registers pushed by push (and stmdb sp!) and not yet popped, the top + /// (lowest address) last. The stack memory below the stack pointer belongs + /// to no C object, so a statement whose pushes and pops are balanced in + /// straight-line code (see \ref make_a32_state) can keep them here. + std::vector stack; +}; + /// The fields of the special register \p target of `msr`. /// \param target: the special register, in lower case, e.g. `cpsr_fc` /// \param [out] known: whether \p target is understood, and writing it has @@ -338,6 +460,25 @@ void msr_fields( known = false; } +/// \return Whether \p instruction, a load or store of multiple registers +/// of the form \p form, pushes registers to or pops them from the stack: +/// push, pop, or stmdb/stmfd (ldmia/ldmfd) of sp with writeback. +bool is_stack_operation( + const asm_instructiont &instruction, + const a32_multiplet &form) +{ + if(form.push_pop) + return instruction.operands.size() == 1; + using modet = a32_multiplet::modet; + return instruction.operands.size() == 2 && + instruction.operands[0].size() == 2 && + instruction.operands[0][0].is_identifier() && + canonical_a32_register(instruction.operands[0][0].text) == "r13" && + instruction.operands[0][1].is_punctuation('!') && + (form.load ? form.mode == modet::INCREMENT_AFTER + : form.mode == modet::DECREMENT_BEFORE); +} + /// The statement-wide properties of \p instructions: /// - In divided syntax, which GCC uses for inline assembly in A32 code and /// for Thumb-1 targets, Thumb-1 data-processing instructions without an `s` @@ -359,13 +500,34 @@ void msr_fields( /// exact for a conditional store-exclusive only if it is the only /// store-exclusive of the statement, and never for a conditional /// load-exclusive. +/// - push and pop (and stmdb/ldmia of sp with writeback) are modeled with a +/// stack of their own (\ref a32_statet::stack), which requires the pushes +/// and pops to be balanced, unconditional, and in straight-line code: no +/// label or branch while registers are pushed. std::unique_ptr make_a32_state(const std::vector &instructions) { auto state = std::make_unique(); static const std::set not_thumb1 = { - "teq", "clz", "rbit", "mrc", "mcr"}; + "teq", + "clz", + "rbit", + "mrc", + "mcr", + // Thumb-1 has only the increment-after forms of ldm and stm + "ldmib", + "ldmed", + "ldmda", + "ldmfa", + "ldmdb", + "ldmea", + "stmib", + "stmfa", + "stmda", + "stmed", + "stmdb", + "stmfd"}; bool unified_at_start = false, before_first_instruction = true; bool divided = false, changes_mode = false, names_banked = false; @@ -375,10 +537,15 @@ make_a32_state(const std::vector &instructions) bool label_before_change = false; bool conditional_load_exclusive = false, conditional_store_exclusive = false; std::size_t store_exclusives = 0; + // the number of registers pushed + std::size_t depth = 0; + std::string stack_failure; for(const auto &instruction : instructions) { if(!instruction.labels.empty() && !changes_mode) label_before_change = true; + if(depth != 0 && !instruction.labels.empty()) + stack_failure = "label while registers are pushed"; const std::string &raw = instruction.mnemonic; if(raw == ".syntax") @@ -445,6 +612,51 @@ make_a32_state(const std::vector &instructions) if(!is_decoded) continue; + + if( + depth != 0 && + (decoded.base == "b" || decoded.base == "cbz" || decoded.base == "cbnz")) + { + stack_failure = "branch while registers are pushed"; + } + a32_multiplet form; + const bool stack_operation = + multiple(decoded.base, form) && is_stack_operation(instruction, form); + if(depth != 0 && !stack_operation) + { + // push and pop do not change the stack pointer in the model + for(const auto &operand : instruction.operands) + { + for(const auto &token : operand) + { + if( + token.is_identifier() && + canonical_a32_register(token.text) == "r13") + { + stack_failure = "sp used while registers are pushed"; + } + } + } + } + if(stack_operation) + { + std::vector entries; + if( + decoded.condition != "al" || + !register_list(instruction.operands.back(), entries)) + { + stack_failure = + "push or pop that is conditional or of registers that are not " + "modeled (such as pc)"; + } + else if(!form.load) + depth += entries.size(); + else if(entries.size() > depth) + stack_failure = "pop of registers that were not pushed"; + else + depth -= entries.size(); + } + if( not_thumb1.count(decoded.base) != 0 || (decoded.condition != "al" && decoded.base != "b") || @@ -498,6 +710,10 @@ make_a32_state(const std::vector &instructions) "conditional load-exclusive, or conditional store-exclusive and " "another store-exclusive"; } + else if(depth != 0) + state->failure = "registers pushed and not popped"; + else if(!stack_failure.empty()) + state->failure = stack_failure; return state; } @@ -636,6 +852,27 @@ class asm_arm_semanticst : public asm_semanticst const a32_mnemonict &decoded, std::vector &ops, asm_lowering_contextt &ctx) const; + + /// Parse the register list \p tokens into \p registers, in ascending + /// order of register numbers (which is the order in memory). + /// \return false if the list is not modeled + bool parse_register_list( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + std::vector ®isters, + std::vector &canonical) const; + + bool lower_multiple( + const a32_multiplet &form, + const asm_instructiont &instruction, + const a32_statet &state, + asm_lowering_contextt &ctx) const; + + bool lower_stack( + const a32_multiplet &form, + const asm_instructiont &instruction, + a32_statet &state, + asm_lowering_contextt &ctx) const; }; bool asm_arm_semanticst::parse_operand( @@ -850,8 +1087,7 @@ bool asm_arm_semanticst::lower( const asm_instructiont &instruction, asm_lowering_contextt &ctx) const { - const auto *state = - dynamic_cast(ctx.semantics_state.get()); + auto *state = dynamic_cast(ctx.semantics_state.get()); INVARIANT(state != nullptr, "the state is created by make_state"); if(!state->failure.empty()) return ctx.fail(state->failure); @@ -935,6 +1171,40 @@ bool asm_arm_semanticst::lower( target, decoded.base == "cbz" ? zero : exprt{not_exprt{zero}}); } + // The compiler may address a memory operand relative to sp, which push and + // pop do not change in the model. + if(!state->stack.empty()) + { + for(const auto &operand : instruction.operands) + { + for(const auto &token : operand) + { + if( + token.kind == asm_tokent::kindt::OPERAND && + ctx.operands.operands.at(token.index).kind == + asm_operandt::kindt::MEMORY) + { + return ctx.fail("memory operand used while registers are pushed"); + } + } + } + } + + a32_multiplet form; + if(multiple(decoded.base, form)) + { + if(is_stack_operation(instruction, form)) + return lower_stack(form, instruction, *state, ctx); + if(decoded.condition == "al") + return lower_multiple(form, instruction, *state, ctx); + const auto skip = + ctx.begin_conditional(asm_arm::condition(decoded.condition, ctx)); + if(!lower_multiple(form, instruction, *state, ctx)) + return false; + ctx.end_conditional(skip); + return true; + } + std::vector ops; for(const auto &tokens : instruction.operands) { @@ -1472,6 +1742,190 @@ bool asm_arm_semanticst::lower_system( return ctx.fail("unsupported coprocessor operation"); } + +bool asm_arm_semanticst::parse_register_list( + const asm_token_listt &tokens, + asm_lowering_contextt &ctx, + std::vector ®isters, + std::vector &canonical) const +{ + std::vector entries; + if(!register_list(tokens, entries)) + return ctx.fail("unsupported register list"); + // The registers are stored in the order of their numbers, which is not + // known for operand references. + if(entries.size() > 1) + { + for(const auto &entry : entries) + { + if(entry.number < 0) + return ctx.fail("operand reference in a register list"); + } + } + std::stable_sort( + entries.begin(), + entries.end(), + [](const a32_list_entryt &a, const a32_list_entryt &b) + { return a.number < b.number; }); + for(std::size_t i = 0; i < entries.size(); ++i) + { + if(i > 0 && entries[i].number == entries[i - 1].number) + return ctx.fail("register listed twice"); + // sp and pc (a load of which is a branch) are not modeled + if(entries[i].number == 13) + return ctx.fail("sp in a register list"); + a32_operandt reg; + if( + !parse_operand(entries[i].tokens, ctx, reg) || + reg.kind != a32_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported register in a register list"); + } + registers.push_back(reg); + canonical.push_back( + entries[i].number < 0 ? std::string{} + : "r" + std::to_string(entries[i].number)); + } + return true; +} + +bool asm_arm_semanticst::lower_multiple( + const a32_multiplet &form, + const asm_instructiont &instruction, + const a32_statet &state, + asm_lowering_contextt &ctx) const +{ + // Rn[!], {registers} + if(form.push_pop || instruction.operands.size() != 2) + return ctx.fail("unsupported operands of " + instruction.mnemonic); + asm_token_listt base_tokens = instruction.operands[0]; + const bool writeback = + !base_tokens.empty() && base_tokens.back().is_punctuation('!'); + if(writeback) + base_tokens.pop_back(); + // In divided syntax for Thumb-1, ldmia and stmia without ! are assembled + // with writeback (with a warning). + else if(state.maybe_thumb1_divided) + return ctx.fail("ldm or stm without writeback, which may be Thumb-1"); + a32_operandt base; + if( + !parse_operand(base_tokens, ctx, base) || + base.kind != a32_operandt::kindt::REGISTER) + { + return ctx.fail("unsupported base register"); + } + + std::vector registers; + std::vector canonical; + if(!parse_register_list(instruction.operands[1], ctx, registers, canonical)) + return false; + const std::size_t n = registers.size(); + bool base_listed = false; + for(const auto ® : registers) + base_listed = base_listed || reg.storage == base.storage; + // unpredictable, or (for stores) storing an unknown value + if(writeback && base_listed) + return ctx.fail("base register in the list with writeback"); + + using modet = a32_multiplet::modet; + const symbol_exprt address = ctx.temporary(bv(32), "base"); + ctx.assign(address, read(ctx, base, 32)); + long long first = 0; + switch(form.mode) + { + case modet::INCREMENT_AFTER: + first = 0; + break; + case modet::INCREMENT_BEFORE: + first = 4; + break; + case modet::DECREMENT_AFTER: + first = 4 - 4 * static_cast(n); + break; + case modet::DECREMENT_BEFORE: + first = -4 * static_cast(n); + break; + } + auto element = [&](std::size_t i) + { + a32_operandt memory; + memory.kind = a32_operandt::kindt::MEMORY; + memory.address = typecast_exprt{ + resize( + plus_exprt{ + address, constant(first + 4 * static_cast(i), 32)}, + config.ansi_c.pointer_width), + pointer_type(char_type())}; + return memory; + }; + + // all values are read before any register or memory is written + std::vector values; + for(std::size_t i = 0; i < n; ++i) + { + const exprt value = + form.load ? read(ctx, element(i), 32) : read(ctx, registers[i], 32); + values.push_back(ctx.temporary(bv(32), "value")); + ctx.assign(values.back(), value); + } + for(std::size_t i = 0; i < n; ++i) + { + if(!write(ctx, form.load ? registers[i] : element(i), 32, values[i])) + return false; + } + if(writeback) + { + const long long delta = (form.mode == modet::INCREMENT_AFTER || + form.mode == modet::INCREMENT_BEFORE) + ? 4 * static_cast(n) + : -4 * static_cast(n); + return write(ctx, base, 32, plus_exprt{address, constant(delta, 32)}); + } + return true; +} + +bool asm_arm_semanticst::lower_stack( + const a32_multiplet &form, + const asm_instructiont &instruction, + a32_statet &state, + asm_lowering_contextt &ctx) const +{ + // The pushes and pops are balanced and in straight-line code + // (make_a32_state), so that the stack memory they use is the statement's + // own, below the stack pointer, where no C object is. + if(ctx.exclusive_open()) + return ctx.fail("memory access between load-exclusive and store-exclusive"); + std::vector registers; + std::vector canonical; + if(!parse_register_list( + instruction.operands.back(), ctx, registers, canonical)) + { + return false; + } + + if(!form.load) + { + // the lowest register ends up at the lowest address, the top + for(std::size_t i = registers.size(); i-- > 0;) + { + const symbol_exprt slot = ctx.temporary(bv(32), "stack"); + ctx.assign(slot, read(ctx, registers[i], 32)); + state.stack.push_back(slot); + } + return true; + } + + if(registers.size() > state.stack.size()) + return ctx.fail("pop of registers that were not pushed"); + for(std::size_t i = 0; i < registers.size(); ++i) + { + const symbol_exprt slot = state.stack.back(); + state.stack.pop_back(); + if(!write(ctx, registers[i], 32, slot)) + return false; + } + return true; +} } // namespace std::unique_ptr make_asm_arm_semantics() diff --git a/src/assembler/asm_template.cpp b/src/assembler/asm_template.cpp index 97523a637681..2cb66ecde5c4 100644 --- a/src/assembler/asm_template.cpp +++ b/src/assembler/asm_template.cpp @@ -387,16 +387,25 @@ bool split_asm_template( return false; } - // operands, split at top-level commas + // operands, split at top-level commas (not those in register lists + // such as ARM's {r4, r5}) int depth = 0; asm_token_listt current; for(; pos < tokens.size(); ++pos) { const auto &token = tokens[pos]; - if(token.is_punctuation('(') || token.is_punctuation('[')) + if( + token.is_punctuation('(') || token.is_punctuation('[') || + token.is_punctuation('{')) + { ++depth; - else if(token.is_punctuation(')') || token.is_punctuation(']')) + } + else if( + token.is_punctuation(')') || token.is_punctuation(']') || + token.is_punctuation('}')) + { --depth; + } if(depth == 0 && token.is_punctuation(',')) { From d49f879399727041f47684bc210a9a72df16c53a Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:39:58 +0000 Subject: [PATCH 091/100] asm_differential: observe the base register of the ldp base case The case "aarch64 ldp into the base register" runs ldp %0, %1, [%0] with p as the base and first destination, but p was not copied back to io, so the value loaded into the base register was not checked: replacing the statement by "ldr %1, [%0, #8]", which leaves p unchanged, still verified. Copy p to a new io slot a in the case's epilogue. asm_aarch64 is regenerated (the case's vectors change, as it has one more slot); with the replaced statement, the three assertions of the case now fail. Co-authored-by: Kiro --- regression/cbmc/asm_aarch64/main.c | 34 +++++++++++++------ .../asm_differential_cases.py | 4 ++- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/regression/cbmc/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c index 348fb948d8c5..dc27639aa6b1 100644 --- a/regression/cbmc/asm_aarch64/main.c +++ b/regression/cbmc/asm_aarch64/main.c @@ -259,11 +259,14 @@ void asm_case_16(unsigned long long *io) m[0] = (unsigned long)io[0]; m[1] = (unsigned long)io[1]; unsigned long b = (unsigned long)io[2]; + unsigned long a = (unsigned long)io[3]; unsigned long *p = m; __asm__ __volatile__("ldp %0, %1, [%0]" : "+r"(p), "=r"(b) : : "memory"); + a = (unsigned long)p; io[0] = (unsigned long long)m[0]; io[1] = (unsigned long long)m[1]; io[2] = (unsigned long long)b; + io[3] = (unsigned long long)a; } int main(void) @@ -728,30 +731,39 @@ int main(void) "aarch64 ldpsw sign-extends two words, vector 2"); } { - unsigned long long io[3] = { - 0x8bb0203c63f4822eULL, 0x2bc27e528f6dfd28ULL, 0x105c864ba75fa96aULL}; + unsigned long long io[4] = { + 0x8bb0203c63f4822eULL, + 0x2bc27e528f6dfd28ULL, + 0x105c864ba75fa96aULL, + 0x8f43bdf7e2b5b16ULL}; asm_case_16(io); __CPROVER_assert( io[0] == 0x8bb0203c63f4822eULL && io[1] == 0x2bc27e528f6dfd28ULL && - io[2] == 0x2bc27e528f6dfd28ULL, + io[2] == 0x2bc27e528f6dfd28ULL && io[3] == 0x8bb0203c63f4822eULL, "aarch64 ldp into the base register, vector 0"); } { - unsigned long long io[3] = { - 0x8f43bdf7e2b5b16ULL, 0xc301696ae878eea2ULL, 0x653e09f78221d081ULL}; + unsigned long long io[4] = { + 0xc301696ae878eea2ULL, + 0x653e09f78221d081ULL, + 0x7fd174cb93801745ULL, + 0x7fffffffffffffffULL}; asm_case_16(io); __CPROVER_assert( - io[0] == 0x8f43bdf7e2b5b16ULL && io[1] == 0xc301696ae878eea2ULL && - io[2] == 0xc301696ae878eea2ULL, + io[0] == 0xc301696ae878eea2ULL && io[1] == 0x653e09f78221d081ULL && + io[2] == 0x653e09f78221d081ULL && io[3] == 0xc301696ae878eea2ULL, "aarch64 ldp into the base register, vector 1"); } { - unsigned long long io[3] = { - 0x7fd174cb93801745ULL, 0x7fffffffffffffffULL, 0xffULL}; + unsigned long long io[4] = { + 0xffULL, + 0xd896febde135c547ULL, + 0x3dc4f8714ad7d0a4ULL, + 0x478f66bdd008ceb8ULL}; asm_case_16(io); __CPROVER_assert( - io[0] == 0x7fd174cb93801745ULL && io[1] == 0x7fffffffffffffffULL && - io[2] == 0x7fffffffffffffffULL, + io[0] == 0xffULL && io[1] == 0xd896febde135c547ULL && + io[2] == 0xd896febde135c547ULL && io[3] == 0xffULL, "aarch64 ldp into the base register, vector 2"); } // the only assertion that fails: the end of main is reachable diff --git a/scripts/asm_differential/asm_differential_cases.py b/scripts/asm_differential/asm_differential_cases.py index 525d17d505d6..f030e3dced12 100644 --- a/scripts/asm_differential/asm_differential_cases.py +++ b/scripts/asm_differential/asm_differential_cases.py @@ -174,7 +174,9 @@ class Case: Case('aarch64 ldp into the base register', '__asm__ __volatile__("ldp %0, %1, [%0]" : "+r"(p), "=r"(b) : : ' '"memory");', - [(U64, 'm', 2), (U64, 'b', None)], prologue='unsigned long *p = m;'), + [(U64, 'm', 2), (U64, 'b', None), (U64, 'a', None)], + prologue='unsigned long *p = m;', + epilogue='a = (unsigned long)p;'), ] # cas needs its compare value to sometimes match memory; supply fixed vectors From ba1e4248864b0ac7ef03bd9d0125fa2b4e1a3d44 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:46:21 +0000 Subject: [PATCH 092/100] Inline assembly: regression test of AArch64 ldp, stp, ldnp, and stnp Only the interpreted forms of ldp and stp were covered, by cases of the differential harness; ldnp and stnp, and the forms that make a statement uninterpreted (writeback, SIMD&FP registers, and ldp of the same register twice), were not covered at all. Add asm_aarch64_pairs: interpreted() checks ldp, ldpsw, stp, ldnp, and stnp, with the base register among the registers, w registers, xzr, and a memory operand, and CBMC proves all its assertions. approximated() checks pre-index and post-index writeback and a pair of d registers, whose assertions CBMC fails, and not_executed() has ldp of the same register twice, which assemblers reject. The test pins the reason of each approximation. All assertions hold under qemu-aarch64 (Clang, -O0 to -O2). With the binaries of the layer below, which do not interpret pairs, the assertions of interpreted() fail. Co-authored-by: Kiro --- regression/cbmc/asm_aarch64_pairs/main.c | 154 ++++++++++++++++++++ regression/cbmc/asm_aarch64_pairs/test.desc | 34 +++++ 2 files changed, 188 insertions(+) create mode 100644 regression/cbmc/asm_aarch64_pairs/main.c create mode 100644 regression/cbmc/asm_aarch64_pairs/test.desc diff --git a/regression/cbmc/asm_aarch64_pairs/main.c b/regression/cbmc/asm_aarch64_pairs/main.c new file mode 100644 index 000000000000..e2fe409563cf --- /dev/null +++ b/regression/cbmc/asm_aarch64_pairs/main.c @@ -0,0 +1,154 @@ +// AArch64 loads and stores of register pairs. All assertions hold on hardware +// (qemu-aarch64, for code compiled by Clang). CBMC proves those in +// interpreted(), and fails those in approximated(), whose statements it does +// not interpret. + +#include + +void interpreted(void) +{ + // the base register is the first destination + { + uint64_t m[4] = { + 0x1111111111111111ull, + 0x2222222222222222ull, + 0x3333333333333333ull, + 0x4444444444444444ull}; + uint64_t *p = m; + uint64_t b; + __asm__ volatile("ldp %0, %1, [%0, #16]" : "+r"(p), "=r"(b) : : "memory"); + __CPROVER_assert( + (uint64_t)p == 0x3333333333333333ull && b == 0x4444444444444444ull, + "ldp into the first base register"); + } + + // the base register is the second destination + { + uint64_t m[2] = {5, 6}; + uint64_t *p = m; + uint64_t a; + __asm__ volatile("ldp %0, %1, [%1]" : "=&r"(a), "+r"(p) : : "memory"); + __CPROVER_assert(a == 5 && (uint64_t)p == 6, "ldp into the second base"); + } + + // w registers are zero-extended into the x registers + { + uint32_t m[2] = {0x80000001u, 0xfffffffeu}; + uint64_t a = ~0ull, b = ~0ull; + __asm__ volatile("ldp %w0, %w1, [%2]" + : "+r"(a), "+r"(b) + : "r"(m) + : "memory"); + __CPROVER_assert(a == 0x80000001ull && b == 0xfffffffeull, "ldp of words"); + } + + // ldpsw sign-extends, with a negative offset + { + uint32_t m[3] = {0x80000001u, 0x7fffffffu, 0}; + uint64_t a, b; + __asm__ volatile("ldpsw %0, %1, [%2, #-8]" + : "=r"(a), "=r"(b) + : "r"(m + 2) + : "memory"); + __CPROVER_assert(a == 0xffffffff80000001ull && b == 0x7fffffffull, "ldpsw"); + } + + // stp of w registers writes four bytes each + { + uint32_t m[3] = {1, 2, 3}; + uint64_t a = 0xaaaaaaaa11111111ull, b = 0xbbbbbbbb22222222ull; + __asm__ volatile("stp %w1, %w2, [%0]" + : + : "r"(m), "r"(a), "r"(b) + : "memory"); + __CPROVER_assert( + m[0] == 0x11111111u && m[1] == 0x22222222u && m[2] == 3, "stp of words"); + } + + // stp of xzr + { + uint64_t m[2] = {7, 8}; + __asm__ volatile("stp xzr, %1, [%0]" : : "r"(m), "r"(9ull) : "memory"); + __CPROVER_assert(m[0] == 0 && m[1] == 9, "stp of xzr"); + } + + // stp of the base register + { + uint64_t m[2] = {0, 0}; + __asm__ volatile("stp %0, %0, [%0]" : : "r"(m) : "memory"); + __CPROVER_assert( + m[0] == (uint64_t)m && m[1] == (uint64_t)m, "stp of the base register"); + } + + // ldnp and stnp + { + uint64_t s[2] = {10, 20}, d[2] = {0, 0}; + uint64_t a, b; + __asm__ volatile("ldnp %0, %1, [%2]\n stnp %1, %0, [%3]" + : "=&r"(a), "=&r"(b) + : "r"(s), "r"(d) + : "memory"); + __CPROVER_assert( + a == 10 && b == 20 && d[0] == 20 && d[1] == 10, "ldnp and stnp"); + } + + // a memory operand + { + uint64_t m[2] = {11, 12}; + uint64_t a, b; + __asm__ volatile("ldp %0, %1, %2" : "=r"(a), "=r"(b) : "Q"(m) : "memory"); + __CPROVER_assert(a == 11 && b == 12, "ldp of a memory operand"); + } +} + +void approximated(void) +{ + // pre-index with writeback + { + uint64_t m[4] = {1, 2, 3, 4}; + uint64_t *p = m; + uint64_t a, b; + __asm__ volatile("ldp %1, %2, [%0, #16]!" + : "+r"(p), "=r"(a), "=r"(b) + : + : "memory"); + __CPROVER_assert(p == m + 2 && a == 3 && b == 4, "ldp with pre-index"); + } + + // post-index with writeback + { + uint64_t m[2] = {0, 0}; + uint64_t *p = m; + __asm__ volatile("stp %1, %2, [%0], #16" + : "+r"(p) + : "r"(7ull), "r"(8ull) + : "memory"); + __CPROVER_assert(p == m + 2 && m[0] == 7 && m[1] == 8, "stp post-index"); + } + + // a pair of SIMD&FP registers + { + uint64_t m[2] = {13, 14}, d[2] = {0, 0}; + __asm__ volatile("ldp d0, d1, [%0]\n stp d1, d0, [%1]" + : + : "r"(m), "r"(d) + : "d0", "d1", "memory"); + __CPROVER_assert(d[0] == 14 && d[1] == 13, "ldp of d registers"); + } +} + +// Statements that are not executed, as assemblers reject them. +void not_executed(void) +{ + uint64_t m[2] = {0, 0}; + uint64_t a; + __asm__ volatile("ldp %0, %0, [%1]" : "=r"(a) : "r"(m) : "memory"); + __asm__ volatile("ldp x4, x4, [%0]" : : "r"(m) : "x4", "memory"); +} + +int main(void) +{ + interpreted(); + approximated(); + return 0; +} diff --git a/regression/cbmc/asm_aarch64_pairs/test.desc b/regression/cbmc/asm_aarch64_pairs/test.desc new file mode 100644 index 000000000000..310fe050e09a --- /dev/null +++ b/regression/cbmc/asm_aarch64_pairs/test.desc @@ -0,0 +1,34 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[interpreted\.assertion\.1\] line 20 ldp into the first base register: SUCCESS$ +^\[interpreted\.assertion\.2\] line 31 ldp into the second base: SUCCESS$ +^\[interpreted\.assertion\.3\] line 42 ldp of words: SUCCESS$ +^\[interpreted\.assertion\.4\] line 53 ldpsw: SUCCESS$ +^\[interpreted\.assertion\.5\] line 64 stp of words: SUCCESS$ +^\[interpreted\.assertion\.6\] line 72 stp of xzr: SUCCESS$ +^\[interpreted\.assertion\.7\] line 79 stp of the base register: SUCCESS$ +^\[interpreted\.assertion\.8\] line 91 ldnp and stnp: SUCCESS$ +^\[interpreted\.assertion\.9\] line 100 ldp of a memory operand: SUCCESS$ +^\[approximated\.assertion\.1\] line 115 ldp with pre-index: FAILURE$ +^\[approximated\.assertion\.2\] line 126 stp post-index: FAILURE$ +^\[approximated\.assertion\.3\] line 136 ldp of d registers: FAILURE$ +^\*\* 3 of \d+ failed +approximating inline assembly statement at .* line 111 function approximated: unsupported addressing mode \(writeback\?\) in +approximating inline assembly statement at .* line 122 function approximated: unsupported operands of stp in +approximating inline assembly statement at .* line 132 function approximated: unsupported operands of ldp in +approximating inline assembly statement at .* line 145 function not_executed: ldp of the same register twice in 'ldp %0, %0, +approximating inline assembly statement at .* line 146 function not_executed: ldp of the same register twice in 'ldp x4, x4, +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function interpreted +-- +The assertions hold on hardware: the results were validated with qemu-aarch64, +for code compiled by Clang (without not_executed(), which assemblers reject as +ldp of the same register twice is constrained unpredictable). CBMC interprets +the statements of interpreted() and proves its assertions. It does not +interpret those of approximated() and not_executed(), for the reasons that the +approximation messages give, so it fails the assertions of approximated(). From 61eb30896b4cbffce4ce206daf2a147796d8115c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:46:21 +0000 Subject: [PATCH 093/100] Inline assembly: regression test of AArch32 ldm, stm, push, and pop The checks that make a statement with ldm, stm, push, or pop uninterpreted had no regression test except for three of the stack checks (in asm_arm_corner_cases), and stmib, stmda, and ldmdb were not covered. Add asm_arm_multiple: interpreted() checks the four address modes of ldm (with writeback) and stm (without), the base register in the list, push and pop with ranges and the stack aliases, and conditional ldm, and CBMC proves all its assertions. approximated() checks sp or a memory operand used while registers are pushed, the base register in the list with writeback, ldmia without ! in divided syntax (which may be Thumb-1), an operand reference with another register in a list, a register listed twice, and sp in a list, whose assertions CBMC fails. not_executed() has a pop of registers that were not pushed and a branch while registers are pushed. The test pins the reason of each approximation. All assertions hold under qemu-arm for A32 code compiled by GCC and Clang at -O1 and above. With the binaries of the layer below, which do not interpret these instructions, the assertions of interpreted() fail. Co-authored-by: Kiro --- regression/cbmc/asm_arm_multiple/main.c | 226 +++++++++++++++++++++ regression/cbmc/asm_arm_multiple/test.desc | 43 ++++ 2 files changed, 269 insertions(+) create mode 100644 regression/cbmc/asm_arm_multiple/main.c create mode 100644 regression/cbmc/asm_arm_multiple/test.desc diff --git a/regression/cbmc/asm_arm_multiple/main.c b/regression/cbmc/asm_arm_multiple/main.c new file mode 100644 index 000000000000..9f3d456f0ee2 --- /dev/null +++ b/regression/cbmc/asm_arm_multiple/main.c @@ -0,0 +1,226 @@ +// AArch32 (A32) loads and stores of multiple registers, and push and pop. +// All assertions hold on hardware (qemu-arm, for A32 code compiled by GCC and +// Clang). CBMC proves those in interpreted(), and fails those in +// approximated(), whose statements it does not interpret. + +#include + +uint32_t g[2] = {1, 2}; + +void interpreted(void) +{ + // the four address modes of ldm, with writeback + { + uint32_t m[8] = {10, 11, 12, 13, 14, 15, 16, 17}; + uint32_t *p = m + 4, *q = m + 4, *r = m + 4, *s = m + 4; + uint32_t a, b, c, d, e, f, x, y; + __asm__ volatile( + "ldmia %[p]!, {r4, r5}\n mov %[a], r4\n mov %[b], r5\n" + " ldmib %[q]!, {r4, r5}\n mov %[c], r4\n mov %[d], r5\n" + " ldmda %[r]!, {r4, r5}\n mov %[e], r4\n mov %[f], r5\n" + " ldmdb %[s]!, {r4, r5}\n mov %[x], r4\n mov %[y], r5\n" + : [p] "+r"(p), + [q] "+r"(q), + [r] "+r"(r), + [s] "+r"(s), + [a] "=&r"(a), + [b] "=&r"(b), + [c] "=&r"(c), + [d] "=&r"(d), + [e] "=&r"(e), + [f] "=&r"(f), + [x] "=&r"(x), + [y] "=&r"(y) + : + : "r4", "r5", "memory"); + __CPROVER_assert(a == 14 && b == 15 && p == m + 6, "ldmia"); + __CPROVER_assert(c == 15 && d == 16 && q == m + 6, "ldmib"); + __CPROVER_assert(e == 13 && f == 14 && r == m + 2, "ldmda"); + __CPROVER_assert(x == 12 && y == 13 && s == m + 2, "ldmdb"); + } + + // the four address modes of stm, without writeback + { + uint32_t m[8] = {0}; + __asm__ volatile( + ".syntax unified\n" + " mov r4, #1\n mov r5, #2\n mov r6, #3\n" + " stmia %0, {r4, r5}\n" + " stmib %1, {r5, r6}\n" + " stmda %2, {r4, r6}\n" + " stmdb %3, {r4-r6}\n" + : + : "r"(m), "r"(m + 2), "r"(m + 7), "r"(m + 7) + : "r4", "r5", "r6", "memory"); + // stmia m: m[0..1] = 1, 2; stmib m + 2: m[3..4] = 2, 3; + // stmda m + 7: m[6..7] = 1, 3; stmdb m + 7: m[4..6] = 1, 2, 3 + __CPROVER_assert( + m[0] == 1 && m[1] == 2 && m[2] == 0 && m[3] == 2 && m[4] == 1 && + m[5] == 2 && m[6] == 3 && m[7] == 3, + "stmia stmib stmda stmdb"); + } + + // the base register in the list, without writeback + { + uint32_t m[2] = {21, 22}; + uint32_t a, b; + __asm__ volatile( + ".syntax unified\n" + " mov r4, %2\n ldm r4, {r4, r5}\n mov %0, r4\n mov %1, r5" + : "=&r"(a), "=&r"(b) + : "r"(m) + : "r4", "r5", "memory"); + __CPROVER_assert(a == 21 && b == 22, "ldm into the base register"); + } + { + uint32_t m[2] = {0, 0}; + __asm__ volatile( + ".syntax unified\n" + " mov r4, %0\n mov r5, #7\n stm r4, {r4, r5}" + : + : "r"(m) + : "r4", "r5", "memory"); + __CPROVER_assert( + m[0] == (uint32_t)m && m[1] == 7, "stm of the base register"); + } + + // push and pop, register ranges, and the stack aliases + { + uint32_t a, b, c, d; + __asm__ volatile( + "mov r4, #1\n mov r5, #2\n mov r6, #3\n mov r7, #4\n" + " push {r4-r7}\n" + " pop {r8}\n" + " ldmia sp!, {r9, r10}\n" + " ldmfd sp!, {r11}\n" + " mov %0, r8\n mov %1, r9\n mov %2, r10\n mov %3, r11\n" + : "=r"(a), "=r"(b), "=r"(c), "=r"(d) + : + : "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "memory"); + __CPROVER_assert(a == 1 && b == 2 && c == 3 && d == 4, "push and pop"); + } + { + uint32_t a, b; + __asm__ volatile( + "mov r4, #5\n mov r5, #6\n" + " stmdb sp!, {r4, r5}\n stmfd sp!, {r4}\n" + " pop {r5, r6}\n pop {r4}\n" + " mov %0, r5\n sub %1, r6, r4\n" + : "=r"(a), "=r"(b) + : + : "r4", "r5", "r6", "memory"); + __CPROVER_assert(a == 5 && b == (uint32_t)(5 - 6), "stmdb and stmfd"); + } + + // conditional ldm with writeback, not executed and executed + { + uint32_t m[2] = {31, 32}; + uint32_t *p = m, *q = m; + uint32_t a = 0, b = 0; + __asm__ volatile( + ".syntax unified\n" + " mov r4, #0\n mov r5, #0\n" + " cmp %4, #0\n" + " ldmne %0!, {r4}\n" + " ldmeq %1!, {r5}\n" + " mov %2, r4\n mov %3, r5" + : "+r"(p), "+r"(q), "=r"(a), "=r"(b) + : "r"(0) + : "r4", "r5", "cc", "memory"); + __CPROVER_assert( + p == m && a == 0 && q == m + 1 && b == 31, "conditional ldm"); + } +} + +void approximated(void) +{ + // sp used while registers are pushed: reads the pushed value + { + uint32_t a; + __asm__ volatile("mov r4, #9\n push {r4}\n ldr %0, [sp]\n pop {r4}" + : "=r"(a) + : + : "r4", "memory"); + __CPROVER_assert(a == 9, "sp while pushed"); + } + + // a memory operand while registers are pushed, which the compiler may + // address relative to sp (it does not for g) + { + __asm__ volatile( + "push {r4}\n ldr r4, %0\n add r4, r4, #1\n str r4, %0\n" + " pop {r4}" + : "+m"(g[0]) + : + : "r4", "memory"); + __CPROVER_assert(g[0] == 2, "memory operand while pushed"); + } + + // the base register in the list, with writeback + { + uint32_t m[2] = {0, 0}; + uint32_t *p; + __asm__ volatile( + ".syntax unified\n mov r5, #3\n mov r4, %1\n" + " stm r4!, {r4, r5}\n mov %0, r4" + : "=r"(p) + : "r"(m) + : "r4", "r5", "memory"); + __CPROVER_assert( + m[1] == 3 && p == m + 2, "stm with writeback of a listed base"); + } + + // in divided syntax for Thumb-1, ldmia without ! writes back + { + uint32_t m[2] = {41, 42}; + uint32_t a; + __asm__ volatile("ldmia %1, {%0}" : "=r"(a) : "r"(m) : "memory"); + __CPROVER_assert(a == 41, "ldmia in divided syntax"); + } + + // an operand reference with another register: the order is not known + { + uint32_t m[2] = {0, 0}; + __asm__ volatile(".syntax unified\n mov r5, #2\n stm %0, {%1, r5}" + : + : "r"(m), "r"(1) + : "r5", "memory"); + __CPROVER_assert(m[0] + m[1] == 3, "operand reference in a list"); + } + + // a register listed twice + { + uint32_t m[2] = {51, 52}; + uint32_t a; + __asm__ volatile(".syntax unified\n ldm %1, {r4, r4}\n mov %0, r4" + : "=r"(a) + : "r"(m) + : "r4", "memory"); + __CPROVER_assert(a == 51, "register listed twice"); + } + + // sp in a register list + { + uint32_t m[2] = {0, 0}; + __asm__ volatile(".syntax unified\n mov r4, #4\n stm %0, {r4, sp}" + : + : "r"(m) + : "r4", "memory"); + __CPROVER_assert(m[0] == 4, "sp in a list"); + } +} + +// Statements whose use of the stack is not modeled. They are not executed, +// as they would break the program. +void not_executed(void) +{ + __asm__ volatile("pop {r4}" : : : "r4"); + __asm__ volatile("push {r4}\n b 1f\n pop {r4}\n1:" : : : "r4"); +} + +int main(void) +{ + interpreted(); + approximated(); + return 0; +} diff --git a/regression/cbmc/asm_arm_multiple/test.desc b/regression/cbmc/asm_arm_multiple/test.desc new file mode 100644 index 000000000000..4894a27ab164 --- /dev/null +++ b/regression/cbmc/asm_arm_multiple/test.desc @@ -0,0 +1,43 @@ +CORE gcc-only +main.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[interpreted\.assertion\.1\] line 36 ldmia: SUCCESS$ +^\[interpreted\.assertion\.2\] line 37 ldmib: SUCCESS$ +^\[interpreted\.assertion\.3\] line 38 ldmda: SUCCESS$ +^\[interpreted\.assertion\.4\] line 39 ldmdb: SUCCESS$ +^\[interpreted\.assertion\.5\] line 57 stmia stmib stmda stmdb: SUCCESS$ +^\[interpreted\.assertion\.6\] line 73 ldm into the base register: SUCCESS$ +^\[interpreted\.assertion\.7\] line 83 stm of the base register: SUCCESS$ +^\[interpreted\.assertion\.8\] line 100 push and pop: SUCCESS$ +^\[interpreted\.assertion\.9\] line 112 stmdb and stmfd: SUCCESS$ +^\[interpreted\.assertion\.10\] line 130 conditional ldm: SUCCESS$ +^\[approximated\.assertion\.1\] line 144 sp while pushed: FAILURE$ +^\[approximated\.assertion\.2\] line 156 memory operand while pushed: FAILURE$ +^\[approximated\.assertion\.3\] line 169 stm with writeback of a listed base: FAILURE$ +^\[approximated\.assertion\.4\] line 178 ldmia in divided syntax: FAILURE$ +^\[approximated\.assertion\.5\] line 188 operand reference in a list: FAILURE$ +^\[approximated\.assertion\.6\] line 199 register listed twice: FAILURE$ +^\[approximated\.assertion\.7\] line 209 sp in a list: FAILURE$ +^\*\* 7 of \d+ failed +approximating inline assembly statement at .* line 140 function approximated: sp used while registers are pushed in +approximating inline assembly statement at .* line 150 function approximated: memory operand used while registers are pushed in +approximating inline assembly statement at .* line 163 function approximated: base register in the list with writeback in +approximating inline assembly statement at .* line 177 function approximated: ldm or stm without writeback, which may be Thumb-1 in +approximating inline assembly statement at .* line 184 function approximated: operand reference in a register list in +approximating inline assembly statement at .* line 195 function approximated: register listed twice in +approximating inline assembly statement at .* line 205 function approximated: sp in a register list in +approximating inline assembly statement at .* line 217 function not_executed: pop of registers that were not pushed in +approximating inline assembly statement at .* line 218 function not_executed: branch while registers are pushed in +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly statement at .* function interpreted +-- +All assertions hold on hardware: the results were validated with qemu-arm, for +A32 code compiled by GCC and Clang (at -O1 and above; at -O0, the first +statement of interpreted() needs more registers than are available). CBMC +interprets the statements of interpreted() and proves its assertions. It does +not interpret those of approximated() and not_executed(), for the reasons that +the approximation messages give, so it fails the assertions of approximated(). From 922b3c6b918077dd15513e029ad3d1adbcc2868c Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 21:57:02 +0000 Subject: [PATCH 094/100] AArch32 inline assembly: push and pop with changes of the processor mode push and pop address the stack through sp, which is banked by processor mode, but make_a32_state only refused mode changes in statements that name r8 to r14 or use operands after the change. The model of push and pop keeps the registers on a stack of the statement's own, so a pop after the mode changed restored the pushed value although the hardware reads the stack of the new mode. CBMC thus proved v == 1 after mov r5, %0; mov r4, #1; push {r4}; msr cpsr_c, %1; pop {r4}; str r4, [r5] with %0 the address of v and %1 the FIQ mode (0x11). A statement that may change the processor mode and uses push or pop is now not interpreted. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 15 ++++++------ doc/cprover-manual/modeling-inline-asm.md | 15 ++++++------ regression/cbmc/asm_arm_corner_cases/main.c | 5 ++++ .../cbmc/asm_arm_corner_cases/test.desc | 1 + src/assembler/asm_arm.cpp | 23 ++++++++++++------- 5 files changed, 37 insertions(+), 22 deletions(-) diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index b793e39df331..10390bcb1622 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -177,14 +177,15 @@ so the flags are nondeterministic after `movs` as well. And `msr` of the control field may change the processor mode, which banks r8 to r14. A statement that does so is not interpreted if it names any of these -registers, or if it uses an operand, which the compiler may allocate to one +registers, if it uses `push` or `pop`, which address the stack through the +banked `sp`, or if it uses an operand, which the compiler may allocate to one of them, after the first such `msr`. Operands may be used before it, and as -its source, unless a label precedes it, to which a later branch could -return. The mode itself is not modeled, so that a statement that leaves the -processor in another mode (`msr cpsr_c, #0x1f`, say) is interpreted as if -the mode were unchanged: the C code after it, which uses the banked `sp` and -`lr` of the new mode, and the output operands, which the compiler may read -from banked registers, are modeled as in the original mode. +its source, unless a label precedes it, to which a later branch could return. +The mode itself is not modeled, so that a statement that leaves the processor +in another mode (`msr cpsr_c, #0x1f`, say) is interpreted as if the mode were +unchanged: the C code after it, which uses the banked `sp` and `lr` of the new +mode, and the output operands, which the compiler may read from banked +registers, are modeled as in the original mode. An `it` instruction has no effect: the instructions of the IT block carry their conditions as suffixes, which the assemblers check against it. A conditional store-exclusive may not execute, so it does not clear the diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 1139402cc5f6..b91e077d49be 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -249,14 +249,15 @@ Thumb-2 code as well. A statement that changes the interrupt masks or the processor mode with `msr` is not interpreted if it names any of the registers r8 to r14, which are -banked by mode, or if it uses an operand, which the compiler may allocate to +banked by mode, if it uses `push` or `pop`, which address the stack through +the banked `sp`, or if it uses an operand, which the compiler may allocate to one of these registers, after the first such `msr` (the source of that `msr` -may be an operand). The processor mode itself is not modeled: a statement -that leaves the processor in another mode, such as `msr cpsr_c, #0x1f`, is -interpreted as if the mode were unchanged, although the code after it uses -the banked registers of the new mode (`sp` and `lr`, and r8 to r12 in FIQ -mode), including the registers from which the compiler reads output -operands. Reading or writing `pc` is not modeled. +may be an operand). The processor mode itself is not modeled: a statement that +leaves the processor in another mode, such as `msr cpsr_c, #0x1f`, is +interpreted as if the mode were unchanged, although the code after it uses the +banked registers of the new mode (`sp` and `lr`, and r8 to r12 in FIQ mode), +including the registers from which the compiler reads output operands. Reading +or writing `pc` is not modeled. The registers that `push` saves are kept on a stack of the statement's own: the memory below the stack pointer belongs to no C object. This requires the diff --git a/regression/cbmc/asm_arm_corner_cases/main.c b/regression/cbmc/asm_arm_corner_cases/main.c index 042c934f21d0..d0c71a884a4a 100644 --- a/regression/cbmc/asm_arm_corner_cases/main.c +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -252,4 +252,9 @@ void unbalanced(void) __asm__ volatile("push {r4}"); __asm__ volatile("push {r4}\n1: pop {r4}"); __asm__ volatile("pop {pc}"); + // a change of the processor mode banks sp, which push and pop use + __asm__ volatile("push {r4}\n msr cpsr_c, %0\n pop {r4}" + : + : "r"(0x11) + : "r4"); } diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index 2454896a604c..0e31987c83cb 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -47,6 +47,7 @@ approximating inline assembly statement at .* line 226 function main: conditiona approximating inline assembly statement at .* line 252 function unbalanced: registers pushed and not popped approximating inline assembly statement at .* line 253 function unbalanced: label while registers are pushed approximating inline assembly statement at .* line 254 function unbalanced: push or pop that is conditional or of registers that are not modeled +approximating inline assembly statement at .* line 256 function unbalanced: msr of the processor mode with push or pop, which use the banked sp ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index ae716b8f66a8..89cacb5098bd 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -488,13 +488,13 @@ bool is_stack_operation( /// syntax for Thumb-1 targets, unless the statement selects divided syntax /// explicitly. ARMv8-M Baseline, a Thumb-1 target, has `movw`, `movt`, /// `cbz`, `cbnz`, and the exclusive loads and stores. -/// - `msr` of the control field may change the processor mode, and with it -/// the registers r8 to r14, which is not modeled. Such a statement must -/// not name these registers, and it must not use operands, which the -/// compiler may allocate to them, after the mode may have changed: it may -/// only use them before the first such `msr`, including as its source, and -/// only if no label precedes that `msr`, to which a later branch could -/// return. +/// - `msr` of the control field may change the processor mode, and with it the +/// registers r8 to r14, which is not modeled. Such a statement must not name +/// these registers, nor use push or pop, which address the stack through sp +/// (r13), and it must not use operands, which the compiler may allocate to +/// them, after the mode may have changed: it may only use them before the +/// first such `msr`, including as its source, and only if no label precedes +/// that `msr`, to which a later branch could return. /// - The exclusive access region and the exclusive monitor are tracked while /// lowering (see \ref asm_lowering_contextt::begin_exclusive), which is /// exact for a conditional store-exclusive only if it is the only @@ -537,8 +537,9 @@ make_a32_state(const std::vector &instructions) bool label_before_change = false; bool conditional_load_exclusive = false, conditional_store_exclusive = false; std::size_t store_exclusives = 0; - // the number of registers pushed + // the number of registers pushed, and whether there is a push or pop std::size_t depth = 0; + bool uses_stack = false; std::string stack_failure; for(const auto &instruction : instructions) { @@ -640,6 +641,7 @@ make_a32_state(const std::vector &instructions) } if(stack_operation) { + uses_stack = true; std::vector entries; if( decoded.condition != "al" || @@ -689,6 +691,11 @@ make_a32_state(const std::vector &instructions) "msr of the processor mode with named registers r8 to r14, which may be " "banked"; } + else if(changes_mode && uses_stack) + { + state->failure = + "msr of the processor mode with push or pop, which use the banked sp"; + } else if( changes_mode && (operand_after_change || (label_before_change && operand_before_change))) From 76b8943ca4a95d820dda285294acd0f5331e1463 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 21:57:08 +0000 Subject: [PATCH 095/100] AArch32 inline assembly: push and pop abandon exclusive regions A push or pop between a load-exclusive and a store-exclusive made the statement uninterpreted, whereas the other memory accesses, branches, and labels abandon the exclusive access region. Abandon it at push and pop as well. The test case, a push and pop between ldrex and strex, passes on qemu-arm when built by arm-linux-gnueabihf-gcc for A32 and T32 code. Co-authored-by: Kiro --- regression/cbmc/asm_arm_exclusive_abandoned/main.c | 12 ++++++++++++ .../cbmc/asm_arm_exclusive_abandoned/test.desc | 2 ++ src/assembler/asm_arm.cpp | 6 +++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/regression/cbmc/asm_arm_exclusive_abandoned/main.c b/regression/cbmc/asm_arm_exclusive_abandoned/main.c index b0219b8a29c9..b727388d2057 100644 --- a/regression/cbmc/asm_arm_exclusive_abandoned/main.c +++ b/regression/cbmc/asm_arm_exclusive_abandoned/main.c @@ -56,5 +56,17 @@ int main(void) __CPROVER_assert(status == 1, "store-exclusive fails"); // fails #endif + // a push and a pop between the load-exclusive and the store-exclusive + __asm__ volatile( + "ldrex %0, [%2]\n" + " push {%0}\n" + " pop {%0}\n" + " strex %1, %3, [%2]" + : "=&r"(t), "=&r"(status) + : "r"(&n), "r"(9) + : "memory"); + __CPROVER_assert(t == 7, "pushed and popped"); + __CPROVER_assert((status == 0) == (n == 9), "status matches the push"); + return 0; } diff --git a/regression/cbmc/asm_arm_exclusive_abandoned/test.desc b/regression/cbmc/asm_arm_exclusive_abandoned/test.desc index 54aa844916e1..a75c34d13122 100644 --- a/regression/cbmc/asm_arm_exclusive_abandoned/test.desc +++ b/regression/cbmc/asm_arm_exclusive_abandoned/test.desc @@ -11,6 +11,8 @@ main.c ^\[main\.assertion\.6\] line 53 status matches the store: SUCCESS$ ^\[main\.assertion\.7\] line 55 store-exclusive succeeds: FAILURE$ ^\[main\.assertion\.8\] line 56 store-exclusive fails: FAILURE$ +^\[main\.assertion\.9\] line 68 pushed and popped: SUCCESS$ +^\[main\.assertion\.10\] line 69 status matches the push: SUCCESS$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 89cacb5098bd..fdee298d22e1 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -1899,9 +1899,9 @@ bool asm_arm_semanticst::lower_stack( { // The pushes and pops are balanced and in straight-line code // (make_a32_state), so that the stack memory they use is the statement's - // own, below the stack pointer, where no C object is. - if(ctx.exclusive_open()) - return ctx.fail("memory access between load-exclusive and store-exclusive"); + // own, below the stack pointer, where no C object is. Like any other + // memory access, they abandon an open exclusive access region. + ctx.abandon_exclusive(); std::vector registers; std::vector canonical; if(!parse_register_list( From 2a0729f46df2801760c8d7b422ddfe8a05f53515 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 17 Nov 2026 11:39:37 +0000 Subject: [PATCH 096/100] Inline assembly: replace restartable LL/SC retry loops by their last attempt A store-exclusive succeeds nondeterministically, as the architecture permits spurious failures, so the loop that retries a load-exclusive/ store-exclusive sequence until the store succeeds can retry arbitrarily often. Symbolic execution had to unwind each such loop, typically one per atomic operation in kernel code, and its unwinding assertions failed. When a failed attempt has no effect, the executions that retry reach the same states as the one whose last attempt succeeds. A store-exclusive now records its code and success (asm_lowering_contextt::record_store_exclusive), and the AArch64 and AArch32 semantics lower conditional branches via retry_branch. That replaces a backward branch by the assumption that it is not taken if - the branch is taken only if the store failed: substituting the straight-line code after the store, and the store's own code, into the condition and assuming success simplifies it to false (this covers cbnz of the status, and bne after teq or cmp of the status with 0); and - the code from the label to the branch is restartable: no other labels or branches, no calls, no memory writes other than the store-exclusive's, the symbols it writes conditionally it also writes unconditionally, and it reads none of the symbols it writes before writing them. Otherwise, the branch is lowered as before, which is always sound. A conditional store-exclusive is not recorded, as its status may be unchanged. The ARM regression tests no longer need --unwind. asm_llsc_retry_loops shows the canonical loops without unwinding, and loops that remain loops: one that counts its attempts, one whose branch is taken on success, and one that stores to memory in each attempt. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 9 +- doc/cprover-manual/modeling-inline-asm.md | 22 +- .../asm_aarch64_exclusive/test.desc | 2 +- .../asm_arm_exclusive/test.desc | 2 +- regression/cbmc/asm_aarch64/test.desc | 11 +- .../cbmc/asm_aarch64_corner_cases/test.desc | 2 +- regression/cbmc/asm_arm/test.desc | 11 +- .../cbmc/asm_arm_corner_cases/test.desc | 2 +- regression/cbmc/asm_llsc_retry_loops/arm.c | 51 +++++ regression/cbmc/asm_llsc_retry_loops/arm.desc | 19 ++ regression/cbmc/asm_llsc_retry_loops/main.c | 49 +++++ .../cbmc/asm_llsc_retry_loops/test.desc | 24 +++ src/assembler/asm_aarch64.cpp | 19 +- src/assembler/asm_arm.cpp | 16 +- src/assembler/asm_lowering.cpp | 189 +++++++++++++++++- src/assembler/asm_semantics.h | 37 ++++ 16 files changed, 430 insertions(+), 35 deletions(-) create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm.desc create mode 100644 regression/cbmc/asm_llsc_retry_loops/main.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/test.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 10390bcb1622..216c283734ed 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -156,7 +156,14 @@ statement may succeed if a load-exclusive executed before. After `clrex` or a store-exclusive, a store-exclusive fails, unless a label or a load-exclusive comes in between: the monitor state is decided along the control flow, and a branch to the label may skip the instruction that cleared the monitor -(`asm_lowering_contextt::define_label` forgets that the monitor is cleared). +(`asm_lowering_contextt::define_label` forgets that the monitor is cleared). A +store-exclusive records itself +(`asm_lowering_contextt::record_store_exclusive`), and the semantics lower +conditional branches with `retry_branch`: a backward branch that is taken only +if the recorded store failed (checked by substituting the code after the store +into the condition and simplifying it with the store succeeding), and whose +loop is restartable (`restartable`), becomes the assumption that it is not +taken. AArch32 needs two statement-wide properties (`make_a32_state` in `asm_arm.cpp`). In divided syntax, which GCC uses for inline assembly in A32 diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index b91e077d49be..f1c6b3df8ef7 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -183,13 +183,21 @@ label between the two may bypass the load-exclusive. The store-exclusive succeeds or fails nondeterministically, as the architecture permits spurious failures, and so does a store-exclusive without a preceding load-exclusive in the statement (a load-exclusive may -have executed before). Hence symbolic execution needs an unwinding bound for -the loop that retries the sequence until the store succeeds, and unwinding -assertions for that loop fail. If the retried code has no effect when the -store fails (it only computes registers that the next attempt computes -again), the executions with more retries reach the same states, so that -bounding the loop (with `--unwindset`, without unwinding assertions) does not -miss any state. +have executed before). + +A statement usually retries the sequence until the store succeeds, as in +`1: ldxr x0, [x2]; add x0, x0, #1; stxr w1, x0, [x2]; cbnz w1, 1b`. If a +failed attempt has no effect (the loop writes memory only with the +store-exclusive, does not read a register or flag before writing it, and +writes the same registers and flags in every attempt), the executions that +retry reach the same states as the one whose last attempt succeeds. CBMC then +replaces the branch that retries by the assumption that it is not taken +(which implies that the store succeeded), so that the statement contains no +loop. This requires the branch to be taken +only when the store fails (`cbnz` of the status, or `bne` after `teq` or +`cmp` of the status with 0) and the loop to contain no other label or branch. +Other retry loops remain loops: symbolic execution needs an unwinding bound +for them, and their unwinding assertions fail. A store-exclusive fails if the exclusive monitor is cleared, by `clrex` or by an earlier store-exclusive. CBMC decides the monitor state along the diff --git a/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc b/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc index 3935b28ec264..2f90350b62df 100644 --- a/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc +++ b/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---arch arm64 --unwind 2 --no-unwinding-assertions +--arch arm64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 32 ll/sc increment: SUCCESS$ diff --git a/regression/cbmc-concurrency/asm_arm_exclusive/test.desc b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc index a0ddf6ab0830..45d8d9f06fed 100644 --- a/regression/cbmc-concurrency/asm_arm_exclusive/test.desc +++ b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---arch arm --unwind 2 --no-unwinding-assertions +--arch arm ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 51 ll/sc increment: SUCCESS$ diff --git a/regression/cbmc/asm_aarch64/test.desc b/regression/cbmc/asm_aarch64/test.desc index bdbb07f358a4..2099ab95531b 100644 --- a/regression/cbmc/asm_aarch64/test.desc +++ b/regression/cbmc/asm_aarch64/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---arch arm64 --unwind 2 --no-unwinding-assertions +--arch arm64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ @@ -12,8 +12,7 @@ approximating inline assembly -- The AArch64 inline assembly in main.c is interpreted exactly: if CBMC approximated any statement, the assertions, which check values observed with -an emulator, would fail. A store-exclusive may fail spuriously, so the retry -loops of load-exclusive/store-exclusive sequences are bounded; the executions -that retry more often reach the same states. The assertion at the end of main -is the only one that fails: it shows that the end of main is reachable, so -that the other assertions do not hold vacuously. +an emulator, would fail. The retry loops of load-exclusive/store-exclusive +sequences need no unwinding: their failed attempts have no effect. The +assertion at the end of main is the only one that fails: it shows that the end +of main is reachable, so that the other assertions do not hold vacuously. diff --git a/regression/cbmc/asm_aarch64_corner_cases/test.desc b/regression/cbmc/asm_aarch64_corner_cases/test.desc index 9d7a25ac97b7..a38286953ed4 100644 --- a/regression/cbmc/asm_aarch64_corner_cases/test.desc +++ b/regression/cbmc/asm_aarch64_corner_cases/test.desc @@ -1,6 +1,6 @@ CORE gcc-only main.c ---arch arm64 --unwind 3 --no-unwinding-assertions +--arch arm64 ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 27 msr nzcv clears Z: SUCCESS$ diff --git a/regression/cbmc/asm_arm/test.desc b/regression/cbmc/asm_arm/test.desc index 5515e05aa947..d599a1fea181 100644 --- a/regression/cbmc/asm_arm/test.desc +++ b/regression/cbmc/asm_arm/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c ---arch arm --unwind 2 --no-unwinding-assertions +--arch arm ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ @@ -13,8 +13,7 @@ approximating inline assembly The AArch32 inline assembly in main.c is interpreted exactly: if CBMC approximated any statement, the assertions, which check values observed with an emulator (Unicorn, and qemu-arm for A32 code compiled by GCC and Clang), -would fail. A store-exclusive may fail spuriously, so the retry loops of -load-exclusive/store-exclusive sequences are bounded; the executions that -retry more often reach the same states. The assertion at the end of main is -the only one that fails: it shows that the end of main is reachable, so that -the other assertions do not hold vacuously. +would fail. The retry loops of load-exclusive/store-exclusive sequences need +no unwinding: their failed attempts have no effect. The assertion at the end +of main is the only one that fails: it shows that the end of main is +reachable, so that the other assertions do not hold vacuously. diff --git a/regression/cbmc/asm_arm_corner_cases/test.desc b/regression/cbmc/asm_arm_corner_cases/test.desc index 0e31987c83cb..1c4f4a24b695 100644 --- a/regression/cbmc/asm_arm_corner_cases/test.desc +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -1,6 +1,6 @@ CORE gcc-only no-new-smt main.c ---arch arm --unwind 3 --no-unwinding-assertions +--arch arm ^EXIT=10$ ^SIGNAL=0$ ^\[main\.assertion\.1\] line 31 msr clears Z: SUCCESS$ diff --git a/regression/cbmc/asm_llsc_retry_loops/arm.c b/regression/cbmc/asm_llsc_retry_loops/arm.c new file mode 100644 index 000000000000..33e317f52e98 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm.c @@ -0,0 +1,51 @@ +// Retry loops of load-exclusive/store-exclusive sequences (AArch32) +unsigned x; + +int main(void) +{ + unsigned result, status; + + // with teq and bne, as in the Linux kernel's atomics + x = 40; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, #2\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(result), "=&r"(status) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(result == 42 && x == 42, "teq/bne loop"); + + // with cmp and bne + x = 40; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " orr %0, %0, #1\n" + " strex %1, %0, [%2]\n" + " cmp %1, #0\n" + " bne 1b" + : "=&r"(result), "=&r"(status) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(x == 41, "cmp/bne loop"); + + // a store to memory before the load makes an attempt observable + unsigned stores = 0; + x = 40; + __asm__ volatile( + "1: ldr %0, [%3]\n" + " add %0, %0, #1\n" + " str %0, [%3]\n" + " ldrex %0, [%2]\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(result), "=&r"(status) + : "r"(&x), "r"(&stores) + : "cc", "memory"); + __CPROVER_assert(stores == 1, "store in the loop"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/arm.desc b/regression/cbmc/asm_llsc_retry_loops/arm.desc new file mode 100644 index 000000000000..cd8ae3203866 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm.desc @@ -0,0 +1,19 @@ +CORE gcc-only no-new-smt +arm.c +--arch arm --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 19 teq/bne loop: SUCCESS$ +^\[main\.assertion\.2\] line 32 cmp/bne loop: SUCCESS$ +^\[main\.unwind\.0\] line 37 unwinding assertion loop 0: FAILURE$ +^\[main\.assertion\.3\] line 48 store in the loop: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +^\[main\.unwind\.1\] +-- +The retry loops of load-exclusive/store-exclusive sequences that end with +teq or cmp of the status and bne need no unwinding; a loop whose attempts +store to memory remains a loop. The assertion that fails may be violated on +hardware, where a store-exclusive may fail spuriously. diff --git a/regression/cbmc/asm_llsc_retry_loops/main.c b/regression/cbmc/asm_llsc_retry_loops/main.c new file mode 100644 index 000000000000..f5249858baf1 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/main.c @@ -0,0 +1,49 @@ +// Retry loops of load-exclusive/store-exclusive sequences (AArch64) +unsigned long x; + +int main(void) +{ + unsigned long result, attempts = 0; + unsigned int status; + + // a restartable retry loop: a failed attempt has no effect + x = 40; + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #2\n" + " stxr %w1, %0, [%2]\n" + " cbnz %w1, 1b" + : "=&r"(result), "=&r"(status) + : "r"(&x) + : "memory"); + __CPROVER_assert(result == 42 && x == 42, "restartable loop"); + + // counting the attempts reads a register before writing it + x = 40; + __asm__ volatile( + "1: add %2, %2, #1\n" + " ldxr %0, [%3]\n" + " add %0, %0, #2\n" + " stxr %w1, %0, [%3]\n" + " cbnz %w1, 1b" + : "=&r"(result), "=&r"(status), "+&r"(attempts) + : "r"(&x) + : "memory"); + __CPROVER_assert(x == 42, "counting loop"); + __CPROVER_assert(attempts == 1, "one attempt"); // fails + + // a branch that is taken when the store succeeds is not a retry + x = 40; + attempts = 0; + __asm__ volatile( + "1: add %2, %2, #1\n" + " ldxr %0, [%3]\n" + " stxr %w1, %0, [%3]\n" + " cbz %w1, 1b" + : "=&r"(result), "=&r"(status), "+&r"(attempts) + : "r"(&x) + : "memory"); + __CPROVER_assert(attempts == 1, "branch on success"); // fails + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/test.desc b/regression/cbmc/asm_llsc_retry_loops/test.desc new file mode 100644 index 000000000000..c3e7b26db094 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c +--arch arm64 --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 19 restartable loop: SUCCESS$ +^\[main\.unwind\.0\] line 23 unwinding assertion loop 0: FAILURE$ +^\[main\.assertion\.2\] line 32 counting loop: SUCCESS$ +^\[main\.assertion\.3\] line 33 one attempt: FAILURE$ +^\[main\.unwind\.1\] line 38 unwinding assertion loop 1: FAILURE$ +^\[main\.assertion\.4\] line 46 branch on success: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +line 11 unwinding assertion +^\[main\.unwind\.2\] +-- +The retry loop of a load-exclusive/store-exclusive sequence whose failed +attempts have no effect is replaced by the attempt that succeeds, so that it +needs no unwinding. Loops whose attempts are observable (here: counted), and +branches that are not taken just when the store fails, remain loops. The +assertions that fail may be violated on hardware, where a store-exclusive +may fail spuriously. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index 33947f383f11..d76f5da89924 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -764,8 +764,16 @@ bool asm_aarch64_semanticst::lower_memory( return false; ctx.end_conditional(store); ctx.clear_exclusive(); - return write( - ctx, ops[0], 32, if_exprt{success, constant(0, 32), constant(1, 32)}); + if(!write( + ctx, + ops[0], + 32, + if_exprt{success, constant(0, 32), constant(1, 32)})) + { + return false; + } + ctx.record_store_exclusive(success); + return true; } } @@ -929,7 +937,7 @@ bool asm_aarch64_semanticst::lower( const exprt cond = asm_arm::condition(m.substr(2), ctx); if(cond.is_nil()) return ctx.fail("unsupported condition " + m); - return ctx.branch(target, cond); + return ctx.retry_branch(target, cond); } asm_token_listt reg_tokens = instruction.operands[0]; @@ -946,7 +954,8 @@ bool asm_aarch64_semanticst::lower( if(instruction.operands.size() != 2) return ctx.fail("unsupported " + m); const exprt zero = is_zero(read(ctx, reg, reg.width)); - return ctx.branch(target, m == "cbz" ? zero : exprt{not_exprt{zero}}); + return ctx.retry_branch( + target, m == "cbz" ? zero : exprt{not_exprt{zero}}); } // tbz/tbnz Rt, #bit, label @@ -961,7 +970,7 @@ bool asm_aarch64_semanticst::lower( } const exprt set = extractbit_exprt{lshr_exprt{read(ctx, reg, 64), read(ctx, bit, 64)}, 0}; - return ctx.branch(target, m == "tbnz" ? set : exprt{not_exprt{set}}); + return ctx.retry_branch(target, m == "tbnz" ? set : exprt{not_exprt{set}}); } std::vector ops; diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index fdee298d22e1..31da3475e9b7 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -1163,7 +1163,8 @@ bool asm_arm_semanticst::lower( { if(instruction.operands.size() != 1) return ctx.fail("unsupported branch"); - return ctx.branch(target, asm_arm::condition(decoded.condition, ctx)); + return ctx.retry_branch( + target, asm_arm::condition(decoded.condition, ctx)); } a32_operandt reg; if( @@ -1174,7 +1175,7 @@ bool asm_arm_semanticst::lower( return ctx.fail("unsupported " + decoded.base); } const exprt zero = is_zero(read(ctx, reg, 32)); - return ctx.branch( + return ctx.retry_branch( target, decoded.base == "cbz" ? zero : exprt{not_exprt{zero}}); } @@ -1590,8 +1591,15 @@ bool asm_arm_semanticst::lower_memory( // keeps its state. if(!conditional) ctx.clear_exclusive(); - return write( - ctx, ops[0], 32, if_exprt{success, constant(0, 32), constant(1, 32)}); + if(!write( + ctx, ops[0], 32, if_exprt{success, constant(0, 32), constant(1, 32)})) + { + return false; + } + // the status of a conditional store-exclusive may be unchanged + if(!conditional) + ctx.record_store_exclusive(success); + return true; } return ctx.fail("unsupported instruction " + instruction.mnemonic); diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index a4de0e55d5d5..1da6eba00a4b 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -16,9 +16,12 @@ Author: Michael Tautschnig #include #include #include +#include #include #include #include +#include +#include #include #include @@ -743,12 +746,191 @@ void asm_lowering_contextt::define_label(const std::string &name) } unknown_at_label[&*t] = unknown; label_index[&*t] = instructions_begun; + label_instructions.insert(&*t); if(numeric) numeric_labels[name].push_back(t); else label_definitions[name] = t; } +void asm_lowering_contextt::record_store_exclusive(const symbol_exprt &success) +{ + const goto_programt::targett first = instruction_start.has_value() + ? std::next(*instruction_start) + : body.instructions.begin(); + last_store_exclusive = + store_exclusivet{first, std::prev(body.instructions.end()), success}; +} + +bool asm_lowering_contextt::implies_store_failure(const exprt &condition) const +{ + if(!last_store_exclusive.has_value()) + return false; + + // Express the condition in terms of the values after the store-exclusive, + // substituting the assignments of the straight-line code after it. + exprt e = condition; + for(auto it = body.instructions.end(); + it != std::next(last_store_exclusive->last);) + { + --it; + if(it->is_assign()) + { + if(it->assign_lhs().id() == ID_symbol) + { + replace_symbolt replace; + replace.insert(to_symbol_expr(it->assign_lhs()), it->assign_rhs()); + replace(e); + } + } + else if(!it->is_skip() && !it->is_other() && !it->is_atomic_end()) + return false; + } + // and of the store-exclusive's own code, which ends with the status + for(auto it = std::next(last_store_exclusive->last); + it != last_store_exclusive->first;) + { + --it; + if( + it->is_assign() && it->assign_lhs().id() == ID_symbol && + it->assign_lhs() != last_store_exclusive->success) + { + replace_symbolt replace; + replace.insert(to_symbol_expr(it->assign_lhs()), it->assign_rhs()); + replace(e); + } + } + + // with a successful store, the branch must not be taken + replace_symbolt success; + success.insert(last_store_exclusive->success, true_exprt{}); + success(e); + return simplify_expr(e, ns) == false; +} + +bool asm_lowering_contextt::restartable(goto_programt::targett label) const +{ + if(!last_store_exclusive.has_value()) + return false; + + // the instructions in conditionally executed code, up to its end + std::set conditional_ends; + bool store_seen = false, in_store = false; + std::set read_first, written, conditionally_written; + auto reads = [&](const exprt &expr) + { + find_symbols_sett symbols; + find_symbols(expr, symbols); + for(const auto &id : symbols) + { + if(written.count(id) == 0) + read_first.insert(id); + } + }; + + for(auto it = std::next(label); it != body.instructions.end(); ++it) + { + const goto_programt::instructiont *const instruction = &*it; + if(it == last_store_exclusive->first) + { + store_seen = true; + in_store = true; + } + conditional_ends.erase(instruction); + const bool conditional = !conditional_ends.empty(); + + if( + label_instructions.count(instruction) != 0 || + branch_instructions.count(instruction) != 0 || it->is_function_call()) + { + return false; + } + + if(it->is_goto()) + { + // conditionally executed code within an instruction, which skips + // forward + reads(it->condition()); + conditional_ends.insert(&*it->get_target()); + } + else if(it->is_assign()) + { + reads(it->assign_rhs()); + const exprt &lhs = it->assign_lhs(); + if(lhs.id() == ID_symbol) + { + const irep_idt &id = to_symbol_expr(lhs).identifier(); + (conditional ? conditionally_written : written).insert(id); + } + else + { + // only the store-exclusive writes memory, and only when it succeeds + if(!in_store) + return false; + reads(lhs); + } + } + else if(it->is_assume() || it->is_assert()) + reads(it->condition()); + else if( + !it->is_skip() && !it->is_atomic_begin() && !it->is_atomic_end() && + !(it->is_other() && it->get_other().get_statement() == ID_fence)) + { + return false; + } + + if(it == last_store_exclusive->last) + in_store = false; + } + + if(!store_seen || !conditional_ends.empty()) + return false; + + // Every attempt writes all it writes, and does not depend on what an + // earlier attempt wrote. + for(const auto &id : conditionally_written) + { + if(written.count(id) == 0) + return false; + } + for(const auto &id : read_first) + { + if(written.count(id) != 0 || conditionally_written.count(id) != 0) + return false; + } + return true; +} + +bool asm_lowering_contextt::retry_branch( + const asm_tokent &target, + const exprt &condition) +{ + std::optional label; + if( + target.kind == asm_tokent::kindt::LOCAL_LABEL && target.backward && + !numeric_labels[target.text].empty()) + { + label = numeric_labels[target.text].back(); + } + else if(target.kind == asm_tokent::kindt::IDENTIFIER) + { + auto it = label_definitions.find(target.text); + if(it != label_definitions.end()) + label = it->second; + } + + if( + !label.has_value() || exclusive_open() || !restartable(*label) || + !implies_store_failure(condition)) + { + return branch(target, condition); + } + + // The attempts that fail have no effect: consider the one that succeeds. + assume(not_exprt{condition}); + return true; +} + bool asm_lowering_contextt::branch( const asm_tokent &target, const exprt &condition) @@ -771,6 +953,7 @@ bool asm_lowering_contextt::branch( goto_target}); exit_branches.push_back( body.add(goto_programt::make_incomplete_goto(condition, location))); + branch_instructions.insert(&*exit_branches.back()); return true; } @@ -784,8 +967,8 @@ bool asm_lowering_contextt::branch( if(!check_unknown_at_target(definitions.back(), unknown)) return false; note_branch(current_instruction(), definitions.back()); - body.add( - goto_programt::make_goto(definitions.back(), condition, location)); + branch_instructions.insert(&*body.add( + goto_programt::make_goto(definitions.back(), condition, location))); return true; } @@ -797,6 +980,7 @@ bool asm_lowering_contextt::branch( true, unknown, current_instruction()}); + branch_instructions.insert(&*pending.back().instruction); return true; } @@ -810,6 +994,7 @@ bool asm_lowering_contextt::branch( false, unknown, current_instruction()}); + branch_instructions.insert(&*pending.back().instruction); return true; } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index a1c261d5387e..c374d02a546f 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -179,6 +179,26 @@ class asm_lowering_contextt { return monitor_cleared; } + + /// Record that the code lowered for the current instruction is a + /// store-exclusive that succeeds iff \p success holds. + void record_store_exclusive(const symbol_exprt &success); + + /// Lower a backward branch to \p target taken iff \p condition holds. + /// When the branch closes the retry loop of a store-exclusive, as in + /// `1: ldxr ...; stxr w1, ...; cbnz w1, 1b`, symbolic execution would have + /// to unwind the loop, which may retry arbitrarily often. Instead, if + /// - \p condition implies that the store-exclusive recorded last + /// (\ref record_store_exclusive) failed, and + /// - the code from \p target to the branch is restartable: it has no + /// other labels or branches, no calls, no writes to memory other than + /// the store-exclusive's, writes the registers and temporaries it writes + /// unconditionally, and does not read any of them before writing it, + /// then an attempt that takes the branch has no effect, and the + /// executions that retry reach the same states as one that succeeds at + /// the last attempt. The branch is then replaced by the assumption that it + /// is not taken. Otherwise, it is lowered as by \ref branch. + bool retry_branch(const asm_tokent &target, const exprt &condition); /// \} /// A call to a library function taking `void *` arguments @@ -294,6 +314,23 @@ class asm_lowering_contextt /// the canonical names of the hardware registers that are written std::set written_registers; + /// the code of the store-exclusive recorded last + struct store_exclusivet + { + goto_programt::targett first, last; + symbol_exprt success; + }; + std::optional last_store_exclusive; + /// the instructions of branches (\ref branch) and of label definitions + std::set branch_instructions, + label_instructions; + /// whether the code after \p label is restartable (see + /// \ref retry_branch) + bool restartable(goto_programt::targett label) const; + /// whether \p condition, at the end of the code lowered so far, implies + /// that the store-exclusive recorded last failed + bool implies_store_failure(const exprt &condition) const; + /// The symbols that may hold a value that is not modeled at the current /// position, and \ref unknown_memory if memory may hold such a value std::set unknown; From 77aa0e92e5220aec09b1559d8ed5097225c6702e Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:57:03 +0000 Subject: [PATCH 097/100] Inline assembly: test retry loops that must remain loops asm_llsc_retry_loops covered three loops that remain loops (one that counts its attempts, one whose branch is taken on success, and one that stores to memory), but not the other conditions under which replacing a retry loop by its last attempt would be unsound, nor a concurrent program, where the interleavings of the last attempt matter. Add tests of loops that remain loops, each with an unwinding assertion that fails and assertions that may be violated on hardware: a branch on the loaded data (D), a second branch that re-runs a first exclusive pair that stored (J), an exit to an asm goto label (K), a register written only in some attempts (E), and cmpeq after teq, which makes bne retry after a successful store (H, where a replacement would make the end of main unreachable). In cbmc-concurrency, asm_llsc_retry_loop checks that a replaced loop that reads another variable before its exclusive pair keeps all values of that variable that the last attempt may read, and that in E the other thread's write between two attempts makes flag come from an earlier attempt. The single-threaded tests were validated with qemu-aarch64 (Clang) and qemu-arm (A32, GCC and Clang). a64_shapes and arm_shapes use tbnz or flags, which the incremental SMT back end does not support (extractbit), and are tagged no-new-smt like the other ARM tests. Co-authored-by: Kiro --- .../asm_llsc_retry_loop/arm.c | 32 +++++++++++ .../asm_llsc_retry_loop/arm.desc | 17 ++++++ .../asm_llsc_retry_loop/main.c | 33 +++++++++++ .../asm_llsc_retry_loop/test.desc | 18 ++++++ .../cbmc/asm_llsc_retry_loops/a64_shapes.c | 57 +++++++++++++++++++ .../cbmc/asm_llsc_retry_loops/a64_shapes.desc | 25 ++++++++ .../cbmc/asm_llsc_retry_loops/arm_shapes.c | 45 +++++++++++++++ .../cbmc/asm_llsc_retry_loops/arm_shapes.desc | 24 ++++++++ 8 files changed, 251 insertions(+) create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/arm.c create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/arm.desc create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/main.c create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/test.desc create mode 100644 regression/cbmc/asm_llsc_retry_loops/a64_shapes.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/a64_shapes.desc create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_shapes.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_shapes.desc diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.c b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.c new file mode 100644 index 000000000000..0b740ed25c41 --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.c @@ -0,0 +1,32 @@ +// A retry loop that writes flag only in the attempts that load 5, so that it +// remains a loop: if the other thread changes x between two attempts, the +// attempt that succeeds may load 7 while an earlier attempt set flag. +unsigned x = 5, flag, done; + +void t(void) +{ + unsigned r, s; + __asm__ volatile( + "1: ldrex %0, [%3]\n" + " cmp %0, #5\n" + " moveq %2, #1\n" + " add %0, %0, #1\n" + " strex %1, %0, [%3]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s), "+&r"(flag) + : "r"(&x) + : "cc", "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), done = 1; + x = 7; + __CPROVER_assume(done); + __CPROVER_assert( + !(flag == 1 && x == 8), "flag of an earlier attempt"); // fails + __CPROVER_assert(x == 7 || x == 8, "x is 7 or 8"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.desc b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.desc new file mode 100644 index 000000000000..258a26deb891 --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm.desc @@ -0,0 +1,17 @@ +CORE gcc-only +arm.c +--arch arm --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 28 flag of an earlier attempt: FAILURE$ +^\[main\.assertion\.2\] line 30 x is 7 or 8: SUCCESS$ +^\[t\.unwind\.0\] line 9 unwinding assertion loop 0: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +-- +flag is written only in the attempts that load 5, so the loop is not replaced +by its last attempt: on hardware, the first attempt may load 5 and set flag, +and its store fail after the other thread wrote 7, so that the attempt that +succeeds loads 7 and stores 8 with flag set. diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/main.c b/regression/cbmc-concurrency/asm_llsc_retry_loop/main.c new file mode 100644 index 000000000000..391a906bb3e5 --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/main.c @@ -0,0 +1,33 @@ +// A retry loop that reads y before its exclusive pair and stores that value +// to x. The loop is replaced by its last attempt, whose read of y is not +// ordered with the other thread's writes: every value that y takes may end +// up in x. +unsigned long x, y, done; + +void t(void) +{ + unsigned long tmp, old; + unsigned int status; + __asm__ volatile( + "1: ldr %1, [%4]\n" + " ldxr %0, [%3]\n" + " stxr %w2, %1, [%3]\n" + " cbnz %w2, 1b" + : "=&r"(old), "=&r"(tmp), "=&r"(status) + : "r"(&x), "r"(&y) + : "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), done = 1; + y = 1; + y = 2; + __CPROVER_assume(done); + __CPROVER_assert(x != 0, "x is not 0"); // fails + __CPROVER_assert(x != 1, "x is not 1"); // fails + __CPROVER_assert(x != 2, "x is not 2"); // fails + __CPROVER_assert(x <= 2, "x is at most 2"); + return 0; +} diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/test.desc b/regression/cbmc-concurrency/asm_llsc_retry_loop/test.desc new file mode 100644 index 000000000000..699bffc63639 --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 28 x is not 0: FAILURE$ +^\[main\.assertion\.2\] line 29 x is not 1: FAILURE$ +^\[main\.assertion\.3\] line 30 x is not 2: FAILURE$ +^\[main\.assertion\.4\] line 31 x is at most 2: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +unwinding assertion +-- +The retry loop is replaced by its last attempt (it needs no unwinding), which +keeps the interleavings of the read of y in that attempt with the other +thread's writes: x may be 0, 1, or 2 on hardware. diff --git a/regression/cbmc/asm_llsc_retry_loops/a64_shapes.c b/regression/cbmc/asm_llsc_retry_loops/a64_shapes.c new file mode 100644 index 000000000000..aa88b85ab608 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/a64_shapes.c @@ -0,0 +1,57 @@ +// AArch64 retry loops of load-exclusive/store-exclusive sequences that are +// not replaced by their last attempt, as an attempt that takes the branch +// may have an effect or the branch may be taken although the store succeeded. +unsigned long x, y; +unsigned long nondet_ulong(void); + +int main(void) +{ + unsigned long r, q; + unsigned int s; + + // D: the branch retries when the loaded value is odd, not when the store + // fails, so the loop does not exit for odd values + x = nondet_ulong(); + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " stxr %w1, %0, [%2]\n" + " tbnz %0, #0, 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory"); + __CPROVER_assert(s == 0, "D: retry on the loaded data"); // fails + + // J: the second branch re-runs the first exclusive pair, which stored + x = 1; + y = 1; + __asm__ volatile( + "1: ldxr %0, [%3]\n" + " add %0, %0, #1\n" + " stxr %w2, %0, [%3]\n" + " cbnz %w2, 1b\n" + " ldxr %1, [%4]\n" + " add %1, %1, #1\n" + " stxr %w2, %1, [%4]\n" + " cbnz %w2, 1b" + : "=&r"(r), "=&r"(q), "=&r"(s) + : "r"(&x), "r"(&y) + : "memory"); + __CPROVER_assert(x == 2 && y == 2, "J: second retry"); // fails + + // K: the loop has an exit to a label of asm goto + x = 1; + __asm__ goto( + "1: ldr x9, [%0]\n" + " cbz x9, %l[zero]\n" + " ldxr x9, [%0]\n" + " add x9, x9, #1\n" + " stxr w10, x9, [%0]\n" + " cbnz w10, 1b" + : + : "r"(&x) + : "x9", "x10", "memory" + : zero); + __CPROVER_assert(x == 2, "K: asm goto exit"); +zero: + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/a64_shapes.desc b/regression/cbmc/asm_llsc_retry_loops/a64_shapes.desc new file mode 100644 index 000000000000..4b9119837676 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/a64_shapes.desc @@ -0,0 +1,25 @@ +CORE gcc-only no-new-smt +a64_shapes.c +--arch arm64 --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.unwind\.0\] line 15 unwinding assertion loop 0: FAILURE$ +^\[main\.assertion\.1\] line 22 D: retry on the loaded data: FAILURE$ +^\[main\.unwind\.1\] line 27 unwinding assertion loop 1: FAILURE$ +^\[main\.assertion\.2\] line 39 J: second retry: FAILURE$ +^\[main\.unwind\.2\] line 43 unwinding assertion loop 2: FAILURE$ +^\[main\.assertion\.3\] line 54 K: asm goto exit: SUCCESS$ +^\*\* 5 of \d+ failed +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +^\[main\.unwind\.3\] +-- +Retry loops that must remain loops: D retries on the loaded data rather than +on a failed store, J's second branch re-runs the first exclusive pair, whose +store succeeded, and K has an exit to an asm goto label. Each statement is one +loop, whose unwinding assertion fails. The assertions marked "fails" in +a64_shapes.c may be violated on hardware, where a store-exclusive may fail +spuriously; the other holds. qemu-aarch64 agrees for code compiled by Clang +(with x even in D, as the loop does not exit for odd x). diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_shapes.c b/regression/cbmc/asm_llsc_retry_loops/arm_shapes.c new file mode 100644 index 000000000000..83a31b798c01 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_shapes.c @@ -0,0 +1,45 @@ +// AArch32 retry loops of load-exclusive/store-exclusive sequences that are +// not replaced by their last attempt, as an attempt that takes the branch +// may have an effect or the branch may be taken although the store succeeded. +unsigned x; + +int main(void) +{ + unsigned r, s, flag; + + // E: flag is written only in the attempts that load 5, so its value may + // come from an earlier attempt (if another thread changes x) + x = 5; + flag = 0; + __asm__ volatile( + "1: ldrex %0, [%3]\n" + " cmp %0, #5\n" + " moveq %2, #1\n" + " add %0, %0, #1\n" + " strex %1, %0, [%3]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s), "+&r"(flag) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(flag == 1 && x == 6, "E: conditional write"); + + // H: cmpeq after teq sets the flags when the store succeeded, so that bne + // retries after a successful store unless the stored value is 0: the first + // attempt stores 0xffffffff, the second 0 + x = 0xfffffffe; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, #1\n" + " strex %1, %0, [%2]\n" + " teq %1, #0\n" + " cmpeq %0, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(x == 0, "H: cmpeq after teq"); + __CPROVER_assert(x != 0, "H: x != 0"); // fails, as x is 0 + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_shapes.desc b/regression/cbmc/asm_llsc_retry_loops/arm_shapes.desc new file mode 100644 index 000000000000..d765b11a3f10 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_shapes.desc @@ -0,0 +1,24 @@ +CORE gcc-only no-new-smt +arm_shapes.c +--arch arm --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.unwind\.0\] line 14 unwinding assertion loop 0: FAILURE$ +^\[main\.assertion\.1\] line 25 E: conditional write: SUCCESS$ +^\[main\.unwind\.1\] line 31 unwinding assertion loop 1: FAILURE$ +^\[main\.assertion\.2\] line 41 H: cmpeq after teq: SUCCESS$ +^\[main\.assertion\.3\] line 42 H: x != 0: FAILURE$ +^\*\* 3 of \d+ failed +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +^\[main\.unwind\.2\] +-- +Retry loops that must remain loops: E writes flag only in some attempts, so +that its value may come from an earlier attempt, and in H, bne also retries +after a successful store. Each statement is one loop, whose unwinding +assertion fails. The assertion marked "fails" in arm_shapes.c is violated on +hardware (H stores 0 in its second attempt); the others hold. qemu-arm agrees +for A32 code compiled by GCC and Clang. If H were replaced by its last +attempt, the end of main would be unreachable, and "H: x != 0" would hold. From 4c1a8c793df5a6499c1c181df45a223af6d64dcf Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 16:58:26 +0000 Subject: [PATCH 098/100] Inline assembly: document which retry branches are replaced The manual said that a retry loop is replaced by its last attempt if its branch is cbnz of the status, or bne after teq or cmp of the status with 0. The check is more general: any branch whose condition, with the code after the store-exclusive substituted, simplifies to false when the store succeeds is replaced, such as tbnz of bit 0 of the status, bne after tst of it with 1, or b.eq after cmp of it with 1. The manual also did not say that replacing these loops renumbers the other loops of the function, so that existing --unwindset options that name loops by number may refer to other loops. Describe the check and give these forms as examples, and document the renumbering. forms.c (AArch64) and arm_forms.c (AArch32) in asm_llsc_retry_loops check that the forms are replaced: with the binaries of the layer below, each of them is a loop whose unwinding assertion fails. The assertions were validated with qemu-aarch64 and qemu-arm. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 21 ++++-- .../cbmc/asm_llsc_retry_loops/arm_forms.c | 34 ++++++++++ .../cbmc/asm_llsc_retry_loops/arm_forms.desc | 18 +++++ regression/cbmc/asm_llsc_retry_loops/forms.c | 67 +++++++++++++++++++ .../cbmc/asm_llsc_retry_loops/forms.desc | 21 ++++++ 5 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_forms.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_forms.desc create mode 100644 regression/cbmc/asm_llsc_retry_loops/forms.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/forms.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index f1c6b3df8ef7..5c07e5cb802d 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -193,11 +193,22 @@ writes the same registers and flags in every attempt), the executions that retry reach the same states as the one whose last attempt succeeds. CBMC then replaces the branch that retries by the assumption that it is not taken (which implies that the store succeeded), so that the statement contains no -loop. This requires the branch to be taken -only when the store fails (`cbnz` of the status, or `bne` after `teq` or -`cmp` of the status with 0) and the loop to contain no other label or branch. -Other retry loops remain loops: symbolic execution needs an unwinding bound -for them, and their unwinding assertions fail. +loop. This requires the branch to be taken only when the store fails: CBMC +substitutes the code between the store-exclusive and the branch into the +branch condition, and checks that the condition simplifies to false when the +store succeeds (and the status is 0). This holds, for example, for `cbnz` of +the status, `tbnz` of its bit 0, `bne` (`b.ne`) after `teq` or `cmp` of the +status with 0 or after `tst` of it with 1, and `beq` (`b.eq`) or `bhs` +(`b.hs`) after `cmp` of the status with 1. The loop must also contain no +other label or branch and no call. Other retry loops remain loops: symbolic +execution needs an unwinding bound for them, and their unwinding assertions +fail. + +As the replaced loops are no longer loops, the loops of a function that +contains them are numbered differently than in versions of CBMC that kept +them as loops (see `--show-loops`): an `--unwindset` option written for such +a version, which names loops by their numbers (as in `main.2:5`), may now +refer to a different loop, or to none. A store-exclusive fails if the exclusive monitor is cleared, by `clrex` or by an earlier store-exclusive. CBMC decides the monitor state along the diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_forms.c b/regression/cbmc/asm_llsc_retry_loops/arm_forms.c new file mode 100644 index 000000000000..369407d70199 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_forms.c @@ -0,0 +1,34 @@ +// Retry loops (AArch32) whose branch is taken only if the store-exclusive +// fails, in other forms than bne after teq or cmp of the status with 0: they +// are replaced by their last attempt, so that they need no unwinding. +unsigned x; + +int main(void) +{ + unsigned r, s; + + x = 0; + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, #1\n" + " strex %1, %0, [%2]\n" + " cmp %1, #1\n" + " beq 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(x == 1 && s == 0, "cmp #1, beq"); + + __asm__ volatile( + "1: ldrex %0, [%2]\n" + " add %0, %0, #1\n" + " strex %1, %0, [%2]\n" + " tst %1, #1\n" + " bne 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(x == 2 && s == 0, "tst #1, bne"); + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_forms.desc b/regression/cbmc/asm_llsc_retry_loops/arm_forms.desc new file mode 100644 index 000000000000..051b931187ff --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_forms.desc @@ -0,0 +1,18 @@ +CORE gcc-only no-new-smt +arm_forms.c +--arch arm --unwind 3 +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 20 cmp #1, beq: SUCCESS$ +^\[main\.assertion\.2\] line 31 tst #1, bne: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +unwinding assertion +-- +Each branch is taken only if the store-exclusive fails: substituting the code +after the store into the condition and assuming that the store succeeds +simplifies the condition to false. The loops are thus replaced by their last +attempt, and there is no loop to unwind. The assertions hold under qemu-arm +for A32 code compiled by GCC and Clang. diff --git a/regression/cbmc/asm_llsc_retry_loops/forms.c b/regression/cbmc/asm_llsc_retry_loops/forms.c new file mode 100644 index 000000000000..8ce1281a87cc --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/forms.c @@ -0,0 +1,67 @@ +// Retry loops (AArch64) whose branch is taken only if the store-exclusive +// fails, in other forms than cbnz of the status: they are replaced by their +// last attempt, so that they need no unwinding. +unsigned long x; + +int main(void) +{ + unsigned long r; + unsigned int s; + + x = 0; + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " tbnz %w1, #0, 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory"); + __CPROVER_assert(x == 1 && s == 0, "tbnz"); + + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " cmp %w1, #0\n" + " b.ne 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory", "cc"); + __CPROVER_assert(x == 2 && s == 0, "cmp #0, b.ne"); + + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " cmp %w1, #1\n" + " b.eq 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory", "cc"); + __CPROVER_assert(x == 3 && s == 0, "cmp #1, b.eq"); + + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " tst %w1, #1\n" + " b.ne 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory", "cc"); + __CPROVER_assert(x == 4 && s == 0, "tst #1, b.ne"); + + __asm__ volatile( + "1: ldxr %0, [%2]\n" + " add %0, %0, #1\n" + " stxr %w1, %0, [%2]\n" + " cmp %w1, #1\n" + " b.hs 1b" + : "=&r"(r), "=&r"(s) + : "r"(&x) + : "memory", "cc"); + __CPROVER_assert(x == 5 && s == 0, "cmp #1, b.hs"); + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/forms.desc b/regression/cbmc/asm_llsc_retry_loops/forms.desc new file mode 100644 index 000000000000..f042a33fd5c9 --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/forms.desc @@ -0,0 +1,21 @@ +CORE gcc-only no-new-smt +forms.c +--arch arm64 --unwind 3 +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 20 tbnz: SUCCESS$ +^\[main\.assertion\.2\] line 31 cmp #0, b\.ne: SUCCESS$ +^\[main\.assertion\.3\] line 42 cmp #1, b\.eq: SUCCESS$ +^\[main\.assertion\.4\] line 53 tst #1, b\.ne: SUCCESS$ +^\[main\.assertion\.5\] line 64 cmp #1, b\.hs: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +unwinding assertion +-- +Each branch is taken only if the store-exclusive fails: substituting the code +after the store into the condition and assuming that the store succeeds +simplifies the condition to false. The loops are thus replaced by their last +attempt, and there is no loop to unwind. The assertions hold under +qemu-aarch64 for code compiled by Clang. From 2aeee223f702dcf7440eae70090bbabf5860c387 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 17:03:17 +0000 Subject: [PATCH 099/100] Inline assembly: ignore instruction temporaries in retry loops A retry loop is replaced by its last attempt only if every symbol that it writes conditionally it also writes unconditionally. This also applied to the temporaries that the AArch32 and AArch64 semantics create for the values within one instruction, so that a conditional instruction made any loop non-restartable. For example, in 1: mov %2, #0; ldrex %0, [%3]; cmp %0, #5; moveq %2, #1; add %0, %0, #1; strex %1, %0, [%3]; teq %1, #0; bne 1b flag (%2) is written in every attempt, but the temporary that moveq assigns before writing %2 is written only when moveq executes, so the loop remained a loop and needed unwinding. Create these temporaries with asm_lowering_contextt:: instruction_temporary, which assigns the temporary at once and is documented to be read only by the code of its instruction, after that assignment. Such a temporary carries no value from one attempt to the next or out of the loop, so restartable() ignores it. Registers, flags, operands, and the other temporaries (such as the slots of push) are checked as before; a register written only conditionally, as in arm_shapes.c, still keeps the loop. arm_conditional.c in asm_llsc_retry_loops (validated with qemu-arm) and in cbmc-concurrency/asm_llsc_retry_loop check that the loop is replaced, and in the concurrent program that flag is that of the attempt that succeeds. With the binaries of the layer below, the single-threaded test fails (its loops have unwinding assertions) and the concurrent one does not terminate without an unwinding bound. Co-authored-by: Kiro --- doc/architectural/inline-assembly.md | 6 ++- .../asm_llsc_retry_loop/arm_conditional.c | 34 +++++++++++++++ .../asm_llsc_retry_loop/arm_conditional.desc | 18 ++++++++ .../asm_llsc_retry_loops/arm_conditional.c | 42 +++++++++++++++++++ .../asm_llsc_retry_loops/arm_conditional.desc | 18 ++++++++ src/assembler/asm_aarch64.cpp | 12 +----- src/assembler/asm_arm.cpp | 6 +-- src/assembler/asm_lowering.cpp | 18 +++++++- src/assembler/asm_semantics.h | 14 ++++++- 9 files changed, 149 insertions(+), 19 deletions(-) create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.c create mode 100644 regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.desc create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_conditional.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/arm_conditional.desc diff --git a/doc/architectural/inline-assembly.md b/doc/architectural/inline-assembly.md index 216c283734ed..547da442b939 100644 --- a/doc/architectural/inline-assembly.md +++ b/doc/architectural/inline-assembly.md @@ -163,7 +163,11 @@ conditional branches with `retry_branch`: a backward branch that is taken only if the recorded store failed (checked by substituting the code after the store into the condition and simplifying it with the store succeeding), and whose loop is restartable (`restartable`), becomes the assumption that it is not -taken. +taken. `restartable` ignores the temporaries that the semantics create with +`asm_lowering_contextt::instruction_temporary`, which only the instruction +that writes them reads: a conditional instruction (such as `moveq`) writes +them only when it executes, but they carry no value from one attempt to the +next. AArch32 needs two statement-wide properties (`make_a32_state` in `asm_arm.cpp`). In divided syntax, which GCC uses for inline assembly in A32 diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.c b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.c new file mode 100644 index 000000000000..258f029ab07f --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.c @@ -0,0 +1,34 @@ +// A retry loop that writes flag in every attempt, unconditionally and then +// conditionally (moveq), so that it is replaced by its last attempt: flag +// tells whether the attempt that succeeds loaded 5, also if the other thread +// changes x between two attempts. +unsigned x = 5, flag, done; + +void t(void) +{ + unsigned r, s; + __asm__ volatile( + "1: mov %2, #0\n" + " ldrex %0, [%3]\n" + " cmp %0, #5\n" + " moveq %2, #1\n" + " add %0, %0, #1\n" + " strex %1, %0, [%3]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s), "=&r"(flag) + : "r"(&x) + : "cc", "memory"); +} + +int main(void) +{ +__CPROVER_ASYNC_1: + t(), done = 1; + x = 7; + __CPROVER_assume(done); + __CPROVER_assert(!(flag == 1 && x == 8), "flag of the last attempt"); + __CPROVER_assert(!(flag == 1 && x == 7), "x written after t"); // fails + __CPROVER_assert(!(flag == 0 && x == 8), "x written before t"); // fails + return 0; +} diff --git a/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.desc b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.desc new file mode 100644 index 000000000000..d03393225195 --- /dev/null +++ b/regression/cbmc-concurrency/asm_llsc_retry_loop/arm_conditional.desc @@ -0,0 +1,18 @@ +CORE gcc-only +arm_conditional.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 30 flag of the last attempt: SUCCESS$ +^\[main\.assertion\.2\] line 31 x written after t: FAILURE$ +^\[main\.assertion\.3\] line 32 x written before t: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +approximating inline assembly +unwinding assertion +-- +flag is written in every attempt, so the loop is replaced by its last attempt +(it needs no unwinding), and flag is that of the attempt that succeeds. On +hardware, flag == 1 and x == 8 is impossible: the attempt that stores 8 +loaded 7. The other two combinations are possible. diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_conditional.c b/regression/cbmc/asm_llsc_retry_loops/arm_conditional.c new file mode 100644 index 000000000000..aa03e240e28a --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_conditional.c @@ -0,0 +1,42 @@ +// An AArch32 retry loop with a conditional instruction (moveq) that writes a +// register that the loop also writes unconditionally first. The temporaries of +// the conditional instruction are written only in some attempts, but they are +// not used outside of it, so that the loop is replaced by its last attempt. +unsigned x; + +int main(void) +{ + unsigned r, s, flag; + + x = 5; + __asm__ volatile( + "1: mov %2, #0\n" + " ldrex %0, [%3]\n" + " cmp %0, #5\n" + " moveq %2, #1\n" + " add %0, %0, #1\n" + " strex %1, %0, [%3]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s), "=&r"(flag) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(flag == 1 && x == 6, "conditional and unconditional write"); + + x = 7; + __asm__ volatile( + "1: mov %2, #0\n" + " ldrex %0, [%3]\n" + " cmp %0, #5\n" + " moveq %2, #1\n" + " add %0, %0, #1\n" + " strex %1, %0, [%3]\n" + " teq %1, #0\n" + " bne 1b" + : "=&r"(r), "=&r"(s), "=&r"(flag) + : "r"(&x) + : "cc", "memory"); + __CPROVER_assert(flag == 0 && x == 8, "the conditional write not executed"); + + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/arm_conditional.desc b/regression/cbmc/asm_llsc_retry_loops/arm_conditional.desc new file mode 100644 index 000000000000..6d6886723dcc --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/arm_conditional.desc @@ -0,0 +1,18 @@ +CORE gcc-only no-new-smt +arm_conditional.c +--arch arm --unwind 3 +^EXIT=0$ +^SIGNAL=0$ +^\[main\.assertion\.1\] line 24 conditional and unconditional write: SUCCESS$ +^\[main\.assertion\.2\] line 39 the conditional write not executed: SUCCESS$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring +approximating inline assembly +unwinding assertion +-- +The loops write flag unconditionally (mov) and conditionally (moveq). The +temporaries of moveq are written only when it executes, but are used only by +moveq itself, so the loops are replaced by their last attempt and there is no +loop to unwind. The assertions hold under qemu-arm for A32 code compiled by +GCC and Clang. diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp index d76f5da89924..c0d5b89547c7 100644 --- a/src/assembler/asm_aarch64.cpp +++ b/src/assembler/asm_aarch64.cpp @@ -611,11 +611,7 @@ bool asm_aarch64_semanticst::lower_memory( asm_lowering_contextt &ctx) const { auto temp = [&](const exprt &value, const std::string &suffix) - { - const symbol_exprt t = ctx.temporary(value.type(), suffix); - ctx.assign(t, value); - return t; - }; + { return ctx.instruction_temporary(value, suffix); }; auto memory_operand = [&](std::size_t i) { return i < ops.size() && ops[i].kind == a64_operandt::kindt::MEMORY; }; @@ -997,11 +993,7 @@ bool asm_aarch64_semanticst::lower( { return i < ops.size() && ops[i].kind == a64_operandt::kindt::REGISTER; }; auto temp = [&](const exprt &value, const std::string &suffix) - { - const symbol_exprt t = ctx.temporary(value.type(), suffix); - ctx.assign(t, value); - return t; - }; + { return ctx.instruction_temporary(value, suffix); }; if(m == "mrs") { diff --git a/src/assembler/asm_arm.cpp b/src/assembler/asm_arm.cpp index 31da3475e9b7..672aa91ed31c 100644 --- a/src/assembler/asm_arm.cpp +++ b/src/assembler/asm_arm.cpp @@ -1268,11 +1268,7 @@ bool asm_arm_semanticst::lower_operation( ops[i].kind == a32_operandt::kindt::IMMEDIATE); }; auto temp = [&](const exprt &value, const std::string &suffix) - { - const symbol_exprt t = ctx.temporary(value.type(), suffix); - ctx.assign(t, value); - return t; - }; + { return ctx.instruction_temporary(value, suffix); }; // the carry out of the shifter for an immediate depends on its encoding auto nondet_carry = [&]() { ctx.assign(ctx.flag("c"), ctx.nondet(bool_typet{})); }; diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index 1da6eba00a4b..affbc4ad60cd 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -81,6 +81,16 @@ asm_lowering_contextt::temporary(const typet &type, const std::string &suffix) return symbol.symbol_expr(); } +symbol_exprt asm_lowering_contextt::instruction_temporary( + const exprt &value, + const std::string &suffix) +{ + const symbol_exprt t = temporary(value.type(), suffix); + instruction_temporaries.insert(t.identifier()); + assign(t, value); + return t; +} + symbol_exprt asm_lowering_contextt::hardware_register(const std::string &canonical) { @@ -817,13 +827,16 @@ bool asm_lowering_contextt::restartable(goto_programt::targett label) const std::set conditional_ends; bool store_seen = false, in_store = false; std::set read_first, written, conditionally_written; + // An instruction temporary is read only by its instruction, after the + // instruction wrote it: its value never flows from one attempt to the next + // or out of the loop, even if it is written conditionally. auto reads = [&](const exprt &expr) { find_symbols_sett symbols; find_symbols(expr, symbols); for(const auto &id : symbols) { - if(written.count(id) == 0) + if(written.count(id) == 0 && instruction_temporaries.count(id) == 0) read_first.insert(id); } }; @@ -860,7 +873,8 @@ bool asm_lowering_contextt::restartable(goto_programt::targett label) const if(lhs.id() == ID_symbol) { const irep_idt &id = to_symbol_expr(lhs).identifier(); - (conditional ? conditionally_written : written).insert(id); + if(instruction_temporaries.count(id) == 0) + (conditional ? conditionally_written : written).insert(id); } else { diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index c374d02a546f..d1f84e51a58b 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -81,6 +81,14 @@ class asm_lowering_contextt /// at the start of the statement. symbol_exprt temporary(const typet &type, const std::string &suffix); + /// A fresh block-local variable (see \ref temporary) that is assigned + /// \p value, for use only by the code that lowers the current instruction, + /// after this assignment. Its value thus never flows from one execution of + /// the instruction to another, or out of the instruction, which lets + /// \ref retry_branch ignore it. + symbol_exprt + instruction_temporary(const exprt &value, const std::string &suffix); + /// A hardware register, identified by its canonical (full-width) name. Its /// storage is block-local: the value is non-deterministic unless an operand /// with a fixed-register constraint initialises it. @@ -193,7 +201,9 @@ class asm_lowering_contextt /// - the code from \p target to the branch is restartable: it has no /// other labels or branches, no calls, no writes to memory other than /// the store-exclusive's, writes the registers and temporaries it writes - /// unconditionally, and does not read any of them before writing it, + /// unconditionally, and does not read any of them before writing it + /// (temporaries created by \ref instruction_temporary are ignored, as + /// their values do not leave their instruction), /// then an attempt that takes the branch has no effect, and the /// executions that retry reach the same states as one that succeeds at /// the last attempt. The branch is then replaced by the assumption that it @@ -313,6 +323,8 @@ class asm_lowering_contextt bool monitor_cleared = false; /// the canonical names of the hardware registers that are written std::set written_registers; + /// the temporaries created by \ref instruction_temporary + std::set instruction_temporaries; /// the code of the store-exclusive recorded last struct store_exclusivet From 779011979b02a9098fb44ab0ab3107878368f5f0 Mon Sep 17 00:00:00 2001 From: Michael Tautschnig Date: Tue, 1 Dec 2026 22:09:59 +0000 Subject: [PATCH 100/100] Inline assembly: retry loops in the check of GCC's operand contract A statement is approximated if it reads an input after writing an output without the earlyclobber modifier '&', in sequence or in a later iteration of a loop formed by a backward branch, as GCC may allocate both to the same register. A retry loop that is replaced by its last attempt did not count as such a loop, although the hardware still retries. CBMC thus proved result == 7 and v == 7 (with v initially 5) after 1: ldxr x5, [%2]; add x5, x5, %3; stxr %w1, x5, [%2]; mov %0, x5; cbnz %w1, 1b with "=r"(result) and %3 holding 2, for which Clang -O2 allocates %0 and %3 to the same register: after a spurious failure of the store, the next attempt adds the result of the failed one. retry_branch now notes the branch as a backward branch, as branch does. Co-authored-by: Kiro --- doc/cprover-manual/modeling-inline-asm.md | 5 ++- .../cbmc/asm_llsc_retry_loops/a64_contract.c | 37 +++++++++++++++++++ .../asm_llsc_retry_loops/a64_contract.desc | 21 +++++++++++ src/assembler/asm_lowering.cpp | 3 ++ src/assembler/asm_semantics.h | 4 +- 5 files changed, 68 insertions(+), 2 deletions(-) create mode 100644 regression/cbmc/asm_llsc_retry_loops/a64_contract.c create mode 100644 regression/cbmc/asm_llsc_retry_loops/a64_contract.desc diff --git a/doc/cprover-manual/modeling-inline-asm.md b/doc/cprover-manual/modeling-inline-asm.md index 5c07e5cb802d..7b30b0adf170 100644 --- a/doc/cprover-manual/modeling-inline-asm.md +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -202,7 +202,10 @@ status with 0 or after `tst` of it with 1, and `beq` (`b.eq`) or `bhs` (`b.hs`) after `cmp` of the status with 1. The loop must also contain no other label or branch and no call. Other retry loops remain loops: symbolic execution needs an unwinding bound for them, and their unwinding assertions -fail. +fail. A replaced loop still counts as a loop for GCC's operand contract (see +above), as the hardware may retry: if an attempt writes an output operand +without `&` before a later attempt reads an input operand, the statement is +approximated. As the replaced loops are no longer loops, the loops of a function that contains them are numbered differently than in versions of CBMC that kept diff --git a/regression/cbmc/asm_llsc_retry_loops/a64_contract.c b/regression/cbmc/asm_llsc_retry_loops/a64_contract.c new file mode 100644 index 000000000000..9cfa7fbd5ffc --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/a64_contract.c @@ -0,0 +1,37 @@ +// A retry loop whose output operand has no earlyclobber modifier '&': GCC may +// allocate the output to the register of an input that the next attempt +// reads, so a failed attempt has an effect even if the loop is replaced by +// its last attempt in the model. +unsigned long v = 5; + +int main(void) +{ + unsigned long result, a = 2; + unsigned int status; + __asm__ volatile( + "1: ldxr x5, [%2]\n" + " add x5, x5, %3\n" + " stxr %w1, x5, [%2]\n" + " mov %0, x5\n" + " cbnz %w1, 1b" + : "=r"(result), "=&r"(status) + : "r"(&v), "r"(a) + : "x5", "memory"); + __CPROVER_assert(result == 7, "result without &"); // fails + __CPROVER_assert(v == 7, "stored without &"); // fails + + // with '&', the loop is replaced by its last attempt + v = 5; + __asm__ volatile( + "1: ldxr x5, [%2]\n" + " add x5, x5, %3\n" + " stxr %w1, x5, [%2]\n" + " mov %0, x5\n" + " cbnz %w1, 1b" + : "=&r"(result), "=&r"(status) + : "r"(&v), "r"(a) + : "x5", "memory"); + __CPROVER_assert(result == 7, "result with &"); + __CPROVER_assert(v == 7, "stored with &"); + return 0; +} diff --git a/regression/cbmc/asm_llsc_retry_loops/a64_contract.desc b/regression/cbmc/asm_llsc_retry_loops/a64_contract.desc new file mode 100644 index 000000000000..26586b1a017d --- /dev/null +++ b/regression/cbmc/asm_llsc_retry_loops/a64_contract.desc @@ -0,0 +1,21 @@ +CORE gcc-only +a64_contract.c +--arch arm64 --unwind 3 +^EXIT=10$ +^SIGNAL=0$ +^approximating inline assembly statement at .* line 11 function main: output operand %0, which has no earlyclobber modifier '&', is written before input operand %2 is read +^\[main\.assertion\.1\] line 20 result without &: FAILURE$ +^\[main\.assertion\.2\] line 21 stored without &: FAILURE$ +^\[main\.assertion\.3\] line 34 result with &: SUCCESS$ +^\[main\.assertion\.4\] line 35 stored with &: SUCCESS$ +^VERIFICATION FAILED$ +-- +^warning: ignoring +^\[main\.unwind\. +approximating inline assembly statement at .* line 25 +-- +Replacing a retry loop by its last attempt must not hide the loop from the +check of GCC's operand contract: in the first statement, Clang -O2 allocates +%0 and %3 to the same register, so that an attempt after a spurious failure +of the store-exclusive adds the result of the failed attempt. The second +statement, with '&', is interpreted, and its loop is replaced. diff --git a/src/assembler/asm_lowering.cpp b/src/assembler/asm_lowering.cpp index affbc4ad60cd..38b8070b5bee 100644 --- a/src/assembler/asm_lowering.cpp +++ b/src/assembler/asm_lowering.cpp @@ -941,6 +941,9 @@ bool asm_lowering_contextt::retry_branch( } // The attempts that fail have no effect: consider the one that succeeds. + // The hardware still loops, so an output that the loop writes before the + // next attempt reads an input may break GCC's operand contract. + note_branch(current_instruction(), *label); assume(not_exprt{condition}); return true; } diff --git a/src/assembler/asm_semantics.h b/src/assembler/asm_semantics.h index d1f84e51a58b..1d8a713c6380 100644 --- a/src/assembler/asm_semantics.h +++ b/src/assembler/asm_semantics.h @@ -207,7 +207,9 @@ class asm_lowering_contextt /// then an attempt that takes the branch has no effect, and the /// executions that retry reach the same states as one that succeeds at /// the last attempt. The branch is then replaced by the assumption that it - /// is not taken. Otherwise, it is lowered as by \ref branch. + /// is not taken; it still counts as a backward branch for GCC's operand + /// contract (see \ref check_operand_contract), as the hardware may retry. + /// Otherwise, it is lowered as by \ref branch. bool retry_branch(const asm_tokent &target, const exprt &condition); /// \}