cverif 0.0.0

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
//! Shared symbolic-execution context: path condition, branching through the
//! prover, deterministic path replay and the memory model used by both the C
//! and the machine-code executors.

use crate::bv::{Prover, Verdict};
use crate::term::{Env, T, Terms};
use std::collections::{HashMap, HashSet};

/// Why a path stopped before producing a comparable result.
#[derive(Debug, Clone)]
pub enum Stop {
    /// Exploration limit reached; the path (and its subtree) is not verified.
    Truncated(String),
    /// A construct the tool does not model.
    Unsupported(String),
    /// The two sides provably differ; the environment is a concrete witness.
    Mismatch(String, Option<Box<Env>>),
    /// The prover could not decide an equality.
    Inconclusive(String),
    /// The C program has undefined behaviour on every input of this path.
    Undefined,
}

pub type R<V> = Result<V, Stop>;

#[derive(Clone, Debug)]
pub struct Write {
    pub addr: T,
    /// Size in bytes.
    pub size: u8,
    pub val: T,
}

/// Memory of one side: a write log for "world" memory (anything reachable by the
/// caller) and one per private object (stack frame, C locals).
#[derive(Clone, Debug, Default)]
pub struct Mem {
    pub world: Vec<Write>,
    pub private: HashMap<T, Vec<Write>>,
    /// Snapshot id of world memory; bumped by every external call.
    pub epoch: u32,
}

/// Snapshot id used for never-written private memory (uninitialised locals, stack).
pub const UNINIT_EPOCH: u32 = 0x8000_0000;

#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Maximum number of undetermined branches on one path.
    pub max_depth: usize,
    /// Maximum number of paths per function.
    pub max_paths: usize,
    /// Maximum number of executed C blocks / instructions per path.
    pub max_steps: u64,
    pub max_call_depth: usize,
}

impl Default for Limits {
    fn default() -> Self {
        Limits {
            max_depth: 40,
            max_paths: 2000,
            max_steps: 20_000,
            max_call_depth: 48,
        }
    }
}

pub struct Ctx {
    pub tm: Terms,
    pub prover: Prover,
    /// Path condition: preconditions and branch decisions.
    pub pc: Vec<T>,
    /// Conditions under which the C program has defined behaviour on this path.
    pub ub: Vec<T>,
    pub decisions: Vec<bool>,
    pub pos: usize,
    pub steps: u64,
    pub limits: Limits,
    /// Base addresses of private objects.
    pub private_bases: HashSet<T>,
    named: HashMap<String, T>,
}

impl Ctx {
    pub fn new(limits: Limits) -> Ctx {
        Ctx {
            tm: Terms::new(),
            prover: Prover::new(),
            pc: Vec::new(),
            ub: Vec::new(),
            decisions: Vec::new(),
            pos: 0,
            steps: 0,
            limits,
            private_bases: HashSet::new(),
            named: HashMap::new(),
        }
    }

    /// A symbol identified by name: the same name gives the same symbol on every path.
    pub fn named_sym(&mut self, name: &str, w: u8) -> T {
        if let Some(&t) = self.named.get(name) {
            debug_assert_eq!(self.tm.width(t), w);
            return t;
        }
        let t = self.tm.sym(name, w);
        self.named.insert(name.to_string(), t);
        t
    }

    pub fn private_base(&mut self, name: &str) -> T {
        let t = self.named_sym(name, 32);
        self.private_bases.insert(t);
        t
    }

    /// Start replaying from the beginning with the current decision vector.
    pub fn restart(&mut self, pre: &[T]) {
        self.pc.clear();
        self.pc.extend_from_slice(pre);
        self.ub.clear();
        self.pos = 0;
        self.steps = 0;
    }

    /// Advance the decision vector to the next unexplored path.  False when done.
    pub fn next_path(&mut self) -> bool {
        while let Some(last) = self.decisions.pop() {
            if last {
                self.decisions.push(false);
                return true;
            }
        }
        false
    }

    pub fn step(&mut self) -> R<()> {
        self.steps += 1;
        if self.steps > self.limits.max_steps {
            return Err(Stop::Truncated("step limit".into()));
        }
        Ok(())
    }

    /// Does the path condition (with the no-undefined-behaviour assumptions if needed) imply `goal`?
    pub fn implied(&mut self, goal: T) -> bool {
        self.check(goal).is_ok()
    }

