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
//! Machine-readable coverage output: LCOV for the source side, drcov for the binary side,
//! and a JSON document with everything the verifier established.

use crate::image::{Image, SymKind};
use crate::verify::{BinRange, ByteState, Report, Status};
use std::collections::BTreeMap;
use std::fmt::Write;

/// Per file: line -> (proved points, total points).
fn lines_by_file(r: &Report) -> BTreeMap<&str, BTreeMap<u32, (u32, u32)>> {
    let mut files: BTreeMap<&str, BTreeMap<u32, (u32, u32)>> = BTreeMap::new();
    for p in &r.src_points {
        let e = files.entry(&p.file).or_default().entry(p.line).or_default();
        e.0 += p.proved as u32;
        e.1 += 1;
    }
    files
}

/// Source coverage as an LCOV tracefile.
///
/// A line counts as hit only when every coverage point on it lies on a proved path; lines
/// with several points also get one branch record per point, so partly proved lines show up
/// as partial branch coverage.  A function counts as hit when it was proved (possibly only
/// up to the exploration bound).
pub fn lcov(r: &Report) -> String {
    let mut out = String::new();
    for (file, lines) in lines_by_file(r) {
        let _ = writeln!(out, "TN:cverif");
        let _ = writeln!(out, "SF:{file}");
        // Functions, in order of their first coverage point.
        let mut funcs: Vec<(&str, u32)> = Vec::new();
        for p in r.src_points.iter().filter(|p| p.file == file) {
            match funcs.iter_mut().find(|f| f.0 == p.func) {
                Some(f) => f.1 = f.1.min(p.line),
                None => funcs.push((&p.func, p.line)),
            }
        }
        for (name, line) in &funcs {
            let _ = writeln!(out, "FN:{line},{name}");
        }
        let mut fnh = 0;
        for (name, _) in &funcs {
            let hit = r
                .funcs
                .iter()
                .any(|f| f.name == *name && f.paths > 0 && matches!(f.status, Status::Proved | Status::Bounded(_)))
                || r.src_points
                    .iter()
                    .any(|p| p.file == file && p.func == *name && p.proved);
            fnh += hit as u32;
            let _ = writeln!(out, "FNDA:{},{name}", hit as u32);
        }
        let _ = writeln!(out, "FNF:{}", funcs.len());
        let _ = writeln!(out, "FNH:{fnh}");
        let (mut brf, mut brh) = (0, 0);
        for (&line, &(_, total)) in &lines {
            if total < 2 {
                continue;
            }
            for (i, p) in r
                .src_points
                .iter()
                .filter(|p| p.file == file && p.line == line)
                .enumerate()
            {
                let _ = writeln!(out, "BRDA:{line},0,{i},{}", if p.proved { "1" } else { "0" });
                brf += 1;
                brh += p.proved as u32;
            }
        }
        let _ = writeln!(out, "BRF:{brf}");
        let _ = writeln!(out, "BRH:{brh}");
        let mut lh = 0;
        for (&line, &(proved, total)) in &lines {
            let hit = proved == total;
            lh += hit as u32;
            let _ = writeln!(out, "DA:{line},{}", hit as u32);
        }
        let _ = writeln!(out, "LF:{}", lines.len());
        let _ = writeln!(out, "LH:{lh}");
        let _ = writeln!(out, "end_of_record");
    }
    out
}

/// Lowest and one-past-highest address of the executable segments.
fn module_bounds(image: &Image) -> (u32, u32) {
    let segs = image.segments.iter().filter(|s| s.exec);
    let lo = segs.clone().map(|s| s.addr).min().unwrap_or(0);
    let hi = segs.map(|s| s.addr + s.data.len() as u32).max().unwrap_or(0);
    (lo, hi)
}

/// Binary coverage in DynamoRIO's drcov format (version 2), as read by disassembler
/// coverage plugins: one module (the binary) and one block per proved address range.
pub fn drcov(r: &Report, image: &Image, path: &str) -> Vec<u8> {
    let (base, end) = module_bounds(image);
    let mut blocks: Vec<(u32, u16)> = Vec::new();
    for b in r.bin_ranges.iter().filter(|b| b.state == ByteState::Proved) {
        let mut a = b.start;
        while a < b.end {
            let n = (b.end - a).min(0xfffe);
            blocks.push((a - base, n as u16));
            a += n;
        }
    }
    let mut out = String::new();
    let _ = writeln!(out, "DRCOV VERSION: 2");
    let _ = writeln!(out, "DRCOV FLAVOR: cverif");
    let _ = writeln!(out, "Module Table: version 2, count 1");
    let _ = writeln!(out, "Columns: id, base, end, entry, checksum, timestamp, path");
    let _ = writeln!(out, " 0, {base:#x}, {end:#x}, 0x0, 0x0, 0x0, {path}");
    let _ = writeln!(out, "BB Table: {} bbs", blocks.len());
    let mut out = out.into_bytes();
    for (off, size) in blocks {
        out.extend_from_slice(&off.to_le_bytes());
        out.extend_from_slice(&size.to_le_bytes());
        out.extend_from_slice(&0u16.to_le_bytes());
    }
    out
}

