cverif 0.0.4

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
//! A cache of verification results on disk (`--cache DIR`).
//!
//! A result is reused only under a key that covers everything the proof can depend on.  A
//! wrong hit would be a false proof, so the key errs on the side of including too much:
//!
//! * the tool itself (its version and the bytes of the executable) and the options that
//!   bear on a result;
//! * the source: the function, and transitively every function and object it names, with
//!   the initial values of the objects and the string literals; every type of the program;
//!   and, if anything in that closure calls through a pointer, the whole program (any
//!   function may then be the one called);
//! * the binding: the address of every function and object in that closure, and what the
//!   source environment derives from the whole program (which objects nothing modifies,
//!   where nothing can be stored);
//! * the image: its symbol table, and every byte of it except the code of the functions
//!   this one cannot reach.  Reach is decided from the machine code: direct calls and jumps,
//!   decoding at every halfword so that no instruction is missed; a function that makes a
//!   call or jump through a register, or forms the address of code, can reach everything.
//!
//! Results that depend on the clock (a time limit that struck) are not stored.

use crate::c::ast::{Program, SymRef};
use crate::c::exec::CEnv;
use crate::image::{Image, SymKind};
use crate::thumb::decode::{Addr, DpOp, Op, Operand, decode};
use crate::verify::{FuncReport, Options, Status};
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use std::hash::Hasher;
use std::path::PathBuf;

/// Bump when the stored format or the meaning of a key changes.
const FORMAT: u32 = 3;

/// A 128-bit digest: two differently seeded 64-bit hashes over the same input.
#[derive(Clone)]
struct Digest(
    std::collections::hash_map::DefaultHasher,
    std::collections::hash_map::DefaultHasher,
);

impl Digest {
    fn new() -> Digest {
        let mut d = Digest(Default::default(), Default::default());
        d.1.write(b"cverif second lane");
        d
    }

    fn bytes(&mut self, b: &[u8]) {
        self.0.write_u64(b.len() as u64);
        self.0.write(b);
        self.1.write_u64(b.len() as u64);
        self.1.write(b);
    }

    fn debug(&mut self, v: &dyn std::fmt::Debug) {
        let mut text = String::new();
        let _ = write!(text, "{v:?}");
        self.bytes(text.as_bytes());
    }

    fn hex(&self) -> String {
        format!("{:016x}{:016x}", self.0.finish(), self.1.finish())
    }
}

impl std::fmt::Write for Digest {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.bytes(s.as_bytes());
        Ok(())
    }
}

/// What is stored for a function.
pub struct Entry {
    pub report: FuncReport,
    pub cov: BTreeSet<u32>,
    pub bytes: BTreeSet<u32>,
}

pub struct Cache<'a> {
    dir: PathBuf,
    prog: &'a Program,
    image: &'a Image,
    env: &'a CEnv<'a>,
    /// Everything that is the same for all functions.
    base: Digest,
    /// The whole program, for functions that call through pointers.
    whole: String,
    /// Function symbols: start -> end.
    funcs: BTreeMap<u32, u32>,
    /// For each function symbol: the functions its code refers to directly, or None if it can
    /// reach anything.
    reach: BTreeMap<u32, Option<BTreeSet<u32>>>,
    /// What each function of the source refers to directly.
    refs: Vec<crate::discover::matcher::SrcSig>,
    /// Digests of the functions and objects of the source, each on its own.
    func_digest: Vec<String>,
    global_digest: Vec<String>,
    /// Functions and objects of the source by name (one name may have several entries).
    funcs_named: std::collections::HashMap<&'a str, Vec<u32>>,
    globals_named: std::collections::HashMap<&'a str, Vec<u32>>,
}

fn digest_of(v: &dyn std::fmt::Debug) -> String {
    let mut d = Digest::new();
    let _ = write!(d, "{v:?}");
    d.hex()
}

