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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! Counterexamples run for real.
//!
//! A verdict of DIFFERENT comes with an input.  Here both machine functions are executed on
//! that input by a concrete interpreter that shares nothing with the symbolic one
//! (`tests/support/armsim.rs`), and what the verdict says differs is looked for in the two
//! runs.  A counterexample that does not reproduce is a defect of the comparison (or of this
//! replay, which says what it does not model).
//!
//! The runs follow the model of the comparison: a call that was compared as a call is not
//! executed, it returns what the counterexample says it returns and memory is afterwards
//! what the counterexample says it is; the new image's accesses go where the comparison
//! sent them (a paired object is the old image's), and a pointer of the old image that the
//! new code receives is given to it as its own pointer to the same thing.

use super::armsim::{Bus, Cpu, Stop};
use super::{Space, last_insn};
use crate::image::Image;
use std::collections::{BTreeMap, HashMap};

/// An input that tells two functions apart, as the prover gave it.
#[derive(Clone, Debug, Default)]
pub struct Model {
    /// The message the input was printed in.
    pub text: String,
    pub syms: HashMap<String, u64>,
    /// (memory snapshot, address) -> byte.
    pub mem: HashMap<(u32, u64), u8>,
    /// The analysis it is from followed every call into the code of the images.
    pub inline: bool,
    /// The functions that analysis followed on both sides although it compared calls as calls.
    pub follow: Vec<String>,
}

/// What became of a counterexample when it was run.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Replay {
    /// The two runs differ in what the verdict names.
    Reproduced(String),
    /// Both ran to their end and do not differ there.
    NotReproduced(String),
    /// The replay does not model something the runs met.
    NotModelled(String),
}

const RET: u32 = 0xffff_fff0;
const STEPS: usize = 50_000;

#[derive(Clone, Debug, PartialEq, Eq)]
enum End {
    Return(u32),
    /// A call that does not return.
    Gone,
    Trap,
}

#[derive(Clone, Debug)]
struct Event {
    name: String,
    target: u32,
    /// World memory written since the previous event: address in the old image's terms -> byte.
    written: BTreeMap<u32, u8>,
}

struct Run {
    events: Vec<Event>,
    end: End,
    written: BTreeMap<u32, u8>,
}

struct Mem<'a> {
    sp: &'a Space<'a>,
    side: usize,
    model: &'a Model,
    /// Bytes written in this run, by address in the old image's terms.
    written: HashMap<u32, u8>,
    epoch: u32,
    /// The instruction being fetched: read from the image as it is.
    fetch: (u32, u32),
    io: usize,
    /// The frame of the function: [lowest stack pointer seen, stack pointer at entry).
    frame: (u32, u32),
}

impl Mem<'_> {
    fn code(&self) -> &Image {
        if self.side == 0 { self.sp.a } else { self.sp.b }
    }

    fn key(&self, a: u32) -> u32 {
        if self.side == 0 {
            a
        } else {
            self.sp.layout.access(a).unwrap_or(a)
        }
    }

    /// (byte, it holds what the old image or the counterexample says rather than what this
    /// run wrote)
    fn byte(&self, a: u32) -> (u8, bool) {
        let k = self.key(a);
        if let Some(&v) = self.written.get(&k) {
            return (v, false);
        }
        for e in (0..=self.epoch).rev() {
            if let Some(&v) = self.model.mem.get(&(e, k as u64)) {
                return (v, true);
            }
            // (Memory a callee may have changed and the counterexample says nothing about
            // is as it was.)
        }
        let data = self.sp.data(self.side);
        match data.read(k, 1) {
            // The new image's own copy holds the new image's pointers.
            Some(b) => (b[0], self.side == 0 || self.sp.a.segment_at(k).is_some()),
            None => (0, true),
        }
    }

    /// The new image's pointer to what `v` designates in the old one.
    fn to_new(&self, v: u32) -> u32 {
        if self.side == 0 {
            return v;
        }
        if let Some(fa) = self.sp.a.func_at(v & !1)
            && fa.addr == v & !1
            && let Some(p) = self.sp.paired.get(&fa.name)
            && p[0] == fa.addr
        {
            return p[1] | (v & 1);
        }
        for o in &self.sp.layout.objs {
            if let Some(to) = o.to
                && o.same
                && v.wrapping_sub(to) < o.size
            {
                return o.start.wrapping_add(v - to);
            }
        }
        v
    }
}

