cverif 0.0.3

Verifies that compiled machine code faithfully matches its C source
Documentation
//! 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.
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());
    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
        );
        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(']');
        // 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 _ = 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
}