cverif 0.0.7

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
//! What the callers of a function with internal linkage pass to it.
//!
//! A `static` function whose address is never taken can only be entered from the calls
//! written in its translation unit, and compilers specialise its code for them: an argument
//! that is 0, 1, 2 or 3 at every call lets `flags & 2` become `flags >= 2`.  Such a function is
//! verified for the argument values its callers can pass, not for every value of the
//! parameter's type.
//!
//! The values are read off the source: a parameter has a known set when every call passes
//! a constant, or one of the caller's own parameters that has a known set.  Anything else
//! (one call with a computed argument, the address taken anywhere, a function of the unit
//! the front end could not read) leaves the parameter unconstrained.
//!
//! Soundness.  The claim made for the function is "for these argument values" and is
//! reported as such.  It is the whole truth because the binary's callers are verified
//! against the same source calls: a caller's proof shows that the binary passes what the
//! source passes (the argument of the call event, or the callee followed with the actual
//! value), and code of the binary that is not a verified function is not counted as proved
//! anyway.

use super::ast::{EK, Expr, OpKind, Program, Term, Type};
use std::collections::BTreeSet;

/// Most distinct values a parameter may take and still be described by enumeration.
const MAX_VALUES: usize = 16;

/// For every function, per parameter: the values its callers pass, when known.
pub type Given = Vec<Vec<Option<BTreeSet<u64>>>>;

/// What is known about who calls each function.
#[derive(Default, Clone, Debug)]
pub struct Callers {
    pub given: Given,
    /// Where the values are not few enough to list: a bound every call's argument is below,
    /// when each call passes a constant, a value of a narrower unsigned type (which the
    /// conversion to the parameter's type extends with zeros) or a parameter of the caller
    /// that has such a bound.  Compilers use it like the listed values (`n > 0` becomes
    /// `n != 0` for a parameter that only receives `uint8_t` values).
    pub below: Vec<Vec<Option<u64>>>,
    /// The function has internal linkage, its address is never taken and every function of
    /// its translation unit was read: it is only entered from `callers`.  How such a
    /// function is called is the compiler's business (it may drop an unused argument or a
    /// result nobody uses), so it is only meaningful together with its callers.
    pub private: Vec<bool>,
    /// The functions with a direct call to it.
    pub callers: Vec<Vec<u32>>,
    /// A `private` function none of whose calls uses the result: every call is an
    /// expression statement.  The compiler need not compute the result at all (clang
    /// removes it), so it is not compared, and the binary's callers are verified with an
    /// unknown value in the result register after the call.
    pub result_unused: Vec<bool>,
}

#[derive(Clone, Debug)]
enum Arg {
    Const(u64),
    /// The caller's own parameter, passed on unchanged.
    Param(u32),
    /// A value of an unsigned type of this many bits, extended with zeros.
    Narrow(u32),
    Unknown,
}

struct Scan<'a> {
    prog: &'a Program,
    /// Functions referred to other than as the callee of a direct call.
    taken: Vec<bool>,
    /// Direct calls: (caller, callee, arguments).
    calls: Vec<(u32, u32, Vec<Arg>)>,
    caller: u32,
    /// Parameters of the caller that it assigns to or takes the address of.
    dirty: Vec<BTreeSet<u32>>,
    /// Functions with a call whose result is used.
    used: Vec<bool>,
    /// The expression being visited is a whole expression statement.
    statement: bool,
}

fn direct(e: &Expr) -> Option<u32> {
    match &e.kind {
        EK::Func(f) => Some(*f),
        EK::Addr(f) | EK::Cast(f) => direct(f),
        _ => None,
    }
}

/// The value `v` of integer type `from` converted to integer type `to`, as bits of `to`.
fn convert(p: &Program, v: u64, from: super::ast::TypeId, to: super::ast::TypeId) -> u64 {
    let mask = |w: u8| if w >= 64 { u64::MAX } else { (1u64 << w) - 1 };
    let (wf, wt) = (p.bits(from), p.bits(to));
    let mut v = v & mask(wf);
    if matches!(p.ty(p.unqual(to)), Type::Bool) {
        return (v != 0) as u64;
    }
    if p.is_signed(from) && wf < 64 && v >> (wf - 1) & 1 == 1 {
        v |= !mask(wf);
    }
    v & mask(wt)
}

