cverif 0.0.4

Verifies that compiled machine code faithfully matches its C source
Documentation
//! What the callers of a function with internal linkage pass to it.
//!
//! A `static` function whose address is never taken can only be entered from the calls
//! written in its translation unit, and compilers specialise its code for them: an argument
//! that is 0, 1, 2 or 3 at every call lets `flags & 2` become `flags >= 2`.  Such a function is
//! verified for the argument values its callers can pass, not for every value of the
//! parameter's type.
//!
//! The values are read off the source: a parameter has a known set when every call passes
//! a constant, or one of the caller's own parameters that has a known set.  Anything else
//! (one call with a computed argument, the address taken anywhere, a function of the unit
//! the front end could not read) leaves the parameter unconstrained.
//!
//! Soundness.  The claim made for the function is "for these argument values" and is
//! reported as such.  It is the whole truth because the binary's callers are verified
//! against the same source calls: a caller's proof shows that the binary passes what the
//! source passes (the argument of the call event, or the callee followed with the actual
//! value), and code of the binary that is not a verified function is not counted as proved
//! anyway.

use super::ast::{EK, Expr, OpKind, Program, Term, Type};
use std::collections::BTreeSet;

/// Most distinct values a parameter may take and still be described by enumeration.
const MAX_VALUES: usize = 16;

/// For every function, per parameter: the values its callers pass, when known.
pub type Given = Vec<Vec<Option<BTreeSet<u64>>>>;

/// What is known about who calls each function.
#[derive(Default, Clone, Debug)]
pub struct Callers {
    pub given: Given,
    /// The function has internal linkage, its address is never taken and every function of
    /// its translation unit was read: it is only entered from `callers`.  How such a
    /// function is called is the compiler's business (it may drop an unused argument or a
    /// result nobody uses), so it is only meaningful together with its callers.
    pub private: Vec<bool>,
    /// The functions with a direct call to it.
    pub callers: Vec<Vec<u32>>,
    /// A `private` function none of whose calls uses the result: every call is an
    /// expression statement.  The compiler need not compute the result at all (clang
    /// removes it), so it is not compared, and the binary's callers are verified with an
    /// unknown value in the result register after the call.
    pub result_unused: Vec<bool>,
}

#[derive(Clone, Debug)]
enum Arg {
    Const(u64),
    /// The caller's own parameter, passed on unchanged.
    Param(u32),
    Unknown,
}

struct Scan<'a> {
    prog: &'a Program,
    /// Functions referred to other than as the callee of a direct call.
    taken: Vec<bool>,
    /// Direct calls: (caller, callee, arguments).
    calls: Vec<(u32, u32, Vec<Arg>)>,
    caller: u32,
    /// Parameters of the caller that it assigns to or takes the address of.
    dirty: Vec<BTreeSet<u32>>,
    /// Functions with a call whose result is used.
    used: Vec<bool>,
    /// The expression being visited is a whole expression statement.
    statement: bool,
}

fn direct(e: &Expr) -> Option<u32> {
    match &e.kind {
        EK::Func(f) => Some(*f),
        EK::Addr(f) | EK::Cast(f) => direct(f),
        _ => None,
    }
}