impl<'a> Cache<'a> {
    pub fn open(
        dir: &std::path::Path,
        prog: &'a Program,
        image: &'a Image,
        env: &'a CEnv<'a>,
        opts: &Options,
    ) -> std::io::Result<Cache<'a>> {
        std::fs::create_dir_all(dir)?;
        let mut base = Digest::new();
        base.bytes(format!("cverif {} format {FORMAT}", env!("CARGO_PKG_VERSION")).as_bytes());
        // The tool as built: a development build with the same version number is another tool.
        base.bytes(&std::env::current_exe().and_then(std::fs::read)?);
        // Options that bear on a result (not: which functions, how many threads).
        base.debug(&(
            &opts.limits,
            opts.time_limit,
            &opts.mmio,
            opts.work_limit,
            opts.max_terms,
            opts.check_solver,
            opts.modular,
            opts.aliasing,
        ));
        // The source as a whole: its types, and what is declared about functions by name.
        base.debug(&(&prog.types, &prog.records, prog.int_enums));
        let mut names: Vec<String> = prog.noreturn.iter().map(|x| format!("noreturn {x}")).collect();
        names.extend(prog.returns_twice.iter().map(|x| format!("returns_twice {x}")));
        names.extend(prog.restrict_params.iter().map(|x| format!("restrict {x:?}")));
        names.sort();
        base.debug(&names);
        // The image as a whole: symbols and what the loader found out about it.
        let mut syms: Vec<String> = image.symbols.iter().map(|s| format!("{s:?}")).collect();
        syms.sort();
        base.debug(&syms);
        let mut ext: Vec<(u32, &String)> = image.externals.iter().map(|(a, n)| (*a, n)).collect();
        ext.sort();
        base.debug(&(
            ext,
            &image.data_ranges,
            image.short_enums,
            image.static_base,
            image.rwpi,
            image.hard_float,
            image.soft_bounds,
            &image.set_aside,
        ));
        for s in &image.segments {
            base.debug(&(s.addr, s.data.len(), s.exec, s.writable, s.load_addr));
        }
        // What the source environment derives from the whole program.
        base.debug(&(
            &env.no_store,
            &env.rom_ranges,
            env.hosted,
            env.aliasing,
            &env.library,
            // Who calls what, and with which constants: a function fitted to its callers is
            // verified for those only (conservative: any change here discards everything).
            &env.callers,
            &env.ambiguous,
        ));
        base.debug(&(
            &env.replaceable,
            &image.meta.weak_funcs,
            std::env::var("CVERIF_CHECK_VACUOUS").ok(),
        ));

        let mut whole = Digest::new();
        whole.debug(&(&prog.funcs, &prog.globals, &prog.strings));
        whole.debug(&(&env.func_addr, &env.global_addr, &env.targets, &env.callable));
        let mut frozen: Vec<u32> = env.frozen.iter().map(|f| f.0).collect();
        frozen.sort();
        whole.debug(&frozen);

