cverif 0.0.4

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Anchoring the source in an image by its data, before any proof.
//!
//! A constant object the source defines has known contents except for the addresses it
//! holds.  It is *located* where the image has exactly those contents, with a plausible
//! address in every pointer slot (an odd address of a function entry for a function, the
//! bytes of the literal for a string), in one place only.  A located object then gives the
//! address of everything it points to: other objects (which have to fit there in turn) and
//! functions.  Programs built around tables of function pointers are named this way almost
//! entirely.
//!
//! What this yields is evidence ("by-data"), not proof: the caller confirms function names
//! by the equivalence proof.

use std::collections::{BTreeMap, BTreeSet};

use crate::c::ast::{Program, SymRef};
use crate::image::Image;

#[derive(Default)]
pub struct Anchors {
    /// Object of the source -> address.
    pub globals: BTreeMap<u32, u32>,
    /// Function of the source -> (address, the object and offset that holds its address).
    pub funcs: BTreeMap<u32, (u32, String)>,
}

struct Pattern {
    gid: u32,
    size: u32,
    align: u32,
    /// Bytes outside the pointer slots.
    bytes: Vec<u8>,
    fixed: Vec<bool>,
    /// How much the fixed bytes say: the number that are not zero.
    weight: usize,
}

fn word(image: &Image, a: u32) -> Option<u32> {
    image
        .read_const(a, 4)
        .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}

struct Finder<'a> {
    prog: &'a Program,
    image: &'a Image,
    starts: &'a BTreeSet<u32>,
    /// Read-only memory: [start, end).
    ro: Vec<(u32, u32)>,
    out: Anchors,
    /// Address -> the function hypothesised there.
    func_at: BTreeMap<u32, u32>,
}

impl Finder<'_> {
    fn in_ro(&self, a: u32) -> bool {
        self.ro.iter().any(|r| a >= r.0 && a < r.1)
    }

    /// Does the image hold object `p` at `at`, consistently with what is located so far?
    fn fits(&self, p: &Pattern, at: u32) -> bool {
        let Some(have) = self.image.read_const(at, p.size) else {
            return false;
        };
        if !(0..p.size as usize).all(|i| !p.fixed[i] || p.bytes[i] == have[i]) {
            return false;
        }
        let g = &self.prog.globals[p.gid as usize];
        for (off, target, add) in g.init.iter().flat_map(|i| &i.relocs) {
            let Some(w) = word(self.image, at + off) else {
                return false;
            };
            let w = w.wrapping_sub(*add as u32);
            let ok = match target {
                SymRef::Func(f) => {
                    w & 1 == 1
                        && self.starts.contains(&(w & !1))
                        && self.out.funcs.get(f).is_none_or(|x| x.0 == w & !1)
                        && self.func_at.get(&(w & !1)).is_none_or(|x| {
                            // (Identical functions may be folded into one.)
                            x == f || self.prog.funcs[*x as usize].name != self.prog.funcs[*f as usize].name
                        })
                }
                SymRef::Global(o) => match self.out.globals.get(o) {
                    Some(a) => *a == w,
                    None => {
                        let t = &self.prog.globals[*o as usize];
                        if t.defined && t.is_const {
                            self.in_ro(w)
                        } else {
                            !self.in_ro(w)
                        }
                    }
                },
                SymRef::Str(s) => {
                    let lit = &self.prog.strings[*s as usize];
                    self.image.read_const(w, lit.len() as u32) == Some(&lit[..])
                }
            };
            if !ok {
                return false;
            }
        }
        true
    }

    /// Object `p` is at `at`: so are the things it points to.  False if one of them cannot be.
    fn place(&mut self, pats: &BTreeMap<u32, Pattern>, gid: u32, at: u32) -> bool {
        let mut work = vec![(gid, at)];
        let mut placed: Vec<u32> = Vec::new();
        let mut named: Vec<u32> = Vec::new();
        let mut ok = true;
        while let Some((gid, at)) = work.pop() {
            match self.out.globals.get(&gid) {
                Some(a) if *a == at => continue,
                Some(_) => {
                    ok = false;
                    break;
                }
                None => {}
            }
            if let Some(p) = pats.get(&gid)
                && !self.fits(p, at)
            {
                ok = false;
                break;
            }
            self.out.globals.insert(gid, at);
            placed.push(gid);
            let g = &self.prog.globals[gid as usize];
            for (off, target, add) in g.init.iter().flat_map(|i| &i.relocs) {
                let Some(w) = word(self.image, at + off) else { continue };
                let w = w.wrapping_sub(*add as u32);
                match target {
                    SymRef::Func(f) if !self.out.funcs.contains_key(f) => {
                        let why = format!(
                            "the source stores its address at {}+{off}, found at {:#x}",
                            g.name,
                            at + off
                        );
                        self.out.funcs.insert(*f, (w & !1, why));
                        self.func_at.entry(w & !1).or_insert(*f);
                        named.push(*f);
                    }
                    SymRef::Global(o) => work.push((*o, w)),
                    _ => {}
                }
            }
        }
        if !ok {
            for g in placed {
                self.out.globals.remove(&g);
            }
            for f in named {
                if let Some((a, _)) = self.out.funcs.remove(&f)
                    && self.func_at.get(&a) == Some(&f)
                {
                    self.func_at.remove(&a);
                }
            }
        }
        ok
    }
}