impl Bus for Mem<'_> {
    fn read8(&mut self, a: u32) -> u8 {
        if a.wrapping_sub(self.fetch.0) < self.fetch.1 {
            return self.code().read(a, 1).map_or(0, |b| b[0]);
        }
        self.byte(a).0
    }

    fn write8(&mut self, a: u32, v: u8) {
        let k = self.key(a);
        self.written.insert(k, v);
    }

    fn read(&mut self, a: u32, size: u32) -> u32 {
        if a.wrapping_sub(self.fetch.0) < self.fetch.1 {
            return (0..size).fold(0, |v, i| v | (self.read8(a.wrapping_add(i)) as u32) << (8 * i));
        }
        if self.sp.mmio.iter().any(|&(lo, hi)| a >= lo && a <= hi) {
            let v = self.model.syms.get(&format!("io{}", self.io)).copied().unwrap_or(0) as u32;
            self.io += 1;
            return if size >= 4 { v } else { v & ((1 << (8 * size)) - 1) };
        }
        let mut v = 0u32;
        let mut old = true;
        for i in 0..size {
            let (b, o) = self.byte(a.wrapping_add(i));
            v |= (b as u32) << (8 * i);
            old &= o;
        }
        if size == 4 && old { self.to_new(v) } else { v }
    }
}