    /// Prove `goal` on this path.  On failure returns a counterexample if one exists (None = solver gave up).
    pub fn check(&mut self, goal: T) -> Result<(), Option<Box<Env>>> {
        if self.tm.is_true(goal) {
            return Ok(());
        }
        match self.prover.prove(&mut self.tm, &self.pc, goal) {
            Verdict::Proved => return Ok(()),
            Verdict::Refuted(env) if self.ub.is_empty() => return Err(Some(env)),
            Verdict::Unknown if self.ub.is_empty() => return Err(None),
            _ => {}
        }
        let mut all = self.pc.clone();
        all.extend_from_slice(&self.ub);
        match self.prover.prove(&mut self.tm, &all, goal) {
            Verdict::Proved => Ok(()),
            Verdict::Refuted(env) => Err(Some(env)),
            Verdict::Unknown => Err(None),
        }
    }

    /// Decide a branch condition, forking the path if it is not determined.
    pub fn branch(&mut self, cond: T) -> R<bool> {
        if let Some(c) = self.tm.as_const(cond) {
            return Ok(c == 1);
        }
        let n = self.tm.not(cond);
        if self.pc.contains(&cond) {
            return Ok(true);
        }
        if self.pc.contains(&n) {
            return Ok(false);
        }
        if self.implied(cond) {
            return Ok(true);
        }
        if self.implied(n) {
            return Ok(false);
        }
        let d = if self.pos < self.decisions.len() {
            self.decisions[self.pos]
        } else {
            if self.decisions.len() >= self.limits.max_depth {
                return Err(Stop::Truncated("branch depth limit".into()));
            }
            self.decisions.push(true);
            true
        };
        self.pos += 1;
        self.pc.push(if d { cond } else { n });
        Ok(d)
    }

    /// Record that the C program is only defined when `cond` holds.
    pub fn assume(&mut self, cond: T) -> R<()> {
        if self.tm.is_true(cond) {
            return Ok(());
        }
        if self.tm.is_false(cond) {
            return Err(Stop::Undefined);
        }
        if !self.ub.contains(&cond) {
            self.ub.push(cond);
        }
        Ok(())
    }

    /// If the path condition pins `t` to a single value, return it.
    pub fn unique_value(&mut self, t: T) -> Option<u64> {
        if let Some(v) = self.tm.as_const(t) {
            return Some(v);
        }
        let f = self.tm.fals();
        let Err(Some(env)) = self.check(f) else { return None };
        let v = self.tm.eval(t, &env, &mut HashMap::new());
        let k = self.tm.konst(self.tm.width(t), v);
        let e = self.tm.eq(t, k);
        if self.implied(e) { Some(v) } else { None }
    }

    // ----- memory -------------------------------------------------------------

    /// The private object an address belongs to, if any.
    pub fn region(&self, addr: T) -> Option<T> {
        if self.private_bases.contains(&addr) {
            return Some(addr);
        }
        let (ts, _) = self.tm.linear(addr);
        ts.iter().map(|x| x.0).find(|t| self.private_bases.contains(t))
    }

    pub fn mem_write(&mut self, mem: &mut Mem, addr: T, size: u8, val: T) {
        debug_assert_eq!(self.tm.width(val), size * 8);
        let log = match self.region(addr) {
            Some(r) => mem.private.entry(r).or_default(),
            None => &mut mem.world,
        };
        // Drop older writes that this one fully covers.
        let tm = &mut self.tm;
        log.retain(|e| match tm.const_diff(e.addr, addr) {
            Some(d) => {
                let d = d as u32 as i32 as i64;
                !(d >= 0 && d + e.size as i64 <= size as i64)
            }
            None => true,
        });
        log.push(Write { addr, size, val });
    }

    /// Read `size` bytes at `addr`.  `init` supplies the value of never-written memory.
    pub fn mem_read(&mut self, mem: &Mem, addr: T, size: u8, init: &mut dyn FnMut(&mut Ctx, T, u8) -> T) -> T {
        static EMPTY: Vec<Write> = Vec::new();
        let log = match self.region(addr) {
            Some(r) => mem.private.get(&r).unwrap_or(&EMPTY),
            None => &mem.world,
        };
        self.read_log(log, log.len(), addr, size, init)
    }

