cverif 0.0.7

Verifies that compiled machine code faithfully matches its C source
Documentation
//! Floating point, end to end: the float corpus compiled for software floating point by gcc
//! and clang at every optimisation level must be proved; `-ffast-math` builds and the
//! floating-point mutants must not be.
//!
//! The tests skip themselves when a cross compiler is not installed.

use cverif::image::Image;
use cverif::verify::{Options, Report, Status, verify};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

const GCC: &str = "arm-none-eabi-gcc";
const CLANG: &str = "clang";
const ALL_LEVELS: &[&str] = &["-Oz", "-Os", "-O0", "-O1", "-O2", "-O3"];

#[derive(Clone, Copy)]
struct Toolchain {
    name: &'static str,
    cc: &'static str,
    flags: &'static [&'static str],
}

const GCC_M3: Toolchain = Toolchain {
    name: "gcc-m3",
    cc: GCC,
    flags: &["-mthumb", "-mcpu=cortex-m3"],
};
const GCC_M0: Toolchain = Toolchain {
    name: "gcc-m0",
    cc: GCC,
    flags: &["-mthumb", "-mcpu=cortex-m0"],
};
const GCC_M35P: Toolchain = Toolchain {
    name: "gcc-m35p",
    cc: GCC,
    flags: &["-mcpu=cortex-m35p+nodsp", "-mthumb", "-msoft-float"],
};
const GCC_M4F: Toolchain = Toolchain {
    name: "gcc-m4f-hard",
    cc: GCC,
    flags: &["-mthumb", "-mcpu=cortex-m4", "-mfloat-abi=hard", "-mfpu=fpv4-sp-d16"],
};
const CLANG_M0PLUS_ROPI: Toolchain = Toolchain {
    name: "clang-m0plus-ropi",
    cc: CLANG,
    flags: &[
        "-fomit-frame-pointer",
        "-momit-leaf-frame-pointer",
        "-mcpu=cortex-m0plus",
        "-mthumb",
        "-mtune=cortex-m0plus",
        "-mlittle-endian",
        "-mno-unaligned-access",
        "--target=armv6m-none-eabi",
        "-fropi",
        "-fno-jump-tables",
    ],
};
const CLANG_M3_RWPI: Toolchain = Toolchain {
    name: "clang-m3-rwpi",
    cc: CLANG,
    flags: &["--target=armv7m-none-eabi", "-mcpu=cortex-m3", "-mthumb", "-frwpi"],
};
const CLANG_M35P_RWPI: Toolchain = Toolchain {
    name: "clang-m35p-rwpi",
    cc: CLANG,
    flags: &[
        "--target=armv8m.main-none-eabi",
        "-mcpu=cortex-m35p+nodsp",
        "-mthumb",
        "-msoft-float",
        "-frwpi",
    ],
};

/// (mutant number, the one function it changes)
const MUTANTS: &[(u32, &str)] = &[
    (1, "mf_lt"),
    (2, "mf_ulp"),
    (3, "mf_prec"),
    (4, "mf_sub"),
    (5, "mf_div"),
    (6, "mf_round"),
    (7, "mf_assoc"),
    (8, "mf_nan"),
    (9, "mf_conv"),
    (10, "mf_table"),
    (11, "mf_zero"),
    (12, "mf_mul_zero"),
    (13, "mf_double_const"),
    (14, "mf_call"),
    (15, "mf_recip"),
    (16, "mf_negsub"),
];

fn corpus(name: &str) -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/corpus").join(name)
}

fn tmp(name: &str) -> PathBuf {
    let dir = Path::new(env!("CARGO_TARGET_TMPDIR")).join("float");
    std::fs::create_dir_all(&dir).unwrap();
    dir.join(name)
}