fn run(sp: &Space, side: usize, entry: u32, model: &Model) -> Result<Run, String> {
    let img = if side == 0 { sp.a } else { sp.b };
    let size = img.func_at(entry).map_or(0, |s| s.size);
    // The functions being executed: the one compared, and the callees that are followed.
    let mut frames: Vec<(u32, u32)> = vec![(entry & !1, size)];
    let mut cpu = Cpu::new();
    let sym = |n: &str| model.syms.get(n).map(|v| *v as u32);
    let sp0 = sym("r13").or(sym("sp")).unwrap_or(0x2000_8000);
    let mut mem = Mem {
        sp,
        side,
        model,
        written: HashMap::new(),
        epoch: 0,
        fetch: (0, 0),
        io: 0,
        frame: (sp0, sp0),
    };
    for (i, r) in cpu.r.iter_mut().enumerate().take(13) {
        *r = mem.to_new(sym(&format!("r{i}")).unwrap_or(0));
    }
    cpu.r[13] = sp0;
    cpu.r[14] = RET | 1;
    cpu.pc = entry & !1;
    // Stack arguments.
    for (n, v) in &model.syms {
        if let Some(off) = n.strip_prefix("stk").and_then(|o| o.parse::<u32>().ok()) {
            let v = mem.to_new(*v as u32);
            for i in 0..4 {
                let k = mem.key(sp0.wrapping_add(off + i));
                mem.written.insert(k, (v >> (8 * i)) as u8);
            }
        }
    }
    let entry_writes = mem.written.clone();
    let mut events: Vec<Event> = Vec::new();
    // World memory written since the last event.
    let world = |mem: &Mem, entry_writes: &HashMap<u32, u8>| -> BTreeMap<u32, u8> {
        (mem.written.iter())
            .filter(|(k, v)| !(**k >= mem.frame.0 && **k < mem.frame.1) && entry_writes.get(*k) != Some(*v))
            .map(|(k, v)| (*k, *v))
            .collect()
    };
    for _ in 0..STEPS {
        mem.frame.0 = mem.frame.0.min(cpu.r[13]);
        let pc = cpu.pc;
        if pc == RET {
            return Ok(Run {
                events,
                end: End::Return(cpu.r[0]),
                written: world(&mem, &entry_writes),
            });
        }
        let within = |f: &(u32, u32)| pc.wrapping_sub(f.0) < f.1;
        if !frames.last().is_some_and(within) && frames.iter().any(within) {
            // Back in a caller.
            while !frames.last().is_some_and(within) {
                frames.pop();
            }
        }
        let inside = frames.last().is_some_and(within);
        if !inside {
            // Control left the code being executed: a call, or a jump to another function.
            let known = img.func_at(pc).filter(|f| f.addr == pc);
            let key = sp.fn_key[side].get(&pc);
            let follow = known.is_some()
                && img.segment_at(pc).is_some_and(|s| s.exec)
                && (model.inline
                    || key.is_some_and(|k| model.follow.contains(k))
                    || super::is_fragment(&known.unwrap().name));
            if let (true, Some(f)) = (follow, known) {
                frames.push((f.addr, f.size));
            } else {
                let name = match (sp.fn_key[side].get(&pc), known, img.externals.get(&(pc | 1))) {
                    (Some(n), _, _) => n.clone(),
                    (None, Some(f), _) => f.name.clone(),
                    (None, None, Some(n)) => n.clone(),
                    _ => match img.externals.get(&pc) {
                        Some(n) => n.clone(),
                        None => format!("{pc:#x}"),
                    },
                };
                let k = events.len();
                let ret = |part: &str| {
                    let prefix = format!("ret{k}:{part}:");
                    (model.syms.iter())
                        .find(|(n, _)| n.starts_with(&prefix))
                        .map(|(_, v)| *v as u32)
                };
                events.push(Event {
                    name: name.clone(),
                    target: mem.key(pc),
                    written: world(&mem, &entry_writes),
                });
                let back = cpu.r[14];
                let site_is_last = back != (RET | 1) && last_insn(img, back & !1);
                if sp.noreturn.contains(&name) || site_is_last {
                    return Ok(Run {
                        events,
                        end: End::Gone,
                        written: BTreeMap::new(),
                    });
                }
                // What the callee leaves: its result, scratch registers of no use, and
                // memory as the counterexample has it from here on.
                cpu.r[0] = mem.to_new(ret("lo").unwrap_or(0));
                cpu.r[1] = mem.to_new(ret("hi").unwrap_or(0));
                (cpu.r[2], cpu.r[3], cpu.r[12]) = (0xdead_0002, 0xdead_0003, 0xdead_000c);
                mem.epoch += 1;
                let frame = mem.frame;
                mem.written.retain(|k, _| *k >= frame.0 && *k < frame.1);
                cpu.pc = back & !1;
                continue;
            }
        }
        let first = img.read(pc, 2).map_or(0, |b| u16::from_le_bytes([b[0], b[1]]));
        mem.fetch = (pc, if first >= 0xe800 { 4 } else { 2 });
        // A call through a register is an event of its own kind.
        let indirect = first & 0xff87 == 0x4780 || (first & 0xff87 == 0x4700 && (first >> 3 & 0xf) != 14);
        // (The target of a call through a pointer may be anything in a counterexample: the
        // call is made here, not by the interpreter, which would fault on a bad address.)
        let r = if indirect {
            let target = cpu.r[(first >> 3 & 0xf) as usize];
            if first & 0xff87 == 0x4780 {
                cpu.r[14] = (pc + 2) | 1;
            }
            cpu.pc = target & !1;
            Ok(())
        } else {
            cpu.step(&mut mem)
        };
        mem.fetch = (0, 0);
        match r {
            Ok(()) => {}
            Err(Stop::Udf) => {
                return Ok(Run {
                    events,
                    end: End::Trap,
                    written: world(&mem, &entry_writes),
                });
            }
            Err(e) => {
                return Err(format!(
                    "{} image at {pc:#x}: {e:?}",
                    if side == 0 { "old" } else { "new" }
                ));
            }
        }
        if indirect && cpu.pc != RET && !frames.iter().any(|f| cpu.pc.wrapping_sub(f.0) < f.1) {
            // Compared as a call whatever the target is.
            let target = cpu.pc;
            let k = events.len();
            let ret = |part: &str| {
                let prefix = format!("ret{k}:{part}:");
                (model.syms.iter())
                    .find(|(n, _)| n.starts_with(&prefix))
                    .map(|(_, v)| *v as u32)
            };
            events.push(Event {
                // A call through a pointer to a function both images have is a call to
                // that function, as a direct call is.
                name: match sp.fn_key[side].get(&target) {
                    Some(n) => n.clone(),
                    None => "<indirect call>".into(),
                },
                target: if side == 0 {
                    target
                } else {
                    // The old image's entry of the same function, if it is one.
                    (sp.fn_key[1].get(&target))
                        .and_then(|n| sp.paired.get(n))
                        .map_or(target, |p| p[0])
                },
                written: world(&mem, &entry_writes),
            });
            let back = cpu.r[14];
            if first & 0xff87 == 0x4700 {
                // A jump: the callee returns to our caller.
                cpu.r[0] = mem.to_new(ret("lo").unwrap_or(0));
                return Ok(Run {
                    events,
                    end: End::Return(cpu.r[0]),
                    written: BTreeMap::new(),
                });
            }
            cpu.r[0] = mem.to_new(ret("lo").unwrap_or(0));
            cpu.r[1] = mem.to_new(ret("hi").unwrap_or(0));
            (cpu.r[2], cpu.r[3], cpu.r[12]) = (0xdead_0002, 0xdead_0003, 0xdead_000c);
            mem.epoch += 1;
            let frame = mem.frame;
            mem.written.retain(|k, _| *k >= frame.0 && *k < frame.1);
            cpu.pc = back & !1;
        }
    }
    Err(format!(
        "the {} image does not come to an end in {STEPS} instructions",
        if side == 0 { "old" } else { "new" }
    ))
}

