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 👇

48.7 KB
Raw Blame
// ©AngelaMos | 2026
// signature.rs

use std::collections::{BTreeMap, 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 AFFINITY_SHARED_TOKENS: usize = 100;

pub const STREAM_RECORDS: &[&str] = &["FILE", "_IO_FILE", "__sFILE"];

pub const VOID_SPELLING: &str = "void";

pub const LENGTH_NAMES: &[&str] = &[
    "size",
    "len",
    "length",
    "nbytes",
    "nbyte",
    "num_bytes",
    "bytes",
    "count",
    "capacity",
    "avail",
    "nmemb",
    "sz",
    "n",
];

// An extent is a count of bytes. These typedefs name a different quantity, so one standing
// beside a buffer is never that buffer's length. libarchive declares
// `time_t archive_parse_date(time_t now, const char *datestr)`, and grading `now` as an
// extent satisfied the char-buffer-needs-a-length guard, so the planner handed a date
// parser to a user who asked to fuzz an archive reader.
pub const NON_EXTENT_TYPES: &[&str] = &[
    "time_t",
    "clock_t",
    "suseconds_t",
    "useconds_t",
    "pid_t",
    "uid_t",
    "gid_t",
    "dev_t",
    "ino_t",
    "mode_t",
    "nlink_t",
    "bool",
    "_Bool",
];

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 {
    // The call that RECEIVES the corpus bytes, as opposed to one that merely appears in the
    // author's sequence. libarchive's `archive_read_support_format_rar5(struct archive *)`
    // is in every one of its 25 fuzz targets and takes no input at all; treating "the
    // authors call it" as "the authors fuzz it" hoisted seven such configurators above the
    // entry point the M3 gate asserts ranks first.
    #[must_use]
    pub fn takes_bytes(self) -> bool {
        matches!(self, Fuzzability::DirectBuffer | Fuzzability::CastBuffer)
    }

    #[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, Default, PartialEq, Eq, serde::Serialize)]
pub struct Prototype {
    pub returns: String,
    pub params: Vec<String>,
}

impl Prototype {
    #[must_use]
    pub fn returns_void(&self) -> bool {
        self.returns == VOID_SPELLING
    }
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum Pointee {
    UnsignedChar,
    SignedChar,
    Char,
    Void,
    Integral,
    Record(String),
    Function(Option<Prototype>),
    // What the second indirection points AT, because the answer decides whether a double
    // pointer is a slot the library fills or a buffer the caller must size, and collapsing
    // it to a leaf made those two indistinguishable. `png_bytep *` and `struct
    // archive_entry **` are the same shape here and opposite obligations one level down.
    Pointer(Box<Pointee>),
    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, Default, PartialEq, Eq, serde::Serialize)]
pub enum Shape {
    Pointer {
        pointee: Pointee,
        is_const: bool,
    },
    Integral,
    Record(String),
    Float,
    #[default]
    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, Default, PartialEq, Eq, serde::Serialize)]
pub struct Returns {
    pub spelling: String,
    pub shape: Shape,
}

fn opaque_typedef(spelling: &str) -> Option<String> {
    let name = spelling.trim();
    let mut characters = name.chars();
    let heads = characters
        .next()
        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_');
    let tails = characters.all(|rest| rest.is_ascii_alphanumeric() || rest == '_');
    (heads && tails).then(|| name.to_owned())
}

// `typedef void *tjhandle` defeats canonical-type matching on 17 of libjpeg-turbo's 21
// entry points: every one of them refused with "parameter handle has no binding rule"
// because the canonical type is a bare `void *` that names nothing. The identity of an
// opaque handle is therefore the typedef it was SPELLED with, never what it collapses to.
#[must_use]
pub fn handle_key(spelling: &str, shape: &Shape) -> Option<String> {
    match shape {
        Shape::Pointer {
            pointee: Pointee::Record(name),
            ..
        } => Some(name.clone()),
        Shape::Pointer {
            pointee: Pointee::Void,
            ..
        } => opaque_typedef(spelling),
        _ => None,
    }
}

// `X **out` where X is a record: the LIBRARY allocates the X and writes its address into a
// slot the caller owns. That is the opposite obligation from `unsigned char **planes`, where
// the caller allocates and the library reads - and the two are the same `Shape::Pointer` until
// this asks what the second indirection points at. Canonical types only: `png_bytep *` spells
// a record and is `unsigned char **`.
#[must_use]
pub fn record_behind_two_pointers(shape: &Shape) -> Option<&str> {
    let Shape::Pointer {
        pointee: Pointee::Pointer(inner),
        ..
    } = shape
    else {
        return None;
    };
    match inner.as_ref() {
        Pointee::Record(name) => Some(name),
        _ => None,
    }
}

#[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,
    // Which parameter is the extent OF which pointer, rather than the single global pair
    // the signature used to carry. A decoder declares several at once -
    // LZ4_decompress_safe(src, dst, compressedSize, dstCapacity) has two - and binding one
    // buffer's length to another buffer is how a harness hands a library a lie about
    // memory it does not own.
    pub extents: BTreeMap<usize, usize>,
}