impl Scan<'_> {
    fn arg(&self, e: &Expr, to: super::ast::TypeId) -> Arg {
        let p = self.prog;
        let int = |t| matches!(p.ty(p.unqual(t)), Type::Int { .. } | Type::Bool);
        if !int(to) || !int(e.ty) || p.bits(to) > 32 || p.bits(e.ty) > 32 {
            return Arg::Unknown;
        }
        match &e.kind {
            EK::Const(c) => {
                let w = p.bits(to);
                Arg::Const(if w >= 64 { *c } else { *c & ((1u64 << w) - 1) })
            }
            // A conversion that keeps the value: to a type at least as wide, or of a constant.
            EK::Cast(inner) => match self.arg(inner, to) {
                Arg::Const(c) => {
                    let w = p.bits(e.ty).min(p.bits(to));
                    Arg::Const(if w >= 64 { c } else { c & ((1u64 << w) - 1) })
                }
                Arg::Param(i) if p.bits(e.ty) >= p.bits(inner.ty) && !p.is_signed(inner.ty) => Arg::Param(i),
                _ => Arg::Unknown,
            },
            // Constant expressions the parser left unfolded.  These operations commute with
            // truncation to the parameter's width.
            EK::Bin(op, a, b) => {
                use super::ast::BinOp as B;
                let (Arg::Const(x), Arg::Const(y)) = (self.arg(a, to), self.arg(b, to)) else {
                    return Arg::Unknown;
                };
                let w = p.bits(to);
                let v = match op {
                    B::Add => x.wrapping_add(y),
                    B::Sub => x.wrapping_sub(y),
                    B::Mul => x.wrapping_mul(y),
                    B::And => x & y,
                    B::Or => x | y,
                    B::Xor => x ^ y,
                    _ => return Arg::Unknown,
                };
                Arg::Const(v & ((1u64 << w) - 1))
            }
            EK::Load(l) => match &l.kind {
                EK::Local(i) if (*i as usize) < p.funcs[self.caller as usize].nparams && p.bits(e.ty) == p.bits(to) => {
                    Arg::Param(*i)
                }
                _ => Arg::Unknown,
            },
            _ => Arg::Unknown,
        }
    }

    fn lvalue_root(&mut self, e: &Expr) {
        match &e.kind {
            EK::Local(i) => {
                self.dirty[self.caller as usize].insert(*i);
            }
            EK::Member(b, _) | EK::BitField(b, ..) | EK::Bits(b, ..) => self.lvalue_root(b),
            _ => {}
        }
    }

    fn expr(&mut self, e: &Expr) {
        let statement = std::mem::take(&mut self.statement);
        match &e.kind {
            // `(void)f(x);`
            EK::Cast(a) if statement && matches!(a.kind, EK::Call(..)) => {
                self.statement = true;
                self.expr(a);
            }
            EK::Func(f) => self.taken[*f as usize] = true,
            EK::Const(_) | EK::FConst(_) | EK::Str(_) | EK::Local(_) | EK::Global(_) | EK::Prev | EK::VlaLive(_) => {}
            EK::Addr(a) => {
                self.lvalue_root(a);
                self.expr(a);
            }
            EK::VaStart(a) | EK::VaArg(a) => {
                self.lvalue_root(a);
                self.expr(a);
            }
            EK::Deref(a)
            | EK::Member(a, _)
            | EK::BitField(a, ..)
            | EK::Bits(a, ..)
            | EK::Load(a)
            | EK::Cast(a)
            | EK::Neg(a)
            | EK::BitNot(a)
            | EK::Alloca(a, ..)
            | EK::LogNot(a) => self.expr(a),
            EK::Asm(a) => {
                if let Some(x) = &a.input {
                    self.expr(x);
                }
            }
            EK::Assign(a, b) | EK::AssignOp(a, b, _) => {
                self.lvalue_root(a);
                self.expr(a);
                self.expr(b);
            }
            EK::Bin(_, a, b)
            | EK::PtrAdd(a, b, _)
            | EK::PtrDiff(a, b, _)
            | EK::LogAnd(a, b)
            | EK::LogOr(a, b)
            | EK::Comma(a, b) => {
                self.expr(a);
                self.expr(b);
            }
            EK::Cond(a, b, c) => {
                self.expr(a);
                self.expr(b);
                self.expr(c);
            }
            EK::Compound { items, .. } => items.iter().for_each(|(_, x)| self.expr(x)),
            EK::Call(f, args) => {
                match direct(f) {
                    Some(callee) => {
                        if !statement {
                            self.used[callee as usize] = true;
                        }
                        let params = &self.prog.funcs[callee as usize].ty.params;
                        let vals = (args.iter().enumerate())
                            .map(|(i, a)| params.get(i).map_or(Arg::Unknown, |&t| self.arg(a, t)))
                            .collect();
                        self.calls.push((self.caller, callee, vals));
                    }
                    None => self.expr(f),
                }
                args.iter().for_each(|x| self.expr(x));
            }
        }
    }
}