        let mut funcs: BTreeMap<u32, u32> = BTreeMap::new();
        for s in image.symbols.iter().filter(|s| s.kind == SymKind::Func && s.size > 0) {
            let e = funcs.entry(s.addr).or_insert(s.addr + s.size);
            *e = (*e).max(s.addr + s.size);
        }
        let mut c = Cache {
            dir: dir.to_path_buf(),
            prog,
            image,
            env,
            base,
            whole: whole.hex(),
            funcs,
            reach: BTreeMap::new(),
            refs: (0..prog.funcs.len() as u32)
                .map(|f| crate::discover::matcher::refs(prog, f))
                .collect(),
            func_digest: prog.funcs.iter().map(|f| digest_of(f)).collect(),
            global_digest: prog.globals.iter().map(|g| digest_of(g)).collect(),
            funcs_named: Default::default(),
            globals_named: Default::default(),
        };
        for (i, f) in prog.funcs.iter().enumerate() {
            c.funcs_named.entry(&*f.name).or_default().push(i as u32);
        }
        for (i, g) in prog.globals.iter().enumerate() {
            c.globals_named.entry(&*g.name).or_default().push(i as u32);
        }
        let starts: Vec<(u32, u32)> = c.funcs.iter().map(|(a, e)| (*a, *e)).collect();
        for (a, e) in starts {
            let r = c.scan(a, e);
            c.reach.insert(a, r);
        }
        Ok(c)
    }

    /// The function containing `addr`, by its start.
    fn func_of(&self, addr: u32) -> Option<u32> {
        let (a, e) = self.funcs.range(..=addr).next_back()?;
        (addr < *e).then_some(*a)
    }

    /// The functions the code at `start..end` refers to directly; None if it can reach any.
    fn scan(&self, start: u32, end: u32) -> Option<BTreeSet<u32>> {
        let mut out = BTreeSet::new();
        let exec = |a: u32| self.image.segment_at(a).is_some_and(|s| s.exec || !s.writable);
        let mut low: [Option<(u32, u16)>; 16] = [None; 16];
        let mut a = start & !1;
        while a < end {
            // (Any even address may be where an instruction starts: after a literal pool the
            // decoding of what precedes says nothing.)
            let bytes = self.image.read(a, 4).or_else(|| self.image.read(a, 2))?;
            // A word that is the address of code: a pointer to a function, a jump table.
            if a.is_multiple_of(4) && bytes.len() == 4 {
                let w = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & !1;
                if exec(w) && self.func_of(w).is_some_and(|f| f != start) {
                    return None;
                }
            }
            for in_it in [false, true] {
                let Some(insn) = decode(bytes, a, in_it) else { continue };
                let target = match insn.op {
                    Op::Bl { target } | Op::B { target, .. } | Op::Cbz { target, .. } => Some(target & !1),
                    // Through a register or from memory: anywhere.  (`bx lr` is a return, and
                    // so is loading pc from the stack.)
                    Op::Blx { .. } => return None,
                    Op::Bx { rm } if rm != 14 => return None,
                    Op::Load { rt: 15, addr, .. } if !matches!(addr, Addr::Base { rn: 13, .. }) => return None,
                    Op::LoadMulti { rn, regs, .. } if regs & 0x8000 != 0 && rn != 13 => return None,
                    Op::Dp { rd: Some(15), .. } => return None,
                    // The address of code formed in two halves.
                    Op::Movt { rd, imm } => {
                        if let Some((at, lo)) = low[rd as usize]
                            && a.wrapping_sub(at) <= 8
                        {
                            let v = ((imm as u32) << 16 | lo as u32) & !1;
                            if exec(v) && self.func_of(v) != Some(start) {
                                return None;
                            }
                        }
                        None
                    }
                    Op::Dp {
                        op: DpOp::Mov,
                        rd: Some(rd),
                        src: Operand::Imm { value, .. },
                        ..
                    } => {
                        low[rd as usize & 15] = Some((a, value as u16));
                        None
                    }
                    _ => None,
                };
                if let Some(t) = target
                    && !(t >= start && t < end)
                {
                    match self.func_of(t) {
                        Some(f) => {
                            out.insert(f);
                        }
                        // Code that belongs to no function symbol.
                        None if exec(t) => return None,
                        None => {}
                    }
                }
            }
            a += 2;
        }
        Some(out)
    }

    /// The function symbols whose code a proof about the function at `entry` may execute or
    /// read; None for all of them.
    fn code_closure(&self, entry: u32) -> Option<BTreeSet<u32>> {
        let mut seen = BTreeSet::new();
        let mut work = vec![self.func_of(entry)?];
        while let Some(f) = work.pop() {
            if !seen.insert(f) {
                continue;
            }
            work.extend(self.reach.get(&f)?.as_ref()?.iter().copied());
        }
        Some(seen)
    }

    /// The key of source function `fid`, placed where the environment places it.
    pub fn key(&self, fid: u32) -> Option<String> {
        let entry = self.env.func_addr[fid as usize]?;
        let mut d = self.base.clone();
        let p = self.prog;
        // --- source closure ---
        let mut funcs: BTreeSet<u32> = BTreeSet::new();
        let mut globals: BTreeSet<u32> = BTreeSet::new();
        let mut strings: BTreeSet<u32> = BTreeSet::new();
        let mut indirect = false;
        let mut work: Vec<SymRef> = vec![SymRef::Func(fid)];
        while let Some(r) = work.pop() {
            match r {
                SymRef::Func(f) => {
                    if !funcs.insert(f) {
                        continue;
                    }
                    let refs = &self.refs[f as usize];
                    indirect |= refs.indirect;
                    work.extend(refs.callees.iter().map(|c| SymRef::Func(*c)));
                    work.extend(refs.globals.iter().map(|g| SymRef::Global(*g)));
                    strings.extend(refs.strings.iter().copied());
                    // Other definitions of the same name (a declaration in one unit, the
                    // body in another).
                    for i in &self.funcs_named[&*p.funcs[f as usize].name] {
                        if !funcs.contains(i) {
                            work.push(SymRef::Func(*i));
                        }
                    }
                }
                SymRef::Global(g) => {
                    if !globals.insert(g) {
                        continue;
                    }
                    for (_, t, _) in p.globals[g as usize].init.iter().flat_map(|i| &i.relocs) {
                        match t {
                            SymRef::Str(s) => {
                                strings.insert(*s);
                            }
                            // (A function whose address is stored can be called through it.)
                            other => work.push(other.clone()),
                        }
                    }
                    for i in &self.globals_named[&*p.globals[g as usize].name] {
                        if !globals.contains(i) {
                            work.push(SymRef::Global(*i));
                        }
                    }
                }
                SymRef::Str(s) => {
                    strings.insert(s);
                }
            }
        }
        let frozen = |a: u32| self.env.frozen.iter().any(|f| f.0 == a);
        let _ = write!(d, "function {fid} at {entry:#x};");
        for &f in &funcs {
            let _ = write!(
                d,
                "F{f} {} unit {:?} at {:?} callable {:?};",
                self.func_digest[f as usize],
                p.func_unit.get(f as usize),
                self.env.func_addr[f as usize],
                self.env.callable.get(f as usize)
            );
        }
        for &g in &globals {
            let at = self.env.global_addr[g as usize];
            let _ = write!(
                d,
                "G{g} {} unit {:?} at {at:?} frozen {:?};",
                self.global_digest[g as usize],
                p.global_unit.get(g as usize),
                at.map(frozen)
            );
        }
        for &s in &strings {
            let _ = write!(
                d,
                "S{s} {:?} at {:?};",
                p.strings[s as usize], self.env.str_addr[s as usize]
            );
        }
        if indirect {
            let _ = write!(d, "whole program {};", self.whole);
        }
        // --- image ---
        let keep = self.code_closure(entry);
        for seg in &self.image.segments {
            match &keep {
                None => d.bytes(&seg.data),
                Some(keep) => {
                    // Everything but the code of the functions that cannot be reached.
                    let mut data = seg.data.clone();
                    for (a, e) in self.funcs.iter().filter(|(a, _)| !keep.contains(a)) {
                        let lo = a.saturating_sub(seg.addr) as usize;
                        let hi = (e.saturating_sub(seg.addr) as usize).min(data.len());
                        if *a >= seg.addr && lo < hi {
                            data[lo..hi].fill(0);
                        }
                    }
                    d.bytes(&data);
                }
            }
        }
        Some(d.hex())
    }

    fn path(&self, key: &str) -> PathBuf {
        self.dir.join(format!("{key}.result"))
    }

    pub fn get(&self, key: &str) -> Option<Entry> {
        let text = std::fs::read_to_string(self.path(key)).ok()?;
        parse(&text)
    }

    /// Store a result, unless it depends on the clock or carries an explanation that is not
    /// stored (a hit has to give the same report).
    pub fn put(&self, key: &str, e: &Entry) {
        if e.report.status.detail().contains("time limit") {
            return;
        }
        let text = render(e);
        // (Written under another name first: another run may be reading.)
        let tmp = self.dir.join(format!("{key}.{}.tmp", std::process::id()));
        if std::fs::write(&tmp, text).is_ok() {
            let _ = std::fs::rename(&tmp, self.path(key));
        }
    }
}