fn name_matches(name: Option<&String>, candidates: &[&str]) -> bool {
    name.is_some_and(|name| matches_vocabulary(name, candidates))
}

// Exposed so the synthesizer asks the SAME question of a name that the grader does. A
// leftover extent is allowed to bind the output capacity only when it names an output
// quantity, and "names an output quantity" has to mean exactly what it means when it
// decides that a pointer is an output, or the two halves of the tool disagree about
// `targetOutputSize`.
#[must_use]
pub fn matches_vocabulary(name: &str, candidates: &[&str]) -> bool {
    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 names_a_non_extent_type(spelling: &str) -> bool {
    spelling
        .split(|character: char| !character.is_ascii_alphanumeric() && character != '_')
        .any(|token| NON_EXTENT_TYPES.contains(&token))
}

// Any integral standing beside a buffer used to be taken as its extent. Measured across
// five upstream libraries, half the parameters that won the role were not extents at all -
// `time_t now`, `int _flag`, `int align`, `int rgb_step`, `int fd`. Every genuine one was
// named for what it is, so a NAMED integral now has to say so; an unnamed one still
// qualifies on type alone, because libtiff and libarchive declare parameters without names.
fn is_length_like(param: &Param) -> bool {
    let carries_a_count = matches!(param.shape, Shape::Integral)
        || matches!(
            &param.shape,
            Shape::Pointer {
                pointee: Pointee::Integral,
                ..
            }
        );
    if !carries_a_count || names_a_non_extent_type(&param.spelling) {
        return false;
    }
    if name_matches(param.name.as_ref(), DIMENSION_NAMES) {
        return false;
    }
    param.name.is_none() || name_matches(param.name.as_ref(), LENGTH_NAMES)
}

fn shared_leading_run(buffer: Option<&String>, extent: Option<&String>) -> usize {
    let (Some(buffer), Some(extent)) = (buffer, extent) else {
        return 0;
    };
    let extent = tokenize(extent);
    tokenize(buffer)
        .into_iter()
        .zip(extent)
        .take_while(|(one, other)| one == other)
        .count()
}

fn carries_extent(role: ParamRole, param: &Param) -> bool {
    matches!(role, ParamRole::Config | ParamRole::Context) && is_length_like(param)
}

// How strongly `extent` reads as the length OF `pointer`. Measured over 81 real signatures
// on seven upstream trees, this is the only tier that survives a count mismatch:
// LZ4_decompress_safe_partial(src, dst, srcSize, targetOutputSize, dstCapacity) has three
// extents for two buffers, and only the names say that targetOutputSize belongs to neither.
//
// A prefix arm and a substring arm were built beside this one and BOTH WERE DELETED: gutting
// them changed the extent map of exactly ZERO candidates across all seven trees. The
// concatenated-lowercase shapes they were written for - blake2xb's `out`/`outlen`,
// `in`/`inlen` - are already placed by the position tier, which needs no name at all. Two
// scoring arms that never decide anything can still decide something WRONG on a tree nobody
// has measured, so they earn their place by measurement or they do not ship.
fn extent_affinity(pointer: Option<&String>, extent: Option<&String>) -> usize {
    let run = shared_leading_run(pointer, extent);
    if run > 0 {
        AFFINITY_SHARED_TOKENS + run
    } else {
        0
    }
}

fn extent_candidates(params: &[Param], roles: &[ParamRole]) -> Vec<usize> {
    (0..params.len())
        .filter(|index| carries_extent(roles[*index], &params[*index]))
        .collect()
}

// Context is in this set because a byte pointer is never a real context - `handle_key`
// returns None for one, so it can only ever refuse. brotli declares
// `uint8_t decoded_buffer[]`, which is not spelled out/dst/dest/output/result and so fell
// to Context and refused the library's canonical decode entry. What makes a parameter an
// output buffer is being writable and carrying a declared capacity, not being named for it.
fn extentable_pointers(params: &[Param], roles: &[ParamRole]) -> Vec<usize> {
    (0..params.len())
        .filter(|index| {
            matches!(
                roles[*index],
                ParamRole::Buffer | ParamRole::Output | ParamRole::Context
            )
        })
        .filter(|index| {
            matches!(&params[*index].shape, Shape::Pointer { pointee, .. }
                if pointee.is_byte_sized())
        })
        // `typedef void *tjhandle` is byte-sized and non-const, so it grades Context beside
        // the real output buffers. Promoting one to an output would hand libjpeg-turbo a
        // zeroed malloc where it expects an initialised handle and SEGV inside the library
        // on the first seed - the D12 class, manufactured by us. An opaque handle is
        // whatever it was SPELLED as, which is the question handle_key already answers.
        .filter(|index| {
            roles[*index] != ParamRole::Context
                || handle_key(&params[*index].spelling, &params[*index].shape).is_none()
        })
        .collect()
}

// Every buffer's own extent, not the one strongest pair in the signature. Adjacency alone
// could not see past an intervening pointer, so LZ4_decompress_safe's `compressedSize`
// graded as a Config and its `src` was refused as an unsized string - which is why lz4
// emitted nothing at all.
fn assign_extents(params: &[Param], roles: &[ParamRole]) -> BTreeMap<usize, usize> {
    let pointers = extentable_pointers(params, roles);
    let extents = extent_candidates(params, roles);
    let mut owned: BTreeMap<usize, usize> = BTreeMap::new();
    let mut claimed: BTreeSet<usize> = BTreeSet::new();

    let mut scored: Vec<(usize, usize, usize)> = Vec::new();
    for pointer in &pointers {
        for extent in &extents {
            let score = extent_affinity(
                params[*pointer].name.as_ref(),
                params[*extent].name.as_ref(),
            );
            if score > 0 {
                scored.push((score, *pointer, *extent));
            }
        }
    }
    scored.sort_by(|one, other| {
        other
            .0
            .cmp(&one.0)
            .then_with(|| one.1.cmp(&other.1))
            .then_with(|| one.2.cmp(&other.2))
    });
    for (_, pointer, extent) in scored {
        if owned.contains_key(&pointer) || claimed.contains(&extent) {
            continue;
        }
        owned.insert(pointer, extent);
        claimed.insert(extent);
    }

    // Position is a statement about the whole signature and adjacency is a statement about
    // one gap, so position speaks first. Running adjacency ahead of it gave
    // LZ4_uncompress_unknownOutputSize(source, dest, isize, maxOutputSize) the pair
    // dest=isize, and the leftover then handed `source` the output capacity - both lies.
    let unowned: Vec<usize> = pointers
        .iter()
        .copied()
        .filter(|pointer| !owned.contains_key(pointer))
        .collect();
    let unclaimed: Vec<usize> = extents
        .iter()
        .copied()
        .filter(|extent| !claimed.contains(extent))
        .collect();
    if !unowned.is_empty() && unowned.len() == unclaimed.len() {
        for (pointer, extent) in unowned.iter().zip(&unclaimed) {
            owned.insert(*pointer, *extent);
            claimed.insert(*extent);
        }
    }

    // Adjacency is what is left when there is no name to reason with - libtiff and
    // libarchive declare their parameters unnamed - or when only one pointer is still
    // asking, so there is nothing for it to be confused with. Letting it decide a NAMED
    // signature with two claimants gave lz4's dst the extent of its src.
    let unowned: Vec<usize> = pointers
        .iter()
        .copied()
        .filter(|pointer| !owned.contains_key(pointer))
        .collect();
    let unambiguous = unowned.len() == 1;
    for pointer in unowned {
        if params[pointer].name.is_some() && !unambiguous {
            continue;
        }
        let follower = pointer
            .checked_add(1)
            .filter(|next| extents.contains(next) && !claimed.contains(next));
        let leader = pointer
            .checked_sub(1)
            .filter(|prior| extents.contains(prior) && !claimed.contains(prior));
        if let Some(extent) = follower.or(leader) {
            owned.insert(pointer, extent);
            claimed.insert(extent);
        }
    }

    owned
}

fn buffer_quality(param: &Param) -> u8 {
    match &param.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 &param.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!(
            &param.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!(
        &params[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.extents.clear();
    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 extents = assign_extents(params, &roles);
    for extent in extents.values() {
        roles[*extent] = ParamRole::Length;
    }
    // A writable byte pointer that ended up owning an extent IS the output buffer, whatever
    // it was called. Leaving it graded Context sent it to the handle rule, which has no
    // binding for a byte pointer and could only refuse.
    for pointer in extents.keys() {
        if roles[*pointer] == ParamRole::Context {
            roles[*pointer] = ParamRole::Output;
        }
    }

    // Which buffer the signature is GRADED on is still a single choice, and it is the
    // strongest fuzzable one that knows its own length. png_set_iCCP(const char *name,
    // int type, const png_byte *profile, png_uint_32 proflen) must grade on `profile`.
    let paired = extents
        .keys()
        .copied()
        .filter(|index| roles[*index] == ParamRole::Buffer)
        .max_by_key(|index| buffer_quality(&params[*index]));

    for index in 0..params.len() {
        if roles[index] != ParamRole::Buffer || extents.contains_key(&index) {
            continue;
        }
        if lone_pointer_is_path(&params[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,
        extents,
    }
}

// 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!(
        &param.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 &param.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,
        },
        _ => ParamRole::Config,
    }
}

fn grade(params: &[Param], roles: &[ParamRole], paired: Option<usize>) -> Fuzzability {
    if let Some(index) = paired
        && let Shape::Pointer { pointee, .. } = &params[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)
        && let Shape::Pointer { pointee, .. } = &params[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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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(None), false),
        ];
        let analysis = analyze(&params);
        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(&params);
        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(&params);
        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(&params);
        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(&params);
        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_buffer_flanked_by_two_extents_takes_the_one_that_shares_its_name() {
        let params = [
            integral("encoded_size"),
            pointer("encoded_buffer", Pointee::UnsignedChar, true),
            integral_pointer("decoded_size"),
            pointer("decoded_buffer", Pointee::UnsignedChar, false),
        ];
        let analysis = analyze(&params);
        assert_eq!(
            analysis.extents.get(&1),
            Some(&0),
            "encoded_buffer's extent is encoded_size, not the output's decoded_size"
        );
        assert_eq!(
            analysis.extents.get(&3),
            Some(&2),
            "and decoded_size is the OUTPUT's, which is why taking it was wrong"
        );
        assert_eq!(
            analysis.roles[3],
            ParamRole::Output,
            "a writable byte pointer owning an extent is an output however it is spelled"
        );
    }

    // The control: with no name affinity to go on, the follower still wins. zlib's
    // uncompress(dest, destLen, source, sourceLen) is flanked on both sides too.
    #[test]
    fn a_flanked_buffer_with_no_affinity_either_way_still_takes_its_follower() {
        let params = [
            integral_pointer("outlen"),
            pointer("in", Pointee::UnsignedChar, true),
            integral("n"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.roles[2], ParamRole::Length);
        assert_ne!(analysis.roles[0], ParamRole::Length);
    }

    #[test]
    fn a_pointer_to_a_length_counts_as_the_extent() {
        let params = [
            pointer("src", Pointee::Void, true),
            integral_pointer("srcSize"),
        ];
        let analysis = analyze(&params);
        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(&params);
        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(&params);
        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(&params);
        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",
            &params,
            &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", &params, &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(None), false),
        ];
        assert_eq!(registered_stream(&params).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(&params, &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(&params);
        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(&params, &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"),
        ]
    }

    fn typed_integral(name: Option<&str>, spelling: &str) -> Param {
        Param {
            name: name.map(str::to_owned),
            spelling: spelling.to_owned(),
            shape: Shape::Integral,
        }
    }

    #[test]
    fn a_time_is_not_the_extent_of_the_string_beside_it() {
        let params = [
            typed_integral(Some("now"), "time_t"),
            pointer("datestr", Pointee::Char, true),
        ];
        let analysis = analyze(&params);
        assert_ne!(
            analysis.roles[0],
            ParamRole::Length,
            "archive_parse_date(time_t now, const char *datestr) planned as a decoder"
        );
    }

    // Isolates the type rule from the name rule: `count` passes LENGTH_NAMES, so only the
    // spelling can reject this one. Without it the name rule alone would alibi the type rule.
    #[test]
    fn a_time_typedef_is_not_an_extent_even_when_it_is_named_like_one() {
        let params = [
            typed_integral(Some("count"), "time_t"),
            pointer("datestr", Pointee::Char, true),
        ];
        let analysis = analyze(&params);
        assert_ne!(analysis.roles[0], ParamRole::Length);
    }

    // The other half of the pair: `int` is a perfectly good extent type, so only the name
    // can reject libarchive's archive_match_include_date(struct archive *, int _flag,
    // const char *_datestr), which ranked 4th on the strength of that bogus pairing.
    #[test]
    fn an_integral_not_named_like_an_extent_never_becomes_one() {
        let params = [
            pointer("a", Pointee::Record("archive".to_owned()), false),
            typed_integral(Some("_flag"), "int"),
            pointer("_datestr", Pointee::Char, true),
        ];
        let analysis = analyze(&params);
        assert_ne!(
            analysis.roles[1],
            ParamRole::Length,
            "a flag is not a length"
        );
    }

    // The control that keeps the name rule honest: demanding a length-like NAME must not
    // cost the libraries that ship no parameter names at all.
    #[test]
    fn an_unnamed_integral_beside_a_buffer_is_still_its_extent() {
        let params = [
            Param {
                name: None,
                spelling: "const void *".to_owned(),
                shape: Shape::Pointer {
                    pointee: Pointee::Void,
                    is_const: true,
                },
            },
            typed_integral(None, "size_t"),
        ];
        let analysis = analyze(&params);
        assert_eq!(
            analysis.roles[1],
            ParamRole::Length,
            "libtiff and libarchive declare their parameters unnamed"
        );
        assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);
    }

    #[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(&params);
        assert_eq!(analysis.roles[1], ParamRole::Buffer);
        assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);
    }

    // Isolates the NAME tier. Both other tiers answer this signature and both answer it
    // wrongly: position pairs data with out_size, and adjacency pairs data with the
    // integral that follows it, which is also out_size.
    #[test]
    fn an_extent_belongs_to_the_buffer_it_is_named_after_not_the_one_beside_it() {
        let params = [
            pointer("data", Pointee::UnsignedChar, true),
            integral("out_size"),
            pointer("out", Pointee::UnsignedChar, false),
            integral("data_size"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.extents.get(&0), Some(&3), "data owns data_size");
        assert_eq!(analysis.extents.get(&2), Some(&1), "out owns out_size");
    }

    // Isolates the SHARED-TOKEN arm of the name tier from the prefix arm beside it, which
    // alibied it on the fixture above: neither `dictStart` nor `srcBuffer` is a prefix or a
    // substring of its own extent, so only a shared leading TOKEN can place them. Without
    // it, position zips the two pairs crosswise and both buffers get the other's length.
    // Real lz4: LZ4_decompress_safe_usingDict declares dictStart beside dictSize.
    #[test]
    fn a_shared_leading_token_places_an_extent_that_is_no_prefix_of_its_buffer() {
        let params = [
            pointer("dictStart", Pointee::UnsignedChar, true),
            pointer("srcBuffer", Pointee::UnsignedChar, true),
            integral("srcSize"),
            integral("dictSize"),
        ];
        let analysis = analyze(&params);
        assert_eq!(
            analysis.extents.get(&0),
            Some(&3),
            "dictStart owns dictSize"
        );
        assert_eq!(analysis.extents.get(&1), Some(&2), "srcBuffer owns srcSize");
    }

    // Isolates the POSITION tier: no name here shares anything with any other, so the name
    // tier is silent, and adjacency would hand `dest` the extent of `source`. Real lz4.
    #[test]
    fn two_unrelated_names_pair_by_position_rather_than_by_the_nearest_integral() {
        let params = [
            pointer("source", Pointee::Char, true),
            pointer("dest", Pointee::Char, false),
            integral("isize"),
            integral("maxOutputSize"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.extents.get(&0), Some(&2), "source owns isize");
        assert_eq!(
            analysis.extents.get(&1),
            Some(&3),
            "dest owns maxOutputSize, and taking isize would be the input's extent"
        );
    }

    // Isolates the ADJACENCY tier: libarchive declares these unnamed, so the name tier
    // cannot speak, and two pointers against one extent leaves position nothing to zip.
    #[test]
    fn an_unnamed_buffer_still_takes_the_unnamed_extent_beside_it() {
        let params = [
            pointer("a", Pointee::Record("archive".to_owned()), false),
            Param {
                name: None,
                spelling: "const char *".to_owned(),
                shape: Shape::Pointer {
                    pointee: Pointee::Char,
                    is_const: true,
                },
            },
            Param {
                name: None,
                spelling: "const void *".to_owned(),
                shape: Shape::Pointer {
                    pointee: Pointee::Void,
                    is_const: true,
                },
            },
            typed_integral(None, "size_t"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.extents.get(&2), Some(&3));
        assert_eq!(
            analysis.extents.get(&1),
            None,
            "the command string has none"
        );
    }

    // Isolates the "last one asking" clause of the adjacency tier. `buff` is NAMED, so the
    // unnamed-parameter clause cannot carry it, and two extents against one pointer leaves
    // position nothing to zip. Real libarchive: archive_read_open_memory2.
    #[test]
    fn the_only_buffer_left_asking_takes_the_extent_beside_it_even_when_named() {
        let params = [
            pointer("a", Pointee::Record("archive".to_owned()), false),
            pointer("buff", Pointee::Void, true),
            integral("size"),
            integral("read_size"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.extents.get(&1), Some(&2));
    }

    // The control for that clause. Two NAMED buffers are both still asking and only one
    // integral is on offer, so there is no evidence which of them owns it. lz4's
    // LZ4_decompress_fast is the real case, and `originalSize` is the OUTPUT's extent -
    // handing it to `src` would tell the library the fuzz data is as long as the data it
    // is about to produce.
    #[test]
    fn two_named_buffers_and_one_extent_is_ambiguous_so_neither_takes_it() {
        let params = [
            pointer("src", Pointee::Char, true),
            pointer("dst", Pointee::Char, false),
            integral("originalSize"),
        ];
        let analysis = analyze(&params);
        assert!(
            analysis.extents.is_empty(),
            "guessing here is the fabricated-crash class, got {:?}",
            analysis.extents
        );
    }

    // The whole point of B69: the extent is not adjacent to the buffer it belongs to,
    // because the output buffer sits between them. Real lz4, and every decoder in the
    // library carries this shape.
    #[test]
    fn a_decoder_whose_output_sits_between_its_input_and_its_length_still_pairs() {
        let params = [
            pointer("src", Pointee::Char, true),
            pointer("dst", Pointee::Char, false),
            integral("compressedSize"),
            integral("dstCapacity"),
        ];
        let analysis = analyze(&params);
        assert_eq!(
            analysis.extents.get(&0),
            Some(&2),
            "src owns compressedSize"
        );
        assert_eq!(analysis.extents.get(&1), Some(&3), "dst owns dstCapacity");
        assert_eq!(analysis.roles[2], ParamRole::Length);
        assert_eq!(analysis.roles[3], ParamRole::Length);
    }

    // An opaque handle is byte-sized and writable, so it sits in the same set as the real
    // output buffers. It must never win an extent: promoting it would hand libjpeg-turbo a
    // zeroed allocation where it expects an initialised handle, and the SEGV would be ours.
    // Only the handle rule can decide this fixture - `jpegSize` shares no name with
    // `handle`, and the name tier is what would otherwise place it.
    #[test]
    fn an_opaque_handle_typedef_never_takes_an_extent_and_never_becomes_an_output() {
        let params = [
            Param {
                name: Some("handle".to_owned()),
                spelling: "tjhandle".to_owned(),
                shape: Shape::Pointer {
                    pointee: Pointee::Void,
                    is_const: false,
                },
            },
            integral("jpegSize"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.extents.get(&0), None);
        assert_ne!(analysis.roles[0], ParamRole::Output);
    }

    // A signature may now carry more than one Length, but only the fuzzable one decides
    // how the entry point is graded.
    #[test]
    fn a_second_extent_on_the_output_does_not_regrade_the_entry_point() {
        let params = [
            pointer("src", Pointee::Char, true),
            pointer("dst", Pointee::Char, false),
            integral("compressedSize"),
            integral("dstCapacity"),
        ];
        let analysis = analyze(&params);
        assert_eq!(analysis.fuzzability, Fuzzability::CastBuffer);
        assert_eq!(analysis.roles[0], ParamRole::Buffer);
        assert_eq!(analysis.roles[1], ParamRole::Output);
    }
}