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.3 KB
Raw Blame
// ©AngelaMos | 2026
// instrument.rs

pub const AFL_CC: &str = "afl-clang-lto";
pub const AFL_CXX: &str = "afl-clang-lto++";
pub const AFL_CC_PCGUARD: &str = "afl-clang-fast";
pub const AFL_CXX_PCGUARD: &str = "afl-clang-fast++";
pub const PLAIN_CC: &str = "clang";
pub const PLAIN_CXX: &str = "clang++";
pub const LLVM_AR: &str = "llvm-ar";
pub const LLVM_RANLIB: &str = "llvm-ranlib";
pub const LLVM_NM: &str = "llvm-nm";
pub const LLVM_AS: &str = "llvm-as";
pub const LLVM_CONFIG: &str = "llvm-config";

pub const ENV_CC: &str = "CC";
pub const ENV_CXX: &str = "CXX";
pub const ENV_AR: &str = "AR";
pub const ENV_RANLIB: &str = "RANLIB";
pub const ENV_NM: &str = "NM";
pub const ENV_AS: &str = "AS";
pub const ENV_CFLAGS: &str = "CFLAGS";
pub const ENV_CXXFLAGS: &str = "CXXFLAGS";
pub const ENV_LDFLAGS: &str = "LDFLAGS";
pub const ENV_AFL_USE_ASAN: &str = "AFL_USE_ASAN";
pub const ENV_AFL_USE_UBSAN: &str = "AFL_USE_UBSAN";
pub const ENV_AFL_USE_MSAN: &str = "AFL_USE_MSAN";
pub const ENV_AFL_LLVM_CMPLOG: &str = "AFL_LLVM_CMPLOG";
pub const ENV_AFL_QUIET: &str = "AFL_QUIET";
pub const ENV_AFL_NOOPT: &str = "AFL_NOOPT";
pub const ENV_ASAN_OPTIONS: &str = "ASAN_OPTIONS";
pub const ENV_UBSAN_OPTIONS: &str = "UBSAN_OPTIONS";
pub const ENV_ENABLED: &str = "1";

pub const BUILD_TIME_ASAN_OPTIONS: &str = "detect_leaks=0:detect_odr_violation=0";
pub const BUILD_TIME_UBSAN_OPTIONS: &str = "print_stacktrace=0";

pub const DEFAULT_CFLAGS: [&str; 3] = ["-g", "-O2", "-fno-omit-frame-pointer"];

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SanitizerSet {
    #[default]
    AddressUndefined,
    Memory,
    Off,
}

