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 👇

11.7 KB
Raw Blame
// ©AngelaMos | 2026
// shadow.rs

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

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

use crate::instrument::{Instrumentation, LLVM_CONFIG, PLAIN_CC, PLAIN_CXX, Toolchain};

pub const SHADOWED_C: [&str; 3] = ["cc", "gcc", "clang"];
pub const SHADOWED_CXX: [&str; 3] = ["c++", "g++", "clang++"];
pub const SHADOWED_AR: &str = "ar";
pub const SHADOWED_RANLIB: &str = "ranlib";
pub const SHADOWED_NM: &str = "nm";
pub const ENV_PATH: &str = "PATH";
pub const ENV_AFL_CC: &str = "AFL_CC";
pub const ENV_AFL_CXX: &str = "AFL_CXX";
pub const ARG_BINDIR: &str = "--bindir";

const SCRIPT_MODE: u32 = 0o755;
const LLVM_CONFIG_TIMEOUT_SECS: u64 = 30;

#[derive(Debug, thiserror::Error)]
pub enum ShadowError {
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShadowScript {
    pub path: PathBuf,
    pub contents: String,
}

#[must_use]
pub fn shell_quote(value: &str) -> String {
    format!("'{}'", value.replace('\'', r"'\''"))
}

#[must_use]
pub fn script_body(name: &str, compiler: &str, flags: &[String]) -> String {
    let mut body = format!(
        "#!/bin/sh\n# ©AngelaMos | 2026\n# {name}\n\nexec {} \"$@\"",
        shell_quote(compiler)
    );
    for flag in flags {
        body.push(' ');
        body.push_str(&shell_quote(flag));
    }
    body.push('\n');
    body
}

#[must_use]
pub fn scripts(dir: &Path, instrumentation: &Instrumentation) -> Vec<ShadowScript> {
    let toolchain = &instrumentation.toolchain;
    let flags = &instrumentation.cflags;
    let mut scripts = Vec::new();
    for name in SHADOWED_C {
        scripts.push(ShadowScript {
            path: dir.join(name),
            contents: script_body(name, &toolchain.cc, flags),
        });
    }
    for name in SHADOWED_CXX {
        scripts.push(ShadowScript {
            path: dir.join(name),
            contents: script_body(name, &toolchain.cxx, flags),
        });
    }
    for (name, tool) in [
        (SHADOWED_AR, &toolchain.ar),
        (SHADOWED_RANLIB, &toolchain.ranlib),
        (SHADOWED_NM, &toolchain.nm),
    ] {
        scripts.push(ShadowScript {
            path: dir.join(name),
            contents: script_body(name, tool, &[]),
        });
    }
    scripts
}

pub fn install(dir: &Path, instrumentation: &Instrumentation) -> Result<(), ShadowError> {
    use std::os::unix::fs::PermissionsExt;

    std::fs::create_dir_all(dir).map_err(|source| ShadowError::Io {
        path: dir.to_path_buf(),
        source,
    })?;
    for script in scripts(dir, instrumentation) {
        std::fs::write(&script.path, &script.contents).map_err(|source| ShadowError::Io {
            path: script.path.clone(),
            source,
        })?;
        let mut perms = std::fs::metadata(&script.path)
            .map_err(|source| ShadowError::Io {
                path: script.path.clone(),
                source,
            })?
            .permissions();
        perms.set_mode(SCRIPT_MODE);
        std::fs::set_permissions(&script.path, perms).map_err(|source| ShadowError::Io {
            path: script.path.clone(),
            source,
        })?;
    }
    Ok(())
}

#[must_use]
pub fn path_value(dir: &Path, current: Option<&str>) -> String {
    match current {
        Some(existing) if !existing.is_empty() => format!("{}:{existing}", dir.display()),
        _ => dir.display().to_string(),
    }
}

#[must_use]
pub fn shadowed(instrumentation: &Instrumentation, dir: &Path) -> Instrumentation {
    let toolchain = Toolchain {
        cc: dir.join(SHADOWED_C[0]).display().to_string(),
        cxx: dir.join(SHADOWED_CXX[0]).display().to_string(),
        ..instrumentation.toolchain.clone()
    };
    Instrumentation {
        toolchain,
        ..instrumentation.clone()
    }
}

#[must_use]
pub fn llvm_config_spec() -> CommandSpec {
    CommandSpec::new(LLVM_CONFIG).arg(ARG_BINDIR)
}

#[must_use]
pub fn bindir_from(succeeded: bool, output: &str) -> Option<PathBuf> {
    if !succeeded {
        return None;
    }
    let trimmed = output.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(PathBuf::from(trimmed))
}

#[must_use]
pub fn llvm_bindir() -> Option<PathBuf> {
    let execution = process::run(
        &llvm_config_spec(),
        Duration::from_secs(LLVM_CONFIG_TIMEOUT_SECS),
    )
    .ok()?;
    bindir_from(execution.success, &execution.output)
}

#[must_use]
pub fn guard_envs_in(bindir: &Path) -> Vec<(String, String)> {
    let cc = bindir.join(PLAIN_CC);
    let cxx = bindir.join(PLAIN_CXX);
    if !cc.is_file() || !cxx.is_file() {
        return Vec::new();
    }
    vec![
        (ENV_AFL_CC.to_owned(), cc.display().to_string()),
        (ENV_AFL_CXX.to_owned(), cxx.display().to_string()),
    ]
}

#[must_use]
pub fn recursion_guard_envs() -> Vec<(String, String)> {
    llvm_bindir()
        .as_deref()
        .map_or_else(Vec::new, guard_envs_in)
}

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