    fn read_log(
        &mut self,
        log: &[Write],
        n: usize,
        addr: T,
        size: u8,
        init: &mut dyn FnMut(&mut Ctx, T, u8) -> T,
    ) -> T {
        let mut slow_at = None;
        for i in (0..n).rev() {
            let e = &log[i];
            match self.tm.const_diff(addr, e.addr) {
                Some(d) => {
                    let d = d as u32 as i32 as i64;
                    if d >= e.size as i64 || d + size as i64 <= 0 {
                        continue;
                    }
                    if d >= 0 && d + size as i64 <= e.size as i64 {
                        return self.tm.extract(e.val, d as u8 * 8, size * 8);
                    }
                    slow_at = Some(i);
                    break;
                }
                None => {
                    if e.size == size {
                        let same = self.tm.eq(addr, e.addr);
                        if self.implied(same) {
                            return e.val;
                        }
                    }
                    let dis = self.disjoint(addr, size, e);
                    if self.implied(dis) {
                        continue;
                    }
                    slow_at = Some(i);
                    break;
                }
            }
        }
        let Some(i) = slow_at else {
            return init(self, addr, size);
        };
        if size > 1 {
            // Assemble from single bytes.
            let mut acc: Option<T> = None;
            for k in 0..size {
                let a = self.tm.add_const(addr, k as u64);
                let b = self.read_log(log, i + 1, a, 1, init);
                acc = Some(match acc {
                    None => b,
                    Some(lo) => self.tm.concat(b, lo),
                });
            }
            return acc.unwrap();
        }
        // One byte against an entry whose relation is unknown.
        let e = &log[i];
        let w = self.tm.width(addr);
        let d = self.tm.sub(addr, e.addr);
        let sz = self.tm.konst(w, e.size as u64);
        let inside = self.tm.ult(d, sz);
        let sel = if e.size == 1 {
            e.val
        } else {
            let vw = self.tm.width(e.val);
            let d8 = self.tm.scale(d, 8);
            let amt = self.tm.resize(d8, vw, false);
            let sh = self.tm.lshr(e.val, amt);
            self.tm.trunc(sh, 8)
        };
        if self.implied(inside) {
            return sel;
        }
        let rest = self.read_log(log, i, addr, 1, init);
        self.tm.ite(inside, sel, rest)
    }

    fn disjoint(&mut self, addr: T, size: u8, e: &Write) -> T {
        let w = self.tm.width(addr);
        let d1 = self.tm.sub(addr, e.addr);
        let d2 = self.tm.sub(e.addr, addr);
        let s1 = self.tm.konst(w, e.size as u64);
        let s2 = self.tm.konst(w, size as u64);
        let a = self.tm.ule(s1, d1);
        let b = self.tm.ule(s2, d2);
        self.tm.and(a, b)
    }

    /// Does `t` mention the address of a private object?
    pub fn mentions_private(&self, t: T) -> bool {
        let mut seen = HashSet::new();
        let mut stack = vec![t];
        while let Some(x) = stack.pop() {
            if !seen.insert(x) {
                continue;
            }
            if self.private_bases.contains(&x) {
                return true;
            }
            stack.extend(crate::bv::Prover::children_of(self.tm.node(x)));
        }
        false
    }
}

/// Where the AAPCS places an argument.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ArgLoc {
    Reg(u8),
    /// 64-bit value in registers n (low) and n + 1 (high).
    RegPair(u8),
    /// Offset from the stack pointer at the call.
    Stack(u32),
    Stack64(u32),
}

/// Assign AAPCS32 locations to integer arguments of the given bit widths (<= 32 or 64).
pub fn arg_locs(widths: &[u8]) -> Vec<ArgLoc> {
    let mut ncrn = 0u8;
    let mut nsaa = 0u32;
    widths
        .iter()
        .map(|&w| {
            if w <= 32 {
                if ncrn < 4 {
                    ncrn += 1;
                    ArgLoc::Reg(ncrn - 1)
                } else {
                    nsaa += 4;
                    ArgLoc::Stack(nsaa - 4)
                }
            } else {
                ncrn = ncrn.next_multiple_of(2);
                if ncrn <= 2 {
                    ncrn += 2;
                    ArgLoc::RegPair(ncrn - 2)
                } else {
                    ncrn = 4;
                    nsaa = nsaa.next_multiple_of(8) + 8;
                    ArgLoc::Stack64(nsaa - 8)
                }
            }
        })
        .collect()
}

/// An externally observable call made by the C side, to be matched by the binary.
#[derive(Clone, Debug)]
pub struct Event {
    pub name: String,
    /// Argument values and whether each is signed (for extension to register width).
    pub args: Vec<(T, bool)>,
    /// World memory at the time of the call.
    pub writes: Vec<Write>,
    pub epoch: u32,
    /// Symbol standing for the returned value, and its signedness.
    pub ret: Option<(T, bool)>,
    pub noreturn: bool,
}