fn check_obj(obj: &Path, src: &Path) -> Report {
    let image = Image::from_elf(&std::fs::read(obj).unwrap()).expect("load ELF");
    let src = src.to_path_buf();
    // Term construction recurses deeply; use a generous stack like the CLI does.
    std::thread::Builder::new()
        .stack_size(32 << 20)
        .spawn(move || {
            let prog = cverif::c::parse_files(&[src], &Default::default()).expect("parse C");
            let opts = Options {
                time_limit: Duration::from_secs(10),
                ..Default::default()
            };
            verify(&prog, &image, &opts)
        })
        .unwrap()
        .join()
        .unwrap()
}

fn describe(r: &Report) -> String {
    let mut s = String::new();
    for f in &r.funcs {
        if f.status != Status::Proved {
            s.push_str(&format!("  {} {}: {}\n", f.status.label(), f.name, f.status.detail()));
        }
    }
    for d in &r.data_issues {
        s.push_str(&format!("  DATA {d}\n"));
    }
    s
}

impl Toolchain {
    fn try_compile(&self, src: &Path, level: &str, extra: &[&str]) -> Result<PathBuf, String> {
        let stem = src.file_stem().unwrap().to_string_lossy();
        let tag: String = extra
            .iter()
            .flat_map(|e| e.chars())
            .filter(|c| c.is_ascii_alphanumeric())
            .collect();
        let obj = tmp(&format!("{stem}-{}{level}{tag}.o", self.name));
        let out = Command::new(self.cc)
            .args(self.flags)
            .args(["-ffreestanding", "-c", level, "-I"])
            .arg(corpus("include"))
            .args(extra)
            .arg(src)
            .arg("-o")
            .arg(&obj)
            .output()
            .map_err(|e| e.to_string())?;
        if out.status.success() {
            Ok(obj)
        } else {
            Err(String::from_utf8_lossy(&out.stderr).into_owned())
        }
    }

    fn compile(&self, src: &Path, level: &str, extra: &[&str]) -> PathBuf {
        self.try_compile(src, level, extra)
            .unwrap_or_else(|e| panic!("{} failed: {e}", self.cc))
    }

    /// Is the compiler installed and able to generate code for this target?
    fn available(&self) -> bool {
        let ok = self.try_compile(&corpus("float.c"), "-Os", &["-DCVERIF_PROBE"]).is_ok();
        if !ok {
            eprintln!("skipping: {} cannot build for {}", self.cc, self.name);
        }
        ok
    }

    /// Every function of the float corpus is proved, at every level.
    fn expect_proved(&self) {
        if !self.available() {
            return;
        }
        let src = corpus("float.c");
        for level in ALL_LEVELS {
            let r = check_obj(&self.compile(&src, level, &[]), &src);
            let ctx = format!("float.c {} {level}", self.name);
            assert!(r.funcs.len() > 100, "{ctx}: only {} functions verified", r.funcs.len());
            assert!(
                r.funcs.iter().all(|f| f.status == Status::Proved),
                "{ctx}: unexpected results\n{}",
                describe(&r)
            );
            assert!(r.data_issues.is_empty(), "{ctx}:\n{}", describe(&r));
        }
    }

    /// Every mutant is reported as a mismatch (never merely left unproved), in the function it
    /// changes and nowhere else.
    fn expect_mutants_rejected(&self) {
        if !self.available() {
            return;
        }
        let src = corpus("mutants_f.c");
        for level in ALL_LEVELS {
            let r = check_obj(&self.compile(&src, level, &[]), &src);
            assert!(
                r.funcs.iter().all(|f| f.status == Status::Proved) && r.data_issues.is_empty(),
                "mutants_f.c {} {level}: the original is not proved\n{}",
                self.name,
                describe(&r)
            );
            for &(n, func) in MUTANTS {
                let r = check_obj(&self.compile(&src, level, &[&format!("-DMUTANT={n}")]), &src);
                let ctx = format!("mutants_f.c mutant {n} ({func}) with {} at {level}", self.name);
                assert!(r.has_mismatch(), "{ctx} was not detected\n{}", describe(&r));
                for f in &r.funcs {
                    if f.name == func {
                        let data = !r.data_issues.is_empty();
                        assert!(matches!(f.status, Status::Mismatch(_)) || data, "{ctx}: {:?}", f.status);
                    } else {
                        assert_eq!(f.status, Status::Proved, "{ctx}: {} should be unaffected", f.name);
                    }
                }
            }
        }
    }

