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 👇

9.7 KB
Raw Blame
// ©AngelaMos | 2026
// plot.rs

pub const PLOT_FILE_NAME: &str = "plot_data";

const HEADER_PREFIX: char = '#';
const FIELD_SEPARATOR: char = ',';
const PERCENT_SUFFIX: char = '%';

const COLUMN_RELATIVE_TIME: &str = "relative_time";
const COLUMN_CORPUS_COUNT: &str = "corpus_count";
const COLUMN_EDGES_FOUND: &str = "edges_found";
const COLUMN_EXECS_PER_SEC: &str = "execs_per_sec";
const COLUMN_TOTAL_EXECS: &str = "total_execs";
const COLUMN_SAVED_CRASHES: &str = "saved_crashes";
const COLUMN_MAP_SIZE: &str = "map_size";

const REQUIRED_COLUMNS: [&str; 7] = [
    COLUMN_RELATIVE_TIME,
    COLUMN_CORPUS_COUNT,
    COLUMN_EDGES_FOUND,
    COLUMN_EXECS_PER_SEC,
    COLUMN_TOTAL_EXECS,
    COLUMN_SAVED_CRASHES,
    COLUMN_MAP_SIZE,
];

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum PlotError {
    #[error("plot_data has no header line, so its columns cannot be named")]
    MissingHeader,
    #[error("plot_data header does not name column {0}")]
    MissingColumn(&'static str),
    #[error("plot_data row {row} has {found} fields, but the header names {expected}")]
    ShortRow {
        row: usize,
        found: usize,
        expected: usize,
    },
    #[error("plot_data column {column} has unparsable value {value}")]
    BadValue { column: &'static str, value: String },
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CoverageSample {
    pub relative_time: u64,
    pub corpus_count: u64,
    pub edges_found: u64,
    pub execs_per_sec: f64,
    pub total_execs: u64,
    pub saved_crashes: u64,
    pub map_size_pct: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CoverageCurve {
    samples: Vec<CoverageSample>,
}

impl CoverageCurve {
    #[must_use]
    pub fn samples(&self) -> &[CoverageSample] {
        &self.samples
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.samples.is_empty()
    }

    #[must_use]
    pub fn last(&self) -> Option<&CoverageSample> {
        self.samples.last()
    }

    #[must_use]
    pub fn duration_secs(&self) -> u64 {
        self.samples.last().map_or(0, |sample| sample.relative_time)
    }

    #[must_use]
    pub fn peak_edges(&self) -> u64 {
        self.samples
            .iter()
            .map(|sample| sample.edges_found)
            .max()
            .unwrap_or(0)
    }

    #[must_use]
    pub fn time_to_first_crash(&self) -> Option<u64> {
        self.samples
            .iter()
            .find(|sample| sample.saved_crashes > 0)
            .map(|sample| sample.relative_time)
    }

    #[must_use]
    pub fn edges_are_monotonic(&self) -> bool {
        self.samples
            .windows(2)
            .all(|pair| pair[1].edges_found >= pair[0].edges_found)
    }
}

fn header_index(header: &str) -> Result<Vec<&str>, PlotError> {
    let names: Vec<&str> = header
        .trim_start_matches(HEADER_PREFIX)
        .split(FIELD_SEPARATOR)
        .map(str::trim)
        .collect();
    for required in REQUIRED_COLUMNS {
        if !names.contains(&required) {
            return Err(PlotError::MissingColumn(required));
        }
    }
    Ok(names)
}

fn cell<'a>(
    fields: &[&'a str],
    names: &[&str],
    column: &'static str,
) -> Result<&'a str, PlotError> {
    let index = names
        .iter()
        .position(|name| *name == column)
        .ok_or(PlotError::MissingColumn(column))?;
    fields
        .get(index)
        .copied()
        .ok_or(PlotError::MissingColumn(column))
}

fn integer(fields: &[&str], names: &[&str], column: &'static str) -> Result<u64, PlotError> {
    let value = cell(fields, names, column)?;
    value.parse().map_err(|_| PlotError::BadValue {
        column,
        value: value.to_owned(),
    })
}

fn decimal(fields: &[&str], names: &[&str], column: &'static str) -> Result<f64, PlotError> {
    let value = cell(fields, names, column)?;
    value
        .trim_end_matches(PERCENT_SUFFIX)
        .parse()
        .map_err(|_| PlotError::BadValue {
            column,
            value: value.to_owned(),
        })
}

pub fn parse(text: &str) -> Result<CoverageCurve, PlotError> {
    let mut lines = text.lines().filter(|line| !line.trim().is_empty());
    let header = lines.next().ok_or(PlotError::MissingHeader)?;
    if !header.trim_start().starts_with(HEADER_PREFIX) {
        return Err(PlotError::MissingHeader);
    }
    let names = header_index(header)?;

    let mut samples = Vec::new();
    for (row, line) in lines.enumerate() {
        if line.trim_start().starts_with(HEADER_PREFIX) {
            continue;
        }
        let fields: Vec<&str> = line.split(FIELD_SEPARATOR).map(str::trim).collect();
        if fields.len() < names.len() {
            return Err(PlotError::ShortRow {
                row,
                found: fields.len(),
                expected: names.len(),
            });
        }
        samples.push(CoverageSample {
            relative_time: integer(&fields, &names, COLUMN_RELATIVE_TIME)?,
            corpus_count: integer(&fields, &names, COLUMN_CORPUS_COUNT)?,
            edges_found: integer(&fields, &names, COLUMN_EDGES_FOUND)?,
            execs_per_sec: decimal(&fields, &names, COLUMN_EXECS_PER_SEC)?,
            total_execs: integer(&fields, &names, COLUMN_TOTAL_EXECS)?,
            saved_crashes: integer(&fields, &names, COLUMN_SAVED_CRASHES)?,
            map_size_pct: decimal(&fields, &names, COLUMN_MAP_SIZE)?,
        });
    }
    Ok(CoverageCurve { samples })
}

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

    const REAL_HEADER: &str = "# relative_time, cycles_done, cur_item, corpus_count, pending_total, pending_favs, map_size, saved_crashes, saved_hangs, max_depth, execs_per_sec, total_execs, edges_found, total_crashes, servers_count";

    const REAL_PLOT: &str = "# relative_time, cycles_done, cur_item, corpus_count, pending_total, pending_favs, map_size, saved_crashes, saved_hangs, max_depth, execs_per_sec, total_execs, edges_found, total_crashes, servers_count
62, 3, 755, 945, 18, 0, 16.96%, 21, 0, 16, 46602.89, 1677996, 11726, 463, 0
124, 6, 900, 980, 4, 0, 17.10%, 24, 0, 17, 45011.02, 3400000, 11800, 500, 0
";

    #[test]
    fn a_real_plot_data_parses_by_column_name() {
        let curve = parse(REAL_PLOT).expect("real plot_data must parse");
        assert_eq!(curve.samples().len(), 2);
        let first = curve.samples()[0];
        assert_eq!(first.relative_time, 62);
        assert_eq!(first.corpus_count, 945);
        assert_eq!(first.edges_found, 11726);
        assert_eq!(first.total_execs, 1_677_996);
        assert_eq!(first.saved_crashes, 21);
        assert!((first.execs_per_sec - 46602.89).abs() < f64::EPSILON);
        assert!(
            (first.map_size_pct - 16.96).abs() < f64::EPSILON,
            "map_size carries a percent suffix in the real file and has to be stripped, not parsed as text"
        );
    }

    #[test]
    fn the_columns_are_found_by_name_so_a_new_one_cannot_shift_the_rest() {
        let reordered = "# edges_found, relative_time, corpus_count, execs_per_sec, total_execs, saved_crashes, map_size, brand_new_column
11726, 62, 945, 46602.89, 1677996, 21, 16.96%, 999
";
        let curve = parse(reordered).expect("column order must not matter");
        let first = curve.samples()[0];
        assert_eq!(
            (first.edges_found, first.relative_time),
            (11726, 62),
            "AFL++ has added columns to this file before (servers_count is recent); reading by position would silently attribute one column's values to another field"
        );
    }

    #[test]
    fn a_header_missing_a_column_we_need_is_refused_rather_than_guessed() {
        let without_edges = "# relative_time, corpus_count, execs_per_sec, total_execs, saved_crashes, map_size\n62, 945, 46602.89, 1677996, 21, 16.96%\n";
        assert_eq!(
            parse(without_edges),
            Err(PlotError::MissingColumn(COLUMN_EDGES_FOUND))
        );
    }

    #[test]
    fn a_file_with_no_header_is_refused_because_its_columns_cannot_be_named() {
        assert_eq!(
            parse("62, 3, 755, 945\n"),
            Err(PlotError::MissingHeader),
            "a headerless file could only be read positionally, which is the thing this parser exists to avoid"
        );
        assert_eq!(parse(""), Err(PlotError::MissingHeader));
    }

    #[test]
    fn a_truncated_row_is_refused_rather_than_read_short() {
        let truncated = format!("{REAL_HEADER}\n62, 3, 755\n");
        assert!(matches!(
            parse(&truncated),
            Err(PlotError::ShortRow {
                row: 0,
                found: 3,
                ..
            })
        ));
    }

    #[test]
    fn a_header_only_file_is_an_empty_curve_and_not_an_error() {
        let curve = parse(&format!("{REAL_HEADER}\n"))
            .expect("a campaign that wrote no row yet is not malformed");
        assert!(curve.is_empty());
        assert_eq!(curve.duration_secs(), 0);
        assert_eq!(curve.peak_edges(), 0);
        assert_eq!(curve.last(), None);
    }

    #[test]
    fn the_curve_reports_its_own_shape() {
        let curve = parse(REAL_PLOT).unwrap();
        assert_eq!(curve.duration_secs(), 124);
        assert_eq!(curve.peak_edges(), 11800);
        assert!(curve.edges_are_monotonic());
    }

    #[test]
    fn edges_going_backwards_is_reported_rather_than_smoothed_over() {
        let regressed = format!(
            "{REAL_HEADER}\n62, 3, 755, 945, 18, 0, 16.96%, 21, 0, 16, 46602.89, 1677996, 11726, 463, 0\n124, 6, 900, 980, 4, 0, 17.10%, 24, 0, 17, 45011.02, 3400000, 9000, 500, 0\n"
        );
        let curve = parse(&regressed).unwrap();
        assert!(
            !curve.edges_are_monotonic(),
            "edges found can only grow within one campaign, so a fall means the file was rotated, resumed over, or concatenated, and a caller comparing first to last would understate coverage"
        );
        assert_eq!(curve.peak_edges(), 11726);
    }
}