/// See the module documentation.
pub fn callers(prog: &Program) -> Callers {
    let n = prog.funcs.len();
    let mut scan = Scan {
        prog,
        taken: vec![false; n],
        calls: Vec::new(),
        caller: 0,
        dirty: vec![BTreeSet::new(); n],
        used: vec![false; n],
        statement: false,
    };
    for g in &prog.globals {
        if let Some(init) = &g.init {
            for (_, sym, _) in &init.relocs {
                if let super::ast::SymRef::Func(f) = sym {
                    scan.taken[*f as usize] = true;
                }
            }
        }
    }
    // A unit with a function the front end could not read may do anything with its statics.
    let mut unread = BTreeSet::new();
    for (i, f) in prog.funcs.iter().enumerate() {
        if f.unsupported.is_some() || f.opaque {
            unread.insert(prog.func_unit[i]);
        }
        let Some(body) = &f.body else { continue };
        scan.caller = i as u32;
        for b in &body.blocks {
            for op in &b.ops {
                match &op.kind {
                    OpKind::Eval(e) => {
                        scan.statement = true;
                        scan.expr(e);
                    }
                    OpKind::Init { items, .. } => items.iter().for_each(|(_, e)| scan.expr(e)),
                }
            }
            match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) | Term::Ret(Some(e)) => scan.expr(e),
                Term::Jump(_) | Term::Ret(None) | Term::Unreachable => {}
            }
        }
    }
    let eligible: Vec<bool> = (0..n)
        .map(|i| {
            let f = &prog.funcs[i];
            f.is_static
                && f.body.is_some()
                && !f.variadic_def
                && !scan.taken[i]
                && !unread.contains(&prog.func_unit[i])
                && scan.calls.iter().any(|c| c.1 == i as u32)
        })
        .collect();
    // Start from "no value at all" and add what each call passes until nothing changes; a
    // parameter that receives something unknown is given up for good.
    let mut sets: Given = (0..n)
        .map(|i| vec![eligible[i].then(BTreeSet::new); prog.funcs[i].ty.params.len()])
        .collect();
    loop {
        let mut changed = false;
        for (caller, callee, args) in &scan.calls {
            let (caller, callee) = (*caller as usize, *callee as usize);
            if !eligible[callee] {
                continue;
            }
            for k in 0..sets[callee].len() {
                if sets[callee][k].is_none() {
                    continue;
                }
                let add: Option<BTreeSet<u64>> = match args.get(k) {
                    Some(Arg::Const(c)) => Some([*c].into()),
                    Some(Arg::Param(i)) if !scan.dirty[caller].contains(i) => {
                        sets[caller].get(*i as usize).cloned().flatten()
                    }
                    _ => None,
                };
                let cur = sets[callee][k].as_mut().unwrap();
                match add {
                    Some(vals) if cur.len() + vals.len() <= 2 * MAX_VALUES => {
                        for v in vals {
                            changed |= cur.insert(v);
                        }
                        if cur.len() > MAX_VALUES {
                            sets[callee][k] = None;
                            changed = true;
                        }
                    }
                    _ => {
                        sets[callee][k] = None;
                        changed = true;
                    }
                }
            }
        }
        if !changed {
            break;
        }
    }
    // A set still empty belongs to a function only called from callers that are themselves
    // never called with known values: nothing is known.
    for f in &mut sets {
        for s in f.iter_mut() {
            if s.as_ref().is_some_and(|s| s.is_empty()) {
                *s = None;
            }
        }
    }
    if std::env::var_os("CVERIF_DEBUG").is_some() {
        for (i, f) in prog.funcs.iter().enumerate() {
            if f.is_static && f.body.is_some() {
                eprintln!(
                    "callers of {}: eligible={} taken={} calls={:?} sets={:?}",
                    f.name,
                    eligible[i],
                    scan.taken[i],
                    scan.calls
                        .iter()
                        .filter(|c| c.1 == i as u32)
                        .map(|c| &c.2)
                        .collect::<Vec<_>>(),
                    sets[i]
                );
            }
        }
    }
    let mut callers = vec![Vec::new(); n];
    for (caller, callee, _) in &scan.calls {
        if !callers[*callee as usize].contains(caller) {
            callers[*callee as usize].push(*caller);
        }
    }
    let void = |i: usize| prog.funcs[i].ty.ret == super::ast::VOID;
    Callers {
        given: sets,
        result_unused: (0..n).map(|i| eligible[i] && !scan.used[i] && !void(i)).collect(),
        private: eligible,
        callers,
    }
}