cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Which pointer parameters a function only borrows.
//!
//! A compiler that sees a callee (same translation unit, or the whole program) works out
//! that the callee does not keep a pointer it is given: it only reads and writes through
//! it.  A caller compiled with that knowledge keeps the pointed-to local in memory for that
//! one call and is free to release or reuse it afterwards, even while other calls follow
//! (GCC's modref escape flags, LLVM's `nocapture`).  Where calls are compared as events the
//! source side has to know the same thing, or it would require the local to stay in memory
//! for every later call.
//!
//! The analysis is syntactic and errs towards "kept".  A parameter is borrowed when the
//! pointer, and everything computed from it, is only ever dereferenced, compared, copied
//! into plain local variables whose address is never taken, or passed on to a parameter
//! that is itself borrowed.  Storing it anywhere else, returning it, passing it to code that
//! is not known to borrow it, or taking the address of a variable that holds it, keeps it.
//! Recursion is resolved optimistically (a greatest fixpoint): the claim "no call of this
//! set of functions keeps the pointer" is proved by induction on the calls made.
//!
//! What a borrowed pointer says nothing about is the contents of the object it points to:
//! a pointer stored *in* that object is read by the callee like any other value, and the
//! event code treats what such pointers lead to as handed over for good.

use super::ast::*;
use std::collections::BTreeSet;

/// Library functions that only read or write through their pointer arguments; those in the
/// first group return their first argument.
const RETURNS_FIRST: [&str; 4] = ["memcpy", "memmove", "memset", "strcpy"];
const ONLY_ACCESS: [&str; 5] = ["memcmp", "strlen", "strcmp", "strncmp", "strnlen"];

/// For every function, for every parameter: is it a pointer the function only borrows?
pub fn borrowed_params(prog: &Program) -> Vec<Vec<bool>> {
    borrowed_params_except(prog, &[])
}

/// The same, with nothing assumed about the functions marked in `unknown` (those whose
/// definition in the source may not be the one that runs).
pub fn borrowed_params_except(prog: &Program, unknown: &[bool]) -> Vec<Vec<bool>> {
    let mut res: Vec<Vec<bool>> = prog
        .funcs
        .iter()
        .enumerate()
        .map(|(fid, f)| {
            let ok = !unknown.get(fid).copied().unwrap_or(false)
                && f.body.is_some()
                && f.unsupported.is_none()
                && !f.opaque
                && !f.variadic_def
                && f.ty.proto;
            (0..f.nparams)
                .map(|i| {
                    ok && f.ty.params.len() == f.nparams && matches!(prog.ty(prog.unqual(f.locals[i].ty)), Type::Ptr(_))
                })
                .collect()
        })
        .collect();
    loop {
        let mut changed = false;
        for (fid, f) in prog.funcs.iter().enumerate() {
            for i in 0..f.nparams {
                if res[fid][i] && !only_borrows(prog, f, i as u32, &res) {
                    res[fid][i] = false;
                    changed = true;
                }
            }
        }
        if !changed {
            return res;
        }
    }
}

struct Walk<'a> {
    prog: &'a Program,
    res: &'a [Vec<bool>],
    /// Locals that may hold the pointer or something computed from it.
    held: BTreeSet<u32>,
    grew: bool,
}

/// The pointer is kept somewhere the analysis does not follow.
struct Kept;

fn only_borrows(prog: &Program, f: &Func, param: u32, res: &[Vec<bool>]) -> bool {
    let Some(body) = &f.body else { return false };
    let mut w = Walk {
        prog,
        res,
        held: BTreeSet::from([param]),
        grew: true,
    };
    while w.grew {
        w.grew = false;
        for b in &body.blocks {
            for op in &b.ops {
                let r = match &op.kind {
                    OpKind::Eval(e) => w.val(e, false).map(|_| ()),
                    OpKind::Init { var, items, .. } => w.init(f, *var, items),
                };
                if r.is_err() {
                    return false;
                }
            }
            let r = match &b.term {
                Term::Br(e, ..) | Term::Switch(e, ..) => w.val(e, false).map(|_| ()),
                Term::Ret(Some(e)) => match w.val(e, false) {
                    Ok(false) => Ok(()),
                    _ => Err(Kept),
                },
                Term::Jump(_) | Term::Ret(None) | Term::Unreachable => Ok(()),
            };
            if r.is_err() {
                return false;
            }
        }
    }
    true
}