/// Do two memories written by the two runs differ?  A word that holds corresponding pointers
/// is the same.
fn memory_differs(
    sp: &Space,
    model: &Model,
    epoch: u32,
    x: &BTreeMap<u32, u8>,
    y: &BTreeMap<u32, u8>,
) -> Option<String> {
    // What a byte holds that a run did not write.
    let initial = |k: u32| -> u8 {
        (0..=epoch)
            .rev()
            .find_map(|e| model.mem.get(&(e, k as u64)).copied())
            .or_else(|| sp.da.read(k, 1).map(|b| b[0]))
            .unwrap_or(0)
    };
    for k in x.keys().chain(y.keys()) {
        let (bx, by) = (
            x.get(k).copied().unwrap_or_else(|| initial(*k)),
            y.get(k).copied().unwrap_or_else(|| initial(*k)),
        );
        if bx == by {
            continue;
        }
        let base = k & !3;
        let word = |m: &BTreeMap<u32, u8>| -> Option<u32> {
            (0..4).try_fold(0u32, |v, i| Some(v | (*m.get(&(base + i))? as u32) << (8 * i)))
        };
        if let (Some(wa), Some(wb)) = (word(x), word(y))
            && wa != wb
            && sp.same_const(wa, wb)
        {
            continue;
        }
        return Some(format!("the byte at {k:#x}: old {bx:#04x}, new {by:#04x}"));
    }
    None
}

/// Run the counterexample on both functions and look for what `why` says differs.
pub(super) fn replay(sp: &Space, entry: [u32; 2], model: &Model, why: &str) -> Replay {
    let (ra, rb) = match (run(sp, 0, entry[0], model), run(sp, 1, entry[1], model)) {
        (Ok(a), Ok(b)) => (a, b),
        (Err(e), _) | (_, Err(e)) => return Replay::NotModelled(e),
    };
    let names = |r: &Run| -> Vec<String> { r.events.iter().map(|e| e.name.clone()).collect() };
    let show_end = |r: &Run| match &r.end {
        End::Return(v) => format!("returns {v:#x}"),
        End::Gone => "does not return".to_string(),
        End::Trap => "traps".to_string(),
    };
    let kind = |r: &Run| std::mem::discriminant(&r.end);
    let (na, nb) = (names(&ra), names(&rb));
    // What the two runs do, call by call.
    let calls = if na != nb {
        let i = (na.iter().zip(&nb)).take_while(|(x, y)| x == y).count();
        let at = |n: &[String], r: &Run| n.get(i).map_or_else(|| show_end(r), |c| format!("calls {c}"));
        Some(format!(
            "after {i} matching call(s) the old code {}, the new code {}",
            at(&na, &ra),
            at(&nb, &rb)
        ))
    } else if kind(&ra) != kind(&rb) {
        Some(format!(
            "after {} matching call(s) the old code {}, the new code {}",
            na.len(),
            show_end(&ra),
            show_end(&rb)
        ))
    } else {
        None
    };
    let targets = (ra.events.iter().zip(&rb.events))
        .position(|(x, y)| x.name == "<indirect call>" && y.name == x.name && x.target != y.target)
        .map(|i| {
            format!(
                "call #{} through a pointer goes to {:#x} in the old code and to {:#x} in the new",
                i + 1,
                ra.events[i].target,
                rb.events[i].target
            )
        });
    let stores = (ra.events.iter().zip(&rb.events))
        .enumerate()
        .find_map(|(i, (x, y))| {
            memory_differs(sp, model, i as u32, &x.written, &y.written).map(|d| format!("at call #{}, {d}", i + 1))
        })
        .or_else(|| {
            (na == nb && kind(&ra) == kind(&rb))
                .then(|| memory_differs(sp, model, na.len() as u32, &ra.written, &rb.written))
                .flatten()
                .map(|d| format!("at the end, {d}"))
        });
    let result = match (&ra.end, &rb.end) {
        (End::Return(x), End::Return(y)) if na == nb && x != y && !sp.same_const(*x, *y) => {
            Some(format!("the old code returns {x:#x}, the new code {y:#x}"))
        }
        _ => None,
    };
    // What the verdict names decides; a run that parts ways earlier than the verdict says
    // shows a difference all the same.
    let wanted = if why.contains("r0 at return") || why.contains("r1 at return") {
        result.clone().or(calls.clone())
    } else if why.contains("target of the call through a pointer") {
        targets.clone().or(calls.clone())
    } else if why.contains("stored at") || why.contains("caller's stack") || why.contains("written to") {
        stores.clone().or(calls.clone())
    } else if why.contains("matching call(s)") {
        calls.clone().or(targets.clone())
    } else {
        // (A verdict in other words, as one taken from the comparison with the source.)
        (calls.clone())
            .or(targets.clone())
            .or(result.clone())
            .or(stores.clone())
    };
    match wanted {
        Some(d) => Replay::Reproduced(d),
        None => {
            let other = result.or(stores).or(targets);
            Replay::NotReproduced(format!(
                "both runs make the call(s) {na:?}; the old code {}, the new code {}{}",
                show_end(&ra),
                show_end(&rb),
                other.map_or(String::new(), |o| format!(" (the runs differ otherwise: {o})"))
            ))
        }
    }
}