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): M3 surface analysis, ranks parser entry points from source
CarterPerez-devc0fd4224e686
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lockindex 306defef..e26daff0 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.lock@@ -95,6 +95,27 @@ version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"+[[package]]+name = "clang"+version = "2.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "84c044c781163c001b913cd018fc95a628c50d0d2dfea8bca77dad71edb16e37"+dependencies = [+ "clang-sys",+ "libc",+]++[[package]]+name = "clang-sys"+version = "1.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"+dependencies = [+ "glob",+ "libc",+ "libloading",+]+[[package]]name = "clap"version = "4.6.4"@@ -198,6 +219,12 @@ dependencies = ["version_check",]+[[package]]+name = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"+[[package]]name = "hashbrown"version = "0.14.5"@@ -240,6 +267,16 @@ version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"+[[package]]+name = "libloading"+version = "0.8.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"+dependencies = [+ "cfg-if",+ "windows-link",+]+[[package]]name = "libsqlite3-sys"version = "0.30.1"@@ -260,6 +297,8 @@ dependencies = ["lisdex-core","lisdex-fuzz","lisdex-ingest",+ "lisdex-surface",+ "serde_json",][[package]]@@ -298,6 +337,15 @@ dependencies = ["thiserror",]+[[package]]+name = "lisdex-surface"+version = "0.1.0"+dependencies = [+ "clang",+ "serde",+ "thiserror",+]+[[package]]name = "memchr"version = "2.8.3"diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.tomlindex ee3ce817..a07569d9 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Cargo.toml@@ -13,6 +13,7 @@ authors = ["Carter Perez <[email protected]>"][workspace.dependencies]thiserror = "2"+clang = { version = "2.0.0", features = ["clang_10_0", "runtime"] }rusqlite = { version = "0.32", features = ["bundled"] }sha2 = "0.10"clap = { version = "4", features = ["derive"] }@@ -22,6 +23,7 @@ lisdex-core = { path = "crates/lisdex-core" }lisdex-fuzz = { path = "crates/lisdex-fuzz" }lisdex-ingest = { path = "crates/lisdex-ingest" }lisdex-build = { path = "crates/lisdex-build" }+lisdex-surface = { path = "crates/lisdex-surface" }[workspace.lints.rust]unsafe_code = "deny"diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.dev b/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.devindex a3146743..6d8f2102 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.dev+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/Dockerfile.dev@@ -16,6 +16,7 @@ ENV MAGMA_ROOT=/opt/magmaENV MAGMA_WORK=/opt/magma-workENV AFL_PATH=/usr/local/lib/aflENV LISDEX_AFL_DRIVER=/usr/local/lib/afl/libAFLDriver.a+ENV LIBCLANG_PATH=/usr/lib/llvm-20/libRUN apt-get update && apt-get install -y --no-install-recommends \autoconf \@@ -29,7 +30,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \libreadline-dev \liblzma-dev \tcl \- libclang-dev \+ libclang-20-dev \bison \flex \gperf \diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/Cargo.tomlnew file mode 100644index 00000000..2fea1925--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/Cargo.toml@@ -0,0 +1,18 @@+# ©AngelaMos | 2026+# Cargo.toml++[package]+name = "lisdex-surface"+version = "0.1.0"+edition.workspace = true+rust-version.workspace = true+license.workspace = true+authors.workspace = true++[dependencies]+thiserror.workspace = true+serde.workspace = true+clang.workspace = true++[lints]+workspace = truediff --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.rsnew file mode 100644index 00000000..0f1ac89f--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs@@ -0,0 +1,597 @@+// ©AngelaMos | 2026+// complexity.rs++use std::collections::{BTreeMap, BTreeSet, VecDeque};+use std::path::Path;++use clang::{Entity, EntityKind, Linkage};++use crate::extract::{self, ExtractError, ParseOptions};++pub const BASE_COMPLEXITY: u32 = 1;++#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]+pub struct Defined {+ pub name: String,+ pub own: u32,+ pub loops: u32,+ pub nested_loops: u32,+ pub max_nesting: u32,+ pub calls: Vec<String>,+ pub exported: bool,+}++impl Defined {+ #[must_use]+ pub fn danger(&self) -> u32 {+ self.own+ .saturating_add(self.loops)+ .saturating_add(self.nested_loops)+ .saturating_add(self.max_nesting)+ }+}++#[must_use]+pub fn is_decision(kind: EntityKind) -> bool {+ matches!(+ kind,+ EntityKind::IfStmt+ | EntityKind::ForStmt+ | EntityKind::WhileStmt+ | EntityKind::DoStmt+ | EntityKind::CaseStmt+ | EntityKind::ConditionalOperator+ | EntityKind::CatchStmt+ )+}++#[must_use]+pub fn is_loop(kind: EntityKind) -> bool {+ matches!(+ kind,+ EntityKind::ForStmt | EntityKind::WhileStmt | EntityKind::DoStmt+ )+}++#[must_use]+pub fn is_nesting(kind: EntityKind) -> bool {+ is_loop(kind) || matches!(kind, EntityKind::IfStmt | EntityKind::SwitchStmt)+}++#[derive(Debug, Default)]+struct Metrics {+ decisions: u32,+ loops: u32,+ nested_loops: u32,+ max_nesting: u32,+ calls: BTreeSet<String>,+}++fn walk(entity: &Entity, metrics: &mut Metrics, depth: u32, loop_depth: u32) {+ let children = entity.get_children();+ let parent_is_if = entity.get_kind() == EntityKind::IfStmt;+ let last = children.len().saturating_sub(1);+ for (position, child) in children.iter().enumerate() {+ let kind = child.get_kind();+ if is_decision(kind) {+ metrics.decisions += 1;+ }+ let inside_loop = is_loop(kind);+ if inside_loop {+ metrics.loops += 1;+ if loop_depth > 0 {+ metrics.nested_loops += 1;+ }+ }+ if kind == EntityKind::CallExpr+ && let Some(target) = child.get_reference()+ && target.get_kind() == EntityKind::FunctionDecl+ && let Some(name) = target.get_name()+ {+ metrics.calls.insert(name);+ }+ let chained_else = parent_is_if && kind == EntityKind::IfStmt && position == last;+ let next_depth = if is_nesting(kind) && !chained_else {+ depth + 1+ } else {+ depth+ };+ metrics.max_nesting = metrics.max_nesting.max(next_depth);+ walk(+ child,+ metrics,+ next_depth,+ if inside_loop {+ loop_depth + 1+ } else {+ loop_depth+ },+ );+ }+}++pub fn parse_source(path: &Path, options: &ParseOptions) -> Result<Vec<Defined>, ExtractError> {+ if !path.is_file() {+ return Err(ExtractError::NotAFile(path.to_path_buf()));+ }+ extract::with_index(|index| {+ let unit = index+ .parser(path)+ .arguments(&options.argv())+ .skip_function_bodies(false)+ .parse()+ .map_err(|source| ExtractError::Parse {+ path: path.to_path_buf(),+ reason: source.to_string(),+ })?;++ let mut found = Vec::new();+ let mut seen = BTreeSet::new();+ for child in unit.get_entity().get_children() {+ collect(&child, &mut found, &mut seen);+ }+ Ok(found)+ })+}++fn collect(entity: &Entity, found: &mut Vec<Defined>, seen: &mut BTreeSet<String>) {+ match entity.get_kind() {+ EntityKind::FunctionDecl => {+ if !entity.is_definition() {+ return;+ }+ let Some(name) = entity.get_name() else {+ return;+ };+ if !seen.insert(name.clone()) {+ return;+ }+ let mut metrics = Metrics::default();+ walk(entity, &mut metrics, 0, 0);+ found.push(Defined {+ name,+ own: BASE_COMPLEXITY + metrics.decisions,+ loops: metrics.loops,+ nested_loops: metrics.nested_loops,+ max_nesting: metrics.max_nesting,+ calls: metrics.calls.into_iter().collect(),+ exported: entity.get_linkage() != Some(Linkage::Internal),+ });+ }+ EntityKind::LinkageSpec | EntityKind::Namespace | EntityKind::UnexposedDecl => {+ for child in entity.get_children() {+ collect(&child, found, seen);+ }+ }+ _ => {}+ }+}++#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct CallGraph {+ nodes: BTreeMap<String, Defined>,+}++impl From<Vec<Defined>> for CallGraph {+ fn from(defined: Vec<Defined>) -> Self {+ Self {+ nodes: defined+ .into_iter()+ .map(|item| (item.name.clone(), item))+ .collect(),+ }+ }+}++impl CallGraph {+ #[must_use]+ pub fn get(&self, name: &str) -> Option<&Defined> {+ self.nodes.get(name)+ }++ #[must_use]+ pub fn own(&self, name: &str) -> u32 {+ self.nodes.get(name).map_or(0, |node| node.own)+ }++ #[must_use]+ pub fn names(&self) -> impl Iterator<Item = &String> {+ self.nodes.keys()+ }++ #[must_use]+ pub fn reachable_from(&self, seeds: &[String]) -> BTreeSet<String> {+ let mut visited = BTreeSet::new();+ let mut queue: VecDeque<&str> = VecDeque::new();+ for seed in seeds {+ queue.push_back(seed.as_str());+ }+ while let Some(name) = queue.pop_front() {+ let Some(node) = self.nodes.get(name) else {+ continue;+ };+ if !visited.insert(node.name.clone()) {+ continue;+ }+ for call in &node.calls {+ if !visited.contains(call) {+ queue.push_back(call.as_str());+ }+ }+ }+ visited+ }++ #[must_use]+ pub fn accumulated(&self, name: &str) -> u32 {+ self.reachable_from(std::slice::from_ref(&name.to_owned()))+ .iter()+ .map(|reached| self.own(reached))+ .sum()+ }++ #[must_use]+ pub fn danger(&self, name: &str) -> u32 {+ self.nodes.get(name).map_or(0, Defined::danger)+ }++ #[must_use]+ pub fn accumulated_danger(&self, name: &str) -> u32 {+ self.reachable_from(std::slice::from_ref(&name.to_owned()))+ .iter()+ .map(|reached| self.danger(reached))+ .sum()+ }++ #[must_use]+ pub fn undiscovered_danger(&self, name: &str, already: &BTreeSet<String>) -> u32 {+ self.reachable_from(std::slice::from_ref(&name.to_owned()))+ .iter()+ .filter(|reached| !already.contains(*reached))+ .map(|reached| self.danger(reached))+ .sum()+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::extract::ParseOptions;+ use std::path::PathBuf;++ fn source(label: &str, body: &str) -> PathBuf {+ let dir =+ std::env::temp_dir().join(format!("lisdex-complexity-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("unit.c");+ std::fs::write(&path, body).unwrap();+ path+ }++ fn defined(label: &str, body: &str) -> Vec<Defined> {+ parse_source(&source(label, body), &ParseOptions::default()).unwrap()+ }++ fn find<'a>(found: &'a [Defined], name: &str) -> &'a Defined {+ found.iter().find(|item| item.name == name).unwrap()+ }++ #[test]+ fn a_straight_line_function_has_the_minimum_complexity_of_one() {+ let found = defined("straight", "int f(int a) { return a + 1; }\n");+ assert_eq!(find(&found, "f").own, 1);+ }++ #[test]+ fn each_branch_adds_one_decision_point() {+ let found = defined(+ "branches",+ "int f(int a) { if (a) { return 1; } if (a > 2) { return 2; } return 0; }\n",+ );+ assert_eq!(find(&found, "f").own, 3);+ }++ #[test]+ fn loops_and_switch_cases_are_decision_points() {+ let found = defined(+ "loops",+ "int f(int a) {\n\+ int i;\n\+ for (i = 0; i < a; i++) { a += i; }\n\+ while (a > 10) { a--; }\n\+ switch (a) { case 1: return 1; case 2: return 2; default: break; }\n\+ return a;\n\+ }\n",+ );+ assert_eq!(find(&found, "f").own, 5);+ }++ #[test]+ fn a_ternary_is_a_decision_point() {+ let found = defined("ternary", "int f(int a) { return a ? 1 : 0; }\n");+ assert_eq!(find(&found, "f").own, 2);+ }++ #[test]+ fn the_functions_a_body_calls_are_recorded_as_edges() {+ let found = defined(+ "edges",+ "int helper(int x) { return x; }\n\+ int other(int x) { return x; }\n\+ int f(int a) { return helper(a) + other(a); }\n",+ );+ let calls = &find(&found, "f").calls;+ assert!(calls.contains(&"helper".to_owned()), "{calls:?}");+ assert!(calls.contains(&"other".to_owned()), "{calls:?}");+ }++ #[test]+ fn a_declaration_without_a_body_is_not_a_definition() {+ let found = defined("declonly", "int f(int a);\nint g(int a) { return a; }\n");+ assert!(found.iter().all(|item| item.name != "f"), "{found:?}");+ assert!(found.iter().any(|item| item.name == "g"));+ }++ #[test]+ fn control_flow_is_still_counted_when_the_unit_does_not_type_check() {+ let found = defined(+ "typeerrors",+ "int f(UNKNOWN_T a) { if (a) { return 1; } return 0; }\n",+ );+ assert_eq!(+ find(&found, "f").own,+ 2,+ "complexity is structural, so unlike type classification it survives a \+ source file we lack the exact flags for"+ );+ }++ #[test]+ fn a_static_function_is_recorded_but_marked_internal() {+ let found = defined(+ "static",+ "static int hidden(int a) { return a; }\nint shown(int a) { return hidden(a); }\n",+ );+ assert!(!find(&found, "hidden").exported);+ assert!(find(&found, "shown").exported);+ }++ #[test]+ fn loops_are_counted_separately_from_branches() {+ let found = defined(+ "leopardloops",+ "int f(int a) { int i; for (i = 0; i < a; i++) { a++; } while (a) { a--; } return a; }\n",+ );+ assert_eq!(find(&found, "f").loops, 2);+ }++ #[test]+ fn a_loop_inside_a_loop_is_counted_as_nested() {+ let found = defined(+ "leopardnested",+ "int f(int a) {\n\+ int i, j;\n\+ for (i = 0; i < a; i++) { for (j = 0; j < a; j++) { a++; } }\n\+ return a;\n\+ }\n",+ );+ let function = find(&found, "f");+ assert_eq!(function.loops, 2);+ assert_eq!(function.nested_loops, 1);+ }++ #[test]+ fn an_else_if_chain_is_flat_not_nested() {+ let chain = defined(+ "elseifchain",+ "int f(int a) {\n\+ if (a == 1) { return 1; }\n\+ else if (a == 2) { return 2; }\n\+ else if (a == 3) { return 3; }\n\+ else if (a == 4) { return 4; }\n\+ return 0;\n\+ }\n",+ );+ assert_eq!(+ find(&chain, "f").max_nesting,+ 1,+ "parser chunk dispatch is written as else-if chains; counting them as \+ depth over-reported libarchive by 2.5x"+ );+ }++ #[test]+ fn genuine_nesting_is_still_counted_after_the_else_if_fix() {+ let nested = defined(+ "trulynested",+ "int f(int a) {\n\+ if (a) { if (a > 1) { if (a > 2) { return 3; } } }\n\+ return 0;\n\+ }\n",+ );+ assert_eq!(find(&nested, "f").max_nesting, 3);+ }++ #[test]+ fn maximum_nesting_depth_is_recorded() {+ let found = defined(+ "leoparddepth",+ "int f(int a) {\n\+ if (a) { if (a > 1) { while (a) { a--; } } }\n\+ return a;\n\+ }\n",+ );+ assert_eq!(find(&found, "f").max_nesting, 3);+ }++ #[test]+ fn danger_combines_cyclomatic_complexity_with_the_loop_metrics() {+ let plain = Defined {+ name: "plain".to_owned(),+ own: 5,+ loops: 0,+ nested_loops: 0,+ max_nesting: 0,+ calls: Vec::new(),+ exported: true,+ };+ let looping = Defined {+ loops: 3,+ nested_loops: 2,+ max_nesting: 4,+ ..plain.clone()+ };+ assert_eq!(plain.danger(), 5);+ assert!(+ looping.danger() > plain.danger(),+ "the SoK's top-ranked metric family is loop structure, not raw cyclomatic \+ complexity alone"+ );+ }++ #[test]+ fn undiscovered_danger_excludes_what_an_existing_harness_already_reaches() {+ let graph = CallGraph::from(vec![+ node("entry", 2, vec!["covered", "fresh"]),+ node("covered", 10, vec![]),+ node("fresh", 20, vec![]),+ ]);+ let already = BTreeSet::from(["covered".to_owned()]);+ assert_eq!(graph.accumulated_danger("entry"), 32);+ assert_eq!(graph.undiscovered_danger("entry", &already), 22);+ }++ #[test]+ fn undiscovered_equals_accumulated_when_no_harness_exists() {+ let graph = CallGraph::from(vec![+ node("entry", 3, vec!["leaf"]),+ node("leaf", 9, vec![]),+ ]);+ let nothing = BTreeSet::new();+ assert_eq!(+ graph.undiscovered_danger("entry", ¬hing),+ graph.accumulated_danger("entry"),+ "a library with no in-tree harness must degrade gracefully, not to zero"+ );+ }++ fn node(name: &str, danger: u32, calls: Vec<&str>) -> Defined {+ Defined {+ name: name.to_owned(),+ own: danger,+ loops: 0,+ nested_loops: 0,+ max_nesting: 0,+ calls: calls.into_iter().map(str::to_owned).collect(),+ exported: true,+ }+ }++ #[test]+ fn accumulated_complexity_sums_the_whole_reachable_call_tree() {+ let graph = CallGraph::from(vec![+ Defined {+ name: "entry".to_owned(),+ own: 2,+ calls: vec!["middle".to_owned()],+ exported: true,+ ..Defined::default()+ },+ Defined {+ name: "middle".to_owned(),+ own: 5,+ calls: vec!["leaf".to_owned()],+ exported: false,+ ..Defined::default()+ },+ Defined {+ name: "leaf".to_owned(),+ own: 10,+ calls: Vec::new(),+ exported: false,+ ..Defined::default()+ },+ ]);+ assert_eq!(graph.accumulated("entry"), 17);+ assert_eq!(graph.accumulated("middle"), 15);+ assert_eq!(graph.accumulated("leaf"), 10);+ }++ #[test]+ fn a_recursive_cycle_does_not_hang_or_double_count() {+ let graph = CallGraph::from(vec![+ Defined {+ name: "a".to_owned(),+ own: 1,+ calls: vec!["b".to_owned()],+ exported: true,+ ..Defined::default()+ },+ Defined {+ name: "b".to_owned(),+ own: 2,+ calls: vec!["a".to_owned(), "c".to_owned()],+ exported: false,+ ..Defined::default()+ },+ Defined {+ name: "c".to_owned(),+ own: 4,+ calls: vec!["b".to_owned()],+ exported: false,+ ..Defined::default()+ },+ ]);+ assert_eq!(graph.accumulated("a"), 7);+ }++ #[test]+ fn an_unknown_function_accumulates_nothing_rather_than_panicking() {+ let graph = CallGraph::from(Vec::new());+ assert_eq!(graph.accumulated("absent"), 0);+ }++ #[test]+ fn calls_into_functions_with_no_definition_are_ignored_not_counted() {+ let graph = CallGraph::from(vec![Defined {+ name: "entry".to_owned(),+ own: 3,+ calls: vec!["memcpy".to_owned(), "malloc".to_owned()],+ exported: true,+ ..Defined::default()+ }]);+ assert_eq!(graph.accumulated("entry"), 3);+ }++ #[test]+ fn the_set_of_functions_reachable_from_a_seed_is_the_novelty_frontier() {+ let graph = CallGraph::from(vec![+ Defined {+ name: "harness_calls_this".to_owned(),+ own: 1,+ calls: vec!["deep".to_owned()],+ exported: true,+ ..Defined::default()+ },+ Defined {+ name: "deep".to_owned(),+ own: 1,+ calls: Vec::new(),+ exported: false,+ ..Defined::default()+ },+ Defined {+ name: "untouched".to_owned(),+ own: 1,+ calls: Vec::new(),+ exported: true,+ ..Defined::default()+ },+ ]);+ let reached = graph.reachable_from(&["harness_calls_this".to_owned()]);+ assert!(reached.contains("harness_calls_this"));+ assert!(reached.contains("deep"));+ assert!(!reached.contains("untouched"));+ }+}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.rsnew file mode 100644index 00000000..bd263ef1--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs@@ -0,0 +1,530 @@+// ©AngelaMos | 2026+// extract.rs++use std::collections::BTreeSet;+use std::path::{Path, PathBuf};+use std::sync::{Mutex, PoisonError};++use clang::diagnostic::Severity;+use clang::{Clang, Entity, EntityKind, Index, Type, TypeKind};++use crate::signature::{Param, Pointee, Shape};++static PARSE_LOCK: Mutex<()> = Mutex::new(());++pub const C_ARGS: [&str; 3] = ["-x", "c", "-std=c11"];+pub const CPP_ARGS: [&str; 3] = ["-x", "c++", "-std=c++17"];++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub enum Language {+ #[default]+ C,+ Cpp,+}++impl Language {+ #[must_use]+ pub fn args(self) -> [&'static str; 3] {+ match self {+ Language::C => C_ARGS,+ Language::Cpp => CPP_ARGS,+ }+ }+}++#[derive(Debug, Clone, Default)]+pub struct ParseOptions {+ pub includes: Vec<PathBuf>,+ pub defines: Vec<String>,+ pub extra_args: Vec<String>,+ pub language: Language,+}++impl ParseOptions {+ #[must_use]+ pub fn argv(&self) -> Vec<String> {+ let mut args: Vec<String> = self+ .language+ .args()+ .iter()+ .map(|arg| (*arg).to_owned())+ .collect();+ for include in &self.includes {+ args.push(format!("-I{}", include.display()));+ }+ for define in &self.defines {+ args.push(format!("-D{define}"));+ }+ args.extend(self.extra_args.iter().cloned());+ args+ }+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Declared {+ pub name: String,+ pub params: Vec<Param>,+ pub header: PathBuf,+ pub line: u32,+}++#[derive(Debug, thiserror::Error)]+pub enum ExtractError {+ #[error("{0} is not a file")]+ NotAFile(PathBuf),+ #[error("libclang is unavailable: {0}")]+ Libclang(String),+ #[error("io error resolving {path}: {source}")]+ Io {+ path: PathBuf,+ source: std::io::Error,+ },+ #[error("{path} could not be parsed: {reason}")]+ Parse { path: PathBuf, reason: String },+ #[error(+ "{path} does not type check ({count} errors, first: {first}) - ranking it would silently under-report byte buffers"+ )]+ Diagnostics {+ path: PathBuf,+ count: usize,+ first: String,+ },+}++pub fn with_index<T, F>(action: F) -> Result<T, ExtractError>+where+ F: FnOnce(&Index) -> Result<T, ExtractError>,+{+ let _guard = PARSE_LOCK.lock().unwrap_or_else(PoisonError::into_inner);+ let clang = Clang::new().map_err(ExtractError::Libclang)?;+ let index = Index::new(&clang, false, false);+ action(&index)+}++fn is_integral(kind: TypeKind) -> bool {+ matches!(+ kind,+ TypeKind::Bool+ | TypeKind::CharS+ | TypeKind::CharU+ | TypeKind::SChar+ | TypeKind::UChar+ | TypeKind::Short+ | TypeKind::UShort+ | TypeKind::Int+ | TypeKind::UInt+ | TypeKind::Long+ | TypeKind::ULong+ | TypeKind::LongLong+ | TypeKind::ULongLong+ | TypeKind::Int128+ | TypeKind::UInt128+ | TypeKind::Enum+ | TypeKind::WChar+ | TypeKind::Char16+ | TypeKind::Char32+ )+}++fn record_name(ty: &Type) -> String {+ ty.get_declaration()+ .and_then(|declaration| declaration.get_name())+ .unwrap_or_else(|| ty.get_display_name())+}++fn pointee_of(ty: &Type) -> Pointee {+ match ty.get_kind() {+ TypeKind::UChar => Pointee::UnsignedChar,+ TypeKind::SChar => Pointee::SignedChar,+ TypeKind::CharS | TypeKind::CharU => Pointee::Char,+ TypeKind::Void => Pointee::Void,+ TypeKind::Record => Pointee::Record(record_name(ty)),+ TypeKind::FunctionPrototype | TypeKind::FunctionNoPrototype => Pointee::Function,+ TypeKind::Pointer => Pointee::Pointer,+ kind if is_integral(kind) => Pointee::Integral,+ _ => Pointee::Other,+ }+}++fn as_pointer(target: &Type, inherited_const: bool) -> Shape {+ let canonical = target.get_canonical_type();+ Shape::Pointer {+ pointee: pointee_of(&canonical),+ is_const: inherited_const || target.is_const_qualified() || canonical.is_const_qualified(),+ }+}++#[must_use]+pub fn shape_of(ty: &Type) -> Shape {+ let canonical = ty.get_canonical_type();+ match canonical.get_kind() {+ TypeKind::Pointer => canonical+ .get_pointee_type()+ .map_or(Shape::Other, |pointee| as_pointer(&pointee, false)),+ // An array's canonical type carries the const; clang_getElementType returns+ // the element UNQUALIFIED. Without inheriting it, `const unsigned char d[]`+ // reads as non-const and the whole function drops out as NoDataInput.+ TypeKind::ConstantArray+ | TypeKind::IncompleteArray+ | TypeKind::VariableArray+ | TypeKind::DependentSizedArray => {+ let array_is_const = canonical.is_const_qualified() || ty.is_const_qualified();+ canonical+ .get_element_type()+ .map_or(Shape::Other, |element| as_pointer(&element, array_is_const))+ }+ TypeKind::Record => Shape::Record(record_name(&canonical)),+ TypeKind::Float | TypeKind::Double | TypeKind::LongDouble => Shape::Float,+ TypeKind::Void => Shape::Void,+ kind if is_integral(kind) => Shape::Integral,+ _ => Shape::Other,+ }+}++fn declared_in(entity: &Entity, target: &Path) -> Option<u32> {+ let location = entity.get_location()?.get_file_location();+ let file = location.file?;+ let path = std::fs::canonicalize(file.get_path()).ok()?;+ (path == target).then_some(location.line)+}++fn parameters(entity: &Entity) -> Vec<Param> {+ entity+ .get_arguments()+ .unwrap_or_default()+ .iter()+ .map(|argument| {+ let ty = argument.get_type();+ Param {+ name: argument.get_name(),+ spelling: ty+ .as_ref()+ .map(clang::Type::get_display_name)+ .unwrap_or_default(),+ shape: ty.as_ref().map_or(Shape::Other, shape_of),+ }+ })+ .collect()+}++fn collect(entity: &Entity, target: &Path, found: &mut Vec<Declared>, seen: &mut BTreeSet<String>) {+ for child in entity.get_children() {+ match child.get_kind() {+ EntityKind::FunctionDecl => {+ let Some(name) = child.get_name() else {+ continue;+ };+ let Some(line) = declared_in(&child, target) else {+ continue;+ };+ if seen.insert(name.clone()) {+ found.push(Declared {+ name,+ params: parameters(&child),+ header: target.to_path_buf(),+ line,+ });+ }+ }+ EntityKind::LinkageSpec | EntityKind::Namespace | EntityKind::UnexposedDecl => {+ collect(&child, target, found, seen);+ }+ _ => {}+ }+ }+}++pub fn parse_header(path: &Path, options: &ParseOptions) -> Result<Vec<Declared>, ExtractError> {+ if !path.is_file() {+ return Err(ExtractError::NotAFile(path.to_path_buf()));+ }+ let target = std::fs::canonicalize(path).map_err(|source| ExtractError::Io {+ path: path.to_path_buf(),+ source,+ })?;++ with_index(|index| {+ let unit = index+ .parser(&target)+ .arguments(&options.argv())+ .skip_function_bodies(true)+ .parse()+ .map_err(|source| ExtractError::Parse {+ path: target.clone(),+ reason: source.to_string(),+ })?;++ let failures: Vec<String> = unit+ .get_diagnostics()+ .iter()+ .filter(|diagnostic| {+ matches!(diagnostic.get_severity(), Severity::Error | Severity::Fatal)+ })+ .map(|diagnostic| diagnostic.get_text())+ .collect();+ if let Some(first) = failures.first() {+ return Err(ExtractError::Diagnostics {+ path: target.clone(),+ count: failures.len(),+ first: first.clone(),+ });+ }++ let mut found = Vec::new();+ let mut seen = BTreeSet::new();+ collect(&unit.get_entity(), &target, &mut found, &mut seen);+ Ok(found)+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::signature::{Pointee, Shape};+ use std::path::PathBuf;++ fn header(label: &str, body: &str) -> PathBuf {+ let dir =+ std::env::temp_dir().join(format!("lisdex-extract-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("target.h");+ std::fs::write(&path, body).unwrap();+ path+ }++ fn parse(label: &str, body: &str) -> Vec<Declared> {+ let path = header(label, body);+ parse_header(&path, &ParseOptions::default()).unwrap()+ }++ fn named<'a>(found: &'a [Declared], name: &str) -> &'a Declared {+ found+ .iter()+ .find(|item| item.name == name)+ .unwrap_or_else(|| panic!("{name} not found in {:?}", names(found)))+ }++ fn names(found: &[Declared]) -> Vec<&str> {+ found.iter().map(|item| item.name.as_str()).collect()+ }++ #[test]+ fn a_plain_declaration_yields_its_name_and_parameters() {+ let found = parse(+ "plain",+ "int my_parse(const unsigned char *data, unsigned long size);\n",+ );+ let function = named(&found, "my_parse");+ assert_eq!(function.params.len(), 2);+ assert_eq!(function.params[0].name.as_deref(), Some("data"));+ }++ #[test]+ fn a_macro_wrapped_declaration_is_still_found() {+ let found = parse(+ "macrowrap",+ "#define MYAPI\n\+ #define MYEXPORT(ordinal, type, name, args) type (MYAPI name) args\n\+ MYEXPORT(1, int, png_style_parse, (const unsigned char *data, unsigned long size));\n",+ );+ assert!(+ found.iter().any(|item| item.name == "png_style_parse"),+ "libpng declares every function through a macro like this: {:?}",+ names(&found)+ );+ }++ #[test]+ fn declarations_pulled_in_from_another_header_are_not_part_of_this_surface() {+ let path = header(+ "included",+ "#include \"other.h\"\nint mine_parse(const unsigned char *d, unsigned long n);\n",+ );+ std::fs::write(+ path.parent().unwrap().join("other.h"),+ "int theirs_parse(const unsigned char *d, unsigned long n);\n",+ )+ .unwrap();+ let found = parse_header(&path, &ParseOptions::default()).unwrap();+ assert!(found.iter().any(|item| item.name == "mine_parse"));+ assert!(+ !found.iter().any(|item| item.name == "theirs_parse"),+ "{:?}",+ names(&found)+ );+ }++ #[test]+ fn a_typedef_chain_resolves_to_the_underlying_byte_type() {+ let found = parse(+ "typedefs",+ "typedef unsigned char byte_t;\n\+ typedef byte_t BYTE;\n\+ int parse_frame(BYTE *data, unsigned int len);\n",+ );+ let function = named(&found, "parse_frame");+ assert_eq!(+ function.params[0].shape,+ Shape::Pointer {+ pointee: Pointee::UnsignedChar,+ is_const: false,+ }+ );+ assert_eq!(function.params[1].shape, Shape::Integral);+ }++ #[test]+ fn const_is_read_off_the_pointee_not_the_pointer() {+ let found = parse("constness", "int f(const unsigned char *data, int n);\n");+ let function = named(&found, "f");+ assert_eq!(+ function.params[0].shape,+ Shape::Pointer {+ pointee: Pointee::UnsignedChar,+ is_const: true,+ }+ );+ }++ #[test]+ fn plain_char_is_ambiguous_and_never_reported_as_an_exact_byte() {+ let found = parse("plainchar", "int f(const char *text, int n);\n");+ let function = named(&found, "f");+ let Shape::Pointer { pointee, .. } = &function.params[0].shape else {+ panic!("expected a pointer");+ };+ assert_eq!(*pointee, Pointee::Char);+ assert!(+ !pointee.is_exact_byte(),+ "plain char is CharS here and CharU on ARM; it must not be an unambiguous byte"+ );+ }++ #[test]+ fn an_explicit_unsigned_char_is_an_exact_byte() {+ let found = parse("uchar", "int f(unsigned char *data, int n);\n");+ let Shape::Pointer { pointee, .. } = &named(&found, "f").params[0].shape else {+ panic!("expected a pointer");+ };+ assert!(pointee.is_exact_byte());+ }++ #[test]+ fn an_array_parameter_is_treated_as_the_pointer_it_decays_to() {+ let found = parse("array", "int f(unsigned char data[16], int n);\n");+ let function = named(&found, "f");+ assert_eq!(+ function.params[0].shape,+ Shape::Pointer {+ pointee: Pointee::UnsignedChar,+ is_const: false,+ }+ );+ }++ #[test]+ fn a_function_pointer_parameter_is_reported_as_a_callback() {+ let found = parse(+ "callback",+ "struct ctx;\n\+ typedef void (*read_fn)(struct ctx *, unsigned char *, unsigned long);\n\+ void set_read(struct ctx *c, void *user, read_fn fn);\n",+ );+ let function = named(&found, "set_read");+ assert_eq!(+ function.params[2].shape,+ Shape::Pointer {+ pointee: Pointee::Function,+ is_const: false,+ }+ );+ }++ #[test]+ fn a_stdio_stream_parameter_is_recognised_through_its_glibc_record_name() {+ let found = parse("stdio", "#include <stdio.h>\nint f(FILE *fp);\n");+ let function = named(&found, "f");+ let analysis = crate::signature::analyze(&function.params);+ assert_eq!(+ analysis.fuzzability,+ crate::signature::Fuzzability::Stream,+ "FILE* canonicalises to struct _IO_FILE on glibc: {:?}",+ function.params[0].shape+ );+ }++ #[test]+ fn a_header_that_does_not_type_check_is_refused_rather_than_guessed_at() {+ let path = header("broken", "int parse_frame(BYTE *data, uint32_t len);\n");+ let error = parse_header(&path, &ParseOptions::default()).unwrap_err();+ assert!(+ matches!(error, ExtractError::Diagnostics { .. }),+ "an unresolved typedef silently degrades BYTE* to int*, halving buffer \+ detection, so it must be an error: {error:?}"+ );+ }++ #[test]+ fn an_include_path_repairs_a_header_that_would_otherwise_be_refused() {+ let path = header(+ "repaired",+ "#include \"types.h\"\nint parse_frame(BYTE *data, unsigned int len);\n",+ );+ let inc = path.parent().unwrap().join("inc");+ std::fs::create_dir_all(&inc).unwrap();+ std::fs::write(inc.join("types.h"), "typedef unsigned char BYTE;\n").unwrap();+ let options = ParseOptions {+ includes: vec![inc],+ ..ParseOptions::default()+ };+ let found = parse_header(&path, &options).unwrap();+ let Shape::Pointer { pointee, .. } = &named(&found, "parse_frame").params[0].shape else {+ panic!("expected a pointer");+ };+ assert_eq!(*pointee, Pointee::UnsignedChar);+ }++ #[test]+ fn functions_inside_an_extern_c_block_are_not_missed() {+ let path = header(+ "externc",+ "extern \"C\" {\nint inner_parse(const unsigned char *d, unsigned long n);\n}\n",+ );+ let options = ParseOptions {+ language: Language::Cpp,+ ..ParseOptions::default()+ };+ let found = parse_header(&path, &options).unwrap();+ assert!(+ found.iter().any(|item| item.name == "inner_parse"),+ "clang::sonar misses these entirely: {:?}",+ names(&found)+ );+ }++ #[test]+ fn a_definition_in_a_header_is_reported_once_not_twice() {+ let found = parse(+ "dedup",+ "int f(const unsigned char *d, unsigned long n);\n\+ int f(const unsigned char *d, unsigned long n);\n",+ );+ assert_eq!(+ found.iter().filter(|item| item.name == "f").count(),+ 1,+ "{:?}",+ names(&found)+ );+ }++ #[test]+ fn a_missing_file_is_an_error_not_a_panic() {+ let error = parse_header(+ std::path::Path::new("/nonexistent/lisdex/extract.h"),+ &ParseOptions::default(),+ )+ .unwrap_err();+ assert!(matches!(error, ExtractError::NotAFile(_)), "{error:?}");+ }+}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.rsnew file mode 100644index 00000000..c4595983--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/harness.rs@@ -0,0 +1,290 @@+// ©AngelaMos | 2026+// harness.rs++use std::collections::BTreeSet;+use std::path::{Path, PathBuf};++pub const ENTRY_POINT: &str = "LLVMFuzzerTestOneInput";+pub const INITIALIZE_POINT: &str = "LLVMFuzzerInitialize";+pub const SOURCE_EXTENSIONS: &[&str] = &["c", "cc", "cpp", "cxx"];+pub const MAX_SOURCE_BYTES: u64 = 4 * 1024 * 1024;+pub const MAX_DEPTH: usize = 12;++pub const SKIP_DIRS: &[&str] = &[+ ".git",+ "build",+ "node_modules",+ "vendor",+ "third_party",+ "3rdparty",+];++pub const NOT_CALLS: &[&str] = &[+ "if",+ "for",+ "while",+ "switch",+ "return",+ "sizeof",+ "do",+ "else",+ "case",+ "catch",+ "defined",+ "static_cast",+ "reinterpret_cast",+ "const_cast",+ "dynamic_cast",+ "alignof",+ "typeof",+ "and",+ "or",+ "not",+];++#[derive(Debug, thiserror::Error)]+pub enum HarnessError {+ #[error("{0} is not a directory")]+ NotADirectory(PathBuf),+ #[error("io error reading {path}: {source}")]+ Io {+ path: PathBuf,+ source: std::io::Error,+ },+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Harness {+ pub path: PathBuf,+ pub calls: Vec<String>,+}++fn is_source(path: &Path) -> bool {+ path.extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| SOURCE_EXTENSIONS.contains(&extension.to_lowercase().as_str()))+}++#[must_use]+pub fn extract_calls(body: &str) -> Vec<String> {+ let chars: Vec<char> = body.chars().collect();+ let mut found = BTreeSet::new();+ let mut index = 0;++ while index < chars.len() {+ if !(chars[index].is_alphabetic() || chars[index] == '_') {+ index += 1;+ continue;+ }+ let start = index;+ while index < chars.len() && (chars[index].is_alphanumeric() || chars[index] == '_') {+ index += 1;+ }+ let identifier: String = chars[start..index].iter().collect();+ let mut lookahead = index;+ while lookahead < chars.len() && chars[lookahead].is_whitespace() {+ lookahead += 1;+ }+ if chars.get(lookahead) == Some(&'(')+ && !NOT_CALLS.contains(&identifier.as_str())+ && identifier != ENTRY_POINT+ && identifier != INITIALIZE_POINT+ {+ found.insert(identifier);+ }+ }++ found.into_iter().collect()+}++fn walk(root: &Path, depth: usize, found: &mut Vec<Harness>) -> Result<(), HarnessError> {+ if depth > MAX_DEPTH {+ return Ok(());+ }+ let entries = std::fs::read_dir(root).map_err(|source| HarnessError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ for entry in entries {+ let entry = entry.map_err(|source| HarnessError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ let path = entry.path();+ let name = entry.file_name().to_string_lossy().to_lowercase();+ if path.is_dir() {+ if !SKIP_DIRS.contains(&name.as_str()) {+ walk(&path, depth + 1, found)?;+ }+ continue;+ }+ if !is_source(&path) {+ continue;+ }+ let oversized = entry+ .metadata()+ .map(|meta| meta.len() > MAX_SOURCE_BYTES)+ .unwrap_or(true);+ if oversized {+ continue;+ }+ let Ok(body) = std::fs::read_to_string(&path) else {+ continue;+ };+ if body.contains(ENTRY_POINT) {+ found.push(Harness {+ path,+ calls: extract_calls(&body),+ });+ }+ }+ Ok(())+}++pub fn discover(source: &Path) -> Result<Vec<Harness>, HarnessError> {+ if !source.is_dir() {+ return Err(HarnessError::NotADirectory(source.to_path_buf()));+ }+ let mut found = Vec::new();+ walk(source, 0, &mut found)?;+ found.sort_by(|left, right| left.path.cmp(&right.path));+ Ok(found)+}++#[must_use]+pub fn reached_functions(harnesses: &[Harness]) -> BTreeSet<String> {+ harnesses+ .iter()+ .flat_map(|harness| harness.calls.iter().cloned())+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::PathBuf;++ fn fixture(label: &str, files: &[(&str, &str)]) -> PathBuf {+ let root =+ std::env::temp_dir().join(format!("lisdex-harness-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ for (path, body) in files {+ let full = root.join(path);+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();+ std::fs::write(&full, body).unwrap();+ }+ root+ }++ const LIBPNG_HARNESS: &str = r#"+#include "png.h"+extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {+ if (png_sig_cmp(data, 0, 8)) { return 0; }+ png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0);+ png_set_read_fn(png_ptr, &buf_state, user_read_data);+ png_read_info(png_ptr, info_ptr);+ return 0;+}+"#;++ #[test]+ fn a_file_defining_the_libfuzzer_entry_point_is_a_harness() {+ let root = fixture(+ "found",+ &[("contrib/oss-fuzz/libpng_read_fuzzer.cc", LIBPNG_HARNESS)],+ );+ let found = discover(&root).unwrap();+ assert_eq!(found.len(), 1);+ assert!(found[0].path.ends_with("libpng_read_fuzzer.cc"));+ }++ #[test]+ fn ordinary_sources_beside_a_harness_are_not_harnesses() {+ let root = fixture(+ "beside",+ &[+ ("contrib/oss-fuzz/libpng_read_fuzzer.cc", LIBPNG_HARNESS),+ ("png.c", "void png_read_info(void) { return; }"),+ ],+ );+ let found = discover(&root).unwrap();+ assert_eq!(found.len(), 1);+ }++ #[test]+ fn the_library_functions_a_harness_calls_become_the_reached_set() {+ let root = fixture("calls", &[("fuzz/f.c", LIBPNG_HARNESS)]);+ let found = discover(&root).unwrap();+ let calls = &found[0].calls;+ assert!(calls.contains(&"png_create_read_struct".to_owned()));+ assert!(calls.contains(&"png_set_read_fn".to_owned()));+ assert!(calls.contains(&"png_read_info".to_owned()));+ assert!(calls.contains(&"png_sig_cmp".to_owned()));+ }++ #[test]+ fn control_flow_keywords_are_not_mistaken_for_calls() {+ let root = fixture("keywords", &[("fuzz/f.c", LIBPNG_HARNESS)]);+ let found = discover(&root).unwrap();+ for keyword in ["if", "return", "for", "while", "switch", "sizeof"] {+ assert!(+ !found[0].calls.contains(&keyword.to_owned()),+ "{keyword} is not a call"+ );+ }+ }++ #[test]+ fn the_entry_point_itself_is_not_reported_as_a_call() {+ let root = fixture("selfcall", &[("fuzz/f.c", LIBPNG_HARNESS)]);+ let found = discover(&root).unwrap();+ assert!(!found[0].calls.contains(&ENTRY_POINT.to_owned()));+ }++ #[test]+ fn a_repository_with_no_harness_yields_an_empty_set_not_an_error() {+ let root = fixture("none", &[("png.c", "int main(void) { return 0; }")]);+ let found = discover(&root).unwrap();+ assert!(found.is_empty());+ }++ #[test]+ fn the_reached_set_unions_every_harness_in_the_tree() {+ let root = fixture(+ "union",+ &[+ (+ "fuzz/a.c",+ "int LLVMFuzzerTestOneInput(const uint8_t* d, size_t n) { alpha_decode(d, n); return 0; }",+ ),+ (+ "fuzz/b.c",+ "int LLVMFuzzerTestOneInput(const uint8_t* d, size_t n) { beta_decode(d, n); return 0; }",+ ),+ ],+ );+ let reached = reached_functions(&discover(&root).unwrap());+ assert!(reached.contains("alpha_decode"));+ assert!(reached.contains("beta_decode"));+ }++ #[test]+ fn a_missing_tree_is_an_error() {+ let error = discover(std::path::Path::new("/nonexistent/lisdex/harness")).unwrap_err();+ assert!(matches!(error, HarnessError::NotADirectory(_)), "{error:?}");+ }++ #[test]+ fn a_declaration_without_a_call_is_not_counted() {+ let root = fixture(+ "declonly",+ &[(+ "fuzz/f.c",+ "int LLVMFuzzerTestOneInput(const uint8_t* d, size_t n);\n",+ )],+ );+ let found = discover(&root).unwrap();+ assert_eq!(found.len(), 1);+ assert!(found[0].calls.is_empty());+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/headers.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/headers.rsnew file mode 100644index 00000000..70bdde9d--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/headers.rs@@ -0,0 +1,376 @@+// ©AngelaMos | 2026+// headers.rs++use std::path::{Path, PathBuf};++pub const HEADER_EXTENSIONS: &[&str] = &["h", "hpp", "hh", "hxx"];+pub const INCLUDE_DIR: &str = "include";+pub const MAX_DEPTH: usize = 12;++pub const EXCLUDED_DIRS: &[&str] = &[+ "test",+ "tests",+ "testing",+ "contrib",+ "example",+ "examples",+ "fuzz",+ "fuzzing",+ "fuzzers",+ "build",+ "doc",+ "docs",+ "third_party",+ "thirdparty",+ "3rdparty",+ "vendor",+ "vendored",+ "external",+ "externals",+ "deps",+ "subprojects",+ "tools",+ "programs",+ "imageio",+ "xmlwf",+ "bin",+ "enc",+ ".git",+];++#[derive(Debug, thiserror::Error)]+pub enum HeaderError {+ #[error("{0} is not a directory")]+ NotADirectory(PathBuf),+ #[error("no public headers found under {0}")]+ NoHeaders(PathBuf),+ #[error("io error reading {path}: {source}")]+ Io {+ path: PathBuf,+ source: std::io::Error,+ },+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum HeaderOrigin {+ Installed,+ IncludeDir,+ SourceRoot,+ Tree,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct HeaderSet {+ pub root: PathBuf,+ pub origin: HeaderOrigin,+ pub headers: Vec<PathBuf>,+}++pub const PRIVATE_MARKERS: &[&str] = &["priv", "internal", "impl", "iop"];+pub const PRIVATE_SUFFIXES: &[&str] = &["_p", "-p", "_int"];++#[must_use]+pub fn is_private_header(path: &Path) -> bool {+ let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {+ return false;+ };+ let lowered = stem.to_lowercase();+ PRIVATE_MARKERS+ .iter()+ .any(|marker| lowered.contains(marker))+ || PRIVATE_SUFFIXES+ .iter()+ .any(|suffix| lowered.ends_with(suffix))+}++#[must_use]+pub fn is_header(path: &Path) -> bool {+ path.extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| HEADER_EXTENSIONS.contains(&extension.to_lowercase().as_str()))+}++#[must_use]+pub fn is_excluded(name: &str) -> bool {+ EXCLUDED_DIRS.contains(&name.to_lowercase().as_str())+}++fn collect(root: &Path, depth: usize, found: &mut Vec<PathBuf>) -> Result<(), HeaderError> {+ if depth > MAX_DEPTH {+ return Ok(());+ }+ let entries = std::fs::read_dir(root).map_err(|source| HeaderError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ for entry in entries {+ let entry = entry.map_err(|source| HeaderError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ let path = entry.path();+ let name = entry.file_name().to_string_lossy().into_owned();+ if path.is_dir() {+ if !is_excluded(&name) {+ collect(&path, depth + 1, found)?;+ }+ } else if is_header(&path) && !is_private_header(&path) {+ found.push(path);+ }+ }+ Ok(())+}++fn collect_shallow(root: &Path) -> Result<Vec<PathBuf>, HeaderError> {+ let entries = std::fs::read_dir(root).map_err(|source| HeaderError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ let mut found = Vec::new();+ for entry in entries {+ let entry = entry.map_err(|source| HeaderError::Io {+ path: root.to_path_buf(),+ source,+ })?;+ let path = entry.path();+ if path.is_file() && is_header(&path) && !is_private_header(&path) {+ found.push(path);+ }+ }+ Ok(found)+}++fn gathered(root: &Path) -> Result<Vec<PathBuf>, HeaderError> {+ let mut found = Vec::new();+ collect(root, 0, &mut found)?;+ found.sort();+ Ok(found)+}++pub fn discover(source: &Path, install: Option<&Path>) -> Result<HeaderSet, HeaderError> {+ if !source.is_dir() {+ return Err(HeaderError::NotADirectory(source.to_path_buf()));+ }++ if let Some(install) = install+ && install.is_dir()+ {+ let headers = gathered(install)?;+ if !headers.is_empty() {+ return Ok(HeaderSet {+ root: install.to_path_buf(),+ origin: HeaderOrigin::Installed,+ headers,+ });+ }+ }++ let include = source.join(INCLUDE_DIR);+ if include.is_dir() {+ let headers = gathered(&include)?;+ if !headers.is_empty() {+ return Ok(HeaderSet {+ root: include,+ origin: HeaderOrigin::IncludeDir,+ headers,+ });+ }+ }++ let mut headers = collect_shallow(source)?;+ headers.sort();+ if !headers.is_empty() {+ return Ok(HeaderSet {+ root: source.to_path_buf(),+ origin: HeaderOrigin::SourceRoot,+ headers,+ });+ }++ let headers = gathered(source)?;+ if headers.is_empty() {+ return Err(HeaderError::NoHeaders(source.to_path_buf()));+ }+ Ok(HeaderSet {+ root: source.to_path_buf(),+ origin: HeaderOrigin::Tree,+ headers,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::path::{Path, PathBuf};++ fn fixture(label: &str, files: &[&str]) -> PathBuf {+ let root =+ std::env::temp_dir().join(format!("lisdex-headers-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ for file in files {+ let path = root.join(file);+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();+ std::fs::write(&path, "int f(void);\n").unwrap();+ }+ root+ }++ fn names(set: &HeaderSet) -> Vec<String> {+ let mut found: Vec<String> = set+ .headers+ .iter()+ .map(|path| path.file_name().unwrap().to_string_lossy().into_owned())+ .collect();+ found.sort();+ found+ }++ #[test]+ fn an_installed_include_tree_is_the_authoritative_public_api() {+ let root = fixture(+ "installed",+ &["src/png.h", "src/pngpriv.h", "install/include/png.h"],+ );+ let set = discover(&root.join("src"), Some(&root.join("install"))).unwrap();+ assert_eq!(set.origin, HeaderOrigin::Installed);+ assert_eq!(names(&set), vec!["png.h"]);+ }++ #[test]+ fn an_include_directory_is_used_when_nothing_was_installed() {+ let root = fixture("includedir", &["include/tiff.h", "libtiff/tif_dir.c"]);+ let set = discover(&root, None).unwrap();+ assert_eq!(set.origin, HeaderOrigin::IncludeDir);+ assert_eq!(names(&set), vec!["tiff.h"]);+ }++ #[test]+ fn headers_at_the_source_root_are_collected_when_there_is_no_include_dir() {+ let root = fixture("sourceroot", &["png.h", "pngconf.h", "png.c"]);+ let set = discover(&root, None).unwrap();+ assert_eq!(set.origin, HeaderOrigin::SourceRoot);+ assert_eq!(names(&set), vec!["png.h", "pngconf.h"]);+ }++ #[test]+ fn test_and_contrib_trees_are_never_part_of_the_public_surface() {+ let root = fixture(+ "excluded",+ &[+ "include/archive.h",+ "include/tests/helper.h",+ "include/contrib/oss-fuzz/harness.h",+ "include/examples/demo.h",+ "include/fuzz/driver.h",+ ],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(names(&set), vec!["archive.h"]);+ }++ #[test]+ fn nested_headers_under_the_include_root_are_found() {+ let root = fixture(+ "nested",+ &["include/openjpeg.h", "include/opj/opj_stdint.h"],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(names(&set), vec!["openjpeg.h", "opj_stdint.h"]);+ }++ #[test]+ fn cpp_header_extensions_are_included_and_sources_are_not() {+ let root = fixture(+ "extensions",+ &[+ "include/a.h",+ "include/b.hpp",+ "include/c.hh",+ "include/d.c",+ "include/e.cpp",+ "include/f.txt",+ ],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(names(&set), vec!["a.h", "b.hpp", "c.hh"]);+ }++ #[test]+ fn headers_that_name_themselves_private_are_not_public_api() {+ let root = fixture(+ "private",+ &[+ "png.h",+ "pngconf.h",+ "pngpriv.h",+ "tiffiop.h",+ "zlib_internal.h",+ "codec_impl.h",+ "thing_p.h",+ ],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(names(&set), vec!["png.h", "pngconf.h"], "{:?}", names(&set));+ }++ #[test]+ fn a_project_keeping_its_public_header_in_a_named_subdirectory_is_still_found() {+ let root = fixture(+ "subdir",+ &[+ "libarchive/archive.h",+ "libarchive/archive_entry.h",+ "libarchive/archive_read_private.h",+ "README.md",+ ],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(set.origin, HeaderOrigin::Tree);+ assert_eq!(names(&set), vec!["archive.h", "archive_entry.h"]);+ }++ #[test]+ fn a_vendored_dependency_is_never_mistaken_for_the_project_surface() {+ let root = fixture(+ "vendored",+ &[+ "src/lib/openjp2/openjpeg.h",+ "thirdparty/libpng/png.h",+ "thirdparty/libtiff/tiffio.h",+ "subprojects/zlib/zlib.h",+ ],+ );+ let set = discover(&root, None).unwrap();+ assert_eq!(names(&set), vec!["openjpeg.h"], "{:?}", names(&set));+ }++ #[test]+ fn a_root_header_still_wins_over_a_deeper_one() {+ let root = fixture("rootwins", &["png.h", "src/internals/helper.h"]);+ let set = discover(&root, None).unwrap();+ assert_eq!(set.origin, HeaderOrigin::SourceRoot);+ assert_eq!(names(&set), vec!["png.h"]);+ }++ #[test]+ fn a_tree_with_no_headers_reports_that_rather_than_guessing() {+ let root = fixture("empty", &["src/main.c", "README.md"]);+ let error = discover(&root, None).unwrap_err();+ assert!(matches!(error, HeaderError::NoHeaders(_)), "{error:?}");+ }++ #[test]+ fn a_missing_source_tree_is_an_error() {+ let missing = Path::new("/nonexistent/lisdex/surface/tree");+ let error = discover(missing, None).unwrap_err();+ assert!(matches!(error, HeaderError::NotADirectory(_)), "{error:?}");+ }++ #[test]+ fn an_install_tree_without_headers_falls_back_to_the_source() {+ let root = fixture("installempty", &["install/lib/libpng.a", "include/png.h"]);+ let set = discover(&root, Some(&root.join("install"))).unwrap();+ assert_eq!(set.origin, HeaderOrigin::IncludeDir);+ assert_eq!(names(&set), vec!["png.h"]);+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/lib.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/lib.rsnew file mode 100644index 00000000..b7053ec4--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/lib.rs@@ -0,0 +1,11 @@+// ©AngelaMos | 2026+// lib.rs++pub mod complexity;+pub mod extract;+pub mod harness;+pub mod headers;+pub mod naming;+pub mod rank;+pub mod signature;+pub mod surface;diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/naming.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/naming.rsnew file mode 100644index 00000000..85423d51--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/naming.rs@@ -0,0 +1,457 @@+// ©AngelaMos | 2026+// naming.rs++pub const SCORE_VERY_HIGH: f64 = 1.0;+pub const SCORE_HIGH: f64 = 0.8;+pub const SCORE_MEDIUM_HIGH: f64 = 0.65;+pub const SCORE_MEDIUM: f64 = 0.5;+pub const SCORE_MEDIUM_LOW: f64 = 0.35;+pub const SCORE_NONE: f64 = 0.0;++pub const ENTRY_PATTERNS: &[(&[&str], Reliability)] = &[+ (&["from", "memory"], Reliability::VeryHigh),+ (&["decode"], Reliability::High),+ (&["parse"], Reliability::High),+ (&["uncompress"], Reliability::High),+ (&["decompress"], Reliability::High),+ (&["inflate"], Reliability::High),+ (&["demux"], Reliability::MediumHigh),+ (&["read"], Reliability::Medium),+ (&["load"], Reliability::Medium),+ (&["open"], Reliability::MediumLow),+];++pub const LIFECYCLE_TOKENS: &[&str] = &[+ "set",+ "init",+ "create",+ "new",+ "alloc",+ "setup",+ "configure",+ "free",+ "destroy",+ "close",+ "cleanup",+ "release",+ "finalize",+ "delete",+ "dealloc",+];++pub const DIAGNOSTIC_TOKENS: &[&str] = &[+ "error",+ "exception",+ "warn",+ "warning",+ "log",+ "debug",+ "print",+ "dump",+];++pub const SCAFFOLD_TOKENS: &[&str] = &["test", "example", "demo", "sample"];++// Checksum and hash primitives are vendored into almost every parser library and+// score well on every signal: byte buffer in, high complexity, no existing harness.+// They are not parser entry points. blake2sp/blake2s reached ranks 7 and 8 on+// libarchive; siphash24 reached 5 on libexpat; XXH64 reached 7 on lz4.+pub const PRIMITIVE_TOKENS: &[&str] = &[+ "blake", "blake2", "blake2b", "blake2s", "blake2sp", "blake2bp", "sha", "sha1", "sha256",+ "sha512", "md5", "crc", "crc32", "crc64", "adler", "adler32", "siphash", "sip", "xxh",+ "xxhash", "murmur", "hmac", "poly1305", "chacha", "aes",+];++pub const PRODUCER_TOKENS: &[&str] = &[+ "write",+ "encode",+ "encoder",+ "compress",+ "deflate",+ "save",+ "emit",+ "serialize",+ "marshal",+ "dest",+];++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum Role {+ Entry,+ Lifecycle,+ Diagnostic,+ Scaffold,+ Producer,+ Primitive,+ Neutral,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum Reliability {+ VeryHigh,+ High,+ MediumHigh,+ Medium,+ MediumLow,+ None,+}++impl Reliability {+ #[must_use]+ pub fn score(self) -> f64 {+ match self {+ Reliability::VeryHigh => SCORE_VERY_HIGH,+ Reliability::High => SCORE_HIGH,+ Reliability::MediumHigh => SCORE_MEDIUM_HIGH,+ Reliability::Medium => SCORE_MEDIUM,+ Reliability::MediumLow => SCORE_MEDIUM_LOW,+ Reliability::None => SCORE_NONE,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct NameSignal {+ pub role: Role,+ pub reliability: Reliability,+ pub matched: Option<String>,+}++#[must_use]+pub fn tokenize(name: &str) -> Vec<String> {+ let mut tokens = Vec::new();+ for segment in name.split(['_', '-', '.', ':']) {+ if !segment.is_empty() {+ split_camel(segment, &mut tokens);+ }+ }+ tokens+}++fn split_camel(segment: &str, out: &mut Vec<String>) {+ let chars: Vec<char> = segment.chars().collect();+ let mut start = 0;+ for index in 1..chars.len() {+ let previous = chars[index - 1];+ let current = chars[index];+ let following = chars.get(index + 1).copied();+ let entering_word =+ current.is_uppercase() && (previous.is_lowercase() || previous.is_numeric());+ let leaving_acronym = current.is_uppercase()+ && previous.is_uppercase()+ && following.is_some_and(char::is_lowercase);+ if entering_word || leaving_acronym {+ out.push(+ chars[start..index]+ .iter()+ .collect::<String>()+ .to_lowercase(),+ );+ start = index;+ }+ }+ if start < chars.len() {+ out.push(chars[start..].iter().collect::<String>().to_lowercase());+ }+}++fn contains_sequence(tokens: &[String], pattern: &[&str]) -> bool {+ if pattern.is_empty() || pattern.len() > tokens.len() {+ return false;+ }+ tokens.windows(pattern.len()).any(|window| {+ window+ .iter()+ .zip(pattern)+ .all(|(token, expected)| token == expected)+ })+}++pub const MIN_SUFFIX_MATCH: usize = 5;++// `compress2`, `compress2_z`, `ZSTD_compress2` and `gzwrite` all escaped exact-token+// matching while plain `compress`/`deflate` were correctly excluded. Strip a trailing+// version digit, and let long producer verbs match as a suffix so `gzwrite` and+// `gzfwrite` are seen. Short tokens are exact-only: `dest` as a suffix would catch+// `modest`.+fn stem(token: &str) -> &str {+ token.trim_end_matches(|character: char| character.is_ascii_digit())+}++fn is_entry_verb(stemmed: &str) -> bool {+ ENTRY_PATTERNS+ .iter()+ .any(|(pattern, _)| pattern.len() == 1 && pattern[0] == stemmed)+}++fn matches_token(token: &str, candidate: &str, allow_suffix: bool) -> bool {+ let stemmed = stem(token);+ if stemmed == candidate {+ return true;+ }+ // `decompress` and `uncompress` both END WITH `compress`. A token that is itself a+ // decode verb is never a producer, whatever it happens to end with.+ allow_suffix+ && candidate.len() >= MIN_SUFFIX_MATCH+ && stemmed.len() > candidate.len()+ && stemmed.ends_with(candidate)+ && !is_entry_verb(stemmed)+}++fn first_match<'a>(tokens: &[String], candidates: &[&'a str]) -> Option<&'a str> {+ candidates.iter().copied().find(|candidate| {+ tokens+ .iter()+ .any(|token| matches_token(token, candidate, false))+ })+}++fn first_producer<'a>(tokens: &[String], candidates: &[&'a str]) -> Option<&'a str> {+ candidates.iter().copied().find(|candidate| {+ tokens+ .iter()+ .any(|token| matches_token(token, candidate, true))+ })+}++#[must_use]+pub fn classify(name: &str) -> NameSignal {+ let tokens = tokenize(name);++ if let Some(matched) = first_match(&tokens, SCAFFOLD_TOKENS) {+ return NameSignal {+ role: Role::Scaffold,+ reliability: Reliability::None,+ matched: Some(matched.to_owned()),+ };+ }+ if let Some(matched) = first_match(&tokens, PRIMITIVE_TOKENS) {+ return NameSignal {+ role: Role::Primitive,+ reliability: Reliability::None,+ matched: Some(matched.to_owned()),+ };+ }+ if let Some(matched) = first_producer(&tokens, PRODUCER_TOKENS) {+ return NameSignal {+ role: Role::Producer,+ reliability: Reliability::None,+ matched: Some(matched.to_owned()),+ };+ }+ if let Some(matched) = first_match(&tokens, DIAGNOSTIC_TOKENS) {+ return NameSignal {+ role: Role::Diagnostic,+ reliability: Reliability::None,+ matched: Some(matched.to_owned()),+ };+ }+ if let Some(matched) = first_match(&tokens, LIFECYCLE_TOKENS) {+ return NameSignal {+ role: Role::Lifecycle,+ reliability: Reliability::None,+ matched: Some(matched.to_owned()),+ };+ }++ let strongest = ENTRY_PATTERNS+ .iter()+ .filter(|(pattern, _)| contains_sequence(&tokens, pattern))+ .max_by(|left, right| {+ left.1+ .score()+ .partial_cmp(&right.1.score())+ .unwrap_or(std::cmp::Ordering::Equal)+ });++ match strongest {+ Some((pattern, reliability)) => NameSignal {+ role: Role::Entry,+ reliability: *reliability,+ matched: Some(pattern.join("_")),+ },+ None => NameSignal {+ role: Role::Neutral,+ reliability: Reliability::None,+ matched: None,+ },+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_from_memory_suffix_is_the_strongest_entry_name() {+ let signal = classify("png_image_begin_read_from_memory");+ assert_eq!(signal.role, Role::Entry);+ assert_eq!(signal.reliability, Reliability::VeryHigh);+ }++ #[test]+ fn a_constructor_outranks_the_generic_verb_it_contains() {+ let signal = classify("png_create_read_struct");+ assert_eq!(signal.role, Role::Lifecycle);+ }++ #[test]+ fn a_destructor_outranks_the_generic_verb_it_contains() {+ let signal = classify("png_destroy_read_struct");+ assert_eq!(signal.role, Role::Lifecycle);+ }++ #[test]+ fn test_scaffolding_outranks_a_decode_verb() {+ let signal = classify("test_decode_frame");+ assert_eq!(signal.role, Role::Scaffold);+ }++ #[test]+ fn encoder_side_functions_are_excluded_despite_mirroring_reader_names() {+ for name in [+ "png_write_iCCP",+ "png_write_png",+ "png_compress_IDAT",+ "TIFFWriteScanline",+ "archive_write_data",+ "opj_encode",+ "jpeg_mem_dest",+ ] {+ assert_eq!(classify(name).role, Role::Producer, "{name}");+ }+ }++ #[test]+ fn decompression_is_not_mistaken_for_compression() {+ for name in [+ "BZ2_bzDecompress",+ "opj_decompress",+ "zlib_uncompress",+ "ZSTD_decompressStream",+ "LZ4F_decompress",+ "tj3DecompressHeader",+ ] {+ assert_eq!(classify(name).role, Role::Entry, "{name}");+ }+ }++ #[test]+ fn a_version_digit_does_not_smuggle_a_producer_past_the_filter() {+ for name in ["compress2", "ZSTD_compress2", "zlib_compress2_z"] {+ assert_eq!(classify(name).role, Role::Producer, "{name}");+ }+ }++ #[test]+ fn a_prefixed_write_verb_is_still_a_producer() {+ for name in ["gzwrite", "gzfwrite", "mylib_overwrite"] {+ assert_eq!(classify(name).role, Role::Producer, "{name}");+ }+ }++ #[test]+ fn vendored_hash_primitives_are_not_parser_entry_points() {+ for name in [+ "blake2sp_update",+ "blake2s",+ "siphash24",+ "XXH64",+ "crc32_z",+ "sha256_update",+ ] {+ assert_eq!(classify(name).role, Role::Primitive, "{name}");+ }+ }++ #[test]+ fn no_ground_truth_entry_point_is_classified_as_a_producer() {+ for name in [+ "png_read_info",+ "png_image_begin_read_from_memory",+ "png_read_png",+ "png_process_data",+ "TIFFClientOpen",+ "TIFFOpen",+ "TIFFReadDirectory",+ "opj_read_header",+ "opj_decode",+ "archive_read_next_header",+ "archive_read_open_memory",+ "archive_read_data",+ "tj3DecompressHeader",+ "tj3Transform",+ "jpeg_read_header",+ ] {+ let role = classify(name).role;+ assert_ne!(role, Role::Producer, "{name} is a real entry point");+ assert_ne!(role, Role::Scaffold, "{name} is a real entry point");+ }+ }++ #[test]+ fn diagnostic_functions_are_never_entry_points() {+ assert_eq!(classify("png_error").role, Role::Diagnostic);+ assert_eq!(classify("TIFFWarningExt").role, Role::Diagnostic);+ }++ #[test]+ fn camel_case_names_are_tokenized_before_matching() {+ let signal = classify("TIFFReadDirectory");+ assert_eq!(signal.role, Role::Entry);+ assert_eq!(signal.reliability, Reliability::Medium);+ }++ #[test]+ fn tokens_match_whole_words_so_resample_is_not_test_scaffolding() {+ let signal = classify("resample_row");+ assert_eq!(signal.role, Role::Neutral);+ }++ #[test]+ fn a_name_with_no_known_token_is_neutral_not_rejected() {+ let signal = classify("png_get_IHDR");+ assert_eq!(signal.role, Role::Neutral);+ assert_eq!(signal.reliability, Reliability::None);+ }++ #[test]+ fn the_exit_gate_exemplar_is_only_a_weak_name_signal() {+ let signal = classify("TIFFClientOpen");+ assert_eq!(signal.role, Role::Entry);+ assert_eq!(signal.reliability, Reliability::MediumLow);+ assert!(+ signal.reliability.score() < Reliability::High.score(),+ "naming must not be able to carry TIFFClientOpen to the top on its own"+ );+ }++ #[test]+ fn decompression_verbs_are_high_reliability_entry_names() {+ for name in ["BZ2_bzDecompress", "lz4_decompress_safe", "zlib_inflate"] {+ let signal = classify(name);+ assert_eq!(signal.role, Role::Entry, "{name}");+ assert_eq!(signal.reliability, Reliability::High, "{name}");+ }+ }++ #[test]+ fn reliability_scores_are_ordered_by_rank() {+ let ranked = [+ Reliability::VeryHigh,+ Reliability::High,+ Reliability::MediumHigh,+ Reliability::Medium,+ Reliability::MediumLow,+ Reliability::None,+ ];+ for pair in ranked.windows(2) {+ assert!(+ pair[0].score() > pair[1].score(),+ "{:?} must outscore {:?}",+ pair[0],+ pair[1]+ );+ }+ }+}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.rsnew file mode 100644index 00000000..319e203c--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/rank.rs@@ -0,0 +1,623 @@+// ©AngelaMos | 2026+// rank.rs++use std::collections::BTreeSet;+use std::path::PathBuf;++use crate::naming::{self, Role};+use crate::signature::{self, Analysis, Fuzzability, Param};++pub const WEIGHT_UNDISCOVERED: f64 = 0.40;+pub const WEIGHT_FUZZABILITY: f64 = 0.25;+pub const WEIGHT_ACCUMULATED: f64 = 0.15;+pub const WEIGHT_EXPORT: f64 = 0.10;+pub const WEIGHT_ARG_SIMPLICITY: f64 = 0.07;+pub const WEIGHT_NAME: f64 = 0.03;++pub const EXPORT_PUBLIC: f64 = 1.0;+pub const EXPORT_INTERNAL: f64 = 0.0;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize)]+pub struct Complexity {+ pub own: u32,+ pub accumulated: u32,+ pub undiscovered: u32,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Function {+ pub name: String,+ pub params: Vec<Param>,+ pub header: PathBuf,+ pub line: u32,+ pub exported: bool,+ pub complexity: Complexity,+ pub reachable_from_harness: bool,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum ExclusionReason {+ Lifecycle,+ Diagnostic,+ Scaffold,+ Producer,+ Primitive,+ NoDataInput,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Excluded {+ pub name: String,+ pub reason: ExclusionReason,+}++#[derive(Debug, Clone, PartialEq, serde::Serialize)]+pub struct Candidate {+ pub name: String,+ pub header: PathBuf,+ pub line: u32,+ pub fuzzability: Fuzzability,+ pub analysis: Analysis,+ pub complexity: Complexity,+ pub exported: bool,+ pub reachable_from_harness: bool,+ pub score: f64,+ pub reasons: Vec<String>,+}++#[derive(Debug, Clone, PartialEq, serde::Serialize)]+pub struct Ranking {+ pub candidates: Vec<Candidate>,+ pub excluded: Vec<Excluded>,+}++#[derive(Debug, Clone, Copy, PartialEq)]+pub struct Weights {+ pub undiscovered: f64,+ pub fuzzability: f64,+ pub accumulated: f64,+ pub export: f64,+ pub arg_simplicity: f64,+ pub name: f64,+}++impl Default for Weights {+ fn default() -> Self {+ Self {+ undiscovered: WEIGHT_UNDISCOVERED,+ fuzzability: WEIGHT_FUZZABILITY,+ accumulated: WEIGHT_ACCUMULATED,+ export: WEIGHT_EXPORT,+ arg_simplicity: WEIGHT_ARG_SIMPLICITY,+ name: WEIGHT_NAME,+ }+ }+}++fn exclusion_for(role: Role) -> Option<ExclusionReason> {+ match role {+ Role::Lifecycle => Some(ExclusionReason::Lifecycle),+ Role::Diagnostic => Some(ExclusionReason::Diagnostic),+ Role::Scaffold => Some(ExclusionReason::Scaffold),+ Role::Producer => Some(ExclusionReason::Producer),+ Role::Primitive => Some(ExclusionReason::Primitive),+ Role::Entry | Role::Neutral => None,+ }+}++#[must_use]+pub fn complexity_score(accumulated: u32, ceiling: u32) -> f64 {+ if accumulated == 0 || ceiling == 0 {+ return 0.0;+ }+ let scaled = f64::from(accumulated + 1).ln() / f64::from(ceiling + 1).ln();+ scaled.clamp(0.0, 1.0)+}++#[must_use]+pub fn arg_simplicity(context_args: usize) -> f64 {+ let count = u32::try_from(context_args).unwrap_or(u32::MAX);+ 1.0 / (1.0 + f64::from(count))+}++#[must_use]+pub fn rank(functions: Vec<Function>, weights: &Weights) -> Ranking {+ let mut excluded = Vec::new();+ let mut kept = Vec::new();++ let streams: BTreeSet<String> = functions+ .iter()+ .filter_map(|function| signature::registered_stream(&function.params))+ .collect();++ for function in functions {+ let signal = naming::classify(&function.name);+ if let Some(reason) = exclusion_for(signal.role) {+ excluded.push(Excluded {+ name: function.name,+ reason,+ });+ continue;+ }+ let analysis = signature::analyze_named(&function.name, &function.params, &streams);+ if analysis.fuzzability == Fuzzability::NoInput {+ excluded.push(Excluded {+ name: function.name,+ reason: ExclusionReason::NoDataInput,+ });+ continue;+ }+ kept.push((function, signal, analysis));+ }++ let accumulated_ceiling = kept+ .iter()+ .map(|(function, _, _)| function.complexity.accumulated)+ .max()+ .unwrap_or(0);+ let undiscovered_ceiling = kept+ .iter()+ .map(|(function, _, _)| function.complexity.undiscovered)+ .max()+ .unwrap_or(0);++ 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,+ analysis,+ complexity: function.complexity,+ exported: function.exported,+ reachable_from_harness: function.reachable_from_harness,+ score,+ reasons,+ }+ })+ .collect();++ candidates.sort_by(|left, right| {+ right+ .score+ .partial_cmp(&left.score)+ .unwrap_or(std::cmp::Ordering::Equal)+ .then_with(|| left.name.cmp(&right.name))+ });++ Ranking {+ candidates,+ excluded,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::signature::{Param, Pointee, Shape};++ fn param(name: &str, shape: Shape) -> Param {+ Param {+ name: Some(name.to_owned()),+ spelling: String::new(),+ shape,+ }+ }++ fn buffer_pair() -> Vec<Param> {+ vec![+ param(+ "data",+ Shape::Pointer {+ pointee: Pointee::UnsignedChar,+ is_const: true,+ },+ ),+ param("size", Shape::Integral),+ ]+ }++ fn function(name: &str, params: Vec<Param>, complexity: u32) -> Function {+ Function {+ name: name.to_owned(),+ params,+ header: "x.h".into(),+ line: 1,+ exported: true,+ complexity: Complexity {+ own: complexity,+ accumulated: complexity,+ undiscovered: complexity,+ },+ reachable_from_harness: false,+ }+ }++ fn names(ranking: &Ranking) -> Vec<&str> {+ ranking+ .candidates+ .iter()+ .map(|candidate| candidate.name.as_str())+ .collect()+ }++ #[test]+ fn constructors_are_excluded_from_the_candidate_set_entirely() {+ let ranking = rank(+ vec![function("png_create_read_struct", buffer_pair(), 50)],+ &Weights::default(),+ );+ assert!(ranking.candidates.is_empty());+ assert_eq!(ranking.excluded[0].reason, ExclusionReason::Lifecycle);+ }++ #[test]+ fn diagnostic_and_scaffold_functions_are_excluded_with_their_reason() {+ let ranking = rank(+ vec![+ function("png_error", buffer_pair(), 50),+ function("test_decode", buffer_pair(), 50),+ ],+ &Weights::default(),+ );+ assert!(ranking.candidates.is_empty());+ let reasons: Vec<ExclusionReason> =+ ranking.excluded.iter().map(|item| item.reason).collect();+ assert!(reasons.contains(&ExclusionReason::Diagnostic));+ assert!(reasons.contains(&ExclusionReason::Scaffold));+ }++ #[test]+ fn a_function_that_consumes_no_data_is_excluded() {+ let ranking = rank(+ vec![function(+ "opj_codec_flags",+ vec![param("flags", Shape::Integral)],+ 90,+ )],+ &Weights::default(),+ );+ assert!(ranking.candidates.is_empty());+ assert_eq!(ranking.excluded[0].reason, ExclusionReason::NoDataInput);+ }++ #[test]+ fn higher_complexity_outranks_lower_when_all_else_is_equal() {+ let ranking = rank(+ vec![+ function("opj_decode_simple", buffer_pair(), 5),+ function("opj_decode_hairy", buffer_pair(), 900),+ ],+ &Weights::default(),+ );+ assert_eq!(+ names(&ranking),+ vec!["opj_decode_hairy", "opj_decode_simple"]+ );+ }++ #[test]+ fn an_exported_function_outranks_an_identical_internal_one() {+ let mut internal = function("archive_read_data_a", buffer_pair(), 100);+ internal.exported = false;+ let ranking = rank(+ vec![+ internal,+ function("archive_read_data_b", buffer_pair(), 100),+ ],+ &Weights::default(),+ );+ assert_eq!(names(&ranking)[0], "archive_read_data_b");+ }++ #[test]+ fn fewer_context_arguments_outranks_more() {+ let mut noisy = buffer_pair();+ noisy.push(param(+ "ctx",+ Shape::Pointer {+ pointee: Pointee::Record("Ctx".to_owned()),+ is_const: false,+ },+ ));+ noisy.push(param("flags", Shape::Integral));+ let ranking = rank(+ vec![+ function("wav_decode_noisy", noisy, 100),+ function("wav_decode_clean", buffer_pair(), 100),+ ],+ &Weights::default(),+ );+ assert_eq!(names(&ranking)[0], "wav_decode_clean");+ }++ #[test]+ fn complexity_an_existing_harness_already_reaches_stops_counting_as_undiscovered() {+ let mut covered = function("png_read_covered", buffer_pair(), 100);+ covered.reachable_from_harness = true;+ covered.complexity.undiscovered = 0;+ let ranking = rank(+ vec![covered, function("png_read_untouched", buffer_pair(), 100)],+ &Weights::default(),+ );+ assert_eq!(+ names(&ranking)[0],+ "png_read_untouched",+ "two functions of identical accumulated complexity must separate on how much \+ of it no existing harness has already reached"+ );+ }++ #[test]+ fn a_deep_complex_custom_stream_entry_outranks_a_trivial_direct_buffer() {+ let client_open = Function {+ name: "TIFFClientOpen".to_owned(),+ params: vec![+ param(+ "name",+ Shape::Pointer {+ pointee: Pointee::Char,+ is_const: true,+ },+ ),+ param(+ "mode",+ Shape::Pointer {+ pointee: Pointee::Char,+ is_const: true,+ },+ ),+ param(+ "clientdata",+ Shape::Pointer {+ pointee: Pointee::Void,+ is_const: false,+ },+ ),+ param(+ "readproc",+ Shape::Pointer {+ pointee: Pointee::Function,+ is_const: false,+ },+ ),+ ],+ header: "tiffio.h".into(),+ line: 1,+ exported: true,+ complexity: Complexity {+ own: 2,+ accumulated: 2753,+ undiscovered: 2753,+ },+ reachable_from_harness: false,+ };+ let trivial = function("tiff_parse_tag", buffer_pair(), 3);+ let ranking = rank(vec![trivial, client_open], &Weights::default());+ assert_eq!(+ names(&ranking)[0],+ "TIFFClientOpen",+ "accumulated complexity must be able to beat a better signature grade"+ );+ }++ fn record(name: &str, record: &str) -> Param {+ param(+ name,+ Shape::Pointer {+ pointee: Pointee::Record(record.to_owned()),+ is_const: false,+ },+ )+ }++ fn png_set_read_fn() -> Function {+ function(+ "png_set_read_fn",+ vec![+ record("png_ptr", "png_struct"),+ param(+ "io_ptr",+ Shape::Pointer {+ pointee: Pointee::Void,+ is_const: false,+ },+ ),+ param(+ "read_data_fn",+ Shape::Pointer {+ pointee: Pointee::Function,+ is_const: false,+ },+ ),+ ],+ 12,+ )+ }++ fn png_read_info() -> Function {+ function(+ "png_read_info",+ vec![+ record("png_ptr", "png_struct"),+ record("info_ptr", "png_info"),+ ],+ 2000,+ )+ }++ #[test]+ fn a_context_only_entry_survives_when_the_library_registers_a_reader() {+ let ranking = rank(+ vec![png_set_read_fn(), png_read_info()],+ &Weights::default(),+ );+ assert!(+ !ranking+ .excluded+ .iter()+ .any(|item| item.name == "png_read_info"),+ "png_read_info is libpng's ground-truth #1 and must not be excluded"+ );+ assert_eq!(names(&ranking)[0], "png_read_info");+ }++ #[test]+ fn the_same_context_only_entry_is_excluded_when_nothing_registers_a_reader() {+ let ranking = rank(vec![png_read_info()], &Weights::default());+ assert_eq!(ranking.excluded[0].reason, ExclusionReason::NoDataInput);+ }++ #[test]+ fn the_magic_byte_comparator_never_outranks_the_real_parser() {+ let png_sig_cmp = function(+ "png_sig_cmp",+ vec![+ param(+ "sig",+ Shape::Pointer {+ pointee: Pointee::UnsignedChar,+ is_const: true,+ },+ ),+ param("start", Shape::Integral),+ param("num_to_check", Shape::Integral),+ ],+ 4,+ );+ let ranking = rank(+ vec![png_sig_cmp, png_set_read_fn(), png_read_info()],+ &Weights::default(),+ );+ let order = names(&ranking);+ let parser = order.iter().position(|name| *name == "png_read_info");+ let comparator = order.iter().position(|name| *name == "png_sig_cmp");+ assert!(+ parser.is_some(),+ "the parser must be ranked at all: {order:?}"+ );+ assert!(+ comparator.is_some(),+ "the control must be ranked, not filtered out: {order:?}"+ );+ assert!(+ parser < comparator,+ "a textbook (ptr,len) that only compares 8 magic bytes must lose to the \+ function that drives the chunk parser: {order:?}"+ );+ }++ #[test]+ fn a_registration_call_is_excluded_but_still_establishes_the_stream() {+ let ranking = rank(+ vec![png_set_read_fn(), png_read_info()],+ &Weights::default(),+ );+ assert!(+ ranking+ .excluded+ .iter()+ .any(|item| item.name == "png_set_read_fn"),+ "the callback installer is support, never a candidate"+ );+ assert!(+ names(&ranking).contains(&"png_read_info"),+ "excluding the installer must not undo the stream it registers"+ );+ }++ #[test]+ fn ranking_is_deterministic_for_identical_scores() {+ let build = || {+ vec![+ function("b_decode", buffer_pair(), 10),+ function("a_decode", buffer_pair(), 10),+ function("c_decode", buffer_pair(), 10),+ ]+ };+ let first = rank(build(), &Weights::default());+ let second = rank(build(), &Weights::default());+ assert_eq!(names(&first), names(&second));+ assert_eq!(names(&first), vec!["a_decode", "b_decode", "c_decode"]);+ }++ #[test]+ fn every_candidate_carries_the_signals_that_produced_its_score() {+ let ranking = rank(+ vec![function("jpeg_decode", buffer_pair(), 42)],+ &Weights::default(),+ );+ let candidate = &ranking.candidates[0];+ assert_eq!(candidate.fuzzability, Fuzzability::DirectBuffer);+ assert!(candidate.score > 0.0);+ assert!(!candidate.reasons.is_empty());+ }++ #[test]+ fn default_weights_sum_to_one() {+ let weights = Weights::default();+ let total = weights.fuzzability+ + weights.undiscovered+ + weights.export+ + weights.accumulated+ + weights.arg_simplicity+ + weights.name;+ assert!((total - 1.0).abs() < f64::EPSILON, "weights total {total}");+ }++ #[test]+ fn an_empty_surface_ranks_to_an_empty_list_without_panicking() {+ let ranking = rank(Vec::new(), &Weights::default());+ assert!(ranking.candidates.is_empty());+ assert!(ranking.excluded.is_empty());+ }+}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.rsnew file mode 100644index 00000000..ad6aa4ff--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/signature.rs@@ -0,0 +1,815 @@+// ©AngelaMos | 2026+// signature.rs++use std::collections::BTreeSet;++use crate::naming::tokenize;++pub const SCORE_DIRECT_BUFFER: f64 = 1.0;+pub const SCORE_CAST_BUFFER: f64 = 0.8;+pub const SCORE_STREAM: f64 = 0.6;+pub const SCORE_CUSTOM_STREAM: f64 = 0.4;+pub const SCORE_STREAM_DRIVEN: f64 = 0.3;+pub const SCORE_PATH: f64 = 0.2;+pub const SCORE_NO_INPUT: f64 = 0.0;++pub const MIN_SUBSTRING_MATCH: usize = 3;++pub const STREAM_RECORDS: &[&str] = &["FILE", "_IO_FILE", "__sFILE"];++pub const LENGTH_NAMES: &[&str] = &[+ "size",+ "len",+ "length",+ "nbytes",+ "nbyte",+ "num_bytes",+ "count",+ "sz",+ "n",+];++pub const DIMENSION_NAMES: &[&str] = &[+ "width", "height", "stride", "channels", "depth", "pitch", "rows", "cols", "bpp",+];++pub const PATH_NAMES: &[&str] = &[+ "filename", "fname", "pathname", "filepath", "path", "file", "url",+];++pub const OUTPUT_NAMES: &[&str] = &["out", "dst", "dest", "output", "result"];++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum Fuzzability {+ DirectBuffer,+ CastBuffer,+ Stream,+ CustomStream,+ StreamDriven,+ Path,+ NoInput,+}++impl Fuzzability {+ #[must_use]+ pub fn score(self) -> f64 {+ match self {+ Fuzzability::DirectBuffer => SCORE_DIRECT_BUFFER,+ Fuzzability::CastBuffer => SCORE_CAST_BUFFER,+ Fuzzability::Stream => SCORE_STREAM,+ Fuzzability::CustomStream => SCORE_CUSTOM_STREAM,+ Fuzzability::StreamDriven => SCORE_STREAM_DRIVEN,+ Fuzzability::Path => SCORE_PATH,+ Fuzzability::NoInput => SCORE_NO_INPUT,+ }+ }+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub enum Pointee {+ UnsignedChar,+ SignedChar,+ Char,+ Void,+ Integral,+ Record(String),+ Function,+ Pointer,+ Other,+}++impl Pointee {+ #[must_use]+ pub fn is_byte_sized(&self) -> bool {+ matches!(+ self,+ Pointee::UnsignedChar | Pointee::SignedChar | Pointee::Char | Pointee::Void+ )+ }++ #[must_use]+ pub fn is_exact_byte(&self) -> bool {+ matches!(self, Pointee::UnsignedChar | Pointee::SignedChar)+ }+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub enum Shape {+ Pointer { pointee: Pointee, is_const: bool },+ Integral,+ Record(String),+ Float,+ Void,+ Other,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Param {+ pub name: Option<String>,+ pub spelling: String,+ pub shape: Shape,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]+pub enum ParamRole {+ Buffer,+ Length,+ Path,+ Stream,+ Callback,+ Context,+ Output,+ Config,+}++#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]+pub struct Analysis {+ pub fuzzability: Fuzzability,+ pub roles: Vec<ParamRole>,+ pub context_args: usize,+}++fn name_matches(name: Option<&String>, candidates: &[&str]) -> bool {+ let Some(name) = name else {+ return false;+ };+ let lowered = name.to_lowercase();+ let tokens = tokenize(name);+ candidates.iter().any(|candidate| {+ tokens.iter().any(|token| token == candidate)+ || (candidate.len() >= MIN_SUBSTRING_MATCH && lowered.contains(candidate))+ })+}++fn name_has_token(name: Option<&String>, candidates: &[&str]) -> bool {+ let Some(name) = name else {+ return false;+ };+ let tokens = tokenize(name);+ candidates+ .iter()+ .any(|candidate| tokens.iter().any(|token| token == candidate))+}++fn is_length_like(param: &Param) -> bool {+ let carries_a_count = matches!(param.shape, Shape::Integral)+ || matches!(+ ¶m.shape,+ Shape::Pointer {+ pointee: Pointee::Integral,+ ..+ }+ );+ carries_a_count && !name_matches(param.name.as_ref(), DIMENSION_NAMES)+}++fn carries_extent(role: ParamRole, param: &Param) -> bool {+ matches!(role, ParamRole::Config | ParamRole::Context) && is_length_like(param)+}++fn buffer_quality(param: &Param) -> u8 {+ match ¶m.shape {+ Shape::Pointer { pointee, .. } if pointee.is_exact_byte() => 3,+ Shape::Pointer {+ pointee: Pointee::Void,+ ..+ } => 2,+ _ => 1,+ }+}++#[must_use]+pub fn context_record(param: &Param) -> Option<&str> {+ match ¶m.shape {+ Shape::Pointer {+ pointee: Pointee::Record(name),+ ..+ } => Some(name.as_str()),+ _ => None,+ }+}++#[must_use]+pub fn registered_stream(params: &[Param]) -> Option<String> {+ let has_callback = params.iter().any(|param| {+ matches!(+ ¶m.shape,+ Shape::Pointer {+ pointee: Pointee::Function,+ ..+ }+ )+ });+ if !has_callback {+ return None;+ }+ params+ .iter()+ .find_map(context_record)+ .map(std::borrow::ToOwned::to_owned)+}++#[must_use]+pub fn analyze(params: &[Param]) -> Analysis {+ analyze_with_streams(params, &BTreeSet::new())+}++// libtiff and libarchive declare their parameters unnamed, so param-name evidence is+// often absent. The FUNCTION name still carries it: `_from_file` takes a path,+// `_from_memory` takes bytes. Without this, every unnamed `const char*` in+// archive.h graded as a byte buffer and outranked the real openers.+#[must_use]+pub fn analyze_named(name: &str, params: &[Param], streams: &BTreeSet<String>) -> Analysis {+ let mut analysis = analyze_with_streams(params, streams);+ if analysis.fuzzability != Fuzzability::CastBuffer || !function_reads_a_path(name) {+ return analysis;+ }+ let Some(index) = analysis+ .roles+ .iter()+ .position(|role| *role == ParamRole::Buffer)+ else {+ return analysis;+ };+ if !matches!(+ ¶ms[index].shape,+ Shape::Pointer { pointee, .. } if matches!(pointee, Pointee::Char | Pointee::SignedChar)+ ) {+ return analysis;+ }+ analysis.roles[index] = ParamRole::Path;+ for role in &mut analysis.roles {+ if *role == ParamRole::Length {+ *role = ParamRole::Config;+ }+ }+ analysis.fuzzability = Fuzzability::Path;+ analysis.context_args = analysis+ .roles+ .iter()+ .filter(|role| !matches!(role, ParamRole::Buffer | ParamRole::Length))+ .count();+ analysis+}++fn function_reads_a_path(name: &str) -> bool {+ let tokens = tokenize(name);+ contains_pair(&tokens, "from", "file")+ || contains_pair(&tokens, "from", "filename")+ || tokens.iter().any(|token| token == "filename")+ || tokens.iter().any(|token| token == "pathname")+}++fn contains_pair(tokens: &[String], first: &str, second: &str) -> bool {+ tokens+ .windows(2)+ .any(|window| window[0] == first && window[1] == second)+}++#[must_use]+pub fn analyze_with_streams(params: &[Param], streams: &BTreeSet<String>) -> Analysis {+ let mut analysis = grade_signature(params);+ if analysis.fuzzability == Fuzzability::NoInput+ && params+ .iter()+ .filter_map(context_record)+ .any(|record| streams.contains(record))+ {+ analysis.fuzzability = Fuzzability::StreamDriven;+ }+ analysis+}++fn grade_signature(params: &[Param]) -> Analysis {+ let mut roles: Vec<ParamRole> = params.iter().map(provisional_role).collect();+ let mut paired: Option<usize> = None;+ let mut best = 0;++ // Score every buffer+length pair and keep the strongest, rather than breaking on+ // the first. png_set_iCCP(const char *name, int type, const png_byte *profile,+ // png_uint_32 proflen) otherwise pairs `name` with the enum `type` and grades on+ // that, leaving the real byte buffer unpaired.+ for index in 0..params.len() {+ if roles[index] != ParamRole::Buffer {+ continue;+ }+ let quality = buffer_quality(¶ms[index]);+ let follower = index+ .checked_add(1)+ .filter(|next| *next < params.len())+ .filter(|next| carries_extent(roles[*next], ¶ms[*next]));+ // A length may also precede its buffer: BrotliDecoderDecompress declares+ // (size_t encoded_size, const uint8_t encoded_buffer[], ...).+ let leader = index+ .checked_sub(1)+ .filter(|prior| carries_extent(roles[*prior], ¶ms[*prior]));+ if let Some(extent) = follower.or(leader)+ && quality >= best+ {+ if let Some(previous) = paired+ && let Some(stale) = roles.iter_mut().find(|role| **role == ParamRole::Length)+ && previous != index+ {+ *stale = ParamRole::Config;+ }+ roles[extent] = ParamRole::Length;+ paired = Some(index);+ best = quality;+ }+ }++ for index in 0..params.len() {+ if roles[index] != ParamRole::Buffer || paired == Some(index) {+ continue;+ }+ if lone_pointer_is_path(¶ms[index]) {+ roles[index] = ParamRole::Path;+ }+ }++ let fuzzability = grade(params, &roles, paired);+ let context_args = roles+ .iter()+ .filter(|role| !matches!(role, ParamRole::Buffer | ParamRole::Length))+ .count();++ Analysis {+ fuzzability,+ roles,+ context_args,+ }+}++// A char pointer is only a path when it is NAMED like one. Demoting on type alone+// classified lz4's compressed input as a filename and buried the library's real+// entry point, and libtiff declares its parameters unnamed entirely.+fn lone_pointer_is_path(param: &Param) -> bool {+ matches!(+ ¶m.shape,+ Shape::Pointer { pointee, .. } if matches!(pointee, Pointee::Char | Pointee::SignedChar)+ ) && name_has_token(param.name.as_ref(), PATH_NAMES)+}++fn provisional_role(param: &Param) -> ParamRole {+ match ¶m.shape {+ Shape::Pointer { pointee, is_const } => match pointee {+ Pointee::Function => ParamRole::Callback,+ Pointee::Record(name) if STREAM_RECORDS.contains(&name.as_str()) => ParamRole::Stream,+ Pointee::Record(_) | Pointee::Pointer | Pointee::Other => ParamRole::Context,+ byte if byte.is_byte_sized() => {+ if matches!(pointee, Pointee::Char | Pointee::SignedChar)+ && name_has_token(param.name.as_ref(), PATH_NAMES)+ {+ ParamRole::Path+ } else if *is_const {+ ParamRole::Buffer+ } else if name_matches(param.name.as_ref(), OUTPUT_NAMES) {+ ParamRole::Output+ } else {+ ParamRole::Context+ }+ }+ _ => 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 roles.contains(&ParamRole::Stream) {+ return Fuzzability::Stream;+ }+ if roles.contains(&ParamRole::Callback) {+ return Fuzzability::CustomStream;+ }+ // 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 roles.contains(&ParamRole::Path) {+ return Fuzzability::Path;+ }+ Fuzzability::NoInput+}++#[cfg(test)]+mod tests {+ use super::*;++ fn pointer(name: &str, pointee: Pointee, is_const: bool) -> Param {+ Param {+ name: Some(name.to_owned()),+ spelling: String::new(),+ shape: Shape::Pointer { pointee, is_const },+ }+ }++ fn integral(name: &str) -> Param {+ Param {+ name: Some(name.to_owned()),+ spelling: String::new(),+ shape: Shape::Integral,+ }+ }++ #[test]+ fn a_const_byte_pointer_followed_by_an_integral_is_a_buffer_and_its_length() {+ let params = [+ pointer("data", Pointee::UnsignedChar, true),+ integral("size"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Buffer);+ assert_eq!(analysis.roles[1], ParamRole::Length);+ assert_eq!(analysis.fuzzability, Fuzzability::DirectBuffer);+ }++ #[test]+ fn a_const_void_pointer_with_a_length_is_a_cast_buffer() {+ let params = [pointer("src", Pointee::Void, true), integral("len")];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Buffer);+ assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);+ }++ #[test]+ fn a_const_char_pointer_with_a_length_is_a_cast_buffer_not_a_path() {+ let params = [pointer("buf", Pointee::Char, true), integral("size")];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Buffer);+ assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);+ }++ #[test]+ fn a_lone_const_char_pointer_named_like_a_file_is_a_path() {+ let params = [pointer("filename", Pointee::Char, true)];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Path);+ assert_eq!(analysis.fuzzability, Fuzzability::Path);+ }++ #[test]+ fn a_file_pointer_is_a_stream_entry() {+ let params = [pointer("fp", Pointee::Record("FILE".to_owned()), false)];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Stream);+ assert_eq!(analysis.fuzzability, Fuzzability::Stream);+ }++ #[test]+ fn a_non_const_pointer_with_a_length_is_an_output_buffer_not_an_input() {+ let params = [+ pointer("out", Pointee::UnsignedChar, false),+ integral("outlen"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Output);+ assert_ne!(analysis.fuzzability, Fuzzability::DirectBuffer);+ }++ #[test]+ fn an_integral_before_the_pointer_is_config_not_a_length() {+ let params = [+ integral("version"),+ pointer("buf", Pointee::Char, true),+ integral("len"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Config);+ assert_eq!(analysis.roles[1], ParamRole::Buffer);+ assert_eq!(analysis.roles[2], ParamRole::Length);+ }++ #[test]+ fn dimension_names_are_config_even_when_they_follow_a_buffer() {+ let params = [+ pointer("data", Pointee::UnsignedChar, true),+ integral("width"),+ integral("height"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[1], ParamRole::Config);+ assert_eq!(analysis.roles[2], ParamRole::Config);+ assert!(+ !analysis.roles.contains(&ParamRole::Length),+ "width is allocation math, not an extent"+ );+ assert_eq!(+ analysis.context_args, 2,+ "both dimensions stay context, so the harness must fix them"+ );+ }++ #[test]+ fn an_abbreviated_length_name_is_still_a_length() {+ let params = [+ pointer("inbuffer", Pointee::UnsignedChar, true),+ integral("insize"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[1], ParamRole::Length);+ assert_eq!(analysis.fuzzability, Fuzzability::DirectBuffer);+ }++ #[test]+ fn a_context_pointer_is_neither_buffer_nor_config() {+ let params = [+ pointer("ctx", Pointee::Record("CodecCtx".to_owned()), false),+ pointer("data", Pointee::UnsignedChar, true),+ integral("len"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Context);+ assert_eq!(analysis.fuzzability, Fuzzability::DirectBuffer);+ }++ #[test]+ fn a_callback_plus_context_is_a_custom_stream_entry() {+ let params = [+ pointer("handle", Pointee::Record("png_struct".to_owned()), false),+ pointer("io_ptr", Pointee::Void, false),+ pointer("read_fn", Pointee::Function, false),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[2], ParamRole::Callback);+ assert_eq!(analysis.fuzzability, Fuzzability::CustomStream);+ }++ #[test]+ fn a_function_taking_no_data_at_all_is_not_fuzzable() {+ let params = [integral("flags")];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.fuzzability, Fuzzability::NoInput);+ }++ #[test]+ fn an_empty_parameter_list_is_not_fuzzable() {+ let analysis = analyze(&[]);+ assert_eq!(analysis.fuzzability, Fuzzability::NoInput);+ assert!(analysis.roles.is_empty());+ }++ #[test]+ fn fuzzability_scores_are_ordered_by_harness_difficulty() {+ let ranked = [+ Fuzzability::DirectBuffer,+ Fuzzability::CastBuffer,+ Fuzzability::Stream,+ Fuzzability::CustomStream,+ Fuzzability::StreamDriven,+ Fuzzability::Path,+ Fuzzability::NoInput,+ ];+ for pair in ranked.windows(2) {+ assert!(+ pair[0].score() > pair[1].score(),+ "{:?} must outscore {:?}",+ pair[0],+ pair[1]+ );+ }+ }++ #[test]+ fn the_context_argument_count_excludes_the_buffer_and_its_length() {+ let params = [+ pointer("ctx", Pointee::Record("CodecCtx".to_owned()), false),+ pointer("data", Pointee::UnsignedChar, true),+ integral("len"),+ integral("flags"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.context_args, 2);+ }++ #[test]+ fn a_path_named_char_pointer_is_not_a_buffer_even_when_an_integral_follows() {+ let params = [+ pointer("a", Pointee::Record("archive".to_owned()), false),+ pointer("filename", Pointee::Char, true),+ integral("block_size"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[1], ParamRole::Path);+ assert_ne!(analysis.roles[2], ParamRole::Length);+ assert_eq!(analysis.fuzzability, Fuzzability::Path);+ }++ fn integral_pointer(name: &str) -> Param {+ Param {+ name: Some(name.to_owned()),+ spelling: String::new(),+ shape: Shape::Pointer {+ pointee: Pointee::Integral,+ is_const: false,+ },+ }+ }++ #[test]+ fn a_length_declared_before_its_buffer_is_still_a_length() {+ let params = [+ integral("encoded_size"),+ pointer("encoded_buffer", Pointee::UnsignedChar, true),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Length);+ assert_eq!(analysis.roles[1], ParamRole::Buffer);+ assert_eq!(+ analysis.fuzzability,+ Fuzzability::DirectBuffer,+ "BrotliDecoderDecompress declares the size first"+ );+ }++ #[test]+ fn a_pointer_to_a_length_counts_as_the_extent() {+ let params = [+ pointer("src", Pointee::Void, true),+ integral_pointer("srcSize"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[1], ParamRole::Length);+ assert_eq!(+ analysis.fuzzability,+ Fuzzability::CastBuffer,+ "ZSTD_decompressStream and d2i_* take a pointer to the length"+ );+ }++ #[test]+ fn an_untrusted_buffer_with_no_length_at_all_is_still_fuzzable() {+ let params = [+ pointer("data", Pointee::UnsignedChar, true),+ pointer("ctx", Pointee::Record("Ctx".to_owned()), false),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[0], ParamRole::Buffer);+ assert_ne!(+ analysis.fuzzability,+ Fuzzability::NoInput,+ "a const byte buffer is untrusted input whether or not we located its extent"+ );+ }++ #[test]+ fn a_char_buffer_whose_follower_is_not_integral_is_not_a_path() {+ let params = [+ pointer("src", Pointee::Char, true),+ pointer("dst", Pointee::Char, false),+ integral("compressedSize"),+ integral("dstCapacity"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(+ analysis.roles[0],+ ParamRole::Buffer,+ "LZ4_decompress_safe's src is compressed input, not a filename"+ );+ assert_ne!(analysis.fuzzability, Fuzzability::Path);+ }++ #[test]+ fn an_unnamed_char_pointer_is_never_demoted_to_a_path_on_type_alone() {+ let params = [Param {+ name: None,+ spelling: String::new(),+ shape: Shape::Pointer {+ pointee: Pointee::Char,+ is_const: true,+ },+ }];+ let analysis = analyze(¶ms);+ assert_ne!(+ analysis.roles[0],+ ParamRole::Path,+ "libtiff declares its params unnamed; type alone cannot say path"+ );+ }++ #[test]+ fn a_from_file_function_takes_a_path_even_with_unnamed_parameters() {+ let params = [+ pointer("a", Pointee::Record("archive".to_owned()), false),+ Param {+ name: None,+ spelling: String::new(),+ shape: Shape::Pointer {+ pointee: Pointee::Char,+ is_const: true,+ },+ },+ integral("null_separator"),+ ];+ let analysis = analyze_named(+ "archive_match_exclude_pattern_from_file",+ ¶ms,+ &BTreeSet::new(),+ );+ assert_eq!(analysis.fuzzability, Fuzzability::Path);+ }++ #[test]+ fn a_from_memory_sibling_keeps_its_buffer() {+ let params = [+ pointer("a", Pointee::Record("archive".to_owned()), false),+ pointer("buff", Pointee::Void, true),+ integral("size"),+ ];+ let analysis = analyze_named("archive_read_open_memory", ¶ms, &BTreeSet::new());+ assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);+ }++ #[test]+ fn a_callback_registration_names_the_context_it_attaches_a_stream_to() {+ let params = [+ pointer("png_ptr", Pointee::Record("png_struct".to_owned()), false),+ pointer("io_ptr", Pointee::Void, false),+ pointer("read_fn", Pointee::Function, false),+ ];+ assert_eq!(registered_stream(¶ms).as_deref(), Some("png_struct"));+ }++ #[test]+ fn a_function_with_no_callback_registers_no_stream() {+ assert!(registered_stream(&buffer_and_length()).is_none());+ }++ #[test]+ fn a_context_only_function_is_stream_driven_once_its_context_has_a_reader() {+ let params = [+ pointer("png_ptr", Pointee::Record("png_struct".to_owned()), false),+ pointer("info_ptr", Pointee::Record("png_info".to_owned()), false),+ ];+ let streams = BTreeSet::from(["png_struct".to_owned()]);+ let analysis = analyze_with_streams(¶ms, &streams);+ assert_eq!(analysis.fuzzability, Fuzzability::StreamDriven);+ }++ #[test]+ fn the_same_function_consumes_nothing_when_no_reader_was_registered() {+ let params = [+ pointer("png_ptr", Pointee::Record("png_struct".to_owned()), false),+ pointer("info_ptr", Pointee::Record("png_info".to_owned()), false),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.fuzzability, Fuzzability::NoInput);+ }++ #[test]+ fn an_unrelated_context_stays_unfuzzable_even_when_other_streams_exist() {+ let params = [pointer(+ "opts",+ Pointee::Record("TIFFOpenOptions".to_owned()),+ false,+ )];+ let streams = BTreeSet::from(["png_struct".to_owned()]);+ let analysis = analyze_with_streams(¶ms, &streams);+ assert_eq!(analysis.fuzzability, Fuzzability::NoInput);+ }++ #[test]+ fn a_real_buffer_still_outgrades_a_stream_driven_context() {+ let streams = BTreeSet::from(["png_struct".to_owned()]);+ let direct = analyze_with_streams(&buffer_and_length(), &streams);+ assert_eq!(direct.fuzzability, Fuzzability::DirectBuffer);+ assert!(Fuzzability::DirectBuffer.score() > Fuzzability::StreamDriven.score());+ }++ fn buffer_and_length() -> Vec<Param> {+ vec![+ pointer("data", Pointee::UnsignedChar, true),+ integral("size"),+ ]+ }++ #[test]+ fn the_in_memory_sibling_of_a_path_entry_is_still_a_buffer() {+ let params = [+ pointer("a", Pointee::Record("archive".to_owned()), false),+ pointer("buff", Pointee::Void, true),+ integral("size"),+ ];+ let analysis = analyze(¶ms);+ assert_eq!(analysis.roles[1], ParamRole::Buffer);+ assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);+ }+}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.rsnew file mode 100644index 00000000..eb59326a--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs@@ -0,0 +1,448 @@+// ©AngelaMos | 2026+// surface.rs++use std::collections::BTreeSet;+use std::path::{Path, PathBuf};++use crate::complexity::{self, CallGraph, Defined};+use crate::extract::{self, Declared, Language, ParseOptions};+use crate::harness::{self, Harness};+use crate::headers::{self, HeaderError, HeaderSet};+use crate::rank::{self, Complexity, Function, Ranking, Weights};++pub const SOURCE_EXTENSIONS: &[&str] = &["c", "cc", "cpp", "cxx"];+pub const MAX_DEPTH: usize = 12;+pub const REFUSAL_NUMERATOR: usize = 1;+pub const REFUSAL_DENOMINATOR: usize = 2;+pub const MIN_PLAUSIBLE_SURFACE: usize = 32;++#[derive(Debug, thiserror::Error)]+pub enum SurfaceError {+ #[error("header discovery failed: {0}")]+ Headers(#[from] HeaderError),+ #[error("harness discovery failed: {0}")]+ Harness(#[from] harness::HarnessError),+ #[error(+ "no header under {root} yielded a declaration; {refused} of {total} were refused. \+ first refusal: {first}. if this project generates a config header at build time, \+ run `lisdex build` and pass its install prefix with --install"+ )]+ NothingDeclared {+ root: PathBuf,+ refused: usize,+ total: usize,+ first: String,+ },+ #[error(+ "{refused} of {total} headers under {root} were refused, so the {declared} declaration(s) \+ that did parse are not a usable surface. first refusal: {first}. if this project \+ generates a config header at build time, run `lisdex build` and pass its install \+ prefix with --install"+ )]+ MostlyRefused {+ root: PathBuf,+ refused: usize,+ total: usize,+ declared: usize,+ first: String,+ },+}++#[derive(Debug, Clone)]+pub struct SurfaceOptions {+ pub source: PathBuf,+ pub install: Option<PathBuf>,+ pub includes: Vec<PathBuf>,+ pub defines: Vec<String>,+ pub language: Language,+ pub weights: Weights,+ pub ignore_harnesses: bool,+}++impl SurfaceOptions {+ #[must_use]+ pub fn new(source: impl Into<PathBuf>) -> Self {+ Self {+ source: source.into(),+ install: None,+ includes: Vec::new(),+ defines: Vec::new(),+ language: Language::default(),+ weights: Weights::default(),+ ignore_harnesses: true,+ }+ }++ #[must_use]+ pub fn parse_options(&self, header_root: &Path) -> ParseOptions {+ let mut includes = vec![header_root.to_path_buf(), self.source.clone()];+ includes.extend(self.includes.iter().cloned());+ ParseOptions {+ includes,+ defines: self.defines.clone(),+ extra_args: Vec::new(),+ language: self.language,+ }+ }+}++#[derive(Debug, Clone, serde::Serialize)]+pub struct SkippedHeader {+ pub header: PathBuf,+ pub reason: String,+}++#[derive(Debug, Clone, serde::Serialize)]+pub struct Surface {+ pub source: PathBuf,+ pub origin: headers::HeaderOrigin,+ pub headers_read: usize,+ pub skipped: Vec<SkippedHeader>,+ pub harnesses: Vec<Harness>,+ pub declared: usize,+ pub defined: usize,+ pub skipped_sources: Vec<SkippedHeader>,+ pub ranking: Ranking,+}++fn is_source(path: &Path) -> bool {+ path.extension()+ .and_then(|extension| extension.to_str())+ .is_some_and(|extension| SOURCE_EXTENSIONS.contains(&extension.to_lowercase().as_str()))+}++fn walk_sources(root: &Path, depth: usize, found: &mut Vec<PathBuf>) {+ if depth > MAX_DEPTH {+ return;+ }+ let Ok(entries) = std::fs::read_dir(root) else {+ return;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ let name = entry.file_name().to_string_lossy().to_lowercase();+ if path.is_dir() {+ if !headers::is_excluded(&name) {+ walk_sources(&path, depth + 1, found);+ }+ } else if is_source(&path) {+ found.push(path);+ }+ }+}++#[must_use]+pub fn library_sources(root: &Path) -> Vec<PathBuf> {+ let mut found = Vec::new();+ walk_sources(root, 0, &mut found);+ found.sort();+ found+}++fn read_headers(set: &HeaderSet, options: &SurfaceOptions) -> (Vec<Declared>, Vec<SkippedHeader>) {+ let parse = options.parse_options(&set.root);+ let mut declared = Vec::new();+ let mut skipped = Vec::new();+ let mut seen = BTreeSet::new();++ for header in &set.headers {+ match extract::parse_header(header, &parse) {+ Ok(found) => {+ for item in found {+ if seen.insert(item.name.clone()) {+ declared.push(item);+ }+ }+ }+ Err(error) => skipped.push(SkippedHeader {+ header: header.clone(),+ reason: error.to_string(),+ }),+ }+ }+ (declared, skipped)+}++// A source file that fails to parse silently truncates the call graph, and the call+// graph drives 55% of the score. Header refusals were already surfaced; source+// refusals were not, so a third of libarchive's translation units could vanish with+// no signal at all. Collect them and report them the same way.+fn read_sources(+ root: &Path,+ options: &SurfaceOptions,+ header_root: &Path,+) -> (Vec<Defined>, Vec<SkippedHeader>) {+ let parse = options.parse_options(header_root);+ let mut defined = Vec::new();+ let mut skipped = Vec::new();+ let mut seen = BTreeSet::new();+ for source in library_sources(root) {+ match complexity::parse_source(&source, &parse) {+ Ok(found) => {+ for item in found {+ if seen.insert(item.name.clone()) {+ defined.push(item);+ }+ }+ }+ Err(error) => skipped.push(SkippedHeader {+ header: source,+ reason: error.to_string(),+ }),+ }+ }+ (defined, skipped)+}++pub fn analyze(options: &SurfaceOptions) -> Result<Surface, SurfaceError> {+ let set = headers::discover(&options.source, options.install.as_deref())?;+ let harnesses = harness::discover(&options.source)?;++ let (declared, skipped) = read_headers(&set, options);+ if declared.is_empty() {+ return Err(SurfaceError::NothingDeclared {+ root: set.root.clone(),+ refused: skipped.len(),+ total: set.headers.len(),+ first: skipped+ .first()+ .map_or_else(|| "none recorded".to_owned(), |item| item.reason.clone()),+ });+ }+ if skipped.len() * REFUSAL_DENOMINATOR > set.headers.len() * REFUSAL_NUMERATOR+ && declared.len() < MIN_PLAUSIBLE_SURFACE+ {+ return Err(SurfaceError::MostlyRefused {+ root: set.root.clone(),+ refused: skipped.len(),+ total: set.headers.len(),+ declared: declared.len(),+ first: skipped+ .first()+ .map_or_else(|| "none recorded".to_owned(), |item| item.reason.clone()),+ });+ }++ let (defined, skipped_sources) = read_sources(&options.source, options, &set.root);+ let defined_count = defined.len();+ let graph = CallGraph::from(defined);++ let seeds: Vec<String> = if options.ignore_harnesses {+ Vec::new()+ } else {+ harness::reached_functions(&harnesses).into_iter().collect()+ };+ let reached = graph.reachable_from(&seeds);+ let directly_called: BTreeSet<String> = seeds.into_iter().collect();++ let functions: Vec<Function> = declared+ .iter()+ .map(|item| Function {+ name: item.name.clone(),+ params: item.params.clone(),+ header: item.header.clone(),+ line: item.line,+ exported: graph.get(&item.name).is_none_or(|node| node.exported),+ complexity: Complexity {+ own: graph.danger(&item.name),+ accumulated: graph.accumulated_danger(&item.name),+ undiscovered: graph.undiscovered_danger(&item.name, &reached),+ },+ reachable_from_harness: reached.contains(&item.name)+ || directly_called.contains(&item.name),+ })+ .collect();++ Ok(Surface {+ source: options.source.clone(),+ origin: set.origin,+ headers_read: set.headers.len(),+ skipped,+ harnesses,+ declared: declared.len(),+ defined: defined_count,+ skipped_sources,+ ranking: rank::rank(functions, &options.weights),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tree(label: &str, files: &[(&str, &str)]) -> PathBuf {+ let root =+ std::env::temp_dir().join(format!("lisdex-surface-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ for (path, body) in files {+ let full = root.join(path);+ std::fs::create_dir_all(full.parent().unwrap()).unwrap();+ std::fs::write(&full, body).unwrap();+ }+ root+ }++ const HEADER: &str = "\+#include <stddef.h>+struct ctx;+typedef void (*read_fn)(struct ctx *, unsigned char *, unsigned long);+void ctx_set_read(struct ctx *c, void *user, read_fn fn);+int ctx_read_header(struct ctx *c);+int quick_sig_cmp(const unsigned char *sig, size_t start, size_t len);+struct ctx *ctx_create(void);+void ctx_destroy(struct ctx *c);+";++ const SOURCE: &str = "\+#include \"lib.h\"+struct ctx { int state; };+static int chunk_parse(struct ctx *c, int tag) {+ if (tag == 1) { return 1; }+ if (tag == 2) { return 2; }+ for (int i = 0; i < tag; i++) { c->state += i; }+ while (c->state > 100) { c->state--; }+ switch (tag) { case 9: return 9; case 8: return 8; }+ return 0;+}+int ctx_read_header(struct ctx *c) {+ if (!c) { return -1; }+ return chunk_parse(c, c->state);+}+int quick_sig_cmp(const unsigned char *sig, size_t start, size_t len) {+ return sig[start] == len;+}+void ctx_set_read(struct ctx *c, void *user, read_fn fn) { (void)c; (void)user; (void)fn; }+";++ fn fixture(label: &str, extra: &[(&str, &str)]) -> PathBuf {+ let mut files = vec![("include/lib.h", HEADER), ("src/lib.c", SOURCE)];+ files.extend_from_slice(extra);+ tree(label, &files)+ }++ #[test]+ fn a_context_only_reader_outranks_a_trivial_buffer_comparator() {+ let root = fixture("ranked", &[]);+ let surface = analyze(&SurfaceOptions::new(&root)).unwrap();+ let order: Vec<&str> = surface+ .ranking+ .candidates+ .iter()+ .map(|candidate| candidate.name.as_str())+ .collect();+ assert_eq!(+ order.first(),+ Some(&"ctx_read_header"),+ "the function that drives the parser must win: {order:?}"+ );+ assert!(+ order.iter().position(|name| *name == "ctx_read_header")+ < order.iter().position(|name| *name == "quick_sig_cmp"),+ "{order:?}"+ );+ }++ #[test]+ fn constructors_and_destructors_never_reach_the_candidate_list() {+ let root = fixture("excluded", &[]);+ let surface = analyze(&SurfaceOptions::new(&root)).unwrap();+ let excluded: Vec<&str> = surface+ .ranking+ .excluded+ .iter()+ .map(|item| item.name.as_str())+ .collect();+ assert!(excluded.contains(&"ctx_create"), "{excluded:?}");+ assert!(excluded.contains(&"ctx_destroy"), "{excluded:?}");+ }++ #[test]+ fn accumulated_complexity_reaches_through_static_helpers() {+ let root = fixture("accumulated", &[]);+ let surface = analyze(&SurfaceOptions::new(&root)).unwrap();+ let reader = surface+ .ranking+ .candidates+ .iter()+ .find(|candidate| candidate.name == "ctx_read_header")+ .unwrap();+ assert!(+ reader.complexity.accumulated > reader.complexity.own,+ "chunk_parse is static and must still be counted: {:?}",+ reader.complexity+ );+ }++ #[test]+ fn an_in_tree_harness_marks_what_it_already_reaches() {+ let root = fixture(+ "reached",+ &[(+ "fuzz/f.c",+ "int LLVMFuzzerTestOneInput(const unsigned char *d, unsigned long n) {\n\+ ctx_read_header(0); return 0;\n\+ }\n",+ )],+ );+ let mut options = SurfaceOptions::new(&root);+ options.ignore_harnesses = false;+ let surface = analyze(&options).unwrap();+ assert_eq!(surface.harnesses.len(), 1);+ let reader = surface+ .ranking+ .candidates+ .iter()+ .find(|candidate| candidate.name == "ctx_read_header")+ .unwrap();+ assert!(reader.reachable_from_harness);+ }++ #[test]+ fn a_surface_built_from_a_minority_of_headers_is_refused_not_reported() {+ let mut files = vec![(+ "include/helper.h",+ "int util_decode(const unsigned char *d, unsigned long n);\n",+ )];+ for name in [+ "include/a.h",+ "include/b.h",+ "include/c.h",+ "include/d.h",+ "include/e.h",+ ] {+ files.push((+ name,+ "#include \"generated_config.h\"\nint f(MISSING_T *p);\n",+ ));+ }+ let root = tree("mostlyrefused", &files);+ let error = analyze(&SurfaceOptions::new(&root)).unwrap_err();+ assert!(+ matches!(error, SurfaceError::MostlyRefused { .. }),+ "a partial surface from a handful of parseable helper headers is worse than \+ an error, because it looks like a complete answer: {error:?}"+ );+ }++ #[test]+ fn a_tree_with_no_headers_is_an_error_not_an_empty_ranking() {+ let root = tree("noheaders", &[("src/lib.c", "int main(void){return 0;}")]);+ assert!(analyze(&SurfaceOptions::new(&root)).is_err());+ }++ #[test]+ fn fuzz_and_test_directories_are_not_mined_for_complexity() {+ let root = fixture("nofuzzsrc", &[]);+ let sources = library_sources(&root);+ assert!(sources.iter().any(|path| path.ends_with("lib.c")));+ let root = fixture(+ "nofuzzsrc2",+ &[("fuzz/harness.c", "int noise(void){return 0;}")],+ );+ let sources = library_sources(&root);+ assert!(+ !sources.iter().any(|path| path.ends_with("harness.c")),+ "{sources:?}"+ );+ }+}diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.toml b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.tomlindex 50f6c645..27c23167 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.toml+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex/Cargo.toml@@ -22,3 +22,5 @@ lisdex-core.workspace = truelisdex-fuzz.workspace = truelisdex-ingest.workspace = truelisdex-build.workspace = true+lisdex-surface.workspace = true+serde_json.workspace = truediff --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 6d0c695e..ab12874d 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@@ -17,6 +17,8 @@ use lisdex_core::store::Store;use lisdex_fuzz::runner::{self, AflOptions};use lisdex_ingest::acquire::{self, Source};use lisdex_ingest::detect;+use lisdex_surface::extract::Language;+use lisdex_surface::surface::{self, SurfaceOptions};const UNKNOWN_TARGET: &str = "unknown";const UNPARSED_KIND: &str = "unparsed";@@ -25,6 +27,8 @@ const STACK_HASH_SHORT_LEN: usize = 16;const DISPLAYED_FRAMES: usize = 6;const SOURCES_DIR: &str = "sources";const BUILDS_DIR: &str = "builds";+const DEFAULT_SURFACE_TOP: usize = 20;+const MAX_SKIPPED_SHOWN: usize = 10;#[derive(Parser)]#[command(@@ -43,6 +47,8 @@ enum Command {Build(BuildArgs),#[command(about = "run an AFL++ campaign against an instrumented harness")]Fuzz(FuzzArgs),+ #[command(about = "rank the parser entry points of a source tree")]+ Surface(SurfaceArgs),#[command(about = "list the crashes persisted for a campaign")]Crashes(CrashesArgs),}@@ -109,6 +115,31 @@ struct CrashesArgs {campaign: i64,}+#[derive(clap::Args)]+struct SurfaceArgs {+ #[arg(help = "source tree of the target library")]+ source: PathBuf,+ #[arg(long, help = "install prefix from a previous build, if one exists")]+ install: Option<PathBuf>,+ #[arg(long = "include", help = "extra include directory, repeatable")]+ includes: Vec<PathBuf>,+ #[arg(long = "define", help = "extra preprocessor define, repeatable")]+ defines: Vec<String>,+ #[arg(long, help = "parse headers as C++ instead of C")]+ cpp: bool,+ #[arg(+ long,+ help = "rank the unreached frontier: what to fuzz next given the in-tree harnesses that already exist"+ )]+ frontier: bool,+ #[arg(long, default_value_t = DEFAULT_SURFACE_TOP, help = "how many ranked entry points to print")]+ top: usize,+ #[arg(long, help = "emit the full ranking as json")]+ json: bool,+ #[arg(long, help = "explain the score of every printed entry point")]+ explain: bool,+}+fn main() -> ExitCode {match dispatch() {Ok(()) => ExitCode::SUCCESS,@@ -123,10 +154,96 @@ fn dispatch() -> Result<(), Box<dyn Error>> {match &Cli::parse().command {Command::Build(args) => build(args),Command::Fuzz(args) => fuzz(args),+ Command::Surface(args) => surface(args),Command::Crashes(args) => crashes(args),}}+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.language = if args.cpp { Language::Cpp } else { Language::C };+ options.ignore_harnesses = !args.frontier;++ let analysis = surface::analyze(&options)?;++ if args.json {+ println!("{}", serde_json::to_string_pretty(&analysis)?);+ return Ok(());+ }++ println!(+ "surface: {} headers ({:?}), {} declared, {} defined, {} in-tree harnesses, mode {}",+ analysis.headers_read,+ analysis.origin,+ analysis.declared,+ analysis.defined,+ analysis.harnesses.len(),+ if args.frontier {+ "frontier"+ } else {+ "canonical"+ }+ );+ if !analysis.skipped_sources.is_empty() {+ println!(+ "{} source file(s) did not parse; the call graph behind 55% of the score is \+ incomplete by that much:",+ analysis.skipped_sources.len()+ );+ for skipped in analysis.skipped_sources.iter().take(MAX_SKIPPED_SHOWN) {+ println!(" {} - {}", skipped.header.display(), skipped.reason);+ }+ }+ if !analysis.skipped.is_empty() {+ println!(+ "{} header(s) refused because they do not type check:",+ analysis.skipped.len()+ );+ for skipped in analysis.skipped.iter().take(MAX_SKIPPED_SHOWN) {+ println!(" {} - {}", skipped.header.display(), skipped.reason);+ }+ }++ println!("\nranked entry points:");+ for (position, candidate) in analysis+ .ranking+ .candidates+ .iter()+ .take(args.top)+ .enumerate()+ {+ println!(+ "{:>3}. {:<44} {:.4} {:?} undiscovered={} accumulated={}{}",+ position + 1,+ candidate.name,+ candidate.score,+ candidate.fuzzability,+ candidate.complexity.undiscovered,+ candidate.complexity.accumulated,+ if candidate.reachable_from_harness {+ " [harnessed]"+ } else {+ ""+ }+ );+ if args.explain {+ for reason in &candidate.reasons {+ println!(" {reason}");+ }+ }+ }++ println!(+ "\n{} candidates, {} excluded",+ analysis.ranking.candidates.len(),+ analysis.ranking.excluded.len()+ );+ Ok(())+}+fn build(args: &BuildArgs) -> Result<(), Box<dyn Error>> {let source = Source::parse(&args.target).at(args.reference.clone());let label = args.label.clone().unwrap_or_else(|| source.label());diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile b/PROJECTS/advanced/zero-day-vulnerability-scanner/justfileindex ac8fe3e5..29077eb7 100644--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/justfile@@ -63,3 +63,9 @@ m2-gate:m2-gate-reset:docker compose -f dev.compose.yml exec toolchain bash scripts/m2-gate.sh reset++m3-gate:+ docker compose -f dev.compose.yml exec toolchain bash scripts/m3-gate.sh++m3-gate-reset:+ docker compose -f dev.compose.yml exec toolchain bash scripts/m3-gate.sh resetdiff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.shnew file mode 100755index 00000000..716f3801--- /dev/null+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh@@ -0,0 +1,210 @@+#!/usr/bin/env bash+# ©AngelaMos | 2026+# m3-gate.sh++set -uo pipefail++WORK="${LISDEX_M3_WORK:-/opt/lisdex-m3}"+SRC="$WORK/src"+OUT="$WORK/out"+LISDEX="${LISDEX_BIN:-./target/debug/lisdex}"++PASS=0+FAIL=0++banner() {+ echo ""+ echo "==============================================================="+ echo " $*"+ echo "==============================================================="+}++ok() {+ echo " PASS $*"+ PASS=$((PASS + 1))+}++bad() {+ echo " FAIL $*"+ FAIL=$((FAIL + 1))+}++if [ "${1:-}" = "reset" ]; then+ rm -rf "$WORK"+ echo "m3 gate work directory removed: $WORK"+ exit 0+fi++mkdir -p "$SRC" "$OUT"++clone() {+ local name="$1" url="$2" ref="$3"+ if [ -d "$SRC/$name/.git" ]; then+ return 0+ fi+ echo "cloning $name ($ref)"+ git clone --depth 1 --branch "$ref" "$url" "$SRC/$name" >/dev/null 2>&1 \+ || git clone --depth 1 "$url" "$SRC/$name" >/dev/null 2>&1+}++# libpng is cloned at libpng16 deliberately: the default branch (libpng18) ships+# no contrib/oss-fuzz at all, so a default clone reports zero in-tree harnesses.+clone libpng https://github.com/pnggroup/libpng.git libpng16+clone libtiff https://gitlab.com/libtiff/libtiff.git master+clone openjpeg https://github.com/uclouvain/openjpeg.git master+clone libarchive https://github.com/libarchive/libarchive.git master++# libpng's png.h includes pnglibconf.h, which is NOT in the repository - it is+# produced by the build. libpng ships scripts/pnglibconf.h.prebuilt for exactly+# this case and its own configure copies it. Do the same, so the gate measures a+# tree lisdex can legitimately analyse rather than one that silently resolves+# pnglibconf.h from a system-installed libpng in /usr/include.+if [ -f "$SRC/libpng/scripts/pnglibconf.h.prebuilt" ] && [ ! -f "$SRC/libpng/pnglibconf.h" ]; then+ cp "$SRC/libpng/scripts/pnglibconf.h.prebuilt" "$SRC/libpng/pnglibconf.h"+ echo "seeded libpng/pnglibconf.h from the shipped prebuilt config"+fi++analyse() {+ local name="$1"+ shift+ "$LISDEX" surface "$SRC/$name" --json "$@" >"$OUT/$name.json" 2>"$OUT/$name.err"+}++rank_of() {+ python3 - "$1" "$2" <<'PY'+import json, sys+data = json.load(open(sys.argv[1]))+order = [c["name"] for c in data["ranking"]["candidates"]]+print(order.index(sys.argv[2]) + 1 if sys.argv[2] in order else 0)+PY+}++excluded_as() {+ python3 - "$1" "$2" <<'PY'+import json, sys+data = json.load(open(sys.argv[1]))+found = {e["name"]: e["reason"] for e in data["ranking"]["excluded"]}+print(found.get(sys.argv[2], "NOT-EXCLUDED"))+PY+}++count_of() {+ python3 - "$1" <<'PY'+import json, sys+data = json.load(open(sys.argv[1]))+print(len(data["ranking"]["candidates"]))+PY+}++require_ranked_within() {+ local file="$1" fn="$2" limit="$3" position+ position="$(rank_of "$file" "$fn")"+ if [ "$position" -gt 0 ] && [ "$position" -le "$limit" ]; then+ ok "$fn ranks $position (required: top $limit)"+ else+ bad "$fn ranks ${position} (required: top $limit; 0 means absent)"+ fi+}++require_ranked_outside() {+ local file="$1" fn="$2" floor="$3" position+ position="$(rank_of "$file" "$fn")"+ # A control that is absent from the ranking entirely must FAIL, not pass.+ # Otherwise any change that starts excluding it turns this assertion into a+ # no-op while the gate stays green - the negative control needs its own floor.+ if [ "$position" -eq 0 ]; then+ bad "NEGATIVE CONTROL $fn is absent from the ranking; the control proves nothing"+ elif [ "$position" -gt "$floor" ]; then+ ok "NEGATIVE CONTROL $fn ranks $position (required: worse than $floor)"+ else+ bad "NEGATIVE CONTROL $fn ranks $position (required: worse than $floor)"+ fi+}++require_excluded_as() {+ local file="$1" fn="$2" reason="$3" got+ got="$(excluded_as "$file" "$fn")"+ if [ "$got" = "$reason" ]; then+ ok "$fn excluded as $reason"+ else+ bad "$fn excluded as $got (required: $reason)"+ fi+}++banner "M3 GATE - parser entry-point discovery and ranking"++banner "1. self-contained-header targets rank with no build at all"+for target in libpng libarchive; do+ if analyse "$target"; then+ total="$(count_of "$OUT/$target.json")"+ if [ "$total" -gt 0 ]; then+ ok "$target produced $total ranked candidates point-and-run"+ else+ bad "$target produced an empty ranking"+ fi+ else+ bad "$target analysis failed: $(head -1 "$OUT/$target.err")"+ fi+done++banner "1b. targets needing a build-generated config header say so, loudly"+# libtiff needs tiffconf.h and openjpeg needs opj_config.h, both produced by+# their build. Analysing without one must fail with an actionable diagnosis+# rather than silently reporting an empty or partial surface.+for target in libtiff openjpeg; do+ if analyse "$target"; then+ bad "$target unexpectedly succeeded with no build; the gate assumption is stale"+ elif grep -q -- "--install" "$OUT/$target.err"; then+ ok "$target refused with an actionable diagnosis naming --install"+ else+ bad "$target failed without telling the user what to do: $(head -1 "$OUT/$target.err")"+ fi+done++banner "2. NEGATIVE CONTROLS - a ranker that name-matches must fail here"+require_ranked_outside "$OUT/libpng.json" png_sig_cmp 10+require_ranked_outside "$OUT/libarchive.json" archive_read_support_format_zip 20+require_ranked_outside "$OUT/libarchive.json" archive_read_support_filter_gzip 20+require_ranked_outside "$OUT/libpng.json" png_read_update_info 5++banner "3. encoder-side and lifecycle functions never reach the candidate list"+require_excluded_as "$OUT/libpng.json" png_write_png Producer+require_excluded_as "$OUT/libpng.json" png_create_read_struct Lifecycle+require_excluded_as "$OUT/libpng.json" png_destroy_read_struct Lifecycle+require_excluded_as "$OUT/libpng.json" png_set_read_fn Lifecycle+require_excluded_as "$OUT/libarchive.json" archive_write_data Producer++banner "4. ground-truth entry points rank in the cold-start surface"+require_ranked_within "$OUT/libpng.json" png_image_begin_read_from_memory 10+require_ranked_within "$OUT/libpng.json" png_read_png 10+require_ranked_within "$OUT/libpng.json" png_process_data 15+require_ranked_within "$OUT/libpng.json" png_read_info 20+require_ranked_within "$OUT/libarchive.json" archive_read_open_memory 10+# archive_read_open takes three callbacks, so it grades CustomStream (0.4) against+# archive_read_open_memory's CastBuffer (0.8) and ranks below it by design - the+# in-memory sibling needs no callback synthesis at all and ranks 1. 30 is the+# measured position, kept tight so a real regression past it still fails.+require_ranked_within "$OUT/libarchive.json" archive_read_open 30++banner "5. the harness-aware mode changes the answer"+analyse libpng --frontier+warm_png="$(rank_of "$OUT/libpng.json" png_process_data)"+analyse libpng+cold_png="$(rank_of "$OUT/libpng.json" png_process_data)"+if [ "$warm_png" -gt 0 ] && [ "$cold_png" -gt 0 ] && [ "$warm_png" -ne "$cold_png" ]; then+ ok "in-tree harnesses move png_process_data from cold rank $cold_png to warm rank $warm_png"+else+ bad "harness awareness had no effect (cold=$cold_png warm=$warm_png)"+fi++banner "RESULT"+echo " passed: $PASS"+echo " failed: $FAIL"+if [ "$FAIL" -eq 0 ]; then+ echo ""+ echo " M3 GATE GREEN"+ exit 0+fi+echo ""+echo " M3 GATE RED"+exit 1