#![allow(clippy::needless_range_loop)]
#[path = "support/armsim.rs"]
mod armsim;
use armsim::{Bus, Cpu};
use cverif::image::{Image, Segment};
use cverif::sym::{Ctx, Limits, Mem, Stop, UNINIT_EPOCH};
use cverif::term::{Env, Node, T};
use cverif::thumb::arch::{Fpu, Need, Profile, need};
use cverif::thumb::exec::{Callee, Exit, Machine};
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
const QEMU: &str = "qemu-system-arm";
const GCC: &str = "arm-none-eabi-gcc";
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
enum Arch {
V6M,
V7M,
V7EM,
V8MMain,
}
struct Target {
name: &'static str,
machine: &'static str,
flash: u32,
ram: u32,
arch: Arch,
}
impl Target {
fn profile(&self) -> Profile {
let p = Profile::from_cpu(self.name).unwrap();
match self.arch {
Arch::V7EM => p.with_fpu("fpv4-sp-d16").unwrap(),
Arch::V8MMain => p.with_fpu("fpv5-sp-d16").unwrap(),
_ => p,
}
}
}
const M0: Target = Target {
name: "cortex-m0",
machine: "microbit",
flash: 0,
ram: 0x2000_0000,
arch: Arch::V6M,
};
const M3: Target = Target {
name: "cortex-m3",
machine: "mps2-an385",
flash: 0,
ram: 0x2000_0000,
arch: Arch::V7M,
};
const M4: Target = Target {
name: "cortex-m4",
machine: "mps2-an386",
flash: 0,
ram: 0x2000_0000,
arch: Arch::V7EM,
};
const M33: Target = Target {
name: "cortex-m33",
machine: "mps2-an505",
flash: 0x1000_0000,
ram: 0x3800_0000,
arch: Arch::V8MMain,
};
const FIELD_LEN: u32 = 0x1000;
const WIN_LEN: u32 = 0x2000;
const CODE_MAX: usize = 64;
const MEM_MAX: usize = 64;
const OUT_WORDS: usize = 24;
const UDF_FILL: u16 = 0xdefe;
const MAGIC: u32 = 0x5145_4d55;
#[derive(Clone, Copy)]
struct Layout {
field: u32,
at: u32,
retpad: u32,
win: u32,
sp0: u32,
profile: Profile,
}
impl Layout {
fn of(t: &Target) -> Layout {
Layout {
field: t.ram,
at: t.ram + 0x800,
retpad: t.ram + FIELD_LEN - 2,
win: t.ram + FIELD_LEN,
sp0: t.ram + 0x2000,
profile: t.profile(),
}
}
fn has_fpu(&self) -> bool {
matches!(self.profile.fpu, Fpu::Present { .. })
}
fn in_field(&self, a: u32) -> bool {
a.wrapping_sub(self.field) < FIELD_LEN
}
fn in_win(&self, a: u32) -> bool {
a.wrapping_sub(self.win) < WIN_LEN
}
fn word(&self, a: u32, seed: u32) -> u32 {
if self.in_field(a) {
return (UDF_FILL as u32) << 16 | UDF_FILL as u32;
}
if a == self.sp0 - 4 {
return self.at | 1;
}
let mut x = a.wrapping_mul(0x9e37_79b1) ^ seed;
x ^= x >> 15;
x = x.wrapping_mul(0x85eb_ca77);
x ^= x >> 13;
x = x.wrapping_mul(0xc2b2_ae3d);
x ^= x >> 16;
x
}
fn byte(&self, a: u32, seed: u32) -> u8 {
(self.word(a & !3, seed) >> (8 * (a & 3))) as u8
}
fn field_image(&self, code: &[u8]) -> Vec<u8> {
let mut data = Vec::with_capacity(FIELD_LEN as usize);
while data.len() < FIELD_LEN as usize {
data.extend_from_slice(&UDF_FILL.to_le_bytes());
}
let o = (self.at - self.field) as usize;
data[o..o + code.len()].copy_from_slice(code);
data[o + code.len()..o + code.len() + 2].copy_from_slice(&0x4770u16.to_le_bytes());
data
}
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn chance(&mut self, num: u64, den: u64) -> bool {
self.below(den) < num
}
fn value(&mut self, lay: &Layout) -> u32 {
match self.below(16) {
0 => 0,
1 => 1,
2 => 0xffff_ffff,
3 => 0x8000_0000,
4 => 0x7fff_ffff,
5 => self.below(40) as u32,
6 => (self.below(64) as u32).wrapping_neg(),
7 => 1 << self.below(32),
8 => self.below(256) as u32 * 4,
9 => self.next() as u32 & 0xffff,
10 => self.next() as u32,
11 | 12 => (lay.win + 0x400 + self.below(0x1800) as u32) & !3,
13 => lay.win + 0x400 + self.below(0x1800) as u32,
_ => lay.win + 0xc00 + (self.below(0x200) as u32) * 4,
}
}
}
#[derive(Clone, Debug)]
struct State {
r: [u32; 15],
flags: [bool; 4], }
fn random_state(rng: &mut Rng, lay: &Layout) -> State {
let mut r = [0u32; 15];
for x in r.iter_mut() {
*x = rng.value(lay);
}
r[13] = lay.sp0;
r[14] = lay.retpad | 1;
let f = rng.next();
State {
r,
flags: [f & 1 != 0, f & 2 != 0, f & 4 != 0, f & 8 != 0],
}
}
fn is_wide(hw1: u16) -> bool {
hw1 >> 11 >= 0b11101
}
fn halfwords(code: &[u8]) -> Vec<u16> {
code.chunks(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect()
}
fn hex(code: &[u8]) -> String {
halfwords(code)
.iter()
.map(|h| format!("{h:04x}"))
.collect::<Vec<_>>()
.join(" ")
}
fn forbidden(code: &[u8]) -> bool {
if qemu_ldrh_hint_bug(code) {
return true;
}
let h = halfwords(code);
let mut i = 0;
while i < h.len() {
let w = h[i];
if w == 0xbeab || w == 0xbf20 || w == 0xbf30 || w & 0xffe8 == 0xb660 || w & 0xff07 == 0x4704 {
return true;
}
if is_wide(w) {
let w2 = *h.get(i + 1).unwrap_or(&0);
if w & 0xffe0 == 0xf380 && w2 & 0xd000 == 0x8000 {
return true;
}
if w & 0xfff0 == 0xf3a0 && w2 & 0xd700 == 0x8000 && matches!(w2 & 0xff, 2 | 3) {
return true;
}
i += 2;
} else {
i += 1;
}
}
false
}
fn push16(v: &mut Vec<u8>, hws: &[u16]) {
for hw in hws {
v.extend(hw.to_le_bytes());
}
}
fn near_branch(rng: &mut Rng, hw1: u16, hw2: u16) -> (u16, u16) {
let off = rng.below(0x600) as i32 - 0x300; let s = (off < 0) as u16;
if hw2 & 0x1000 == 0 && hw2 & 0x4000 == 0 {
let imm11 = off as u16 & 0x7ff;
let imm6 = (off >> 11) as u16 & 0x3f;
let (j1, j2) = (s, s);
(
hw1 & 0xfbc0 | s << 10 | imm6,
hw2 & 0xd000 | j1 << 13 | j2 << 11 | imm11,
)
} else {
let imm11 = off as u16 & 0x7ff;
let imm10 = (off >> 11) as u16 & 0x3ff;
let (i1, i2) = (s, s);
let (j1, j2) = (!(i1 ^ s) & 1, !(i2 ^ s) & 1);
(
hw1 & 0xf800 | s << 10 | imm10,
hw2 & 0xd000 | j1 << 13 | j2 << 11 | imm11,
)
}
}
fn rand32(rng: &mut Rng) -> Vec<u8> {
let x = rng.next();
let mut hw1 = 0xe800 | (x as u16 & 0x1fff);
if (hw1 & 0x0400 != 0 && hw1 >> 11 == 0b11101 || hw1 >> 10 == 0b111111) && !rng.chance(1, 8) {
hw1 &= !0x0400;
}
let mut hw2 = (x >> 16) as u16;
if hw1 >> 11 == 0b11110 && hw2 & 0x8000 != 0 && rng.chance(3, 4) {
(hw1, hw2) = near_branch(rng, hw1, hw2);
}
let mut v = Vec::new();
push16(&mut v, &[hw1, hw2]);
v
}
fn v6m_32(rng: &mut Rng) -> Vec<u8> {
let (hw1, hw2) = match rng.below(4) {
0 => near_branch(rng, 0xf000, 0xd000),
1 => (
0xf3ef,
0x8000 | (rng.below(16) as u16) << 8 | [0, 1, 2, 3, 5, 6, 7, 8, 9, 16, 20][rng.below(11) as usize],
),
2 => (0xf3bf, 0x8f40 | (rng.below(3) as u16) << 4 | 0xf),
_ => (0xf7f0 | rng.below(16) as u16, 0xa000 | rng.below(0x1000) as u16),
};
let mut v = Vec::new();
push16(&mut v, &[hw1, hw2]);
v
}
fn rand16(rng: &mut Rng, it_ok: bool) -> u16 {
loop {
let hw = rng.below(0xe800) as u16;
if hw & 0xff00 == 0xbf00 && hw & 0xf != 0 && !it_ok {
continue;
}
return hw;
}
}
fn mem16(rng: &mut Rng) -> u16 {
match rng.below(5) {
0 | 1 => 0x5000 + rng.below(0x5000) as u16,
2 => 0x4800 + rng.below(0x800) as u16,
3 => 0xc000 + rng.below(0x1000) as u16,
_ => [0xb400, 0xbc00][rng.below(2) as usize] | rng.below(0x200) as u16,
}
}
fn mem32(rng: &mut Rng) -> Vec<u8> {
let hw1 = if rng.chance(2, 3) {
0xf800 | rng.below(0x200) as u16
} else {
0xe800 | rng.below(0x200) as u16
};
let mut hw2 = rng.next() as u16;
if rng.chance(1, 2) {
hw2 &= 0xff0f; }
let mut v = Vec::new();
push16(&mut v, &[hw1, hw2]);
v
}
const NEAR: &[(u16, u16)] = &[
(0xf04f, 0x30ff),
(0xf100, 0x0c01),
(0xf1a0, 0x0210),
(0xf5b0, 0x7f80),
(0xf000, 0x0301),
(0xf080, 0x0003),
(0xf64c, 0x41cd),
(0xf6cc, 0x41cc),
(0xf2c0, 0x0100),
(0xeb00, 0x0081),
(0xeba0, 0x0043),
(0xea4f, 0x1030),
(0xea40, 0x2001),
(0xea6f, 0x0000),
(0xeb10, 0x0001),
(0xeb41, 0x0103),
(0xeb61, 0x0103),
(0xebc0, 0x00c0),
(0xebb0, 0x0f01),
(0xea10, 0x0f01),
(0xfa00, 0xf001),
(0xfa20, 0xf001),
(0xfa40, 0xf001),
(0xfa60, 0xf001),
(0xfa0f, 0xf080),
(0xfa1f, 0xf080),
(0xfa4f, 0xf080),
(0xfa5f, 0xf080),
(0xfa90, 0xf080),
(0xfa90, 0xf0a0),
(0xfab0, 0xf080),
(0xfb00, 0xf001),
(0xfb00, 0x2001),
(0xfb00, 0x2011),
(0xfb90, 0xf0f1),
(0xfbb0, 0xf0f1),
(0xfba0, 0x1201),
(0xfb80, 0x0101),
(0xfbe0, 0x1201),
(0xfbc0, 0x0101),
(0xfb10, 0xf001),
(0xfb10, 0x2011),
(0xf8d0, 0x0004),
(0xf8c0, 0x1004),
(0xf890, 0x0001),
(0xf8b0, 0x0002),
(0xf990, 0x0001),
(0xf9b0, 0x0002),
(0xf850, 0x0021),
(0xf840, 0x1022),
(0xf850, 0x1b04),
(0xf840, 0x1d04),
(0xf85d, 0x7b04),
(0xf84d, 0x7d04),
(0xf810, 0x1f01),
(0xf800, 0x1c01),
(0xf8df, 0x0010),
(0xf85f, 0x0004),
(0xe9d0, 0x0102),
(0xe9c0, 0x0102),
(0xe8f0, 0x0102),
(0xe9e0, 0x0102),
(0xe8bd, 0x41f0),
(0xe92d, 0x41f0),
(0xe890, 0x000e),
(0xe8a0, 0x000e),
(0xe8b0, 0x000e),
(0xe930, 0x000e),
(0xe8df, 0xf001),
(0xe8df, 0xf011),
(0xf360, 0x0107),
(0xf36f, 0x0107),
(0xf3c0, 0x1003),
(0xf340, 0x1003),
(0xf300, 0x0007),
(0xf380, 0x0008),
(0xf1c0, 0x0000),
(0xf140, 0x0000),
(0xf160, 0x0000),
(0xf110, 0x0f01),
(0xf090, 0x0f01),
(0xf010, 0x0f01),
(0xf060, 0x0001),
(0xf020, 0x0001),
(0xf44f, 0x7080),
(0xf06f, 0x0001),
(0xf20f, 0x0004),
(0xf2af, 0x0004),
(0xf200, 0x0001),
(0xf2a0, 0x0001),
(0xea5f, 0x0030),
(0xea5f, 0x0050),
(0xf3af, 0x8000),
(0xf7f0, 0xa000),
(0xfb20, 0x0001),
(0xfb30, 0x0001),
(0xfb40, 0x0001),
(0xfac0, 0xf080),
(0xfa80, 0xf000),
];
fn near_compiler(rng: &mut Rng) -> Vec<u8> {
let (hw1, hw2) = NEAR[rng.below(NEAR.len() as u64) as usize];
let word = (hw1 as u32) << 16 | hw2 as u32;
let v = match rng.below(3) {
0 => word ^ 1 << rng.below(32),
1 => word ^ 1 << rng.below(32) ^ 1 << rng.below(32),
_ => word ^ (rng.next() as u32 & 0x000f_7fff),
};
let (mut a, b) = ((v >> 16) as u16, v as u16);
if !is_wide(a) {
a = hw1;
}
let mut out = Vec::new();
push16(&mut out, &[a, b]);
out
}
const BODY: &[&[u16]] = &[
&[0x1840],
&[0x1a40],
&[0x3001],
&[0x3801],
&[0x2105],
&[0x4048],
&[0x4308],
&[0x43c8],
&[0x4088],
&[0x4108],
&[0x4148],
&[0x4188],
&[0x4248],
&[0x4348],
&[0x0048],
&[0x1048],
&[0x4288],
&[0x42c8],
&[0x2800],
&[0x4608],
&[0x6808],
&[0x6008],
&[0xb2c8],
&[0xf04f, 0x0801],
&[0xf110, 0x0001],
&[0xeb10, 0x0041],
&[0xfb00, 0xf001],
&[0xf1b0, 0x0f05],
&[0xea5f, 0x0040],
&[0xf850, 0x1b04],
&[0xbf00],
&[0xdefe],
&[0x4770],
&[0xe7fe],
];
fn it_block(rng: &mut Rng) -> Vec<u8> {
let cond = rng.below(15) as u16;
let mask = 1 + rng.below(15) as u16;
let len = 4 - mask.trailing_zeros() as usize;
let mut code = Vec::new();
push16(&mut code, &[0xbf00 | cond << 4 | mask]);
for _ in 0..len {
let b = BODY[rng.below(BODY.len() as u64) as usize];
push16(&mut code, b);
}
code
}
const PRODUCERS: &[&[u16]] = &[
&[0x1840],
&[0x1a40],
&[0x4288],
&[0x42c8],
&[0x4208],
&[0x0048],
&[0x0848],
&[0x1048],
&[0x4088],
&[0x40c8],
&[0x4108],
&[0x41c8],
&[0x4248],
&[0x4348],
&[0x2800],
&[0x4148],
&[0x4188],
&[0xf110, 0x0f01],
&[0xf1b0, 0x0f05],
&[0xebb0, 0x0f41],
&[0xea10, 0x7f01],
&[0xea90, 0x0f31],
&[0xea5f, 0x0031],
&[0xea5f, 0x0071],
&[0xfa10, 0xf001],
&[0xfa30, 0xf001],
&[0xfa50, 0xf001],
&[0xfa70, 0xf001],
&[0xf090, 0x4f00],
&[0xf010, 0x0fff],
&[0xf5b0, 0x3f80],
&[0xeb50, 0x0001],
&[0xeb70, 0x0001],
&[0xf1d0, 0x0000],
&[0xf150, 0x0000],
&[0xf170, 0x0000],
&[0xebd0, 0x0001],
];
const CONSUMERS: &[&[u16]] = &[
&[0x4148],
&[0x4188],
&[0x41c8],
&[0xeb41, 0x0002],
&[0xeb61, 0x0002],
&[0xea4f, 0x0030],
&[0xea5f, 0x0030],
&[0xf141, 0x0100],
&[0xf161, 0x0100],
&[0xd000],
&[0xd100],
&[0xd200],
&[0xd300],
&[0xd400],
&[0xd500],
&[0xd600],
&[0xd700],
&[0xd800],
&[0xd900],
&[0xda00],
&[0xdb00],
&[0xdc00],
&[0xdd00],
&[0xf000, 0x8000],
&[0xf040, 0x8000],
&[0xf280, 0x8000],
&[0xf2c0, 0x8000],
&[0xf300, 0x8000],
&[0xf340, 0x8000],
&[0xf200, 0x8000],
&[0xf240, 0x8000],
];
fn flag_chain(rng: &mut Rng, thumb1: bool) -> Vec<u8> {
loop {
let p = PRODUCERS[rng.below(PRODUCERS.len() as u64) as usize];
let c = CONSUMERS[rng.below(CONSUMERS.len() as u64) as usize];
if thumb1 && (p.len() > 1 || c.len() > 1) {
continue;
}
let mut code = Vec::new();
push16(&mut code, p);
push16(&mut code, c);
push16(&mut code, &[0x3701]); return code;
}
}
fn fp_op(rng: &mut Rng) -> Vec<u8> {
let x = rng.next();
let hw1 = 0xee00 | (x as u16 & 0xff);
let hw2 = ((x >> 16) as u16 & 0xf1ef) | 0x0a00;
let double = hw2 & 0x100 != 0;
let (d, vd) = ((hw1 >> 6) & 1, hw2 >> 12);
let s = if double { 2 * (d << 4 | vd) } else { vd << 1 | d };
let mut v = Vec::new();
push16(&mut v, &[hw1, hw2]);
for (rt, sn) in [(0u16, s), (1, s + 1)].into_iter().take(1 + double as usize) {
if sn < 32 {
push16(&mut v, &[0xee10 | sn >> 1, rt << 12 | 0x0a10 | (sn & 1) << 7]);
}
}
if rng.chance(1, 4) {
push16(&mut v, &[0xeef1, 0xfa10]);
}
v
}
fn gen_code(rng: &mut Rng, arch: Arch) -> (Vec<u8>, &'static str) {
loop {
let (code, class) = if arch == Arch::V6M {
match rng.below(20) {
0..=6 => {
let it = rng.chance(1, 20);
(rand16(rng, it).to_le_bytes().to_vec(), "16-bit")
}
7..=10 => (mem16(rng).to_le_bytes().to_vec(), "16-bit memory"),
11..=13 => (flag_chain(rng, true), "flag chain"),
14 | 15 => {
let mut v = Vec::new();
for _ in 0..2 + rng.below(2) {
push16(&mut v, &[rand16(rng, false)]);
}
(v, "16-bit sequence")
}
16..=18 => (v6m_32(rng), "ARMv6-M 32-bit"),
_ => (rand32(rng), "32-bit"),
}
} else {
match rng.below(20) {
0..=3 => (rand16(rng, false).to_le_bytes().to_vec(), "16-bit"),
4..=8 => (rand32(rng), "32-bit"),
9 | 10 => (near_compiler(rng), "near-compiler 32-bit"),
11 | 12 => (it_block(rng), "IT block"),
13 | 14 => (flag_chain(rng, false), "flag chain"),
15 | 16 => (mem16(rng).to_le_bytes().to_vec(), "16-bit memory"),
17 => (fp_op(rng), "floating point"),
_ => (mem32(rng), "32-bit memory"),
}
};
if !forbidden(&code) && code.len() <= CODE_MAX - 4 {
return (code, class);
}
}
}
struct WinMem {
lay: Layout,
seed: u32,
field: Vec<u8>,
written: HashMap<u32, u8>,
initial_reads: HashMap<u32, u8>,
outside: bool,
misaligned: bool,
}
impl Bus for WinMem {
fn read(&mut self, a: u32, size: u32) -> u32 {
self.misaligned |= !a.is_multiple_of(size);
(0..size).fold(0, |v, i| v | (self.read8(a.wrapping_add(i)) as u32) << (8 * i))
}
fn write(&mut self, a: u32, size: u32, v: u32) {
self.misaligned |= !a.is_multiple_of(size);
for i in 0..size {
self.write8(a.wrapping_add(i), (v >> (8 * i)) as u8);
}
}
fn read8(&mut self, a: u32) -> u8 {
if let Some(&v) = self.written.get(&a) {
return v;
}
let v = if self.lay.in_field(a) {
self.field[(a - self.lay.field) as usize]
} else if self.lay.in_win(a) {
self.lay.byte(a, self.seed)
} else {
self.outside = true;
0
};
self.initial_reads.insert(a, v);
v
}
fn write8(&mut self, a: u32, v: u8) {
if !self.lay.in_win(a) {
self.outside = true;
}
self.written.insert(a, v);
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum End {
Return,
Trap(u32),
Left,
Fault {
pc: u32,
cfsr: u32,
hfsr: u32,
ipsr: u32,
},
}
#[derive(Clone, Debug)]
struct Outcome {
end: End,
r: [u32; 15],
flags: Option<[bool; 4]>,
mem: BTreeMap<u32, u8>,
}
struct Reference {
out: Outcome,
reads: HashMap<u32, u8>,
misaligned: bool,
}
fn run_armsim(lay: &Layout, seed: u32, field: &[u8], st: &State) -> Result<Option<Reference>, armsim::Stop> {
let mut mem = WinMem {
lay: *lay,
seed,
field: field.to_vec(),
written: HashMap::new(),
initial_reads: HashMap::new(),
outside: false,
misaligned: false,
};
let mut cpu = Cpu::new();
cpu.r[..15].copy_from_slice(&st.r);
(cpu.n, cpu.z, cpu.c, cpu.v) = (st.flags[0], st.flags[1], st.flags[2], st.flags[3]);
cpu.pc = lay.at;
let mut steps = 0;
let end = loop {
if cpu.pc == lay.retpad {
break End::Return;
}
if !lay.in_field(cpu.pc) {
return Ok(None);
}
steps += 1;
if steps > 40 {
return Ok(None);
}
let at = cpu.pc;
match cpu.step(&mut mem) {
Ok(()) => {}
Err(armsim::Stop::Udf) => break End::Trap(at),
Err(armsim::Stop::Unaligned(_)) => {
mem.misaligned = true;
break End::Trap(at);
}
Err(e) => return Err(e),
}
if mem.outside {
return Ok(None);
}
};
let sp = cpu.r[13];
if !(lay.win + 0x100..=lay.win + WIN_LEN).contains(&sp) || mem.outside {
return Ok(None);
}
let mut r = [0u32; 15];
r.copy_from_slice(&cpu.r[..15]);
Ok(Some(Reference {
out: Outcome {
end,
r,
flags: Some([cpu.n, cpu.z, cpu.c, cpu.v]),
mem: mem.written.into_iter().collect(),
},
reads: mem.initial_reads,
misaligned: mem.misaligned,
}))
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Mode {
Concrete,
Pinned,
PrivateStack,
}
fn sym_id(ctx: &Ctx, t: T) -> u32 {
match ctx.tm.node(t) {
Node::Sym(id) => *id,
n => panic!("not a symbol: {n:?}"),
}
}
struct ExecRun {
end: End,
r: [u32; 15],
trace: Vec<u32>,
mem: BTreeMap<u32, u8>,
}
fn run_exec(
lay: &Layout,
seed: u32,
code: &[u8],
st: &State,
mode: Mode,
reads: &HashMap<u32, u8>,
) -> Result<ExecRun, String> {
let image = {
let mut built = Image::default();
built.segments = vec![{
let mut seg = Segment::new(".text", lay.field, lay.field_image(code));
seg.exec = true;
seg
}];
built
};
let mut ctx = Ctx::new(Limits::default());
ctx.set_budget(u64::MAX, 2_000_000, Some(Instant::now() + Duration::from_secs(2)));
let mut env = Env::default();
for (&a, &b) in reads {
env.mem.insert((0, a as u64), b);
env.mem.insert((UNINIT_EPOCH, a as u64), b);
}
let mut regs = [0 as T; 16];
for i in 0..15 {
let k = ctx.tm.konst(32, st.r[i] as u64);
regs[i] = match mode {
Mode::Concrete => k,
_ if i == 14 => k,
Mode::PrivateStack if i == 13 => {
let s = ctx.private_base("SP0");
env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
let low = ctx.tm.extract(s, 0, 3);
let zero = ctx.tm.konst(3, 0);
let aligned = ctx.tm.eq(low, zero);
ctx.pc.push(aligned);
s
}
_ => {
let s = ctx.named_sym(&format!("r{i}"), 32);
env.syms.insert(sym_id(&ctx, s), st.r[i] as u64);
let e = ctx.tm.eq(s, k);
ctx.pc.push(e);
s
}
};
}
regs[15] = ctx.tm.konst(32, 0);
let facts = reads.len() < WIN_LEN as usize;
for (&a, &b) in reads.iter().filter(|_| facts) {
let k = ctx.tm.konst(8, b as u64);
let addr = ctx.tm.konst(32, a as u64);
let l = ctx.tm.load(0, addr, 1);
let e = ctx.tm.eq(l, k);
ctx.pc.push(e);
if mode == Mode::PrivateStack && a.wrapping_sub(st.r[13]).wrapping_add(0x1000) < 0x2000 {
let addr = ctx
.tm
.add_const(regs[13], a.wrapping_sub(st.r[13]) as i32 as i64 as u64);
let l = ctx.tm.load(UNINIT_EPOCH, addr, 1);
let e = ctx.tm.eq(l, k);
ctx.pc.push(e);
}
}
let lr0 = regs[14];
let mut m = Machine::new(&mut ctx, lay.at, regs);
m.profile = lay.profile;
if lay.has_fpu() {
for i in 0..32 {
m.fregs[i] = ctx.tm.konst(32, lay.word(lay.win + 4 * i as u32, seed) as u64);
}
for name in ["fpflag.n", "fpflag.z", "fpflag.c", "fpflag.v"] {
let s = ctx.named_sym(name, 1);
env.syms.insert(sym_id(&ctx, s), 0);
let k = ctx.tm.konst(1, 0);
let e = ctx.tm.eq(s, k);
ctx.pc.push(e);
}
}
for (name, v) in ["flag.n", "flag.z", "flag.c", "flag.v"].iter().zip(st.flags) {
let s = ctx.named_sym(name, 1);
env.syms.insert(sym_id(&ctx, s), v as u64);
let k = ctx.tm.konst(1, v as u64);
let e = ctx.tm.eq(s, k);
ctx.pc.push(e);
}
let field = lay.field;
let classify = move |addr: u32| {
if addr.wrapping_sub(field) < FIELD_LEN {
Callee::Internal
} else {
Callee::External("elsewhere".into())
}
};
let exit = m.run(&mut ctx, &image, lr0, &classify);
let trace: Vec<u32> = m.covered.iter().map(|c| c.0).collect();
let end = match exit {
Ok(Exit::Return) => End::Return,
Ok(Exit::Asm { .. }) => return Err("system instruction".into()),
Ok(Exit::Call { .. }) => End::Left,
Ok(Exit::Trap) => End::Trap(*trace.last().unwrap_or(&0)),
Ok(Exit::Cut(_)) => return Err("loop cut point".into()),
Ok(Exit::Hang) => return Err("endless loop".into()),
Ok(_) => return Err("unmodelled exit".into()),
Err(Stop::Unsupported(s)) => {
let s = s.split(" at ").next().unwrap_or("");
return Err(format!("unsupported: {}", s.split(" 0x").next().unwrap_or("")));
}
Err(e) => return Err(format!("{e:?}")),
};
if !ctx.decisions.is_empty() {
return Err("forked".into());
}
let mut memo = HashMap::new();
let mut r = [0u32; 15];
for i in 0..15 {
r[i] = ctx.tm.eval(m.regs[i], &env, &mut memo) as u32;
}
let mut mem = BTreeMap::new();
let Mem { world, private, .. } = &m.mem;
for log in std::iter::once(world).chain(private.values()) {
for w in log {
let a = ctx.tm.eval(w.addr, &env, &mut memo) as u32;
let v = ctx.tm.eval(w.val, &env, &mut memo);
for i in 0..w.size as u32 {
mem.insert(a.wrapping_add(i), (v >> (8 * i)) as u8);
}
}
}
Ok(ExecRun { end, r, trace, mem })
}
fn flag_probe() -> Vec<u8> {
let mut v = Vec::new();
for (i, cond) in [0u16, 2, 4, 6].into_iter().enumerate() {
let rd = 8 + i as u16;
push16(&mut v, &[0xbf0c | cond << 4, 0xf04f, rd << 8 | 1, 0xf04f, rd << 8]);
}
v
}
fn executor_outcome(
lay: &Layout,
seed: u32,
code: &[u8],
st: &State,
mode: Mode,
reads: &HashMap<u32, u8>,
) -> Result<Outcome, String> {
let plain = run_exec(lay, seed, code, st, mode, reads)?;
let mut flags = None;
let fall = lay.at + code.len() as u32;
if plain.end == End::Return && plain.trace.last() == Some(&fall) {
let mut probed = code.to_vec();
probed.extend(flag_probe());
let any = Layout {
profile: {
let mut built = Profile::ANY;
built.fpu = lay.profile.fpu;
built
},
..*lay
};
if let Ok(p) = run_exec(&any, seed, &probed, st, mode, reads)
&& p.trace.last() == Some(&(fall + flag_probe().len() as u32))
&& p.trace[..plain.trace.len() - 1] == plain.trace[..plain.trace.len() - 1]
&& p.r[..8] == plain.r[..8]
&& p.r[12..] == plain.r[12..]
&& p.mem == plain.mem
{
flags = Some([p.r[10] == 1, p.r[8] == 1, p.r[9] == 1, p.r[11] == 1]);
}
}
Ok(Outcome {
end: plain.end,
r: plain.r,
flags,
mem: plain.mem,
})
}
fn have(tool: &str) -> bool {
Command::new(tool)
.arg("--version")
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.map(|s| s.success())
.unwrap_or(false)
}
fn workdir(t: &Target) -> PathBuf {
let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("qemu_diff").join(t.name);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn build_harness(t: &Target) -> PathBuf {
let dir = workdir(t);
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/qemu");
let ld = dir.join("link.ld");
std::fs::write(
&ld,
format!(
"MEMORY {{ FLASH (rx) : ORIGIN = {:#x}, LENGTH = 0x40000\n\
RAM (rw) : ORIGIN = {:#x}, LENGTH = 0x800 }}\n\
SECTIONS {{\n\
.text : {{ KEEP(*(.vectors)) *(.text*) *(.rodata*) }} > FLASH\n\
.bss (NOLOAD) : {{ __bss_start = .; *(.bss*) *(COMMON) . = ALIGN(4); __bss_end = .; }} > RAM\n\
.data : {{ *(.data*) }} > RAM\n\
/DISCARD/ : {{ *(.ARM.exidx*) *(.comment) }}\n}}\n",
t.flash,
t.ram + 0x3000
),
)
.unwrap();
let elf = dir.join("harness.elf");
let part = dir.join(format!("harness.elf.{}", std::process::id()));
let mut cmd = Command::new(GCC);
cmd.args([
"-mcpu=cortex-m0",
"-mthumb",
"-O2",
"-ffreestanding",
"-fno-builtin",
"-nostdlib",
])
.arg(format!("-DRAM_BASE={:#x}", t.ram))
.arg("-T")
.arg(&ld)
.arg(src.join("harness.c"))
.arg(src.join("harness.S"))
.arg("-lgcc")
.arg("-o")
.arg(&part);
if t.arch != Arch::V6M {
cmd.arg("-DHAS_CFSR");
}
if Layout::of(t).has_fpu() {
cmd.arg("-DHAS_FPU");
}
let out = cmd.output().expect("run arm-none-eabi-gcc");
assert!(
out.status.success(),
"building the harness failed:\n{}",
String::from_utf8_lossy(&out.stderr)
);
std::fs::rename(&part, &elf).unwrap();
elf
}
struct Case {
code: Vec<u8>,
class: &'static str,
st: State,
reference: Option<Reference>,
}
#[derive(Debug)]
struct QemuOut {
regs: [u32; OUT_WORDS],
mem: Vec<(u32, u32)>,
mem_total: u32,
}
fn run_qemu(t: &Target, elf: &Path, batch: usize, seed: u32, cases: &[Case]) -> Result<Vec<QemuOut>, String> {
let dir = workdir(t).join(format!("batch{batch}"));
std::fs::create_dir_all(&dir).unwrap();
let mut input = Vec::new();
for w in [MAGIC, cases.len() as u32, seed, 0] {
input.extend(w.to_le_bytes());
}
for c in cases {
for w in c.st.r {
input.extend(w.to_le_bytes());
}
let apsr = (c.st.flags[0] as u32) << 31
| (c.st.flags[1] as u32) << 30
| (c.st.flags[2] as u32) << 29
| (c.st.flags[3] as u32) << 28;
input.extend(apsr.to_le_bytes());
input.extend((c.code.len() as u32).to_le_bytes());
let mut code = c.code.clone();
code.resize(CODE_MAX, 0);
input.extend(code);
}
std::fs::write(dir.join("cases.in"), &input).unwrap();
let _ = std::fs::remove_file(dir.join("cases.out"));
let mut child = Command::new(QEMU)
.current_dir(&dir)
.args([
"-M", t.machine, "-display", "none", "-monitor", "none", "-serial", "none",
])
.args(["-semihosting-config", "enable=on,target=native"])
.arg("-kernel")
.arg(elf)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("cannot start {QEMU}: {e}"))?;
let deadline = Instant::now() + Duration::from_secs(120);
let status = loop {
if let Some(s) = child.try_wait().unwrap() {
break s;
}
if Instant::now() > deadline {
let _ = child.kill();
let _ = child.wait();
return Err("QEMU timed out".into());
}
std::thread::sleep(Duration::from_millis(20));
};
let out = child.wait_with_output().unwrap();
let data = std::fs::read(dir.join("cases.out")).unwrap_or_default();
let words: Vec<u32> = data.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c)).collect();
let mut res = Vec::new();
let mut i = 0;
while i + 2 + OUT_WORDS <= words.len() {
let (total, n) = (words[i], words[i + 1] as usize);
let mut regs = [0; OUT_WORDS];
regs.copy_from_slice(&words[i + 2..i + 2 + OUT_WORDS]);
i += 2 + OUT_WORDS;
let mem = (0..n).map(|k| (words[i + 2 * k], words[i + 2 * k + 1])).collect();
i += 2 * n;
res.push(QemuOut {
regs,
mem,
mem_total: total,
});
}
if res.len() != cases.len() {
let stuck = &cases[res.len().min(cases.len() - 1)];
return Err(format!(
"QEMU ({status}) returned {} results for {} cases (case {}: {} from {:x?}); stderr: {}",
res.len(),
cases.len(),
res.len(),
hex(&stuck.code),
stuck.st,
String::from_utf8_lossy(&out.stderr)
));
}
Ok(res)
}
const UNDEFINSTR: u32 = 1 << 16;
const INVSTATE: u32 = 1 << 17;
const NOCP: u32 = 1 << 19;
const UNALIGNED: u32 = 1 << 24;
const PRECISERR: u32 = 1 << 9;
const IMPRECISERR: u32 = 1 << 10;
const DIVBYZERO: u32 = 1 << 25;
fn fault_name(cfsr: u32, ipsr: u32) -> String {
let mut v = Vec::new();
for (bit, name) in [
(UNDEFINSTR, "UNDEFINSTR"),
(INVSTATE, "INVSTATE"),
(1 << 18, "INVPC"),
(NOCP, "NOCP"),
(UNALIGNED, "UNALIGNED"),
(DIVBYZERO, "DIVBYZERO"),
(1 << 8, "IBUSERR"),
(PRECISERR, "PRECISERR"),
(IMPRECISERR, "IMPRECISERR"),
(1 << 12, "STKERR"),
(1 << 0, "IACCVIOL"),
(1 << 1, "DACCVIOL"),
] {
if cfsr & bit != 0 {
v.push(name);
}
}
if v.is_empty() {
format!("exception {ipsr}")
} else {
v.join("+")
}
}
fn qemu_outcome(lay: &Layout, arch: Arch, q: &QemuOut) -> (Outcome, (u32, u32)) {
let g = &q.regs;
let (pc, xpsr, cfsr, ipsr, frame) = (g[15], g[16], g[17], g[20], g[21]);
let sp = g[13];
let end = if ipsr == 3 && pc == lay.retpad && (arch == Arch::V6M || cfsr == UNDEFINSTR) {
End::Return
} else if ipsr == 3 && (arch == Arch::V6M || matches!(cfsr, UNDEFINSTR | NOCP | UNALIGNED)) {
End::Trap(pc)
} else {
End::Fault {
pc,
cfsr,
hfsr: g[18],
ipsr,
}
};
let mut r = [0u32; 15];
r[..13].copy_from_slice(&g[..13]);
r[13] = sp;
r[14] = g[14];
let mut mem = BTreeMap::new();
for &(a, v) in &q.mem {
for i in 0..4 {
mem.insert(a + i, (v >> (8 * i)) as u8);
}
}
(
Outcome {
end,
r,
flags: Some([
xpsr >> 31 & 1 != 0,
xpsr >> 30 & 1 != 0,
xpsr >> 29 & 1 != 0,
xpsr >> 28 & 1 != 0,
]),
mem,
},
(frame, sp),
)
}
fn changed_words(lay: &Layout, seed: u32, writes: &BTreeMap<u32, u8>, skip: (u32, u32)) -> BTreeMap<u32, u32> {
let words: std::collections::BTreeSet<u32> = writes.keys().map(|a| a & !3).collect();
let mut out = BTreeMap::new();
for &w in &words {
if (skip.0..skip.1).contains(&w) {
continue;
}
let mut v = lay.word(w, seed);
for i in 0..4 {
if let Some(&b) = writes.get(&(w + i)) {
v = v & !(0xff << (8 * i)) | (b as u32) << (8 * i);
}
}
if v != lay.word(w, seed) {
out.insert(w, v);
}
}
out
}
fn differences(lay: &Layout, seed: u32, want: &Outcome, got: &Outcome, skip: (u32, u32)) -> Vec<String> {
let mut d = Vec::new();
let end = if got.end == End::Trap(lay.retpad) {
End::Return
} else {
got.end
};
if want.end != end {
d.push(format!("end: QEMU {:x?}, model {:x?}", want.end, got.end));
return d;
}
for i in 0..15 {
if want.r[i] != got.r[i] {
d.push(format!("r{i}: QEMU {:#x}, model {:#x}", want.r[i], got.r[i]));
}
}
if let (Some(a), Some(b)) = (want.flags, got.flags)
&& a != b
{
d.push(format!("nzcv: QEMU {a:?}, model {b:?}"));
}
let (mw, mg) = (
changed_words(lay, seed, &want.mem, skip),
changed_words(lay, seed, &got.mem, skip),
);
if mw != mg {
let keys: std::collections::BTreeSet<u32> = mw.keys().chain(mg.keys()).copied().collect();
for a in keys.into_iter().filter(|a| mw.get(a) != mg.get(a)).take(4) {
d.push(format!("mem[{a:#x}]: QEMU {:x?}, model {:x?}", mw.get(&a), mg.get(&a)));
}
}
d
}
fn arch_lacks(p: &Profile, code: &[u8]) -> bool {
let h = halfwords(code);
let mut i = 0;
while i < h.len() {
let w = h[i] as u32;
let wide = is_wide(h[i]);
let w2 = wide.then(|| h.get(i + 1).copied().unwrap_or(0) as u32);
if p.allows(need(w, w2)) != Some(true) {
return true;
}
i += if wide { 2 } else { 1 };
}
false
}
fn qemu_m0_runs_thumb2(code: &[u8]) -> bool {
halfwords(code)
.iter()
.any(|&w| w & 0xf500 == 0xb100 || (w & 0xff00 == 0xbf00 && w & 0xf != 0))
}
fn qemu_m3_runs_dsp(code: &[u8]) -> bool {
let h = halfwords(code);
let mut i = 0;
while i < h.len() {
let w = h[i];
if is_wide(w) {
let w2 = h.get(i + 1).copied().unwrap_or(0) as u32;
if need(w as u32, Some(w2)) == Need::Dsp {
return true;
}
i += 2;
} else {
i += 1;
}
}
false
}
#[derive(Default)]
struct Tally {
cases: usize,
armsim_compared: usize,
exec_compared: usize,
exec_declined: usize,
exec_only: usize,
classes: BTreeMap<(String, String, String), (usize, Vec<String>)>,
known: usize,
unexpected: usize,
}
impl Tally {
fn record(&mut self, who: &str, what: String, class: String, known: bool, example: String) {
if known {
self.known += 1;
} else {
self.unexpected += 1;
}
let tag = if known { "known" } else { "UNEXPECTED" };
let e = self
.classes
.entry((tag.to_string(), format!("{who}: {what}"), class))
.or_default();
e.0 += 1;
if e.1.len() < 3 {
e.1.push(example);
}
}
}
fn enc_class(code: &[u8]) -> String {
let hw1 = u16::from_le_bytes([code[0], code[1]]);
if is_wide(hw1) {
format!("{:03x}x", hw1 >> 4)
} else {
format!("{:02x}xx", hw1 >> 8)
}
}
fn compare_case(t: &Target, lay: &Layout, seed: u32, c: &Case, q: &QemuOut, mode: Mode, tally: &mut Tally) {
tally.cases += 1;
let (want, skip) = qemu_outcome(lay, t.arch, q);
let cfsr = q.regs[17];
let ipsr = q.regs[20];
let example = |d: &[String]| {
format!(
"{} [{}] regs {:x?} nzcv {:?} ({mode:?})\n {}",
hex(&c.code),
c.class,
c.st.r,
c.st.flags,
d.join("\n ")
)
};
let lacks = arch_lacks(&lay.profile, &c.code);
let known_kind = |who: &str, want: &Outcome| -> Option<String> {
let name = fault_name(cfsr, ipsr);
let exception = !matches!(want.end, End::Return);
if who == "armsim" && exception && lacks {
return Some(format!("{name}: instruction not in {:?} (armsim has them all)", t.arch));
}
if who == "executor" && t.arch == Arch::V6M && qemu_m0_runs_thumb2(&c.code) {
return Some("QEMU executes CBZ / CBNZ / IT on the Cortex-M0".into());
}
if who == "executor" && t.arch == Arch::V7M && qemu_m3_runs_dsp(&c.code) {
return Some("QEMU executes DSP instructions on the Cortex-M3".into());
}
if who == "executor" && c.reference.is_none() && cfsr & (PRECISERR | IMPRECISERR) != 0 {
return Some(format!("{name}: read outside the harness's memory"));
}
if exception && t.arch == Arch::V6M && unaligned_access(c) {
return Some(format!("{name}: misaligned access (ARMv6-M) not modelled"));
}
if cfsr == UNALIGNED && who == "executor" && mode != Mode::Concrete {
return Some(format!("{name}: alignment of a symbolic address not decided"));
}
None
};
if q.mem_total as usize > MEM_MAX {
tally.record(
"harness",
"too many memory writes".into(),
enc_class(&c.code),
false,
example(&[]),
);
return;
}
if let Some(r) = &c.reference {
tally.armsim_compared += 1;
let d = differences(lay, seed, &want, &r.out, skip);
if !d.is_empty() {
let known = known_kind("armsim", &want);
let what = known
.clone()
.unwrap_or_else(|| d[0].split(':').next().unwrap_or("").to_string());
tally.record("armsim", what, enc_class(&c.code), known.is_some(), example(&d));
}
}
if c.reference.is_none() {
tally.exec_only += 1;
}
let reads = c
.reference
.as_ref()
.map(|r| r.reads.clone())
.unwrap_or_else(|| full_window(lay, seed));
match executor_outcome(lay, seed, &c.code, &c.st, mode, &reads) {
Err(_) => tally.exec_declined += 1,
Ok(got) => {
tally.exec_compared += 1;
let d = differences(lay, seed, &want, &got, skip);
if !d.is_empty() {
let known = known_kind("executor", &want).or_else(|| {
(c.class == "floating point" && nan_results(&d, &want, &got))
.then(|| "NaN result: which NaN is left open by the model".to_string())
});
let what = known
.clone()
.unwrap_or_else(|| d[0].split(':').next().unwrap_or("").to_string());
tally.record("executor", what, enc_class(&c.code), known.is_some(), example(&d));
}
}
}
}
fn nan_results(d: &[String], want: &Outcome, got: &Outcome) -> bool {
let nan32 = |w: u32| w & 0x7f80_0000 == 0x7f80_0000 && w & 0x007f_ffff != 0;
let nan64 = |lo: u32, hi: u32| hi & 0x7ff0_0000 == 0x7ff0_0000 && (hi & 0x000f_ffff != 0 || lo != 0);
let nan = |o: &Outcome| nan32(o.r[0]) || nan64(o.r[0], o.r[1]);
d.iter().all(|l| l.starts_with("r0:") || l.starts_with("r1:")) && nan(want) && nan(got)
}
fn unaligned_access(c: &Case) -> bool {
match &c.reference {
Some(r) => r.misaligned,
None => true,
}
}
fn full_window(lay: &Layout, seed: u32) -> HashMap<u32, u8> {
(lay.win..lay.win + WIN_LEN).map(|a| (a, lay.byte(a, seed))).collect()
}
fn cases_per_core() -> usize {
std::env::var("CVERIF_QEMU_CASES")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(10000)
}
fn generate(t: &Target, seed: u64, n: usize, batch_seed: u32) -> (Vec<Case>, BTreeMap<&'static str, usize>) {
let lay = Layout::of(t);
let mut rng = Rng(seed);
let mut cases = Vec::new();
let mut dropped: BTreeMap<&'static str, usize> = BTreeMap::new();
while cases.len() < n {
let (code, class) = gen_code(&mut rng, t.arch);
let st = random_state(&mut rng, &lay);
let field = lay.field_image(&code);
match run_armsim(&lay, batch_seed, &field, &st) {
Ok(Some(r)) => cases.push(Case {
code,
class,
st,
reference: Some(r),
}),
Ok(None) => *dropped.entry("leaves the harness's memory or loops").or_default() += 1,
Err(armsim::Stop::Event(_) | armsim::Stop::ArmState(_)) => {
*dropped
.entry("system instruction (BKPT, SVC, ...), switch to ARM state")
.or_default() += 1
}
Err(_) => {
let reads = full_window(&lay, batch_seed);
let any = Layout {
profile: {
let mut built = Profile::ANY;
built.fpu = lay.profile.fpu;
built
},
..lay
};
let stays = |l: &Layout| {
run_exec(l, batch_seed, &code, &st, Mode::Concrete, &reads).is_ok_and(|x| {
matches!(x.end, End::Return | End::Trap(_))
&& x.mem.keys().all(|&a| lay.in_win(a))
&& (lay.win + 0x100..=lay.win + WIN_LEN).contains(&x.r[13])
})
};
if stays(&lay) && stays(&any) {
cases.push(Case {
code,
class,
st,
reference: None,
});
} else {
*dropped
.entry("not modelled by armsim, declined by the executor")
.or_default() += 1;
}
}
}
}
(cases, dropped)
}
fn campaign(t: &Target, seed: u64) {
if !have(QEMU) || !have(GCC) {
eprintln!("{}: {QEMU} or {GCC} not installed, skipped", t.name);
return;
}
let started = Instant::now();
let elf = build_harness(t);
let lay = Layout::of(t);
let total = cases_per_core();
let batch_size = 1500;
let batches = total.div_ceil(batch_size);
let threads = 2;
let results: Vec<(Tally, BTreeMap<&'static str, usize>)> = std::thread::scope(|s| {
let handles: Vec<_> = (0..threads)
.map(|k| {
let elf = &elf;
s.spawn(move || {
let mut tally = Tally::default();
let mut dropped = BTreeMap::new();
for b in (k..batches).step_by(threads) {
let n = batch_size.min(total - b * batch_size);
let bseed = (seed as u32).wrapping_mul(31).wrapping_add(b as u32 * 0x1000_0001);
let (cases, d) =
generate(t, seed ^ (b as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15), n, bseed);
for (k, v) in d {
*dropped.entry(k).or_default() += v;
}
let out = run_qemu(t, elf, b, bseed, &cases).unwrap_or_else(|e| panic!("{}: {e}", t.name));
for (i, (c, q)) in cases.iter().zip(&out).enumerate() {
let mode = [Mode::Concrete, Mode::Pinned, Mode::PrivateStack][i % 3];
compare_case(t, &lay, bseed, c, q, mode, &mut tally);
}
}
(tally, dropped)
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let mut tally = Tally::default();
let mut dropped: BTreeMap<&'static str, usize> = BTreeMap::new();
for (t, d) in results {
tally.cases += t.cases;
tally.armsim_compared += t.armsim_compared;
tally.exec_compared += t.exec_compared;
tally.exec_declined += t.exec_declined;
tally.exec_only += t.exec_only;
tally.known += t.known;
tally.unexpected += t.unexpected;
for (k, (n, ex)) in t.classes {
let e = tally.classes.entry(k).or_default();
e.0 += n;
for x in ex {
if e.1.len() < 3 {
e.1.push(x);
}
}
}
for (k, v) in d {
*dropped.entry(k).or_default() += v;
}
}
eprintln!(
"{} ({}): {} cases run on QEMU in {:.1?}: armsim compared on {}, executor on {} (declined {}; {} cases armsim does not model); {} known differences, {} unexpected",
t.name,
t.machine,
tally.cases,
started.elapsed(),
tally.armsim_compared,
tally.exec_compared,
tally.exec_declined,
tally.exec_only,
tally.known,
tally.unexpected
);
eprintln!(" not run: {dropped:?}");
let verbose = std::env::var_os("CVERIF_QEMU_VERBOSE").is_some();
let mut failures = Vec::new();
for ((tag, what, class), (n, ex)) in &tally.classes {
if tag == "known" && !verbose {
continue;
}
let line = format!(" {tag} {n:5} {what} [{class}]\n {}", ex.join("\n "));
eprintln!("{line}");
if tag != "known" {
failures.push(line);
}
}
assert!(
failures.is_empty(),
"{}: {} disagreements with QEMU",
t.name,
failures.len()
);
assert!(
tally.exec_compared * 3 > tally.cases,
"{}: too few cases were compared",
t.name
);
}
#[test]
fn qemu_cortex_m0() {
campaign(&M0, 0x0123_4567_89ab_cdef);
}
#[test]
fn qemu_cortex_m3() {
campaign(&M3, 0x3333_5555_7777_9999);
}
#[test]
fn qemu_cortex_m4() {
campaign(&M4, 0x4444_6666_8888_aaaa);
}
#[test]
fn qemu_cortex_m33() {
campaign(&M33, 0x3333_3333_dead_beef);
}
fn qemu_ldrh_hint_bug(code: &[u8]) -> bool {
let h = halfwords(code);
h.windows(2)
.any(|w| w[0] & 0xff70 == 0xf830 && w[0] & 15 != 15 && w[1] >> 12 == 15)
}