cverif 0.0.3

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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
//! Typed C program representation (target: ARM EABI, ILP32, little-endian).

use super::lex::Loc;
use std::collections::HashMap;
use std::sync::Arc as Rc; // shared read-only between verification threads

pub type TypeId = u32;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FuncType {
    pub ret: TypeId,
    pub params: Vec<TypeId>,
    pub variadic: bool,
    /// Declared with a prototype (`f(void)` or `f(int)`, as opposed to `f()`).
    pub proto: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Type {
    Void,
    Bool,
    Int { size: u8, signed: bool },
    Float { size: u8 },
    Ptr(TypeId),
    Array(TypeId, Option<u32>),
    Func(Rc<FuncType>),
    Record(u32),
}

pub const VOID: TypeId = 0;
pub const BOOL: TypeId = 1;
pub const UCHAR: TypeId = 2;
pub const SCHAR: TypeId = 3;
pub const SHORT: TypeId = 4;
pub const USHORT: TypeId = 5;
pub const INT: TypeId = 6;
pub const UINT: TypeId = 7;
pub const LLONG: TypeId = 8;
pub const ULLONG: TypeId = 9;
pub const FLOAT: TypeId = 10;
pub const DOUBLE: TypeId = 11;

#[derive(Clone, Debug)]
pub struct Field {
    pub name: Rc<str>,
    pub ty: TypeId,
    pub offset: u32,
    /// Bit-field: (first bit within the byte at `offset`, width in bits).
    pub bits: Option<(u8, u8)>,
}

#[derive(Clone, Debug)]
pub struct Record {
    pub name: Option<Rc<str>>,
    pub is_union: bool,
    pub fields: Vec<Field>,
    pub size: u32,
    pub align: u32,
    pub complete: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum SymRef {
    Global(u32),
    Func(u32),
    Str(u32),
}

/// Initial contents of a global: raw bytes plus address relocations.
#[derive(Clone, Debug, Default)]
pub struct Init {
    pub bytes: Vec<u8>,
    /// (offset, target, addend): a 32-bit pointer to `target + addend` is stored at `offset`.
    pub relocs: Vec<(u32, SymRef, i64)>,
}

#[derive(Clone, Debug)]
pub struct Global {
    pub name: Rc<str>,
    pub ty: TypeId,
    /// Internal linkage (file-scope `static`) or function-local `static`.
    pub is_static: bool,
    /// Function-local static: the binary symbol is `name.N`.
    pub is_local_static: bool,
    pub is_const: bool,
    pub is_volatile: bool,
    /// Has a definition (initializer or tentative definition) rather than only `extern`.
    pub defined: bool,
    pub init: Option<Init>,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub struct Local {
    pub name: Rc<str>,
    pub ty: TypeId,
}

#[derive(Clone, Debug)]
pub struct Func {
    pub name: Rc<str>,
    pub ty: Rc<FuncType>,
    pub is_static: bool,
    pub is_inline: bool,
    /// The first `nparams` locals are the parameters.
    pub nparams: usize,
    pub locals: Vec<Local>,
    pub body: Option<Body>,
    pub loc: Loc,
    /// The body uses something the front end cannot model ("line N: reason"); the function
    /// has an empty stand-in body and must be reported as unsupported, as must its callers.
    pub unsupported: Option<String>,
    /// Number of fixed parameters is `nparams`; this one also takes variable arguments.
    pub variadic_def: bool,
    /// Written in assembly (a `naked` function, or a body that is nothing but inline assembly
    /// the front end has no meaning for): the function itself cannot be verified, but its
    /// callers treat it like a function defined elsewhere.
    pub opaque: bool,
}

/// One instruction of an inline assembly statement that the front end knows the meaning of: an
/// observable event the binary must reproduce with the same instruction.
#[derive(Clone, Debug)]
pub struct AsmInsn {
    /// The instruction without its register operand: `cpsid i`, `wfi`, `bkpt 3`, `mrs primask`,
    /// `msr basepri`.
    pub name: Rc<str>,
    /// The value an MSR writes.
    pub input: Option<Expr>,
    /// The instruction produces a value (MRS): it is the value of the expression.
    pub output: bool,
    /// The statement lists `memory` among the things it clobbers: as far as memory is concerned
    /// it is a call to an unknown function.
    pub memory: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    And,
    Or,
    Xor,
    Shl,
    Shr,
    Eq,
    Ne,
    Lt,
    Le,
}

#[derive(Clone, Debug)]
pub struct Expr {
    pub kind: EK,
    pub ty: TypeId,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum EK {
    Const(u64),
    FConst(f64),
    // --- lvalues ---
    Str(u32),
    Local(u32),
    Global(u32),
    /// Function designator.
    Func(u32),
    Deref(Box<Expr>),
    /// Member of the lvalue at byte offset.
    Member(Box<Expr>, u32),
    /// Bit-field member of the lvalue: byte offset, first bit within that byte, width.
    BitField(Box<Expr>, u32, u8, u8),
    /// Compound literal: an unnamed local that is (re)initialised whenever the expression is evaluated.
    Compound {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
    /// Only as an initialiser item: the value of a bit-field (first bit, width) of the unit at the item's offset.
    Bits(Box<Expr>, u8, u8),
    // --- rvalues ---
    /// Address of an lvalue (also array and function decay).
    Addr(Box<Expr>),
    /// Lvalue-to-rvalue conversion.
    Load(Box<Expr>),
    /// Conversion to `ty`.
    Cast(Box<Expr>),
    Neg(Box<Expr>),
    BitNot(Box<Expr>),
    LogNot(Box<Expr>),
    /// Operands already converted to the operation type (the left operand's type).
    Bin(BinOp, Box<Expr>, Box<Expr>),
    /// pointer + index * elem_size; index is a 32-bit signed integer.
    PtrAdd(Box<Expr>, Box<Expr>, u32),
    /// (a - b) / elem_size
    PtrDiff(Box<Expr>, Box<Expr>, u32),
    LogAnd(Box<Expr>, Box<Expr>),
    LogOr(Box<Expr>, Box<Expr>),
    Cond(Box<Expr>, Box<Expr>, Box<Expr>),
    Comma(Box<Expr>, Box<Expr>),
    Assign(Box<Expr>, Box<Expr>),
    /// Read-modify-write of an lvalue.  The second operand computes the new value and refers
    /// to the old one through `EK::Prev`.  With `post`, the result is the old value.
    AssignOp(Box<Expr>, Box<Expr>, bool),
    Prev,
    /// Callee is a pointer-to-function rvalue.
    Call(Box<Expr>, Vec<Expr>),
    /// `va_start(ap, last)`: the operand is the `va_list` lvalue.
    VaStart(Box<Expr>),
    /// `va_arg(ap, type)`: the operand is the `va_list` lvalue, the expression type is `type`.
    VaArg(Box<Expr>),
    /// The address of a new object with automatic storage whose size in bytes is the operand
    /// (`alloca`, and the storage of a variable-length array).  The object lives until the
    /// function returns.  The operand counts elements of the given size; a variable-length
    /// array names its declaration (the hidden local that holds its address), must have at
    /// least one element, and lives until its scope is left (see `VlaLive`).
    Alloca(Box<Expr>, u32, Option<u32>),
    /// Control is at a point where only these variable-length array declarations of the
    /// function are in scope: the objects of the others are dead.
    VlaLive(Rc<[u32]>),
    /// A modelled inline assembly instruction; the value is what an MRS reads (32 bits).
    Asm(Box<AsmInsn>),
}

#[derive(Clone, Debug)]
pub struct Stmt {
    pub kind: SK,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum SK {
    Expr(Expr),
    /// Initialise a local: optionally zero it, then store each (offset, value).
    Init {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
    Block(Vec<Stmt>),
    If(Expr, Box<Stmt>, Option<Box<Stmt>>),
    While(Expr, Box<Stmt>),
    DoWhile(Box<Stmt>, Expr),
    For(Option<Box<Stmt>>, Option<Expr>, Option<Expr>, Box<Stmt>),
    Switch(Expr, Box<Stmt>),
    /// Inclusive range of values (a single value when both are equal).
    Case(u64, u64),
    Default,
    Break,
    Continue,
    Return(Option<Expr>),
    Goto(Rc<str>),
    Label(Rc<str>),
    Empty,
}

/// Control-flow graph of a function body.
#[derive(Clone, Debug, Default)]
pub struct Body {
    pub blocks: Vec<Block>,
}

#[derive(Clone, Debug)]
pub struct Block {
    pub ops: Vec<Op>,
    pub term: Term,
    /// Coverage point of the terminator.
    pub term_cov: u32,
    pub term_loc: Loc,
}

#[derive(Clone, Debug)]
pub struct Op {
    pub kind: OpKind,
    /// Coverage point id, unique within the program.
    pub cov: u32,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum OpKind {
    Eval(Expr),
    Init {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
}

#[derive(Clone, Debug)]
pub enum Term {
    Jump(usize),
    Br(Expr, usize, usize),
    /// Cases are inclusive ranges (low, high, target), compared in the type of the controlling expression.
    Switch(Expr, Vec<(u64, u64, usize)>, usize),
    Ret(Option<Expr>),
    /// Falling off the end of a non-void function, or a block not yet terminated.
    Unreachable,
}

#[derive(Default)]
pub struct Program {
    pub types: Vec<Type>,
    type_map: HashMap<Type, TypeId>,
    pub records: Vec<Record>,
    pub globals: Vec<Global>,
    pub funcs: Vec<Func>,
    pub strings: Vec<Rc<[u8]>>,
    pub files: Vec<String>,
    /// Translation units, in the order they were parsed: the path of each main file.
    pub units: Vec<String>,
    /// For each function / global, the translation unit that first declared it.  For objects
    /// with internal linkage this is the unit that owns them.
    pub func_unit: Vec<u16>,
    pub global_unit: Vec<u16>,
    /// Number of coverage points allocated.
    pub ncov: u32,
    /// Coverage point -> (function index, location).
    pub cov_info: Vec<(u32, Loc)>,
    /// Enumerated types are at least as wide as `int` (`-fno-short-enums`, the AAPCS variant
    /// clang uses) instead of the smallest type that fits (`-fshort-enums`, GCC's bare-metal default).
    pub int_enums: bool,
    /// Names of functions declared `_Noreturn` / `__attribute__((noreturn))`.
    pub noreturn: std::collections::HashSet<Rc<str>>,
    /// Names of functions declared `__attribute__((returns_twice))`.
    pub returns_twice: std::collections::HashSet<Rc<str>>,
    /// `restrict`-qualified pointer parameters of function definitions: (function, parameter).
    pub restrict_params: std::collections::HashSet<(u32, u32)>,
    /// Volatile-qualified variants of types: unqualified id -> qualified id and back.
    volatile: HashMap<TypeId, TypeId>,
    unqualified: HashMap<TypeId, TypeId>,
}

impl Program {
    pub fn new() -> Program {
        let mut p = Program::default();
        let base = [
            Type::Void,
            Type::Bool,
            Type::Int { size: 1, signed: false },
            Type::Int { size: 1, signed: true },
            Type::Int { size: 2, signed: true },
            Type::Int { size: 2, signed: false },
            Type::Int { size: 4, signed: true },
            Type::Int { size: 4, signed: false },
            Type::Int { size: 8, signed: true },
            Type::Int { size: 8, signed: false },
            Type::Float { size: 4 },
            Type::Float { size: 8 },
        ];
        for t in base {
            p.intern(t);
        }
        p
    }

    pub fn intern(&mut self, t: Type) -> TypeId {
        if let Some(&id) = self.type_map.get(&t) {
            return id;
        }
        let id = self.types.len() as TypeId;
        self.types.push(t.clone());
        self.type_map.insert(t, id);
        id
    }

    /// The volatile-qualified variant of `t`: a distinct id with the same structure.  Only lvalues
    /// and pointees carry it; values always have the unqualified type.
    pub fn volatile_of(&mut self, t: TypeId) -> TypeId {
        if self.unqualified.contains_key(&t) {
            return t;
        }
        if let Some(&v) = self.volatile.get(&t) {
            return v;
        }
        let ty = match self.ty(t).clone() {
            // Qualifying an array qualifies its elements.
            Type::Array(e, n) => Type::Array(self.volatile_of(e), n),
            other => other,
        };
        let id = self.types.len() as TypeId;
        self.types.push(ty);
        self.volatile.insert(t, id);
        self.unqualified.insert(id, t);
        id
    }

    pub fn is_volatile(&self, t: TypeId) -> bool {
        self.unqualified.contains_key(&t)
    }

    pub fn unqual(&self, t: TypeId) -> TypeId {
        self.unqualified.get(&t).copied().unwrap_or(t)
    }

    /// Bits of an object of type `t` that hold a value (as opposed to padding): bit ranges
    /// (first bit, length) relative to the start of the object.
    pub fn value_bits(&self, t: TypeId, base: u32, out: &mut Vec<(u32, u32)>) {
        match self.ty(t) {
            Type::Array(e, n) => {
                let es = self.size_of(*e).unwrap_or(0);
                for i in 0..n.unwrap_or(0) {
                    self.value_bits(*e, base + i * es * 8, out);
                }
            }
            Type::Record(r) => {
                for f in &self.records[*r as usize].fields {
                    match f.bits {
                        Some((bit, w)) => out.push((base + f.offset * 8 + bit as u32, w as u32)),
                        None => self.value_bits(f.ty, base + f.offset * 8, out),
                    }
                }
            }
            _ => out.push((base, self.size_of(t).unwrap_or(0) * 8)),
        }
    }

    /// Per-byte masks of the value bits of an object of type `t`.
    pub fn value_mask(&self, t: TypeId) -> Vec<u8> {
        let mut m = vec![0u8; self.size_of(t).unwrap_or(0) as usize];
        let mut ranges = Vec::new();
        self.value_bits(t, 0, &mut ranges);
        for (first, len) in ranges {
            for b in first..first + len {
                if let Some(x) = m.get_mut(b as usize / 8) {
                    *x |= 1 << (b % 8);
                }
            }
        }
        m
    }

    pub fn ty(&self, id: TypeId) -> &Type {
        &self.types[id as usize]
    }

    pub fn ptr_to(&mut self, t: TypeId) -> TypeId {
        self.intern(Type::Ptr(t))
    }

    pub fn is_integer(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Bool | Type::Int { .. })
    }

    pub fn is_float(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Float { .. })
    }

    pub fn is_arith(&self, t: TypeId) -> bool {
        self.is_integer(t) || self.is_float(t)
    }

    pub fn is_ptr(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Ptr(_))
    }

    pub fn is_scalar(&self, t: TypeId) -> bool {
        self.is_arith(t) || self.is_ptr(t)
    }

    /// May records `a` and `b` be one structure type?  Each translation unit reads the
    /// headers afresh and so has records of its own for the types it shares with the others:
    /// the same tag (or none) and the same layout, or a declaration left incomplete.
    pub fn records_may_match(&self, a: u32, b: u32) -> bool {
        if a == b {
            return true;
        }
        let (ra, rb) = (&self.records[a as usize], &self.records[b as usize]);
        if ra.name != rb.name || ra.is_union != rb.is_union {
            return false;
        }
        !ra.complete
            || !rb.complete
            || (ra.size == rb.size
                && ra.fields.len() == rb.fields.len()
                && ra
                    .fields
                    .iter()
                    .zip(&rb.fields)
                    .all(|(x, y)| x.name == y.name && x.offset == y.offset))
    }

    /// May `a` and `b` be compatible types?  False only for types that certainly are not:
    /// used to rule a function out as the target of a call through a pointer, which is
    /// sound only when the call would be undefined.  Integer types of one size, pointers
    /// to `void` and to anything, unprototyped functions and incomplete types all count as
    /// possibly compatible.
    pub fn may_be_compatible(&self, a: TypeId, b: TypeId, depth: u32) -> bool {
        let (a, b) = (self.unqual(a), self.unqual(b));
        if a == b || depth > 8 {
            return true;
        }
        match (self.ty(a), self.ty(b)) {
            (Type::Void, Type::Void) => true,
            (Type::Bool | Type::Int { .. }, Type::Bool | Type::Int { .. }) => self.size_of(a) == self.size_of(b),
            (Type::Float { size: x }, Type::Float { size: y }) => x == y,
            (Type::Ptr(x), Type::Ptr(y)) => {
                let void = |t: TypeId| matches!(self.ty(self.unqual(t)), Type::Void);
                void(*x) || void(*y) || self.may_be_compatible(*x, *y, depth + 1)
            }
            (Type::Array(x, n), Type::Array(y, m)) => {
                (n.is_none() || m.is_none() || n == m) && self.may_be_compatible(*x, *y, depth + 1)
            }
            (Type::Func(x), Type::Func(y)) => self.funcs_may_be_compatible(x, y, depth + 1),
            (Type::Record(x), Type::Record(y)) => self.records_may_match(*x, *y),
            _ => false,
        }
    }

    pub fn funcs_may_be_compatible(&self, a: &FuncType, b: &FuncType, depth: u32) -> bool {
        self.may_be_compatible(a.ret, b.ret, depth)
            && (!a.proto
                || !b.proto
                || (a.variadic == b.variadic
                    && a.params.len() == b.params.len()
                    && a.params
                        .iter()
                        .zip(&b.params)
                        .all(|(&x, &y)| self.may_be_compatible(x, y, depth))))
    }

    pub fn is_signed(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Int { signed: true, .. })
    }

    pub fn pointee(&self, t: TypeId) -> Option<TypeId> {
        match self.ty(t) {
            Type::Ptr(p) => Some(*p),
            _ => None,
        }
    }

    /// Size in bytes; None for incomplete types.
    pub fn size_of(&self, t: TypeId) -> Option<u32> {
        Some(match self.ty(t) {
            Type::Void | Type::Func(_) => 1,
            Type::Bool => 1,
            Type::Int { size, .. } | Type::Float { size } => *size as u32,
            Type::Ptr(_) => 4,
            Type::Array(e, n) => self.size_of(*e)?.checked_mul((*n)?)?,
            Type::Record(r) => {
                let r = &self.records[*r as usize];
                if !r.complete {
                    return None;
                }
                r.size
            }
        })
    }

    pub fn align_of(&self, t: TypeId) -> u32 {
        match self.ty(t) {
            Type::Void | Type::Func(_) | Type::Bool => 1,
            Type::Int { size, .. } | Type::Float { size } => *size as u32,
            Type::Ptr(_) => 4,
            Type::Array(e, _) => self.align_of(*e),
            Type::Record(r) => self.records[*r as usize].align.max(1),
        }
    }

    /// Width in bits of a scalar type as a term.
    pub fn bits(&self, t: TypeId) -> u8 {
        match self.ty(t) {
            Type::Bool => 8,
            Type::Int { size, .. } | Type::Float { size } => size * 8,
            _ => 32,
        }
    }

    pub fn type_name(&self, t: TypeId) -> String {
        match self.ty(t) {
            Type::Void => "void".into(),
            Type::Bool => "_Bool".into(),
            Type::Int { size, signed } => {
                format!("{}int{}_t", if *signed { "" } else { "u" }, size * 8)
            }
            Type::Float { size } => if *size == 4 { "float" } else { "double" }.into(),
            Type::Ptr(p) => format!("{}*", self.type_name(*p)),
            Type::Array(e, n) => format!(
                "{}[{}]",
                self.type_name(*e),
                n.map(|n| n.to_string()).unwrap_or_default()
            ),
            Type::Func(f) => format!("{}()", self.type_name(f.ret)),
            Type::Record(r) => {
                let r = &self.records[*r as usize];
                format!(
                    "{} {}",
                    if r.is_union { "union" } else { "struct" },
                    r.name.as_deref().unwrap_or("<anon>")
                )
            }
        }
    }
}