impl Scan<'_> {
    /// The value of a constant integer expression of at most 32 bits, in its own type.
    fn konst(&self, e: &Expr) -> Option<u64> {
        let p = self.prog;
        let int = |t| matches!(p.ty(p.unqual(t)), Type::Int { .. } | Type::Bool);
        if !int(e.ty) || p.bits(e.ty) > 32 {
            return None;
        }
        let w = p.bits(e.ty);
        let mask = (1u64 << w) - 1;
        match &e.kind {
            EK::Const(c) => Some(convert(p, *c, e.ty, e.ty)),
            EK::Cast(inner) => Some(convert(p, self.konst(inner)?, inner.ty, e.ty)),
            // Operations that commute with truncation, on operands already converted to
            // the type of the result.
            EK::Bin(op, a, b) if p.bits(a.ty) == w && p.bits(b.ty) == w => {
                use super::ast::BinOp as B;
                let (x, y) = (self.konst(a)?, self.konst(b)?);
                let v = match op {
                    B::Add => x.wrapping_add(y),
                    B::Sub => x.wrapping_sub(y),
                    B::Mul => x.wrapping_mul(y),
                    B::And => x & y,
                    B::Or => x | y,
                    B::Xor => x ^ y,
                    _ => return None,
                };
                Some(v & mask)
            }
            _ => None,
        }
    }
}

impl Scan<'_> {
    fn arg(&self, e: &Expr, to: super::ast::TypeId) -> Arg {
        let p = self.prog;
        let int = |t| matches!(p.ty(p.unqual(t)), Type::Int { .. } | Type::Bool);
        if !int(to) || !int(e.ty) || p.bits(to) > 32 || p.bits(e.ty) > 32 {
            return Arg::Unknown;
        }
        // A constant expression: its value in its own type, then converted to the
        // parameter's type as the call converts it (a `_Bool` parameter receives 0 or 1,
        // a narrow signed value is sign-extended).
        if let Some(c) = self.konst(e) {
            return Arg::Const(convert(p, c, e.ty, to));
        }
        // A value of a narrower unsigned type, whatever computes it: the conversions up to
        // the parameter's type (each to a type at least as wide) leave it below 2^bits.
        let narrow = |e: &Expr| {
            let mut x = e;
            loop {
                let unsigned = matches!(p.ty(p.unqual(x.ty)), Type::Bool)
                    || (matches!(p.ty(p.unqual(x.ty)), Type::Int { .. }) && !p.is_signed(x.ty));
                let bits = if matches!(p.ty(p.unqual(x.ty)), Type::Bool) {
                    1
                } else {
                    p.bits(x.ty) as u32
                };
                if unsigned && bits < p.bits(to) as u32 && bits <= 16 {
                    return Some(bits);
                }
                match &x.kind {
                    EK::Cast(inner)
                        if int(inner.ty)
                            && p.bits(x.ty) >= p.bits(inner.ty)
                            && !matches!(p.ty(p.unqual(x.ty)), Type::Bool) =>
                    {
                        x = inner
                    }
                    _ => return None,
                }
            }
        };
        let fallback = || narrow(e).map_or(Arg::Unknown, Arg::Narrow);
        match &e.kind {
            // A conversion that keeps the value: to a type at least as wide.
            EK::Cast(inner) => match self.arg(inner, to) {
                Arg::Param(i)
                    if p.bits(e.ty) >= p.bits(inner.ty)
                        && !p.is_signed(inner.ty)
                        && !matches!(p.ty(p.unqual(e.ty)), Type::Bool) =>
                {
                    Arg::Param(i)
                }
                _ => fallback(),
            },
            EK::Load(l) => match &l.kind {
                EK::Local(i)
                    if (*i as usize) < p.funcs[self.caller as usize].nparams
                        && p.bits(e.ty) == p.bits(to)
                        && matches!(p.ty(p.unqual(e.ty)), Type::Bool) == matches!(p.ty(p.unqual(to)), Type::Bool) =>
                {
                    Arg::Param(*i)
                }
                _ => fallback(),
            },
            _ => fallback(),
        }
    }

    fn lvalue_root(&mut self, e: &Expr) {
        match &e.kind {
            EK::Local(i) => {
                self.dirty[self.caller as usize].insert(*i);
            }
            EK::Member(b, _) | EK::BitField(b, ..) | EK::Bits(b, ..) => self.lvalue_root(b),
            _ => {}
        }
    }

    fn expr(&mut self, e: &Expr) {
        let statement = std::mem::take(&mut self.statement);
        match &e.kind {
            // `(void)f(x);`
            EK::Cast(a) if statement && matches!(a.kind, EK::Call(..)) => {
                self.statement = true;
                self.expr(a);
            }
            EK::Func(f) => self.taken[*f as usize] = true,
            EK::Const(_) | EK::FConst(_) | EK::Str(_) | EK::Local(_) | EK::Global(_) | EK::Prev | EK::VlaLive(_) => {}
            EK::Addr(a) => {
                self.lvalue_root(a);
                self.expr(a);
            }
            EK::VaStart(a) | EK::VaArg(a) => {
                self.lvalue_root(a);
                self.expr(a);
            }
            EK::Deref(a)
            | EK::Member(a, _)
            | EK::BitField(a, ..)
            | EK::Bits(a, ..)
            | EK::Load(a)
            | EK::Cast(a)
            | EK::Neg(a)
            | EK::BitNot(a)
            | EK::Alloca(a, ..)
            | EK::LogNot(a) => self.expr(a),
            EK::Asm(a) => {
                if let Some(x) = &a.input {
                    self.expr(x);
                }
            }
            EK::Assign(a, b) | EK::AssignOp(a, b, _) => {
                self.lvalue_root(a);
                self.expr(a);
                self.expr(b);
            }
            EK::Bin(_, a, b)
            | EK::PtrAdd(a, b, _)
            | EK::PtrDiff(a, b, _)
            | EK::LogAnd(a, b)
            | EK::LogOr(a, b)
            | EK::Comma(a, b) => {
                self.expr(a);
                self.expr(b);
            }
            EK::Cond(a, b, c) => {
                self.expr(a);
                self.expr(b);
                self.expr(c);
            }
            EK::Compound { items, .. } => items.iter().for_each(|(_, x)| self.expr(x)),
            EK::Call(f, args) => {
                match direct(f) {
                    Some(callee) => {
                        if !statement {
                            self.used[callee as usize] = true;
                        }
                        let params = &self.prog.funcs[callee as usize].ty.params;
                        let vals = (args.iter().enumerate())
                            .map(|(i, a)| params.get(i).map_or(Arg::Unknown, |&t| self.arg(a, t)))
                            .collect();
                        self.calls.push((self.caller, callee, vals));
                    }
                    None => self.expr(f),
                }
                args.iter().for_each(|x| self.expr(x));
            }
        }
    }
}

