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 👇

41.9 KB
Raw Blame
// ©AngelaMos | 2026
// ladder.rs

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

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

use crate::artifact::{self, Artifact};
use crate::instrument::Instrumentation;
use crate::layout::BuildLayout;
use crate::plan::{self, BuildPlan, Generator, PlanOptions, STEP_COMPILE};
use crate::replay::{self, COMPILE_COMMANDS};
use crate::shadow::{self, ENV_PATH};
use crate::verify::{self, Requirements, SymbolCounts};

pub const BEAR_BIN: &str = "bear";
pub const LOG_EXTENSION: &str = "log";

const PREPASS_VARIANT_SUFFIX: &str = "-prepass";
const LABEL_PREPASS: &str = "prepass";
const FAILURE_DIAGNOSIS_LINES: usize = 15;
const LABEL_INSTRUMENTED: &str = "instrumented";
const LABEL_CAPTURE: &str = "capture";
const CONFIGURE_ONLY_LABEL: &str = "configure-only";
const STEP_CLEAN: &str = "clean";

#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    #[error("io error at {path}: {source}")]
    Io {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("planning error: {0}")]
    Plan(#[from] plan::PlanError),
    #[error("process error: {0}")]
    Process(#[from] process::ProcessError),
    #[error("shadow error: {0}")]
    Shadow(#[from] shadow::ShadowError),
    #[error("replay error: {0}")]
    Replay(#[from] replay::ReplayError),
    #[error("artifact error: {0}")]
    Artifact(#[from] artifact::ArtifactError),
    #[error(
        "no build system under {tree} could run its configure step, so the headers it generates were not produced: {refusals}"
    )]
    NotConfigured { tree: PathBuf, refusals: String },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tier {
    FlagInjection,
    CompilerShadow,
    GeneratedSourcePrepass,
    CompileCommandsReplay,
}

pub const TIERS: [Tier; 4] = [
    Tier::FlagInjection,
    Tier::CompilerShadow,
    Tier::GeneratedSourcePrepass,
    Tier::CompileCommandsReplay,
];

impl Tier {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Tier::FlagInjection => "flag-injection",
            Tier::CompilerShadow => "compiler-shadow",
            Tier::GeneratedSourcePrepass => "generated-source-prepass",
            Tier::CompileCommandsReplay => "compile-commands-replay",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StepOutcome {
    pub name: String,
    pub command_line: String,
    pub success: bool,
    pub timed_out: bool,
    pub log: Option<PathBuf>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Attempt {
    pub tier: Tier,
    pub system: BuildSystem,
    pub build_dir: PathBuf,
    pub steps: Vec<StepOutcome>,
    pub artifacts: Vec<Artifact>,
    pub counts: SymbolCounts,
    pub lto_bitcode: bool,
    pub shortfalls: Vec<String>,
    pub failure: Option<String>,
}

impl Attempt {
    #[must_use]
    pub fn succeeded(&self) -> bool {
        self.failure.is_none() && self.shortfalls.is_empty() && !self.artifacts.is_empty()
    }

    #[must_use]
    pub fn summary(&self) -> String {
        let reason = self.failure.clone().unwrap_or_else(|| {
            if self.artifacts.is_empty() {
                "build produced no libraries or executables".to_owned()
            } else {
                self.shortfalls.join("; ")
            }
        });
        format!(
            "{} via {}: {reason}",
            self.system.as_str(),
            self.tier.as_str()
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildOutcome {
    pub source: PathBuf,
    pub system: Option<BuildSystem>,
    pub tier: Option<Tier>,
    pub build_dir: Option<PathBuf>,
    pub artifacts: Vec<Artifact>,
    pub counts: SymbolCounts,
    pub lto_bitcode: bool,
    pub attempts: Vec<Attempt>,
    pub unplanned: Vec<BuildSystem>,
    pub degradation: Vec<String>,
}

impl BuildOutcome {
    #[must_use]
    pub fn succeeded(&self) -> bool {
        self.tier.is_some()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BuildOptions {
    pub variant: String,
    pub jobs: usize,
    pub requirements: Requirements,
    pub step_timeout: Duration,
    pub tiers: Vec<Tier>,
}

impl BuildOptions {
    #[must_use]
    pub fn new(variant: impl Into<String>, jobs: usize) -> Self {
        Self {
            variant: variant.into(),
            jobs,
            requirements: Requirements::library(),
            step_timeout: Duration::from_secs(DEFAULT_STEP_TIMEOUT_SECS),
            tiers: TIERS.to_vec(),
        }
    }

    #[must_use]
    pub fn with_requirements(mut self, requirements: Requirements) -> Self {
        self.requirements = requirements;
        self
    }

    #[must_use]
    pub fn with_tiers(mut self, tiers: Vec<Tier>) -> Self {
        self.tiers = tiers;
        self
    }
}

#[must_use]
pub fn bear_wrapped(spec: &CommandSpec, database: &Path) -> CommandSpec {
    let mut wrapped = CommandSpec::new(BEAR_BIN)
        .arg("--output")
        .path_arg(database)
        .arg("--")
        .arg(spec.program.clone())
        .args(spec.args.clone())
        .envs(spec.envs.clone());
    wrapped.cwd.clone_from(&spec.cwd);
    wrapped
}

fn log_path(
    layout: &BuildLayout,
    tier: Tier,
    system: BuildSystem,
    label: &str,
    step: &str,
) -> PathBuf {
    layout.logs_dir().join(format!(
        "{}-{}-{label}-{step}.{LOG_EXTENSION}",
        tier.as_str(),
        system.as_str()
    ))
}

fn prepare_build_dir(
    layout: &BuildLayout,
    built: &BuildPlan,
    timeout: Duration,
) -> Result<Option<StepOutcome>, BuildError> {
    if layout.is_out_of_tree(&built.build_dir) {
        layout
            .reset_dir(&built.build_dir)
            .map_err(|source| BuildError::Io {
                path: built.build_dir.clone(),
                source,
            })?;
        return Ok(None);
    }
    let (outcome, _) = run_single(&plan::clean_spec(&built.build_dir), STEP_CLEAN, timeout)?;
    Ok(Some(outcome))
}

fn execute(
    layout: &BuildLayout,
    built: &BuildPlan,
    tier: Tier,
    label: &str,
    extra_envs: &[(String, String)],
    timeout: Duration,
) -> Result<(Vec<StepOutcome>, Option<String>), BuildError> {
    let mut outcomes = Vec::new();
    if let Some(cleaned) = prepare_build_dir(layout, built, timeout)? {
        outcomes.push(cleaned);
    }
    plan::write_generated(built)?;

    for step in &built.steps {
        let mut spec = step.spec.clone();
        spec.envs.extend_from_slice(extra_envs);
        let execution = process::run(&spec, timeout)?;
        let log = log_path(layout, tier, built.system, label, step.name);
        let written = std::fs::write(&log, &execution.output).is_ok();
        outcomes.push(StepOutcome {
            name: step.name.to_owned(),
            command_line: execution.command_line.clone(),
            success: execution.success,
            timed_out: execution.timed_out,
            log: written.then(|| log.clone()),
        });
        if !execution.success {
            let reason = if execution.timed_out {
                format!("step {} timed out", step.name)
            } else {
                format!(
                    "step {} failed ({:?}): {}",
                    step.name,
                    execution.code,
                    execution.diagnosis(FAILURE_DIAGNOSIS_LINES)
                )
            };
            return Ok((outcomes, Some(reason)));
        }
        if let Some(reason) = bootstrap_wrote_a_broken_configure(layout, step.name) {
            return Ok((outcomes, Some(reason)));
        }
    }
    Ok((outcomes, None))
}

// `autoreconf` exits 0 having written a `configure` that cannot run, whenever a macro comes
// from a namespace autoconf does not forbid. Reproduced: a configure.ac calling an
// unavailable `AX_` macro bootstraps with exit 0, and the `configure` it wrote then dies with
// `syntax error near unexpected token` on the line holding the macro. The build fails either
// way; the difference is that the shell's message names a token and this one names the cause,
// which is what the M5 repair tier needs to act on.
fn bootstrap_wrote_a_broken_configure(layout: &BuildLayout, step: &str) -> Option<String> {
    if step != plan::STEP_BOOTSTRAP {
        return None;
    }
    let script = layout.source.join(plan::CONFIGURE_SCRIPT);
    let found = plan::unexpanded_macros(&std::fs::read_to_string(&script).ok()?);
    let first = found.first()?;
    Some(format!(
        "step {step} reported success but wrote a configure script with {} unexpanded m4 \
         macro(s); {} is still a bare token at {}:{}. the macro's m4 file is not installed, \
         so autoconf copied the call through instead of expanding it and the shell will read \
         it as a command. install the package that provides it (autoconf-archive for AX_, \
         pkg-config for PKG_, libtool for LT_) and build again",
        found.len(),
        first.token,
        script.display(),
        first.line
    ))
}

fn inspect_artifacts(
    roots: &[PathBuf],
    requirements: &Requirements,
) -> Result<(Vec<Artifact>, SymbolCounts, bool, Vec<String>), BuildError> {
    let found = artifact::discover(roots)?;
    let measured = artifact::libraries(&found);
    let mut counts = SymbolCounts::default();
    let mut lto_bitcode = false;
    let mut shortfalls = Vec::new();

    if found.is_empty() {
        return Ok((found, counts, lto_bitcode, shortfalls));
    }
    if measured.is_empty() {
        shortfalls.push(
            "no library artifacts were produced; instrumentation of the target's own code \
             cannot be verified from executables alone, because the AFL++ runtime defines \
             the sanitizer and coverage symbols itself"
                .to_owned(),
        );
        return Ok((found, counts, lto_bitcode, shortfalls));
    }

    for item in measured {
        let kinds = artifact::member_kinds(&item.path);
        lto_bitcode = lto_bitcode || kinds.holds_bitcode();
        if kinds.is_mixed() {
            shortfalls.push(format!(
                "{}: {} of {} archive members are native objects, so they were built by a \
                 compiler lisdex did not instrument",
                item.path.display(),
                kinds.native,
                kinds.native + kinds.bitcode
            ));
        }
        let measured_counts = match verify::inspect(&item.path) {
            Ok(measured_counts) => measured_counts,
            Err(verify::VerifyError::Unreadable { .. }) => continue,
            Err(source @ verify::VerifyError::Truncated { .. }) => {
                shortfalls.push(format!("{}: {source}", item.path.display()));
                continue;
            }
            Err(verify::VerifyError::Process(source)) => {
                return Err(BuildError::Process(source));
            }
        };
        counts = counts.merge(measured_counts);
        for shortfall in requirements.shortfalls(measured_counts, kinds.holds_bitcode()) {
            shortfalls.push(format!("{}: {shortfall}", item.path.display()));
        }
    }

    Ok((found, counts, lto_bitcode, shortfalls))
}

fn finish_attempt(
    layout: &BuildLayout,
    built: &BuildPlan,
    tier: Tier,
    steps: Vec<StepOutcome>,
    failure: Option<String>,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    let roots = vec![built.build_dir.clone(), layout.source.clone()];
    let (artifacts, counts, lto_bitcode, shortfalls) = if failure.is_some() {
        (Vec::new(), SymbolCounts::default(), false, Vec::new())
    } else {
        inspect_artifacts(&roots, &options.requirements)?
    };
    Ok(Attempt {
        tier,
        system: built.system,
        build_dir: built.build_dir.clone(),
        steps,
        artifacts,
        counts,
        lto_bitcode,
        shortfalls,
        failure,
    })
}

fn attempt_planned(
    tier: Tier,
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
    extra_envs: &[(String, String)],
) -> Result<Attempt, BuildError> {
    let variants = plan::plan_variants(
        detection,
        system,
        layout,
        instrumentation,
        &PlanOptions::new(&options.variant, options.jobs),
    )?;
    let mut last = None;
    for (index, built) in variants.iter().enumerate() {
        let (steps, failure) = execute(
            layout,
            built,
            tier,
            &format!("v{index}"),
            extra_envs,
            options.step_timeout,
        )?;
        let attempt = finish_attempt(layout, built, tier, steps, failure, options)?;
        if attempt.succeeded() {
            return Ok(attempt);
        }
        last = Some(attempt);
    }
    last.ok_or(BuildError::Plan(plan::PlanError::NoPlan))
}

fn attempt_flag_injection(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    attempt_planned(
        Tier::FlagInjection,
        detection,
        system,
        layout,
        instrumentation,
        options,
        &[],
    )
}

fn attempt_compiler_shadow(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    let dir = layout.shadow_dir(&options.variant);
    shadow::install(&dir, instrumentation)?;
    let shadowed = shadow::shadowed(instrumentation, &dir);

    let mut extra = shadow::recursion_guard_envs();
    extra.push((
        ENV_PATH.to_owned(),
        shadow::path_value(&dir, std::env::var(ENV_PATH).ok().as_deref()),
    ));
    attempt_planned(
        Tier::CompilerShadow,
        detection,
        system,
        layout,
        &shadowed,
        options,
        &extra,
    )
}

fn prepass_plan(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    options: &BuildOptions,
) -> Result<BuildPlan, BuildError> {
    let variant = format!("{}{PREPASS_VARIANT_SUFFIX}", options.variant);
    Ok(plan::plan(
        detection,
        system,
        layout,
        &Instrumentation::uninstrumented(),
        &PlanOptions::new(variant, options.jobs).with_generator(Generator::Makefiles),
    )?)
}

fn attempt_generated_source_prepass(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    let prepass = prepass_plan(detection, system, layout, options)?;
    let (mut steps, failure) = execute(
        layout,
        &prepass,
        Tier::GeneratedSourcePrepass,
        LABEL_PREPASS,
        &[],
        options.step_timeout,
    )?;
    if let Some(failure) = failure {
        return finish_attempt(
            layout,
            &prepass,
            Tier::GeneratedSourcePrepass,
            steps,
            Some(failure),
            options,
        );
    }

    let built = plan::plan(
        detection,
        system,
        layout,
        instrumentation,
        &PlanOptions::new(&options.variant, options.jobs),
    )?;

    let (instrumented_steps, failure) = execute(
        layout,
        &built,
        Tier::GeneratedSourcePrepass,
        LABEL_INSTRUMENTED,
        &[],
        options.step_timeout,
    )?;
    steps.extend(instrumented_steps);
    finish_attempt(
        layout,
        &built,
        Tier::GeneratedSourcePrepass,
        steps,
        failure,
        options,
    )
}

fn run_single(
    spec: &CommandSpec,
    name: &str,
    timeout: Duration,
) -> Result<(StepOutcome, Option<String>), BuildError> {
    let execution = process::run(spec, timeout)?;
    let failure = (!execution.success).then(|| format!("{name} failed: {}", execution.tail(15)));
    Ok((
        StepOutcome {
            name: name.to_owned(),
            command_line: execution.command_line,
            success: execution.success,
            timed_out: execution.timed_out,
            log: None,
        },
        failure,
    ))
}

fn capture_database(
    layout: &BuildLayout,
    prepass: &BuildPlan,
    database: &Path,
    options: &BuildOptions,
) -> Result<(Vec<StepOutcome>, Option<String>), BuildError> {
    if database.is_file() {
        return Ok((Vec::new(), None));
    }
    let Some(compile) = prepass.step(STEP_COMPILE) else {
        return Ok((
            Vec::new(),
            Some("build plan has no compile step to capture".to_owned()),
        ));
    };
    let wrapped = bear_wrapped(&compile.spec, database);
    let mut captured = prepass.clone();
    for step in &mut captured.steps {
        if step.name == STEP_COMPILE {
            step.spec = wrapped.clone();
        }
    }
    execute(
        layout,
        &captured,
        Tier::CompileCommandsReplay,
        LABEL_CAPTURE,
        &[],
        options.step_timeout,
    )
}

fn attempt_compile_commands_replay(
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    let prepass = prepass_plan(detection, system, layout, options)?;
    let database = prepass.build_dir.join(COMPILE_COMMANDS);
    let finish = |steps, failure| {
        finish_attempt(
            layout,
            &prepass,
            Tier::CompileCommandsReplay,
            steps,
            failure,
            options,
        )
    };

    if prepass.generator.rebuilds_externally_modified_outputs() {
        return finish(
            Vec::new(),
            Some(format!(
                "{} builds through {}, which rebuilds an output whose bytes changed underneath \
                 it using the command it recorded, so the relink step would recompile every \
                 object this tier just replayed and hand back an uninstrumented library",
                prepass.system.as_str(),
                prepass.generator.as_str()
            )),
        );
    }

    let (mut steps, failure) = capture_database(layout, &prepass, &database, options)?;
    if failure.is_some() {
        return finish(steps, failure);
    }
    if !database.is_file() {
        return finish(steps, Some(format!("no {COMPILE_COMMANDS} was produced")));
    }

    let entries = match replay::load(&database) {
        Ok(entries) => entries,
        Err(err) => return finish(steps, Some(err.to_string())),
    };
    let report = replay::replay(&entries, instrumentation)?;
    steps.push(StepOutcome {
        name: "replay".to_owned(),
        command_line: format!(
            "replay {} compile commands, {} skipped, {} libtool stamp(s) refreshed",
            report.attempted, report.skipped, report.restamped
        ),
        success: report.succeeded(),
        timed_out: false,
        log: None,
    });
    if !report.succeeded() {
        return finish(
            steps,
            Some(format!(
                "{} of {} replayed commands failed: {}",
                report.failures.len(),
                report.attempted,
                report.failures.join(" | ")
            )),
        );
    }

    if let Some(relink) = prepass.step(STEP_COMPILE) {
        let (outcome, failure) = run_single(&relink.spec, "relink", options.step_timeout)?;
        steps.push(outcome);
        if failure.is_some() {
            return finish(steps, failure);
        }
    }

    finish(steps, None)
}

fn run_tier(
    tier: Tier,
    detection: &Detection,
    system: BuildSystem,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Attempt, BuildError> {
    match tier {
        Tier::FlagInjection => {
            attempt_flag_injection(detection, system, layout, instrumentation, options)
        }
        Tier::CompilerShadow => {
            attempt_compiler_shadow(detection, system, layout, instrumentation, options)
        }
        Tier::GeneratedSourcePrepass => {
            attempt_generated_source_prepass(detection, system, layout, instrumentation, options)
        }
        Tier::CompileCommandsReplay => {
            attempt_compile_commands_replay(detection, system, layout, instrumentation, options)
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Configured {
    pub system: BuildSystem,
    pub build_dir: PathBuf,
}

// The configure step alone, for a tree whose PUBLIC headers are generated by its build.
// Compiling the library is not needed to read its API and costs minutes; a cmake configure
// costs seconds. Measured on a fresh clone: libtiff 1.97s, openjpeg 1.33s, and both emit
// the header their own public headers include.
pub fn configure_only(
    detection: &Detection,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<Configured, BuildError> {
    layout.prepare().map_err(|source| BuildError::Io {
        path: layout.work.clone(),
        source,
    })?;

    let mut refusals = Vec::new();
    for system in &detection.candidates {
        let plan_options = PlanOptions {
            jobs: options.jobs,
            generator: Generator::default(),
            bootstrap: plan::BootstrapPolicy::Auto,
            variant: options.variant.clone(),
        };
        let Ok(mut planned) =
            plan::plan(detection, *system, layout, instrumentation, &plan_options)
        else {
            continue;
        };
        let Some(stop) = planned
            .steps
            .iter()
            .position(|step| step.name == plan::STEP_CONFIGURE)
        else {
            continue;
        };
        planned.steps.truncate(stop + 1);

        let (_, failure) = execute(
            layout,
            &planned,
            Tier::FlagInjection,
            CONFIGURE_ONLY_LABEL,
            &[],
            options.step_timeout,
        )?;
        match failure {
            None => {
                return Ok(Configured {
                    system: *system,
                    build_dir: planned.build_dir,
                });
            }
            Some(reason) => refusals.push(format!("{}: {reason}", system.as_str())),
        }
    }
    Err(BuildError::NotConfigured {
        tree: layout.source.clone(),
        refusals: if refusals.is_empty() {
            "no candidate build system plans a configure step".to_owned()
        } else {
            refusals.join("; ")
        },
    })
}

pub fn build(
    detection: &Detection,
    layout: &BuildLayout,
    instrumentation: &Instrumentation,
    options: &BuildOptions,
) -> Result<BuildOutcome, BuildError> {
    layout.prepare().map_err(|source| BuildError::Io {
        path: layout.work.clone(),
        source,
    })?;

    let mut outcome = BuildOutcome {
        source: layout.source.clone(),
        system: None,
        tier: None,
        build_dir: None,
        artifacts: Vec::new(),
        counts: SymbolCounts::default(),
        lto_bitcode: false,
        attempts: Vec::new(),
        unplanned: Vec::new(),
        degradation: Vec::new(),
    };

    outcome.unplanned = detection.unsupported();

    let supported = detection.supported();
    if supported.is_empty() {
        let named = outcome
            .unplanned
            .iter()
            .map(|system| system.as_str())
            .collect::<Vec<&str>>()
            .join(", ");
        outcome.degradation.push(if named.is_empty() {
            "no supported build system detected in the source tree".to_owned()
        } else {
            format!(
                "no supported build system detected in the source tree; the only one(s) present \
                 are {named}, which lisdex plans no build for"
            )
        });
        return Ok(outcome);
    }

    let mut unplannable = Vec::new();
    for tier in &options.tiers {
        for system in &supported {
            let system = *system;
            if unplannable.contains(&system) {
                continue;
            }
            let attempt = match run_tier(*tier, detection, system, layout, instrumentation, options)
            {
                Ok(attempt) => attempt,
                Err(BuildError::Plan(err)) => {
                    outcome
                        .degradation
                        .push(format!("{}: {err}", system.as_str()));
                    unplannable.push(system);
                    continue;
                }
                Err(err) => return Err(err),
            };

            if attempt.succeeded() {
                outcome.system = Some(system);
                outcome.tier = Some(*tier);
                outcome.build_dir = Some(attempt.build_dir.clone());
                outcome.artifacts.clone_from(&attempt.artifacts);
                outcome.counts = attempt.counts;
                outcome.lto_bitcode = attempt.lto_bitcode;
                outcome.attempts.push(attempt);
                return Ok(outcome);
            }

            outcome.degradation.push(attempt.summary());
            outcome.attempts.push(attempt);
        }
    }

    Ok(outcome)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::artifact::ArtifactKind;
    use crate::plan::{GENERATOR_MAKEFILES, GENERATOR_NINJA};
    use lisdex_ingest::detect::{Evidence, Marker};

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

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

    fn elf_file(dir: &Path, name: &str) -> PathBuf {
        use std::os::unix::fs::PermissionsExt;
        let path = dir.join(name);
        let mut body = vec![0x7f, b'E', b'L', b'F'];
        body.resize(64, 0);
        std::fs::write(&path, body).unwrap();
        let mut perms = std::fs::metadata(&path).unwrap().permissions();
        perms.set_mode(0o755);
        std::fs::set_permissions(&path, perms).unwrap();
        path
    }

    #[test]
    fn a_build_producing_only_executables_is_short_of_what_can_be_verified() {
        let dir = scratch("executable-only");
        elf_file(&dir, "tool");

        let (found, _, _, shortfalls) =
            inspect_artifacts(std::slice::from_ref(&dir), &Requirements::library()).unwrap();

        assert_eq!(
            found.len(),
            1,
            "the fixture must produce exactly one artifact"
        );
        assert_eq!(
            found[0].kind,
            ArtifactKind::Executable,
            "the fixture must isolate the signal: an executable and no library at all"
        );
        assert!(
            shortfalls
                .iter()
                .any(|s| s.contains("no library artifacts were produced")),
            "the AFL++ runtime defines the sanitizer and coverage symbols itself, so an executable-only build looks instrumented whether or not the TARGET's code was instrumented; reporting it verified is how a campaign fuzzes an uninstrumented library at full speed and finds nothing"
        );
    }

    #[test]
    fn a_build_producing_a_library_is_not_refused_by_that_rule() {
        let dir = scratch("has-library");
        elf_file(&dir, "tool");
        std::fs::write(dir.join("libfoo.so"), [0x7f, b'E', b'L', b'F', 0, 0, 0, 0]).unwrap();

        let (_, _, _, shortfalls) =
            inspect_artifacts(std::slice::from_ref(&dir), &Requirements::library()).unwrap();

        assert!(
            !shortfalls
                .iter()
                .any(|s| s.contains("no library artifacts were produced")),
            "a rule that refuses every build regardless of what it produced would satisfy the test above while being useless"
        );
    }

    #[test]
    fn tiers_are_ordered_cheapest_first() {
        assert_eq!(TIERS[0], Tier::FlagInjection);
        assert_eq!(TIERS[1], Tier::CompilerShadow);
        assert_eq!(TIERS.len(), 4);
    }

    #[test]
    fn the_cheapest_tier_is_tried_on_every_build_system_before_any_costlier_tier() {
        let dir = scratch("tier-major");
        std::fs::write(
            dir.join("CMakeLists.txt"),
            "cmake_minimum_required(VERSION 3.10)\n",
        )
        .unwrap();
        std::fs::write(dir.join("Makefile"), "all:\n\t@false\n").unwrap();
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(
                vec![BuildSystem::CMake, BuildSystem::Make],
                &[
                    (Marker::CMakeLists, "CMakeLists.txt"),
                    (Marker::Makefile, "Makefile"),
                ],
            ),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1)
                .with_tiers(vec![Tier::FlagInjection, Tier::CompilerShadow]),
        )
        .unwrap();

        let order: Vec<(Tier, BuildSystem)> = outcome
            .attempts
            .iter()
            .map(|attempt| (attempt.tier, attempt.system))
            .collect();
        let first_shadow = order
            .iter()
            .position(|(tier, _)| *tier == Tier::CompilerShadow)
            .expect("the shadow tier should have been reached");
        let flag_injection_attempts = order
            .iter()
            .filter(|(tier, _)| *tier == Tier::FlagInjection)
            .count();
        assert_eq!(
            flag_injection_attempts, 2,
            "flag injection must be tried on both systems first: {order:?}"
        );
        assert_eq!(first_shadow, 2, "a costlier tier ran too early: {order:?}");
    }

    fn replay_only_attempt(name: &str, system: BuildSystem) -> Attempt {
        let dir = scratch(name);
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![system], &[]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1).with_tiers(vec![Tier::CompileCommandsReplay]),
        )
        .unwrap();
        outcome
            .attempts
            .into_iter()
            .find(|attempt| attempt.tier == Tier::CompileCommandsReplay)
            .expect("the replay tier must have been attempted")
    }

    #[test]
    fn compile_commands_replay_refuses_a_ninja_backed_tree_and_names_the_generator() {
        let attempt = replay_only_attempt("replay-ninja", BuildSystem::Meson);
        let reason = attempt
            .failure
            .expect("a ninja-backed tier must be refused");
        assert!(
            reason.contains(GENERATOR_NINJA),
            "the refusal must name the generator that undoes the replay: {reason}"
        );
        assert!(
            attempt.steps.is_empty(),
            "the tier must refuse before it builds anything, not after burning a full \
             uninstrumented build and a full replay: {:?}",
            attempt.steps
        );
    }

    #[test]
    fn compile_commands_replay_does_not_refuse_a_make_backed_tree() {
        let attempt = replay_only_attempt("replay-make", BuildSystem::CMake);
        let reason = attempt.failure.unwrap_or_default();
        assert!(
            !reason.contains(GENERATOR_NINJA),
            "cmake's prepass is pinned to {GENERATOR_MAKEFILES} and must reach the database \
             capture, or the guard rejects every tree rather than the ninja-backed ones: \
             {reason}"
        );
    }

    #[test]
    fn every_tier_has_a_stable_name() {
        for tier in TIERS {
            assert!(!tier.as_str().is_empty());
        }
    }

    #[test]
    fn a_tree_with_no_supported_build_system_degrades_loudly_instead_of_failing_silently() {
        let dir = scratch("unsupported");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![BuildSystem::Bazel], &[]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        assert!(!outcome.succeeded());
        assert_eq!(outcome.unplanned, vec![BuildSystem::Bazel]);
        assert_eq!(outcome.degradation.len(), 1);
        assert!(outcome.degradation[0].contains("no supported build system"));
        assert!(
            outcome.degradation[0].contains("bazel"),
            "when the unplanned system IS the reason nothing built, the degradation must name \
             it: {}",
            outcome.degradation[0]
        );
    }

    #[test]
    fn an_unplanned_build_system_is_never_reported_as_degradation_when_another_one_is_planned() {
        let dir = scratch("unplanned-alongside");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![BuildSystem::Bazel, BuildSystem::CMake], &[]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        assert_eq!(
            outcome.unplanned,
            vec![BuildSystem::Bazel],
            "the unplanned system must still be reported somewhere, just not as a loss"
        );
        assert!(
            !outcome
                .degradation
                .iter()
                .any(|line| line.contains(BuildSystem::Bazel.as_str())),
            "brotli ships 8 bazel files and a CMakeLists.txt, and a fully instrumented cmake \
             build of it printed `degraded: bazel detected` when nothing was degraded: {:?}",
            outcome.degradation
        );
    }

    #[test]
    fn an_empty_detection_degrades_loudly() {
        let dir = scratch("empty");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(Vec::new(), &[]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        assert!(!outcome.succeeded());
        assert!(outcome.artifacts.is_empty());
        assert_eq!(outcome.tier, None);
    }

    #[test]
    fn a_failing_build_records_the_attempt_and_keeps_the_log() {
        let dir = scratch("failing");
        std::fs::write(dir.join("Makefile"), "all:\n\t@false\n").unwrap();
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![BuildSystem::Make], &[(Marker::Makefile, "Makefile")]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1).with_tiers(vec![Tier::FlagInjection]),
        )
        .unwrap();
        assert!(!outcome.succeeded());
        assert_eq!(outcome.attempts.len(), 1);
        assert!(outcome.attempts[0].failure.is_some());
        let log = outcome.attempts[0]
            .steps
            .iter()
            .find_map(|step| step.log.clone())
            .expect("the failing step must keep its log");
        assert!(log.is_file());
    }

    #[test]
    fn an_in_tree_make_build_never_resets_the_source_directory() {
        let dir = scratch("in-tree");
        std::fs::write(dir.join("Makefile"), "all:\n\t@true\n").unwrap();
        std::fs::write(dir.join("precious.c"), "int main(void){return 0;}\n").unwrap();
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let _ = build(
            &detection(vec![BuildSystem::Make], &[(Marker::Makefile, "Makefile")]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1).with_tiers(vec![Tier::FlagInjection]),
        )
        .unwrap();
        assert!(dir.join("precious.c").is_file());
        assert!(dir.join("Makefile").is_file());
    }

    #[test]
    fn a_build_that_produces_nothing_is_not_reported_as_a_success() {
        let dir = scratch("no-artifacts");
        std::fs::write(dir.join("Makefile"), "all:\n\t@true\n").unwrap();
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![BuildSystem::Make], &[(Marker::Makefile, "Makefile")]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1).with_tiers(vec![Tier::FlagInjection]),
        )
        .unwrap();
        assert!(!outcome.succeeded());
        assert!(
            outcome.degradation[0].contains("no libraries or executables"),
            "{:?}",
            outcome.degradation
        );
    }

    #[test]
    fn bear_wraps_a_compile_step_without_losing_its_environment_or_directory() {
        let spec = CommandSpec::new("make")
            .arg("-j4")
            .cwd("/build")
            .env("CC", "clang");
        let wrapped = bear_wrapped(&spec, &PathBuf::from("/build/compile_commands.json"));
        assert_eq!(wrapped.program, BEAR_BIN);
        assert_eq!(wrapped.cwd, Some(PathBuf::from("/build")));
        assert_eq!(wrapped.env_value("CC"), Some("clang"));
        let separator = wrapped.args.iter().position(|arg| arg == "--").unwrap();
        assert_eq!(wrapped.args[separator + 1], "make");
        assert_eq!(wrapped.args[separator + 2], "-j4");
    }

    #[test]
    fn attempt_summaries_name_the_system_and_the_tier() {
        let attempt = Attempt {
            tier: Tier::CompilerShadow,
            system: BuildSystem::CMake,
            build_dir: PathBuf::from("/w/build"),
            steps: Vec::new(),
            artifacts: Vec::new(),
            counts: SymbolCounts::default(),
            lto_bitcode: false,
            shortfalls: Vec::new(),
            failure: Some("configure failed".to_owned()),
        };
        assert_eq!(
            attempt.summary(),
            "cmake via compiler-shadow: configure failed"
        );
    }

    #[test]
    fn an_attempt_with_artifacts_but_missing_instrumentation_is_a_failure() {
        let attempt = Attempt {
            tier: Tier::FlagInjection,
            system: BuildSystem::Autotools,
            build_dir: PathBuf::from("/w/build"),
            steps: Vec::new(),
            artifacts: vec![Artifact {
                path: PathBuf::from("/w/build/libpng.a"),
                kind: artifact::ArtifactKind::StaticLib,
            }],
            counts: SymbolCounts::default(),
            lto_bitcode: false,
            shortfalls: vec!["address sanitizer symbols: found 0, need at least 1".to_owned()],
            failure: None,
        };
        assert!(!attempt.succeeded());
        assert!(attempt.summary().contains("address sanitizer"));
    }

    #[test]
    fn the_prepass_uses_makefiles_so_replayed_objects_are_not_rebuilt() {
        let dir = scratch("generator");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let built = prepass_plan(
            &detection(vec![BuildSystem::CMake], &[]),
            BuildSystem::CMake,
            &layout,
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        let configure = built.step(crate::plan::STEP_CONFIGURE).unwrap();
        let generator = configure
            .spec
            .args
            .iter()
            .position(|arg| arg == "-G")
            .unwrap();
        assert_eq!(
            configure.spec.args[generator + 1],
            crate::plan::GENERATOR_MAKEFILES
        );
        assert_eq!(built.generator, Generator::Makefiles);
    }

    #[test]
    fn a_meson_prepass_reports_ninja_however_the_prepass_asked_for_makefiles() {
        let dir = scratch("generator-meson");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let built = prepass_plan(
            &detection(vec![BuildSystem::Meson], &[]),
            BuildSystem::Meson,
            &layout,
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        assert_eq!(
            built.generator,
            Generator::Ninja,
            "meson has no generator but ninja, so a plan that echoed the requested \
             {GENERATOR_MAKEFILES} back would let the replay tier believe its relink is safe"
        );
    }

    #[test]
    fn the_prepass_is_uninstrumented_so_code_generators_run_with_a_plain_compiler() {
        let dir = scratch("prepass-plain");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let built = prepass_plan(
            &detection(vec![BuildSystem::CMake], &[]),
            BuildSystem::CMake,
            &layout,
            &BuildOptions::new("afl", 1),
        )
        .unwrap();
        let configure = built.step(crate::plan::STEP_CONFIGURE).unwrap();
        assert!(!configure.spec.has_env(crate::instrument::ENV_AFL_USE_ASAN));
        assert!(
            configure
                .spec
                .args
                .iter()
                .any(|arg| arg.contains(crate::instrument::PLAIN_CC))
        );
    }

    #[test]
    fn an_in_tree_prepass_is_cleaned_before_the_instrumented_pass_is_built() {
        let dir = scratch("prepass-clean");
        std::fs::write(
            dir.join("Makefile"),
            "all:\n\t@echo built >> $(HOME)/.lisdex-ignore || true\nclean:\n\t@touch cleaned\n",
        )
        .unwrap();
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let outcome = build(
            &detection(vec![BuildSystem::Make], &[(Marker::Makefile, "Makefile")]),
            &layout,
            &Instrumentation::instrumented(),
            &BuildOptions::new("afl", 1).with_tiers(vec![Tier::GeneratedSourcePrepass]),
        )
        .unwrap();
        assert!(
            dir.join("cleaned").is_file(),
            "a raw-make prepass must clean between passes or make reuses uninstrumented objects"
        );
        assert!(
            outcome.attempts[0]
                .steps
                .iter()
                .any(|step| step.name == "clean")
        );
    }

    #[test]
    fn the_prepass_never_shares_a_build_dir_with_the_instrumented_build() {
        let dir = scratch("prepass-dir");
        let layout = BuildLayout::new(&dir, dir.join("work"));
        let options = BuildOptions::new("afl", 1);
        let prepass = prepass_plan(
            &detection(vec![BuildSystem::CMake], &[]),
            BuildSystem::CMake,
            &layout,
            &options,
        )
        .unwrap();
        assert_ne!(
            prepass.build_dir,
            layout.build_dir(BuildSystem::CMake, &options.variant)
        );
    }
}