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 👇

34.5 KB
Raw Blame
// ©AngelaMos | 2026
// plan.rs

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

use lisdex_core::process::CommandSpec;
use lisdex_ingest::detect::{Bootstrap, BuildSystem, Detection};

use crate::instrument::{
    ENV_AFL_NOOPT, ENV_AR, ENV_CFLAGS, ENV_CXXFLAGS, ENV_ENABLED, ENV_RANLIB, Instrumentation,
};
use crate::layout::BuildLayout;

pub const CMAKE_BIN: &str = "cmake";
pub const MESON_BIN: &str = "meson";
pub const MAKE_BIN: &str = "make";
pub const AUTORECONF_BIN: &str = "autoreconf";
pub const SH_BIN: &str = "sh";

pub const STEP_BOOTSTRAP: &str = "bootstrap";
pub const STEP_CONFIGURE: &str = "configure";
pub const STEP_COMPILE: &str = "compile";

pub const INJECT_FILE: &str = "lisdex-inject.cmake";
pub const NATIVE_FILE: &str = "lisdex-native.ini";

pub const GENERATOR_NINJA: &str = "Ninja";
pub const GENERATOR_MAKEFILES: &str = "Unix Makefiles";

pub const ENV_NOCONFIGURE: &str = "NOCONFIGURE";
pub const ENV_CMAKE_POLICY_MINIMUM: &str = "CMAKE_POLICY_VERSION_MINIMUM";
pub const CMAKE_POLICY_MINIMUM: &str = "3.5";

pub const CONFIGURE_SCRIPT: &str = "configure";

// autoconf already refuses an unexpanded macro whose name matches its own forbidden pattern,
// `^_?A[CHUM]_`, and exits non-zero. Every namespace BELOW is one autoconf does not forbid,
// which is why `autoreconf` can exit 0 having written a `configure` that dies on line 4216
// with `syntax error near unexpected token`. These are the m4 namespaces the tools that
// install macros actually use: autoconf-archive, pkg-config, libtool, gtk-doc, gettext,
// glib and intltool.
//
// The prefix is REQUIRED rather than accepting any uppercase token, because a bare
// `^[A-Z][A-Z0-9_]*\(` scan has a false positive on a real script: qemuafl's configure
// embeds `G_DEFINE_AUTOPTR_CLEANUP_FUNC(Foo, foo_free);` inside a C compile test, which is
// working code and not a leftover. Censused over every configure of 40KB or more in the
// image: this list flags that file zero times and the reproduction once.
pub const M4_NAMESPACES: &[&str] = &[
    "AX_", "PKG_", "LT_", "AS_", "AU_", "GTK_DOC_", "GLIB_", "IT_", "BOOST_",
];

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnexpandedMacro {
    pub line: usize,
    pub token: String,
}

fn macro_token(line: &str) -> Option<&str> {
    let token = line.split('(').next()?;
    if token.is_empty() || token.len() == line.len() {
        return None;
    }
    if !token
        .chars()
        .all(|letter| letter.is_ascii_uppercase() || letter.is_ascii_digit() || letter == '_')
    {
        return None;
    }
    M4_NAMESPACES
        .iter()
        .any(|namespace| token.starts_with(namespace))
        .then_some(token)
}

// A generated `configure` is shell, so a macro nobody expanded survives as a bare word at the
// start of a line and the shell reads it as a command with a syntax error in its arguments.
#[must_use]
pub fn unexpanded_macros(script: &str) -> Vec<UnexpandedMacro> {
    script
        .lines()
        .enumerate()
        .filter_map(|(offset, line)| {
            macro_token(line).map(|token| UnexpandedMacro {
                line: offset + 1,
                token: token.to_owned(),
            })
        })
        .collect()
}
const TARGET_CLEAN: &str = "clean";
const RELWITHDEBINFO_FLAGS: &str = "-O2 -g";
const AUTORECONF_ARGS: [&str; 4] = ["--force", "--install", "-I", "m4"];
const AUTOTOOLS_CONFIGURE_ARGS: [&str; 4] = [
    "--disable-shared",
    "--enable-static",
    "--disable-dependency-tracking",
    "--disable-werror",
];

