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 👇

23.1 KB
Raw Blame
// ©AngelaMos | 2026
// oracle.rs

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

use crate::coverage::EdgeSet;

pub const MIN_INTER_SEED_DIVERGENCE: usize = 5;
pub const MIN_GLOBAL_NOVELTY: usize = 1;
pub const MIN_VALID_SEEDS: usize = 2;
pub const EXEC_TIMEOUT_SECS: u64 = 5;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunStatus {
    Clean,
    NonZeroExit,
    TimedOut,
}

#[derive(Debug, Clone)]
pub struct SeedRun {
    pub seed: PathBuf,
    pub map: EdgeSet,
    pub status: RunStatus,
    pub stderr: String,
}

#[derive(Debug, Clone, Default)]
pub struct Observation {
    pub valid: Vec<SeedRun>,
    pub invalid: Vec<SeedRun>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Rejection {
    CompileFailed {
        diagnostic: String,
    },
    TooFewValidSeeds {
        have: usize,
    },
    CrashedOnSeed {
        seed: PathBuf,
    },
    TimedOutOnSeed {
        seed: PathBuf,
    },
    StderrOnValidSeed {
        seed: PathBuf,
        text: String,
        missing: bool,
    },
    NoInterSeedDivergence {
        best: usize,
    },
    ConstantCoverageIncrease {
        amount: usize,
    },
    InvalidSeedsIndistinguishable,
    NoGlobalNovelty,
    ParentMapIncomplete {
        seed: PathBuf,
    },
    ParentMapIncomparable {
        seed: PathBuf,
        shared: usize,
        parent: usize,
    },
}

impl std::fmt::Display for Rejection {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Rejection::CompileFailed { diagnostic } => {
                write!(formatter, "does not compile: {diagnostic}")
            }
            Rejection::TooFewValidSeeds { have } => write!(
                formatter,
                "{have} valid seed(s); the coverage oracle needs at least {MIN_VALID_SEEDS}"
            ),
            Rejection::CrashedOnSeed { seed } => {
                write!(formatter, "crashed on seed {}", seed.display())
            }
            Rejection::TimedOutOnSeed { seed } => write!(
                formatter,
                "exceeded {EXEC_TIMEOUT_SECS}s on seed {}",
                seed.display()
            ),
            Rejection::StderrOnValidSeed {
                seed,
                text,
                missing: false,
            } => write!(
                formatter,
                "valid seed {} is the only one that wrote {text:?} to stderr",
                seed.display()
            ),
            Rejection::StderrOnValidSeed {
                seed,
                text,
                missing: true,
            } => write!(
                formatter,
                "valid seed {} is missing the stderr line {text:?} that the other seeds all wrote",
                seed.display()
            ),
            Rejection::NoInterSeedDivergence { best } => write!(
                formatter,
                "no two valid seeds diverge by more than {MIN_INTER_SEED_DIVERGENCE} edges (best {best})"
            ),
            Rejection::ConstantCoverageIncrease { amount } => write!(
                formatter,
                "every seed gained the same {amount} edges, so the added call ignores its input"
            ),
            Rejection::InvalidSeedsIndistinguishable => write!(
                formatter,
                "invalid seeds cover everything the valid seeds do, so the harness does not discriminate"
            ),
            Rejection::NoGlobalNovelty => write!(
                formatter,
                "adds no edge that an already-accepted harness does not already reach"
            ),
            Rejection::ParentMapIncomplete { seed } => write!(
                formatter,
                "the parent coverage map has no entry for seed {} - the linearity oracle cannot run and must not silently pass",
                seed.display()
            ),
            Rejection::ParentMapIncomparable {
                seed,
                shared,
                parent,
            } => write!(
                formatter,
                "on seed {} the shorter sequence reached {parent} edge(s) and the extended one shares only {shared} of them, so the two maps do not describe the same numbering and their difference is not a coverage gain; an LTO-bitcode archive is re-instrumented at every link, which renumbers every edge when the harness changes size - the oracle bench needs an archive whose instrumentation was fixed when the LIBRARY was built",
                seed.display()
            ),
        }
    }
}

pub fn judge_execution(observation: &Observation) -> Result<(), Rejection> {
    // A crash is diagnosed before the seed count, so a harness that dies on its first
    // seed is reported as crashing rather than as an undersized corpus.
    for run in observation.valid.iter().chain(&observation.invalid) {
        match run.status {
            RunStatus::TimedOut => {
                return Err(Rejection::TimedOutOnSeed {
                    seed: run.seed.clone(),
                });
            }
            RunStatus::NonZeroExit => {
                return Err(Rejection::CrashedOnSeed {
                    seed: run.seed.clone(),
                });
            }
            RunStatus::Clean => {}
        }
    }
    if observation.valid.len() < MIN_VALID_SEEDS {
        return Err(Rejection::TooFewValidSeeds {
            have: observation.valid.len(),
        });
    }
    judge_stderr(&observation.valid)
}