    /// With `-ffast-math` the compiler assumes there are no NaNs or signed zeros and replaces
    /// division by multiplication with a rounded reciprocal: the code no longer implements the
    /// source, and the affected functions must not be proved.
    fn expect_fast_math_rejected(&self) {
        if !self.available() {
            return;
        }
        let src = corpus("float.c");
        for level in ["-O2", "-Os"] {
            let r = check_obj(&self.compile(&src, level, &["-ffast-math"]), &src);
            let ctx = format!("float.c {} {level} -ffast-math", self.name);
            for name in ["f_isnan", "f_tenth", "f_not_lt", "f_abs", "f_ordered"] {
                let f = r.funcs.iter().find(|f| f.name == name).unwrap();
                assert!(
                    matches!(f.status, Status::Mismatch(_)),
                    "{ctx}: {name} is {:?}",
                    f.status
                );
            }
            // Code that fast-math leaves alone is still proved.
            for name in ["f_add", "d_mul", "f_lt", "i_to_f", "d_to_i", "f_bits", "call_mixed"] {
                let f = r.funcs.iter().find(|f| f.name == name).unwrap();
                assert_eq!(f.status, Status::Proved, "{ctx}: {name}");
            }
        }
    }
}

#[test]
fn float_gcc_m3() {
    GCC_M3.expect_proved();
}

#[test]
fn float_gcc_m0() {
    GCC_M0.expect_proved();
}

#[test]
fn float_gcc_m35p() {
    GCC_M35P.expect_proved();
}

#[test]
fn float_clang_m0plus_ropi() {
    CLANG_M0PLUS_ROPI.expect_proved();
}

#[test]
fn float_clang_m3_rwpi() {
    CLANG_M3_RWPI.expect_proved();
}

#[test]
fn float_clang_m35p_rwpi() {
    CLANG_M35P_RWPI.expect_proved();
}

#[test]
fn float_mutants_are_rejected_gcc() {
    for t in [GCC_M3, GCC_M0, GCC_M35P] {
        t.expect_mutants_rejected();
    }
}

#[test]
fn float_mutants_are_rejected_clang() {
    for t in [CLANG_M0PLUS_ROPI, CLANG_M3_RWPI, CLANG_M35P_RWPI] {
        t.expect_mutants_rejected();
    }
}

#[test]
fn fast_math_is_not_proved() {
    GCC_M3.expect_fast_math_rejected();
    CLANG_M3_RWPI.expect_fast_math_rejected();
}

/// The hard-float calling convention is not modelled: functions that pass floating-point
/// values are reported as unsupported, never as proved or as differing.
#[test]
fn hard_float_is_unsupported() {
    if !GCC_M4F.available() {
        return;
    }
    let src = corpus("float.c");
    for level in ["-O0", "-O2"] {
        let r = check_obj(&GCC_M4F.compile(&src, level, &[]), &src);
        assert!(!r.has_mismatch(), "{level}:\n{}", describe(&r));
        for f in &r.funcs {
            match f.name.as_str() {
                // No floating-point value crosses the interface or is computed at run time.
                "f_fold" => assert_eq!(f.status, Status::Proved, "{level}"),
                "f_add" | "d_mul" | "f_lt" | "f_select" | "f_round_trip" | "vec_len2" | "call_sink" => {
                    assert!(
                        matches!(f.status, Status::Unsupported(_)),
                        "{level}: {} is {:?}",
                        f.name,
                        f.status
                    )
                }
                _ => assert!(!matches!(f.status, Status::Mismatch(_)), "{level}: {}", f.name),
            }
        }
    }
}