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 👇

35.5 KB
Raw Blame
// ©AngelaMos | 2026
// runner.rs

use std::borrow::Cow;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use lisdex_core::campaign::CampaignId;
use lisdex_core::config::{
    DEFAULT_REPRODUCE_TIMEOUT_MS, ENV_ASAN_OPTIONS, ENV_UBSAN_OPTIONS,
    REPRODUCE_SANITIZER_OPTIONS as SANITIZER_OPTIONS,
};
use lisdex_core::crash::Crash;
use lisdex_core::process;
use lisdex_core::report::SanitizerReport;

use crate::dictionary;
use crate::interrupt;
use crate::plot::{self, CoverageCurve, PLOT_FILE_NAME, PlotError};
use crate::stats::{FuzzerStats, STATS_FILE_NAME, StatsError};

pub const AFL_FUZZ_BIN: &str = "afl-fuzz";
pub const DEFAULT_INSTANCE: &str = "default";
pub const MAX_REPORT_BYTES: usize = 256 * 1024;

const REPRODUCE_POLL_MS: u64 = 25;
const SUPERVISE_POLL_MS: u64 = 100;
// How long a child gets to act on a signal it may never have received before it is killed.
const INTERRUPT_GRACE_MS: u64 = 5_000;
const UNPARSEABLE_REASON: &str = "no parseable sanitizer report";
const UNSYMBOLIZED_REASON: &str =
    "no symbolized frames, so any key would be shared by every crash of this kind in this module";
const CRASHES_DIR: &str = "crashes";
const CRASH_PREFIX: &str = "id:";
const MEM_LIMIT_UNLIMITED: &str = "none";
const ARG_INPUT: &str = "-i";
const ARG_OUTPUT: &str = "-o";
const ARG_MEMORY: &str = "-m";
const ARG_CMPLOG: &str = "-c";
const ARG_DURATION: &str = "-V";
const ARG_SKIP_DETERMINISTIC: &str = "-d";
const ARG_DICTIONARY: &str = "-x";
const ARG_MAIN: &str = "-M";
const ARG_SECONDARY: &str = "-S";
const ARG_SCHEDULE: &str = "-p";
const ARG_SEPARATOR: &str = "--";
const RESUME_IN_PLACE: &str = "-";
const ENV_FINAL_SYNC: &str = "AFL_FINAL_SYNC";

const ENV_SKIP_CPUFREQ: &str = "AFL_SKIP_CPUFREQ";
const ENV_NO_AFFINITY: &str = "AFL_NO_AFFINITY";
const ENV_NO_UI: &str = "AFL_NO_UI";
const ENV_MISSING_CRASHES: &str = "AFL_I_DONT_CARE_ABOUT_MISSING_CRASHES";
const ENV_BENCH_UNTIL_CRASH: &str = "AFL_BENCH_UNTIL_CRASH";
const ENV_ENABLED: &str = "1";

pub const INSTANCE_LOG_SUFFIX: &str = ".log";
pub const MAIN_INSTANCE: &str = "main";
pub const SECONDARY_PREFIX: &str = "secondary";
pub const SECONDARY_SCHEDULES: [&str; 6] = ["fast", "coe", "lin", "quad", "exploit", "rare"];

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Instance {
    Main(String),
    Secondary { name: String, schedule: String },
}

impl Instance {
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::Main(name) | Self::Secondary { name, .. } => name,
        }
    }

    #[must_use]
    pub fn is_main(&self) -> bool {
        matches!(self, Self::Main(_))
    }
}

#[must_use]
pub fn instance_plan(jobs: usize) -> Vec<Instance> {
    if jobs <= 1 {
        return Vec::new();
    }
    let mut plan = vec![Instance::Main(MAIN_INSTANCE.to_owned())];
    for index in 0..jobs - 1 {
        plan.push(Instance::Secondary {
            name: format!("{SECONDARY_PREFIX}{}", index + 1),
            schedule: SECONDARY_SCHEDULES[index % SECONDARY_SCHEDULES.len()].to_owned(),
        });
    }
    plan
}

#[derive(Debug, thiserror::Error)]
pub enum RunnerError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),
    #[error("stats error: {0}")]
    Stats(#[from] StatsError),
    #[error("plot error: {0}")]
    Plot(#[from] PlotError),
    #[error("no fuzzer instance under {findings}")]
    NoInstance { findings: String },
    #[error(
        "{AFL_FUZZ_BIN} failed before writing stats ({status}); check the {AFL_FUZZ_BIN} output above"
    )]
    AflFailed { status: String },
    #[error(
        "asked to resume but {findings} holds no previous instance; drop --resume to start a new campaign there"
    )]
    NothingToResume { findings: String },
}

