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..547da442b939 --- /dev/null +++ b/doc/architectural/inline-assembly.md @@ -0,0 +1,239 @@ +\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. 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 + 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.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. +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 +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 +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: + +- 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 + (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. +- 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. +- 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 + 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 +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. 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). 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. `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 +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 GNU as does not accept in divided syntax for +Thumb-1 targets (conditional execution other than of branches, `it`, `s` +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 +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 +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. +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. 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). +`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 +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/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..7b30b0adf170 --- /dev/null +++ b/doc/cprover-manual/modeling-inline-asm.md @@ -0,0 +1,546 @@ +[CPROVER Manual TOC](../../) + +## Modeling Inline Assembly + +CBMC supports GCC-style (`asm`/`__asm__`) and MSVC-style (`__asm {}`) +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: + +- On x86 (`--arch i386`, `--arch x86_64`, or `--arch x32`, which uses the + 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, + 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 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 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`, 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`); +- 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`, `out`); `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, and so are +the bits of a register above the width of the input operand it holds, when +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. + +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); +- 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 + 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 + 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; +- 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); +- 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; +- 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; +- 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 +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) 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 + (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`, + `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. +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 +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: 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. 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 +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 +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. + +### 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); 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`, + their byte and halfword forms, and `clrex`), as on AArch64 (see above); + 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; +- 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 + 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. 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 +`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`, `.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` +is not interpreted if it names any of the registers r8 to r14, which are +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. + +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 +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 + +| Instruction | Effect in CBMC | +|---|---| +| `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 (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 | +| `nop`, `pause` | No effect | + +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, 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). 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 + +| 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, 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 | + +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 | +|---|---| +| `sync`, `hwsync` | Full memory barrier | +| `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 | + +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. 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 + +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 + +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, 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, 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, + 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 +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, 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. + +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 +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. A +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 pointers that CBMC does not track (for + 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 + 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. +- 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), 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, 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 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, `__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 + 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). 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 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. +- 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 + 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. +- 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/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/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_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/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..2f90350b62df --- /dev/null +++ b/regression/cbmc-concurrency/asm_aarch64_exclusive/test.desc @@ -0,0 +1,14 @@ +CORE gcc-only +main.c +--arch arm64 +^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-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_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-concurrency/asm_arm_exclusive/main.c b/regression/cbmc-concurrency/asm_arm_exclusive/main.c new file mode 100644 index 000000000000..d256d9c51874 --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_exclusive/main.c @@ -0,0 +1,55 @@ +// A load-exclusive/store-exclusive sequence is atomic; plain loads and +// stores are not. +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) +{ + 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"); + unsigned old = z; + __CPROVER_assume(cmpxchg(&z, old, old + 1) == old); +} + +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 + __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 new file mode 100644 index 000000000000..45d8d9f06fed --- /dev/null +++ b/regression/cbmc-concurrency/asm_arm_exclusive/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only +main.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[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. A conditional store-exclusive that is the only +store-exclusive of its statement is part of the atomic section. 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/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-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-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-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-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++. 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-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_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/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/asm_aarch64/main.c b/regression/cbmc/asm_aarch64/main.c new file mode 100644 index 000000000000..dc27639aa6b1 --- /dev/null +++ b/regression/cbmc/asm_aarch64/main.c @@ -0,0 +1,772 @@ +// 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) +{ + 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; +} + +// 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 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) +{ + { + 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"); + } + { + 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[4] = { + 0x8bb0203c63f4822eULL, + 0x2bc27e528f6dfd28ULL, + 0x105c864ba75fa96aULL, + 0x8f43bdf7e2b5b16ULL}; + asm_case_16(io); + __CPROVER_assert( + io[0] == 0x8bb0203c63f4822eULL && io[1] == 0x2bc27e528f6dfd28ULL && + io[2] == 0x2bc27e528f6dfd28ULL && io[3] == 0x8bb0203c63f4822eULL, + "aarch64 ldp into the base register, vector 0"); + } + { + unsigned long long io[4] = { + 0xc301696ae878eea2ULL, + 0x653e09f78221d081ULL, + 0x7fd174cb93801745ULL, + 0x7fffffffffffffffULL}; + asm_case_16(io); + __CPROVER_assert( + io[0] == 0xc301696ae878eea2ULL && io[1] == 0x653e09f78221d081ULL && + io[2] == 0x653e09f78221d081ULL && io[3] == 0xc301696ae878eea2ULL, + "aarch64 ldp into the base register, vector 1"); + } + { + unsigned long long io[4] = { + 0xffULL, + 0xd896febde135c547ULL, + 0x3dc4f8714ad7d0a4ULL, + 0x478f66bdd008ceb8ULL}; + asm_case_16(io); + __CPROVER_assert( + 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 + __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 new file mode 100644 index 000000000000..2099ab95531b --- /dev/null +++ b/regression/cbmc/asm_aarch64/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c +--arch arm64 +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ +^\*\* 1 of \d+ failed +^VERIFICATION FAILED$ +-- +^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. 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_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_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/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..a38286953ed4 --- /dev/null +++ b/regression/cbmc/asm_aarch64_corner_cases/test.desc @@ -0,0 +1,22 @@ +CORE gcc-only +main.c +--arch arm64 +^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_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/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/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/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. 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(). 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/asm_arm/main.c b/regression/cbmc/asm_arm/main.c new file mode 100644 index 000000000000..ccc90e534d4f --- /dev/null +++ b/regression/cbmc/asm_arm/main.c @@ -0,0 +1,663 @@ +// 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) +{ + 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; +} + +// 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) +{ + { + 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"); + } + { + 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/test.desc b/regression/cbmc/asm_arm/test.desc new file mode 100644 index 000000000000..d599a1fea181 --- /dev/null +++ b/regression/cbmc/asm_arm/test.desc @@ -0,0 +1,19 @@ +CORE gcc-only no-new-smt +main.c +--arch arm +^EXIT=10$ +^SIGNAL=0$ +^\[main\.assertion\.\d+\] line \d+ end of main is reachable: FAILURE$ +^\*\* 1 of \d+ failed +^VERIFICATION FAILED$ +-- +^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. 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/main.c b/regression/cbmc/asm_arm_corner_cases/main.c new file mode 100644 index 000000000000..d0c71a884a4a --- /dev/null +++ b/regression/cbmc/asm_arm_corner_cases/main.c @@ -0,0 +1,260 @@ +// 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 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" + " 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 + + // 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"); + + // 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 + + // 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 + + // 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"); + + // 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; +} + +// 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}"); + // 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 new file mode 100644 index 000000000000..1c4f4a24b695 --- /dev/null +++ b/regression/cbmc/asm_arm_corner_cases/test.desc @@ -0,0 +1,68 @@ +CORE gcc-only no-new-smt +main.c +--arch arm +^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: 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$ +^\[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$ +^\[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$ +^\[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 +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 +approximating inline assembly statement at .* function add_ll_sc +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 +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. "carry after movs" is violated in code +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/regression/cbmc/asm_arm_exclusive_abandoned/main.c b/regression/cbmc/asm_arm_exclusive_abandoned/main.c new file mode 100644 index 000000000000..b727388d2057 --- /dev/null +++ b/regression/cbmc/asm_arm_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. + +#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 + + // 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 new file mode 100644 index 000000000000..a75c34d13122 --- /dev/null +++ b/regression/cbmc/asm_arm_exclusive_abandoned/test.desc @@ -0,0 +1,24 @@ +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$ +^\[main\.assertion\.9\] line 68 pushed and popped: SUCCESS$ +^\[main\.assertion\.10\] line 69 status matches the push: SUCCESS$ +^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/regression/cbmc/asm_arm_instructions/main.c b/regression/cbmc/asm_arm_instructions/main.c new file mode 100644 index 000000000000..84acfb9e47b4 --- /dev/null +++ b/regression/cbmc/asm_arm_instructions/main.c @@ -0,0 +1,154 @@ +// 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"); +} + +// 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"); +} + +// 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 new file mode 100644 index 000000000000..8162ffdfe756 --- /dev/null +++ b/regression/cbmc/asm_arm_instructions/test.desc @@ -0,0 +1,40 @@ +CORE gcc-only no-new-smt +main.c +--arch arm +^EXIT=10$ +^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$ +^\[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 +-- +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), with nondet_unsigned +returning each of eight values (0, 1, 41, 0x7fffffff, 0x80000001, ...) first. 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(). 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/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/regression/cbmc/asm_block_function_body/main.c b/regression/cbmc/asm_block_function_body/main.c new file mode 100644 index 000000000000..3d35230d94c1 --- /dev/null +++ b/regression/cbmc/asm_block_function_body/main.c @@ -0,0 +1,23 @@ +#ifdef __GNUC__ +// 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, p + mov dword ptr [eax], 1 +} +// clang-format on +#endif + +int main() +{ + int x = 0; +#ifdef __GNUC__ + 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 new file mode 100644 index 000000000000..c19dc6878910 --- /dev/null +++ b/regression/cbmc/asm_block_function_body/test.desc @@ -0,0 +1,17 @@ +CORE +main.c +--arch riscv64 +^EXIT=10$ +^SIGNAL=0$ +^\[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. 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/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_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/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.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/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/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/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. 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. 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/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..c08be45bac8f --- /dev/null +++ b/regression/cbmc/asm_operand_side_effects/test.desc @@ -0,0 +1,11 @@ +CORE +main.c +--arch riscv64 +^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/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/regression/cbmc/asm_x86/main.i b/regression/cbmc/asm_x86/main.i new file mode 100644 index 000000000000..deb0798dfe02 --- /dev/null +++ b/regression/cbmc/asm_x86/main.i @@ -0,0 +1,452 @@ +// 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) +{ + 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"); + lo = s.lo; + hi = s.hi; + 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] = {0x7ULL, 0x5ULL, 0x5ULL, 0x9ULL}; + asm_case_9(io); + __CPROVER_assert( + 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] = {0x7ULL, 0xdeadbeefULL, 0xdeadbeefULL, 0x0ULL}; + asm_case_9(io); + __CPROVER_assert( + 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] = {0x7ULL, 0x5ULL, 0x6ULL, 0x9ULL}; + asm_case_9(io); + __CPROVER_assert( + io[0] == 0x0ULL && io[1] == 0x5ULL && io[2] == 0x5ULL && io[3] == 0x9ULL, + "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] == 0xa699e71cULL && + 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] == 0xf0b4c97bULL && + 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] == 0xfcffb5fdULL && + 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 new file mode 100644 index 000000000000..c0115026079e --- /dev/null +++ b/regression/cbmc/asm_x86/test.desc @@ -0,0 +1,17 @@ +CORE gcc-only no-new-smt +main.i +--arch x86_64 +^EXIT=10$ +^SIGNAL=0$ +^\[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.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. 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_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_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/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/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/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/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/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/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/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/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/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/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/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..a2e6da68e940 --- /dev/null +++ b/regression/cbmc/inline_asm_approximation/test.desc @@ -0,0 +1,29 @@ +CORE gcc-only +main.c +--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 +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..83392ca9ed8a --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/main.c @@ -0,0 +1,10 @@ +int main(void) +{ + float f = 1.0f; + 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 new file mode 100644 index 000000000000..d06b0b037f54 --- /dev/null +++ b/regression/cbmc/inline_asm_approximation_rounding_mode/test.desc @@ -0,0 +1,13 @@ +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 +^\[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_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_fpu_control_word/main.c b/regression/cbmc/inline_asm_fpu_control_word/main.c new file mode 100644 index 000000000000..6376ec6cb520 --- /dev/null +++ b/regression/cbmc/inline_asm_fpu_control_word/main.c @@ -0,0 +1,22 @@ +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"); + + // 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 new file mode 100644 index 000000000000..d0f4dd2cd1d7 --- /dev/null +++ b/regression/cbmc/inline_asm_fpu_control_word/test.desc @@ -0,0 +1,19 @@ +CORE gcc-only +main.c +--arch riscv64 +^EXIT=10$ +^SIGNAL=0$ +^\[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. 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/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..697082078e1a --- /dev/null +++ b/regression/cbmc/inline_asm_goto/test.desc @@ -0,0 +1,18 @@ +CORE gcc-only +main.c +--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\) +^\[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/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..079ac343e738 --- /dev/null +++ b/regression/cbmc/inline_asm_goto_scope/test.desc @@ -0,0 +1,21 @@ +CORE gcc-only +main.c +--arch riscv64 --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). diff --git a/regression/cbmc/inline_asm_hash/arm.desc b/regression/cbmc/inline_asm_hash/arm.desc new file mode 100644 index 000000000000..58ca477e1929 --- /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: 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\(\)$ +^ *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..e5772b4b3666 --- /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: unsupported option of dmb in 'dmb #0x0' +-- +^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/cbmc/inline_asm_havoc_reachable/full-slice.desc b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc new file mode 100644 index 000000000000..e77e32e0c028 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/full-slice.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c +--arch riscv64 --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/paths-lifo.desc b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc new file mode 100644 index 000000000000..dfb9aeb499bf --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/paths-lifo.desc @@ -0,0 +1,20 @@ +CORE gcc-only +main.c +--arch riscv64 --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/cbmc/inline_asm_havoc_reachable/test.desc b/regression/cbmc/inline_asm_havoc_reachable/test.desc new file mode 100644 index 000000000000..1efb572af131 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c +--arch riscv64 +^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/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..9d46d7a369cd --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_alignment/test.desc @@ -0,0 +1,23 @@ +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$ +^\[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_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..1b8525ee77dd --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_array/test.desc @@ -0,0 +1,19 @@ +CORE gcc-only no-new-smt +main.c +--arch riscv64 +^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). +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/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..8e109fe085fc --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_budget/test.desc @@ -0,0 +1,20 @@ +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$ +^\[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. +The test is not run with the new SMT backend (no-new-smt), with which it took +31 s (z3). 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..f1fc020bd2b4 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/main.c @@ -0,0 +1,97 @@ +// 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"); + // 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 new file mode 100644 index 000000000000..4c9128cd1902 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_candidates/test.desc @@ -0,0 +1,22 @@ +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$ +^\[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 +-- +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. +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/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/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..e555513a5191 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_offsets/test.desc @@ -0,0 +1,21 @@ +CORE gcc-only +main.c +--arch riscv64 +^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 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/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..507ad777911e --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_union/test.desc @@ -0,0 +1,24 @@ +CORE gcc-only +main.c +--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$ +^\[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/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..ac49b1ccd3d4 --- /dev/null +++ b/regression/cbmc/inline_asm_havoc_reachable_unknown/test.desc @@ -0,0 +1,30 @@ +CORE gcc-only +main.c +--arch riscv64 --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/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..d908a0333a53 --- /dev/null +++ b/regression/cbmc/inline_asm_lock_prefix/test.desc @@ -0,0 +1,16 @@ +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 +^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/regression/cbmc/inline_asm_modeled_outputs/main.c b/regression/cbmc/inline_asm_modeled_outputs/main.c new file mode 100644 index 000000000000..bcbffe99b161 --- /dev/null +++ b/regression/cbmc/inline_asm_modeled_outputs/main.c @@ -0,0 +1,43 @@ +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 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..b3abc072b589 --- /dev/null +++ b/regression/cbmc/inline_asm_modeled_outputs/test.desc @@ -0,0 +1,22 @@ +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 35 wider output: FAILURE$ +^\[main\.assertion\.7\] line 40 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/regression/cbmc/inline_asm_modeling/main.c b/regression/cbmc/inline_asm_modeling/main.c new file mode 100644 index 000000000000..1569359e1b44 --- /dev/null +++ b/regression/cbmc/inline_asm_modeling/main.c @@ -0,0 +1,44 @@ +// Each statement below is processed independently by the remove_asm pass. +// 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: 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 + 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 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 + 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)); + + 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..b40d42fad46c --- /dev/null +++ b/regression/cbmc/inline_asm_modeling/test.desc @@ -0,0 +1,46 @@ +CORE gcc-only +main.c +--arch riscv64 --show-goto-functions +activate-multi-line-match +^EXIT=0$ +^SIGNAL=0$ +^ *// \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 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. 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/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..92913b97cce6 --- /dev/null +++ b/regression/cbmc/inline_asm_mxcsr/test.desc @@ -0,0 +1,16 @@ +CORE gcc-only no-new-smt +main.c +--arch riscv64 +^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/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/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..2b8f05d32ad1 --- /dev/null +++ b/regression/goto-analyzer/dependence-graph-havoc-reachable/test.desc @@ -0,0 +1,15 @@ +CORE +main.c +--arch riscv64 --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/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/regression/goto-analyzer/havoc-reachable-domains/constants.desc b/regression/goto-analyzer/havoc-reachable-domains/constants.desc new file mode 100644 index 000000000000..bb808ac8431d --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/constants.desc @@ -0,0 +1,13 @@ +CORE +main.c +--arch riscv64 --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..7a948a207074 --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/intervals.desc @@ -0,0 +1,12 @@ +CORE +main.c +--arch riscv64 --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..10c6c3cbfe74 --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-domains/vsd.desc @@ -0,0 +1,12 @@ +CORE +main.c +--arch riscv64 --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/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..268fdef722ac --- /dev/null +++ b/regression/goto-analyzer/havoc-reachable-three-way-merge/test.desc @@ -0,0 +1,19 @@ +CORE +main.c +--arch riscv64 --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/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/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/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..586c59b6b3d1 --- /dev/null +++ b/regression/goto-cc-file-local/asm-goto/main.c @@ -0,0 +1,46 @@ +// 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: else symbolic execution fails to +// find it, or the jump is lost and control always reaches "return 0". +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"); // 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 new file mode 100644 index 000000000000..39026da38cc8 --- /dev/null +++ b/regression/goto-cc-file-local/asm-goto/test.desc @@ -0,0 +1,17 @@ +CORE +main.c +compile-and-link assertion-check +^EXIT=10$ +^SIGNAL=0$ +^\[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 (and crashes), or +the dispatch on it is lost, in which case the jump is never taken and the +second assertion holds. 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..7a0a22507812 --- /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("unmodeled_instruction" ::: "memory"); +#else + __asm { unmodeled_instruction } +#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/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/regression/goto-instrument/isr-havoc-reachable/main.c b/regression/goto-instrument/isr-havoc-reachable/main.c new file mode 100644 index 000000000000..0f12a67b446e --- /dev/null +++ b/regression/goto-instrument/isr-havoc-reachable/main.c @@ -0,0 +1,18 @@ +int flag; + +void isr(void) +{ +#ifdef __GNUC__ + asm volatile("unmodeled_instruction" ::: "memory"); +#else + __asm { unmodeled_instruction } +#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..ec84e5e66a5c --- /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("unmodeled_instruction" ::: "memory"); +#else + __asm { unmodeled_instruction } +#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/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..28bbc134f5b1 --- /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("unmodeled_instruction" ::: "memory"); +#else + __asm { unmodeled_instruction } +#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/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..d18fb2306524 --- /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("unmodeled_instruction" ::: "memory"); +#else + __asm { unmodeled_instruction } +#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 = \{[^}]* +\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/regression/validate-trace-xml-schema/check.py b/regression/validate-trace-xml-schema/check.py index 674dec2e91c9..5e55936819ae 100644 --- a/regression/validate-trace-xml-schema/check.py +++ b/regression/validate-trace-xml-schema/check.py @@ -25,11 +25,17 @@ ['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'], ['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'], ['rational1', 'typecheck.desc'], diff --git a/scripts/asm_differential/README.md b/scripts/asm_differential/README.md new file mode 100644 index 000000000000..07a1e2d8184d --- /dev/null +++ b/scripts/asm_differential/README.md @@ -0,0 +1,72 @@ +# 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. + +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; +* optionally `clang-format-18` (see below). + +## 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 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 + +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. 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 +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..af513cd6fd4a --- /dev/null +++ b/scripts/asm_differential/asm_differential.py @@ -0,0 +1,298 @@ +#!/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 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 +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) + if case.epilogue: + lines.append(' ' + case.epilogue) + 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('dead_symbol()); } + else if( + from->is_other() && + (from->get_other().get_statement() == ID_havoc_object || + from->get_other().get_statement() == ID_havoc_reachable)) + { + // 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 + values.set_to_top(); + } else if(from->is_function_call()) { const exprt &function = from->call_function(); 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/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..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, @@ -840,6 +917,10 @@ 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) + { + rw_set.get_havoc_reachable_objects(function, target, code); + } } static void goto_rw( 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/interval_domain.cpp b/src/analyses/interval_domain.cpp index dcc22a1ac34d..4a95d1b18960 100644 --- a/src/analyses/interval_domain.cpp +++ b/src/analyses/interval_domain.cpp @@ -127,6 +127,13 @@ void interval_domaint::transform( case SKIP: // No action required break; case OTHER: + // 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"); #endif diff --git a/src/analyses/invariant_set.cpp b/src/analyses/invariant_set.cpp index 26eca1aef504..aa4d33899120 100644 --- a/src/analyses/invariant_set.cpp +++ b/src/analyses/invariant_set.cpp @@ -1081,6 +1081,12 @@ void invariant_sett::apply_code(const codet &code) // may be a disaster make_true(); } + else if(statement == ID_havoc_object || statement == ID_havoc_reachable) + { + // 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 || statement==ID_cpp_delete_array) { 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/analyses/variable-sensitivity/abstract_environment.cpp b/src/analyses/variable-sensitivity/abstract_environment.cpp index c5fa3a3f6fde..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( @@ -384,7 +390,20 @@ 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)); + havocked = true; } void abstract_environmentt::make_top() @@ -398,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 10efb04e147f..5a684ddaec39 100644 --- a/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp +++ b/src/analyses/variable-sensitivity/variable_sensitivity_domain.cpp @@ -154,6 +154,14 @@ void variable_sensitivity_domaint::transform( throw "exceptions not handled"; case OTHER: + // 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; @@ -355,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 = @@ -427,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); 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/ansi-c/expr2c.cpp b/src/ansi-c/expr2c.cpp index 6305d6f6b005..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) { - if(src.operands().size()==5) + // 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/ansi-c/goto-conversion/goto_asm.cpp b/src/ansi-c/goto-conversion/goto_asm.cpp index 9b85ff0cb7f0..ded1708d9d05 100644 --- a/src/ansi-c/goto-conversion/goto_asm.cpp +++ b/src/ansi-c/goto-conversion/goto_asm.cpp @@ -11,8 +11,103 @@ Author: Daniel Kroening, kroening@kroening.com #include "goto_convert_class.h" -void goto_convertt::convert_asm(const code_asmt &code, goto_programt &dest) +#include +#include +#include + +#include "destructor.h" + +#include + +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); + + // asm goto: the translation of the statement (see remove_asm) records the + // 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)); + + 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; + + 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() = source_location; + + code_blockt then_case{{dead, std::move(code_goto)}}; + then_case.add_source_location() = 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() = source_location; + + convert(if_goto, dest, mode); + } + + dest.add(goto_programt::make_dead(goto_target, source_location)); } 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..053352cb1cf1 100644 --- a/src/ansi-c/goto-conversion/goto_convert_class.h +++ b/src/ansi-c/goto-conversion/goto_convert_class.h @@ -357,7 +357,28 @@ 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); + + /// 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); diff --git a/src/ansi-c/library/x86_assembler.c b/src/ansi-c/library/x86_assembler.c index 9b70e185c3b6..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 */ @@ -29,6 +37,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) @@ -40,12 +73,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"); } diff --git a/src/ansi-c/parser.y b/src/ansi-c/parser.y index 8b5df32cf803..2853d9e47c11 100644 --- a/src/ansi-c/parser.y +++ b/src/ansi-c/parser.y @@ -2495,8 +2495,12 @@ compound_statement: } | compound_scope '{' TOK_ASM_STRING '}' { + // a block of assembly following the asm keyword, as in + // 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_msc); parser_stack($$).set(ID_C_end_location, parser_stack($4).source_location()); mto($$, $3); PARSER.pop_scope(); @@ -2731,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); } ; @@ -2884,6 +2889,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))); } ; @@ -2921,6 +2929,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/Makefile b/src/assembler/Makefile index 57638617bddf..b30322441b85 100644 --- a/src/assembler/Makefile +++ b/src/assembler/Makefile @@ -1,4 +1,12 @@ -SRC = assembler_lex.yy.cpp \ +SRC = asm_aarch64.cpp \ + asm_approximation.cpp \ + asm_arm.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 \ # Empty last line diff --git a/src/assembler/asm_aarch64.cpp b/src/assembler/asm_aarch64.cpp new file mode 100644 index 000000000000..c0d5b89547c7 --- /dev/null +++ b/src/assembler/asm_aarch64.cpp @@ -0,0 +1,1260 @@ +/*******************************************************************\ + +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 "asm_arm_flags.h" +#include "asm_bv_util.h" +#include "asm_semantics.h" + +#include +#include +#include +#include + +using asm_bv::bv; +using asm_bv::constant; +using asm_bv::extract; +using asm_bv::is_zero; +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_hint( + 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 {}; +} + +/// 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, + 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) + 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; + } + + 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: + 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; + + 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: + 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); + + 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: + ctx.abandon_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) + { return ctx.instruction_temporary(value, suffix); }; + + 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)); + } + } + + // 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 = { + {"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(); + if(!write( + ctx, + ops[0], + 32, + if_exprt{success, constant(0, 32), constant(1, 32)})) + { + return false; + } + ctx.record_store_exclusive(success); + return true; + } + } + + // 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 == "csdb" || m == "esb" || m == "sb") + { + return true; + } + + if(m == "hint") + return lower_hint(instruction, ctx); + + if(m == "clrex") + { + ctx.clear_exclusive(); + return true; + } + + if(m == "dmb" || m == "dsb" || m == "isb") + return asm_arm::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.retry_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.retry_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.retry_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) + { return ctx.instruction_temporary(value, suffix); }; + + 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_approximation.cpp b/src/assembler/asm_approximation.cpp new file mode 100644 index 000000000000..4d7588352fc1 --- /dev/null +++ b/src/assembler/asm_approximation.cpp @@ -0,0 +1,306 @@ +/*******************************************************************\ + +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 + +/// \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 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; +} + +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, + 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); + } + } + } +} + +/// 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)); +} + +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 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. the lvalues written, with addresses evaluated before the statement + // changes any object + std::vector writes; + for(const auto &write : footprint.writes) + { + writes.push_back(at_current_address( + write, function_id, source_location, temporaries, dest)); + } + + // 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) + { + 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)); + } + + // 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; + // and whether and where the statement jumps + 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); + } + 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 + 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..084ade89b792 --- /dev/null +++ b/src/assembler/asm_approximation.h @@ -0,0 +1,163 @@ +/*******************************************************************\ + +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, 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 + /// (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 +/// statement given its footprint. +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 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; 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 + /// 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 irep_idt &function_id, + 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 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( + const exprt &expr, + const namespacet &ns, + std::vector &dest); + +private: + symbol_table_baset &symbol_table; + + /// 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/asm_arm.cpp b/src/assembler/asm_arm.cpp new file mode 100644 index 000000000000..672aa91ed31c --- /dev/null +++ b/src/assembler/asm_arm.cpp @@ -0,0 +1,1945 @@ +/*******************************************************************\ + +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 + +#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", "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(), + [](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; +} + +/// \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'; }); +} + +/// \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}; +} + +/// \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) +{ + const std::string name = to_lower(raw); + + 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 {}; +} + +/// 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 +/// 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; +} + +/// \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` +/// 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 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, 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 +/// 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", + // 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; + // 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; + bool conditional_load_exclusive = false, conditional_store_exclusive = false; + std::size_t store_exclusives = 0; + // 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) + { + 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") + { + 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(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); + + bool changes_mode_here = false; + if( + is_decoded && decoded.base == "msr" && !instruction.operands.empty() && + instruction.operands[0].size() == 1) + { + bool known, flags, control; + msr_fields( + to_lower(instruction.operands[0][0].text), 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); + if(!reg.empty() && std::stoi(reg.substr(1)) >= 8) + names_banked = true; + } + } + if(changes_mode_here) + changes_mode = true; + + if(is_it_mnemonic(m)) + { + state->maybe_thumb1_divided = false; + continue; + } + + 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) + { + uses_stack = true; + 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") || + (decoded.sets_flags && decoded.base != "mov")) + { + 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) + 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) + { + state->failure = + "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))) + { + state->failure = + "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"; + } + else if(depth != 0) + state->failure = "registers pushed and not popped"; + else if(!stack_failure.empty()) + state->failure = stack_failure; + + 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; + + /// 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( + 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 = to_lower(first.text); + 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: + 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); + + 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: + ctx.abandon_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 +{ + 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); + + if(!instruction.prefixes.empty()) + return ctx.fail("unexpected prefix"); + + // the width qualifiers of unified syntax select an encoding + 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(is_it_mnemonic(m)) + { + if( + instruction.operands.size() != 1 || instruction.operands[0].size() != 1 || + !instruction.operands[0][0].is_identifier()) + { + return ctx.fail("unsupported " + m); + } + 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; + } + + // 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.retry_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.retry_branch( + 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) + { + 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), 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 || decoded.base == "mov") && + 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) + { 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{})); }; + + 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 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: 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) + 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(); + 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); +} + +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. A mode that persists + // after the statement, with its banked sp and lr, is not modeled. + 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 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") + return true; + // the software thread ID registers + if(crn == "c13" && crm == "c0" && opc2 >= 2 && opc2 <= 4) + return true; + + 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. 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( + 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() +{ + 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_arm_flags.h b/src/assembler/asm_arm_flags.h new file mode 100644 index 000000000000..8da5bb2252e3 --- /dev/null +++ b/src/assembler/asm_arm_flags.h @@ -0,0 +1,184 @@ +/*******************************************************************\ + +Module: Inline assembly: ARM condition flags + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// 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 +{ +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{}); +} + +/// 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 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..38b8070b5bee --- /dev/null +++ b/src/assembler/asm_lowering.cpp @@ -0,0 +1,1155 @@ +/*******************************************************************\ + +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 +#include +#include +#include +#include + +#include "asm_approximation.h" +#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::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) +{ + 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); + // 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); + 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); + } + + 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) + { + 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)); +} + +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(); + else + instruction_start = std::prev(body.instructions.end()); +} + +void asm_lowering_contextt::end_instruction() +{ + std::optional> start; + if(exclusive_ends) + start = ended_exclusive_start; + else if(atomic) + start = instruction_start; + exclusive_ends = false; + atomic = false; + + 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); + 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) + { + 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}}, + 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) +{ + 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) + { + // 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(); + + 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) + { + 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) + { + for(const auto &token : tokens) + { + if( + token.kind == asm_tokent::kindt::OPERAND && + 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) + { + // 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()) + { + 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) + { + // 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}; + 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 && read_bits[register_of(i)] > w) + { + // 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, + bitor_exprt{ + bitand_exprt{ + s, from_integer(power(2, register_width) - 1 - mask, s.type())}, + value}, + location)); + mark_unknown(s.identifier()); + } + else + { + // 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()); + } + } + break; + } + + case asm_operandt::kindt::MEMORY: + { + 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{object}, 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; + } + } + + // 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; +} + +void asm_lowering_contextt::define_label(const std::string &name) +{ + // 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; + 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). + const bool numeric = + !name.empty() && + std::all_of( + 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) + { + 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; + 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; + // 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 && instruction_temporaries.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(); + if(instruction_temporaries.count(id) == 0) + (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. + // 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; +} + +bool asm_lowering_contextt::branch( + const asm_tokent &target, + const exprt &condition) +{ + note_reads(condition); + // the atomic section of an exclusive access region cannot extend to the + // branch target + abandon_exclusive(); + + 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))); + branch_instructions.insert(&*exit_branches.back()); + 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"); + if(!check_unknown_at_target(definitions.back(), unknown)) + return false; + note_branch(current_instruction(), definitions.back()); + branch_instructions.insert(&*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, + unknown, + current_instruction()}); + branch_instructions.insert(&*pending.back().instruction); + 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, + unknown, + current_instruction()}); + branch_instructions.insert(&*pending.back().instruction); + return true; + } + + return fail("unsupported branch target"); +} + +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)); +} + +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))); +} + +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; + } + 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); + + // 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)"); + } + } + + // 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]; + 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..a009db945b8a --- /dev/null +++ b/src/assembler/asm_operands.cpp @@ -0,0 +1,402 @@ +/*******************************************************************\ + +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 {}; +} + +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) + 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 == '&') + operand.earlyclobber = true; + else if(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 == ',') + { + // GCC may choose any alternative, consistently for all operands + error = "constraint \"" + constraint + "\" with several alternatives"; + return false; + } + + 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; + 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( + 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; + 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. 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; + 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 && + (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 + operand.expr = address_of_exprt{operand.expr}; + } + + if( + operand.kind == asm_operandt::kindt::MEMORY && !operand.is_output && + !operand.is_lvalue()) + { + 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..2014a261a443 --- /dev/null +++ b/src/assembler/asm_operands.h @@ -0,0 +1,117 @@ +/*******************************************************************\ + +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; + /// 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; + /// 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; + /// 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; + + /// \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 +/// 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; + + /// 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 + /// 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..33721ae7302c --- /dev/null +++ b/src/assembler/asm_semantics.cpp @@ -0,0 +1,38 @@ +/*******************************************************************\ + +Module: Inline assembly: instruction semantics + +Author: Michael Tautschnig + +\*******************************************************************/ + +/// \file +/// Architecture-independent parts of the inline assembly semantics + +#include "asm_semantics.h" + +#include "asm_aarch64.h" +#include "asm_arm.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 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 new file mode 100644 index 000000000000..1d8a713c6380 --- /dev/null +++ b/src/assembler/asm_semantics.h @@ -0,0 +1,583 @@ +/*******************************************************************\ + +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; + +/// 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. +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 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. + 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, 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). + /// Another memory access, branch, or label abandons the region (see + /// \ref abandon_exclusive). + /// \{ + + /// 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(); + + /// 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 + /// first. + void clear_exclusive(); + + /// \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; + } + + /// 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 + /// (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 + /// 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); + /// \} + + /// 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). 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 + /// \{ + + /// 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. + /// \param instructions: the instructions of the statement, used to decide + /// 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); + + /// 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; + + /// 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 + /// \{ + + /// \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; + /// 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; + /// 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; + /// the temporaries created by \ref instruction_temporary + std::set instruction_temporaries; + + /// 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; + /// 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); + + /// \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. + bool check_unknown_at_target( + goto_programt::const_targett target, + const std::set &at_branch); + + 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; + /// \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; + 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. Used only by the default + /// implementation of \ref reference_bits. + 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(); + } + + /// \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 + { + 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 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 +/// `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..2cb66ecde5c4 --- /dev/null +++ b/src/assembler/asm_template.cpp @@ -0,0 +1,432 @@ +/*******************************************************************\ + +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))) + { + // 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; + 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 + 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) + { + i += 2; + digits_start = i; + } + else if( + c == '0' && i + 1 < text.size() && + std::isdigit(static_cast(text[i + 1]))) + { + 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( + 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}; + 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 = + string2integer(text.substr(digits_start, i - digits_start), base); + 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 (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('[') || + token.is_punctuation('{')) + { + ++depth; + } + else if( + token.is_punctuation(')') || 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..bd81377787bd --- /dev/null +++ b/src/assembler/asm_x86.cpp @@ -0,0 +1,1634 @@ +/*******************************************************************\ + +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; + /// for a reference to an operand of the statement: its index + std::optional index; + + // IMMEDIATE + exprt value; + + // MEMORY + exprt address; + /// 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; nil + /// otherwise + exprt lvalue = nil_exprt{}; + /// 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; +} + +/// \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) + { + 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; + } + + 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( + 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; + } + + /// 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) + { + if(suffix != 0) + return suffix; + for(const auto &op : operands) + { + if(op.kind == x86_operandt::kindt::REGISTER && op.width != 0) + return op.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); + operand.index = 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"); + // 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; + } + + 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; + // 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); + 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 == "n" || tokens[pos].modifier.empty()) && + ctx.operands.operands.at(tokens[pos].index).kind == + asm_operandt::kindt::IMMEDIATE) + { + 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; + } + 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.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); + + 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) + { + // 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( + 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) + { + 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( + 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, + // which does not give the size) and for in (whose port may be %dx) + std::vector by_size = operands; + if( + !by_size.empty() && (base == "shl" || base == "sal" || base == "shr" || + base == "sar" || base == "rol" || base == "ror")) + { + 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( + "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") + { + // 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") + { + // 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, base == "sar" ? ID_gt : ID_ge, 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"); + 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; + 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/assembler_parser.h b/src/assembler/assembler_parser.h index 1e52566c7a41..693520fd49fe 100644 --- a/src/assembler/assembler_parser.h +++ b/src/assembler/assembler_parser.h @@ -36,6 +36,25 @@ 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; + + /// 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 43426ace3452..cc41251ee4ed 100644 --- a/src/assembler/remove_asm.cpp +++ b/src/assembler/remove_asm.cpp @@ -15,18 +15,33 @@ Date: December 2014 #include "remove_asm.h" +#include #include +#include +#include +#include +#include #include +#include #include #include #include #include +#include #include #include +#include "asm_approximation.h" +#include "asm_semantics.h" #include "assembler_parser.h" +#include +#include +#include +#include +#include + class remove_asmt { public: @@ -36,7 +51,10 @@ 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), + approximate(_symbol_table), + semantics(make_asm_semantics(config.ansi_c.arch)) { } @@ -50,6 +68,18 @@ class remove_asmt symbol_tablet &symbol_table; goto_functionst &goto_functions; 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; + + using handle_commandt = std::function; void process_function(const irep_idt &, goto_functionst::goto_functiont &); @@ -58,88 +88,109 @@ 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 &, + const irep_idt &function_id, const code_asmt &, goto_programt &dest); - void gcc_asm_function_call( - const irep_idt &function_base_name, + 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_alternative( + const irep_idt &function_id, const code_asm_gcct &code, - std::size_t n_args, + asm_operandst &operands, + const std::vector &instructions, + 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, + const handle_commandt &handle_command); + + void approximate_asm( + const irep_idt &function_id, + const code_asmt &code, + const std::string &reason, + const asm_footprintt &footprint, + const std::string &writes_description, + const std::string &addresses_description, goto_programt &dest); - void msc_asm_function_call( + bool handle_gcc_command( + const irep_idt &command, + 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( + 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 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()); - - code_function_callt function_call(std::move(fkt), std::move(arguments)); + source_location); - 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)) @@ -156,65 +207,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 /// @@ -232,308 +229,1270 @@ 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 DATA_INVARIANT(false, "unexpected assembler flavor"); } -/// Translates the given inline assembly code (in gcc style) to non-assembly -/// goto program instructions -/// -/// \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 code_asm_gcct &code, - goto_programt &dest) +/// 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 cumulative) { - const irep_idt &i_str = to_string_constant(code.asm_text()).value(); + 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(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; +} - std::istringstream str(id2string(i_str)); +/// 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, 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"; + // 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); +} +/// Shared scaffolding for translating gcc-style and msc-style inline assembly. +/// 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 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 +/// \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 instructionst &instructions, + goto_programt &dest, + const handle_commandt &handle_command) +{ 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; -#if 0 - std::cout << "A ********************\n"; - for(const auto &ins : instruction) + irep_idt command; + std::size_t pos = 0; + if(instruction.front().id() == ID_symbol) { - std::cout << "XX: " << ins.pretty() << '\n'; + command = instruction.front().get(ID_identifier); + pos++; } - std::cout << "B ********************\n"; -#endif + if(!handle_command(command, pos, instruction, tmp_dest)) + return command; + } - // deal with prefixes - irep_idt command; - unsigned pos = 0; + dest.destructive_append(tmp_dest); + return {}; +} +/// 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 +/// \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 +/// \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 std::string &reason, + const asm_footprintt &footprint, + const std::string &writes_description, + const std::string &addresses_description, + goto_programt &dest) +{ + approximate(footprint, 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.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"); + parts.push_back( + "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"); + + 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() << ": " << reason << ", so " + << havocked + << (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; +} + +/// \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( - instruction.front().id() == ID_symbol && - instruction.front().get(ID_identifier) == "lock") + outputs[i].operands().size() == 2 && + gcc_constraint(outputs[i]).find('+') == std::string::npos && + written_operands.find(i) == written_operands.end()) { - x86_32_locked_atomic = true; - pos++; + assigned[i] = + asm_approximationt::outputt{to_binary_expr(outputs[i]).op1(), {}}; } + } - // done? - if(pos == instruction.size()) + // 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; - if(instruction[pos].id() == ID_symbol) + 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)) { - command = instruction[pos].get(ID_identifier); - pos++; + output.value = value; } + else + output.value.reset(); + } - if(command == "xchg" || command == "xchgl") - x86_32_locked_atomic = true; + std::vector result; + for(auto &output : assigned) + { + if(output.has_value()) + result.push_back(std::move(*output)); + } + return result; +} - if(x86_32_locked_atomic) - { - tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); +/// \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"; +} - 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); +/// \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; - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); + for(const auto &output : outputs) + { + if( + output.operands().size() == 2 && + asm_approximationt::has_state_dependent_address( + to_binary_expr(output).op1())) + { + return true; } + } - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + 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; + } + + // 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; + + 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; + } + + // 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()) { - gcc_asm_function_call("__asm_" + id2string(command), code, 1, tmp_dest); + choices.push_back(i); } - else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 + } + 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) { - gcc_asm_function_call("__asm_" + id2string(command), code, 0, tmp_dest); + if( + (mask & (std::size_t{1} << j)) != 0 && + !alternative.memory_alternative(choices[j], failure)) + { + return false; + } } - else if(command == ID_sync) // Power + alternatives.emplace_back(); + if(!lower_alternative( + function_id, + code, + alternative, + instructions, + alternatives.back(), + failure)) { - 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); + return false; + } + } - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); + 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 if(command == ID_lwsync) // Power + 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()) + 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; +} + +/// \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. 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 +/// \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::set labels; + for(const auto &instruction : instructions) + labels.insert(instruction.labels.begin(), instruction.labels.end()); + + std::vector pending_prefixes; + // the names of the other sections that are active, innermost last + std::vector sections; + + for(const auto &original : 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") { - 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); + failure = "'" + instruction.text + "' switches to Intel syntax"; + return false; + } - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); + if(m == ".pushsection" || m == ".section") + { + sections.push_back(section_name(instruction)); + continue; } - else if(command == ID_isync) // Power + if(m == ".popsection" || m == ".previous") { - 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 + if(sections.empty()) + { + failure = "unbalanced " + m; + return false; + } + sections.pop_back(); + continue; } - else if(command == "dmb" || command == "dsb") // ARM + if(!sections.empty()) { - 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())); + 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; + 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; } - else if(command == "isb") // ARM + + for(const auto &label : instruction.labels) + ctx.define_label(label); + if(!ctx.failure.empty()) { - codet code_fence(ID_fence); - code_fence.add_source_location() = code.source_location(); + failure = ctx.failure; + return false; + } - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); - // doesn't do anything by itself, - // needs to be combined with branch + 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; } - else - unknown = true; // give up - if(x86_32_locked_atomic) + instruction.prefixes.insert( + instruction.prefixes.begin(), + pending_prefixes.begin(), + pending_prefixes.end()); + pending_prefixes.clear(); + + if(instruction.is_directive()) { - tmp_dest.add(goto_programt::make_atomic_end(code.source_location())); + if(no_effect.count(m) != 0) + continue; + failure = "unsupported directive '" + instruction.text + "'"; + return false; + } - x86_32_locked_atomic = false; + ctx.begin_instruction(); + // 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 + "'" + : ctx.failure + " in '" + instruction.text + "'"; + return false; } + ctx.end_instruction(); } - if(unknown) + if(!pending_prefixes.empty()) { - // we give up; we should perhaps print a warning + failure = "prefix without instruction"; + return false; } - else - dest.destructive_append(tmp_dest); + + if(!sections.empty()) + { + failure = "unterminated section"; + return false; + } + + return true; } -/// Translates the given inline assembly code (in msc style) to non-assembly -/// goto program instructions +/// 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 +/// 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 /// \param dest: The goto program to append the new instructions to -void remove_asmt::process_instruction_msc( +void remove_asmt::process_instruction_gcc( const irep_idt &function_id, - const code_asmt &code, + const code_asm_gcct &code, goto_programt &dest) { - const irep_idt &i_str = to_string_constant(code.op0()).value(); + // 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; + } + } - std::istringstream str(id2string(i_str)); - assembler_parsert assembler_parser{message_handler}; - assembler_parser.in = &str; - assembler_parser.parse(); + const instructionst instructions = + parse(to_string_constant(code.asm_text()).value(), ID_gcc); + + goto_programt modeled; + std::set written_operands; + const auto unknown = process_asm( + instructions, + 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, written_operands, tmp_dest); + }); - goto_programt tmp_dest; - bool unknown = false; - bool x86_32_locked_atomic = false; + const namespacet ns{symbol_table}; - for(const auto &instruction : assembler_parser.instructions) + std::string reason; + if(unknown.has_value()) { - if(instruction.empty()) - continue; - -#if 0 - std::cout << "A ********************\n"; - for(const auto &ins : instruction) + // 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 = + "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), + modeled, + function_id, + code.source_location(), + dest); + + // none of the modeled instructions jumps + if(code.has_goto_target()) { - std::cout << "XX: " << ins.pretty() << '\n'; + const exprt &target = code.goto_target(); + dest.add(goto_programt::make_assignment( + target, from_integer(0, target.type()), code.source_location())); } + return; + } - std::cout << "B ********************\n"; -#endif - - // deal with prefixes - irep_idt command; - unsigned pos = 0; + asm_footprintt footprint; + if(code.has_goto_target()) + footprint.goto_target = code.goto_target(); + 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( - instruction.front().id() == ID_symbol && - instruction.front().get(ID_identifier) == "lock") + constraint.id() == ID_string_constant && + id2string(to_string_constant(constraint).value()).find('+') != + std::string::npos) { - x86_32_locked_atomic = true; - pos++; + footprint.reads.push_back(lvalue); + asm_approximationt::collect_addresses(lvalue, ns, footprint.addresses); } + } - // done? - if(pos == instruction.size()) + 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); + } - if(instruction[pos].id() == ID_symbol) + 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") { - command = instruction[pos].get(ID_identifier); - pos++; + footprint.arbitrary_memory = true; } + } - if(command == "xchg" || command == "xchgl") - x86_32_locked_atomic = 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; + } - if(x86_32_locked_atomic) + approximate_asm( + function_id, + code, + reason, + footprint, + "its output operands", + "the objects reachable from its operands", + dest); +} + +/// \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) +{ + 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'); + } + + std::size_t remaining = index; + for(const auto *list : {&code.outputs(), &code.inputs()}) + { + for(const auto &operand : list->operands()) { - tmp_dest.add(goto_programt::make_atomic_begin(code.source_location())); + if(operand.operands().size() != 2) + return {}; + 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(); +} + +/// \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 {}; - 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); + // 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 +/// \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( + const irep_idt &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(); + const bool no_operands = pos == instruction.size(); - tmp_dest.add( - goto_programt::make_other(code_fence, code.source_location())); + auto fence = [&](bool ww, bool rr, bool rw, bool wr, bool cumulative) + { + tmp_dest.add(goto_programt::make_other( + make_fence(source_location, ww, rr, rw, wr, cumulative), + source_location)); + return true; + }; + + if( + command == "fstcw" || command == "fnstcw" || command == "fldcw" || + command == "stmxcsr" || command == "ldmxcsr") // x86 + { + const auto index = gcc_operand_index(code, pos, instruction); + if(!index.has_value()) + return false; + asm_function_call( + "__asm_" + id2string(command), + {address_of_exprt{gcc_operand(code, *index)}}, + source_location, + tmp_dest); + if(command != "fldcw" && command != "ldmxcsr") + written_operands.insert(*index); + return true; + } + + if(command == "dmb" || command == "dsb") // ARM + { + if(no_operands) + return fence(true, true, true, true, true); + + // the barrier option selects the accesses being ordered + const auto barrier_option = arm_barrier_option(pos, instruction); + if(!barrier_option.has_value()) + return false; + 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 + return fence(false, true, true, 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; + } - if(command == "fstcw" || command == "fnstcw" || command == "fldcw") // x86 + if(command == "isb") // ARM + { + 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); + } + + // all other modeled instructions have no operands + if(!no_operands) + return false; + + if(command == "mfence" || command == "lfence" || command == "sfence") // x86 + { + 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 == 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 + return fence(false, false, false, false, false); + } + else + return false; +} + +/// Translates the given inline assembly code (in msc style) to non-assembly +/// 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_msc( + const irep_idt &function_id, + const code_asmt &code, + goto_programt &dest) +{ + const instructionst instructions = + parse(to_string_constant(code.op0()).value(), ID_msc); + + const auto unknown = process_asm( + instructions, + dest, + [this, &code, &function_id]( + const irep_idt &command, + std::size_t pos, + const assembler_parsert::instructiont &instruction, + goto_programt &tmp_dest) + { + return handle_msc_command( + command, pos, instruction, function_id, code, tmp_dest); + }); + + 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) { - exprt::operandst args{null_pointer_exprt{pointer_type(empty_typet{})}}; - // try to typecheck the argument - if(pos != instruction.size() && instruction[pos].id() == ID_symbol) + // a member of a struct or union, as in s.a, is part of the variable s + if(token.id() == ID_symbol) { - 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) - { - 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()}; - } - } + const std::string &identifier = id2string(token.get(ID_identifier)); + names.insert(identifier.substr(0, identifier.find('.'))); } - msc_asm_function_call( - "__asm_" + id2string(command), args, code, tmp_dest); } - else if( - command == "mfence" || command == "lfence" || command == "sfence") // x86 + } + + for(const auto &name : names) + { + for(const auto &entry : equal_range(symbol_table.symbol_base_map, name)) { - msc_asm_function_call("__asm_" + id2string(command), {}, code, tmp_dest); + 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); } - else - unknown = true; // give up + } - if(x86_32_locked_atomic) - { - tmp_dest.add(goto_programt::make_atomic_end(code.source_location())); + approximate_asm( + function_id, + code, + not_modeled(*unknown), + footprint, + "the local variables it names", + "the objects reachable from these", + dest); +} - x86_32_locked_atomic = false; +/// 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) +{ + const bool no_operands = pos == instruction.size(); + + if( + command == "fstcw" || command == "fnstcw" || command == "fldcw" || + command == "stmxcsr" || command == "ldmxcsr") // x86 + { + if(pos + 1 != instruction.size() || instruction[pos].id() != ID_symbol) + return false; + + // 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 variable; + 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) + { + continue; + } + if( + entry.second == name || + has_prefix(id2string(entry.second), local_prefix)) + { + if(variable.has_value()) + return false; + variable = entry.second; + } } - } - if(unknown) + if(!variable.has_value()) + return false; + + 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); + } + else if( + no_operands && + (command == "mfence" || command == "lfence" || command == "sfence")) // x86 { - // we give up; we should perhaps print a warning + asm_function_call( + "__asm_" + id2string(command), {}, code.source_location(), tmp_dest); + } + else if(no_operands && (command == "nop" || command == "pause")) + { + // no effect on the C program state } else - dest.destructive_append(tmp_dest); + return false; + + return true; } /// Replaces inline assembly instructions in the goto function by non-assembly @@ -583,9 +1542,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). +/// 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 diff --git a/src/assembler/scanner.l b/src/assembler/scanner.l index 614185472bb1..90f06f80f38f 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 */ @@ -77,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 ***/ 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-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/goto-instrument/full_slicer.cpp b/src/goto-instrument/full_slicer.cpp index 812d9b5ba5ce..3a6f1c1e9c39 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,27 @@ void full_slicert::operator()( const slicing_criteriont &criterion, message_handlert &message_handler) { + // The objects that havoc_reachable (from the approximation of inline + // 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) + { + 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-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, 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, 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..d09cfa1be082 100644 --- a/src/goto-symex/goto_symex.h +++ b/src/goto-symex/goto_symex.h @@ -747,6 +747,20 @@ 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 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); + 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..2c4797cd4b39 --- /dev/null +++ b/src/goto-symex/symex_havoc_reachable.cpp @@ -0,0 +1,1140 @@ +/*******************************************************************\ + +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 + +#include + +#include "goto_symex.h" +#include "path_storage.h" +#include "symex_dereference_state.h" + +#include +#include +#include +#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; + +/// 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) +{ + 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 \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); +} + +/// 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) +{ + 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 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) +{ + 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) + { + result.known = false; + continue; + } + const exprt &root = to_object_descriptor_expr(target).root_object(); + if(root.id() == ID_null_object) + continue; + 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 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 &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()}, offset_type}; + const exprt fits = and_exprt{ + {not_exprt{equal_exprt{ + pointer_object(pointer), + pointer_object(null_pointer_exprt{to_pointer_type(pointer.type())})}}, + binary_relation_exprt{position, ID_ge, from_integer(0, offset_type)}, + binary_relation_exprt{ + 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)}; +} + +/// \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(); + + // 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) + { + if(known.insert(object_identifier(object)).second) + objects.push_back(object); + }; + + // 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_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_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()) + { + if(operand.type().id() != ID_pointer) + 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)) + { + 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 + // all functions on the call stack + if(code.get_bool(ID_arbitrary_memory)) + { + 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()) + { + 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); + + // the maps of targets visited so far, which pointers assigned an + // arbitrary value share + 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; + for(const auto *entry : it->second) + { + if(!visited.insert(&entry->object_map.read()).second) + continue; + for(const auto &target : entry->object_map.read()) + 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()) || + without_address.count(object_identifier(object))) + { + 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; + // 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 + // 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]( + 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) + { + const symbol_exprt old_value = new_temporary("old_pointer", pointer.type()); + symex_assign(state, old_value, pointer); + candidates.push_back(old_value); + } + std::vector candidate_objects; + for(const auto &object : objects) + { + 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) + { + symex_assign( + state, other, side_effect_expr_nondett{other.type(), source_location}); + } + + // 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 candidate_targets = + [&](const exprt *candidate) -> const pointer_targetst & + { + const std::size_t i = candidate - candidates.data(); + auto &entry = candidate_targets_cache[i]; + if(!entry.has_value()) + { + if(i < pointers.size()) + { + entry = targets_of( + state.value_set.get_value_set( + state.rename(candidates[i], ns).get(), ns), + ns, + layouts); + } + else + { + const exprt &object = candidate_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 *entry; + }; + + 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 typet &type, + const mp_integer &element_size, + const mp_integer &element_alignment) + { + // 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) + { + 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; + } + + // 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 + // unconstrained, whose value set is that of a nondeterministic pointer (any + // 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()) + { + 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 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_of_type->second, 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, possibly + // with an offset. Restricting the pointers to these values (or null) keeps + // 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 + // its candidates would exclude values the statement may store, so the + // 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 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 + { + 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(); + + // 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()); + same_type = + by_type == candidates_by_type.end() ? &empty : &by_type->second; + other_type = &generic_candidates; + } + + 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; + 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 + // 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 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); + } + 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 = 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()) + { + 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), + typecast_exprt::conditional_cast(candidates[i], type), + std::move(value)}; + 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. + if(unknown_target) + { + 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) + { + log.warning() << "havocking the objects reachable at " << source_location + << ": some pointers have more than " << max_pointer_candidates + << " possible values, and are assigned arbitrary values" + << 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 + << ": the pointers have more than " << max_pointer_choices + << " possible values in total, and some are assigned " + "arbitrary values" + << messaget::eom; + } +} diff --git a/src/goto-symex/symex_other.cpp b/src/goto-symex/symex_other.cpp index c5e046356bf5..57c54d7f4d41 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( @@ -253,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/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..9a12571d6ca1 --- /dev/null +++ b/src/pointer-analysis/reachable_objects.cpp @@ -0,0 +1,305 @@ +/*******************************************************************\ + +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 +#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; +} + +/// \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) +{ + 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) && + !is_internal_object(symbol)) + { + 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_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) +{ + 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: +/// 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 get_pointer_targetst &get_targets, + const namespacet &ns, + bool include_previous_value) +{ + 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) + { + 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) + { + 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 + 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}; + + // the previous value, possibly moved within the objects it points to + std::set moved_targets; + for(const auto &target : get_targets(pointer)) + { + 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 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 new file mode 100644 index 000000000000..d852ef8c9cb6 --- /dev/null +++ b/src/pointer-analysis/reachable_objects.h @@ -0,0 +1,108 @@ +/*******************************************************************\ + +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 +/// (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); + +/// 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, 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 +/// \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, + 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. +bool is_compatible_pointer(const typet &location, const typet &candidate); + +#endif // CPROVER_POINTER_ANALYSIS_REACHABLE_OBJECTS_H diff --git a/src/pointer-analysis/value_set.cpp b/src/pointer-analysis/value_set.cpp index d9d4dcd561cc..891e790d1634 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`. @@ -319,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(); @@ -1841,6 +1851,49 @@ 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 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, get_targets, ns, true), + ns, + false, + false); + } +} + void value_sett::apply_code_rec( const codet &code, const namespacet &ns) @@ -1954,6 +2007,10 @@ void value_sett::apply_code_rec( else if(statement == ID_havoc_object) { } + else if(statement == ID_havoc_reachable) + { + havoc_reachable(code, ns); + } else { UNIMPLEMENTED_FEATURE( 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 7a57fdad707f..899d45241853 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,56 @@ 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.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); + } + } + roots.insert(roots.end(), stored.begin(), stored.end()); + } + + 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, get_targets, ns, false), + ns); + } +} + void value_set_fit::apply_code(const codet &code, const namespacet &ns) { const irep_idt &statement=code.get(ID_statement); @@ -1461,6 +1514,10 @@ void value_set_fit::apply_code(const codet &code, const namespacet &ns) else if(statement == ID_havoc_object) { } + else if(statement == ID_havoc_reachable) + { + havoc_reachable(code, ns); + } else throw code.pretty()+"\n"+ 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, 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 43bf0c5b7c07..8cd8bd38596d 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) @@ -945,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 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) 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..eb5f3936839f --- /dev/null +++ b/unit/assembler/asm_template.cpp @@ -0,0 +1,183 @@ +/*******************************************************************\ + +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("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( + 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