fn stderr_lines(run: &SeedRun) -> BTreeSet<&str> {
    run.stderr
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .collect()
}

pub fn judge_stderr(valid: &[SeedRun]) -> Result<(), Rejection> {
    if valid.is_empty() {
        return Ok(());
    }
    // D4 rejects any stderr on a valid seed, which rejects every harness here because
    // magma prints an unconditional preamble. The rule is therefore differential: a line
    // every seed writes is a runtime preamble, and only a line that varies is a warning.
    let mut carriers: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
    for (index, run) in valid.iter().enumerate() {
        for line in stderr_lines(run) {
            carriers.entry(line).or_default().push(index);
        }
    }
    for (line, present) in carriers {
        if present.len() == valid.len() {
            continue;
        }
        // Blame the minority: a line two of three seeds wrote is an anomaly on the third,
        // not on whichever seed the iteration happened to reach first.
        let missing = present.len() * 2 > valid.len();
        let culprit = if missing {
            (0..valid.len()).find(|index| !present.contains(index))
        } else {
            present.first().copied()
        };
        let Some(culprit) = culprit else { continue };
        return Err(Rejection::StderrOnValidSeed {
            seed: valid[culprit].seed.clone(),
            text: line.to_owned(),
            missing,
        });
    }
    Ok(())
}

pub fn judge_inter_seed_divergence(valid: &[SeedRun]) -> Result<(), Rejection> {
    if valid.len() < MIN_VALID_SEEDS {
        return Err(Rejection::TooFewValidSeeds { have: valid.len() });
    }
    let mut best = 0;
    for (index, left) in valid.iter().enumerate() {
        for right in &valid[index + 1..] {
            let divergence = left.map.divergence(&right.map);
            best = best.max(divergence);
            if divergence > MIN_INTER_SEED_DIVERGENCE {
                return Ok(());
            }
        }
    }
    Err(Rejection::NoInterSeedDivergence { best })
}

pub fn judge_linear_increase(
    valid: &[SeedRun],
    parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
) -> Result<(), Rejection> {
    let Some(parent) = parent else {
        return Ok(());
    };
    if valid.len() < MIN_VALID_SEEDS {
        return Ok(());
    }
    let mut gains = Vec::with_capacity(valid.len());
    for run in valid {
        let Some(before) = parent.get(&run.seed) else {
            return Err(Rejection::ParentMapIncomplete {
                seed: run.seed.clone(),
            });
        };
        // A DELTA needs the shorter sequence's coverage to be contained in the longer one's.
        // The extended body is the parent's body with further calls spliced in before the
        // teardown, so on the same seed it must execute every block the parent did - and if it
        // does not, `novel_against` counts what appeared while ignoring what vanished, which is
        // not a gain in either direction.
        //
        // Measured, and it is why this guard exists rather than a comment: with an LTO-bitcode
        // archive, `afl-clang-lto` re-instruments the WHOLE program at every link, so appending
        // one call to the harness renumbered every library edge - a synthetic parent's
        // {13, 15, 32} became the child's {12, 14, 31, 35} for the same seed, sharing NOTHING.
        // The per-seed gains then vary with map size rather than with the input, and a call
        // doing identical work on every seed was ACCEPTED. With the same library pre-instrumented
        // by `afl-clang-fast` the parent's 15 edges were all 15 present in the child's 17.
        if !run.map.covers(before) {
            let shared = before.len() - before.novel_against(&run.map);
            return Err(Rejection::ParentMapIncomparable {
                seed: run.seed.clone(),
                shared,
                parent: before.len(),
            });
        }
        gains.push(run.map.novel_against(before));
    }
    let first = gains[0];
    if gains.iter().all(|gain| *gain == first) {
        return Err(Rejection::ConstantCoverageIncrease { amount: first });
    }
    Ok(())
}

pub fn judge_invalid_differential(observation: &Observation) -> Result<(), Rejection> {
    if observation.invalid.is_empty() {
        return Ok(());
    }
    let valid_union = EdgeSet::union_of(observation.valid.iter().map(|run| &run.map));
    let discriminates = observation
        .invalid
        .iter()
        .any(|run| !run.map.covers(&valid_union));
    if discriminates {
        Ok(())
    } else {
        Err(Rejection::InvalidSeedsIndistinguishable)
    }
}