#[derive(Debug, Clone, PartialEq)]
pub struct InstanceStats {
    pub name: String,
    pub stats: FuzzerStats,
}

impl InstanceStats {
    #[must_use]
    pub fn is_main(&self) -> bool {
        self.name == MAIN_INSTANCE || self.name == DEFAULT_INSTANCE
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reproduction {
    pub output: String,
    pub timed_out: bool,
    pub truncated: bool,
    pub lossy: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct RunOutcome {
    pub clean_exit: bool,
    // An interrupted campaign is not a failed one. afl-fuzz stopped because it was asked to, the
    // crashes it already wrote are on disk, and harvesting them is the whole point of catching
    // the signal rather than dying of it.
    pub interrupted: bool,
    pub stats: FuzzerStats,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AflOptions {
    pub target: PathBuf,
    pub cmplog: Option<PathBuf>,
    pub seeds: PathBuf,
    pub findings: PathBuf,
    pub duration: Option<Duration>,
    pub bench_until_crash: bool,
    pub skip_deterministic: bool,
    pub dictionaries: Vec<PathBuf>,
    pub instance: Option<Instance>,
    pub resume: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AflInvocation {
    pub program: String,
    pub args: Vec<String>,
    pub envs: Vec<(String, String)>,
}

impl AflOptions {
    #[must_use]
    pub fn invocation(&self) -> AflInvocation {
        let mut args = vec![
            ARG_INPUT.to_owned(),
            if self.resume {
                RESUME_IN_PLACE.to_owned()
            } else {
                self.seeds.display().to_string()
            },
            ARG_OUTPUT.to_owned(),
            self.findings.display().to_string(),
            ARG_MEMORY.to_owned(),
            MEM_LIMIT_UNLIMITED.to_owned(),
        ];

        if let Some(duration) = self.duration {
            args.push(ARG_DURATION.to_owned());
            args.push(duration.as_secs().to_string());
        }

        if let Some(cmplog) = &self.cmplog {
            args.push(ARG_CMPLOG.to_owned());
            args.push(cmplog.display().to_string());
        }

        if self.skip_deterministic {
            args.push(ARG_SKIP_DETERMINISTIC.to_owned());
        }

        for dictionary in self.dictionaries.iter().take(dictionary::MAX_DICTIONARIES) {
            args.push(ARG_DICTIONARY.to_owned());
            args.push(dictionary.display().to_string());
        }

        match &self.instance {
            Some(Instance::Main(name)) => {
                args.push(ARG_MAIN.to_owned());
                args.push(name.clone());
            }
            Some(Instance::Secondary { name, schedule }) => {
                args.push(ARG_SECONDARY.to_owned());
                args.push(name.clone());
                args.push(ARG_SCHEDULE.to_owned());
                args.push(schedule.clone());
            }
            None => {}
        }

        args.push(ARG_SEPARATOR.to_owned());
        args.push(self.target.display().to_string());

        let mut envs = vec![
            (ENV_SKIP_CPUFREQ.to_owned(), ENV_ENABLED.to_owned()),
            (ENV_NO_AFFINITY.to_owned(), ENV_ENABLED.to_owned()),
            (ENV_NO_UI.to_owned(), ENV_ENABLED.to_owned()),
            (ENV_MISSING_CRASHES.to_owned(), ENV_ENABLED.to_owned()),
        ];
        if self.bench_until_crash {
            envs.push((ENV_BENCH_UNTIL_CRASH.to_owned(), ENV_ENABLED.to_owned()));
        }
        if self.instance.as_ref().is_some_and(Instance::is_main) {
            envs.push((ENV_FINAL_SYNC.to_owned(), ENV_ENABLED.to_owned()));
        }

        AflInvocation {
            program: AFL_FUZZ_BIN.to_owned(),
            args,
            envs,
        }
    }
}

#[must_use]
pub fn crashes_dir(findings: &Path) -> PathBuf {
    findings.join(DEFAULT_INSTANCE).join(CRASHES_DIR)
}

pub fn instance_dirs(findings: &Path) -> Result<Vec<PathBuf>, RunnerError> {
    if !findings.is_dir() {
        return Ok(Vec::new());
    }
    let mut dirs = Vec::new();
    for entry in std::fs::read_dir(findings)? {
        let entry = entry?;
        if entry.file_type()?.is_dir() && entry.path().join(STATS_FILE_NAME).is_file() {
            dirs.push(entry.path());
        }
    }
    dirs.sort();
    Ok(dirs)
}

pub fn discover_crash_inputs(findings: &Path) -> Result<Vec<PathBuf>, RunnerError> {
    let mut roots = instance_dirs(findings)?;
    let default_dir = findings.join(DEFAULT_INSTANCE);
    if roots.is_empty() && default_dir.is_dir() {
        roots.push(default_dir);
    }

    let mut inputs = Vec::new();
    for root in roots {
        let dir = root.join(CRASHES_DIR);
        if !dir.is_dir() {
            continue;
        }
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            if !entry.file_type()?.is_file() {
                continue;
            }
            if entry
                .file_name()
                .to_string_lossy()
                .starts_with(CRASH_PREFIX)
            {
                inputs.push(entry.path());
            }
        }
    }
    inputs.sort();
    Ok(inputs)
}

pub fn read_stats(findings: &Path) -> Result<FuzzerStats, RunnerError> {
    Ok(FuzzerStats::parse(&read_stats_text(findings)?)?)
}

pub fn read_stats_text(findings: &Path) -> Result<String, RunnerError> {
    let path = primary_instance(findings)?.join(STATS_FILE_NAME);
    Ok(std::fs::read_to_string(path)?)
}

pub fn read_all_stats(findings: &Path) -> Result<Vec<FuzzerStats>, RunnerError> {
    let mut all = Vec::new();
    for dir in instance_dirs(findings)? {
        let text = std::fs::read_to_string(dir.join(STATS_FILE_NAME))?;
        all.push(FuzzerStats::parse(&text)?);
    }
    Ok(all)
}

pub fn primary_instance(findings: &Path) -> Result<PathBuf, RunnerError> {
    let dirs = instance_dirs(findings)?;
    let named = |wanted: &str| {
        dirs.iter()
            .find(|dir| dir.file_name().is_some_and(|name| name == wanted))
            .cloned()
    };
    named(MAIN_INSTANCE)
        .or_else(|| named(DEFAULT_INSTANCE))
        .or_else(|| dirs.first().cloned())
        .ok_or_else(|| RunnerError::NoInstance {
            findings: findings.display().to_string(),
        })
}

pub fn read_curve(findings: &Path) -> Result<CoverageCurve, RunnerError> {
    let path = primary_instance(findings)?.join(PLOT_FILE_NAME);
    Ok(plot::parse(&std::fs::read_to_string(path)?)?)
}

pub fn read_instance_stats(findings: &Path) -> Result<Vec<InstanceStats>, RunnerError> {
    let mut all = Vec::new();
    for dir in instance_dirs(findings)? {
        let name = dir.file_name().map_or_else(
            || DEFAULT_INSTANCE.to_owned(),
            |n| n.to_string_lossy().into_owned(),
        );
        let text = std::fs::read_to_string(dir.join(STATS_FILE_NAME))?;
        all.push(InstanceStats {
            name,
            stats: FuzzerStats::parse(&text)?,
        });
    }
    Ok(all)
}

#[must_use]
pub fn combine_stats(instances: &[FuzzerStats]) -> Option<FuzzerStats> {
    let first = instances.first()?;
    let mut combined = first.clone();
    for stats in instances.iter().skip(1) {
        combined.execs_done += stats.execs_done;
        combined.execs_per_sec += stats.execs_per_sec;
        combined.saved_crashes += stats.saved_crashes;
        combined.edges_found = combined.edges_found.max(stats.edges_found);
        combined.bitmap_coverage_pct = combined.bitmap_coverage_pct.max(stats.bitmap_coverage_pct);
        combined.total_edges = combined.total_edges.max(stats.total_edges);
    }
    Some(combined)
}

pub fn reproduce(
    target: &Path,
    input: &Path,
    timeout: Duration,
) -> Result<Reproduction, RunnerError> {
    let mut child = Command::new(target)
        .arg(input)
        .env(ENV_ASAN_OPTIONS, SANITIZER_OPTIONS)
        .env(ENV_UBSAN_OPTIONS, SANITIZER_OPTIONS)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()?;

    let captured = child
        .stderr
        .take()
        .map(|stream| process::drain(stream, MAX_REPORT_BYTES));

    let started = Instant::now();
    let mut timed_out = false;
    loop {
        if child.try_wait()?.is_some() {
            break;
        }
        if started.elapsed() >= timeout {
            child.kill()?;
            child.wait()?;
            timed_out = true;
            break;
        }
        std::thread::sleep(Duration::from_millis(REPRODUCE_POLL_MS));
    }

    let mut raw = Vec::new();
    if let Some((buffer, handle)) = captured {
        let deadline = Instant::now() + Duration::from_millis(process::DRAIN_GRACE_MS);
        while !handle.is_finished() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(REPRODUCE_POLL_MS));
        }
        raw = process::take_captured(&buffer);
    }
    let truncated = raw.len() >= MAX_REPORT_BYTES;
    let decoded = String::from_utf8_lossy(&raw);
    let lossy = matches!(decoded, Cow::Owned(_));
    let raw_text = decoded.into_owned();

    Ok(Reproduction {
        output: crate::symbolize::symbolize_report(&raw_text),
        timed_out,
        truncated,
        lossy,
    })
}

pub fn harvest(
    campaign_id: CampaignId,
    target: &Path,
    findings: &Path,
) -> Result<(Vec<Crash>, Vec<String>), RunnerError> {
    let timeout = Duration::from_millis(DEFAULT_REPRODUCE_TIMEOUT_MS);
    let mut crashes = Vec::new();
    let mut problems = Vec::new();

    for input_path in discover_crash_inputs(findings)? {
        let input = match std::fs::read(&input_path) {
            Ok(bytes) => bytes,
            Err(err) => {
                problems.push(format!("{}: unreadable ({err})", input_path.display()));
                continue;
            }
        };
        let reproduction = match reproduce(target, &input_path, timeout) {
            Ok(reproduction) => reproduction,
            Err(err) => {
                problems.push(format!("{}: not reproduced ({err})", input_path.display()));
                crashes.push(Crash::new(campaign_id, input, String::new(), None));
                continue;
            }
        };
        if reproduction.timed_out {
            problems.push(format!(
                "{}: hung, killed after timeout",
                input_path.display()
            ));
        }
        if reproduction.lossy {
            problems.push(format!(
                "{}: report held bytes that are not UTF-8 and they were replaced",
                input_path.display()
            ));
        }
        if reproduction.truncated {
            problems.push(format!("{}: report truncated", input_path.display()));
        }
        let report = SanitizerReport::parse(&reproduction.output);
        if report
            .as_ref()
            .and_then(SanitizerReport::stack_hash)
            .is_none()
        {
            let reason = if report.is_some() {
                UNSYMBOLIZED_REASON
            } else {
                UNPARSEABLE_REASON
            };
            problems.push(format!(
                "{}: {reason}, stored without a dedup key",
                input_path.display()
            ));
        }
        crashes.push(Crash::from_report(campaign_id, input, reproduction.output));
    }

    Ok((crashes, problems))
}

// Waits for every child while watching the interrupt flag, polling rather than blocking in
// `wait` so the flag is still observed once a signal has been caught.
//
// Ctrl-C at a terminal reaches the whole foreground group, so afl-fuzz already has its own copy
// and stops cleanly on its own; the only thing lisdex must do is survive long enough to harvest.
// A signal aimed at lisdex alone does NOT reach the children, so after `INTERRUPT_GRACE_MS` of
// them ignoring it they are killed outright. That loses afl's final `fuzzer_stats` update but
// never the crash files, which afl writes as it finds them - and recovering exactly those is
// what this is for.
fn supervise(
    mut children: Vec<Child>,
    interrupt: &interrupt::Interrupt,
) -> Result<(bool, bool), RunnerError> {
    let mut clean_exit = true;
    let mut waited_since_signal = 0u64;
    let mut killed = false;

    while !children.is_empty() {
        if interrupt.raised() {
            if waited_since_signal >= INTERRUPT_GRACE_MS && !killed {
                for child in &mut children {
                    let _ = child.kill();
                }
                killed = true;
            }
            waited_since_signal += SUPERVISE_POLL_MS;
        }
        let mut running = Vec::with_capacity(children.len());
        for mut child in children {
            match child.try_wait()? {
                Some(status) => clean_exit = clean_exit && status.success(),
                None => running.push(child),
            }
        }
        children = running;
        if !children.is_empty() {
            std::thread::sleep(Duration::from_millis(SUPERVISE_POLL_MS));
        }
    }

    Ok((clean_exit, interrupt.raised()))
}

pub fn run(
    options: &AflOptions,
    interrupt: &interrupt::Interrupt,
) -> Result<RunOutcome, RunnerError> {
    // afl-fuzz aborts with "Unable to create" rather than creating the parent itself.
    if let Some(parent) = options.findings.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let invocation = options.invocation();
    let mut command = Command::new(&invocation.program);
    command.args(&invocation.args);
    for (key, value) in &invocation.envs {
        command.env(key, value);
    }
    // Spawned rather than run through `status`, because the child has to stay addressable while
    // we wait for it.
    let (clean_exit, interrupted) = supervise(vec![command.spawn()?], interrupt)?;
    let measured = read_stats(&options.findings).map_err(|cause| match cause {
        RunnerError::Io(_) | RunnerError::NoInstance { .. } if !clean_exit => {
            RunnerError::AflFailed {
                status: "afl-fuzz exited without writing stats".to_owned(),
            }
        }
        other => other,
    })?;
    Ok(RunOutcome {
        clean_exit,
        interrupted,
        stats: measured,
    })
}

pub fn resumable(findings: &Path) -> Result<bool, RunnerError> {
    Ok(!instance_dirs(findings)?.is_empty())
}

pub fn run_parallel(
    base: &AflOptions,
    jobs: usize,
    interrupt: &interrupt::Interrupt,
) -> Result<RunOutcome, RunnerError> {
    if base.resume && !resumable(&base.findings)? {
        return Err(RunnerError::NothingToResume {
            findings: base.findings.display().to_string(),
        });
    }
    let plan = instance_plan(jobs);
    if plan.is_empty() {
        return run(base, interrupt);
    }
    if let Some(parent) = base.findings.parent() {
        std::fs::create_dir_all(parent)?;
    }

    std::fs::create_dir_all(&base.findings)?;
    let mut children = Vec::new();
    for instance in plan {
        let log_path = base
            .findings
            .join(format!("{}{INSTANCE_LOG_SUFFIX}", instance.name()));
        let mut options = base.clone();
        options.instance = Some(instance);
        let invocation = options.invocation();
        let mut command = Command::new(&invocation.program);
        command.args(&invocation.args);
        for (key, value) in &invocation.envs {
            command.env(key, value);
        }
        let log = std::fs::File::create(&log_path)?;
        let errors = log.try_clone()?;
        command.stdout(Stdio::from(log)).stderr(Stdio::from(errors));
        children.push(command.spawn()?);
    }

    let (clean_exit, interrupted) = supervise(children, interrupt)?;

    let instances = read_all_stats(&base.findings)?;
    let stats = combine_stats(&instances).ok_or(RunnerError::AflFailed {
        status: "no instance wrote fuzzer_stats".to_owned(),
    })?;
    Ok(RunOutcome {
        clean_exit,
        interrupted,
        stats,
    })
}

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

    fn options() -> AflOptions {
        AflOptions {
            target: PathBuf::from("/out/afl/harness"),
            cmplog: Some(PathBuf::from("/out/cmplog/harness")),
            seeds: PathBuf::from("/corpus"),
            findings: PathBuf::from("/findings"),
            duration: Some(Duration::from_mins(1)),
            bench_until_crash: true,
            skip_deterministic: true,
            dictionaries: Vec::new(),
            instance: None,
            resume: false,
        }
    }

    #[test]
    fn a_resuming_campaign_reads_its_own_output_instead_of_the_seed_corpus() {
        let mut options = options();
        options.resume = true;
        let args = options.invocation().args;
        let input = args
            .windows(2)
            .find(|pair| pair[0] == ARG_INPUT)
            .expect("an input is always given");
        assert_eq!(
            input[1], RESUME_IN_PLACE,
            "afl-fuzz resumes only when the input directory is literally '-'; handing it the seeds again would restart from the seeds and discard the queue"
        );
        assert!(!args.contains(&"/corpus".to_owned()));
    }

    #[test]
    fn a_fresh_campaign_still_reads_the_seed_corpus() {
        let args = options().invocation().args;
        let input = args
            .windows(2)
            .find(|pair| pair[0] == ARG_INPUT)
            .expect("an input is always given");
        assert_eq!(input[1], "/corpus");
    }

    // B5. Every campaign now goes through `supervise`, so a child that simply finishes has to
    // come back exactly as `status()` used to report it, or the fix for the interrupted case
    // would have changed every uninterrupted one.
    #[test]
    fn an_uninterrupted_child_reports_its_own_exit_and_no_interruption() {
        let interrupt = interrupt::Interrupt::arm().unwrap();
        let ok = Command::new("true").spawn().unwrap();
        assert_eq!(supervise(vec![ok], &interrupt).unwrap(), (true, false));

        let bad = Command::new("false").spawn().unwrap();
        assert_eq!(
            supervise(vec![bad], &interrupt).unwrap(),
            (false, false),
            "a child that failed on its own must not be reported as interrupted"
        );
    }

    // The whole point of B5: a raised flag must end the wait rather than leave lisdex blocked on
    // a child that never received the signal. `sleep 600` outlives any grace period, so the only
    // way this returns is the escalation.
    #[test]
    fn a_raised_interrupt_ends_the_wait_on_a_child_that_ignores_it() {
        let interrupt = interrupt::Interrupt::arm().unwrap();
        interrupt.raise_for_test();
        let sleeper = Command::new("sleep").arg("600").spawn().unwrap();

        let started = Instant::now();
        let (clean_exit, interrupted) = supervise(vec![sleeper], &interrupt).unwrap();

        assert!(interrupted, "the outcome must say it was interrupted");
        assert!(!clean_exit, "a killed child did not exit cleanly");
        assert!(
            started.elapsed() < Duration::from_millis(INTERRUPT_GRACE_MS * 4),
            "the wait outlived the grace period, so lisdex would hang instead of harvesting"
        );
    }

    #[test]
    fn resuming_a_findings_directory_that_never_ran_is_refused() {
        let empty = scratch("nothing-to-resume");
        std::fs::create_dir_all(&empty).unwrap();
        assert!(!resumable(&empty).unwrap());
        let mut options = options();
        options.resume = true;
        options.findings = empty;
        let interrupt = interrupt::Interrupt::arm().unwrap();
        let err =
            run_parallel(&options, 1, &interrupt).expect_err("there is nothing to resume from");
        assert!(
            matches!(err, RunnerError::NothingToResume { .. }),
            "afl-fuzz would instead start a fresh campaign from an input directory named '-', which does not exist, and fail with a path error that says nothing about resuming"
        );
    }

    #[test]
    fn a_single_job_campaign_names_no_instance_at_all() {
        assert!(
            instance_plan(1).is_empty(),
            "-M on a lone fuzzer costs trimming and buys nothing, so one job stays the plain single-instance invocation it already was"
        );
        assert!(instance_plan(0).is_empty());
        let args = options().invocation().args;
        assert!(!args.contains(&ARG_MAIN.to_owned()) && !args.contains(&ARG_SECONDARY.to_owned()));
    }

    #[test]
    fn a_parallel_plan_has_exactly_one_main_and_unique_names() {
        let plan = instance_plan(5);
        assert_eq!(plan.len(), 5);
        assert_eq!(
            plan.iter().filter(|instance| instance.is_main()).count(),
            1,
            "afl-fuzz syncs through a single main; a second one would leave two queues claiming to be authoritative"
        );
        let mut names: Vec<&str> = plan.iter().map(Instance::name).collect();
        names.sort_unstable();
        let unique = names.len();
        names.dedup();
        assert_eq!(
            names.len(),
            unique,
            "every -M/-S name has to be unique or the instances collide in one output directory"
        );
    }

    #[test]
    fn the_main_instance_carries_the_final_sync_afl_documents() {
        let mut options = options();
        options.instance = Some(Instance::Main(MAIN_INSTANCE.to_owned()));
        let invocation = options.invocation();
        assert!(invocation.args.windows(2).any(|pair| pair[0] == ARG_MAIN));
        assert!(
            invocation.envs.iter().any(|(key, _)| key == ENV_FINAL_SYNC),
            "without a final sync the main's queue can miss what the secondaries found just before the deadline"
        );
    }

    #[test]
    fn a_secondary_carries_a_power_schedule_and_no_final_sync() {
        let mut options = options();
        options.instance = Some(Instance::Secondary {
            name: "secondary1".to_owned(),
            schedule: "fast".to_owned(),
        });
        let invocation = options.invocation();
        let args = invocation.args;
        assert!(args.windows(2).any(|pair| pair[0] == ARG_SECONDARY));
        assert!(
            args.windows(2)
                .any(|pair| pair[0] == ARG_SCHEDULE && pair[1] == "fast"),
            "-p is the power schedule and -P is the mutation strategy; they are different flags that share value names"
        );
        assert!(!invocation.envs.iter().any(|(key, _)| key == ENV_FINAL_SYNC));
    }

    #[test]
    fn secondaries_vary_their_schedules_rather_than_all_running_the_default() {
        let plan = instance_plan(4);
        let schedules: Vec<&str> = plan
            .iter()
            .filter_map(|instance| match instance {
                Instance::Secondary { schedule, .. } => Some(schedule.as_str()),
                Instance::Main(_) => None,
            })
            .collect();
        assert_eq!(schedules.len(), 3);
        let mut unique = schedules.clone();
        unique.sort_unstable();
        unique.dedup();
        assert_eq!(
            unique.len(),
            schedules.len(),
            "AFL++ recommends running each secondary on a different power schedule; identical secondaries would explore the same way and waste the cores"
        );
        for schedule in schedules {
            assert!(
                SECONDARY_SCHEDULES.contains(&schedule),
                "{schedule} is not one of the schedules afl-fuzz accepts, and an unknown -p value stops the campaign at startup"
            );
        }
    }

    #[test]
    fn combined_stats_add_the_work_and_never_add_the_coverage() {
        let mut first = FuzzerStats {
            execs_done: 100,
            execs_per_sec: 10.0,
            saved_crashes: 2,
            bitmap_coverage_pct: 5.0,
            edges_found: 500,
            total_edges: 1000,
            afl_version: "5.02c".to_owned(),
        };
        let second = FuzzerStats {
            execs_done: 50,
            execs_per_sec: 4.0,
            saved_crashes: 3,
            bitmap_coverage_pct: 6.0,
            edges_found: 600,
            ..first.clone()
        };
        first.afl_version = "5.02c".to_owned();
        let combined = combine_stats(&[first, second]).expect("two instances combine");
        assert_eq!(combined.execs_done, 150);
        assert_eq!(combined.saved_crashes, 5);
        assert_eq!(
            combined.edges_found, 600,
            "instances share one coverage map and sync, so adding their edge counts would report coverage the campaign never had; the best instance is an honest lower bound on the union"
        );
        assert_eq!(combined.total_edges, 1000);
    }

    #[test]
    fn combining_nothing_yields_nothing_rather_than_a_zeroed_campaign() {
        assert_eq!(combine_stats(&[]), None);
    }

    #[test]
    fn each_dictionary_becomes_its_own_flag() {
        let mut options = options();
        options.dictionaries = vec![PathBuf::from("/d/png.dict"), PathBuf::from("/d/exif.dict")];
        let args = options.invocation().args;
        assert_eq!(
            args.windows(2)
                .filter(|pair| pair[0] == ARG_DICTIONARY)
                .count(),
            2
        );
        assert!(args.contains(&"/d/png.dict".to_owned()));
        assert!(args.contains(&"/d/exif.dict".to_owned()));
    }

    #[test]
    fn a_fifth_dictionary_never_reaches_the_command_line() {
        let mut options = options();
        options.dictionaries = (0..6)
            .map(|index| PathBuf::from(format!("/d/{index}.dict")))
            .collect();
        let args = options.invocation().args;
        assert_eq!(
            args.iter().filter(|arg| *arg == ARG_DICTIONARY).count(),
            dictionary::MAX_DICTIONARIES,
            "afl-fuzz FATALs on the fifth -x, so a caller that assembled too many must be truncated here rather than killing the campaign at startup"
        );
    }

    #[test]
    fn no_dictionary_means_no_flag_at_all() {
        let args = options().invocation().args;
        assert!(
            !args.contains(&ARG_DICTIONARY.to_owned()),
            "an empty -x would be a startup error, so the flag has to be absent rather than present and blank"
        );
    }

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

    #[test]
    fn invocation_uses_afl_fuzz_with_input_and_output() {
        let inv = options().invocation();
        assert_eq!(inv.program, AFL_FUZZ_BIN);
        let i = inv.args.iter().position(|a| a == ARG_INPUT).unwrap();
        assert_eq!(inv.args[i + 1], "/corpus");
        let o = inv.args.iter().position(|a| a == ARG_OUTPUT).unwrap();
        assert_eq!(inv.args[o + 1], "/findings");
    }

    #[test]
    fn invocation_disables_memory_limit_for_asan() {
        let inv = options().invocation();
        let m = inv.args.iter().position(|a| a == ARG_MEMORY).unwrap();
        assert_eq!(inv.args[m + 1], MEM_LIMIT_UNLIMITED);
    }

    #[test]
    fn invocation_passes_cmplog_binary() {
        let inv = options().invocation();
        let c = inv.args.iter().position(|a| a == ARG_CMPLOG).unwrap();
        assert_eq!(inv.args[c + 1], "/out/cmplog/harness");
    }

    #[test]
    fn invocation_omits_cmplog_when_absent() {
        let mut opts = options();
        opts.cmplog = None;
        let inv = opts.invocation();
        assert!(!inv.args.iter().any(|a| a == ARG_CMPLOG));
    }

    #[test]
    fn invocation_puts_target_after_separator() {
        let inv = options().invocation();
        let sep = inv.args.iter().position(|a| a == ARG_SEPARATOR).unwrap();
        assert_eq!(inv.args[sep + 1], "/out/afl/harness");
        assert_eq!(inv.args.len(), sep + 2);
    }

    #[test]
    fn invocation_encodes_duration_in_seconds() {
        let inv = options().invocation();
        let v = inv.args.iter().position(|a| a == ARG_DURATION).unwrap();
        assert_eq!(inv.args[v + 1], "60");
    }

    #[test]
    fn invocation_omits_duration_when_unbounded() {
        let mut opts = options();
        opts.duration = None;
        let inv = opts.invocation();
        assert!(!inv.args.iter().any(|a| a == ARG_DURATION));
    }

    #[test]
    fn invocation_honours_skip_deterministic_flag() {
        let inv = options().invocation();
        assert!(inv.args.iter().any(|a| a == ARG_SKIP_DETERMINISTIC));
        let mut opts = options();
        opts.skip_deterministic = false;
        assert!(
            !opts
                .invocation()
                .args
                .iter()
                .any(|a| a == ARG_SKIP_DETERMINISTIC)
        );
    }

    #[test]
    fn invocation_sets_container_safe_environment() {
        let inv = options().invocation();
        for key in [
            ENV_SKIP_CPUFREQ,
            ENV_NO_AFFINITY,
            ENV_NO_UI,
            ENV_MISSING_CRASHES,
        ] {
            assert!(
                inv.envs.iter().any(|(k, v)| k == key && v == ENV_ENABLED),
                "missing env {key}"
            );
        }
    }

    #[test]
    fn invocation_sets_bench_until_crash_only_when_requested() {
        let inv = options().invocation();
        assert!(inv.envs.iter().any(|(k, _)| k == ENV_BENCH_UNTIL_CRASH));
        let mut opts = options();
        opts.bench_until_crash = false;
        assert!(
            !opts
                .invocation()
                .envs
                .iter()
                .any(|(k, _)| k == ENV_BENCH_UNTIL_CRASH)
        );
    }

    #[test]
    fn discover_finds_crash_inputs_and_ignores_readme() {
        let findings = scratch("discover");
        let dir = crashes_dir(&findings);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("README.txt"), "not a crash").unwrap();
        std::fs::write(dir.join("id:000001,sig:11,src:000007"), b"second").unwrap();
        std::fs::write(dir.join("id:000000,sig:06,src:000000"), b"first").unwrap();

        let found = discover_crash_inputs(&findings).unwrap();
        assert_eq!(found.len(), 2);
        let names: Vec<String> = found
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert!(names.iter().all(|n| n.starts_with(CRASH_PREFIX)));
        assert_eq!(names[0], "id:000000,sig:06,src:000000");
    }