/// Binary coverage per object file, where the image records which file each byte comes
/// from: (object, proved bytes, counted bytes), in address order of first appearance.
/// Bytes of unknown origin are gathered under an empty name.
pub fn object_coverage(r: &Report, image: &Image) -> Vec<(String, usize, usize)> {
    let mut out: Vec<(String, usize, usize)> = Vec::new();
    if image.owners.is_empty() {
        return out;
    }
    for b in r
        .bin_ranges
        .iter()
        .filter(|b| !matches!(b.state, ByteState::Padding | ByteState::SetAside))
    {
        let mut a = b.start;
        while a < b.end {
            let owner = image.owner(a).unwrap_or("");
            // The run of bytes up to the next change of owner.
            let i = image.owners.partition_point(|o| o.0 <= a);
            let end = image.owners.get(i).map_or(b.end, |o| o.0.min(b.end)).max(a + 1);
            let n = (end - a) as usize;
            let slot = match out.iter().position(|o| o.0 == owner) {
                Some(i) => i,
                None => {
                    out.push((owner.to_string(), 0, 0));
                    out.len() - 1
                }
            };
            out[slot].2 += n;
            if b.state == ByteState::Proved {
                out[slot].1 += n;
            }
            a = end;
        }
    }
    out
}

fn json_str(s: &str) -> String {
    let mut o = String::with_capacity(s.len() + 2);
    o.push('"');
    for c in s.chars() {
        match c {
            '"' => o.push_str("\\\""),
            '\\' => o.push_str("\\\\"),
            '\n' => o.push_str("\\n"),
            '\r' => o.push_str("\\r"),
            '\t' => o.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                let _ = write!(o, "\\u{:04x}", c as u32);
            }
            c => o.push(c),
        }
    }
    o.push('"');
    o
}

/// The function symbol containing `addr`, with the offset into it.
/// Code coverage of one object file of the image.
pub struct ObjectCoverage {
    pub name: String,
    /// The directory of its source file, as the sources were given; empty without source.
    pub dir: String,
    /// Some source file given to the tool has this object's name.
    pub has_source: bool,
    pub proved: usize,
    pub total: usize,
}

/// [`object_coverage`] with each object's source directory, and the totals by directory
/// (objects none of whose functions has source under `(no source function)`), largest first.
#[allow(clippy::type_complexity)]
pub fn coverage_tables(r: &Report, image: &Image) -> (Vec<ObjectCoverage>, Vec<(String, usize, usize, usize)>) {
    let stem = |n: &str| {
        let base = n.rsplit(['/', '\\', '(']).next().unwrap_or(n).trim_end_matches(')');
        base.rsplit_once('.').map_or(base, |x| x.0).to_string()
    };
    let mut dirs: BTreeMap<String, String> = BTreeMap::new();
    for p in &r.src_points {
        let dir = p.file.rsplit_once('/').map_or("", |x| x.0);
        dirs.entry(stem(&p.file)).or_insert_with(|| dir.to_string());
    }
    for (file, _) in &r.skipped_sources {
        dirs.entry(stem(file)).or_default();
    }
    let objects: Vec<ObjectCoverage> = object_coverage(r, image)
        .into_iter()
        .map(|(name, proved, total)| {
            let dir = dirs.get(&stem(&name));
            ObjectCoverage {
                has_source: dir.is_some(),
                dir: dir.cloned().unwrap_or_default(),
                name,
                proved,
                total,
            }
        })
        .collect();
    let mut by_dir: BTreeMap<String, (usize, usize, usize)> = BTreeMap::new();
    for o in &objects {
        let key = if o.has_source {
            o.dir.clone()
        } else {
            "(no source function)".to_string()
        };
        let e = by_dir.entry(key).or_default();
        e.0 += o.proved;
        e.1 += o.total;
        e.2 += 1;
    }
    let mut totals: Vec<(String, usize, usize, usize)> = by_dir.into_iter().map(|(d, v)| (d, v.0, v.1, v.2)).collect();
    totals.sort_by(|a, b| b.2.cmp(&a.2).then(a.0.cmp(&b.0)));
    (objects, totals)
}

