Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

22.5 KB
Raw Blame
// ©AngelaMos | 2026
// rank.rs

use std::collections::BTreeSet;
use std::path::PathBuf;

use crate::naming::{self, NameSignal, Role};
use crate::signature::{self, Analysis, Fuzzability, Param, Returns};

pub const WEIGHT_UNDISCOVERED: f64 = 0.40;
pub const WEIGHT_FUZZABILITY: f64 = 0.25;
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)]
// All three are DANGER, not cyclomatic complexity: `danger` is a function's own cyclomatic plus
// its loops, nested loops and maximum nesting, and the other two sum that over what it reaches.
// The first field was published as `own` while carrying `graph.danger()`, which named a
// different metric than it held in an artifact other people read.
pub struct Complexity {
    pub danger: 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 result: Returns,
    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 params: Vec<Param>,
    pub result: Returns,
    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,
    }
}

// The fixed scale a danger score is measured against, so that a score is a property of the
// FUNCTION rather than of whatever else happened to be analysed beside it. Normalising
// against the candidate set's own maximum made it a property of the SET: adding one generated
// candidate to libpng moved every top-10 score - png_image_begin_read_from_memory went 0.9150
// to 0.9045 while its accumulated danger stayed at 5086 in both runs.
//
// The value is MEASURED, not guessed, and the obvious guess is wrong. Over the six validation
// trees the largest accumulated danger is libarchive's 18673, then openjpeg 9855, libpng 7076,
// libtiff 5390, brotli 1122, lz4 699. A scale of 10000 therefore CLAMPS: libarchive's whole
// top would saturate at 1.0 and stop discriminating, on the one tree where the numbers were
// hardest won. This leaves 1.75x headroom over anything measured.
//
// A saturating ratio was tried first because it can never clamp at all, and was rejected on
// measurement: it cannot discriminate across a range this wide. At the magnitudes a small
// synthetic tree produces it scored a parser-driving reader 0.012 against a trivial
// comparator's 0.001, a gap of one hundredth, which handed the ordering to the signature
// grade. A logarithm keeps the same pair 0.247 against 0.067.
pub const DANGER_SCALE: u32 = 32_768;

#[must_use]
pub fn complexity_score(accumulated: u32) -> f64 {
    if accumulated == 0 {
        return 0.0;
    }
    let scaled = f64::from(accumulated + 1).ln() / f64::from(DANGER_SCALE + 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))
}

fn score_candidate(
    function: Function,
    signal: &NameSignal,
    analysis: Analysis,
    weights: &Weights,
) -> Candidate {
    let accumulated = complexity_score(function.complexity.accumulated);
    let undiscovered = complexity_score(function.complexity.undiscovered);
    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 {} -> {undiscovered:.3}",
            function.complexity.undiscovered
        ),
        format!("signature {:?} -> {fuzzability:.3}", analysis.fuzzability),
        format!(
            "accumulated danger {} -> {accumulated:.3}",
            function.complexity.accumulated
        ),
        format!(
            "{}",
            if function.reachable_from_harness {
                "an in-tree harness already calls this directly"
            } else {
                "no in-tree harness calls this directly"
            }
        ),
        format!("{} context args -> {simplicity:.3}", analysis.context_args),
        format!("name signal {:?} -> {name:.3}", signal.reliability),
    ];

    Candidate {
        name: function.name,
        params: function.params,
        result: function.result,
        header: function.header,
        line: function.line,
        fuzzability: analysis.fuzzability,
        analysis,
        complexity: function.complexity,
        exported: function.exported,
        reachable_from_harness: function.reachable_from_harness,
        score,
        reasons,
    }
}

#[must_use]
pub fn rank(functions: Vec<Function>, weights: &Weights) -> Ranking {
    let mut excluded = Vec::new();
    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 mut candidates: Vec<Candidate> = kept
        .into_iter()
        .map(|(function, signal, analysis)| score_candidate(function, &signal, analysis, weights))
        .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,
            result: Returns::default(),
            header: "x.h".into(),
            line: 1,
            exported: true,
            complexity: Complexity {
                danger: 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 {
            result: Returns::default(),
            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(None),
                        is_const: false,
                    },
                ),
            ],
            header: "tiffio.h".into(),
            line: 1,
            exported: true,
            complexity: Complexity {
                danger: 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(None),
                        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());
    }

    #[test]
    fn the_same_danger_scores_the_same_whatever_else_was_analysed() {
        let alone = complexity_score(5086);
        let beside_a_giant = complexity_score(5086);
        assert!((alone - beside_a_giant).abs() < f64::EPSILON);
        assert!(
            complexity_score(5086) > complexity_score(2745),
            "a score must still order two functions by their danger"
        );
    }

    #[test]
    fn the_scale_still_separates_the_largest_library_measured() {
        // libarchive's largest measured accumulated danger is 14646, and a scale of 10000 -
        // the obvious guess - saturates it and everything above it to a single 1.0.
        let biggest = complexity_score(14646);
        let mid = complexity_score(5088);
        let small = complexity_score(439);
        assert!(small < mid && mid < biggest && biggest < 1.0);
        assert!(
            biggest - mid > 0.05,
            "the top of the largest tree must stay distinguishable: {mid} then {biggest}"
        );
    }

    #[test]
    fn the_scale_still_separates_the_magnitudes_a_small_tree_produces() {
        let reader = complexity_score(12);
        let comparator = complexity_score(1);
        assert!(
            reader - comparator > 0.1,
            "a saturating ratio put these one hundredth apart and handed the ordering to the \
             signature grade: {comparator} then {reader}"
        );
    }

    #[test]
    fn a_function_that_reaches_nothing_scores_nothing() {
        assert!((complexity_score(0) - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn adding_a_more_dangerous_candidate_leaves_every_other_score_untouched() {
        let modest = function("modest", buffer_pair(), 100);
        let giant = function("giant", buffer_pair(), 40_000);
        let small_set = rank(vec![modest.clone()], &Weights::default());
        let large_set = rank(vec![modest, giant], &Weights::default());
        let before = small_set.candidates[0].score;
        let after = large_set
            .candidates
            .iter()
            .find(|candidate| candidate.name == "modest")
            .unwrap()
            .score;
        assert!(
            (before - after).abs() < f64::EPSILON,
            "normalising against the set's own maximum moved libpng's whole top ten while \
             every accumulated danger stayed identical: {before} then {after}"
        );
    }
}