pub fn judge_global_novelty(candidate: &EdgeSet, accepted: &EdgeSet) -> Result<(), Rejection> {
    if candidate.novel_against(accepted) >= MIN_GLOBAL_NOVELTY {
        Ok(())
    } else {
        Err(Rejection::NoGlobalNovelty)
    }
}

pub fn judge(
    observation: &Observation,
    parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
    accepted: &EdgeSet,
) -> Result<EdgeSet, Rejection> {
    judge_execution(observation)?;
    judge_inter_seed_divergence(&observation.valid)?;
    judge_linear_increase(&observation.valid, parent)?;
    judge_invalid_differential(observation)?;
    let reached = EdgeSet::union_of(
        observation
            .valid
            .iter()
            .chain(&observation.invalid)
            .map(|run| &run.map),
    );
    judge_global_novelty(&reached, accepted)?;
    Ok(reached)
}

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

    fn run(name: &str, edges: &[u32]) -> SeedRun {
        SeedRun {
            seed: PathBuf::from(name),
            map: edges.iter().copied().collect(),
            status: RunStatus::Clean,
            stderr: String::new(),
        }
    }

    fn spread() -> Vec<SeedRun> {
        vec![run("a", &[1, 2, 3, 4, 5, 6, 7]), run("b", &[1])]
    }

    #[test]
    fn a_clean_pair_of_seeds_passes_execution() {
        let observation = Observation {
            valid: spread(),
            invalid: Vec::new(),
        };
        assert!(judge_execution(&observation).is_ok());
    }

    #[test]
    fn one_valid_seed_cannot_be_judged() {
        let observation = Observation {
            valid: vec![run("a", &[1])],
            invalid: Vec::new(),
        };
        assert_eq!(
            judge_execution(&observation),
            Err(Rejection::TooFewValidSeeds { have: 1 })
        );
    }

    #[test]
    fn a_crash_on_any_seed_rejects() {
        let mut valid = spread();
        valid[1].status = RunStatus::NonZeroExit;
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert_eq!(
            judge_execution(&observation),
            Err(Rejection::CrashedOnSeed {
                seed: PathBuf::from("b")
            })
        );
    }

    #[test]
    fn a_crash_on_an_invalid_seed_also_rejects() {
        let mut invalid = vec![run("bad", &[9])];
        invalid[0].status = RunStatus::NonZeroExit;
        let observation = Observation {
            valid: spread(),
            invalid,
        };
        assert!(judge_execution(&observation).is_err());
    }

    #[test]
    fn a_harness_that_dies_on_its_first_seed_is_reported_as_crashing() {
        let mut only = vec![run("a", &[1])];
        only[0].status = RunStatus::NonZeroExit;
        let observation = Observation {
            valid: only,
            invalid: Vec::new(),
        };
        assert_eq!(
            judge_execution(&observation),
            Err(Rejection::CrashedOnSeed {
                seed: PathBuf::from("a")
            }),
            "observation stops at the first dirty seed, so the count must not mask the crash"
        );
    }

    #[test]
    fn a_timeout_is_reported_as_a_timeout_not_a_crash() {
        let mut valid = spread();
        valid[0].status = RunStatus::TimedOut;
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert_eq!(
            judge_execution(&observation),
            Err(Rejection::TimedOutOnSeed {
                seed: PathBuf::from("a")
            })
        );
    }

    #[test]
    fn stderr_on_a_valid_seed_rejects() {
        let mut valid = spread();
        valid[0].stderr = "libpng warning: iCCP".to_owned();
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert!(matches!(
            judge_execution(&observation),
            Err(Rejection::StderrOnValidSeed { .. })
        ));
    }

    #[test]
    fn stderr_on_an_invalid_seed_is_allowed() {
        let mut invalid = vec![run("bad", &[9])];
        invalid[0].stderr = "libpng error: bad signature".to_owned();
        let observation = Observation {
            valid: spread(),
            invalid,
        };
        assert!(judge_execution(&observation).is_ok());
    }

    #[test]
    fn a_runtime_preamble_present_on_every_seed_is_not_a_rejection() {
        let mut valid = spread();
        for run in &mut valid {
            run.stderr = "Monitor not running. Canaries will be disabled.".to_owned();
        }
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert!(judge_execution(&observation).is_ok());
    }

    #[test]
    fn a_seed_specific_warning_on_top_of_a_preamble_still_rejects() {
        let mut valid = spread();
        valid[0].stderr = "Monitor not running.\nlibpng warning: iCCP".to_owned();
        valid[1].stderr = "Monitor not running.".to_owned();
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert_eq!(
            judge_execution(&observation),
            Err(Rejection::StderrOnValidSeed {
                seed: PathBuf::from("a"),
                text: "libpng warning: iCCP".to_owned(),
                missing: false
            })
        );
    }

    #[test]
    fn the_seed_that_lacks_a_near_universal_line_is_the_one_blamed() {
        let mut valid = vec![
            run("a", &[1, 2, 3, 4, 5, 6, 7]),
            run("b", &[1]),
            run("c", &[2]),
        ];
        valid[1].stderr = "preamble".to_owned();
        valid[2].stderr = "preamble".to_owned();
        assert_eq!(
            judge_stderr(&valid),
            Err(Rejection::StderrOnValidSeed {
                seed: PathBuf::from("a"),
                text: "preamble".to_owned(),
                missing: true
            }),
            "two of three seeds wrote the line, so the anomaly is the seed that did not"
        );
    }

    #[test]
    fn whitespace_only_stderr_is_not_stderr() {
        let mut valid = spread();
        valid[0].stderr = "  \n".to_owned();
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert!(judge_execution(&observation).is_ok());
    }

    #[test]
    fn seeds_diverging_by_more_than_the_floor_pass() {
        assert!(judge_inter_seed_divergence(&spread()).is_ok());
    }

    #[test]
    fn a_stub_harness_that_ignores_its_input_is_rejected() {
        let identical = vec![run("a", &[1, 2, 3]), run("b", &[1, 2, 3])];
        assert_eq!(
            judge_inter_seed_divergence(&identical),
            Err(Rejection::NoInterSeedDivergence { best: 0 })
        );
    }

    #[test]
    fn divergence_of_exactly_the_floor_is_not_enough() {
        let borderline = vec![run("a", &[1, 2, 3, 4, 5, 6]), run("b", &[1])];
        assert_eq!(
            judge_inter_seed_divergence(&borderline),
            Err(Rejection::NoInterSeedDivergence {
                best: MIN_INTER_SEED_DIVERGENCE
            })
        );
    }

    #[test]
    fn divergence_is_satisfied_by_any_pair_not_only_neighbours() {
        let seeds = vec![
            run("a", &[1]),
            run("b", &[1]),
            run("c", &[1, 2, 3, 4, 5, 6, 7]),
        ];
        assert!(judge_inter_seed_divergence(&seeds).is_ok());
    }

    #[test]
    fn no_parent_means_no_linearity_verdict() {
        assert!(judge_linear_increase(&spread(), None).is_ok());
    }

    #[test]
    fn an_identical_gain_across_every_seed_rejects() {
        let parent = BTreeMap::from([
            (PathBuf::from("a"), [1, 2].into_iter().collect()),
            (PathBuf::from("b"), [3, 4].into_iter().collect()),
        ]);
        let valid = vec![run("a", &[1, 2, 90]), run("b", &[3, 4, 91])];
        assert_eq!(
            judge_linear_increase(&valid, Some(&parent)),
            Err(Rejection::ConstantCoverageIncrease { amount: 1 })
        );
    }

    #[test]
    fn a_call_that_adds_nothing_anywhere_rejects() {
        let parent = BTreeMap::from([
            (PathBuf::from("a"), [1, 2].into_iter().collect()),
            (PathBuf::from("b"), [3, 4].into_iter().collect()),
        ]);
        let valid = vec![run("a", &[1, 2]), run("b", &[3, 4])];
        assert_eq!(
            judge_linear_increase(&valid, Some(&parent)),
            Err(Rejection::ConstantCoverageIncrease { amount: 0 })
        );
    }

    // The liveness guard on the oracle itself. Without it the ID renumbering an LTO relink
    // produces reads as a per-seed-varying gain, which is the ONE answer this oracle must never
    // give by accident: it means "the added call depends on its input" and it accepts.
    #[test]
    fn a_parent_map_the_child_does_not_contain_cannot_be_a_delta() {
        let parent = BTreeMap::from([
            (PathBuf::from("a"), [13, 15, 32].into_iter().collect()),
            (PathBuf::from("b"), [13, 15, 32, 40].into_iter().collect()),
        ]);
        // The measured renumbering: every ID shifted by one and one new edge appeared.
        let valid = vec![run("a", &[12, 14, 31, 35]), run("b", &[12, 14, 31, 35, 39])];
        assert_eq!(
            judge_linear_increase(&valid, Some(&parent)),
            Err(Rejection::ParentMapIncomparable {
                seed: PathBuf::from("a"),
                shared: 0,
                parent: 3,
            })
        );
    }

    // Isolates the guard from the gain test: the same shapes, one edge of the parent's missing.
    // A guard keyed on "shares nothing" would pass this and still accept a bad delta.
    #[test]
    fn losing_one_edge_of_the_parents_coverage_is_enough_to_refuse_the_verdict() {
        let parent = BTreeMap::from([
            (PathBuf::from("a"), [1, 2, 3].into_iter().collect()),
            (PathBuf::from("b"), [3, 4].into_iter().collect()),
        ]);
        let valid = vec![run("a", &[1, 2, 90, 91]), run("b", &[3, 4, 92])];
        assert_eq!(
            judge_linear_increase(&valid, Some(&parent)),
            Err(Rejection::ParentMapIncomparable {
                seed: PathBuf::from("a"),
                shared: 2,
                parent: 3,
            })
        );
    }

    #[test]
    fn an_input_dependent_gain_passes() {
        let parent = BTreeMap::from([
            (PathBuf::from("a"), [1, 2].into_iter().collect()),
            (PathBuf::from("b"), [3, 4].into_iter().collect()),
        ]);
        let valid = vec![run("a", &[1, 2, 90, 91, 92]), run("b", &[3, 4, 93])];
        assert!(judge_linear_increase(&valid, Some(&parent)).is_ok());
    }

    #[test]
    fn invalid_seeds_covering_everything_valid_seeds_do_rejects() {
        let observation = Observation {
            valid: spread(),
            invalid: vec![run("bad", &[1, 2, 3, 4, 5, 6, 7, 8])],
        };
        assert_eq!(
            judge_invalid_differential(&observation),
            Err(Rejection::InvalidSeedsIndistinguishable)
        );
    }

    #[test]
    fn an_invalid_seed_missing_valid_coverage_discriminates() {
        let observation = Observation {
            valid: spread(),
            invalid: vec![run("bad", &[1])],
        };
        assert!(judge_invalid_differential(&observation).is_ok());
    }

    #[test]
    fn without_invalid_seeds_the_differential_is_skipped() {
        let observation = Observation {
            valid: spread(),
            invalid: Vec::new(),
        };
        assert!(judge_invalid_differential(&observation).is_ok());
    }

    #[test]
    fn a_candidate_reaching_nothing_new_is_rejected() {
        let candidate: EdgeSet = [1, 2].into_iter().collect();
        let accepted: EdgeSet = [1, 2, 3].into_iter().collect();
        assert_eq!(
            judge_global_novelty(&candidate, &accepted),
            Err(Rejection::NoGlobalNovelty)
        );
    }

    #[test]
    fn a_single_new_edge_is_enough_novelty() {
        let candidate: EdgeSet = [1, 2, 99].into_iter().collect();
        let accepted: EdgeSet = [1, 2, 3].into_iter().collect();
        assert!(judge_global_novelty(&candidate, &accepted).is_ok());
    }

    #[test]
    fn the_first_candidate_is_novel_against_an_empty_world() {
        let candidate: EdgeSet = [1].into_iter().collect();
        assert!(judge_global_novelty(&candidate, &EdgeSet::new()).is_ok());
    }

    #[test]
    fn judge_runs_every_oracle_and_returns_the_reached_map() {
        let observation = Observation {
            valid: spread(),
            invalid: vec![run("bad", &[1])],
        };
        let reached = judge(&observation, None, &EdgeSet::new()).expect("all oracles pass");
        assert_eq!(reached.len(), 7);
    }

    #[test]
    fn judge_reports_the_earliest_failing_oracle() {
        let mut valid = spread();
        valid[0].status = RunStatus::NonZeroExit;
        let observation = Observation {
            valid,
            invalid: Vec::new(),
        };
        assert!(matches!(
            judge(&observation, None, &EdgeSet::new()),
            Err(Rejection::CrashedOnSeed { .. })
        ));
    }

    #[test]
    fn a_stub_harness_is_rejected_by_judge_even_when_it_runs_clean() {
        let observation = Observation {
            valid: vec![run("a", &[1, 2, 3]), run("b", &[1, 2, 3])],
            invalid: Vec::new(),
        };
        assert!(matches!(
            judge(&observation, None, &EdgeSet::new()),
            Err(Rejection::NoInterSeedDivergence { .. })
        ));
    }
}