use verif::smt::{self, var, Var};
use verif::wp::{self, Proc, Stmt};
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Rng {
Rng(seed | 1)
}
fn next(&mut self) -> u64 {
let mut x = self.0;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.0 = x;
x
}
fn below(&mut self, n: u64) -> u64 {
self.next() % n
}
fn flip(&mut self) -> bool {
self.below(2) == 1
}
}
type State = std::collections::BTreeMap<u32, u64>;
#[derive(Debug, PartialEq, Eq)]
enum Stopped {
Blocked,
Failed,
TooLong,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CallMode {
Real,
SkipCalls,
}
fn exec(s: &Stmt<'_>, state: &mut State, mode: CallMode) -> Result<(), Stopped> {
const LOOP_LIMIT: u32 = 64;
match s {
Stmt::Skip => Ok(()),
Stmt::Assign { var, expr } => {
let v = lookup(state, *expr).ok_or(Stopped::Blocked)?;
state.insert(smt::index(*var), v);
Ok(())
}
Stmt::AssignMany { binds } => {
let mut vals = Vec::new();
for (_, expr) in binds.iter() {
vals.push(lookup(state, *expr).ok_or(Stopped::Blocked)?);
}
for ((var, _), v) in binds.iter().zip(vals) {
state.insert(smt::index(*var), v);
}
Ok(())
}
Stmt::Assume(c) => match lookup_pred(state, *c) {
Some(true) => Ok(()),
_ => Err(Stopped::Blocked),
},
Stmt::Assert(c) => match lookup_pred(state, *c) {
Some(true) => Ok(()),
Some(false) => Err(Stopped::Failed),
None => Err(Stopped::Blocked),
},
Stmt::Seq { first, second } => {
exec(first, state, mode)?;
exec(second, state, mode)
}
Stmt::If { cond, then_, else_ } => match lookup_pred(state, *cond) {
Some(true) => exec(then_, state, mode),
Some(false) => exec(else_, state, mode),
None => Err(Stopped::Blocked),
},
Stmt::While { cond, body, .. } => {
let mut n = 0;
loop {
match lookup_pred(state, *cond) {
Some(true) => {}
Some(false) => return Ok(()),
None => return Err(Stopped::Blocked),
}
if n >= LOOP_LIMIT {
return Err(Stopped::TooLong);
}
exec(body, state, mode)?;
n += 1;
}
}
Stmt::Call { proc_, actuals, writes } => {
if mode == CallMode::SkipCalls {
return Ok(());
}
let mut callee: State = State::new();
for (global, local) in actuals.iter() {
if let Some(v) = state.get(&smt::index(*local)) {
callee.insert(smt::index(*global), *v);
}
}
match lookup_pred(&callee, proc_.requires) {
Some(true) => {}
_ => return Err(Stopped::Blocked),
}
exec(proc_.body, &mut callee, mode)?;
for w in writes.iter() {
if let Some((_, local)) = actuals.iter().find(|(g, _)| g == w) {
if let Some(v) = callee.get(&smt::index(*w)) {
state.insert(smt::index(*local), *v);
}
}
}
Ok(())
}
}
}
fn lookup(state: &State, t: Var) -> Option<u64> {
smt::evaluate(t, |i| state.get(&i).copied())
}
fn lookup_pred(state: &State, p: smt::Pred) -> Option<bool> {
smt::evaluate_pred(p, |i| state.get(&i).copied())
}
fn rand_expr(rng: &mut Rng, x: Var, depth: u32) -> Var {
let choices = if depth == 0 { 4 } else { 7 };
match rng.below(choices) {
0 => x,
1 => smt::word(rng.below(8), 8),
2 => x + smt::word(1 + rng.below(3), 8),
3 => x * smt::word(2, 8),
4 => smt::band(x, smt::word(rng.below(256), 8)),
5 => smt::bor(x, smt::word(rng.below(256), 8)),
_ => {
let l = rand_expr(rng, x, depth - 1);
let r = rand_expr(rng, x, depth - 1);
l + r
}
}
}
fn run_case(seed: u64, case_no: u32) -> bool {
let mut rng = Rng::new(seed);
let use_helper = rng.flip();
let writes_scratch = rng.flip();
let x = smt::var(8);
let rr = smt::var(8);
let sc = smt::var(8);
let f_expr = rand_expr(&mut rng, x, 2);
let g_expr = rand_expr(&mut rng, x, 1);
let write_rr = Stmt::Assign { var: rr, expr: f_expr };
let write_sc = Stmt::Assign { var: sc, expr: g_expr };
let hx = smt::var(8);
let hr = smt::var(8);
let helper_body = Stmt::Assign { var: hr, expr: hx + 1u32 };
let helper = Proc {
name: "helper",
requires: smt::truth(true),
ensures: smt::eq(hr, hx + 1u32),
body: &helper_body,
};
let h_actuals = vec![(hx, x), (hr, sc)];
let h_writes = vec![hr];
let helper_call = Stmt::Call { proc_: &helper, actuals: &h_actuals, writes: &h_writes };
let sc_is_written = writes_scratch || use_helper;
let callee_body = if use_helper {
Stmt::Seq { first: &helper_call, second: &write_rr }
} else if writes_scratch {
Stmt::Seq { first: &write_rr, second: &write_sc }
} else {
Stmt::Seq { first: &write_rr, second: &Stmt::Skip }
};
let callee = Proc {
name: "callee",
requires: smt::truth(true),
ensures: smt::eq(rr, f_expr),
body: &callee_body,
};
assert!(
wp::verify_proc(&helper).is_verified(),
"case {}: the helper must verify",
case_no
);
let callee_report = wp::verify_proc(&callee);
assert!(
callee_report.is_verified(),
"case {}: the callee itself must verify: {:?}",
case_no,
callee_report.first_failure()
);
let input = smt::var(8);
let t = smt::var(8);
let b = smt::var(8);
let alias_result = rng.below(4) == 0;
let result_target = if alias_result { input } else { t };
let mut actuals = vec![(x, input), (rr, result_target)];
let map_scratch = sc_is_written && rng.flip();
if map_scratch {
actuals.push((sc, b));
}
let declared: Vec<Var> = match rng.below(4) {
0 => vec![rr], 1 => vec![rr, sc], 2 => vec![rr, sc, x], _ => Vec::new(), };
let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &declared };
let seed_b = Stmt::Assign { var: b, expr: smt::word(0x07, 8) };
let seed_value = 0x55u64;
let seed_result = !alias_result;
let seed_t = Stmt::Assign { var: result_target, expr: smt::word(seed_value, 8) };
let prog = if seed_result {
Stmt::Seq {
first: &seed_b,
second: &Stmt::Seq { first: &seed_t, second: &call },
}
} else {
Stmt::Seq { first: &seed_b, second: &call }
};
let result_in_caller = smt::substitute_word(f_expr, &[(x, input)]);
let post = match rng.below(5) {
0 => smt::eq(result_target, result_in_caller),
1 => smt::ule_const(result_target, 0xff),
2 => smt::eq_const(b, 0x07),
3 if seed_result => smt::eq_const(result_target, seed_value),
_ => smt::truth(true),
};
let report = wp::verify(&prog, smt::truth(true), post);
let verified = report.is_verified();
if verified {
for v in 0..=255u64 {
let mut state = State::new();
state.insert(smt::index(input), v);
match exec(&prog, &mut state, CallMode::Real) {
Ok(()) => {
let holds = lookup_pred(&state, post);
assert!(
holds != Some(false),
"case {} (seed {}): the engine VERIFIED but input {} violates the \
postcondition",
case_no,
seed,
v
);
}
Err(Stopped::Failed) => panic!(
"case {} (seed {}): engine VERIFIED but input {} fails an assertion",
case_no, seed, v
),
Err(Stopped::Blocked) | Err(Stopped::TooLong) => {}
}
}
} else {
assert!(
report.first_failure().is_some(),
"case {}: a report that is not verified must have a failure",
case_no
);
}
verified
}
#[test]
fn a_proof_never_outruns_concrete_execution() {
let mut verified_count = 0;
for i in 0..300u64 {
let seed = 0x9E37_79B9_7F4A_7C15u64.wrapping_mul(i + 1);
if smt::with_fresh(|| run_case(seed, i as u32)) {
verified_count += 1;
}
}
assert!(
verified_count > 30,
"the generator produced only {} verifiable callers, so the check is nearly vacuous",
verified_count
);
}
#[test]
fn the_harness_catches_a_deliberately_broken_frame_rule() {
smt::with_fresh(|| {
let x = smt::var(8);
let rr = smt::var(8);
let sc = smt::var(8);
let a1 = Stmt::Assign { var: sc, expr: x + x };
let a2 = Stmt::Assign { var: rr, expr: sc };
let body = Stmt::Seq { first: &a1, second: &a2 };
let callee = Proc {
name: "dbl",
requires: smt::truth(true),
ensures: smt::eq(rr, x + x),
body: &body,
};
let input = smt::var(8);
let t = smt::var(8);
let b = smt::var(8);
let actuals = vec![(x, input), (rr, t), (sc, b)];
let lie: Vec<Var> = Vec::new();
assert!(!Stmt::frame(&callee, &actuals, &lie));
let seed_b = Stmt::Assign { var: b, expr: smt::word(7, 8) };
let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &lie };
let prog = Stmt::Seq { first: &seed_b, second: &call };
let mut state = State::new();
state.insert(smt::index(input), 3);
exec(&prog, &mut state, CallMode::Real).expect("the run completes");
assert_eq!(state.get(&smt::index(b)).copied(), Some(7));
let real_b = 3u64 + 3;
assert_ne!(real_b, 7);
assert_eq!(real_b, 6);
});
}
#[test]
fn the_property_has_teeth() {
smt::with_fresh(|| {
let x = smt::var(8);
let rr = smt::var(8);
let body = Stmt::Assign { var: rr, expr: smt::word(1, 8) };
let f = Proc {
name: "f",
requires: smt::truth(true),
ensures: smt::eq_const(rr, 1),
body: &body,
};
let input = smt::var(8);
let t = smt::var(8);
let actuals = vec![(x, input), (rr, t)];
let declared = vec![rr];
let call = Stmt::Call { proc_: &f, actuals: &actuals, writes: &declared };
let seed_t = Stmt::Assign { var: t, expr: smt::word(0, 8) };
let prog = Stmt::Seq { first: &seed_t, second: &call };
let post = smt::eq_const(t, 1);
let report = wp::verify(&prog, smt::truth(true), post);
assert!(report.is_verified(), "{:?}", report.first_failure());
for v in 0..=255u64 {
let mut st = State::new();
st.insert(smt::index(input), v);
exec(&prog, &mut st, CallMode::Real).expect("the run completes");
assert_eq!(st.get(&smt::index(t)).copied(), Some(1));
}
let mut caught = 0;
for v in 0..=255u64 {
let mut st = State::new();
st.insert(smt::index(input), v);
exec(&prog, &mut st, CallMode::SkipCalls).expect("the run completes");
if lookup_pred(&st, post) == Some(false) {
caught += 1;
}
}
assert_eq!(
caught, 256,
"the broken semantics must be caught for every input, or the harness is blind"
);
});
}
fn run_loop_case(seed: u64, case_no: u32) -> (bool, bool) {
let mut rng = Rng::new(seed);
let n = 1 + rng.below(3);
let exact_contract = rng.below(4) != 0;
let lie_frame = rng.below(4) == 0;
let wrong_variant = rng.below(4) == 0;
let diverges = rng.below(8) == 0;
let x = smt::var(8);
let rr = smt::var(8);
let callee_body = Stmt::Assign { var: rr, expr: x + 1u32 };
let callee_ensures = if exact_contract {
smt::eq(rr, x + 1u32)
} else {
smt::implies(smt::ult_const(x, 255), smt::eq(rr, x + 1u32))
};
let callee = Proc {
name: "inc",
requires: smt::truth(true),
ensures: callee_ensures,
body: &callee_body,
};
assert!(
wp::verify_proc(&callee).is_verified(),
"case {}: the callee must verify on its own",
case_no
);
let c = smt::var(8); let a = smt::var(8); let k = smt::var(3); let tmp = smt::var(8);
let actuals = vec![(x, a), (rr, tmp)];
let declared: Vec<Var> = if lie_frame { Vec::new() } else { vec![rr] };
let call = Stmt::Call { proc_: &callee, actuals: &actuals, writes: &declared };
let advance = Stmt::Assign { var: k, expr: k + 1u32 };
let copy_back = Stmt::Assign { var: a, expr: tmp };
let loop_body = if diverges {
Stmt::Seq { first: &call, second: ©_back }
} else {
Stmt::Seq {
first: &call,
second: &Stmt::Seq { first: ©_back, second: &advance },
}
};
let inv = smt::and(
smt::ule_const(k, n),
smt::eq(a, c + smt::truncate(k, 8)),
);
let variant = if diverges || wrong_variant {
Some(k)
} else {
Some(smt::sub(smt::word(n, 3), k))
};
let loop_ = Stmt::While {
cond: smt::ult_const(k, n),
invariant: inv,
variant,
body: &loop_body,
};
let init_k = Stmt::Assign { var: k, expr: smt::word(0, 3) };
let init_a = Stmt::Assign { var: a, expr: c };
let prologue = Stmt::Seq { first: &init_k, second: &init_a };
let prog = Stmt::Seq { first: &prologue, second: &loop_ };
let post = smt::eq(a, c + smt::word(n, 8));
let report = wp::verify(&prog, smt::truth(true), post);
let verified = report.is_verified();
let raw_total = report.correctness() == wp::Correctness::Total;
let total = report.establishes() == wp::Established::Total;
if !verified {
assert!(
report.first_failure().is_some(),
"case {}: a report that is not verified must have a failure",
case_no
);
}
for v in 0..=255u64 {
let mut state = State::new();
state.insert(smt::index(c), v);
match exec(&prog, &mut state, CallMode::Real) {
Ok(()) => {
if verified {
let holds = lookup_pred(&state, post);
assert!(
holds != Some(false),
"case {} (seed {}): VERIFIED but input {} violates the \
postcondition",
case_no,
seed,
v
);
}
}
Err(Stopped::Failed) => assert!(
!verified,
"case {} (seed {}): VERIFIED but input {} fails an assertion",
case_no, seed, v
),
Err(Stopped::TooLong) => {
assert!(
!raw_total,
"case {} (seed {}): the report claims TERMINATION but input {} \
diverged. `correctness()` said Total for a loop whose variant was \
never proved to decrease.",
case_no, seed, v
);
}
Err(Stopped::Blocked) => {}
}
}
(verified, total)
}
#[test]
fn a_loop_with_a_call_never_proves_a_false_postcondition() {
let mut verified = 0;
let mut total = 0;
for i in 0..300u64 {
let seed = 0xD1B5_4A32_D192_ED03u64.wrapping_mul(i + 1);
let (v, t) = smt::with_fresh(|| run_loop_case(seed, i as u32));
if v {
verified += 1;
}
if t {
total += 1;
}
}
assert!(
verified > 20,
"only {} of 300 loop cases verified, so the check is nearly vacuous",
verified
);
assert!(
total > 10,
"only {} of 300 loop cases proved termination, so the variant rule is barely \
exercised",
total
);
}
#[test]
fn a_total_claim_is_not_made_for_a_divergent_loop() {
smt::with_fresh(|| {
let k = smt::var(3);
let a = smt::var(8);
let c = smt::var(8);
let body = Stmt::Skip;
let inv = smt::and(smt::ule_const(k, 3), smt::eq(a, c));
let loop_ = Stmt::While {
cond: smt::ult_const(k, 3),
invariant: inv,
variant: None,
body: &body,
};
let init_k = Stmt::Assign { var: k, expr: smt::word(0, 3) };
let init_a = Stmt::Assign { var: a, expr: c };
let prog = Stmt::Seq {
first: &init_k,
second: &Stmt::Seq { first: &init_a, second: &loop_ },
};
let report = wp::verify(&prog, smt::truth(true), smt::eq(a, c));
assert!(report.is_verified(), "{:?}", report.first_failure());
assert!(
!report.terminates(),
"a divergent loop must not be reported as terminating"
);
assert_eq!(report.correctness(), wp::Correctness::Partial);
assert_eq!(report.establishes(), wp::Established::Partial);
let mut state = State::new();
state.insert(smt::index(c), 7);
assert_eq!(
exec(&prog, &mut state, CallMode::Real),
Err(Stopped::TooLong),
"the loop must not terminate concretely"
);
let bad = Stmt::While {
cond: smt::ult_const(k, 3),
invariant: inv,
variant: Some(k),
body: &body,
};
let prog2 = Stmt::Seq {
first: &init_k,
second: &Stmt::Seq { first: &init_a, second: &bad },
};
let report2 = wp::verify(&prog2, smt::truth(true), smt::eq(a, c));
let (ob, _) = report2
.first_failure()
.expect("a non-decreasing measure must fail");
assert_eq!(ob.rule, wp::Rule::LoopVariant);
});
}
fn run_padded_case(padding: u32, case_no: u32) -> bool {
smt::with_fresh(|| {
let i = smt::var(8);
let init: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Assign {
var: i,
expr: smt::word(0, 8),
}));
let step: &'static Stmt<'static> =
Box::leak(Box::new(Stmt::Assign { var: i, expr: i + 1u32 }));
let loop_: &'static Stmt<'static> = Box::leak(Box::new(Stmt::While {
cond: smt::ult_const(i, 10),
invariant: smt::ule_const(i, 10),
variant: None,
body: step,
}));
let core: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Seq {
first: init,
second: loop_,
}));
let mut node = core;
for _ in 0..padding {
let leaf: &'static Stmt<'static> =
Box::leak(Box::new(Stmt::Assert(smt::truth(true))));
node = Box::leak(Box::new(Stmt::Seq { first: node, second: leaf }));
}
let post = smt::not(smt::ult_const(i, 100));
let report = wp::verify(node, smt::truth(true), post);
let verified = report.is_verified();
if verified {
let mut state = State::new();
let outcome = exec(node, &mut state, CallMode::Real);
assert!(
outcome != Ok(()),
"case {} (padding {}): VERIFIED but the program runs to completion and \
the postcondition is false",
case_no,
padding
);
let holds = lookup_pred(&state, post);
assert!(
holds != Some(false),
"case {} (padding {}): VERIFIED but the postcondition is false on \
completion",
case_no,
padding
);
}
verified
})
}
#[test]
fn obligation_pressure_never_produces_a_false_verification() {
let mut verified = 0;
for padding in 0..28u32 {
if run_padded_case(padding, padding) {
verified += 1;
}
}
assert_eq!(
verified, 0,
"no padding may turn a failing program into a verified one, but {} did",
verified
);
}
#[test]
fn crossing_the_cap_is_observable() {
smt::with_fresh(|| {
let i = smt::var(8);
let init: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Assign {
var: i,
expr: smt::word(0, 8),
}));
let step: &'static Stmt<'static> =
Box::leak(Box::new(Stmt::Assign { var: i, expr: i + 1u32 }));
let loop_: &'static Stmt<'static> = Box::leak(Box::new(Stmt::While {
cond: smt::ult_const(i, 10),
invariant: smt::ule_const(i, 10),
variant: None,
body: step,
}));
let core: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Seq {
first: init,
second: loop_,
}));
let post = smt::not(smt::ult_const(i, 100));
let report = wp::verify(core, smt::truth(true), post);
let (ob, _) = report.first_failure().expect("the exit obligation fails");
assert_eq!(ob.rule, wp::Rule::LoopExit);
let mut node = core;
for _ in 0..wp::MAX_OBLIGATIONS {
let leaf: &'static Stmt<'static> =
Box::leak(Box::new(Stmt::Assert(smt::truth(true))));
node = Box::leak(Box::new(Stmt::Seq { first: node, second: leaf }));
}
let report = wp::verify(node, smt::truth(true), post);
let (ob, _) = report.first_failure().expect("the overflow must be reported");
assert_eq!(ob.rule, wp::Rule::ObligationOverflow);
assert!(!report.is_verified());
assert_eq!(report.establishes(), wp::Established::Nothing);
});
}
const MEM_VALS: [u8; 6] = [0, 1, 2, 3, 7, 200];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Op {
StoreConst { addr: usize, val: u8 },
StoreCopy { dst: usize, src: usize },
SwapCells { x: usize, y: usize },
StoreAtSymbolic { src: usize },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Post {
EqCells(usize, usize),
EqConst(usize, u8),
BelowConst(u8),
}
fn mem_pick_cell(rng: &mut Rng) -> usize {
rng.below(4) as usize
}
fn mem_pick_val(rng: &mut Rng) -> u8 {
MEM_VALS[rng.below(6) as usize]
}
fn gen_ops(rng: &mut Rng, len: usize) -> Vec<Op> {
let mut ops = Vec::with_capacity(len);
for _ in 0..len {
let which = rng.below(4);
let op = match which {
0 => Op::StoreConst {
addr: mem_pick_cell(rng),
val: mem_pick_val(rng),
},
1 => Op::StoreCopy {
dst: mem_pick_cell(rng),
src: mem_pick_cell(rng),
},
2 => Op::SwapCells {
x: mem_pick_cell(rng),
y: mem_pick_cell(rng),
},
_ => Op::StoreAtSymbolic {
src: mem_pick_cell(rng),
},
};
ops.push(op);
}
ops
}
fn gen_post(rng: &mut Rng) -> Post {
match rng.below(3) {
0 => Post::EqCells(mem_pick_cell(rng), mem_pick_cell(rng)),
1 => Post::EqConst(mem_pick_cell(rng), mem_pick_val(rng)),
_ => Post::BelowConst(mem_pick_val(rng)),
}
}
fn exec_ops(ops: &[Op], a: usize, init: [u8; 4]) -> [u8; 4] {
let mut m = init;
for op in ops {
match *op {
Op::StoreConst { addr, val } => m[addr] = val,
Op::StoreCopy { dst, src } => m[dst] = m[src],
Op::SwapCells { x, y } => m.swap(x, y),
Op::StoreAtSymbolic { src } => m[a] = m[src],
}
}
m
}
fn eval_post(post: Post, a: usize, m: [u8; 4]) -> bool {
match post {
Post::EqCells(i, j) => m[i] == m[j],
Post::EqConst(i, c) => m[i] == c,
Post::BelowConst(c) => (0..a).all(|k| m[k] == c),
}
}
fn build_mem_program(
ops: &[Op],
a: Var,
m: &verif::mem::Mem<'_>,
) -> &'static Stmt<'static> {
fn binds_of(b: &[(Var, Var)]) -> &'static [(Var, Var)] {
Box::leak(b.to_vec().into_boxed_slice())
}
let mut stmts: Vec<&'static Stmt<'static>> = Vec::new();
let const_addr = |c: usize| smt::word(c as u64, 2);
for op in ops {
match *op {
Op::StoreConst { addr, val } => {
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(const_addr(addr), smt::word(val as u64, 8), &mut b);
stmts.push(Box::leak(Box::new(Stmt::AssignMany {
binds: binds_of(&b[..n]),
})));
}
Op::StoreCopy { dst, src } => {
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(const_addr(dst), m.read_const(src), &mut b);
stmts.push(Box::leak(Box::new(Stmt::AssignMany {
binds: binds_of(&b[..n]),
})));
}
Op::SwapCells { x, y } => {
let t = smt::var(8);
stmts.push(Box::leak(Box::new(Stmt::Assign {
var: t,
expr: m.read_const(x),
})));
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(const_addr(x), m.read_const(y), &mut b);
stmts.push(Box::leak(Box::new(Stmt::AssignMany {
binds: binds_of(&b[..n]),
})));
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(const_addr(y), t, &mut b);
stmts.push(Box::leak(Box::new(Stmt::AssignMany {
binds: binds_of(&b[..n]),
})));
}
Op::StoreAtSymbolic { src } => {
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(a, m.read_const(src), &mut b);
stmts.push(Box::leak(Box::new(Stmt::AssignMany {
binds: binds_of(&b[..n]),
})));
}
}
}
let mut node: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
while let Some(s) = stmts.pop() {
node = Box::leak(Box::new(Stmt::Seq { first: s, second: node }));
}
node
}
fn sample_arrays() -> Vec<[u8; 4]> {
let mut out = Vec::new();
for a in MEM_VALS {
for b in MEM_VALS {
for c in MEM_VALS {
for d in MEM_VALS {
out.push([a, b, c, d]);
}
}
}
}
out
}
fn count_violations(ops: &[Op], post: Post, arrays: &[[u8; 4]]) -> usize {
let mut violations = 0;
for init in arrays {
for a in 0..4usize {
if !eval_post(post, a, exec_ops(ops, a, *init)) {
violations += 1;
}
}
}
violations
}
#[test]
fn a_memory_proof_never_outruns_the_array() {
let arrays = sample_arrays();
let mut verified_cases = 0;
let mut falsified_cases = 0;
let mut symbolic_store_ops = 0;
let mut swap_ops = 0;
let mut below_posts = 0;
for seed in 0..400u64 {
let mut rng = Rng::new(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let len = 1 + rng.below(4) as usize;
let ops = gen_ops(&mut rng, len);
let post = gen_post(&mut rng);
symbolic_store_ops += ops
.iter()
.filter(|o| matches!(o, Op::StoreAtSymbolic { .. }))
.count();
swap_ops += ops.iter().filter(|o| matches!(o, Op::SwapCells { .. })).count();
if matches!(post, Post::BelowConst(_)) {
below_posts += 1;
}
let verdict = smt::with_fresh(|| {
let mut buf = [Var::SENTINEL; 4];
let n = verif::mem::declare(2, 8, &mut buf);
let m = verif::mem::Mem::new(&buf[..n], 8);
let a = var(2);
let bound = var(3);
let prog = build_mem_program(&ops, a, &m);
let symbolic_post = match post {
Post::EqCells(i, j) => smt::eq(m.read_const(i), m.read_const(j)),
Post::EqConst(i, c) => smt::eq(m.read_const(i), smt::word(c as u64, 8)),
Post::BelowConst(c) => {
m.forall_below(bound, |v| smt::eq(v, smt::word(c as u64, 8)))
}
};
smt::prove(wp::wp(symbolic_post, prog))
});
let violations = count_violations(&ops, post, &arrays);
if verdict.is_proved() {
verified_cases += 1;
assert_eq!(
violations, 0,
"seed {}: VERIFIED but {} sampled (array, address) pairs violate {:?} \
after {:?}",
seed, violations, post, ops
);
} else {
assert!(
violations > 0,
"seed {}: verdict {:?} is not a proof, yet no sampled input violates {:?} \
after {:?}",
seed, verdict, post, ops
);
falsified_cases += 1;
}
}
assert!(
verified_cases > 0,
"no case was proved; the memory family is vacuous"
);
assert!(
falsified_cases > 0,
"no case was refuted; the memory family cannot detect a bad rule"
);
assert!(
symbolic_store_ops > 0,
"no store at a symbolic address was generated; the ite-chain read and the frame \
rule are not being exercised"
);
assert!(
swap_ops > 0,
"no swap was generated; the simultaneous-binding path is not being exercised"
);
assert!(
below_posts > 0,
"no `forall_below` postcondition was generated; the guarded quantifier is not \
being exercised"
);
eprintln!(
"memory family: {} proved, {} refuted; {} symbolic stores, {} swaps, {} below-posts",
verified_cases, falsified_cases, symbolic_store_ops, swap_ops, below_posts
);
}
#[test]
fn the_memory_family_has_teeth() {
let arrays = sample_arrays();
let addr = 0usize;
let other = 1usize;
let val = 5u8;
let ops = [Op::StoreConst { addr, val }];
let post = Post::EqConst(other, val);
let verdict = smt::with_fresh(|| {
let mut buf = [Var::SENTINEL; 4];
let n = verif::mem::declare(2, 8, &mut buf);
let m = verif::mem::Mem::new(&buf[..n], 8);
let binds: &'static [(Var, Var)] = Box::leak(
m.cells()
.iter()
.map(|c| (*c, smt::word(val as u64, 8)))
.collect::<Vec<_>>()
.into_boxed_slice(),
);
let prog = Stmt::AssignMany { binds };
let symbolic_post = smt::eq(m.read_const(other), smt::word(val as u64, 8));
smt::prove(wp::wp(symbolic_post, &prog))
});
let violations = count_violations(&ops, post, &arrays);
assert!(
verdict.is_proved(),
"the broken rule was expected to prove the false postcondition, but gave {:?}",
verdict
);
assert!(
violations > 0,
"the broken rule proved a postcondition that no sampled array violates; the \
teeth test is not exercising the disagreement it claims to"
);
}
#[derive(Debug, Clone, Copy)]
enum Pos {
StoreReadSymbolic { val: u8 },
StoreFrameSymbolic { val: u8, at: usize },
FillBelow { n: usize, val: u8 },
Swap { x: usize, y: usize },
Copy { dst: usize, src: usize },
}
fn pos_templates() -> Vec<Pos> {
let mut out = Vec::new();
for val in MEM_VALS {
out.push(Pos::StoreReadSymbolic { val });
for at in 0..4usize {
out.push(Pos::StoreFrameSymbolic { val, at });
}
for n in 0..=4usize {
out.push(Pos::FillBelow { n, val });
}
}
for x in 0..4usize {
for y in 0..4usize {
out.push(Pos::Swap { x, y });
for src in 0..4usize {
out.push(Pos::Copy { dst: x, src });
}
}
}
out
}
fn pos_seq(stmts: Vec<&'static Stmt<'static>>) -> &'static Stmt<'static> {
let mut node: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
for s in stmts.into_iter().rev() {
node = Box::leak(Box::new(Stmt::Seq { first: s, second: node }));
}
node
}
fn pos_store(
m: &verif::mem::Mem<'_>,
addr: Var,
val: Var,
) -> &'static Stmt<'static> {
let mut b = [(Var::SENTINEL, Var::SENTINEL); verif::mem::MAX_CELLS];
let n = m.store_binds(addr, val, &mut b);
let binds: &'static [(Var, Var)] = Box::leak(b[..n].to_vec().into_boxed_slice());
Box::leak(Box::new(Stmt::AssignMany { binds }))
}
fn pos_assign(v: Var, e: Var) -> &'static Stmt<'static> {
Box::leak(Box::new(Stmt::Assign { var: v, expr: e }))
}
fn build_pos(
p: Pos,
m: &verif::mem::Mem<'_>,
a: Var,
bound: Var,
mutate: bool,
) -> (smt::Pred, &'static Stmt<'static>, smt::Pred) {
let caddr = |c: usize| smt::word(c as u64, 2);
let w8 = |v: u8| smt::word(v as u64, 8);
match p {
Pos::StoreReadSymbolic { val } => {
let prog = pos_store(m, a, w8(val));
let post = if mutate {
smt::eq(m.read(a), w8(val.wrapping_add(1)))
} else {
smt::eq(m.read(a), w8(val))
};
(smt::truth(true), pos_seq(vec![prog]), post)
}
Pos::StoreFrameSymbolic { val, at } => {
let old = var(8);
let save = pos_assign(old, m.read_const(at));
let store = pos_store(m, a, w8(val));
let post = smt::implies(
smt::not(smt::eq(a, caddr(at))),
smt::eq(m.read_const(at), if mutate { w8(val) } else { old }),
);
(smt::truth(true), pos_seq(vec![save, store]), post)
}
Pos::FillBelow { n, val } => {
let mut stmts = Vec::new();
for k in 0..n {
stmts.push(pos_store(m, caddr(k), w8(val)));
}
let post = m.forall_below(
bound,
|c| {
smt::eq(
c,
if mutate { w8(val.wrapping_add(1)) } else { w8(val) },
)
},
);
(smt::eq_const(bound, n as u64), pos_seq(stmts), post)
}
Pos::Swap { x, y } => {
let t = var(8);
let oi = var(8);
let oj = var(8);
let save_x = pos_assign(oi, m.read_const(x));
let save_y = pos_assign(oj, m.read_const(y));
let save_t = pos_assign(t, oi);
let wr_x = pos_store(m, caddr(x), oj);
let wr_y = pos_store(m, caddr(y), t);
let (e0, e1) = if mutate {
(w8(0), w8(0))
} else {
(oj, oi)
};
let post = smt::and(
smt::eq(m.read_const(x), e0),
smt::eq(m.read_const(y), e1),
);
(smt::truth(true), pos_seq(vec![save_x, save_y, save_t, wr_x, wr_y]), post)
}
Pos::Copy { dst, src } => {
let old = var(8);
let save = pos_assign(old, m.read_const(src));
let store = pos_store(m, caddr(dst), m.read_const(src));
let post = smt::eq(
m.read_const(dst),
if mutate { w8(0) } else { old },
);
(smt::truth(true), pos_seq(vec![save, store]), post)
}
}
}
fn pos_concrete_ok(p: Pos, arrays: &[[u8; 4]]) -> bool {
for init in arrays {
let mut m = *init;
let ok = match p {
Pos::StoreReadSymbolic { val } => {
(0..4usize).all(|addr| {
let mut mm = m;
mm[addr] = val;
mm[addr] == val
})
}
Pos::StoreFrameSymbolic { val, at } => (0..4usize).all(|addr| {
let mut mm = m;
let old = mm[at];
mm[addr] = val;
addr == at || mm[at] == old
}),
Pos::FillBelow { n, val } => {
for slot in m.iter_mut().take(n) {
*slot = val;
}
m.iter().take(n).all(|cell| *cell == val)
}
Pos::Swap { x, y } => {
let (ox, oy) = (m[x], m[y]);
m.swap(x, y);
m[x] == oy && m[y] == ox
}
Pos::Copy { dst, src } => {
let old = m[src];
m[dst] = old;
m[dst] == old
}
};
if !ok {
return false;
}
}
true
}
#[test]
fn memory_programs_that_should_verify_do_verify() {
let arrays = sample_arrays();
let mut proved = 0usize;
let mut mutations_refuted = 0usize;
for p in pos_templates() {
let concrete_ok = pos_concrete_ok(p, &arrays);
assert!(
concrete_ok,
"template {:?} violates its own postcondition on a concrete array; the template \
is wrong, not the engine",
p
);
let verdict = smt::with_fresh(|| {
let mut buf = [Var::SENTINEL; 4];
let n = verif::mem::declare(2, 8, &mut buf);
let m = verif::mem::Mem::new(&buf[..n], 8);
let a = var(2);
let bound = var(3);
let (pre, prog, post) = build_pos(p, &m, a, bound, false);
smt::prove_implies(pre, wp::wp(post, prog))
});
assert!(
verdict.is_proved(),
"template {:?} should verify but the engine gave {:?}",
p,
verdict
);
proved += 1;
let vacuously_true = matches!(p, Pos::FillBelow { n: 0, .. });
let mutated = smt::with_fresh(|| {
let mut buf = [Var::SENTINEL; 4];
let n = verif::mem::declare(2, 8, &mut buf);
let m = verif::mem::Mem::new(&buf[..n], 8);
let a = var(2);
let bound = var(3);
let (pre, prog, post) = build_pos(p, &m, a, bound, true);
smt::prove_implies(pre, wp::wp(post, prog))
});
if vacuously_true {
assert!(
mutated.is_proved(),
"{:?} is vacuously true and its mutation should also prove",
p
);
} else {
assert!(
!mutated.is_proved(),
"the mutated postcondition of {:?} was proved, so the template's proof is insensitive to the postcondition",
p
);
mutations_refuted += 1;
}
}
assert!(proved > 100, "expected many templates to verify, got {}", proved);
assert!(
mutations_refuted > 100,
"expected nearly every mutated template to be refuted, got {}; a template whose \
mutation survives is proving nothing",
mutations_refuted
);
eprintln!(
"memory positive family: {} templates proved, {} mutations refuted",
proved, mutations_refuted
);
}
#[derive(Clone, Copy, Debug)]
enum EDesc {
X,
K(u64),
AddK(u64),
MaskK(u64),
}
#[derive(Clone, Debug)]
enum PDesc {
EqK(u64),
LtK(u64),
Not(Box<PDesc>),
Or(Box<PDesc>, Box<PDesc>),
}
#[derive(Clone, Debug)]
enum SDesc {
Assign(EDesc),
Assert(PDesc),
If(PDesc, Vec<SDesc>, Vec<SDesc>),
}
fn gen_edesc(rng: &mut Rng) -> EDesc {
match rng.below(4) {
0 => EDesc::X,
1 => EDesc::K(rng.below(4)),
2 => EDesc::AddK(1 + rng.below(2)),
_ => EDesc::MaskK(rng.below(8)),
}
}
fn gen_pdesc(rng: &mut Rng, depth: u32) -> PDesc {
if depth == 0 || rng.below(3) == 0 {
return if rng.below(2) == 0 {
PDesc::EqK(rng.below(4))
} else {
PDesc::LtK(rng.below(4))
};
}
match rng.below(3) {
0 => PDesc::Not(Box::new(gen_pdesc(rng, depth - 1))),
_ => {
let a = gen_pdesc(rng, depth - 1);
let b = gen_pdesc(rng, depth - 1);
PDesc::Or(Box::new(a), Box::new(b))
}
}
}
fn gen_sdesc(rng: &mut Rng, depth: u32, n: usize) -> Vec<SDesc> {
let mut out = Vec::with_capacity(n);
for _ in 0..n {
let which = rng.below(if depth > 0 { 3 } else { 2 });
let s = match which {
0 => SDesc::Assign(gen_edesc(rng)),
1 => SDesc::Assert(gen_pdesc(rng, 1)),
_ => {
let c = gen_pdesc(rng, 1);
let (nt, ne) = (rng.below(3) as usize, rng.below(3) as usize);
let t = gen_sdesc(rng, depth - 1, nt);
let e = gen_sdesc(rng, depth - 1, ne);
SDesc::If(c, t, e)
}
};
out.push(s);
}
out
}
enum Step {
Assign(Var),
Assert(smt::Pred),
If(smt::Pred, Vec<Step>, Vec<Step>),
}
fn build_step(d: &SDesc, x: Var) -> Step {
match d {
SDesc::Assign(e) => Step::Assign(match e {
EDesc::X => x,
EDesc::K(k) => smt::word(*k, 8),
EDesc::AddK(k) => smt::add(x, smt::word(*k, 8)),
EDesc::MaskK(k) => smt::band(x, smt::word(*k, 8)),
}),
SDesc::Assert(p) => Step::Assert(build_pdesc(p, x)),
SDesc::If(c, t, e) => Step::If(
build_pdesc(c, x),
t.iter().map(|s| build_step(s, x)).collect(),
e.iter().map(|s| build_step(s, x)).collect(),
),
}
}
fn build_pdesc(d: &PDesc, x: Var) -> smt::Pred {
match d {
PDesc::EqK(k) => x.eq_val(*k),
PDesc::LtK(k) => x.lt_val(*k),
PDesc::Not(p) => smt::not(build_pdesc(p, x)),
PDesc::Or(a, b) => smt::or(build_pdesc(a, x), build_pdesc(b, x)),
}
}
fn build_program(steps: &[SDesc], x: Var) -> &'static Stmt<'static> {
let built: Vec<Step> = steps.iter().map(|d| build_step(d, x)).collect();
leaked_seq(&built, x)
}
fn leaked_seq(steps: &[Step], x: Var) -> &'static Stmt<'static> {
let mut seq: &'static Stmt<'static> = Box::leak(Box::new(Stmt::Skip));
for s in steps.iter().rev() {
let one: &'static Stmt<'static> = match s {
Step::Assign(e) => Box::leak(Box::new(Stmt::Assign { var: x, expr: *e })),
Step::Assert(p) => Box::leak(Box::new(Stmt::Assert(*p))),
Step::If(c, t, e) => Box::leak(Box::new(Stmt::If {
cond: *c,
then_: leaked_seq(t, x),
else_: leaked_seq(e, x),
})),
};
seq = Box::leak(Box::new(Stmt::Seq { first: one, second: seq }));
}
seq
}
fn run_steps(steps: &[Step], x: u64) -> bool {
let mut x = x;
run_steps_mut(steps, &mut x)
}
fn run_steps_mut(steps: &[Step], x: &mut u64) -> bool {
for s in steps {
match s {
Step::Assign(e) => {
let cur = *x;
if let Some(v) = smt::evaluate(*e, |_| Some(cur)) {
*x = v;
}
}
Step::Assert(p) => {
let cur = *x;
if smt::evaluate_pred(*p, |_| Some(cur)) != Some(true) {
return false;
}
}
Step::If(c, t, e) => {
let cur = *x;
let take_then = smt::evaluate_pred(*c, |_| Some(cur)) == Some(true);
if !run_steps_mut(if take_then { t } else { e }, x) {
return false;
}
}
}
}
true
}
#[test]
fn an_assertion_claim_matches_concrete_execution_both_ways() {
let mut rng = Rng::new(0xa55e_2718_1337_0001);
let mut verified = 0u32;
let mut refused = 0u32;
for case in 0..500u32 {
let n = 1 + rng.below(4) as usize;
let desc = gen_sdesc(&mut rng, 2, n);
smt::with_fresh(|| {
let x = var(8);
let steps: Vec<Step> = desc.iter().map(|d| build_step(d, x)).collect();
let any_failure = (0..=255u64).any(|v| !run_steps(&steps, v));
let prog = build_program(&desc, x);
let is_verified = wp::verify(prog, smt::truth(true), smt::truth(true)).is_verified();
assert!(
!(is_verified && any_failure),
"case {}: the engine verified a program whose assertion fails on a real input",
case
);
assert!(
!(!is_verified && !any_failure),
"case {}: every concrete run is fine but the engine refused the program",
case
);
if is_verified {
verified += 1;
} else {
refused += 1;
}
});
}
assert!(verified > 20, "expected some programs to verify, got {}", verified);
assert!(refused > 20, "expected some programs to be refused, got {}", refused);
eprintln!("assertion family: {} verified, {} refused", verified, refused);
}