fn locate(image: &Image, addr: u32) -> Option<(&str, u32)> {
    image
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Func && addr >= s.addr && addr - s.addr < s.size.max(1))
        .map(|s| (s.name.as_str(), addr - s.addr))
        .next()
}

fn range_json(image: &Image, b: &BinRange) -> String {
    let mut o = format!(
        "{{\"start\":{},\"end\":{},\"size\":{},\"state\":\"{}\"",
        b.start,
        b.end,
        b.end - b.start,
        b.state.label()
    );
    if let Some(seg) = image.segment_at(b.start) {
        let _ = write!(
            o,
            ",\"section\":{},\"section_offset\":{}",
            json_str(&seg.name),
            b.start - seg.addr
        );
        if image.soft_bounds {
            let _ = write!(o, ",\"known_code\":{}", seg.exec);
        }
    }
    if let Some(r) = image.set_aside.iter().find(|r| b.start >= r.0 && b.start < r.1)
        && b.state == ByteState::SetAside
    {
        let _ = write!(o, ",\"why\":{}", json_str(&r.2));
    }
    if let Some((name, off)) = locate(image, b.start) {
        let _ = write!(o, ",\"symbol\":{},\"symbol_offset\":{off}", json_str(name));
    }
    o.push('}');
    o
}

/// Everything in one JSON document.  Addresses are numbers; for a relocatable object they
/// are positions in cverif's own layout, so each binary range also carries its section and
/// enclosing function with offsets.  `end` is exclusive, source line ranges are inclusive.
pub fn json(r: &Report, image: &Image, path: &str) -> String {
    let mut o = String::new();
    let _ = write!(
        o,
        "{{\n  \"format\": \"cverif-report\",\n  \"version\": 1,\n  \"binary\": {},\n",
        json_str(path)
    );
    let verdict = if r.has_mismatch() {
        "mismatch"
    } else {
        "no difference found"
    };
    let _ = write!(
        o,
        "  \"verdict\": {},\n  \"score\": {:.1},\n",
        json_str(verdict),
        r.score()
    );
    let _ = writeln!(o, "  \"build\": {},", crate::detect::detect(image).json());
    let _ = writeln!(o, "  \"aliasing\": {},", json_str(r.aliasing));
    if let Some(sb) = image.static_base {
        let _ = writeln!(o, "  \"static_base\": {sb},");
    }
    let names = crate::explain::Names::new(image, None);
    o.push_str("  \"functions\": [");
    for (i, f) in r.funcs.iter().enumerate() {
        let _ = write!(
            o,
            "{}\n    {{\"name\":{},\"address\":{},\"size\":{},\"status\":{},\"detail\":{},\"paths\":{},\"undefined_paths\":{},\"ms\":{}",
            if i > 0 { "," } else { "" },
            json_str(&f.name),
            f.addr,
            f.size,
            json_str(&f.status.label().to_lowercase()),
            json_str(f.status.detail()),
            f.paths,
            f.undefined_paths,
            f.millis
        );
        if f.cached {
            let _ = write!(o, ",\"cached\":true");
        }
        let _ = write!(o, ",\"assumes\":[");
        for (j, a) in f.assumes.iter().enumerate() {
            let _ = write!(o, "{}{}", if j > 0 { "," } else { "" }, json_str(a));
        }
        let _ = write!(o, "]");
        if let Some(g) = &f.given {
            let _ = write!(o, ",\"given\":{}", json_str(g));
        }
        let _ = write!(o, ",\"unconditional\":{},\"modulo\":[", f.unconditional);
        for (j, m) in f.modulo.iter().enumerate() {
            let _ = write!(
                o,
                "{}{{\"name\":{},\"status\":{}}}",
                if j > 0 { "," } else { "" },
                json_str(&m.0),
                json_str(&m.1.to_lowercase())
            );
        }
        o.push(']');
        if !f.hazards.is_empty() {
            o.push_str(",\"hazards\":[");
            for (j, h) in f.hazards.iter().enumerate() {
                let _ = write!(
                    o,
                    "{}{{\"kind\":\"below-sp {}\",\"address\":{},\"size\":{}}}",
                    if j > 0 { "," } else { "" },
                    if h.write { "store" } else { "read" },
                    h.pc,
                    h.size
                );
            }
            o.push(']');
        }
        // Why the function is not proved: the goal, the path, both terms, the counterexample.
        if let Some(e) = f.detail.as_ref().and_then(|d| d.explanation.as_ref()) {
            let _ = write!(o, ",\"explanation\":{}", e.json(&names));
        }
        o.push('}');
    }
    o.push_str("\n  ],\n");
    if !r.skipped_sources.is_empty() {
        o.push_str("  \"skipped_sources\": [");
        for (i, (file, why)) in r.skipped_sources.iter().enumerate() {
            let _ = write!(
                o,
                "{}\n    {{\"path\":{},\"error\":{}}}",
                if i > 0 { "," } else { "" },
                json_str(file),
                json_str(why)
            );
        }
        o.push_str("\n  ],\n");
    }

    // Source side: per file, runs of lines in one state.
    let _ = write!(
        o,
        "  \"source\": {{\n    \"proved\": {},\n    \"total\": {},\n    \"files\": [",
        r.src.0, r.src.1
    );
    for (i, (file, lines)) in lines_by_file(r).into_iter().enumerate() {
        let (proved, total) = lines.values().fold((0, 0), |a, l| (a.0 + l.0, a.1 + l.1));
        let _ = write!(
            o,
            "{}\n      {{\"path\":{},\"proved\":{proved},\"total\":{total},\"ranges\":[",
            if i > 0 { "," } else { "" },
            json_str(file)
        );
        let mut runs: Vec<(u32, u32, &str)> = Vec::new();
        for (&line, &(p, t)) in &lines {
            let state = if p == t {
                "proved"
            } else if p == 0 {
                "unproved"
            } else {
                "partial"
            };
            match runs.last_mut() {
                Some(run) if run.2 == state => run.1 = line,
                _ => runs.push((line, line, state)),
            }
        }
        for (j, (a, b, state)) in runs.iter().enumerate() {
            let _ = write!(
                o,
                "{}\n        {{\"start_line\":{a},\"end_line\":{b},\"state\":\"{state}\"}}",
                if j > 0 { "," } else { "" }
            );
        }
        o.push_str("\n      ]}");
    }
    o.push_str("\n    ]\n  },\n");

    // Binary side.
    let _ = write!(
        o,
        "  \"binary_coverage\": {{\n    \"proved\": {},\n    \"total\": {},\n    \"ranges\": [",
        r.bin.0, r.bin.1
    );
    for (i, b) in r.bin_ranges.iter().enumerate() {
        let _ = write!(o, "{}\n      {}", if i > 0 { "," } else { "" }, range_json(image, b));
    }
    o.push_str("\n    ]\n  },\n");

    let (objects, dirs) = coverage_tables(r, image);
    if !objects.is_empty() {
        o.push_str("  \"objects\": [");
        for (i, x) in objects.iter().enumerate() {
            let _ = write!(
                o,
                "{}\n    {{\"name\":{},\"directory\":{},\"has_source\":{},\"proved\":{},\"total\":{}}}",
                if i > 0 { "," } else { "" },
                json_str(&x.name),
                json_str(&x.dir),
                x.has_source,
                x.proved,
                x.total
            );
        }
        o.push_str("\n  ],\n  \"directories\": [");
        for (i, (d, proved, total, n)) in dirs.iter().enumerate() {
            let _ = write!(
                o,
                "{}\n    {{\"directory\":{},\"objects\":{n},\"proved\":{proved},\"total\":{total}}}",
                if i > 0 { "," } else { "" },
                json_str(d)
            );
        }
        o.push_str("\n  ],\n");
    }
    let _ = write!(o, "  \"data\": {{\"compared\": {}, \"issues\": [", r.data_checked);
    for (i, d) in r.data_issues.iter().enumerate() {
        let _ = write!(o, "{}{}", if i > 0 { "," } else { "" }, json_str(d));
    }
    o.push_str("]},\n  \"unreached_binary_functions\": [");
    for (i, (name, size)) in r.unmatched.iter().enumerate() {
        let _ = write!(
            o,
            "{}{{\"name\":{},\"size\":{size}}}",
            if i > 0 { "," } else { "" },
            json_str(name)
        );
    }
    o.push_str("],\n  \"source_functions_not_in_binary\": [");
    for (i, name) in r.absent.iter().enumerate() {
        let _ = write!(o, "{}{}", if i > 0 { "," } else { "" }, json_str(name));
    }
    o.push_str("]\n}\n");
    o
}