    #[test]
    fn discover_returns_empty_when_no_crashes_directory() {
        let findings = scratch("empty");
        assert!(discover_crash_inputs(&findings).unwrap().is_empty());
    }

    fn instance_with_stats(findings: &Path, name: &str, body: &str) {
        let dir = findings.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(STATS_FILE_NAME), body).unwrap();
    }

    #[test]
    fn stats_are_readable_from_a_parallel_campaign_that_has_no_default_instance() {
        let findings = scratch("parallel-stats");
        instance_with_stats(&findings, MAIN_INSTANCE, "execs_done : 41\n");
        instance_with_stats(&findings, "secondary1", "execs_done : 7\n");
        assert!(
            !findings.join(DEFAULT_INSTANCE).is_dir(),
            "the fixture must isolate the signal: a parallel campaign names its instances main and secondaryN, and never creates default"
        );

        let text = read_stats_text(&findings).expect(
            "a campaign run with --jobs > 1 writes no default/ directory, so reading stats from a hardcoded default path fails on every parallel run - which is how lisdex is documented to be run",
        );
        assert!(
            text.contains("41"),
            "and it must read the MAIN instance, not a secondary"
        );
    }

    #[test]
    fn a_single_instance_campaign_still_reads_its_default_directory() {
        let findings = scratch("single-stats");
        instance_with_stats(&findings, DEFAULT_INSTANCE, "execs_done : 99\n");
        let text = read_stats_text(&findings).unwrap();
        assert!(
            text.contains("99"),
            "afl-fuzz with no -M/-S writes default/, and that path must keep working"
        );
    }

    #[test]
    fn stats_from_an_empty_findings_directory_are_an_error_not_a_silent_default() {
        let findings = scratch("no-instance");
        assert!(
            matches!(
                read_stats_text(&findings),
                Err(RunnerError::NoInstance { .. })
            ),
            "no instance wrote stats, and inventing a reading from that is worse than saying so"
        );
    }
}