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 👇

13.7 KB
Raw Blame
// ©AngelaMos | 2026
// compile.rs

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

use lisdex_core::process::CommandSpec;

pub const CC: &str = "afl-clang-lto";
pub const CC_PCGUARD: &str = "afl-clang-fast";
pub const WHOLE_ARCHIVE: &str = "-Wl,--whole-archive";
pub const NO_WHOLE_ARCHIVE: &str = "-Wl,--no-whole-archive";
pub const START_GROUP: &str = "-Wl,--start-group";
pub const END_GROUP: &str = "-Wl,--end-group";
pub const SHOWMAP: &str = "afl-showmap";
pub const DEFAULT_DRIVER: &str = "/usr/local/lib/afl/libAFLDriver.a";
pub const ASAN_OPTIONS: &str = "ASAN_OPTIONS";
// In-process symbolization of one report costs upwards of twelve seconds, and the oracle
// only needs the exit status, never the frames.
pub const ASAN_OPTIONS_VALUE: &str = "symbolize=0:detect_leaks=0";
pub const ASAN_OPTIONS_LEAKS: &str = "symbolize=0:detect_leaks=1";
pub const SHOWMAP_TIMEOUT_MS: u64 = 5000;
pub const TARGET_MODE_KEY: &str = "target_mode";
pub const REQUIRED_TARGET_MODES: &[&str] = &["persistent", "shmem_testcase", "deferred"];

// B80. Which compiler builds the bench harness, and where the library sits on the link line.
// Both are decided by the archive, and neither is a preference.
//
// PCGUARD assigns edge IDs at startup by walking the concatenated `__sancov_guards` sections,
// so whichever object the linker placed FIRST owns the low IDs and everything after it shifts
// when that object changes size. `Lto` is the shape that has always shipped: `afl-clang-lto`
// instruments the whole merged module at link time, and nothing about the argument order
// changes that. `PcGuard` puts the library's guards in front of the harness's, which is the
// only arrangement in which appending a call to the harness leaves the library's numbering
// alone. `--whole-archive` rather than a `--start-group` that merely lists the archive first:
// a group re-scan still places each member where it was PULLED IN, which is after the harness,
// and measured 0 of 16 for exactly that reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LinkScheme {
    #[default]
    Lto,
    PcGuard,
}

impl LinkScheme {
    #[must_use]
    pub fn compiler(self) -> &'static str {
        match self {
            LinkScheme::Lto => CC,
            LinkScheme::PcGuard => CC_PCGUARD,
        }
    }

    #[must_use]
    pub fn library_leads(self) -> bool {
        self == LinkScheme::PcGuard
    }
}

#[derive(Debug, Clone)]
pub struct BuildSpec {
    pub source: PathBuf,
    pub output: PathBuf,
    pub includes: Vec<PathBuf>,
    pub defines: Vec<String>,
    pub cflags: Vec<String>,
    pub archives: Vec<PathBuf>,
    pub link_args: Vec<String>,
    pub driver: PathBuf,
    pub cmplog: bool,
    pub scheme: LinkScheme,
}

impl BuildSpec {
    #[must_use]
    pub fn new(source: impl Into<PathBuf>, output: impl Into<PathBuf>) -> Self {
        Self {
            source: source.into(),
            output: output.into(),
            includes: Vec::new(),
            defines: Vec::new(),
            cflags: Vec::new(),
            archives: Vec::new(),
            link_args: Vec::new(),
            driver: PathBuf::from(DEFAULT_DRIVER),
            cmplog: false,
            scheme: LinkScheme::default(),
        }
    }
}

#[must_use]
pub fn build_command(spec: &BuildSpec) -> CommandSpec {
    let mut command = CommandSpec::new(spec.scheme.compiler())
        .env("AFL_USE_ASAN", "1")
        .env("AFL_USE_UBSAN", "1")
        .env("AFL_QUIET", "1");
    if spec.cmplog {
        command = command.env("AFL_LLVM_CMPLOG", "1");
    }
    for flag in &spec.cflags {
        command = command.arg(flag);
    }
    for define in &spec.defines {
        command = command.arg(format!("-D{define}"));
    }
    for include in &spec.includes {
        command = command.arg(format!("-I{}", include.display()));
    }
    if spec.scheme.library_leads() && !spec.archives.is_empty() {
        command = command.arg(WHOLE_ARCHIVE);
        for archive in &spec.archives {
            command = command.path_arg(archive);
        }
        command = command.arg(NO_WHOLE_ARCHIVE);
    }
    command = command
        .path_arg(&spec.source)
        .arg("-o")
        .path_arg(&spec.output);
    if !spec.scheme.library_leads() && !spec.archives.is_empty() {
        command = command.arg(START_GROUP);
        for archive in &spec.archives {
            command = command.path_arg(archive);
        }
        command = command.arg(END_GROUP);
    }
    command = command.path_arg(&spec.driver);
    for link in &spec.link_args {
        command = command.arg(link);
    }
    command
}