/// See the module documentation.
pub fn callers(prog: &Program) -> Callers {
    callers_except(prog, &[])
}

/// The same, when some functions can be entered in ways the source does not show
/// (`exported[f]`: the image has a global symbol at the function's address, as an `alias`
/// attribute or a linker script makes one).
pub fn callers_except(prog: &Program, exported: &[bool]) -> Callers {
    let n = prog.funcs.len();
    let mut scan = Scan {
        prog,
        taken: (0..n).map(|i| exported.get(i).copied().unwrap_or(false)).collect(),
        calls: Vec::new(),
        caller: 0,
        dirty: vec![BTreeSet::new(); n],
        used: vec![false; n],
        statement: false,
    };
    for g in &prog.globals {
        if let Some(init) = &g.init {
            for (_, sym, _) in &init.relocs {
                if let super::ast::SymRef::Func(f) = sym {
                    scan.taken[*f as usize] = true;
                }
            }
        }
    }
    // A unit with a function the front end could not read may do anything with its statics.
    let mut unread = BTreeSet::new();
    let mut unread_funcs = Vec::new();
    for (i, f) in prog.funcs.iter().enumerate() {
        if f.unsupported.is_some() || f.opaque {
            unread_funcs.push(i);
        }
        let Some(body) = &f.body else { continue };
        scan.caller = i as u32;
        for b in &body.blocks {
            for op in &b.ops {
                match &op.kind {
                    OpKind::Eval(e) => {
                        scan.statement = true;
                        scan.expr(e);
                    }
                    OpKind::Init { items, .. } => items.iter().for_each(|(_, e)| scan.expr(e)),
                }
            }
            match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => scan.expr(e),
                Term::Jump(_) | Term::Ret(None) | Term::Unreachable => {}
            }
        }
    }
    // ... unless it cannot run at all: a function with internal linkage that no function
    // that was read calls or mentions, in a unit where the same holds for every unread
    // function (an unused `static inline` of a header, typically).  Code only reachable
    // from such functions is dead: whatever starts executing one of them is itself one of
    // them, and none can be entered from outside the unit or from what was read.
    let mentioned = |i: usize| scan.taken[i] || scan.calls.iter().any(|c| c.1 == i as u32);
    for &i in &unread_funcs {
        if !prog.funcs[i].is_static || mentioned(i) {
            unread.insert(prog.func_unit[i]);
        }
    }
    let eligible: Vec<bool> = (0..n)
        .map(|i| {
            let f = &prog.funcs[i];
            f.is_static
                && f.body.is_some()
                && !f.variadic_def
                && !scan.taken[i]
                && !unread.contains(&prog.func_unit[i])
                && scan.calls.iter().any(|c| c.1 == i as u32)
        })
        .collect();
    // Start from "no value at all" and add what each call passes until nothing changes; a
    // parameter that receives something unknown is given up for good.
    let mut sets: Given = (0..n)
        .map(|i| vec![eligible[i].then(BTreeSet::new); prog.funcs[i].ty.params.len()])
        .collect();
    loop {
        let mut changed = false;
        for (caller, callee, args) in &scan.calls {
            let (caller, callee) = (*caller as usize, *callee as usize);
            if !eligible[callee] {
                continue;
            }
            for k in 0..sets[callee].len() {
                if sets[callee][k].is_none() {
                    continue;
                }
                let add: Option<BTreeSet<u64>> = match args.get(k) {
                    Some(Arg::Const(c)) => Some([*c].into()),
                    Some(Arg::Param(i)) if !scan.dirty[caller].contains(i) => {
                        sets[caller].get(*i as usize).cloned().flatten()
                    }
                    _ => None,
                };
                let cur = sets[callee][k].as_mut().unwrap();
                match add {
                    Some(vals) if cur.len() + vals.len() <= 2 * MAX_VALUES => {
                        for v in vals {
                            changed |= cur.insert(v);
                        }
                        if cur.len() > MAX_VALUES {
                            sets[callee][k] = None;
                            changed = true;
                        }
                    }
                    _ => {
                        sets[callee][k] = None;
                        changed = true;
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    // The bounds, the same way: the least bound every call stays below, growing until
    // nothing changes; one unknown argument and there is none.
    let mut below: Vec<Vec<Option<u64>>> = (0..n)
        .map(|i| vec![eligible[i].then_some(0); prog.funcs[i].ty.params.len()])
        .collect();
    loop {
        let mut changed = false;
        for (caller, callee, args) in &scan.calls {
            let (caller, callee) = (*caller as usize, *callee as usize);
            if !eligible[callee] {
                continue;
            }
            for k in 0..below[callee].len() {
                let Some(cur) = below[callee][k] else { continue };
                let add: Option<u64> = match args.get(k) {
                    Some(Arg::Const(c)) if *c < 1 << 16 => Some(*c + 1),
                    Some(Arg::Narrow(bits)) => Some(1 << *bits),
                    Some(Arg::Param(i)) if !scan.dirty[caller].contains(i) => {
                        below[caller].get(*i as usize).copied().flatten()
                    }
                    _ => None,
                };
                let next = add.map(|a| a.max(cur));
                if next != Some(cur) {
                    below[callee][k] = next;
                    changed = true;
                }
            }
        }
        if !changed {
            break;
        }
    }
    for f in &mut below {
        for b in f.iter_mut() {
            if *b == Some(0) {
                *b = None;
            }
        }
    }
    // A set still empty belongs to a function only called from callers that are themselves
    // never called with known values: nothing is known.
    for f in &mut sets {
        for s in f.iter_mut() {
            if s.as_ref().is_some_and(|s| s.is_empty()) {
                *s = None;
            }
        }
    }
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        for (i, f) in prog.funcs.iter().enumerate() {
            if f.is_static && f.body.is_some() {
                eprintln!(
                    "callers of {}: eligible={} taken={} calls={:?} sets={:?}",
                    f.name,
                    eligible[i],
                    scan.taken[i],
                    scan.calls
                        .iter()
                        .filter(|c| c.1 == i as u32)
                        .map(|c| &c.2)
                        .collect::<Vec<_>>(),
                    sets[i]
                );
            }
        }
    }
    let mut callers = vec![Vec::new(); n];
    for (caller, callee, _) in &scan.calls {
        if !callers[*callee as usize].contains(caller) {
            callers[*callee as usize].push(*caller);
        }
    }
    let void = |i: usize| prog.funcs[i].ty.ret == super::ast::VOID;
    Callers {
        given: sets,
        below,
        result_unused: (0..n).map(|i| eligible[i] && !scan.used[i] && !void(i)).collect(),
        private: eligible,
        callers,
    }
}