cverif 0.1.1

Verifies that compiled machine code faithfully matches its C source
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! Fuzzing of the proof checker (`cverif::certify`), the part that `--certify` trusts.
//!
//! Real proofs come from the solver on small random formulas, so that every claim can be
//! decided by enumerating assignments.  They are then corrupted in many ways.  The oracle is
//! semantic: whatever the checker accepts must be true — every derived clause it accepts
//! follows from the input clauses before it, and every UNSAT answer it accepts is UNSAT by
//! enumeration.  Corruptions that make a claim false must therefore be rejected; harmless
//! ones (a hint that was not needed) may be accepted.  Unmodified proofs must be accepted.
//!
//! Deterministic (fixed seeds).  `CVERIF_FUZZ_ITERS=<n>` multiplies the iteration counts and
//! `CVERIF_FUZZ_SEED=<n>` selects a different set of cases.

use cverif::certify::{Checker, Step, Trace};
use cverif::sat::{Lit, SatResult, Solver};

// ----- PRNG ---------------------------------------------------------------------

struct Rng(u64);

fn mix(mut z: u64) -> u64 {
    z = z.wrapping_add(0x9e37_79b9_7f4a_7c15);
    z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
    z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
    z ^ (z >> 31)
}

impl Rng {
    fn new(seed: u64) -> Rng {
        Rng(mix(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.wrapping_mul(0x2545_f491_4f6c_dd1d)
    }
    fn below(&mut self, n: u64) -> u64 {
        (self.next() >> 11) % n
    }
    fn lit(&mut self, nvars: u32) -> Lit {
        Lit::new(self.below(nvars as u64) as u32, self.below(2) == 1)
    }
}

/// `CVERIF_FUZZ_SEED=<n>` explores a different set of cases.
fn seed(test: u64) -> u64 {
    let k = std::env::var("CVERIF_FUZZ_SEED")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(0);
    test ^ mix(k).wrapping_mul((k != 0) as u64)
}

fn iters(default: u64) -> u64 {
    let k = std::env::var("CVERIF_FUZZ_ITERS")
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .unwrap_or(1);
    default * k.max(1)
}

// ----- traces as plain values ----------------------------------------------------

#[derive(Clone, Debug, PartialEq)]
enum Own {
    Input(u64, Vec<Lit>),
    Derive(u64, Vec<Lit>, Vec<u64>),
    Delete(u64),
}

fn own(t: &Trace) -> Vec<Own> {
    t.steps()
        .map(|s| match s {
            Step::Input { id, lits } => Own::Input(id, lits.to_vec()),
            Step::Derive { id, lits, hints } => Own::Derive(id, lits.to_vec(), hints.to_vec()),
            Step::Delete { id } => Own::Delete(id),
        })
        .collect()
}

fn trace(steps: &[Own]) -> Trace {
    let mut t = Trace::default();
    for s in steps {
        t.push(match s {
            Own::Input(id, l) => Step::Input { id: *id, lits: l },
            Own::Derive(id, l, h) => Step::Derive {
                id: *id,
                lits: l,
                hints: h,
            },
            Own::Delete(id) => Step::Delete { id: *id },
        });
    }
    t
}

/// One certified query: the trace up to the answer, the assumptions and the final clause.
#[derive(Clone, Debug)]
struct Query {
    steps: Vec<Own>,
    assumptions: Vec<Lit>,
    last: u64,
}

// ----- semantics ---------------------------------------------------------------------

fn holds(l: Lit, m: u32) -> bool {
    (m >> l.var() & 1 == 1) != l.is_neg()
}

fn sat_by(c: &[Lit], m: u32) -> bool {
    c.iter().any(|&l| holds(l, m))
}

/// Replays queries through one checker, as `--certify` does, and checks every acceptance
/// against enumeration of the `nvars`-variable assignments.  Returns the number of queries
/// accepted; panics if the checker accepted something false.
fn replay(nvars: u32, queries: &[Query], what: &str) -> usize {
    let mut checker = Checker::new();
    // Assignments satisfying every input clause so far.
    let mut models: Vec<u32> = (0..1u32 << nvars).collect();
    let mut accepted = 0;
    for (k, q) in queries.iter().enumerate() {
        let mut ok = true;
        for s in &q.steps {
            let t = trace(std::slice::from_ref(s));
            let step = t.steps().next().unwrap();
            if checker.step(step).is_err() {
                ok = false;
                break;
            }
            match s {
                Own::Input(_, c) => models.retain(|&m| sat_by(c, m)),
                Own::Derive(id, c, _) => {
                    let bad = models.iter().find(|&&m| !sat_by(c, m));
                    assert!(
                        bad.is_none(),
                        "{what}: query {k}: checker accepted clause {id} = {c:?}, false under {:#b}",
                        bad.unwrap()
                    );
                }
                Own::Delete(_) => {}
            }
        }
        if !ok {
            // A rejected step leaves the rest of the trace unusable, as in the prover.
            return accepted;
        }
        if checker.check_unsat(&q.assumptions, q.last).is_ok() {
            let model = models.iter().find(|&&m| q.assumptions.iter().all(|&a| holds(a, m)));
            assert!(
                model.is_none(),
                "{what}: query {k}: checker accepted UNSAT under {:?}, but {:#b} satisfies everything",
                q.assumptions,
                model.unwrap()
            );
            accepted += 1;
        }
    }
    accepted
}

/// Random small formula solved incrementally with proof logging: the queries answered UNSAT.
fn proofs(r: &mut Rng, nvars: u32) -> Vec<Query> {
    let mut s = Solver::new();
    s.enable_proof();
    let mut out = Vec::new();
    for _ in 0..6 {
        for _ in 0..1 + r.below(nvars as u64 + 3) {
            let w = 1 + r.below(4);
            let c: Vec<Lit> = (0..w).map(|_| r.lit(nvars)).collect();
            s.add_clause(&c);
        }
        for _ in 0..3 {
            let assumptions: Vec<Lit> = (0..r.below(5)).map(|_| r.lit(nvars)).collect();
            if s.solve(&assumptions, u64::MAX) == SatResult::Unsat {
                out.push(Query {
                    steps: own(&s.take_proof()),
                    assumptions,
                    last: s.unsat_clause().expect("final clause"),
                });
            }
        }
    }
    out
}

fn ids(qs: &[Query]) -> Vec<u64> {
    qs.iter()
        .flat_map(|q| &q.steps)
        .filter_map(|s| match s {
            Own::Input(id, _) | Own::Derive(id, _, _) => Some(*id),
            Own::Delete(_) => None,
        })
        .collect()
}

/// Apply one random corruption somewhere in the queries.  Returns a description.
fn corrupt(r: &mut Rng, qs: &mut [Query], nvars: u32) -> String {
    let all = ids(qs);
    let max_id = all.iter().copied().max().unwrap_or(1);
    let qi = r.below(qs.len() as u64) as usize;
    let q = &mut qs[qi];
    let kind = r.below(14);
    if kind == 0 {
        let a = r.lit(nvars);
        let i = r.below(q.assumptions.len() as u64 + 1) as usize;
        if i < q.assumptions.len() {
            q.assumptions.remove(i);
            return format!("q{qi}: drop assumption {i}");
        }
        q.assumptions.push(a);
        return format!("q{qi}: add assumption {a:?}");
    }
    if kind == 1 {
        q.last = 1 + r.below(max_id + 2);
        return format!("q{qi}: final clause {}", q.last);
    }
    if q.steps.is_empty() {
        return "nothing".into();
    }
    let si = r.below(q.steps.len() as u64) as usize;
    if kind == 2 {
        let removed = q.steps.remove(si);
        return format!("q{qi}: remove step {si}: {removed:?}");
    }
    if kind == 13 {
        let id = 1 + r.below(max_id + 2);
        q.steps.insert(si, Own::Delete(id));
        return format!("q{qi}: insert delete {id} at {si}");
    }
    let step = &mut q.steps[si];
    let pick = |r: &mut Rng, n: usize| r.below(n.max(1) as u64) as usize;
    match (kind, step) {
        (3, Own::Derive(_, l, _)) | (3, Own::Input(_, l)) if !l.is_empty() => {
            let i = pick(r, l.len());
            l[i] = !l[i];
            format!("q{qi} step {si}: negate literal {i}")
        }
        (4, Own::Derive(_, l, _)) | (4, Own::Input(_, l)) if !l.is_empty() => {
            let i = pick(r, l.len());
            l.remove(i);
            format!("q{qi} step {si}: drop literal {i}")
        }
        (5, Own::Derive(_, l, _)) | (5, Own::Input(_, l)) => {
            let x = r.lit(nvars);
            l.push(x);
            format!("q{qi} step {si}: add literal {x:?}")
        }
        (6, Own::Derive(_, l, _)) | (6, Own::Input(_, l)) if !l.is_empty() => {
            let i = pick(r, l.len());
            l[i] = r.lit(nvars);
            format!("q{qi} step {si}: replace literal {i}")
        }
        (7, Own::Derive(_, _, h)) if !h.is_empty() => {
            let i = pick(r, h.len());
            h.remove(i);
            format!("q{qi} step {si}: drop hint {i}")
        }
        (8, Own::Derive(_, _, h)) if h.len() > 1 => {
            let i = pick(r, h.len());
            let j = pick(r, h.len());
            h.swap(i, j);
            format!("q{qi} step {si}: swap hints {i} {j}")
        }
        (9, Own::Derive(_, _, h)) if !h.is_empty() => {
            let i = pick(r, h.len());
            h[i] = 1 + r.below(max_id + 2);
            format!("q{qi} step {si}: hint {i} := {}", h[i])
        }
        (10, Own::Derive(id, _, h)) => {
            h.push(*id);
            format!("q{qi} step {si}: self hint")
        }
        (11, s @ Own::Derive(..)) => {
            // Turn a derived clause into an input: the checker then trusts it, and so does
            // the oracle, which follows the trace's inputs.
            if let Own::Derive(id, l, _) = s {
                *s = Own::Input(*id, std::mem::take(l));
            }
            format!("q{qi} step {si}: derived clause made an input (allowed)")
        }
        (12, Own::Delete(id)) => {
            *id = 1 + r.below(max_id + 2);
            format!("q{qi} step {si}: delete {id}")
        }
        (_, Own::Derive(_, l, _)) => {
            // Claim a stronger clause: drop every literal, keep the hints.
            l.clear();
            format!("q{qi} step {si}: claim the empty clause")
        }
        _ => "nothing".into(),
    }
}

#[test]
fn genuine_proofs_are_accepted() {
    let mut r = Rng::new(seed(0xc0ffee));
    let mut total = 0;
    for iter in 0..iters(400) {
        let nvars = 3 + r.below(10) as u32;
        let qs = proofs(&mut r, nvars);
        let n = replay(nvars, &qs, &format!("iter {iter}"));
        assert_eq!(n, qs.len(), "iter {iter}: a genuine proof was rejected");
        total += n;
    }
    assert!(total > 500, "only {total} UNSAT answers");
}

#[test]
fn corrupted_proofs_are_never_accepted_wrongly() {
    let mut r = Rng::new(seed(0xbad_c0de));
    let (mut runs, mut rejected) = (0u64, 0u64);
    for iter in 0..iters(1500) {
        let nvars = 3 + r.below(10) as u32;
        let mut qs = proofs(&mut r, nvars);
        if qs.is_empty() {
            continue;
        }
        let n = qs.len();
        let mut what = Vec::new();
        for _ in 0..1 + r.below(3) {
            what.push(corrupt(&mut r, &mut qs, nvars));
        }
        // Panics if anything false was accepted.
        let accepted = replay(nvars, &qs, &format!("iter {iter}: {what:?}"));
        runs += 1;
        rejected += (accepted < n) as u64;
    }
    // Many corruptions break the proof; the rest were harmless (checked above: an input clause
    // or assumption that the proof does not use, a hint that was not needed).  Make sure the
    // test is not vacuous.
    eprintln!("{rejected} of {runs} corrupted traces rejected");
    assert!(
        rejected * 4 > runs,
        "only {rejected} of {runs} corrupted traces rejected"
    );
}

/// Traces made of random steps: whatever is accepted must be true.
#[test]
fn random_traces() {
    let mut r = Rng::new(seed(0x7ace));
    let mut accepted_derived = 0;
    for _ in 0..iters(3000) {
        let nvars = 2 + r.below(5) as u32;
        let mut steps = Vec::new();
        let mut next = 1u64;
        for _ in 0..2 + r.below(12) {
            let w = r.below(4);
            let lits: Vec<Lit> = (0..w).map(|_| r.lit(nvars)).collect();
            let s = match r.below(5) {
                0 | 1 => Own::Input(next, lits),
                2 | 3 => {
                    let h = (0..r.below(6)).map(|_| 1 + r.below(next + 1)).collect();
                    Own::Derive(next, lits, h)
                }
                _ => Own::Delete(1 + r.below(next)),
            };
            if !matches!(s, Own::Delete(_)) && r.below(16) != 0 {
                next += 1;
            }
            steps.push(s);
        }
        let assumptions: Vec<Lit> = (0..r.below(3)).map(|_| r.lit(nvars)).collect();
        let q = Query {
            last: 1 + r.below(next),
            steps,
            assumptions,
        };
        // Count derived clauses that survive, to make sure the test is not vacuous.
        let mut c = Checker::new();
        for s in &q.steps {
            let t = trace(std::slice::from_ref(s));
            if c.step(t.steps().next().unwrap()).is_err() {
                break;
            }
            accepted_derived += matches!(s, Own::Derive(..)) as u64;
        }
        replay(nvars, &[q], "random trace");
    }
    assert!(
        accepted_derived > 100,
        "only {accepted_derived} derived clauses accepted"
    );
}

/// Hand-written proofs and the specific ways they must fail.
#[test]
fn handwritten() {
    let x = |v: u32| Lit::new(v, false);
    let check = |steps: &[Own], assumptions: &[Lit], last: u64| -> Result<(), String> {
        let mut c = Checker::new();
        c.check(&trace(steps))?;
        c.check_unsat(assumptions, last)
    };
    // (a | b), (!a | b), (a | !b), (!a | !b): resolution proof of the empty clause.
    let (a, b) = (x(0), x(1));
    let base = vec![
        Own::Input(1, vec![a, b]),
        Own::Input(2, vec![!a, b]),
        Own::Input(3, vec![a, !b]),
        Own::Input(4, vec![!a, !b]),
    ];
    let mut good = base.clone();
    good.push(Own::Derive(5, vec![b], vec![1, 2]));
    good.push(Own::Derive(6, vec![], vec![5, 3, 4]));
    assert_eq!(check(&good, &[], 6), Ok(()));
    // Also usable as the answer under any assumptions.
    assert_eq!(check(&good, &[a, !b], 6), Ok(()));
    // The unit clause b is not an UNSAT answer, except under the assumption !b.
    assert!(check(&good, &[], 5).is_err());
    assert_eq!(check(&good, &[!b], 5), Ok(()));
    assert!(check(&good, &[b], 5).is_err());
    // Wrong hint order: 3 is not unit before 5 has made b true.
    let mut bad = base.clone();
    bad.push(Own::Derive(5, vec![b], vec![1, 2]));
    bad.push(Own::Derive(6, vec![], vec![3, 5, 4]));
    assert!(check(&bad, &[], 6).is_err());
    // Missing the last hint: no conflict.
    let mut bad = base.clone();
    bad.push(Own::Derive(5, vec![b], vec![1]));
    assert!(check(&bad, &[], 5).is_err());
    // A hint deleted before use.
    let mut bad = base.clone();
    bad.push(Own::Delete(2));
    bad.push(Own::Derive(5, vec![b], vec![1, 2]));
    assert!(check(&bad, &[], 5).is_err());
    // Using a deleted clause as the answer.
    let mut bad = good.clone();
    bad.push(Own::Delete(6));
    assert!(check(&bad, &[], 6).is_err());
    // A hint naming the clause itself or a later one.
    let mut bad = base.clone();
    bad.push(Own::Derive(5, vec![], vec![5]));
    assert!(check(&bad, &[], 5).is_err());
    // Identifiers out of sequence, repeated, or skipped.
    let mut bad = base.clone();
    bad.push(Own::Input(4, vec![a]));
    assert!(check(&bad, &[a], 4).is_err() || check(&bad, &[], 4).is_err());
    let mut bad = base.clone();
    bad.push(Own::Input(7, vec![!a]));
    assert!(check(&bad, &[a], 7).is_err());
    // A satisfied hint is an error, not a no-op.
    let mut bad = base.clone();
    bad.push(Own::Derive(5, vec![a, b], vec![1]));
    assert!(check(&bad, &[], 5).is_err());
    // Tautologies need no hints; repeated literals are fine.
    let mut ok = base.clone();
    ok.push(Own::Derive(5, vec![a, !a], vec![]));
    ok.push(Own::Derive(6, vec![b, b], vec![1, 2]));
    assert_eq!(check(&ok, &[!b], 6), Ok(()));
    // A unit clause with a repeated literal is still unit.
    let rep = vec![
        Own::Input(1, vec![a, a]),
        Own::Input(2, vec![!a]),
        Own::Derive(3, vec![], vec![1, 2]),
    ];
    assert_eq!(check(&rep, &[], 3), Ok(()));
    // Deleting an unknown clause.
    assert!(check(&[Own::Delete(1)], &[], 1).is_err());
    // Redefining a clause, even a deleted one.
    let redefine = [Own::Input(1, vec![a]), Own::Delete(1), Own::Input(1, vec![b])];
    assert!(Checker::new().check(&trace(&redefine)).is_err());
    let redefine = [Own::Input(1, vec![a]), Own::Derive(1, vec![a], vec![1])];
    assert!(Checker::new().check(&trace(&redefine)).is_err());
}

/// Enough deletions to make the checker compact its clause store; the survivors must keep
/// their identity.
#[test]
fn compaction_keeps_clauses() {
    let x = |v: u32| Lit::new(v, false);
    let mut steps = Vec::new();
    let mut id = 0u64;
    // 3000 groups: a long clause that is deleted, and a binary implication x_i -> x_{i+1}.
    for i in 0..3000u32 {
        id += 1;
        steps.push(Own::Input(id, (0..40).map(|k| x(10_000 + k)).collect()));
        steps.push(Own::Delete(id));
        id += 1;
        steps.push(Own::Input(id, vec![!x(i), x(i + 1)]));
    }
    // x_0 and !x_3000 contradict the chain; the hints are the chain in order.
    id += 1;
    steps.push(Own::Input(id, vec![x(0)]));
    let unit = id;
    id += 1;
    steps.push(Own::Input(id, vec![!x(3000)]));
    let last = id;
    let mut hints = vec![unit];
    hints.extend((0..3000u64).map(|i| 2 * i + 2));
    hints.push(last);
    id += 1;
    steps.push(Own::Derive(id, vec![], hints.clone()));
    let mut c = Checker::new();
    assert_eq!(c.check(&trace(&steps)), Ok(()));
    assert_eq!(c.check_unsat(&[], id), Ok(()));
    // The same with one link missing must fail.
    hints.remove(1500);
    steps.pop();
    steps.push(Own::Derive(id, vec![], hints));
    assert!(Checker::new().check(&trace(&steps)).is_err());
}