#[must_use]
pub fn showmap_command(binary: &Path, seed: &Path, map: &Path) -> CommandSpec {
    CommandSpec::new(SHOWMAP)
        .env(ASAN_OPTIONS, ASAN_OPTIONS_VALUE)
        .arg("-o")
        .path_arg(map)
        .arg("-t")
        .arg(SHOWMAP_TIMEOUT_MS.to_string())
        .arg("--")
        .path_arg(binary)
        .path_arg(seed)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LeakCheck {
    Enforce,
    Ignore,
}

#[must_use]
pub fn exercise_command(binary: &Path, seed: &Path, leaks: LeakCheck) -> CommandSpec {
    let command = CommandSpec::new(binary.display().to_string());
    let command = match leaks {
        LeakCheck::Enforce => command.env(ASAN_OPTIONS, ASAN_OPTIONS_LEAKS),
        LeakCheck::Ignore => command.env(ASAN_OPTIONS, ASAN_OPTIONS_VALUE),
    };
    command.path_arg(seed)
}

#[must_use]
pub fn drives_persistent_mode(fuzzer_stats: &str) -> bool {
    fuzzer_stats
        .lines()
        .filter_map(|line| line.split_once(':'))
        .any(|(key, value)| {
            key.trim() == TARGET_MODE_KEY
                && REQUIRED_TARGET_MODES
                    .iter()
                    .all(|mode| value.split_whitespace().any(|token| token == *mode))
        })
}

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

    fn spec() -> BuildSpec {
        let mut spec = BuildSpec::new("/w/h.c", "/w/h.bin");
        spec.includes.push(PathBuf::from("/src"));
        spec.archives.push(PathBuf::from("/out/libpng16.a"));
        spec.link_args.push("-lz".to_owned());
        spec
    }

    #[test]
    fn the_sanitizers_are_set_in_the_environment_not_only_as_flags() {
        let command = build_command(&spec());
        assert_eq!(command.env_value("AFL_USE_ASAN"), Some("1"));
        assert_eq!(command.env_value("AFL_USE_UBSAN"), Some("1"));
    }

    #[test]
    fn cmplog_is_off_unless_asked_for() {
        assert!(!build_command(&spec()).has_env("AFL_LLVM_CMPLOG"));
    }

    #[test]
    fn cmplog_is_an_environment_switch() {
        let mut cmplog = spec();
        cmplog.cmplog = true;
        assert_eq!(
            build_command(&cmplog).env_value("AFL_LLVM_CMPLOG"),
            Some("1")
        );
    }

    #[test]
    fn the_driver_is_linked_after_the_library_archives() {
        let line = build_command(&spec()).command_line();
        let archive = line.find("libpng16.a").expect("archive on the line");
        let driver = line.find("libAFLDriver.a").expect("driver on the line");
        assert!(archive < driver);
    }

    #[test]
    fn link_arguments_come_last() {
        let line = build_command(&spec()).command_line();
        let driver = line.find("libAFLDriver.a").expect("driver on the line");
        let lz = line.find("-lz").expect("link arg on the line");
        assert!(driver < lz);
    }

    #[test]
    fn includes_and_defines_are_prefixed() {
        let mut spec = spec();
        spec.defines.push("MAGMA_ENABLE_CANARIES".to_owned());
        let line = build_command(&spec).command_line();
        assert!(line.contains("-I/src"));
        assert!(line.contains("-DMAGMA_ENABLE_CANARIES"));
    }

    #[test]
    fn the_compiler_is_the_lto_driver() {
        assert_eq!(build_command(&spec()).program, CC);
    }

    // B80's remaining half. Against a PCGUARD archive the harness has to be compiled by the
    // matching driver, because `afl-clang-lto` numbers its own blocks at link time and PCGUARD
    // bases the library's runtime numbering after that count.
    #[test]
    fn a_pcguard_archive_is_matched_by_the_pcguard_driver() {
        let mut spec = spec();
        spec.scheme = LinkScheme::PcGuard;
        assert_eq!(build_command(&spec).program, CC_PCGUARD);
    }

    // The ordering half, and it is the one the toy lab hid. Measured on libpng's real emitted
    // climb: the library ahead of the harness contains the parent's map in 16 of 16, and the
    // shipped order in 0 of 16 even with both sides on PCGUARD.
    #[test]
    fn a_pcguard_link_puts_the_library_ahead_of_the_harness() {
        let mut spec = spec();
        spec.scheme = LinkScheme::PcGuard;
        let line = build_command(&spec).command_line();
        let archive = line.find("libpng16.a").expect("archive on the line");
        let source = line.find("h.c").expect("source on the line");
        assert!(
            archive < source,
            "the library's guards must be numbered before the harness's: {line}"
        );
        assert!(line.contains(WHOLE_ARCHIVE));
        assert!(line.contains(NO_WHOLE_ARCHIVE));
    }

    // `--whole-archive` is what forces the placement; a `--start-group` listing the archive
    // first still places each member where it was pulled in, which is after the harness.
    #[test]
    fn a_pcguard_link_does_not_fall_back_to_a_group_that_would_not_reorder() {
        let mut spec = spec();
        spec.scheme = LinkScheme::PcGuard;
        let line = build_command(&spec).command_line();
        assert!(!line.contains(START_GROUP));
    }

    // The default is unchanged, and stays unchanged: an LTO archive is re-instrumented at every
    // link, so reordering it buys nothing and `--whole-archive` would only inflate the binary.
    #[test]
    fn the_lto_link_keeps_the_harness_first_and_the_archive_in_a_group() {
        let line = build_command(&spec()).command_line();
        let archive = line.find("libpng16.a").expect("archive on the line");
        let source = line.find("h.c").expect("source on the line");
        assert!(source < archive);
        assert!(line.contains(START_GROUP));
        assert!(!line.contains(WHOLE_ARCHIVE));
    }

    // The driver defines main and is not the thing being measured, so it stays last under both
    // schemes - ahead of it the library, behind it the caller's own link arguments.
    #[test]
    fn the_driver_still_follows_the_library_under_the_pcguard_scheme() {
        let mut spec = spec();
        spec.scheme = LinkScheme::PcGuard;
        let line = build_command(&spec).command_line();
        let archive = line.find("libpng16.a").expect("archive on the line");
        let driver = line.find("libAFLDriver.a").expect("driver on the line");
        let lz = line.find("-lz").expect("link arg on the line");
        assert!(archive < driver);
        assert!(driver < lz);
    }

    #[test]
    fn a_scheme_with_no_archives_emits_no_ordering_flags_at_all() {
        let mut spec = BuildSpec::new("/w/h.c", "/w/h.bin");
        spec.scheme = LinkScheme::PcGuard;
        let line = build_command(&spec).command_line();
        assert!(!line.contains(WHOLE_ARCHIVE));
        assert!(!line.contains(START_GROUP));
    }

    #[test]
    fn showmap_bounds_the_execution_and_silences_leak_detection() {
        let command = showmap_command(
            Path::new("/w/h.bin"),
            Path::new("/seeds/a.png"),
            Path::new("/tmp/map"),
        );
        let line = command.command_line();
        assert!(line.contains("-t 5000"));
        assert!(line.contains("-- /w/h.bin /seeds/a.png"));
        assert_eq!(command.env_value(ASAN_OPTIONS), Some(ASAN_OPTIONS_VALUE));
    }

    #[test]
    fn a_direct_exercise_runs_the_binary_on_the_seed() {
        let command = exercise_command(
            Path::new("/w/h.bin"),
            Path::new("/seeds/a.png"),
            LeakCheck::Enforce,
        );
        assert_eq!(command.program, "/w/h.bin");
        assert_eq!(command.command_line(), "/w/h.bin /seeds/a.png");
    }

    #[test]
    fn the_leak_gate_turns_leak_detection_on() {
        let command = exercise_command(
            Path::new("/w/h.bin"),
            Path::new("/seeds/a.png"),
            LeakCheck::Enforce,
        );
        assert_eq!(
            command.env_value(ASAN_OPTIONS),
            Some("symbolize=0:detect_leaks=1")
        );
    }

    #[test]
    fn every_oracle_path_disables_in_process_symbolization() {
        // Symbolizing one report cost twelve seconds of CPU, so a single crashing
        // candidate burned four minutes across the corpus before the timeout fired.
        for options in [ASAN_OPTIONS_VALUE, ASAN_OPTIONS_LEAKS] {
            assert!(
                options.contains("symbolize=0"),
                "{options} must disable symbolization"
            );
        }
        assert_eq!(
            showmap_command(
                Path::new("/w/h.bin"),
                Path::new("/seeds/a.png"),
                Path::new("/tmp/map")
            )
            .env_value(ASAN_OPTIONS),
            Some("symbolize=0:detect_leaks=0")
        );
    }

    #[test]
    fn a_campaign_run_leaves_leak_detection_off() {
        let command = exercise_command(
            Path::new("/w/h.bin"),
            Path::new("/seeds/a.png"),
            LeakCheck::Ignore,
        );
        assert_eq!(command.env_value(ASAN_OPTIONS), Some(ASAN_OPTIONS_VALUE));
    }

    #[test]
    fn persistent_mode_is_recognised_from_fuzzer_stats() {
        let stats = "execs_done : 12\ntarget_mode : persistent shmem_testcase deferred\n";
        assert!(drives_persistent_mode(stats));
    }

    #[test]
    fn a_shadowed_main_is_caught_by_the_target_mode_check() {
        let stats = "execs_done : 12\ntarget_mode : shmem_testcase default\n";
        assert!(!drives_persistent_mode(stats));
    }

    #[test]
    fn a_missing_target_mode_line_is_not_persistent() {
        assert!(!drives_persistent_mode("execs_done : 12\n"));
    }
}