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 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
// ©AngelaMos | 2026
// search.rs
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use crate::coverage::EdgeSet;
use crate::emit;
use crate::plan::HarnessPlan;
use crate::synth::{self, Extension, Refusal};
use crate::verify::{Verdict, VerifyError};
// The bench a trial runs on. `verify::Bench` is the real one - compile, run every seed,
// showmap, judge - and the tests supply a fake, which is the only way the accumulation itself
// can be tested: every property below (a survivor set that grows, a variant loop that stops at
// the first acceptance, an extension judged against its parent's per-seed maps) needs a
// controlled verdict rather than a real compiler.
pub trait Bench {
fn verify(
&self,
source: &Path,
label: &str,
parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
accepted: &EdgeSet,
) -> Result<Verdict, VerifyError>;
}
impl Bench for crate::verify::Bench {
fn verify(
&self,
source: &Path,
label: &str,
parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
accepted: &EdgeSet,
) -> Result<Verdict, VerifyError> {
crate::verify::Bench::verify(self, source, label, parent, accepted)
}
}
// One ranked candidate, planned or refused. The refusals travel WITH the plans rather than in
// a list beside them so the evidence trail stays in ranking order: a libarchive user handed a
// date parser needs to read down the list and see the archive readers above it refuse.
pub enum Attempt {
Planned {
name: String,
variants: Vec<HarnessPlan>,
steps: Vec<Extension>,
},
Refused {
name: String,
refusal: Refusal,
},
}
// What the oracles decided about one accepted entry point. `judged_against` is the size of the
// accepted set at the moment this harness was judged: 0 means it was first and oracle 4 could
// only reject a harness reaching nothing, which is the weak form B51 described. `steps` is how
// far the author's own sequence was followed past the entry point, and it is what makes oracle
// 3b's verdict a fact about this survivor rather than about the run.
pub struct Survivor {
pub name: String,
pub plan: HarnessPlan,
pub verdict: Verdict,
pub edges: usize,
pub novel: usize,
pub judged_against: usize,
pub variants: usize,
pub steps: usize,
}
#[derive(Default)]
pub struct Outcome {
pub survivors: Vec<Survivor>,
pub rejected: Vec<String>,
pub accepted: EdgeSet,
}
// Only the VALID seeds. `judge_linear_increase` compares per-seed gains and an invalid seed is
// allowed to crash the library's error path, so a map from one would put a gain in the vector
// that says nothing about how the added call reads its input.
fn parent_maps(verdict: &Verdict) -> BTreeMap<PathBuf, EdgeSet> {
verdict
.observation
.as_ref()
.map_or_else(BTreeMap::new, |observation| {
observation
.valid
.iter()
.map(|run| (run.seed.clone(), run.map.clone()))
.collect()
})
}
fn write(dir: &Path, label: &str, plan: &HarnessPlan) -> Result<PathBuf, std::io::Error> {
let filename = format!("{label}.c");
let path = dir.join(&filename);
std::fs::write(&path, emit::render(plan, &filename))?;
Ok(path)
}
// The upward climb, and the direction is the whole design. The parent is an ACCEPTED harness,
// never a truncation of one: D4's oracle 3b asks whether the added call raises every seed's
// coverage by the same constant, and the only honest baseline for that question is a sequence
// that already earned its place. Walking DOWN instead - judging the entry point against a
// prefix of the author's setup - would put the baseline below the floor the ranked source
// ladder established, where a harness that registers no format reads nothing at all.
//
// An accepted step REPLACES its parent as the survivor for this entry point rather than
// standing beside it. The extended body is the parent's body plus further calls, so it reaches
// everything the parent reached; keeping both would report one entry point twice and promote
// two files with the same name.
fn climb<B: Bench>(
outcome: &mut Outcome,
survivor: &mut Survivor,
steps: &[Extension],
bench: &B,
dir: &Path,
) -> Result<(), std::io::Error> {
let mut parent = parent_maps(&survivor.verdict);
let base = survivor.plan.clone();
for depth in 1..=steps.len() {
let label = format!("{}.up{depth}", survivor.name);
let plan = synth::extend(&base, &steps[..depth]);
let source = write(dir, &label, &plan)?;
let against = outcome.accepted.len();
let verdict = match bench.verify(&source, &label, Some(&parent), &outcome.accepted) {
Ok(verdict) => verdict,
Err(err) => {
outcome
.rejected
.push(format!(" {label} - could not be judged: {err}"));
return Ok(());
}
};
let (edges, novel) = match &verdict.outcome {
Ok(reached) => {
let novel = reached.novel_against(&outcome.accepted);
let edges = reached.len();
outcome.accepted.absorb(reached);
(edges, novel)
}
Err(rejection) => {
// Names the call that was appended, because "this harness was rejected" and
// "this harness plus THIS call was rejected" are different statements and only
// the second one tells the reader which call to stop appending.
outcome.rejected.push(format!(
" {label} - appending {} - {rejection}",
steps[depth - 1].function
));
return Ok(());
}
};
survivor.edges = edges;
survivor.novel = novel;
survivor.judged_against = against;
survivor.steps = depth;
survivor.plan = plan;
parent = parent_maps(&verdict);
survivor.verdict = verdict;
}
Ok(())
}
pub fn accumulate<B: Bench>(
attempts: &[Attempt],
bench: &B,
dir: &Path,
) -> Result<Outcome, std::io::Error> {
let mut outcome = Outcome::default();
for attempt in attempts {
let (name, variants, steps) = match attempt {
Attempt::Refused { name, refusal } => {
outcome
.rejected
.push(format!(" {name} - refused: {refusal}"));
continue;
}
Attempt::Planned {
name,
variants,
steps,
} => (name, variants, steps),
};
// Every variant is written before any is judged: the rejected ones are the evidence
// trail, and the gate uses them as ready-made negative controls.
let mut emitted = Vec::with_capacity(variants.len());
for (index, plan) in variants.iter().enumerate() {
let label = format!("{name}.v{index}");
let source = write(dir, &label, plan)?;
emitted.push((label, source));
}
for ((label, source), plan) in emitted.iter().zip(variants) {
// No parent at depth 0: oracle 3b measures a candidate against the shorter call
// sequence it EXTENDS, and variants run most-populated first, so no later variant
// extends an earlier one. Feeding it a sibling would reject the fallback for a
// constant gain of zero, which is true and meaningless.
let against = outcome.accepted.len();
let verdict = match bench.verify(source, label, None, &outcome.accepted) {
Ok(verdict) => verdict,
Err(err) => {
// One candidate's toolchain failure must not kill the other nineteen.
outcome
.rejected
.push(format!(" {label} - could not be judged: {err}"));
continue;
}
};
match &verdict.outcome {
Ok(reached) => {
let novel = reached.novel_against(&outcome.accepted);
let mut survivor = Survivor {
name: name.clone(),
plan: plan.clone(),
verdict: verdict.clone(),
edges: reached.len(),
novel,
judged_against: against,
variants: variants.len(),
steps: 0,
};
outcome.accepted.absorb(reached);
climb(&mut outcome, &mut survivor, steps, bench, dir)?;
outcome.survivors.push(survivor);
// Variants of ONE candidate are alternatives, not distinct harnesses:
// they call the same entry point with more or less of its context
// populated. Taking the first that survives and moving on is what makes
// the accumulated set a set of ENTRY POINTS.
break;
}
Err(rejection) => outcome.rejected.push(format!(" {label} - {rejection}")),
}
}
}
Ok(outcome)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::oracle::{Observation, Rejection, RunStatus, SeedRun};
use crate::plan::{Stmt, Value};
use std::cell::RefCell;
use std::collections::BTreeSet;
struct Call {
label: String,
parent: Option<Vec<PathBuf>>,
}
// Accepts whatever it is told to and records what it was asked. The recorded PARENT is the
// point: without it, a run that never passes the parent maps through looks identical to
// one that does, and oracle 3b is unreachable code either way.
struct Fake {
accept: BTreeSet<String>,
edges: BTreeMap<String, Vec<u32>>,
seeds: Vec<PathBuf>,
calls: RefCell<Vec<Call>>,
}
impl Fake {
fn new(accept: &[&str]) -> Self {
Self {
accept: accept.iter().map(|label| (*label).to_owned()).collect(),
edges: BTreeMap::new(),
seeds: vec![PathBuf::from("valid-a"), PathBuf::from("valid-b")],
calls: RefCell::new(Vec::new()),
}
}
fn reaching(mut self, label: &str, edges: &[u32]) -> Self {
self.edges.insert(label.to_owned(), edges.to_vec());
self
}
fn labels(&self) -> Vec<String> {
self.calls
.borrow()
.iter()
.map(|call| call.label.clone())
.collect()
}
fn parent_of(&self, label: &str) -> Option<Vec<PathBuf>> {
self.calls
.borrow()
.iter()
.find(|call| call.label == label)
.and_then(|call| call.parent.clone())
}
}
impl Bench for Fake {
fn verify(
&self,
source: &Path,
label: &str,
parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
_accepted: &EdgeSet,
) -> Result<Verdict, VerifyError> {
self.calls.borrow_mut().push(Call {
label: label.to_owned(),
parent: parent.map(|maps| maps.keys().cloned().collect()),
});
let reached: Vec<u32> = self
.edges
.get(label)
.cloned()
.unwrap_or_else(|| vec![1, 2, 3]);
let observation = Observation {
valid: self
.seeds
.iter()
.map(|seed| SeedRun {
seed: seed.clone(),
map: reached.iter().copied().collect::<EdgeSet>(),
status: RunStatus::Clean,
stderr: String::new(),
})
.collect(),
invalid: Vec::new(),
};
let outcome = if self.accept.contains(label) {
Ok(EdgeSet::from_iter(reached))
} else {
Err(Rejection::NoInterSeedDivergence { best: 0 })
};
Ok(Verdict {
label: label.to_owned(),
source: source.to_path_buf(),
binary: PathBuf::from("/dev/null"),
outcome,
observation: Some(observation),
})
}
}
fn scratch(label: &str) -> PathBuf {
let dir = lisdex_core::scratch::path(&format!("search-{label}"));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn planned(name: &str, variants: usize, steps: &[&str]) -> Attempt {
let plan = HarnessPlan::new(name).with(Stmt::Call {
function: name.to_owned(),
args: vec![Value::Data { cast: None }, Value::Size],
capture: None,
});
Attempt::Planned {
name: name.to_owned(),
variants: vec![plan; variants],
steps: steps
.iter()
.map(|function| Extension {
function: (*function).to_owned(),
declares: Vec::new(),
call: Stmt::Call {
function: (*function).to_owned(),
args: vec![Value::Local("ctx".to_owned())],
capture: None,
},
releases: Vec::new(),
})
.collect(),
}
}
#[test]
fn every_survivor_is_kept_so_the_accepted_set_grows() {
let dir = scratch("set");
let bench = Fake::new(&["one.v0", "two.v0"])
.reaching("one.v0", &[1, 2, 3])
.reaching("two.v0", &[3, 4, 5]);
let outcome = accumulate(
&[planned("one", 1, &[]), planned("two", 1, &[])],
&bench,
&dir,
)
.unwrap();
assert_eq!(outcome.survivors.len(), 2);
assert_eq!(outcome.accepted.len(), 5);
assert_eq!(outcome.survivors[0].judged_against, 0);
assert_eq!(
outcome.survivors[1].judged_against, 3,
"the second candidate must be judged against the first"
);
assert_eq!(outcome.survivors[1].novel, 2);
}
#[test]
fn only_the_first_surviving_variant_of_one_candidate_is_kept() {
let dir = scratch("variants");
let bench = Fake::new(&["one.v1"]);
let outcome = accumulate(&[planned("one", 3, &[])], &bench, &dir).unwrap();
assert_eq!(outcome.survivors.len(), 1);
assert_eq!(
bench.labels(),
vec!["one.v0", "one.v1"],
"the third variant must never be judged once the second survives"
);
}
#[test]
fn a_planner_refusal_is_reported_in_ranking_order() {
let dir = scratch("order");
let bench = Fake::new(&["two.v0"]);
let outcome = accumulate(
&[
Attempt::Refused {
name: "one".to_owned(),
refusal: Refusal::PathEntry,
},
planned("two", 1, &[]),
Attempt::Refused {
name: "three".to_owned(),
refusal: Refusal::NoDataInput,
},
],
&bench,
&dir,
)
.unwrap();
assert_eq!(outcome.rejected.len(), 2);
assert!(
outcome.rejected[0].contains("one"),
"{:?}",
outcome.rejected
);
assert!(
outcome.rejected[1].contains("three"),
"{:?}",
outcome.rejected
);
}
// The B51(b) plumbing, and the only test that can see it: oracle 3b is passed None at
// depth 0 and the accepted parent's per-seed maps at depth 1. A run that forgot to thread
// them through would still accept the extension and still report a survivor.
#[test]
fn an_extension_is_judged_against_its_parents_per_seed_maps() {
let dir = scratch("parent");
let bench = Fake::new(&["one.v0", "one.up1"])
.reaching("one.v0", &[1, 2])
.reaching("one.up1", &[1, 2, 7]);
let outcome = accumulate(&[planned("one", 1, &["further"])], &bench, &dir).unwrap();
assert_eq!(bench.parent_of("one.v0"), None, "depth 0 has no parent");
assert_eq!(
bench.parent_of("one.up1"),
Some(vec![PathBuf::from("valid-a"), PathBuf::from("valid-b")]),
"the extension must be judged against the parent's own seeds"
);
assert_eq!(outcome.survivors.len(), 1);
}
#[test]
fn an_accepted_extension_replaces_its_parent_as_the_survivor() {
let dir = scratch("replace");
let bench = Fake::new(&["one.v0", "one.up1"])
.reaching("one.v0", &[1, 2])
.reaching("one.up1", &[1, 2, 7]);
let outcome = accumulate(&[planned("one", 1, &["further"])], &bench, &dir).unwrap();
assert_eq!(outcome.survivors.len(), 1, "not one survivor per depth");
let survivor = &outcome.survivors[0];
assert_eq!(survivor.steps, 1);
assert_eq!(survivor.edges, 3);
assert_eq!(survivor.plan.extended, vec!["further".to_owned()]);
assert!(outcome.rejected.is_empty(), "{:?}", outcome.rejected);
}
#[test]
fn a_rejected_extension_leaves_the_parent_standing_and_names_the_call() {
let dir = scratch("reject");
let bench = Fake::new(&["one.v0"]).reaching("one.v0", &[1, 2]);
let outcome = accumulate(&[planned("one", 1, &["further"])], &bench, &dir).unwrap();
assert_eq!(outcome.survivors.len(), 1);
assert_eq!(outcome.survivors[0].steps, 0);
assert_eq!(outcome.survivors[0].edges, 2);
assert_eq!(outcome.rejected.len(), 1);
assert!(
outcome.rejected[0].contains("appending further"),
"{:?}",
outcome.rejected
);
}
#[test]
fn the_climb_stops_at_the_first_rejected_step() {
let dir = scratch("stop");
let bench = Fake::new(&["one.v0", "one.up1"])
.reaching("one.v0", &[1])
.reaching("one.up1", &[1, 2]);
let outcome = accumulate(
&[planned("one", 1, &["first", "second", "third"])],
&bench,
&dir,
)
.unwrap();
assert_eq!(
bench.labels(),
vec!["one.v0", "one.up1", "one.up2"],
"up3 must never be built once up2 is rejected"
);
assert_eq!(outcome.survivors[0].steps, 1);
}
#[test]
fn a_candidate_with_no_step_is_never_extended() {
let dir = scratch("nosteps");
let bench = Fake::new(&["one.v0"]);
accumulate(&[planned("one", 1, &[])], &bench, &dir).unwrap();
assert_eq!(bench.labels(), vec!["one.v0"]);
}
#[test]
fn a_bench_error_on_one_candidate_does_not_stop_the_walk() {
struct Broken;
impl Bench for Broken {
fn verify(
&self,
_source: &Path,
label: &str,
_parent: Option<&BTreeMap<PathBuf, EdgeSet>>,
_accepted: &EdgeSet,
) -> Result<Verdict, VerifyError> {
Err(VerifyError::NoCoverageMap {
seed: PathBuf::from(label),
})
}
}
let dir = scratch("broken");
let outcome = accumulate(
&[planned("one", 1, &[]), planned("two", 1, &[])],
&Broken,
&dir,
)
.unwrap();
assert!(outcome.survivors.is_empty());
assert_eq!(outcome.rejected.len(), 2);
assert!(
outcome.rejected[0].contains("could not be judged"),
"{:?}",
outcome.rejected
);
}
}