#[derive(Debug, thiserror::Error)]
pub enum PlanError {
    #[error("{0} builds are detected but not planned by lisdex")]
    Unsupported(&'static str),
    #[error("autotools target has no configure script and bootstrapping is disabled")]
    MissingConfigure,
    #[error("no build plan could be produced")]
    NoPlan,
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Generator {
    #[default]
    Ninja,
    Makefiles,
}

impl Generator {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Generator::Ninja => GENERATOR_NINJA,
            Generator::Makefiles => GENERATOR_MAKEFILES,
        }
    }

    #[must_use]
    pub fn rebuilds_externally_modified_outputs(self) -> bool {
        match self {
            Generator::Ninja => true,
            Generator::Makefiles => false,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanOptions {
    pub jobs: usize,
    pub generator: Generator,
    pub bootstrap: BootstrapPolicy,
    pub variant: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BootstrapPolicy {
    #[default]
    Auto,
    Force,
    Never,
}

impl BootstrapPolicy {
    #[must_use]
    pub fn wants_bootstrap(self, has_generated_configure: bool) -> bool {
        match self {
            BootstrapPolicy::Auto => !has_generated_configure,
            BootstrapPolicy::Force => true,
            BootstrapPolicy::Never => false,
        }
    }
}

impl PlanOptions {
    #[must_use]
    pub fn new(variant: impl Into<String>, jobs: usize) -> Self {
        Self {
            jobs,
            generator: Generator::default(),
            bootstrap: BootstrapPolicy::default(),
            variant: variant.into(),
        }
    }

    #[must_use]
    pub fn with_generator(mut self, generator: Generator) -> Self {
        self.generator = generator;
        self
    }

    #[must_use]
    pub fn with_bootstrap(mut self, bootstrap: BootstrapPolicy) -> Self {
        self.bootstrap = bootstrap;
        self
    }

    #[must_use]
    pub fn without_bootstrap(self) -> Self {
        self.with_bootstrap(BootstrapPolicy::Never)
    }
}

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

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildStep {
    pub name: &'static str,
    pub spec: CommandSpec,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildPlan {
    pub system: BuildSystem,
    pub generator: Generator,
    pub build_dir: PathBuf,
    pub generated: Vec<GeneratedFile>,
    pub steps: Vec<BuildStep>,
}

impl BuildPlan {
    #[must_use]
    pub fn step(&self, name: &str) -> Option<&BuildStep> {
        self.steps.iter().find(|step| step.name == name)
    }
}

fn jobs_arg(jobs: usize) -> String {
    jobs.max(1).to_string()
}

#[must_use]
pub fn absolute_tool(program: &str) -> String {
    lisdex_core::process::resolve_on_path(program)
        .map_or_else(|| program.to_owned(), |path| path.display().to_string())
}

#[must_use]
pub fn clean_spec(build_dir: &Path) -> CommandSpec {
    CommandSpec::new(MAKE_BIN)
        .arg("-C")
        .path_arg(build_dir)
        .arg(TARGET_CLEAN)
}

fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(path).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
}

fn script_spec(script: &Path) -> CommandSpec {
    if is_executable(script) {
        CommandSpec::new(script.display().to_string())
    } else {
        CommandSpec::new(SH_BIN).path_arg(script)
    }
}

fn without_flag_env(envs: Vec<(String, String)>) -> Vec<(String, String)> {
    envs.into_iter()
        .filter(|(key, _)| key != ENV_CFLAGS && key != ENV_CXXFLAGS)
        .collect()
}

fn cmake_inject_file(path: PathBuf, instrumentation: &Instrumentation) -> GeneratedFile {
    use std::fmt::Write;

    let mut contents = String::from("# ©AngelaMos | 2026\n# lisdex-inject.cmake\n\n");
    if !instrumentation.cflags.is_empty() {
        let _ = writeln!(
            contents,
            "add_compile_options({})",
            instrumentation.cflags.join(" ")
        );
    }
    if !instrumentation.ldflags.is_empty() {
        let _ = writeln!(
            contents,
            "add_link_options({})",
            instrumentation.ldflags.join(" ")
        );
    }
    GeneratedFile { path, contents }
}

fn meson_native_file(path: PathBuf, instrumentation: &Instrumentation) -> GeneratedFile {
    let quoted = |flags: &[String]| {
        flags
            .iter()
            .map(|flag| format!("'{flag}'"))
            .collect::<Vec<String>>()
            .join(", ")
    };
    let toolchain = &instrumentation.toolchain;
    let contents = format!(
        "# ©AngelaMos | 2026\n# lisdex-native.ini\n\n\
         [binaries]\n\
         c = '{}'\n\
         cpp = '{}'\n\
         ar = '{}'\n\
         nm = '{}'\n\n\
         [built-in options]\n\
         c_args = [{}]\n\
         cpp_args = [{}]\n\
         c_link_args = [{}]\n\
         cpp_link_args = [{}]\n",
        absolute_tool(&toolchain.cc),
        absolute_tool(&toolchain.cxx),
        absolute_tool(&toolchain.ar),
        absolute_tool(&toolchain.nm),
        quoted(&instrumentation.cflags),
        quoted(&instrumentation.cflags),
        quoted(&instrumentation.ldflags),
        quoted(&instrumentation.ldflags),
    );
    GeneratedFile { path, contents }
}

fn cmake_plan(
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> BuildPlan {
    let build_dir = layout.build_dir(BuildSystem::CMake, &options.variant);
    let inject = cmake_inject_file(layout.toolchain_dir().join(INJECT_FILE), instrumentation);
    let toolchain = &instrumentation.toolchain;

    let configure = CommandSpec::new(CMAKE_BIN)
        .arg("-S")
        .path_arg(&layout.source)
        .arg("-B")
        .path_arg(&build_dir)
        .arg("-G")
        .arg(options.generator.as_str())
        .arg(format!(
            "-DCMAKE_PROJECT_TOP_LEVEL_INCLUDES={}",
            inject.path.display()
        ))
        .arg(format!("-DCMAKE_C_COMPILER={}", toolchain.cc))
        .arg(format!("-DCMAKE_CXX_COMPILER={}", toolchain.cxx))
        .arg(format!("-DCMAKE_AR={}", absolute_tool(&toolchain.ar)))
        .arg(format!(
            "-DCMAKE_RANLIB={}",
            absolute_tool(&toolchain.ranlib)
        ))
        .arg("-DBUILD_SHARED_LIBS=OFF")
        .arg("-DCMAKE_BUILD_TYPE=RelWithDebInfo")
        .arg(format!(
            "-DCMAKE_C_FLAGS_RELWITHDEBINFO={RELWITHDEBINFO_FLAGS}"
        ))
        .arg(format!(
            "-DCMAKE_CXX_FLAGS_RELWITHDEBINFO={RELWITHDEBINFO_FLAGS}"
        ))
        .arg("-DCMAKE_EXPORT_COMPILE_COMMANDS=ON")
        .arg(format!(
            "-D{ENV_CMAKE_POLICY_MINIMUM}={CMAKE_POLICY_MINIMUM}"
        ))
        .envs(without_flag_env(instrumentation.envs()))
        .env(ENV_CMAKE_POLICY_MINIMUM, CMAKE_POLICY_MINIMUM)
        .env(ENV_AFL_NOOPT, ENV_ENABLED);

    let compile = CommandSpec::new(CMAKE_BIN)
        .arg("--build")
        .path_arg(&build_dir)
        .arg("-j")
        .arg(jobs_arg(options.jobs))
        .envs(without_flag_env(instrumentation.envs()));

    BuildPlan {
        system: BuildSystem::CMake,
        generator: options.generator,
        build_dir,
        generated: vec![inject],
        steps: vec![
            BuildStep {
                name: STEP_CONFIGURE,
                spec: configure,
            },
            BuildStep {
                name: STEP_COMPILE,
                spec: compile,
            },
        ],
    }
}

fn meson_plan(
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> BuildPlan {
    let build_dir = layout.build_dir(BuildSystem::Meson, &options.variant);
    let native = meson_native_file(layout.toolchain_dir().join(NATIVE_FILE), instrumentation);

    let configure = CommandSpec::new(MESON_BIN)
        .arg("setup")
        .path_arg(&build_dir)
        .path_arg(&layout.source)
        .arg("--native-file")
        .path_arg(&native.path)
        .arg("--buildtype=debugoptimized")
        .arg("-Ddefault_library=static")
        .arg("-Dwerror=false")
        .envs(without_flag_env(instrumentation.envs()))
        .env(ENV_AFL_NOOPT, ENV_ENABLED);

    let compile = CommandSpec::new(MESON_BIN)
        .arg("compile")
        .arg("-C")
        .path_arg(&build_dir)
        .arg("-j")
        .arg(jobs_arg(options.jobs))
        .envs(without_flag_env(instrumentation.envs()));

    BuildPlan {
        system: BuildSystem::Meson,
        generator: Generator::Ninja,
        build_dir,
        generated: vec![native],
        steps: vec![
            BuildStep {
                name: STEP_CONFIGURE,
                spec: configure,
            },
            BuildStep {
                name: STEP_COMPILE,
                spec: compile,
            },
        ],
    }
}

fn autotools_plan(
    detection: &Detection,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> Result<BuildPlan, PlanError> {
    let build_dir = layout.build_dir(BuildSystem::Autotools, &options.variant);
    let configure_path = layout.source.join(CONFIGURE_SCRIPT);
    let mut steps = Vec::new();

    if options
        .bootstrap
        .wants_bootstrap(detection.has_generated_configure())
    {
        match detection.bootstrap() {
            Bootstrap::Autogen(script) => {
                steps.push(BuildStep {
                    name: STEP_BOOTSTRAP,
                    spec: script_spec(&layout.source.join(&script))
                        .cwd(&layout.source)
                        .envs(instrumentation.envs())
                        .env(ENV_NOCONFIGURE, ENV_ENABLED)
                        .env(ENV_AFL_NOOPT, ENV_ENABLED),
                });
            }
            Bootstrap::Autoreconf => {
                steps.push(BuildStep {
                    name: STEP_BOOTSTRAP,
                    spec: CommandSpec::new(AUTORECONF_BIN)
                        .args(AUTORECONF_ARGS)
                        .cwd(&layout.source)
                        .envs(instrumentation.envs())
                        .env(ENV_AFL_NOOPT, ENV_ENABLED),
                });
            }
            Bootstrap::None => {}
        }
    }

    if steps.is_empty() && !detection.has_generated_configure() {
        return Err(PlanError::MissingConfigure);
    }

    steps.push(BuildStep {
        name: STEP_CONFIGURE,
        spec: script_spec(&configure_path)
            .args(AUTOTOOLS_CONFIGURE_ARGS)
            .cwd(&build_dir)
            .envs(instrumentation.envs())
            .env(ENV_AFL_NOOPT, ENV_ENABLED),
    });

    steps.push(BuildStep {
        name: STEP_COMPILE,
        spec: CommandSpec::new(MAKE_BIN)
            .arg("-j")
            .arg(jobs_arg(options.jobs))
            .arg(format!("{ENV_AR}={}", instrumentation.toolchain.ar))
            .arg(format!("{ENV_RANLIB}={}", instrumentation.toolchain.ranlib))
            .cwd(&build_dir)
            .envs(instrumentation.envs()),
    });

    Ok(BuildPlan {
        system: BuildSystem::Autotools,
        generator: Generator::Makefiles,
        build_dir,
        generated: Vec::new(),
        steps,
    })
}

fn make_plan(
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> BuildPlan {
    let toolchain = &instrumentation.toolchain;
    let compile = CommandSpec::new(MAKE_BIN)
        .arg("-j")
        .arg(jobs_arg(options.jobs))
        .arg("-C")
        .path_arg(&layout.source)
        .arg(format!("CC={}", toolchain.cc))
        .arg(format!("CXX={}", toolchain.cxx))
        .envs(instrumentation.envs());

    BuildPlan {
        system: BuildSystem::Make,
        generator: Generator::Makefiles,
        build_dir: layout.source.clone(),
        generated: Vec::new(),
        steps: vec![BuildStep {
            name: STEP_COMPILE,
            spec: compile,
        }],
    }
}

pub fn plan(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> Result<BuildPlan, PlanError> {
    match system {
        BuildSystem::CMake => Ok(cmake_plan(layout, instrumentation, options)),
        BuildSystem::Meson => Ok(meson_plan(layout, instrumentation, options)),
        BuildSystem::Autotools => autotools_plan(detection, layout, instrumentation, options),
        BuildSystem::Make => Ok(make_plan(layout, instrumentation, options)),
        BuildSystem::Bazel => Err(PlanError::Unsupported("bazel")),
        BuildSystem::Scons => Err(PlanError::Unsupported("scons")),
        BuildSystem::Waf => Err(PlanError::Unsupported("waf")),
    }
}

pub fn plan_variants(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &PlanOptions,
) -> Result<Vec<BuildPlan>, PlanError> {
    let mut variants = vec![plan(detection, system, layout, instrumentation, options)?];
    let bootstrap_would_help = system == BuildSystem::Autotools
        && options.bootstrap == BootstrapPolicy::Auto
        && detection.has_generated_configure()
        && detection.bootstrap() != Bootstrap::None;
    if bootstrap_would_help {
        variants.push(plan(
            detection,
            system,
            layout,
            instrumentation,
            &options.clone().with_bootstrap(BootstrapPolicy::Force),
        )?);
    }
    Ok(variants)
}

pub fn write_generated(plan: &BuildPlan) -> Result<(), PlanError> {
    for file in &plan.generated {
        if let Some(parent) = file.path.parent() {
            std::fs::create_dir_all(parent).map_err(|source| PlanError::Io {
                path: parent.to_path_buf(),
                source,
            })?;
        }
        std::fs::write(&file.path, &file.contents).map_err(|source| PlanError::Io {
            path: file.path.clone(),
            source,
        })?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use lisdex_ingest::detect::{Evidence, Marker};

    fn layout() -> BuildLayout {
        BuildLayout::new("/src/libpng", "/work/libpng")
    }

    fn options() -> PlanOptions {
        PlanOptions::new("afl", 4)
    }

    fn detection(markers: &[(Marker, &str)]) -> Detection {
        Detection {
            root: PathBuf::from("/src/libpng"),
            evidence: markers
                .iter()
                .map(|(marker, file)| Evidence {
                    marker: *marker,
                    file: (*file).to_owned(),
                })
                .collect(),
            candidates: Vec::new(),
        }
    }

    fn plan_for(system: BuildSystem, detection: &Detection) -> BuildPlan {
        plan(
            detection,
            system,
            &layout(),
            &Instrumentation::instrumented(),
            &options(),
        )
        .unwrap()
    }

    #[test]
    fn cmake_injects_flags_through_the_top_level_include_hook() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(
            configure
                .spec
                .args
                .iter()
                .any(|arg| arg.starts_with("-DCMAKE_PROJECT_TOP_LEVEL_INCLUDES="))
        );
        let inject = &built.generated[0];
        assert!(inject.contents.contains("add_compile_options("));
        assert!(inject.path.ends_with(INJECT_FILE));
    }

    #[test]
    fn cmake_never_relies_on_cmake_c_flags_which_projects_clobber() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(
            !configure
                .spec
                .args
                .iter()
                .any(|arg| arg.starts_with("-DCMAKE_C_FLAGS=")
                    || arg.starts_with("-DCMAKE_C_FLAGS_INIT="))
        );
    }

    #[test]
    fn cmake_relwithdebinfo_flags_are_overridden_to_drop_ndebug() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        let flags: Vec<&String> = configure
            .spec
            .args
            .iter()
            .filter(|arg| arg.contains("RELWITHDEBINFO"))
            .collect();
        assert_eq!(flags.len(), 2);
        assert!(flags.iter().all(|arg| !arg.contains("NDEBUG")));
    }

    #[test]
    fn cmake_exports_a_compilation_database_and_uses_a_supporting_generator() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(
            configure
                .spec
                .args
                .contains(&"-DCMAKE_EXPORT_COMPILE_COMMANDS=ON".to_owned())
        );
        let generator = configure
            .spec
            .args
            .iter()
            .position(|arg| arg == "-G")
            .unwrap();
        assert_eq!(configure.spec.args[generator + 1], GENERATOR_NINJA);
    }

    #[test]
    fn cmake_carries_the_policy_minimum_on_the_command_line_and_in_the_environment() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(configure.spec.args.contains(&format!(
            "-D{ENV_CMAKE_POLICY_MINIMUM}={CMAKE_POLICY_MINIMUM}"
        )));
        assert_eq!(
            configure.spec.env_value(ENV_CMAKE_POLICY_MINIMUM),
            Some(CMAKE_POLICY_MINIMUM)
        );
    }

    #[test]
    fn cmake_builds_out_of_tree() {
        let built = plan_for(BuildSystem::CMake, &detection(&[]));
        assert!(layout().is_out_of_tree(&built.build_dir));
    }

    #[test]
    fn meson_configures_through_a_native_file_and_never_through_cflags() {
        let built = plan_for(BuildSystem::Meson, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(configure.spec.args.iter().any(|arg| arg == "--native-file"));
        assert!(!configure.spec.has_env(ENV_CFLAGS));
        assert!(
            !configure
                .spec
                .args
                .iter()
                .any(|arg| arg.starts_with("-Dc_args"))
        );
    }

    #[test]
    fn meson_never_sets_b_sanitize_because_afl_cc_owns_the_sanitizer_flags() {
        let built = plan_for(BuildSystem::Meson, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(
            !configure
                .spec
                .args
                .iter()
                .any(|arg| arg.contains("b_sanitize"))
        );
        assert!(configure.spec.has_env(crate::instrument::ENV_AFL_USE_UBSAN));
    }

    #[test]
    fn meson_native_file_names_the_compilers_and_quotes_flag_arrays() {
        let built = plan_for(BuildSystem::Meson, &detection(&[]));
        let native = &built.generated[0];
        assert!(native.contents.contains("[binaries]"));
        assert!(native.contents.contains(&format!(
            "c = '{}'",
            absolute_tool(crate::instrument::AFL_CC)
        )));
        assert!(native.contents.contains("[built-in options]"));
        assert!(native.contents.contains("c_args = ['-g', '-O2'"));
    }

    #[test]
    fn meson_builds_static_libraries() {
        let built = plan_for(BuildSystem::Meson, &detection(&[]));
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert!(
            configure
                .spec
                .args
                .contains(&"-Ddefault_library=static".to_owned())
        );
    }

    #[test]
    fn autotools_runs_autogen_when_the_project_ships_one() {
        let detected = detection(&[
            (Marker::Autogen, "autogen.sh"),
            (Marker::ConfigureAc, "configure.ac"),
        ]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        let bootstrap = built.step(STEP_BOOTSTRAP).unwrap();
        assert!(bootstrap.spec.command_line().contains("autogen.sh"));
        assert_eq!(bootstrap.spec.env_value(ENV_NOCONFIGURE), Some(ENV_ENABLED));
    }

    #[test]
    fn autotools_falls_back_to_autoreconf() {
        let detected = detection(&[(Marker::ConfigureAc, "configure.ac")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        let bootstrap = built.step(STEP_BOOTSTRAP).unwrap();
        assert_eq!(bootstrap.spec.program, AUTORECONF_BIN);
        assert!(bootstrap.spec.args.contains(&"--install".to_owned()));
    }

    #[test]
    fn a_shipped_configure_suppresses_autogen_which_refuses_to_rerun() {
        let detected = detection(&[
            (Marker::Autogen, "autogen.sh"),
            (Marker::ConfigureAc, "configure.ac"),
            (Marker::ConfigureScript, "configure"),
        ]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        assert!(built.step(STEP_BOOTSTRAP).is_none());
        assert!(built.step(STEP_CONFIGURE).is_some());
    }

    #[test]
    fn a_shipped_configure_still_yields_a_bootstrapping_fallback_variant() {
        let detected = detection(&[
            (Marker::Autogen, "autogen.sh"),
            (Marker::ConfigureAc, "configure.ac"),
            (Marker::ConfigureScript, "configure"),
        ]);
        let variants = plan_variants(
            &detected,
            BuildSystem::Autotools,
            &layout(),
            &Instrumentation::instrumented(),
            &options(),
        )
        .unwrap();
        assert_eq!(variants.len(), 2);
        assert!(variants[0].step(STEP_BOOTSTRAP).is_none());
        assert!(variants[1].step(STEP_BOOTSTRAP).is_some());
    }

    #[test]
    fn a_tree_without_a_shipped_configure_has_a_single_variant() {
        let detected = detection(&[(Marker::ConfigureAc, "configure.ac")]);
        let variants = plan_variants(
            &detected,
            BuildSystem::Autotools,
            &layout(),
            &Instrumentation::instrumented(),
            &options(),
        )
        .unwrap();
        assert_eq!(variants.len(), 1);
        assert!(variants[0].step(STEP_BOOTSTRAP).is_some());
    }

    #[test]
    fn cmake_receives_absolute_tool_paths_because_it_resolves_them_against_the_cwd() {
        assert!(absolute_tool("sh").starts_with('/'));
        assert_eq!(
            absolute_tool("lisdex-no-such-tool"),
            "lisdex-no-such-tool".to_owned()
        );
    }

    #[test]
    fn a_clean_step_targets_the_build_directory() {
        let spec = clean_spec(Path::new("/src/lua"));
        assert_eq!(spec.program, MAKE_BIN);
        assert_eq!(spec.args, vec!["-C", "/src/lua", TARGET_CLEAN]);
    }

    #[test]
    fn autotools_skips_bootstrap_for_a_pre_generated_configure() {
        let detected = detection(&[(Marker::ConfigureScript, "configure")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        assert!(built.step(STEP_BOOTSTRAP).is_none());
        assert!(built.step(STEP_CONFIGURE).is_some());
    }

    #[test]
    fn autotools_without_configure_or_bootstrap_is_a_planning_error() {
        let detected = detection(&[(Marker::ConfigureAc, "configure.ac")]);
        let result = plan(
            &detected,
            BuildSystem::Autotools,
            &layout(),
            &Instrumentation::instrumented(),
            &options().without_bootstrap(),
        );
        assert!(matches!(result, Err(PlanError::MissingConfigure)));
    }

    #[test]
    fn autotools_configure_runs_in_the_out_of_tree_build_dir() {
        let detected = detection(&[(Marker::ConfigureScript, "configure")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        let configure = built.step(STEP_CONFIGURE).unwrap();
        assert_eq!(
            configure.spec.cwd.as_deref(),
            Some(built.build_dir.as_path())
        );
        assert!(
            configure
                .spec
                .command_line()
                .contains("/src/libpng/configure")
        );
    }

    #[test]
    fn autotools_configure_disables_shared_and_werror() {
        let detected = detection(&[(Marker::ConfigureScript, "configure")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        let configure = built.step(STEP_CONFIGURE).unwrap();
        for expected in AUTOTOOLS_CONFIGURE_ARGS {
            assert!(configure.spec.args.contains(&expected.to_owned()));
        }
    }

    #[test]
    fn configure_runs_with_afl_noopt_and_the_build_does_not() {
        let detected = detection(&[(Marker::ConfigureScript, "configure")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        assert_eq!(
            built
                .step(STEP_CONFIGURE)
                .unwrap()
                .spec
                .env_value(ENV_AFL_NOOPT),
            Some(ENV_ENABLED)
        );
        assert!(
            !built
                .step(STEP_COMPILE)
                .unwrap()
                .spec
                .has_env(ENV_AFL_NOOPT)
        );
    }

    #[test]
    fn autotools_repasses_the_archiver_to_make_because_configure_may_not_save_it() {
        let detected = detection(&[(Marker::ConfigureScript, "configure")]);
        let built = plan_for(BuildSystem::Autotools, &detected);
        let compile = built.step(STEP_COMPILE).unwrap();
        assert!(compile.spec.args.iter().any(|arg| arg == "AR=llvm-ar"));
        assert!(
            compile
                .spec
                .args
                .iter()
                .any(|arg| arg == "RANLIB=llvm-ranlib")
        );
    }

    #[test]
    fn raw_make_overrides_a_hardcoded_compiler_with_a_command_line_variable() {
        let built = plan_for(BuildSystem::Make, &detection(&[]));
        let compile = built.step(STEP_COMPILE).unwrap();
        assert!(
            compile
                .spec
                .args
                .iter()
                .any(|arg| arg == "CC=afl-clang-lto")
        );
        assert!(compile.spec.has_env(ENV_CFLAGS));
        assert!(
            !compile
                .spec
                .args
                .iter()
                .any(|arg| arg.starts_with("CFLAGS="))
        );
    }

    #[test]
    fn raw_make_never_overrides_ar_because_makefiles_bake_flags_into_it() {
        let built = plan_for(BuildSystem::Make, &detection(&[]));
        let compile = built.step(STEP_COMPILE).unwrap();
        assert!(
            !compile
                .spec
                .args
                .iter()
                .any(|arg| arg.starts_with("AR=") || arg.starts_with("RANLIB=")),
            "lua declares AR= ar rcu; overriding AR drops rcu and ar prints its usage"
        );
    }

    #[test]
    fn unsupported_build_systems_fail_planning_loudly() {
        for system in [BuildSystem::Bazel, BuildSystem::Scons, BuildSystem::Waf] {
            let result = plan(
                &detection(&[]),
                system,
                &layout(),
                &Instrumentation::instrumented(),
                &options(),
            );
            assert!(matches!(result, Err(PlanError::Unsupported(_))));
        }
    }

    #[test]
    fn the_cmplog_variant_gets_its_own_build_dir_and_env() {
        let built = plan(
            &detection(&[]),
            BuildSystem::CMake,
            &layout(),
            &Instrumentation::instrumented().with_cmplog(true),
            &PlanOptions::new("cmplog", 4),
        )
        .unwrap();
        assert!(built.build_dir.ends_with("build-cmake-cmplog"));
        assert!(
            built
                .step(STEP_COMPILE)
                .unwrap()
                .spec
                .has_env(crate::instrument::ENV_AFL_LLVM_CMPLOG)
        );
    }

    #[test]
    fn generated_files_are_written_to_disk() {
        let work = lisdex_core::scratch::path("plan-generated");
        let _ = std::fs::remove_dir_all(&work);
        let layout = BuildLayout::new("/src/libpng", &work);
        let built = plan(
            &detection(&[]),
            BuildSystem::CMake,
            &layout,
            &Instrumentation::instrumented(),
            &options(),
        )
        .unwrap();
        write_generated(&built).unwrap();
        let written = std::fs::read_to_string(&built.generated[0].path).unwrap();
        assert!(written.contains("©AngelaMos"));
    }

    #[test]
    fn a_non_executable_configure_is_run_through_a_shell() {
        let work = lisdex_core::scratch::path("plan-shell");
        let _ = std::fs::remove_dir_all(&work);
        std::fs::create_dir_all(&work).unwrap();
        std::fs::write(work.join(CONFIGURE_SCRIPT), "#!/bin/sh\n").unwrap();
        let layout = BuildLayout::new(&work, work.join("out"));
        let built = plan(
            &detection(&[(Marker::ConfigureScript, "configure")]),
            BuildSystem::Autotools,
            &layout,
            &Instrumentation::instrumented(),
            &options(),
        )
        .unwrap();
        assert_eq!(built.step(STEP_CONFIGURE).unwrap().spec.program, SH_BIN);
    }

    #[test]
    fn a_macro_no_m4_file_expanded_is_found_where_the_shell_will_choke_on_it() {
        let found = unexpanded_macros(
            "#! /bin/sh\n\
             ac_cv_prog_cc=gcc\n\
             AX_TOTALLY_MADE_UP_MACRO(one, two)\n\
             exit 0\n",
        );
        assert_eq!(found.len(), 1);
        assert_eq!(found[0].line, 3);
        assert_eq!(found[0].token, "AX_TOTALLY_MADE_UP_MACRO");
    }

    #[test]
    fn c_code_a_configure_test_compiles_is_not_a_leftover_macro() {
        let found = unexpanded_macros(
            "G_DEFINE_AUTOPTR_CLEANUP_FUNC(Foo, foo_free);\n\
             G_STATIC_ASSERT(sizeof(int) == 4);\n",
        );
        assert!(
            found.is_empty(),
            "qemuafl's configure embeds this in a compile test, and a scan that accepts any \
             uppercase token refuses a project that builds perfectly well: {found:?}"
        );
    }

    #[test]
    fn a_macro_autoconf_itself_forbids_is_left_to_autoconf() {
        let found = unexpanded_macros("AC_INIT(foo, 1.0)\nAM_INIT_AUTOMAKE(bar)\n");
        assert!(
            found.is_empty(),
            "autoconf's own forbidden pattern already covers ^_?A[CHUM]_ and exits non-zero, \
             so reporting these here would blame the bootstrap for a failure it did report"
        );
    }

    #[test]
    fn ordinary_shell_a_configure_script_is_made_of_is_not_flagged() {
        // Every line here begins with an uppercase run and contains a parenthesis, so each
        // one is a shape a looser reading of "bare macro call" would accept. `PKG_` and `LT_`
        // are deliberately among them: those namespaces ARE on the list, and an assignment or
        // a substitution using one is still ordinary shell rather than a leftover call.
        let found = unexpanded_macros(
            "PKG_CONFIG=$(which pkg-config)\n\
             LT_SYS_LIBRARY_PATH=$(cat /etc/ld.so.conf)\n\
             AX_FLAGS=\"$(echo -O2)\"\n\
             CFLAGS=$(get_flags)\n\
             LIBS=\"-lz $LIBS\"\n\
             as_fn_error ()\n",
        );
        assert!(found.is_empty(), "{found:?}");
    }

    #[test]
    fn every_namespace_the_list_carries_is_recognised() {
        for namespace in M4_NAMESPACES {
            let line = format!("{namespace}SOME_CHECK(arg)\n");
            assert_eq!(
                unexpanded_macros(&line).len(),
                1,
                "{namespace} is listed but not matched"
            );
        }
    }
}