fn esc(s: &str) -> String {
    s.replace('\\', "\\\\").replace('\n', "\\n").replace('\t', "\\t")
}

fn unesc(s: &str) -> String {
    let mut out = String::new();
    let mut it = s.chars();
    while let Some(c) = it.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match it.next() {
            Some('n') => out.push('\n'),
            Some('t') => out.push('\t'),
            Some(x) => out.push(x),
            None => {}
        }
    }
    out
}

fn render(e: &Entry) -> String {
    let r = &e.report;
    let mut o = String::new();
    let _ = writeln!(o, "cverif-cache {FORMAT}");
    let _ = writeln!(o, "name\t{}", esc(&r.name));
    let _ = writeln!(o, "addr\t{}", r.addr);
    let _ = writeln!(o, "size\t{}", r.size);
    let _ = writeln!(o, "status\t{}\t{}", r.status.label(), esc(r.status.detail()));
    let _ = writeln!(o, "paths\t{}", r.paths);
    let _ = writeln!(o, "undefined\t{}", r.undefined_paths);
    let _ = writeln!(o, "effort\t{}\t{}\t{}\t{}", r.millis, r.sat_calls, r.conflicts, r.work);
    for m in &r.modulo {
        let _ = writeln!(o, "modulo\t{}", esc(&m.0));
    }
    for a in &r.assumes {
        let _ = writeln!(o, "assumes\t{}", esc(a));
    }
    if let Some(g) = &r.given {
        let _ = writeln!(o, "given\t{}", esc(g));
    }
    for h in &r.hazards {
        let _ = writeln!(o, "hazard\t{}\t{}\t{}", h.pc, h.size, h.write as u8);
    }
    let list = |s: &BTreeSet<u32>| s.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(" ");
    let _ = writeln!(o, "cov\t{}", list(&e.cov));
    let _ = writeln!(o, "bytes\t{}", list(&e.bytes));
    let _ = writeln!(o, "end");
    o
}