    fn scratch(name: &str) -> PathBuf {
        let dir = lisdex_core::scratch::path(&format!("shadow-{name}"));
        let _ = std::fs::remove_dir_all(&dir);
        dir
    }

    #[test]
    fn every_compiler_name_a_makefile_might_hardcode_is_shadowed() {
        let generated = scripts(Path::new("/w/shadow"), &Instrumentation::instrumented());
        let names: Vec<String> = generated
            .iter()
            .map(|script| {
                script
                    .path
                    .file_name()
                    .unwrap()
                    .to_string_lossy()
                    .into_owned()
            })
            .collect();
        for expected in ["cc", "gcc", "clang", "c++", "g++", "clang++"] {
            assert!(names.contains(&expected.to_owned()), "missing {expected}");
        }
    }

    #[test]
    fn the_binutils_are_shadowed_so_makefiles_that_bake_flags_into_ar_still_work() {
        let generated = scripts(Path::new("/w/shadow"), &Instrumentation::instrumented());
        let ar = generated
            .iter()
            .find(|script| script.path.ends_with(SHADOWED_AR))
            .unwrap();
        assert!(ar.contents.contains("exec 'llvm-ar' \"$@\""));
        assert!(
            !ar.contents.contains("-fno-omit-frame-pointer"),
            "compiler flags must never be appended to an archiver invocation"
        );
        for tool in [SHADOWED_RANLIB, SHADOWED_NM] {
            assert!(generated.iter().any(|script| script.path.ends_with(tool)));
        }
    }

    #[test]
    fn the_c_preprocessor_is_never_shadowed_with_a_cxx_compiler() {
        let generated = scripts(Path::new("/w/shadow"), &Instrumentation::instrumented());
        assert!(!generated.iter().any(|script| script.path.ends_with("cpp")));
    }

    #[test]
    fn c_wrappers_call_the_c_compiler_and_cxx_wrappers_the_cxx_compiler() {
        let generated = scripts(Path::new("/w/shadow"), &Instrumentation::instrumented());
        let gcc = generated
            .iter()
            .find(|script| script.path.ends_with("gcc"))
            .unwrap();
        let gxx = generated
            .iter()
            .find(|script| script.path.ends_with("g++"))
            .unwrap();
        assert!(gcc.contents.contains("'afl-clang-lto' \"$@\""));
        assert!(gxx.contents.contains("'afl-clang-lto++' \"$@\""));
    }

    #[test]
    fn injected_flags_land_after_the_projects_own_arguments_so_they_win() {
        let instrumentation = Instrumentation::instrumented().with_extra_cflags(["-DLISDEX=1"]);
        let body = script_body("gcc", "afl-clang-lto", &instrumentation.cflags);
        let args = body.find("\"$@\"").unwrap();
        let ours = body.find("-DLISDEX=1").unwrap();
        assert!(ours > args);
    }

