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
feat(lisdex): M4 harness synthesis foundation - oracle layer, C emitter, compile driver
CarterPerez-deveb288498286f
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lockindex e26daff0..f7a969c6 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock@@ -329,6 +329,16 @@ dependencies = ["thiserror",]+[[package]]+name = "lisdex-harness"+version = "0.0.0"+dependencies = [+ "lisdex-core",+ "lisdex-surface",+ "serde",+ "thiserror",+]+[[package]]name = "lisdex-ingest"version = "0.0.0"diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.tomlindex a07569d9..da330ed7 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml@@ -24,6 +24,7 @@ lisdex-fuzz = { path = "crates/lisdex-fuzz" }lisdex-ingest = { path = "crates/lisdex-ingest" }lisdex-build = { path = "crates/lisdex-build" }lisdex-surface = { path = "crates/lisdex-surface" }+lisdex-harness = { path = "crates/lisdex-harness" }[workspace.lints.rust]unsafe_code = "deny"diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/Cargo.tomlnew file mode 100644index 00000000..0a819954--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/Cargo.toml@@ -0,0 +1,19 @@+# ©AngelaMos | 2026+# Cargo.toml++[package]+name = "lisdex-harness"+version = "0.0.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true++[dependencies]+lisdex-core = { workspace = true }+lisdex-surface = { workspace = true }+serde = { workspace = true }+thiserror = { workspace = true }++[lints]+workspace = truediff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/compile.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/compile.rsnew file mode 100644index 00000000..59697e2c--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/compile.rs@@ -0,0 +1,186 @@+// ©AngelaMos | 2026+// compile.rs++use std::path::{Path, PathBuf};++use lisdex_core::process::CommandSpec;++pub const CC: &str = "afl-clang-lto";+pub const SHOWMAP: &str = "afl-showmap";+pub const DEFAULT_DRIVER: &str = "/usr/local/lib/afl/libAFLDriver.a";+pub const ASAN_OPTIONS: &str = "ASAN_OPTIONS";+pub const ASAN_OPTIONS_VALUE: &str = "detect_leaks=0";+pub const SHOWMAP_TIMEOUT_MS: u64 = 5000;++#[derive(Debug, Clone)]+pub struct BuildSpec {+ pub source: PathBuf,+ pub output: PathBuf,+ pub includes: Vec<PathBuf>,+ pub defines: Vec<String>,+ pub cflags: Vec<String>,+ pub archives: Vec<PathBuf>,+ pub link_args: Vec<String>,+ pub driver: PathBuf,+ pub cmplog: bool,+}++impl BuildSpec {+ #[must_use]+ pub fn new(source: impl Into<PathBuf>, output: impl Into<PathBuf>) -> Self {+ Self {+ source: source.into(),+ output: output.into(),+ includes: Vec::new(),+ defines: Vec::new(),+ cflags: Vec::new(),+ archives: Vec::new(),+ link_args: Vec::new(),+ driver: PathBuf::from(DEFAULT_DRIVER),+ cmplog: false,+ }+ }+}++#[must_use]+pub fn build_command(spec: &BuildSpec) -> CommandSpec {+ let mut command = CommandSpec::new(CC)+ .env("AFL_USE_ASAN", "1")+ .env("AFL_USE_UBSAN", "1")+ .env("AFL_QUIET", "1");+ if spec.cmplog {+ command = command.env("AFL_LLVM_CMPLOG", "1");+ }+ for flag in &spec.cflags {+ command = command.arg(flag);+ }+ for define in &spec.defines {+ command = command.arg(format!("-D{define}"));+ }+ for include in &spec.includes {+ command = command.arg(format!("-I{}", include.display()));+ }+ command = command+ .path_arg(&spec.source)+ .arg("-o")+ .path_arg(&spec.output);+ for archive in &spec.archives {+ command = command.path_arg(archive);+ }+ command = command.path_arg(&spec.driver);+ for link in &spec.link_args {+ command = command.arg(link);+ }+ command+}++#[must_use]+pub fn showmap_command(binary: &Path, seed: &Path, map: &Path) -> CommandSpec {+ CommandSpec::new(SHOWMAP)+ .env(ASAN_OPTIONS, ASAN_OPTIONS_VALUE)+ .arg("-o")+ .path_arg(map)+ .arg("-t")+ .arg(SHOWMAP_TIMEOUT_MS.to_string())+ .arg("--")+ .path_arg(binary)+ .path_arg(seed)+}++#[must_use]+pub fn exercise_command(binary: &Path, seed: &Path) -> CommandSpec {+ CommandSpec::new(binary.display().to_string())+ .env(ASAN_OPTIONS, ASAN_OPTIONS_VALUE)+ .path_arg(seed)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn spec() -> BuildSpec {+ let mut spec = BuildSpec::new("/w/h.c", "/w/h.bin");+ spec.includes.push(PathBuf::from("/src"));+ spec.archives.push(PathBuf::from("/out/libpng16.a"));+ spec.link_args.push("-lz".to_owned());+ spec+ }++ #[test]+ fn the_sanitizers_are_set_in_the_environment_not_only_as_flags() {+ let command = build_command(&spec());+ assert_eq!(command.env_value("AFL_USE_ASAN"), Some("1"));+ assert_eq!(command.env_value("AFL_USE_UBSAN"), Some("1"));+ }++ #[test]+ fn cmplog_is_off_unless_asked_for() {+ assert!(!build_command(&spec()).has_env("AFL_LLVM_CMPLOG"));+ }++ #[test]+ fn cmplog_is_an_environment_switch() {+ let mut cmplog = spec();+ cmplog.cmplog = true;+ assert_eq!(+ build_command(&cmplog).env_value("AFL_LLVM_CMPLOG"),+ Some("1")+ );+ }++ #[test]+ fn the_driver_is_linked_after_the_library_archives() {+ let line = build_command(&spec()).command_line();+ let archive = line.find("libpng16.a").expect("archive on the line");+ let driver = line.find("libAFLDriver.a").expect("driver on the line");+ assert!(archive < driver);+ }++ #[test]+ fn link_arguments_come_last() {+ let line = build_command(&spec()).command_line();+ let driver = line.find("libAFLDriver.a").expect("driver on the line");+ let lz = line.find("-lz").expect("link arg on the line");+ assert!(driver < lz);+ }++ #[test]+ fn includes_and_defines_are_prefixed() {+ let mut spec = spec();+ spec.defines.push("MAGMA_ENABLE_CANARIES".to_owned());+ let line = build_command(&spec).command_line();+ assert!(line.contains("-I/src"));+ assert!(line.contains("-DMAGMA_ENABLE_CANARIES"));+ }++ #[test]+ fn the_compiler_is_the_lto_driver() {+ assert_eq!(build_command(&spec()).program, CC);+ }++ #[test]+ fn showmap_bounds_the_execution_and_silences_leak_detection() {+ let command = showmap_command(+ Path::new("/w/h.bin"),+ Path::new("/seeds/a.png"),+ Path::new("/tmp/map"),+ );+ let line = command.command_line();+ assert!(line.contains("-t 5000"));+ assert!(line.contains("-- /w/h.bin /seeds/a.png"));+ assert_eq!(command.env_value(ASAN_OPTIONS), Some(ASAN_OPTIONS_VALUE));+ }++ #[test]+ fn a_direct_exercise_runs_the_binary_on_the_seed() {+ let command = exercise_command(Path::new("/w/h.bin"), Path::new("/seeds/a.png"));+ assert_eq!(command.program, "/w/h.bin");+ assert_eq!(command.command_line(), "/w/h.bin /seeds/a.png");+ }++ #[test]+ fn a_direct_exercise_also_silences_leak_detection() {+ let command = exercise_command(Path::new("/w/h.bin"), Path::new("/seeds/a.png"));+ assert_eq!(command.env_value(ASAN_OPTIONS), Some(ASAN_OPTIONS_VALUE));+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/coverage.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/coverage.rsnew file mode 100644index 00000000..075ab9f8--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/coverage.rs@@ -0,0 +1,155 @@+// ©AngelaMos | 2026+// coverage.rs++use std::collections::BTreeSet;++pub const EDGE_FIELD_SEPARATOR: char = ':';++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct EdgeSet {+ edges: BTreeSet<u32>,+}++impl EdgeSet {+ #[must_use]+ pub fn new() -> Self {+ Self::default()+ }++ #[must_use]+ pub fn len(&self) -> usize {+ self.edges.len()+ }++ #[must_use]+ pub fn is_empty(&self) -> bool {+ self.edges.is_empty()+ }++ #[must_use]+ pub fn divergence(&self, other: &EdgeSet) -> usize {+ self.edges.symmetric_difference(&other.edges).count()+ }++ #[must_use]+ pub fn novel_against(&self, other: &EdgeSet) -> usize {+ self.edges.difference(&other.edges).count()+ }++ #[must_use]+ pub fn covers(&self, other: &EdgeSet) -> bool {+ other.edges.is_subset(&self.edges)+ }++ pub fn absorb(&mut self, other: &EdgeSet) {+ self.edges.extend(other.edges.iter().copied());+ }++ #[must_use]+ pub fn union_of<'a>(maps: impl IntoIterator<Item = &'a EdgeSet>) -> EdgeSet {+ let mut total = EdgeSet::new();+ for map in maps {+ total.absorb(map);+ }+ total+ }+}++impl FromIterator<u32> for EdgeSet {+ fn from_iter<I: IntoIterator<Item = u32>>(iter: I) -> Self {+ Self {+ edges: iter.into_iter().collect(),+ }+ }+}++#[must_use]+pub fn parse_showmap(text: &str) -> EdgeSet {+ text.lines()+ .filter_map(|line| {+ let field = line.split(EDGE_FIELD_SEPARATOR).next()?.trim();+ field.parse::<u32>().ok()+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parses_edge_ids_and_discards_hit_counts() {+ let map = parse_showmap("000123:1\n004567:3\n065535:255\n");+ assert_eq!(map.len(), 3);+ assert_eq!(map, [123, 4567, 65535].into_iter().collect());+ }++ #[test]+ fn a_differing_hit_count_is_not_a_differing_edge() {+ let hot = parse_showmap("42:1\n");+ let hotter = parse_showmap("42:250\n");+ assert_eq!(hot, hotter);+ assert_eq!(hot.divergence(&hotter), 0);+ }++ #[test]+ fn ignores_blank_and_malformed_lines() {+ let map = parse_showmap("\n12:1\nnot-an-edge\n\n34:2\n");+ assert_eq!(map.len(), 2);+ }++ #[test]+ fn empty_output_is_an_empty_map() {+ assert!(parse_showmap("").is_empty());+ }++ #[test]+ fn divergence_counts_both_directions() {+ let left: EdgeSet = [1, 2, 3].into_iter().collect();+ let right: EdgeSet = [3, 4].into_iter().collect();+ assert_eq!(left.divergence(&right), 3);+ }++ #[test]+ fn identical_maps_do_not_diverge() {+ let left: EdgeSet = [1, 2, 3].into_iter().collect();+ let right: EdgeSet = [3, 2, 1].into_iter().collect();+ assert_eq!(left.divergence(&right), 0);+ }++ #[test]+ fn novelty_is_one_directional() {+ let candidate: EdgeSet = [1, 2, 9].into_iter().collect();+ let accepted: EdgeSet = [1, 2, 3, 4].into_iter().collect();+ assert_eq!(candidate.novel_against(&accepted), 1);+ assert_eq!(accepted.novel_against(&candidate), 2);+ }++ #[test]+ fn covers_detects_a_superset() {+ let wide: EdgeSet = [1, 2, 3, 4].into_iter().collect();+ let narrow: EdgeSet = [2, 3].into_iter().collect();+ assert!(wide.covers(&narrow));+ assert!(!narrow.covers(&wide));+ }++ #[test]+ fn a_map_covers_itself() {+ let map: EdgeSet = [7, 8].into_iter().collect();+ assert!(map.covers(&map));+ }++ #[test]+ fn union_merges_every_map() {+ let first: EdgeSet = [1, 2].into_iter().collect();+ let second: EdgeSet = [2, 3].into_iter().collect();+ let third: EdgeSet = [9].into_iter().collect();+ let total = EdgeSet::union_of([&first, &second, &third]);+ assert_eq!(total.len(), 4);+ }++ #[test]+ fn union_of_nothing_is_empty() {+ assert!(EdgeSet::union_of([]).is_empty());+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rsnew file mode 100644index 00000000..cadb25b2--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs@@ -0,0 +1,498 @@+// ©AngelaMos | 2026+// emit.rs++use std::fmt::Write;++use crate::plan::{+ CALLBACK_BUDGET, CURSOR_LOCAL, CURSOR_STRUCT, CallbackKind, CallbackStub, FUZZ_DATA, FUZZ_SIZE,+ HarnessPlan, Init, MAX_CALLBACK_CALLS, Stmt, Value,+};++pub const CALLBACK_COUNTER: &str = "lisdex_callback_calls";+pub const ENTRY_SYMBOL: &str = "LLVMFuzzerTestOneInput";+pub const SYSTEM_INCLUDES: &[&str] = &["stddef.h", "stdint.h", "stdlib.h", "string.h"];++#[must_use]+pub fn render(plan: &HarnessPlan, filename: &str) -> String {+ let mut out = String::new();+ render_header(&mut out, filename);+ render_includes(&mut out, plan);+ render_support(&mut out, plan);+ render_callbacks(&mut out, plan);+ render_entry(&mut out, plan);+ out+}++fn render_header(out: &mut String, filename: &str) {+ let _ = writeln!(out, "// ©AngelaMos | 2026");+ let _ = writeln!(out, "// {filename}");+ let _ = writeln!(out);+}++fn render_includes(out: &mut String, plan: &HarnessPlan) {+ for header in SYSTEM_INCLUDES {+ let _ = writeln!(out, "#include <{header}>");+ }+ if !plan.includes.is_empty() {+ let _ = writeln!(out);+ }+ for header in &plan.includes {+ let _ = writeln!(out, "#include \"{header}\"");+ }+ let _ = writeln!(out);+}++fn render_support(out: &mut String, plan: &HarnessPlan) {+ if !plan.needs_cursor && plan.callbacks.is_empty() {+ return;+ }+ let _ = writeln!(out, "#define {CALLBACK_BUDGET} {MAX_CALLBACK_CALLS}");+ let _ = writeln!(out);+ if plan.needs_cursor {+ let _ = writeln!(out, "typedef struct {{");+ let _ = writeln!(out, " const uint8_t *data;");+ let _ = writeln!(out, " size_t size;");+ let _ = writeln!(out, " size_t offset;");+ let _ = writeln!(out, "}} {CURSOR_STRUCT};");+ let _ = writeln!(out);+ let _ = writeln!(out, "static {CURSOR_STRUCT} {CURSOR_LOCAL};");+ }+ if !plan.callbacks.is_empty() {+ let _ = writeln!(out, "static unsigned {CALLBACK_COUNTER};");+ }+ let _ = writeln!(out);+}++fn render_callbacks(out: &mut String, plan: &HarnessPlan) {+ for stub in &plan.callbacks {+ render_callback(out, stub);+ let _ = writeln!(out);+ }+}++fn signature(stub: &CallbackStub) -> String {+ let params = if stub.params.is_empty() {+ "void".to_owned()+ } else {+ stub.params+ .iter()+ .enumerate()+ .map(|(index, ty)| format!("{ty} a{index}"))+ .collect::<Vec<_>>()+ .join(", ")+ };+ format!("static {} {}({params})", stub.return_ty, stub.name)+}++fn render_callback(out: &mut String, stub: &CallbackStub) {+ let _ = writeln!(out, "{}", signature(stub));+ let _ = writeln!(out, "{{");+ for index in 0..stub.params.len() {+ if !touches(stub, index) {+ let _ = writeln!(out, " (void)a{index};");+ }+ }+ let _ = writeln!(out, " if ({CALLBACK_COUNTER} >= {CALLBACK_BUDGET}) {{");+ let _ = writeln!(out, " {}", bail(stub));+ let _ = writeln!(out, " }}");+ let _ = writeln!(out, " {CALLBACK_COUNTER}++;");+ if let CallbackKind::ReadFromCursor { buffer, count } = stub.kind {+ render_cursor_read(out, buffer, count);+ }+ let _ = writeln!(out, " {}", bail(stub));+ let _ = writeln!(out, "}}");+}++fn touches(stub: &CallbackStub, index: usize) -> bool {+ match stub.kind {+ CallbackKind::Benign => false,+ CallbackKind::ReadFromCursor { buffer, count } => index == buffer || index == count,+ }+}++fn bail(stub: &CallbackStub) -> String {+ if stub.return_ty.trim() == "void" {+ "return;".to_owned()+ } else {+ "return 0;".to_owned()+ }+}++fn render_cursor_read(out: &mut String, buffer: usize, count: usize) {+ let _ = writeln!(out, " size_t available = 0;");+ let _ = writeln!(+ out,+ " if ({CURSOR_LOCAL}.offset < {CURSOR_LOCAL}.size) {{"+ );+ let _ = writeln!(+ out,+ " available = {CURSOR_LOCAL}.size - {CURSOR_LOCAL}.offset;"+ );+ let _ = writeln!(out, " }}");+ let _ = writeln!(out, " if (available > (size_t)a{count}) {{");+ let _ = writeln!(out, " available = (size_t)a{count};");+ let _ = writeln!(out, " }}");+ let _ = writeln!(out, " if (available > 0 && a{buffer} != NULL) {{");+ let _ = writeln!(+ out,+ " memcpy(a{buffer}, {CURSOR_LOCAL}.data + {CURSOR_LOCAL}.offset, available);"+ );+ let _ = writeln!(out, " {CURSOR_LOCAL}.offset += available;");+ let _ = writeln!(out, " }}");+}++fn render_entry(out: &mut String, plan: &HarnessPlan) {+ let _ = writeln!(+ out,+ "int {ENTRY_SYMBOL}(const uint8_t *{FUZZ_DATA}, size_t {FUZZ_SIZE})"+ );+ let _ = writeln!(out, "{{");+ render_prologue(out, plan);+ for statement in &plan.body {+ render_stmt(out, statement);+ }+ let _ = writeln!(out, " return 0;");+ let _ = writeln!(out, "}}");+}++fn render_prologue(out: &mut String, plan: &HarnessPlan) {+ let mut wrote = false;+ if plan.needs_cursor {+ let _ = writeln!(out, " {CURSOR_LOCAL}.data = {FUZZ_DATA};");+ let _ = writeln!(out, " {CURSOR_LOCAL}.size = {FUZZ_SIZE};");+ let _ = writeln!(out, " {CURSOR_LOCAL}.offset = 0;");+ wrote = true;+ }+ if !plan.callbacks.is_empty() {+ let _ = writeln!(out, " {CALLBACK_COUNTER} = 0;");+ wrote = true;+ }+ if wrote {+ let _ = writeln!(out);+ }+}++fn render_stmt(out: &mut String, statement: &Stmt) {+ match statement {+ Stmt::Declare { ty, name, init } => match init {+ Init::Null => {+ let _ = writeln!(out, " {ty} {name} = NULL;");+ }+ Init::ZeroBytes => {+ let _ = writeln!(out, " {ty} {name};");+ let _ = writeln!(out, " memset(&{name}, 0, sizeof {name});");+ }+ Init::Uninitialised => {+ let _ = writeln!(out, " {ty} {name};");+ }+ },+ Stmt::SetField {+ local,+ field,+ value,+ } => {+ let _ = writeln!(out, " {local}.{field} = {};", render_value(value));+ }+ Stmt::Call {+ function,+ args,+ capture,+ } => {+ let rendered = args.iter().map(render_value).collect::<Vec<_>>().join(", ");+ match capture {+ Some(binding) => {+ let _ = writeln!(+ out,+ " {} {} = {function}({rendered});",+ binding.ty, binding.name+ );+ }+ None => {+ let _ = writeln!(out, " {function}({rendered});");+ }+ }+ }+ Stmt::BailIfNull { local } => {+ let _ = writeln!(out, " if ({local} == NULL) {{");+ let _ = writeln!(out, " return 0;");+ let _ = writeln!(out, " }}");+ }+ Stmt::BailIfZero { local } => {+ let _ = writeln!(out, " if ({local} == 0) {{");+ let _ = writeln!(out, " return 0;");+ let _ = writeln!(out, " }}");+ }+ }+}++fn render_value(value: &Value) -> String {+ match value {+ Value::Data { cast } => match cast {+ Some(ty) => format!("({ty}){FUZZ_DATA}"),+ None => FUZZ_DATA.to_owned(),+ },+ Value::Size => FUZZ_SIZE.to_owned(),+ Value::Null => "NULL".to_owned(),+ Value::Zero => "0".to_owned(),+ Value::Literal(text) | Value::Local(text) | Value::Callback(text) => text.clone(),+ Value::AddressOf(name) => format!("&{name}"),+ Value::Cursor => format!("&{CURSOR_LOCAL}"),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::plan::Binding;++ fn simplified_libpng() -> HarnessPlan {+ HarnessPlan::new("png_image_begin_read_from_memory")+ .with_include("png.h")+ .with(Stmt::Declare {+ ty: "png_image".to_owned(),+ name: "image".to_owned(),+ init: Init::ZeroBytes,+ })+ .with(Stmt::SetField {+ local: "image".to_owned(),+ field: "version".to_owned(),+ value: Value::Literal("PNG_IMAGE_VERSION".to_owned()),+ })+ .with(Stmt::Call {+ function: "png_image_begin_read_from_memory".to_owned(),+ args: vec![+ Value::AddressOf("image".to_owned()),+ Value::Data { cast: None },+ Value::Size,+ ],+ capture: Some(Binding {+ ty: "int".to_owned(),+ name: "started".to_owned(),+ }),+ })+ .with(Stmt::BailIfZero {+ local: "started".to_owned(),+ })+ }++ #[test]+ fn every_harness_carries_the_file_header() {+ let source = render(&simplified_libpng(), "libpng_begin_read.c");+ assert!(source.starts_with("// ©AngelaMos | 2026\n// libpng_begin_read.c\n"));+ }++ #[test]+ fn the_entry_point_has_the_libfuzzer_signature() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.contains("int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)"));+ }++ #[test]+ fn library_headers_are_quoted_and_system_headers_are_bracketed() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.contains("#include <stdint.h>"));+ assert!(source.contains("#include \"png.h\""));+ }++ #[test]+ fn a_record_local_is_zeroed_with_memset() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.contains(" png_image image;"));+ assert!(source.contains(" memset(&image, 0, sizeof image);"));+ }++ #[test]+ fn a_typedefd_pointer_is_nulled_not_memset() {+ let plan = HarnessPlan::new("f").with(Stmt::Declare {+ ty: "png_structp".to_owned(),+ name: "png".to_owned(),+ init: Init::Null,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains(" png_structp png = NULL;"));+ assert!(!source.contains("memset(&png"));+ }++ #[test]+ fn an_uninitialised_local_gets_no_initialiser() {+ let plan = HarnessPlan::new("f").with(Stmt::Declare {+ ty: "int".to_owned(),+ name: "rc".to_owned(),+ init: Init::Uninitialised,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains(" int rc;"));+ assert!(!source.contains("memset(&rc"));+ assert!(!source.contains("rc = NULL"));+ }++ #[test]+ fn a_macro_valued_field_is_emitted_verbatim() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.contains(" image.version = PNG_IMAGE_VERSION;"));+ }++ #[test]+ fn a_captured_call_declares_its_binding() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(+ source.contains(+ " int started = png_image_begin_read_from_memory(&image, data, size);"+ )+ );+ }++ #[test]+ fn a_zero_return_bails_out() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.contains(" if (started == 0) {\n return 0;\n }"));+ }++ #[test]+ fn a_plan_without_callbacks_emits_no_cursor_machinery() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(!source.contains(CURSOR_STRUCT));+ assert!(!source.contains(CALLBACK_COUNTER));+ }++ #[test]+ fn a_cast_buffer_argument_is_cast() {+ let plan = HarnessPlan::new("f").with(Stmt::Call {+ function: "decode".to_owned(),+ args: vec![+ Value::Data {+ cast: Some("const char *".to_owned()),+ },+ Value::Size,+ ],+ capture: None,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains(" decode((const char *)data, size);"));+ }++ fn libpng_read_callback() -> HarnessPlan {+ HarnessPlan::new("png_read_info")+ .with_include("png.h")+ .with_callback(CallbackStub {+ name: "lisdex_read".to_owned(),+ return_ty: "void".to_owned(),+ params: vec![+ "png_structp".to_owned(),+ "png_bytep".to_owned(),+ "size_t".to_owned(),+ ],+ kind: CallbackKind::ReadFromCursor {+ buffer: 1,+ count: 2,+ },+ })+ .with(Stmt::Call {+ function: "png_set_read_fn".to_owned(),+ args: vec![+ Value::Local("png".to_owned()),+ Value::Cursor,+ Value::Callback("lisdex_read".to_owned()),+ ],+ capture: None,+ })+ }++ #[test]+ fn a_read_callback_emits_the_cursor_type_and_a_static_instance() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains("typedef struct {"));+ assert!(source.contains(&format!("static {CURSOR_STRUCT} {CURSOR_LOCAL};")));+ }++ #[test]+ fn the_cursor_is_reset_on_every_input() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains(&format!(" {CURSOR_LOCAL}.data = data;")));+ assert!(source.contains(&format!(" {CURSOR_LOCAL}.offset = 0;")));+ }++ #[test]+ fn the_callback_counter_is_reset_on_every_input() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains(&format!(" {CALLBACK_COUNTER} = 0;")));+ }++ #[test]+ fn a_read_callback_serves_bytes_and_never_overruns_the_cursor() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains("if (available > (size_t)a2)"));+ assert!(source.contains(&format!(+ "memcpy(a1, {CURSOR_LOCAL}.data + {CURSOR_LOCAL}.offset, available);"+ )));+ }++ #[test]+ fn a_read_callback_is_bounded_and_returns_rather_than_exiting() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains(&format!("if ({CALLBACK_COUNTER} >= {CALLBACK_BUDGET})")));+ assert!(!source.contains("exit(0)"));+ }++ #[test]+ fn a_benign_callback_returns_a_value_for_a_non_void_return() {+ let plan = HarnessPlan::new("f").with_callback(CallbackStub {+ name: "cb".to_owned(),+ return_ty: "int".to_owned(),+ params: vec!["void *".to_owned()],+ kind: CallbackKind::Benign,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains("static int cb(void * a0)"));+ assert!(source.contains(" return 0;"));+ assert!(!source.contains("exit(0)"));+ }++ #[test]+ fn unused_callback_parameters_are_voided_to_keep_the_compile_quiet() {+ let plan = HarnessPlan::new("f").with_callback(CallbackStub {+ name: "cb".to_owned(),+ return_ty: "void".to_owned(),+ params: vec!["int".to_owned(), "int".to_owned()],+ kind: CallbackKind::Benign,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains(" (void)a0;"));+ assert!(source.contains(" (void)a1;"));+ }++ #[test]+ fn a_read_callback_does_not_void_the_parameters_it_uses() {+ let source = render(&libpng_read_callback(), "x.c");+ assert!(source.contains(" (void)a0;"));+ assert!(!source.contains(" (void)a1;"));+ assert!(!source.contains(" (void)a2;"));+ }++ #[test]+ fn a_callback_with_no_parameters_takes_void() {+ let plan = HarnessPlan::new("f").with_callback(CallbackStub {+ name: "cb".to_owned(),+ return_ty: "void".to_owned(),+ params: Vec::new(),+ kind: CallbackKind::Benign,+ });+ let source = render(&plan, "x.c");+ assert!(source.contains("static void cb(void)"));+ }++ #[test]+ fn a_null_check_bails_out() {+ let plan = HarnessPlan::new("f").with(Stmt::BailIfNull {+ local: "png".to_owned(),+ });+ let source = render(&plan, "x.c");+ assert!(source.contains(" if (png == NULL) {\n return 0;\n }"));+ }++ #[test]+ fn the_body_ends_by_returning_zero() {+ let source = render(&simplified_libpng(), "x.c");+ assert!(source.trim_end().ends_with(" return 0;\n}"));+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/lib.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/lib.rsnew file mode 100644index 00000000..771ffda7--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/lib.rs@@ -0,0 +1,8 @@+// ©AngelaMos | 2026+// lib.rs++pub mod compile;+pub mod coverage;+pub mod emit;+pub mod oracle;+pub mod plan;diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/oracle.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/oracle.rsnew file mode 100644index 00000000..8b5cf113--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/oracle.rs@@ -0,0 +1,543 @@+// ©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 },+ NoInterSeedDivergence { best: usize },+ ConstantCoverageIncrease { amount: usize },+ InvalidSeedsIndistinguishable,+ NoGlobalNovelty,+}++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 } => write!(+ formatter,+ "wrote to stderr on valid seed {}: {text}",+ 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"+ ),+ }+ }+}++pub fn judge_execution(observation: &Observation) -> Result<(), Rejection> {+ if observation.valid.len() < MIN_VALID_SEEDS {+ return Err(Rejection::TooFewValidSeeds {+ have: observation.valid.len(),+ });+ }+ 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 => {}+ }+ }+ 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> {+ let Some(first) = valid.first() else {+ return Ok(());+ };+ let mut invariant = stderr_lines(first);+ for run in &valid[1..] {+ let lines = stderr_lines(run);+ invariant.retain(|line| lines.contains(line));+ }+ for run in valid {+ if let Some(extra) = stderr_lines(run)+ .into_iter()+ .find(|line| !invariant.contains(line))+ {+ return Err(Rejection::StderrOnValidSeed {+ seed: run.seed.clone(),+ text: extra.to_owned(),+ });+ }+ }+ 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 Ok(());+ };+ 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_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()+ })+ );+ }++ #[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 })+ );+ }++ #[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 { .. })+ ));+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rsnew file mode 100644index 00000000..2efdd55a--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs@@ -0,0 +1,179 @@+// ©AngelaMos | 2026+// plan.rs++pub const FUZZ_DATA: &str = "data";+pub const FUZZ_SIZE: &str = "size";+pub const CURSOR_STRUCT: &str = "lisdex_cursor";+pub const CURSOR_LOCAL: &str = "lisdex_input";+pub const CALLBACK_BUDGET: &str = "LISDEX_CALLBACK_BUDGET";+pub const MAX_CALLBACK_CALLS: u32 = 4096;++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Value {+ Data { cast: Option<String> },+ Size,+ Null,+ Zero,+ Literal(String),+ Local(String),+ AddressOf(String),+ Callback(String),+ Cursor,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Init {+ Uninitialised,+ Null,+ ZeroBytes,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Stmt {+ Declare {+ ty: String,+ name: String,+ init: Init,+ },+ SetField {+ local: String,+ field: String,+ value: Value,+ },+ Call {+ function: String,+ args: Vec<Value>,+ capture: Option<Binding>,+ },+ BailIfNull {+ local: String,+ },+ BailIfZero {+ local: String,+ },+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct Binding {+ pub ty: String,+ pub name: String,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CallbackStub {+ pub name: String,+ pub return_ty: String,+ pub params: Vec<String>,+ pub kind: CallbackKind,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum CallbackKind {+ Benign,+ ReadFromCursor { buffer: usize, count: usize },+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub struct HarnessPlan {+ pub entry: String,+ pub includes: Vec<String>,+ pub needs_cursor: bool,+ pub callbacks: Vec<CallbackStub>,+ pub body: Vec<Stmt>,+}++impl HarnessPlan {+ #[must_use]+ pub fn new(entry: impl Into<String>) -> Self {+ Self {+ entry: entry.into(),+ includes: Vec::new(),+ needs_cursor: false,+ callbacks: Vec::new(),+ body: Vec::new(),+ }+ }++ #[must_use]+ pub fn with_include(mut self, header: impl Into<String>) -> Self {+ self.includes.push(header.into());+ self+ }++ #[must_use]+ pub fn with_callback(mut self, stub: CallbackStub) -> Self {+ if matches!(stub.kind, CallbackKind::ReadFromCursor { .. }) {+ self.needs_cursor = true;+ }+ self.callbacks.push(stub);+ self+ }++ #[must_use]+ pub fn with(mut self, statement: Stmt) -> Self {+ if let Stmt::Call { args, .. } = &statement+ && args.contains(&Value::Cursor)+ {+ self.needs_cursor = true;+ }+ self.body.push(statement);+ self+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_read_callback_forces_the_cursor_in() {+ let plan = HarnessPlan::new("png_read_info").with_callback(CallbackStub {+ name: "lisdex_read".to_owned(),+ return_ty: "void".to_owned(),+ params: vec!["png_structp".to_owned(), "png_bytep".to_owned()],+ kind: CallbackKind::ReadFromCursor {+ buffer: 1,+ count: 2,+ },+ });+ assert!(plan.needs_cursor);+ }++ #[test]+ fn a_benign_callback_does_not_force_the_cursor_in() {+ let plan = HarnessPlan::new("expat_parse").with_callback(CallbackStub {+ name: "lisdex_on_element".to_owned(),+ return_ty: "void".to_owned(),+ params: vec!["void *".to_owned()],+ kind: CallbackKind::Benign,+ });+ assert!(!plan.needs_cursor);+ }++ #[test]+ fn passing_the_cursor_to_a_call_forces_it_in() {+ let plan = HarnessPlan::new("png_read_info").with(Stmt::Call {+ function: "png_set_read_fn".to_owned(),+ args: vec![+ Value::Local("png".to_owned()),+ Value::Cursor,+ Value::Callback("lisdex_read".to_owned()),+ ],+ capture: None,+ });+ assert!(plan.needs_cursor);+ }++ #[test]+ fn a_plain_plan_needs_no_cursor() {+ let plan = HarnessPlan::new("png_image_begin_read_from_memory")+ .with_include("png.h")+ .with(Stmt::Declare {+ ty: "png_image".to_owned(),+ name: "image".to_owned(),+ init: Init::ZeroBytes,+ });+ assert!(!plan.needs_cursor);+ assert_eq!(plan.includes, vec!["png.h".to_owned()]);+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rsindex 0f1ac89f..14ddea2c 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs@@ -194,7 +194,6 @@ impl CallGraph {self.nodes.get(name).map_or(0, |node| node.own)}- #[must_use]pub fn names(&self) -> impl Iterator<Item = &String> {self.nodes.keys()}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rsindex bd263ef1..3a7a0d6b 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs@@ -5,10 +5,10 @@ use std::collections::BTreeSet;use std::path::{Path, PathBuf};use std::sync::{Mutex, PoisonError};-use clang::diagnostic::Severity;+use clang::diagnostic::{Diagnostic, Severity};use clang::{Clang, Entity, EntityKind, Index, Type, TypeKind};-use crate::signature::{Param, Pointee, Shape};+use crate::signature::{Param, Pointee, Returns, Shape};static PARSE_LOCK: Mutex<()> = Mutex::new(());@@ -64,6 +64,7 @@ impl ParseOptions {pub struct Declared {pub name: String,pub params: Vec<Param>,+ pub result: Returns,pub header: PathBuf,pub line: u32,}@@ -207,6 +208,17 @@ fn parameters(entity: &Entity) -> Vec<Param> {.collect()}+fn result_of(entity: &Entity) -> Returns {+ let ty = entity.get_result_type();+ Returns {+ spelling: ty+ .as_ref()+ .map(clang::Type::get_display_name)+ .unwrap_or_default(),+ shape: ty.as_ref().map_or(Shape::Other, shape_of),+ }+}+fn collect(entity: &Entity, target: &Path, found: &mut Vec<Declared>, seen: &mut BTreeSet<String>) {for child in entity.get_children() {match child.get_kind() {@@ -221,6 +233,7 @@ fn collect(entity: &Entity, target: &Path, found: &mut Vec<Declared>, seen: &mutfound.push(Declared {name,params: parameters(&child),+ result: result_of(&child),header: target.to_path_buf(),line,});@@ -260,7 +273,7 @@ pub fn parse_header(path: &Path, options: &ParseOptions) -> Result<Vec<Declared>.filter(|diagnostic| {matches!(diagnostic.get_severity(), Severity::Error | Severity::Fatal)})- .map(|diagnostic| diagnostic.get_text())+ .map(Diagnostic::get_text).collect();if let Some(first) = failures.first() {return Err(ExtractError::Diagnostics {diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/harness.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/harness.rsindex c4595983..8cd385a9 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/harness.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/harness.rs@@ -123,8 +123,7 @@ fn walk(root: &Path, depth: usize, found: &mut Vec<Harness>) -> Result<(), Harne}let oversized = entry.metadata()- .map(|meta| meta.len() > MAX_SOURCE_BYTES)- .unwrap_or(true);+ .map_or(true, |meta| meta.len() > MAX_SOURCE_BYTES);if oversized {continue;}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/rank.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/rank.rsindex 319e203c..c2cc56c2 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/rank.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/rank.rs@@ -4,8 +4,8 @@use std::collections::BTreeSet;use std::path::PathBuf;-use crate::naming::{self, Role};-use crate::signature::{self, Analysis, Fuzzability, Param};+use crate::naming::{self, NameSignal, Role};+use crate::signature::{self, Analysis, Fuzzability, Param, Returns};pub const WEIGHT_UNDISCOVERED: f64 = 0.40;pub const WEIGHT_FUZZABILITY: f64 = 0.25;@@ -28,6 +28,7 @@ pub struct Complexity {pub struct Function {pub name: String,pub params: Vec<Param>,+ pub result: Returns,pub header: PathBuf,pub line: u32,pub exported: bool,@@ -54,6 +55,8 @@ pub struct Excluded {#[derive(Debug, Clone, PartialEq, serde::Serialize)]pub struct Candidate {pub name: String,+ pub params: Vec<Param>,+ pub result: Returns,pub header: PathBuf,pub line: u32,pub fuzzability: Fuzzability,@@ -120,6 +123,75 @@ pub fn arg_simplicity(context_args: usize) -> f64 {1.0 / (1.0 + f64::from(count))}+fn score_candidate(+ function: Function,+ signal: &NameSignal,+ analysis: Analysis,+ weights: &Weights,+ accumulated_ceiling: u32,+ undiscovered_ceiling: u32,+) -> Candidate {+ let accumulated = complexity_score(function.complexity.accumulated, accumulated_ceiling);+ let undiscovered = complexity_score(function.complexity.undiscovered, undiscovered_ceiling);+ let fuzzability = analysis.fuzzability.score();+ let export = if function.exported {+ EXPORT_PUBLIC+ } else {+ EXPORT_INTERNAL+ };+ let simplicity = arg_simplicity(analysis.context_args);+ let name = signal.reliability.score();++ let score: f64 = [+ (undiscovered, weights.undiscovered),+ (fuzzability, weights.fuzzability),+ (accumulated, weights.accumulated),+ (export, weights.export),+ (simplicity, weights.arg_simplicity),+ (name, weights.name),+ ]+ .iter()+ .map(|(value, weight)| value * weight)+ .sum();++ let reasons = vec![+ format!(+ "undiscovered danger {} of {undiscovered_ceiling} -> {undiscovered:.3}",+ function.complexity.undiscovered+ ),+ format!("signature {:?} -> {fuzzability:.3}", analysis.fuzzability),+ format!(+ "accumulated danger {} of {accumulated_ceiling} -> {accumulated:.3}",+ function.complexity.accumulated+ ),+ format!(+ "{}",+ if function.reachable_from_harness {+ "an in-tree harness already calls this directly"+ } else {+ "no in-tree harness calls this directly"+ }+ ),+ format!("{} context args -> {simplicity:.3}", analysis.context_args),+ format!("name signal {:?} -> {name:.3}", signal.reliability),+ ];++ Candidate {+ name: function.name,+ params: function.params,+ result: function.result,+ header: function.header,+ line: function.line,+ fuzzability: analysis.fuzzability,+ analysis,+ complexity: function.complexity,+ exported: function.exported,+ reachable_from_harness: function.reachable_from_harness,+ score,+ reasons,+ }+}+#[must_use]pub fn rank(functions: Vec<Function>, weights: &Weights) -> Ranking {let mut excluded = Vec::new();@@ -164,65 +236,14 @@ pub fn rank(functions: Vec<Function>, weights: &Weights) -> Ranking {let mut candidates: Vec<Candidate> = kept.into_iter().map(|(function, signal, analysis)| {- let accumulated =- complexity_score(function.complexity.accumulated, accumulated_ceiling);- let undiscovered =- complexity_score(function.complexity.undiscovered, undiscovered_ceiling);- let fuzzability = analysis.fuzzability.score();- let export = if function.exported {- EXPORT_PUBLIC- } else {- EXPORT_INTERNAL- };- let simplicity = arg_simplicity(analysis.context_args);- let name = signal.reliability.score();-- let score: f64 = [- (undiscovered, weights.undiscovered),- (fuzzability, weights.fuzzability),- (accumulated, weights.accumulated),- (export, weights.export),- (simplicity, weights.arg_simplicity),- (name, weights.name),- ]- .iter()- .map(|(value, weight)| value * weight)- .sum();-- let reasons = vec![- format!(- "undiscovered danger {} of {undiscovered_ceiling} -> {undiscovered:.3}",- function.complexity.undiscovered- ),- format!("signature {:?} -> {fuzzability:.3}", analysis.fuzzability),- format!(- "accumulated danger {} of {accumulated_ceiling} -> {accumulated:.3}",- function.complexity.accumulated- ),- format!(- "{}",- if function.reachable_from_harness {- "an in-tree harness already calls this directly"- } else {- "no in-tree harness calls this directly"- }- ),- format!("{} context args -> {simplicity:.3}", analysis.context_args),- format!("name signal {:?} -> {name:.3}", signal.reliability),- ];-- Candidate {- name: function.name,- header: function.header,- line: function.line,- fuzzability: analysis.fuzzability,+ score_candidate(+ function,+ &signal,analysis,- complexity: function.complexity,- exported: function.exported,- reachable_from_harness: function.reachable_from_harness,- score,- reasons,- }+ weights,+ accumulated_ceiling,+ undiscovered_ceiling,+ )}).collect();@@ -270,6 +291,7 @@ mod tests {Function {name: name.to_owned(),params,+ result: Returns::default(),header: "x.h".into(),line: 1,exported: true,@@ -400,6 +422,7 @@ mod tests {#[test]fn a_deep_complex_custom_stream_entry_outranks_a_trivial_direct_buffer() {let client_open = Function {+ result: Returns::default(),name: "TIFFClientOpen".to_owned(),params: vec![param(diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rsindex ad6aa4ff..c40ee9a9 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs@@ -93,12 +93,16 @@ impl Pointee {}}-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]pub enum Shape {- Pointer { pointee: Pointee, is_const: bool },+ Pointer {+ pointee: Pointee,+ is_const: bool,+ },Integral,Record(String),Float,+ #[default]Void,Other,}@@ -110,6 +114,12 @@ pub struct Param {pub shape: Shape,}+#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]+pub struct Returns {+ pub spelling: String,+ pub shape: Shape,+}+#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]pub enum ParamRole {Buffer,@@ -371,20 +381,19 @@ fn provisional_role(param: &Param) -> ParamRole {}_ => ParamRole::Context,},- Shape::Integral => ParamRole::Config,_ => ParamRole::Config,}}fn grade(params: &[Param], roles: &[ParamRole], paired: Option<usize>) -> Fuzzability {- if let Some(index) = paired {- if let Shape::Pointer { pointee, .. } = ¶ms[index].shape {- return if pointee.is_exact_byte() {- Fuzzability::DirectBuffer- } else {- Fuzzability::CastBuffer- };- }+ if let Some(index) = paired+ && let Shape::Pointer { pointee, .. } = ¶ms[index].shape+ {+ return if pointee.is_exact_byte() {+ Fuzzability::DirectBuffer+ } else {+ Fuzzability::CastBuffer+ };}if roles.contains(&ParamRole::Stream) {return Fuzzability::Stream;@@ -395,14 +404,14 @@ fn grade(params: &[Param], roles: &[ParamRole], paired: Option<usize>) -> Fuzzab// A const byte buffer whose extent we could not locate is still untrusted input.// Falling straight through to NoInput here hard-excluded the canonical decode// entry of brotli, zstd, lz4 and the whole OpenSSL d2i_* family.- if let Some(index) = roles.iter().position(|role| *role == ParamRole::Buffer) {- if let Shape::Pointer { pointee, .. } = ¶ms[index].shape {- return if pointee.is_exact_byte() {- Fuzzability::DirectBuffer- } else {- Fuzzability::CastBuffer- };- }+ if let Some(index) = roles.iter().position(|role| *role == ParamRole::Buffer)+ && let Shape::Pointer { pointee, .. } = ¶ms[index].shape+ {+ return if pointee.is_exact_byte() {+ Fuzzability::DirectBuffer+ } else {+ Fuzzability::CastBuffer+ };}if roles.contains(&ParamRole::Path) {return Fuzzability::Path;diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rsindex eb59326a..e87e940a 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs@@ -240,6 +240,7 @@ pub fn analyze(options: &SurfaceOptions) -> Result<Surface, SurfaceError> {.map(|item| Function {name: item.name.clone(),params: item.params.clone(),+ result: item.result.clone(),header: item.header.clone(),line: item.line,exported: graph.get(&item.name).is_none_or(|node| node.exported),diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rsindex ab12874d..c8dfc267 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rs+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/src/main.rs@@ -116,6 +116,7 @@ struct CrashesArgs {}#[derive(clap::Args)]+#[allow(clippy::struct_excessive_bools)]struct SurfaceArgs {#[arg(help = "source tree of the target library")]source: PathBuf,@@ -161,9 +162,9 @@ fn dispatch() -> Result<(), Box<dyn Error>> {fn surface(args: &SurfaceArgs) -> Result<(), Box<dyn Error>> {let mut options = SurfaceOptions::new(&args.source);- options.install = args.install.clone();- options.includes = args.includes.clone();- options.defines = args.defines.clone();+ options.install.clone_from(&args.install);+ options.includes.clone_from(&args.includes);+ options.defines.clone_from(&args.defines);options.language = if args.cpp { Language::Cpp } else { Language::C };options.ignore_harnesses = !args.frontier;