impl Walk<'_> {
    fn hold(&mut self, var: u32) {
        if self.held.insert(var) {
            self.grew = true;
        }
    }

    fn init(&mut self, f: &Func, var: u32, items: &[(u32, Expr)]) -> Result<(), Kept> {
        for (off, e) in items {
            if self.val(e, false)? {
                let scalar = matches!(
                    self.prog.ty(self.prog.unqual(f.locals[var as usize].ty)),
                    Type::Ptr(_) | Type::Int { .. }
                );
                if *off != 0 || items.len() != 1 || !scalar {
                    return Err(Kept);
                }
                self.hold(var);
            }
        }
        Ok(())
    }

    /// An lvalue that is read or written: only the computation of its address matters.
    fn access(&mut self, lv: &Expr, prev: bool) -> Result<(), Kept> {
        match &lv.kind {
            EK::Deref(e) => self.val(e, prev).map(|_| ()),
            EK::Member(l, _) | EK::BitField(l, ..) => self.access(l, prev),
            EK::Compound { items, .. } => self.clean(items.iter().map(|x| &x.1), prev),
            _ => Ok(()),
        }
    }

    /// Does the address of this lvalue derive from the pointer?
    fn addr_of(&mut self, lv: &Expr, prev: bool) -> Result<bool, Kept> {
        match &lv.kind {
            EK::Deref(e) => self.val(e, prev),
            EK::Member(l, _) | EK::BitField(l, ..) => self.addr_of(l, prev),
            EK::Local(j) if self.held.contains(j) => Err(Kept),
            EK::Compound { items, .. } => {
                self.clean(items.iter().map(|x| &x.1), prev)?;
                Ok(false)
            }
            _ => Ok(false),
        }
    }

    /// Values that must not derive from the pointer.
    fn clean<'e>(&mut self, es: impl Iterator<Item = &'e Expr>, prev: bool) -> Result<(), Kept> {
        for e in es {
            if self.val(e, prev)? {
                return Err(Kept);
            }
        }
        Ok(())
    }

    /// Does the value of `e` derive from the pointer?  `prev` says so of `EK::Prev`.
    fn val(&mut self, e: &Expr, prev: bool) -> Result<bool, Kept> {
        Ok(match &e.kind {
            EK::Const(_) | EK::FConst(_) | EK::VlaLive(_) => false,
            EK::Prev => prev,
            EK::Load(lv) => match &lv.kind {
                EK::Local(j) => self.held.contains(j),
                _ => {
                    self.access(lv, prev)?;
                    false
                }
            },
            EK::Addr(lv) => self.addr_of(lv, prev)?,
            EK::Cast(a) | EK::Neg(a) | EK::BitNot(a) | EK::Bits(a, ..) => self.val(a, prev)?,
            EK::LogNot(a) => {
                self.val(a, prev)?;
                false
            }
            EK::Bin(op, a, b) => {
                let t = self.val(a, prev)? | self.val(b, prev)?;
                t && !matches!(op, BinOp::Eq | BinOp::Ne | BinOp::Lt | BinOp::Le)
            }
            EK::PtrAdd(a, b, _) | EK::PtrDiff(a, b, _) => self.val(a, prev)? | self.val(b, prev)?,
            EK::LogAnd(a, b) | EK::LogOr(a, b) => {
                self.val(a, prev)?;
                self.val(b, prev)?;
                false
            }
            EK::Cond(c, a, b) => {
                self.val(c, prev)?;
                self.val(a, prev)? | self.val(b, prev)?
            }
            EK::Comma(a, b) => {
                self.val(a, prev)?;
                self.val(b, prev)?
            }
            EK::Assign(lv, rhs) => {
                let t = self.val(rhs, prev)?;
                self.store(lv, t, prev)?;
                t
            }
            EK::AssignOp(lv, new, _) => {
                let old = matches!(&lv.kind, EK::Local(j) if self.held.contains(j));
                let t = self.val(new, old)?;
                self.store(lv, t, prev)?;
                t | old
            }
            EK::Call(callee, args) => {
                if self.val(callee, prev)? {
                    return Err(Kept);
                }
                let target = match &callee.kind {
                    EK::Addr(f) => match f.kind {
                        EK::Func(g) => Some(g as usize),
                        _ => None,
                    },
                    _ => None,
                };
                let mut first = false;
                for (k, a) in args.iter().enumerate() {
                    if !self.val(a, prev)? {
                        continue;
                    }
                    let Some(g) = target else { return Err(Kept) };
                    let gf = &self.prog.funcs[g];
                    let name = gf.name.strip_prefix("__builtin_").unwrap_or(&gf.name);
                    if gf.body.is_some() {
                        if !self.res[g].get(k).copied().unwrap_or(false) {
                            return Err(Kept);
                        }
                    } else if RETURNS_FIRST.contains(&name) {
                        first |= k == 0;
                    } else if !ONLY_ACCESS.contains(&name) {
                        return Err(Kept);
                    }
                }
                first
            }
            EK::VaStart(_) | EK::VaArg(_) => return Err(Kept),
            EK::Alloca(n, ..) => {
                self.val(n, prev)?;
                false
            }
            EK::Asm(insn) => {
                if let Some(i) = &insn.input {
                    self.clean(std::iter::once(i), prev)?;
                }
                false
            }
            // An lvalue where a value is expected does not occur; were it to, only its
            // address computation could matter.
            EK::Str(_) | EK::Global(_) | EK::Func(_) | EK::Local(_) => false,
            EK::Deref(_) | EK::Member(..) | EK::BitField(..) | EK::Compound { .. } => {
                self.access(e, prev)?;
                false
            }
        })
    }

    fn store(&mut self, lv: &Expr, tainted: bool, prev: bool) -> Result<(), Kept> {
        match &lv.kind {
            EK::Local(j) => {
                if tainted {
                    self.hold(*j);
                }
                Ok(())
            }
            _ if tainted => Err(Kept),
            _ => self.access(lv, prev),
        }
    }
}