impl SanitizerSet {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            SanitizerSet::AddressUndefined => "address+undefined",
            SanitizerSet::Memory => "memory",
            SanitizerSet::Off => "off",
        }
    }

    #[must_use]
    pub fn envs(self) -> Vec<(String, String)> {
        match self {
            SanitizerSet::AddressUndefined => vec![
                (ENV_AFL_USE_ASAN.to_owned(), ENV_ENABLED.to_owned()),
                (ENV_AFL_USE_UBSAN.to_owned(), ENV_ENABLED.to_owned()),
            ],
            SanitizerSet::Memory => vec![(ENV_AFL_USE_MSAN.to_owned(), ENV_ENABLED.to_owned())],
            SanitizerSet::Off => Vec::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Toolchain {
    pub cc: String,
    pub cxx: String,
    pub ar: String,
    pub ranlib: String,
    pub nm: String,
    pub assembler: String,
}

impl Default for Toolchain {
    fn default() -> Self {
        Self {
            cc: AFL_CC.to_owned(),
            cxx: AFL_CXX.to_owned(),
            ar: LLVM_AR.to_owned(),
            ranlib: LLVM_RANLIB.to_owned(),
            nm: LLVM_NM.to_owned(),
            assembler: LLVM_AS.to_owned(),
        }
    }
}

impl Toolchain {
    #[must_use]
    pub fn plain() -> Self {
        Self {
            cc: PLAIN_CC.to_owned(),
            cxx: PLAIN_CXX.to_owned(),
            ..Self::default()
        }
    }

    // B80. The fuzzing archive is LTO because that is the faster instrumentation, and LTO is
    // also why two harnesses linked against it cannot have their edges compared. PCGUARD bakes
    // a guard array into each object instead, so the library's numbering survives a second
    // link - which is the whole precondition oracles 3b and 4 rest on.
    #[must_use]
    pub fn pcguard() -> Self {
        Self {
            cc: AFL_CC_PCGUARD.to_owned(),
            cxx: AFL_CXX_PCGUARD.to_owned(),
            ..Self::default()
        }
    }

    #[must_use]
    pub fn with_compilers(mut self, cc: impl Into<String>, cxx: impl Into<String>) -> Self {
        self.cc = cc.into();
        self.cxx = cxx.into();
        self
    }

    #[must_use]
    pub fn envs(&self) -> Vec<(String, String)> {
        vec![
            (ENV_CC.to_owned(), self.cc.clone()),
            (ENV_CXX.to_owned(), self.cxx.clone()),
            (ENV_AR.to_owned(), self.ar.clone()),
            (ENV_RANLIB.to_owned(), self.ranlib.clone()),
            (ENV_NM.to_owned(), self.nm.clone()),
            (ENV_AS.to_owned(), self.assembler.clone()),
        ]
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instrumentation {
    pub sanitizers: SanitizerSet,
    pub cmplog: bool,
    pub toolchain: Toolchain,
    pub cflags: Vec<String>,
    pub ldflags: Vec<String>,
}

impl Default for Instrumentation {
    fn default() -> Self {
        Self {
            sanitizers: SanitizerSet::default(),
            cmplog: false,
            toolchain: Toolchain::default(),
            cflags: DEFAULT_CFLAGS
                .iter()
                .map(|flag| (*flag).to_owned())
                .collect(),
            ldflags: Vec::new(),
        }
    }
}

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

    #[must_use]
    pub fn uninstrumented() -> Self {
        Self {
            sanitizers: SanitizerSet::Off,
            cmplog: false,
            toolchain: Toolchain::plain(),
            ..Self::default()
        }
    }

    // The oracle bench's own library build. Same sanitizers and same flags as the fuzzing
    // build - it has to execute the same code - and cmplog is off because it is a fuzzing
    // aid that costs the bench time and buys it nothing.
    #[must_use]
    pub fn oracle_bench() -> Self {
        Self {
            cmplog: false,
            toolchain: Toolchain::pcguard(),
            ..Self::default()
        }
    }

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

    #[must_use]
    pub fn with_sanitizers(mut self, sanitizers: SanitizerSet) -> Self {
        self.sanitizers = sanitizers;
        self
    }

    #[must_use]
    pub fn with_toolchain(mut self, toolchain: Toolchain) -> Self {
        self.toolchain = toolchain;
        self
    }

    #[must_use]
    pub fn with_extra_cflags<I, S>(mut self, flags: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.cflags.extend(flags.into_iter().map(Into::into));
        self
    }

    #[must_use]
    pub fn is_instrumented(&self) -> bool {
        self.sanitizers != SanitizerSet::Off
    }

    #[must_use]
    pub fn cflags_string(&self) -> String {
        self.cflags.join(" ")
    }

    #[must_use]
    pub fn ldflags_string(&self) -> String {
        self.ldflags.join(" ")
    }

    #[must_use]
    pub fn envs(&self) -> Vec<(String, String)> {
        let mut envs = self.toolchain.envs();
        envs.push((ENV_CFLAGS.to_owned(), self.cflags_string()));
        envs.push((ENV_CXXFLAGS.to_owned(), self.cflags_string()));
        envs.push((ENV_LDFLAGS.to_owned(), self.ldflags_string()));
        envs.extend(self.sanitizers.envs());
        if self.cmplog {
            envs.push((ENV_AFL_LLVM_CMPLOG.to_owned(), ENV_ENABLED.to_owned()));
        }
        envs.push((ENV_AFL_QUIET.to_owned(), ENV_ENABLED.to_owned()));
        envs.push((
            ENV_ASAN_OPTIONS.to_owned(),
            BUILD_TIME_ASAN_OPTIONS.to_owned(),
        ));
        envs.push((
            ENV_UBSAN_OPTIONS.to_owned(),
            BUILD_TIME_UBSAN_OPTIONS.to_owned(),
        ));
        envs
    }
}

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

    fn value(envs: &[(String, String)], key: &str) -> Option<String> {
        envs.iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value.clone())
    }

    #[test]
    fn default_instrumentation_uses_the_lto_compiler() {
        let envs = Instrumentation::instrumented().envs();
        assert_eq!(value(&envs, ENV_CC).as_deref(), Some(AFL_CC));
        assert_eq!(value(&envs, ENV_CXX).as_deref(), Some(AFL_CXX));
    }

    #[test]
    fn lto_requires_the_llvm_binutils_drop_ins() {
        let envs = Instrumentation::instrumented().envs();
        assert_eq!(value(&envs, ENV_AR).as_deref(), Some(LLVM_AR));
        assert_eq!(value(&envs, ENV_RANLIB).as_deref(), Some(LLVM_RANLIB));
        assert_eq!(value(&envs, ENV_AS).as_deref(), Some(LLVM_AS));
        assert_eq!(value(&envs, ENV_NM).as_deref(), Some(LLVM_NM));
    }

    #[test]
    fn the_linker_is_left_to_the_compiler_driver() {
        let envs = Instrumentation::instrumented().envs();
        assert!(envs.iter().all(|(key, _)| key != "LD"));
    }

    #[test]
    fn address_and_undefined_share_one_build() {
        let envs = Instrumentation::instrumented().envs();
        assert_eq!(value(&envs, ENV_AFL_USE_ASAN).as_deref(), Some(ENV_ENABLED));
        assert_eq!(
            value(&envs, ENV_AFL_USE_UBSAN).as_deref(),
            Some(ENV_ENABLED)
        );
        assert_eq!(value(&envs, ENV_AFL_USE_MSAN), None);
    }

    #[test]
    fn memory_sanitizer_never_shares_a_build_with_address() {
        let envs = Instrumentation::instrumented()
            .with_sanitizers(SanitizerSet::Memory)
            .envs();
        assert_eq!(value(&envs, ENV_AFL_USE_MSAN).as_deref(), Some(ENV_ENABLED));
        assert_eq!(value(&envs, ENV_AFL_USE_ASAN), None);
        assert_eq!(value(&envs, ENV_AFL_USE_UBSAN), None);
    }

    #[test]
    fn cmplog_is_opt_in() {
        let plain = Instrumentation::instrumented().envs();
        assert_eq!(value(&plain, ENV_AFL_LLVM_CMPLOG), None);
        let cmplog = Instrumentation::instrumented().with_cmplog(true).envs();
        assert_eq!(
            value(&cmplog, ENV_AFL_LLVM_CMPLOG).as_deref(),
            Some(ENV_ENABLED)
        );
    }

    #[test]
    fn leak_detection_is_disabled_while_building_so_configure_probes_do_not_fail() {
        let envs = Instrumentation::instrumented().envs();
        let options = value(&envs, ENV_ASAN_OPTIONS).unwrap();
        assert!(options.contains("detect_leaks=0"));
    }

    #[test]
    fn default_flags_keep_frames_and_debug_info() {
        let flags = Instrumentation::instrumented().cflags_string();
        assert!(flags.contains("-g"));
        assert!(flags.contains("-fno-omit-frame-pointer"));
    }

    #[test]
    fn default_flags_never_define_ndebug_because_assertions_are_free_oracles() {
        let flags = Instrumentation::instrumented().cflags_string();
        assert!(!flags.contains("NDEBUG"));
    }

    #[test]
    fn extra_cflags_are_appended_after_the_defaults() {
        let instrumentation =
            Instrumentation::instrumented().with_extra_cflags(["-DMAGMA_ENABLE_CANARIES"]);
        let flags = instrumentation.cflags_string();
        assert!(flags.ends_with("-DMAGMA_ENABLE_CANARIES"));
        assert!(flags.starts_with("-g"));
    }

    #[test]
    fn c_and_cxx_flags_stay_in_lockstep() {
        let envs = Instrumentation::instrumented()
            .with_extra_cflags(["-DX=1"])
            .envs();
        assert_eq!(value(&envs, ENV_CFLAGS), value(&envs, ENV_CXXFLAGS));
    }

    // B80's remaining half. The oracle bench needs a library whose guard IDs are baked into the
    // objects, which is what `afl-clang-fast` emits and what `afl-clang-lto` by definition
    // cannot: LTO has no objects to bake them into until the link.
    #[test]
    fn the_oracle_bench_builds_the_library_with_the_pcguard_compiler() {
        let envs = Instrumentation::oracle_bench().envs();
        assert_eq!(value(&envs, ENV_CC).as_deref(), Some(AFL_CC_PCGUARD));
        assert_eq!(value(&envs, ENV_CXX).as_deref(), Some(AFL_CXX_PCGUARD));
    }

    // It has to execute the SAME code as the fuzzing build or the coverage it measures is not
    // the coverage that gets fuzzed, so the sanitizers and flags are not relaxed for speed.
    #[test]
    fn the_oracle_bench_keeps_the_sanitizers_the_fuzzing_build_has() {
        let envs = Instrumentation::oracle_bench().envs();
        assert_eq!(value(&envs, ENV_AFL_USE_ASAN).as_deref(), Some(ENV_ENABLED));
        assert_eq!(
            value(&envs, ENV_AFL_USE_UBSAN).as_deref(),
            Some(ENV_ENABLED)
        );
        assert_eq!(
            Instrumentation::oracle_bench().cflags_string(),
            Instrumentation::instrumented().cflags_string()
        );
    }

    // cmplog is a fuzzing aid. The bench never fuzzes, and a cmplog pass on it is build time
    // spent on a table nothing reads.
    #[test]
    fn the_oracle_bench_does_not_carry_cmplog() {
        assert!(!Instrumentation::oracle_bench().cmplog);
        assert_eq!(
            value(&Instrumentation::oracle_bench().envs(), ENV_AFL_LLVM_CMPLOG),
            None
        );
    }

    #[test]
    fn the_uninstrumented_pass_uses_plain_clang_and_no_sanitizers() {
        let instrumentation = Instrumentation::uninstrumented();
        assert!(!instrumentation.is_instrumented());
        let envs = instrumentation.envs();
        assert_eq!(value(&envs, ENV_CC).as_deref(), Some(PLAIN_CC));
        assert_eq!(value(&envs, ENV_AFL_USE_ASAN), None);
    }

    #[test]
    fn a_shadow_toolchain_replaces_only_the_compilers() {
        let envs = Instrumentation::instrumented()
            .with_toolchain(Toolchain::default().with_compilers("/shadow/cc", "/shadow/c++"))
            .envs();
        assert_eq!(value(&envs, ENV_CC).as_deref(), Some("/shadow/cc"));
        assert_eq!(value(&envs, ENV_AR).as_deref(), Some(LLVM_AR));
    }

    #[test]
    fn sanitizer_sets_have_stable_names() {
        assert_eq!(SanitizerSet::AddressUndefined.as_str(), "address+undefined");
        assert_eq!(SanitizerSet::Memory.as_str(), "memory");
        assert_eq!(SanitizerSet::Off.as_str(), "off");
    }
}