/// Locate the constant objects of `prog` in `image`.  `starts`: the function entries found
/// in the image; `code`: the ranges that are code or literal pools (no object lies there).
pub fn anchor(prog: &Program, image: &Image, starts: &BTreeSet<u32>, code: &[(u32, u32)]) -> Anchors {
    let mut f = Finder {
        prog,
        image,
        starts,
        ro: image
            .segments
            .iter()
            .filter(|s| !s.writable)
            .map(|s| (s.addr, s.addr + s.data.len() as u32))
            .collect(),
        out: Anchors::default(),
        func_at: BTreeMap::new(),
    };
    // Patterns of the constant objects that say something.
    let mut pats: BTreeMap<u32, Pattern> = BTreeMap::new();
    for (gid, g) in prog.globals.iter().enumerate() {
        let Some(init) = g.init.as_ref().filter(|_| g.defined && g.is_const) else {
            continue;
        };
        let Some(size) = prog.size_of(g.ty) else { continue };
        let size = size.max(init.bytes.len() as u32);
        if size == 0 {
            continue;
        }
        let mut bytes = init.bytes.clone();
        bytes.resize(size as usize, 0);
        let mut fixed = vec![true; size as usize];
        let mut bad = false;
        for (off, ..) in &init.relocs {
            match fixed.get_mut(*off as usize..*off as usize + 4) {
                Some(s) => s.fill(false),
                None => bad = true,
            }
        }
        if bad {
            continue;
        }
        let weight = (0..size as usize).filter(|&i| fixed[i] && bytes[i] != 0).count();
        pats.insert(
            gid as u32,
            Pattern {
                gid: gid as u32,
                size,
                align: prog.align_of(g.ty).max(1),
                bytes,
                fixed,
                weight,
            },
        );
    }
    // Where each could be.
    let in_code = |a: u32, n: u32| {
        let i = code.partition_point(|r| r.1 <= a);
        code.get(i).is_some_and(|r| r.0 < a + n)
    };
    let mut cands: BTreeMap<u32, Vec<u32>> = BTreeMap::new();
    // Objects of the source that look the same before anything is located: with fewer places
    // than objects (the linker dropped some), a place does not say which one it holds.
    let shape = |p: &Pattern| {
        let g = &prog.globals[p.gid as usize];
        let relocs: Vec<(u32, u8, i64)> = (g.init.iter().flat_map(|i| &i.relocs))
            .map(|(off, t, add)| {
                let kind = match t {
                    SymRef::Func(_) => 0,
                    SymRef::Global(o) => {
                        1 + (prog.globals[*o as usize].defined && prog.globals[*o as usize].is_const) as u8
                    }
                    SymRef::Str(_) => 3,
                };
                (*off, kind, *add)
            })
            .collect();
        (p.bytes.clone(), relocs)
    };
    #[allow(clippy::type_complexity)]
    let mut alike: BTreeMap<(Vec<u8>, Vec<(u32, u8, i64)>), usize> = BTreeMap::new();
    for p in pats.values() {
        *alike.entry(shape(p)).or_default() += 1;
    }
    for p in pats.values() {
        let g = &prog.globals[p.gid as usize];
        let relocs = g.init.as_ref().map_or(0, |i| i.relocs.len());
        // Little to go by: such an object is found through what points to it, if at all.
        if p.weight + 2 * relocs < 4 {
            continue;
        }
        let mut found = Vec::new();
        'seg: for seg in image.segments.iter().filter(|s| !s.writable) {
            let mut at = seg.addr.next_multiple_of(p.align);
            while at + p.size <= seg.addr + seg.data.len() as u32 {
                if !in_code(at, p.size) && f.fits(p, at) {
                    found.push(at);
                    if found.len() > 64 {
                        break 'seg;
                    }
                }
                at += p.align;
            }
        }
        if !found.is_empty() && found.len() <= 64 && found.len() >= alike[&shape(p)] {
            cands.insert(p.gid, found);
        }
    }
    if std::env::var_os("CVERIF_ANCHOR_DEBUG").is_some() {
        eprintln!(
            "anchor: {} constant objects, {} with candidate places",
            pats.len(),
            cands.len()
        );
        for p in pats.values() {
            let g = &prog.globals[p.gid as usize];
            eprintln!(
                "anchor:   {} size {} weight {} relocs {} places {:?} alike {}",
                g.name,
                p.size,
                p.weight,
                g.init.as_ref().map_or(0, |i| i.relocs.len()),
                cands.get(&p.gid).map(|c| c.len()),
                alike[&shape(p)]
            );
        }
    }
    // Unique places first; what they point to narrows down the others.
    loop {
        let mut progress = false;
        let gids: Vec<u32> = cands.keys().copied().collect();
        for gid in gids {
            if f.out.globals.contains_key(&gid) {
                cands.remove(&gid);
                continue;
            }
            let p = &pats[&gid];
            let taken: BTreeSet<u32> = f.out.globals.values().copied().collect();
            let live: Vec<u32> = cands[&gid]
                .iter()
                .copied()
                .filter(|at| !taken.contains(at) && f.fits(p, *at))
                .collect();
            match live[..] {
                [] => {
                    cands.remove(&gid);
                }
                [at] => {
                    cands.remove(&gid);
                    progress |= f.place(&pats, gid, at);
                }
                _ => {
                    cands.insert(gid, live);
                }
            }
        }
        if !progress {
            break;
        }
    }
    f.out
}