cverif 0.0.0

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Typed C program representation (target: ARM EABI, ILP32, little-endian).

use super::lex::Loc;
use std::collections::HashMap;
use std::rc::Rc;

pub type TypeId = u32;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct FuncType {
    pub ret: TypeId,
    pub params: Vec<TypeId>,
    pub variadic: bool,
    /// Declared with a prototype (`f(void)` or `f(int)`, as opposed to `f()`).
    pub proto: bool,
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Type {
    Void,
    Bool,
    Int { size: u8, signed: bool },
    Float { size: u8 },
    Ptr(TypeId),
    Array(TypeId, Option<u32>),
    Func(Rc<FuncType>),
    Record(u32),
}

pub const VOID: TypeId = 0;
pub const BOOL: TypeId = 1;
pub const UCHAR: TypeId = 2;
pub const SCHAR: TypeId = 3;
pub const SHORT: TypeId = 4;
pub const USHORT: TypeId = 5;
pub const INT: TypeId = 6;
pub const UINT: TypeId = 7;
pub const LLONG: TypeId = 8;
pub const ULLONG: TypeId = 9;
pub const FLOAT: TypeId = 10;
pub const DOUBLE: TypeId = 11;

#[derive(Clone, Debug)]
pub struct Field {
    pub name: Rc<str>,
    pub ty: TypeId,
    pub offset: u32,
}

#[derive(Clone, Debug)]
pub struct Record {
    pub name: Option<Rc<str>>,
    pub is_union: bool,
    pub fields: Vec<Field>,
    pub size: u32,
    pub align: u32,
    pub complete: bool,
}

#[derive(Clone, Debug, PartialEq)]
pub enum SymRef {
    Global(u32),
    Func(u32),
    Str(u32),
}

/// Initial contents of a global: raw bytes plus address relocations.
#[derive(Clone, Debug, Default)]
pub struct Init {
    pub bytes: Vec<u8>,
    /// (offset, target, addend): a 32-bit pointer to `target + addend` is stored at `offset`.
    pub relocs: Vec<(u32, SymRef, i64)>,
}

#[derive(Clone, Debug)]
pub struct Global {
    pub name: Rc<str>,
    pub ty: TypeId,
    /// Internal linkage (file-scope `static`) or function-local `static`.
    pub is_static: bool,
    /// Function-local static: the binary symbol is `name.N`.
    pub is_local_static: bool,
    pub is_const: bool,
    pub is_volatile: bool,
    /// Has a definition (initializer or tentative definition) rather than only `extern`.
    pub defined: bool,
    pub init: Option<Init>,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub struct Local {
    pub name: Rc<str>,
    pub ty: TypeId,
}

#[derive(Clone, Debug)]
pub struct Func {
    pub name: Rc<str>,
    pub ty: Rc<FuncType>,
    pub is_static: bool,
    pub is_inline: bool,
    /// The first `nparams` locals are the parameters.
    pub nparams: usize,
    pub locals: Vec<Local>,
    pub body: Option<Body>,
    pub loc: Loc,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Rem,
    And,
    Or,
    Xor,
    Shl,
    Shr,
    Eq,
    Ne,
    Lt,
    Le,
}

#[derive(Clone, Debug)]
pub struct Expr {
    pub kind: EK,
    pub ty: TypeId,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum EK {
    Const(u64),
    FConst(f64),
    // --- lvalues ---
    Str(u32),
    Local(u32),
    Global(u32),
    /// Function designator.
    Func(u32),
    Deref(Box<Expr>),
    /// Member of the lvalue at byte offset.
    Member(Box<Expr>, u32),
    // --- rvalues ---
    /// Address of an lvalue (also array and function decay).
    Addr(Box<Expr>),
    /// Lvalue-to-rvalue conversion.
    Load(Box<Expr>),
    /// Conversion to `ty`.
    Cast(Box<Expr>),
    Neg(Box<Expr>),
    BitNot(Box<Expr>),
    LogNot(Box<Expr>),
    /// Operands already converted to the operation type (the left operand's type).
    Bin(BinOp, Box<Expr>, Box<Expr>),
    /// pointer + index * elem_size; index is a 32-bit signed integer.
    PtrAdd(Box<Expr>, Box<Expr>, u32),
    /// (a - b) / elem_size
    PtrDiff(Box<Expr>, Box<Expr>, u32),
    LogAnd(Box<Expr>, Box<Expr>),
    LogOr(Box<Expr>, Box<Expr>),
    Cond(Box<Expr>, Box<Expr>, Box<Expr>),
    Comma(Box<Expr>, Box<Expr>),
    Assign(Box<Expr>, Box<Expr>),
    /// Read-modify-write of an lvalue.  The second operand computes the new value and refers
    /// to the old one through `EK::Prev`.  With `post`, the result is the old value.
    AssignOp(Box<Expr>, Box<Expr>, bool),
    Prev,
    /// Callee is a pointer-to-function rvalue.
    Call(Box<Expr>, Vec<Expr>),
}

#[derive(Clone, Debug)]
pub struct Stmt {
    pub kind: SK,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum SK {
    Expr(Expr),
    /// Initialise a local: optionally zero it, then store each (offset, value).
    Init {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
    Block(Vec<Stmt>),
    If(Expr, Box<Stmt>, Option<Box<Stmt>>),
    While(Expr, Box<Stmt>),
    DoWhile(Box<Stmt>, Expr),
    For(Option<Box<Stmt>>, Option<Expr>, Option<Expr>, Box<Stmt>),
    Switch(Expr, Box<Stmt>),
    Case(u64),
    Default,
    Break,
    Continue,
    Return(Option<Expr>),
    Goto(Rc<str>),
    Label(Rc<str>),
    Empty,
}

/// Control-flow graph of a function body.
#[derive(Clone, Debug, Default)]
pub struct Body {
    pub blocks: Vec<Block>,
}

#[derive(Clone, Debug)]
pub struct Block {
    pub ops: Vec<Op>,
    pub term: Term,
    /// Coverage point of the terminator.
    pub term_cov: u32,
    pub term_loc: Loc,
}

#[derive(Clone, Debug)]
pub struct Op {
    pub kind: OpKind,
    /// Coverage point id, unique within the program.
    pub cov: u32,
    pub loc: Loc,
}

#[derive(Clone, Debug)]
pub enum OpKind {
    Eval(Expr),
    Init {
        var: u32,
        zero: bool,
        items: Vec<(u32, Expr)>,
    },
}

#[derive(Clone, Debug)]
pub enum Term {
    Jump(usize),
    Br(Expr, usize, usize),
    Switch(Expr, Vec<(u64, usize)>, usize),
    Ret(Option<Expr>),
    /// Falling off the end of a non-void function, or a block not yet terminated.
    Unreachable,
}

#[derive(Default)]
pub struct Program {
    pub types: Vec<Type>,
    type_map: HashMap<Type, TypeId>,
    pub records: Vec<Record>,
    pub globals: Vec<Global>,
    pub funcs: Vec<Func>,
    pub strings: Vec<Rc<[u8]>>,
    pub files: Vec<String>,
    /// Number of coverage points allocated.
    pub ncov: u32,
    /// Coverage point -> (function index, location).
    pub cov_info: Vec<(u32, Loc)>,
}

impl Program {
    pub fn new() -> Program {
        let mut p = Program::default();
        let base = [
            Type::Void,
            Type::Bool,
            Type::Int { size: 1, signed: false },
            Type::Int { size: 1, signed: true },
            Type::Int { size: 2, signed: true },
            Type::Int { size: 2, signed: false },
            Type::Int { size: 4, signed: true },
            Type::Int { size: 4, signed: false },
            Type::Int { size: 8, signed: true },
            Type::Int { size: 8, signed: false },
            Type::Float { size: 4 },
            Type::Float { size: 8 },
        ];
        for t in base {
            p.intern(t);
        }
        p
    }

    pub fn intern(&mut self, t: Type) -> TypeId {
        if let Some(&id) = self.type_map.get(&t) {
            return id;
        }
        let id = self.types.len() as TypeId;
        self.types.push(t.clone());
        self.type_map.insert(t, id);
        id
    }

    pub fn ty(&self, id: TypeId) -> &Type {
        &self.types[id as usize]
    }

    pub fn ptr_to(&mut self, t: TypeId) -> TypeId {
        self.intern(Type::Ptr(t))
    }

    pub fn is_integer(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Bool | Type::Int { .. })
    }

    pub fn is_float(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Float { .. })
    }

    pub fn is_arith(&self, t: TypeId) -> bool {
        self.is_integer(t) || self.is_float(t)
    }

    pub fn is_ptr(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Ptr(_))
    }

    pub fn is_scalar(&self, t: TypeId) -> bool {
        self.is_arith(t) || self.is_ptr(t)
    }

    pub fn is_signed(&self, t: TypeId) -> bool {
        matches!(self.ty(t), Type::Int { signed: true, .. })
    }

    pub fn pointee(&self, t: TypeId) -> Option<TypeId> {
        match self.ty(t) {
            Type::Ptr(p) => Some(*p),
            _ => None,
        }
    }

    /// Size in bytes; None for incomplete types.
    pub fn size_of(&self, t: TypeId) -> Option<u32> {
        Some(match self.ty(t) {
            Type::Void | Type::Func(_) => 1,
            Type::Bool => 1,
            Type::Int { size, .. } | Type::Float { size } => *size as u32,
            Type::Ptr(_) => 4,
            Type::Array(e, n) => self.size_of(*e)?.checked_mul((*n)?)?,
            Type::Record(r) => {
                let r = &self.records[*r as usize];
                if !r.complete {
                    return None;
                }
                r.size
            }
        })
    }

    pub fn align_of(&self, t: TypeId) -> u32 {
        match self.ty(t) {
            Type::Void | Type::Func(_) | Type::Bool => 1,
            Type::Int { size, .. } | Type::Float { size } => *size as u32,
            Type::Ptr(_) => 4,
            Type::Array(e, _) => self.align_of(*e),
            Type::Record(r) => self.records[*r as usize].align.max(1),
        }
    }

    /// Width in bits of a scalar type as a term.
    pub fn bits(&self, t: TypeId) -> u8 {
        match self.ty(t) {
            Type::Bool => 8,
            Type::Int { size, .. } | Type::Float { size } => size * 8,
            _ => 32,
        }
    }

    pub fn type_name(&self, t: TypeId) -> String {
        match self.ty(t) {
            Type::Void => "void".into(),
            Type::Bool => "_Bool".into(),
            Type::Int { size, signed } => {
                format!("{}int{}_t", if *signed { "" } else { "u" }, size * 8)
            }
            Type::Float { size } => if *size == 4 { "float" } else { "double" }.into(),
            Type::Ptr(p) => format!("{}*", self.type_name(*p)),
            Type::Array(e, n) => format!(
                "{}[{}]",
                self.type_name(*e),
                n.map(|n| n.to_string()).unwrap_or_default()
            ),
            Type::Func(f) => format!("{}()", self.type_name(f.ret)),
            Type::Record(r) => {
                let r = &self.records[*r as usize];
                format!(
                    "{} {}",
                    if r.is_union { "union" } else { "struct" },
                    r.name.as_deref().unwrap_or("<anon>")
                )
            }
        }
    }
}