fn parse(text: &str) -> Option<Entry> {
    let mut lines = text.lines();
    if lines.next()? != format!("cverif-cache {FORMAT}") {
        return None;
    }
    let mut r = FuncReport {
        name: String::new(),
        addr: 0,
        size: 0,
        status: Status::Proved,
        paths: 0,
        undefined_paths: 0,
        millis: 0,
        sat_calls: 0,
        conflicts: 0,
        work: 0,
        detail: None,
        modulo: Vec::new(),
        unconditional: false,
        cached: true,
        assumes: Vec::new(),
        given: None,
        hazards: Vec::new(),
    };
    let (mut cov, mut bytes) = (BTreeSet::new(), BTreeSet::new());
    let mut complete = false;
    let set = |v: &str| {
        v.split_whitespace()
            .map(|x| x.parse::<u32>().ok())
            .collect::<Option<BTreeSet<u32>>>()
    };
    for l in lines {
        let mut f = l.split('\t');
        match f.next()? {
            "name" => r.name = unesc(f.next()?),
            "addr" => r.addr = f.next()?.parse().ok()?,
            "size" => r.size = f.next()?.parse().ok()?,
            "status" => {
                let label = f.next()?;
                let detail = unesc(f.next().unwrap_or(""));
                r.status = match label {
                    "PROVED" => Status::Proved,
                    "BOUNDED" => Status::Bounded(detail),
                    "MISMATCH" => Status::Mismatch(detail),
                    "INCONCLUSIVE" => Status::Inconclusive(detail),
                    "UNSUPPORTED" => Status::Unsupported(detail),
                    _ => return None,
                };
            }
            "assumes" => r.assumes.push(unesc(f.next()?)),
            "given" => r.given = Some(unesc(f.next()?)),
            "paths" => r.paths = f.next()?.parse().ok()?,
            "undefined" => r.undefined_paths = f.next()?.parse().ok()?,
            "hazard" => r.hazards.push(crate::sym::Hazard {
                pc: f.next()?.parse().ok()?,
                size: f.next()?.parse().ok()?,
                write: f.next()? == "1",
            }),
            "effort" => {
                r.millis = f.next()?.parse().ok()?;
                r.sat_calls = f.next()?.parse().ok()?;
                r.conflicts = f.next()?.parse().ok()?;
                r.work = f.next()?.parse().ok()?;
            }
            "modulo" => r.modulo.push((unesc(f.next()?), String::new())),
            "cov" => cov = set(f.next().unwrap_or(""))?,
            "bytes" => bytes = set(f.next().unwrap_or(""))?,
            "end" => complete = true,
            _ => return None,
        }
    }
    // (A file cut short is no result.)
    complete.then_some(Entry { report: r, cov, bytes })
}