Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

19.6 KB
Raw Blame
// ©AngelaMos | 2026
// verify.rs

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::time::Duration;

use lisdex_core::process::{self, CommandSpec};

use crate::instrument::{LLVM_NM, SanitizerSet};

pub const NM_TIMEOUT_SECS: u64 = 120;

const PATTERN_ASAN: &str = "__asan_";
const PATTERN_UBSAN: &str = "__ubsan_";
const PATTERN_MSAN: &str = "__msan_";
const PATTERN_AFL: &str = "__afl_";
const PATTERN_COVERAGE: &str = "__sanitizer_cov";
const PATTERN_CMPLOG: &str = "__cmplog";
const PATTERN_MAGMA: &str = "magma_log";
const MEMBER_HEADER_SUFFIX: char = ':';

const ARG_NO_SORT: &str = "--no-sort";
const ARG_DEFINED_ONLY: &str = "--defined-only";
const TEXT_SYMBOL_TYPES: [&str; 2] = ["T", "W"];
const SYMBOL_FIELDS: usize = 2;

#[derive(Debug, thiserror::Error)]
pub enum VerifyError {
    #[error("process error: {0}")]
    Process(#[from] process::ProcessError),
    #[error("{nm} could not read {path}: {output}")]
    Unreadable {
        nm: String,
        path: PathBuf,
        output: String,
    },
    #[error(
        "{nm} output for {path} exceeded the {captured}-byte capture limit, so an unknown number of symbols were never read; a count taken from a partial listing can report an instrumented build as bare, or a benchmark build as field"
    )]
    Truncated {
        nm: String,
        path: PathBuf,
        captured: usize,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SymbolCounts {
    pub asan: usize,
    pub ubsan: usize,
    pub msan: usize,
    pub afl: usize,
    pub cmplog: usize,
    pub magma: usize,
}

impl SymbolCounts {
    #[must_use]
    pub fn merge(self, other: SymbolCounts) -> SymbolCounts {
        SymbolCounts {
            asan: self.asan + other.asan,
            ubsan: self.ubsan + other.ubsan,
            msan: self.msan + other.msan,
            afl: self.afl + other.afl,
            cmplog: self.cmplog + other.cmplog,
            magma: self.magma + other.magma,
        }
    }

    #[must_use]
    pub fn is_empty(self) -> bool {
        self == SymbolCounts::default()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Requirements {
    pub sanitizers: SanitizerSet,
    pub min_asan: usize,
    pub min_ubsan: usize,
    pub min_msan: usize,
    pub min_coverage: usize,
    pub min_cmplog: usize,
    pub min_magma: usize,
}

impl Default for Requirements {
    fn default() -> Self {
        Self {
            sanitizers: SanitizerSet::AddressUndefined,
            min_asan: 1,
            min_ubsan: 0,
            min_msan: 0,
            min_coverage: 1,
            min_cmplog: 0,
            min_magma: 0,
        }
    }
}

impl Requirements {
    #[must_use]
    pub fn library() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn for_sanitizers(sanitizers: SanitizerSet) -> Self {
        match sanitizers {
            SanitizerSet::AddressUndefined => Self::default(),
            SanitizerSet::Memory => Self {
                sanitizers,
                min_asan: 0,
                min_msan: 1,
                ..Self::default()
            },
            SanitizerSet::Off => Self {
                sanitizers,
                min_asan: 0,
                min_ubsan: 0,
                min_msan: 0,
                min_coverage: 0,
                ..Self::default()
            },
        }
    }

    #[must_use]
    pub fn with_cmplog(mut self, required: bool) -> Self {
        self.min_cmplog = usize::from(required);
        self
    }

    #[must_use]
    pub fn with_magma_canaries(mut self, required: bool) -> Self {
        self.min_magma = usize::from(required);
        self
    }

    #[must_use]
    pub fn shortfalls(&self, counts: SymbolCounts, lto_bitcode: bool) -> Vec<String> {
        let coverage_required = if lto_bitcode { 0 } else { self.min_coverage };
        let checks = [
            ("address sanitizer", counts.asan, self.min_asan),
            ("undefined sanitizer", counts.ubsan, self.min_ubsan),
            ("memory sanitizer", counts.msan, self.min_msan),
            (
                "afl coverage",
                counts.afl + counts.cmplog,
                coverage_required,
            ),
            ("cmplog", counts.cmplog, self.min_cmplog),
            ("magma canary", counts.magma, self.min_magma),
        ];
        checks
            .into_iter()
            .filter(|(_, found, required)| found < required)
            .map(|(what, found, required)| {
                format!("{what} symbols: found {found}, need at least {required}")
            })
            .collect()
    }
}

pub fn count_symbol_line(counts: &mut SymbolCounts, line: &str) {
    let trimmed = line.trim_end();
    if trimmed.ends_with(MEMBER_HEADER_SUFFIX) {
        return;
    }
    let Some(symbol) = trimmed.split_whitespace().last() else {
        return;
    };
    if symbol.contains(PATTERN_ASAN) {
        counts.asan += 1;
    }
    if symbol.contains(PATTERN_UBSAN) {
        counts.ubsan += 1;
    }
    if symbol.contains(PATTERN_MSAN) {
        counts.msan += 1;
    }
    if symbol.contains(PATTERN_AFL) || symbol.contains(PATTERN_COVERAGE) {
        counts.afl += 1;
    }
    if symbol.contains(PATTERN_CMPLOG) {
        counts.cmplog += 1;
    }
    if symbol.contains(PATTERN_MAGMA) {
        counts.magma += 1;
    }
}

#[must_use]
pub fn scan_symbols(text: &str) -> SymbolCounts {
    let mut counts = SymbolCounts::default();
    for line in text.lines() {
        count_symbol_line(&mut counts, line);
    }
    counts
}

#[must_use]
pub fn nm_spec(path: &Path) -> CommandSpec {
    CommandSpec::new(LLVM_NM).arg(ARG_NO_SORT).path_arg(path)
}

pub fn scan_listing(
    path: &Path,
    succeeded: bool,
    truncated: bool,
    output: &str,
    tail: &str,
) -> Result<SymbolCounts, VerifyError> {
    if !succeeded {
        return Err(VerifyError::Unreadable {
            nm: LLVM_NM.to_owned(),
            path: path.to_path_buf(),
            output: tail.to_owned(),
        });
    }
    if truncated {
        return Err(VerifyError::Truncated {
            nm: LLVM_NM.to_owned(),
            path: path.to_path_buf(),
            captured: process::MAX_CAPTURED_BYTES,
        });
    }
    Ok(scan_symbols(output))
}

#[must_use]
pub fn defined_spec(path: &Path) -> CommandSpec {
    CommandSpec::new(LLVM_NM)
        .arg(ARG_NO_SORT)
        .arg(ARG_DEFINED_ONLY)
        .path_arg(path)
}

#[must_use]
pub fn scan_defined_functions(text: &str) -> BTreeSet<String> {
    let mut found = BTreeSet::new();
    for line in text.lines() {
        let trimmed = line.trim_end();
        if trimmed.ends_with(MEMBER_HEADER_SUFFIX) {
            continue;
        }
        let fields: Vec<&str> = trimmed.split_whitespace().collect();
        if fields.len() < SYMBOL_FIELDS {
            continue;
        }
        let kind = fields[fields.len() - SYMBOL_FIELDS];
        let name = fields[fields.len() - 1];
        if TEXT_SYMBOL_TYPES.contains(&kind) {
            found.insert(name.to_owned());
        }
    }
    found
}

pub fn collect_defined_line(found: &mut BTreeSet<String>, line: &str) {
    let trimmed = line.trim_end();
    if trimmed.ends_with(MEMBER_HEADER_SUFFIX) {
        return;
    }
    let fields: Vec<&str> = trimmed.split_whitespace().collect();
    if fields.len() < SYMBOL_FIELDS {
        return;
    }
    let kind = fields[fields.len() - SYMBOL_FIELDS];
    let name = fields[fields.len() - 1];
    if TEXT_SYMBOL_TYPES.contains(&kind) {
        found.insert(name.to_owned());
    }
}

pub fn defined_functions(path: &Path) -> Result<BTreeSet<String>, VerifyError> {
    let (execution, found) = process::run_folding(
        &defined_spec(path),
        Duration::from_secs(NM_TIMEOUT_SECS),
        BTreeSet::new(),
        collect_defined_line,
    )?;
    if !execution.success {
        return Err(VerifyError::Unreadable {
            nm: LLVM_NM.to_owned(),
            path: path.to_path_buf(),
            output: execution.diagnosis(10),
        });
    }
    Ok(found)
}

pub fn inspect(path: &Path) -> Result<SymbolCounts, VerifyError> {
    let (execution, counts) = process::run_folding(
        &nm_spec(path),
        Duration::from_secs(NM_TIMEOUT_SECS),
        SymbolCounts::default(),
        count_symbol_line,
    )?;
    if !execution.success {
        return Err(VerifyError::Unreadable {
            nm: LLVM_NM.to_owned(),
            path: path.to_path_buf(),
            output: execution.diagnosis(10),
        });
    }
    Ok(counts)
}

#[cfg(test)]
mod tests {
    use super::*;

    const NM_INSTRUMENTED: &str = "\
00000000001c6370 t _Z19ubsan_GetStackTracePN11__sanitizer18BufferedStackTraceEmmmPvb
0000000000ea0870 b _ZL13ubsan_init_mu
0000000000185bd0 t _ZL17asan_thread_startPv
---------------- C ___asan_globals_registered
                 U __asan_after_dynamic_init
                 U __asan_report_load4
                 U __ubsan_handle_out_of_bounds
                 U __ubsan_handle_shift_out_of_bounds
                 U __sanitizer_cov_trace_pc_guard
0000000000ea1000 B __afl_area_ptr
                 U magma_log
";

    const NM_PLAIN: &str = "\
0000000000001139 T png_read_info
                 U memcpy
0000000000004010 B png_error_ptr
";

    const NM_CMPLOG: &str = "\
                 U __cmplog_ins_hook4
                 U __cmplog_rtn_hook
                 U __sanitizer_cov_trace_pc_guard
                 U __asan_report_load1
                 U __ubsan_handle_out_of_bounds
";

    const NM_ARCHIVE: &str = "\
libpng16.a[png.o]:
                 U __asan_report_load4
                 U __ubsan_handle_shift_out_of_bounds
0000000000000000 T png_get_io_ptr
libpng16.a[pngread.o]:
                 U __afl_area_ptr
";

    const NM_DEFINED: &str = "\
adler32.c.o:
---------------- T adler32_z
                 U __ubsan_handle_type_mismatch_v1_abort
---------------- T adler32
---------------- t asan.module_ctor
---------------- d __unnamed_1
0000000000000000 W inflateResetKeep
0000000000000000 D z_errmsg
";

    const NM_RUNTIME_INTERNALS: &str = "\
00000000001c6370 t _Z19ubsan_GetStackTracePN11__sanitizer18BufferedStackTraceEmmmPvb
0000000000ea0870 b _ZL13ubsan_init_mu
0000000000185bd0 t _ZL17asan_thread_startPv
0000000000001139 T asan_helper
";

    const NM_FILENAME_ONLY: &str = "\
magma_log.o:
0000000000000000 T nothing_instrumented
asan_shim.o:
0000000000000000 T also_nothing
";

    #[test]
    fn an_instrumented_binary_reports_every_family() {
        let counts = scan_symbols(NM_INSTRUMENTED);
        assert!(counts.asan >= 3);
        assert!(counts.ubsan >= 1);
        assert!(counts.afl >= 2);
        assert_eq!(counts.magma, 1);
        assert_eq!(counts.cmplog, 0);
    }

    #[test]
    fn object_file_names_are_never_counted_as_instrumentation() {
        let counts = scan_symbols(NM_FILENAME_ONLY);
        assert!(
            counts.is_empty(),
            "a translation unit named magma_log.c must not satisfy --require-canaries: {counts:?}"
        );
        assert!(
            Requirements::library()
                .with_magma_canaries(true)
                .shortfalls(counts, false)
                .len()
                >= 2
        );
    }

    #[test]
    fn sanitizer_runtime_internals_are_not_evidence_that_project_code_is_instrumented() {
        let counts = scan_symbols(NM_RUNTIME_INTERNALS);
        assert!(
            counts.is_empty(),
            "only the __asan_/__ubsan_/__msan_ interface symbols count: {counts:?}"
        );
    }

    #[test]
    fn a_plain_build_reports_nothing() {
        let counts = scan_symbols(NM_PLAIN);
        assert!(counts.is_empty());
    }

    #[test]
    fn ubsan_symbols_are_not_miscounted_as_asan() {
        let counts = scan_symbols("                 U __ubsan_handle_add_overflow\n");
        assert_eq!(counts.ubsan, 1);
        assert_eq!(counts.asan, 0);
    }

    #[test]
    fn cmplog_symbols_are_counted_separately_and_also_prove_coverage() {
        let counts = scan_symbols(NM_CMPLOG);
        assert_eq!(counts.cmplog, 2);
        assert!(counts.afl >= 1);
    }

    #[test]
    fn archive_member_headers_do_not_become_symbols() {
        let counts = scan_symbols(NM_ARCHIVE);
        assert_eq!(counts.asan, 1);
        assert_eq!(counts.ubsan, 1);
        assert_eq!(counts.afl, 1);
    }

    #[test]
    fn only_globally_defined_text_symbols_count_as_library_functions() {
        let defined = scan_defined_functions(NM_DEFINED);
        assert!(defined.contains("adler32"));
        assert!(defined.contains("adler32_z"));
        assert!(
            defined.contains("inflateResetKeep"),
            "a weak text symbol is still a definition the linker resolves"
        );
        assert!(
            !defined.contains("asan.module_ctor"),
            "a lowercase t is file-local: static helpers are not the library's surface"
        );
        assert!(
            !defined.contains("__ubsan_handle_type_mismatch_v1_abort"),
            "an undefined symbol is imported, not defined here"
        );
        assert!(
            !defined.contains("z_errmsg"),
            "D is data, not a callable entry point"
        );
        assert!(!defined.contains("__unnamed_1"));
    }

    #[test]
    fn an_archive_member_header_is_never_read_as_a_defined_function() {
        let defined = scan_defined_functions(NM_ARCHIVE);
        assert_eq!(defined, ["png_get_io_ptr".to_owned()].into_iter().collect());
    }

    #[test]
    fn empty_output_is_empty_counts() {
        assert!(scan_symbols("").is_empty());
    }

    #[test]
    fn counts_merge_across_artifacts() {
        let merged = scan_symbols(NM_ARCHIVE).merge(scan_symbols(NM_CMPLOG));
        assert_eq!(merged.asan, 2);
        assert_eq!(merged.cmplog, 2);
    }

    #[test]
    fn an_uninstrumented_library_fails_the_requirements_loudly() {
        let shortfalls = Requirements::library().shortfalls(scan_symbols(NM_PLAIN), false);
        assert_eq!(shortfalls.len(), 2);
        assert!(shortfalls.iter().any(|line| line.contains("address")));
        assert!(shortfalls.iter().any(|line| line.contains("afl coverage")));
    }

    #[test]
    fn a_library_without_undefined_behaviour_checks_is_still_accepted() {
        let counts = scan_symbols(
            "libtiny.a[tiny.o]:\n                 U __asan_report_load4\n                 U __afl_area_ptr\n",
        );
        assert_eq!(counts.ubsan, 0);
        assert!(
            Requirements::library().shortfalls(counts, false).is_empty(),
            "a translation unit with no UB-checkable operation emits no __ubsan_ references"
        );
    }

    #[test]
    fn an_instrumented_library_satisfies_the_requirements() {
        assert!(
            Requirements::library()
                .shortfalls(scan_symbols(NM_ARCHIVE), false)
                .is_empty()
        );
    }

    #[test]
    fn a_cmplog_build_missing_cmplog_instrumentation_is_rejected() {
        let shortfalls = Requirements::library()
            .with_cmplog(true)
            .shortfalls(scan_symbols(NM_ARCHIVE), false);
        assert_eq!(shortfalls.len(), 1);
        assert!(shortfalls[0].contains("cmplog"));
    }

    #[test]
    fn a_truncated_listing_is_refused_rather_than_counted() {
        let magma_listing = "                 U magma_log\n";
        let path = Path::new("/out/harness");

        assert_eq!(
            scan_listing(path, true, false, magma_listing, "")
                .unwrap()
                .magma,
            1,
            "the fixture must isolate the signal: a complete listing of these bytes DOES count a canary"
        );

        assert!(
            matches!(
                scan_listing(path, true, true, magma_listing, ""),
                Err(VerifyError::Truncated { .. })
            ),
            "the same bytes cut short must refuse instead. B94's benchmark-tree detection is `counts.magma > 0` over this listing, so a partial read that happens to miss the canary silently marks a benchmark tree as field and makes its findings disclosable. Measured headroom on the real magma target is 355,611 of 524,288 bytes - it fits today, and a bigger target does not."
        );
    }

    #[test]
    fn a_failed_listing_is_refused_before_truncation_is_considered() {
        assert!(
            matches!(
                scan_listing(Path::new("/out/x"), false, true, "", "no such file"),
                Err(VerifyError::Unreadable { .. })
            ),
            "a command that failed outright is unreadable, not truncated, and the message has to name the real cause"
        );
    }

    #[test]
    fn a_memory_sanitizer_build_does_not_demand_address_symbols() {
        let requirements = Requirements::for_sanitizers(SanitizerSet::Memory);
        let counts =
            scan_symbols("                 U __msan_warning\n                 U __afl_area_ptr\n");
        assert!(requirements.shortfalls(counts, false).is_empty());
    }

    #[test]
    fn magma_canaries_can_be_demanded_for_benchmark_targets() {
        let shortfalls = Requirements::library()
            .with_magma_canaries(true)
            .shortfalls(scan_symbols(NM_ARCHIVE), false);
        assert_eq!(shortfalls.len(), 1);
        assert!(shortfalls[0].contains("magma"));
    }

    #[test]
    fn an_lto_archive_satisfies_coverage_because_instrumentation_lands_at_link_time() {
        let lto_only = scan_symbols(
            "libtiff.a[tif_error.o]:\n                 U __asan_report_load4\n                 U __ubsan_handle_shift_out_of_bounds\n",
        );
        assert_eq!(lto_only.afl, 0);
        assert!(
            !Requirements::library()
                .shortfalls(lto_only, false)
                .is_empty()
        );
        assert!(
            Requirements::library()
                .shortfalls(lto_only, true)
                .is_empty(),
            "afl-clang-lto emits bitcode archives; coverage symbols only exist after the link"
        );
    }

    #[test]
    fn an_lto_archive_still_has_to_carry_sanitizer_instrumentation() {
        let shortfalls = Requirements::library().shortfalls(scan_symbols(NM_PLAIN), true);
        assert_eq!(shortfalls.len(), 1);
        assert!(shortfalls.iter().any(|line| line.contains("address")));
        assert!(!shortfalls.iter().any(|line| line.contains("coverage")));
    }

    #[test]
    fn cmplog_is_never_waived_by_bitcode_because_it_is_a_compile_time_pass() {
        let counts = scan_symbols(NM_ARCHIVE);
        assert_eq!(counts.cmplog, 0);
        let shortfalls = Requirements::library()
            .with_cmplog(true)
            .shortfalls(counts, true);
        assert_eq!(
            shortfalls.len(),
            1,
            "afl-cc loads cmplog through -fpass-plugin, so the symbols are in the objects"
        );
        assert!(shortfalls[0].contains("cmplog"));
    }

    #[test]
    fn nm_is_invoked_without_sorting_because_only_counts_matter() {
        let spec = nm_spec(Path::new("/out/libpng16.a"));
        assert_eq!(spec.program, LLVM_NM);
        assert_eq!(spec.args, vec![ARG_NO_SORT, "/out/libpng16.a"]);
    }

    #[test]
    fn inspecting_a_file_that_is_not_an_object_never_reports_instrumentation() {
        let path = lisdex_core::scratch::path("build-verify-nonobject").with_extension("txt");
        std::fs::write(&path, "not an object file").unwrap();
        match inspect(&path) {
            Ok(counts) => panic!("a text file reported symbols: {counts:?}"),
            Err(VerifyError::Unreadable { .. }) => {}
            Err(VerifyError::Truncated { .. }) => {
                panic!("18 bytes cannot exceed the capture limit")
            }
            Err(VerifyError::Process(_)) => {
                assert!(
                    process::run(
                        &CommandSpec::new(LLVM_NM).arg("--version"),
                        Duration::from_secs(10)
                    )
                    .is_err(),
                    "{LLVM_NM} is present, so an unreadable file must be reported as such"
                );
            }
        }
    }
}