cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! C front end: preprocessor, parser, type checker and CFG lowering.

pub mod ast;
pub mod borrow;
pub mod callers;
pub mod exec;
pub mod lex;
pub mod lower;
pub mod parse;
pub mod target;

use std::path::{Path, PathBuf};

/// Front-end options.
#[derive(Default, Clone, Debug)]
pub struct Options {
    pub include_dirs: Vec<PathBuf>,
    pub defines: Vec<(String, String)>,
    /// Macros undefined with `-U` (applied after `defines`).
    pub undefines: Vec<String>,
    /// Files included before each source file (`-include`).
    pub forced_includes: Vec<PathBuf>,
    /// Size of enumerated types: `Some(true)` the smallest type that fits (`-fshort-enums`),
    /// `Some(false)` at least `int`.  `None` means GCC's bare-metal ARM default, short enums.
    pub short_enums: Option<bool>,
    /// The compiler and architecture whose predefined macros the preprocessor provides.
    pub target: target::Target,
}

impl Options {
    /// Options matching the ABI variant the binary records in its build attributes.
    pub fn for_image(image: &crate::image::Image) -> Options {
        Options {
            short_enums: image.short_enums,
            target: target::Target::for_image(image),
            ..Default::default()
        }
    }
}

/// Parse a set of C translation units into one program.
pub fn parse_files(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, String> {
    parse_units(paths, opts).map_err(|(_, e)| e)
}

/// Like [`parse_files`], but a translation unit the front end cannot parse is left out
/// instead of failing the whole run: its functions simply have no source.  Returns the
/// program and every file left out with its error.  Nothing of a failed unit is kept (the
/// remaining files are parsed afresh), so no half-read declaration can influence a proof.
pub fn parse_files_lenient(
    paths: &[PathBuf],
    opts: &Options,
) -> Result<(ast::Program, Vec<(PathBuf, String)>), String> {
    let mut paths = paths.to_vec();
    let mut skipped = Vec::new();
    loop {
        match parse_units(&paths, opts) {
            Ok(prog) => return Ok((prog, skipped)),
            Err((Some(i), e)) => skipped.push((paths.remove(i), e)),
            Err((None, e)) => return Err(e),
        }
    }
}

/// On failure, the index of the file at fault (none when the options themselves are wrong).
fn parse_units(paths: &[PathBuf], opts: &Options) -> Result<ast::Program, (Option<usize>, String)> {
    let mut prog = ast::Program::new();
    prog.int_enums = opts.short_enums == Some(false);
    let mut externs = parse::Externs::default();
    let target = opts.target.predefines();
    let defs: Vec<(String, Option<String>)> = opts
        .defines
        .iter()
        .map(|(k, v)| (k.clone(), Some(v.clone())))
        .chain(opts.undefines.iter().map(|k| (k.clone(), None)))
        .collect();
    // Preprocessing a unit depends on nothing but the unit: all of them at once.  Parsing
    // then goes file by file in the order given, as the units share one program.
    type Pre = Result<(Vec<lex::Token>, Vec<PathBuf>), (Option<usize>, String)>;
    let preprocess = |index: usize| -> Pre {
        let mut pp =
            lex::Preprocessor::new(opts.include_dirs.clone(), &target, &defs).map_err(|e| (None, fmt_err(&[], &e)))?;
        let toks = pp
            .preprocess_file(&paths[index], &opts.forced_includes)
            .map_err(|e| (Some(index), fmt_err(&pp.files, &e)))?;
        Ok((toks, pp.files.clone()))
    };
    let workers = std::thread::available_parallelism()
        .map_or(1, |n| n.get())
        .min(8)
        .min(paths.len().max(1));
    let next = std::sync::atomic::AtomicUsize::new(0);
    let done: Vec<std::sync::Mutex<Option<Pre>>> = paths.iter().map(|_| std::sync::Mutex::new(None)).collect();
    std::thread::scope(|scope| {
        for _ in 0..workers {
            scope.spawn(|| {
                loop {
                    let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    if i >= paths.len() {
                        break;
                    }
                    *done[i].lock().unwrap() = Some(preprocess(i));
                }
            });
        }
    });
    let mut file_ids: std::collections::HashMap<String, u16> = std::collections::HashMap::new();
    for (index, path) in paths.iter().enumerate() {
        let at = Some(index);
        let (toks, files) = done[index]
            .lock()
            .unwrap()
            .take()
            .expect("every unit was preprocessed")?;
        // File ids are per translation unit; map them onto the program-wide table, in which a
        // file has one id however many units include it.
        let mut ids: Vec<u16> = Vec::with_capacity(files.len());
        for f in &files {
            let name = f.display().to_string();
            let id = match file_ids.get(&name) {
                Some(id) => *id,
                None => {
                    let id = u16::try_from(prog.files.len())
                        .ok()
                        .filter(|id| *id < u16::MAX)
                        .ok_or_else(|| (None, "more than 65534 source files (headers included)".to_string()))?;
                    prog.files.push(name.clone());
                    file_ids.insert(name, id);
                    id
                }
            };
            ids.push(id);
        }
        let toks = toks
            .into_iter()
            .map(|mut t| {
                t.loc.file = ids[t.loc.file as usize];
                t
            })
            .collect();
        parse::parse_unit(&mut prog, &mut externs, toks).map_err(|mut e| {
            // (Back to the unit's own numbering, for its file table.)
            e.loc.file = ids.iter().position(|i| *i == e.loc.file).unwrap_or(0) as u16;
            (at, fmt_err(&files, &e))
        })?;
        // Everything created while parsing this file belongs to its translation unit.
        let unit = prog.units.len() as u16;
        prog.units.push(path.display().to_string());
        prog.func_unit.resize(prog.funcs.len(), unit);
        prog.global_unit.resize(prog.globals.len(), unit);
    }
    Ok(prog)
}

fn fmt_err(files: &[PathBuf], e: &lex::CError) -> String {
    let f = files
        .get(e.loc.file as usize)
        .map(|p| p.display().to_string())
        .unwrap_or_else(|| "<input>".into());
    format!("{f}:{}: {}", e.loc.line, e.msg)
}

/// Collect the C source files under a path (a file or a directory tree).
pub fn collect_sources(root: &Path) -> std::io::Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    if root.is_file() {
        out.push(root.to_path_buf());
        return Ok(out);
    }
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for ent in std::fs::read_dir(&dir)? {
            let p = ent?.path();
            if p.is_dir() {
                stack.push(p);
            } else if p.extension().is_some_and(|e| e == "c") {
                out.push(p);
            }
        }
    }
    out.sort();
    Ok(out)
}