    #[test]
    fn scripts_are_written_executable() {
        use std::os::unix::fs::PermissionsExt;
        let dir = scratch("install");
        install(&dir, &Instrumentation::instrumented()).unwrap();
        let mode = std::fs::metadata(dir.join("gcc"))
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, SCRIPT_MODE);
    }

    #[test]
    fn the_shadow_directory_is_prepended_to_path() {
        let value = path_value(Path::new("/w/shadow"), Some("/usr/bin:/bin"));
        assert_eq!(value, "/w/shadow:/usr/bin:/bin");
        assert_eq!(path_value(Path::new("/w/shadow"), None), "/w/shadow");
    }

    #[test]
    fn a_shadowed_instrumentation_points_the_compilers_at_the_wrappers() {
        let shadowed = shadowed(&Instrumentation::instrumented(), Path::new("/w/shadow"));
        assert_eq!(shadowed.toolchain.cc, "/w/shadow/cc");
        assert_eq!(shadowed.toolchain.cxx, "/w/shadow/c++");
        assert_eq!(shadowed.toolchain.ar, "llvm-ar");
    }

    #[test]
    fn the_recursion_guard_pins_the_underlying_compiler_by_absolute_path() {
        let envs = recursion_guard_envs();
        assert_eq!(envs.len(), 2, "guard must name both compilers: {envs:?}");
        assert!(
            envs.iter()
                .all(|(_, value)| value.starts_with('/') && !value.contains("shadow"))
        );
    }

    #[test]
    fn every_compiler_the_guard_names_exists_on_disk() {
        for (name, value) in recursion_guard_envs() {
            assert!(
                Path::new(&value).is_file(),
                "{name}={value} does not exist; afl-cc aborts with 'failed to execute'"
            );
        }
    }

    #[test]
    fn the_guard_follows_the_installed_llvm_rather_than_a_pinned_release() {
        let bindir = llvm_bindir().expect("llvm-config --bindir must resolve in the toolchain");
        let envs = recursion_guard_envs();
        let cc = envs
            .iter()
            .find(|(name, _)| name == ENV_AFL_CC)
            .map(|(_, value)| value.clone())
            .unwrap();
        assert_eq!(cc, bindir.join(PLAIN_CC).display().to_string());
    }

    #[test]
    fn a_bindir_without_the_compilers_emits_no_guard_rather_than_a_fatal_path() {
        let dir = scratch("emptybindir");
        std::fs::create_dir_all(&dir).unwrap();
        assert!(guard_envs_in(&dir).is_empty());
        assert!(guard_envs_in(Path::new("/usr/lib/llvm-99/bin")).is_empty());
    }

    #[test]
    fn the_guard_names_the_bindir_it_was_given_and_not_a_baked_in_one() {
        let dir = scratch("otherbindir");
        std::fs::create_dir_all(&dir).unwrap();
        for name in [PLAIN_CC, PLAIN_CXX] {
            std::fs::write(dir.join(name), "#!/bin/sh\n").unwrap();
        }
        let envs = guard_envs_in(&dir);
        assert_eq!(envs.len(), 2);
        for (_, value) in envs {
            assert!(
                value.starts_with(&dir.display().to_string()),
                "{value} ignores the requested bindir {}",
                dir.display()
            );
        }
    }

    #[test]
    fn a_failed_or_silent_llvm_config_resolves_to_no_bindir() {
        assert!(bindir_from(false, "/usr/lib/llvm-20/bin").is_none());
        assert!(bindir_from(true, "   \n").is_none());
        assert_eq!(
            bindir_from(true, "/usr/lib/llvm-20/bin\n"),
            Some(PathBuf::from("/usr/lib/llvm-20/bin"))
        );
    }

    #[test]
    fn a_shadow_script_runs_and_forwards_its_arguments() {
        let dir = scratch("run");
        let instrumentation = Instrumentation::instrumented()
            .with_toolchain(Toolchain::default().with_compilers("echo", "echo"));
        install(&dir, &instrumentation).unwrap();
        let spec = lisdex_core::process::CommandSpec::new(dir.join("gcc").display().to_string())
            .arg("-c")
            .arg("png.c");
        let run = lisdex_core::process::run(&spec, std::time::Duration::from_secs(10)).unwrap();
        assert!(run.success);
        assert!(run.output.contains("-c png.c"));
        assert!(run.output.contains("-fno-omit-frame-pointer"));
    }
}