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 👇

29.2 KB
Raw Blame
// ©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 CONSUMER_POINT: &str = "main";
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()))
}

// `Copyright (C) 2009 ...` in a licence header mines as a call to `Copyright`, and every
// libjpeg-turbo target carried `Copyright`, `DAMAGES` and `TORT` in its call list. That is
// not merely noise in the length and frequency keys: a comment naming a real function would
// have made it "authored", and authorship is what decides the floor.
//
// Stripping only comments left the identical defect alive in its other form. zlib's
// `examples/gun.c` writes `fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n")`, and the
// text INSIDE that string literal mines as a call to `Copyright` exactly as the licence
// header did - it is the fourth entry in the sequence the ladder chose for zlib. A usage or
// error string naming a real library function is the case that matters, because it would be
// replayed as setup. A literal cannot span a raw newline, so an unterminated quote stops at
// the end of its line rather than eating the rest of the file.
fn without_comments_or_literals(body: &str) -> String {
    let chars: Vec<char> = body.chars().collect();
    let mut kept = String::with_capacity(body.len());
    let mut index = 0;
    while index < chars.len() {
        let pair = (chars[index], chars.get(index + 1).copied());
        match pair {
            ('/', Some('*')) => {
                index += 2;
                while index < chars.len()
                    && !(chars[index] == '*' && chars.get(index + 1) == Some(&'/'))
                {
                    index += 1;
                }
                index = (index + 2).min(chars.len());
                kept.push(' ');
            }
            ('/', Some('/')) => {
                while index < chars.len() && chars[index] != '\n' {
                    index += 1;
                }
            }
            ('"' | '\'', _) => {
                let quote = chars[index];
                index += 1;
                while index < chars.len() && chars[index] != quote && chars[index] != '\n' {
                    index += if chars[index] == '\\' { 2 } else { 1 };
                }
                if chars.get(index) == Some(&quote) {
                    index += 1;
                }
                kept.push(' ');
            }
            _ => {
                kept.push(chars[index]);
                index += 1;
            }
        }
    }
    kept
}

// `#if 0` around a block of real calls is how a C author comments out code that still has to
// compile if switched back on, and openjpeg's own J2K fuzzer carries one. The identifiers inside
// it are not calls this program makes. A directive LINE never contributes a call either: the
// body of `#define WRAP(x) inner_call(x)` yielded both `WRAP` and `inner_call`, neither of which
// anything called.
fn is_always_false(rest: &str) -> bool {
    matches!(rest.trim(), "0" | "false")
}

fn directive_word(directive: &str) -> &str {
    directive
        .split(|character: char| !character.is_alphanumeric() && character != '_')
        .next()
        .unwrap_or("")
}

fn without_inactive_preprocessor(body: &str) -> String {
    let mut kept = String::with_capacity(body.len());
    let mut lines = body.lines();
    let mut depth = 0usize;
    let mut skipping: Option<usize> = None;

    while let Some(line) = lines.next() {
        // A directive continued with a trailing backslash is one logical line, so a multi-line
        // `#define` does not leak its tail into the kept text.
        let mut logical = line.to_owned();
        while logical.trim_end().ends_with('\\') {
            let Some(next) = lines.next() else { break };
            let trimmed = logical.trim_end();
            logical = format!("{} {next}", &trimmed[..trimmed.len() - 1]);
        }

        if let Some(directive) = logical.trim_start().strip_prefix('#') {
            let directive = directive.trim_start();
            let word = directive_word(directive);
            match word {
                "if" | "ifdef" | "ifndef" => {
                    depth += 1;
                    if skipping.is_none()
                        && word == "if"
                        && is_always_false(&directive[word.len()..])
                    {
                        skipping = Some(depth);
                    }
                }
                "elif" | "else" => {
                    if skipping == Some(depth) {
                        skipping = None;
                    }
                }
                "endif" => {
                    if skipping == Some(depth) {
                        skipping = None;
                    }
                    depth = depth.saturating_sub(1);
                }
                _ => {}
            }
            kept.push('\n');
            continue;
        }

        if skipping.is_some() {
            kept.push('\n');
            continue;
        }
        kept.push_str(&logical);
        kept.push('\n');
    }

    kept
}

// What separates `png_read_info(p, i)` from `int png_read_info(png_structp, png_infop);` is the
// token in front of it: a declarator is introduced by its return type, a call never is. The
// keyword list is what keeps `return foo(x)` and `case FOO: bar(x)` on the call side, and the
// `*` hop is what puts `void *lisdex_malloc(...)` on the declarator side.
//
// A DEFINITION is deliberately NOT filtered, and the distinction is load-bearing rather than
// pedantic: `defines_a_program` decides a file is a consumer by finding `main` call-shaped, so
// suppressing every declarator took `main` with it and emptied the ladder's whole consumer tier
// - three ladder tests and the program-detection test went red together. Only the form that
// ends in `;` is a declaration; the form that ends in `{` is the author writing the function.
fn is_declaration(chars: &[char], start: usize, open: usize) -> bool {
    is_declarator(chars, start) && closes_into_semicolon(chars, open)
}

fn closes_into_semicolon(chars: &[char], open: usize) -> bool {
    let mut depth = 0usize;
    let mut index = open;
    while index < chars.len() {
        match chars[index] {
            '(' => depth += 1,
            ')' => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            _ => {}
        }
        index += 1;
    }
    index += 1;
    while index < chars.len() && chars[index].is_whitespace() {
        index += 1;
    }
    chars.get(index) == Some(&';')
}

fn is_declarator(chars: &[char], start: usize) -> bool {
    let mut index = start;
    let mut hopped_star = false;
    loop {
        while index > 0 && chars[index - 1].is_whitespace() {
            index -= 1;
        }
        if index > 0 && chars[index - 1] == '*' && !hopped_star {
            index -= 1;
            hopped_star = true;
            continue;
        }
        break;
    }
    if index == 0 {
        return false;
    }
    let end = index;
    while index > 0 && (chars[index - 1].is_alphanumeric() || chars[index - 1] == '_') {
        index -= 1;
    }
    if index == end {
        return false;
    }
    let preceding: String = chars[index..end].iter().collect();
    !NOT_CALLS.contains(&preceding.as_str())
}

// Whole-FILE order is only the author's call order when the file holds one function. zlib's
// `test/infcover.c` defines twenty, so first-occurrence order over the file put `inflate`
// at position 25 and `inflateInit` nowhere before it - the setup replay therefore found
// nothing to replay for the one library D23 says needs it most. The order that means
// something is the order inside the entry function's own body.
#[must_use]
pub fn body_of(source: &str, function: &str) -> Option<String> {
    let chars: Vec<char> = source.chars().collect();
    let name: Vec<char> = function.chars().collect();
    let mut index = 0;
    while let Some(start) = find_identifier(&chars, &name, index) {
        index = start + name.len();
        let mut cursor = skip_space(&chars, index);
        if chars.get(cursor) != Some(&'(') {
            continue;
        }
        let mut depth = 0;
        while cursor < chars.len() {
            match chars[cursor] {
                '(' => depth += 1,
                ')' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                _ => {}
            }
            cursor += 1;
        }
        cursor = skip_space(&chars, cursor + 1);
        if chars.get(cursor) != Some(&'{') {
            continue;
        }
        let open = cursor;
        let mut braces = 0;
        while cursor < chars.len() {
            match chars[cursor] {
                '{' => braces += 1,
                '}' => {
                    braces -= 1;
                    if braces == 0 {
                        return Some(chars[open..=cursor].iter().collect());
                    }
                }
                _ => {}
            }
            cursor += 1;
        }
    }
    None
}

fn skip_space(chars: &[char], mut index: usize) -> usize {
    while index < chars.len() && chars[index].is_whitespace() {
        index += 1;
    }
    index
}

fn find_identifier(chars: &[char], name: &[char], from: usize) -> Option<usize> {
    let boundary = |position: usize| -> bool {
        chars
            .get(position)
            .is_none_or(|character| !(character.is_alphanumeric() || *character == '_'))
    };
    (from..chars.len().saturating_sub(name.len().saturating_sub(1))).find(|start| {
        chars[*start..].starts_with(name)
            && (*start == 0 || boundary(start - 1))
            && boundary(start + name.len())
    })
}

// Source order IS the finding. A `BTreeSet` here alphabetised the calls, which silently
// turned every mined harness into a reachability SET - and the set is the one thing headers
// already give you. libarchive's own harness says
// `archive_read_new` -> `archive_read_support_filter_all` -> `archive_read_support_format_all`
// -> `archive_read_open_memory`, and the middle two are exactly what our synthesized version
// omits to earn `ARCHIVE_FATAL` at full exec rate. Alphabetising loses which call must come
// first. Dedup on FIRST occurrence, because that is where the author established the order.
#[must_use]
pub fn extract_calls(body: &str) -> Vec<String> {
    let body = without_inactive_preprocessor(&without_comments_or_literals(body));
    let chars: Vec<char> = body.chars().collect();
    let mut seen = BTreeSet::new();
    let mut found = Vec::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
            && !is_declaration(&chars, start, lookahead)
            && seen.insert(identifier.clone())
        {
            found.push(identifier);
        }
    }

    found
}

// `body.contains("main")` would take every file that mentions a domain, a remainder or a
// mainline. The mined call list is already an exact-identifier scan, so the cheapest honest
// test for "this file defines a program" is that `main` appears in it AS a call-shaped
// identifier, which is what a definition and nothing else in prose looks like.
fn defines_a_program(body: &str) -> bool {
    extract_calls(body)
        .iter()
        .any(|call| call == CONSUMER_POINT)
}

fn defines_a_fuzz_target(body: &str) -> bool {
    body.contains(ENTRY_POINT)
}

fn walk_for(
    root: &Path,
    marks: fn(&str) -> bool,
    scope: &str,
    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_for(&path, marks, scope, depth + 1, found)?;
            }
            continue;
        }
        if !is_source(&path) {
            continue;
        }
        let oversized = entry
            .metadata()
            .map_or(true, |meta| meta.len() > MAX_SOURCE_BYTES);
        if oversized {
            continue;
        }
        let Ok(body) = std::fs::read_to_string(&path) else {
            continue;
        };
        if marks(&body) {
            // The entry function's body when it has one; the whole file otherwise, because
            // a target whose entry is behind a macro still carries a usable call list.
            let mined = body_of(&body, scope).unwrap_or(body);
            found.push(Harness {
                path,
                calls: extract_calls(&mined),
            });
        }
    }
    Ok(())
}

fn discover_marked(
    source: &Path,
    marks: fn(&str) -> bool,
    entry: &str,
) -> Result<Vec<Harness>, HarnessError> {
    if !source.is_dir() {
        return Err(HarnessError::NotADirectory(source.to_path_buf()));
    }
    let mut found = Vec::new();
    walk_for(source, marks, entry, 0, &mut found)?;
    found.sort_by(|left, right| left.path.cmp(&right.path));
    Ok(found)
}

pub fn discover(source: &Path) -> Result<Vec<Harness>, HarnessError> {
    discover_marked(source, defines_a_fuzz_target, ENTRY_POINT)
}

// A library that ships no fuzz harness is not a library with no call-order signal, which is
// what doc 02 D10 claimed and D18 refuted by measurement: zlib ships zero harnesses and
// nineteen `main()` consumers, six of which run inflateInit -> inflate in sequence.
pub fn discover_consumers(source: &Path) -> Result<Vec<Harness>, HarnessError> {
    let found = discover_marked(source, defines_a_program, CONSUMER_POINT)?;
    Ok(found
        .into_iter()
        .filter(|item| !item.calls.is_empty())
        .collect())
}

// The isolating control for the ordering above: this fixture is written so that source order
// and alphabetical order DISAGREE. A `BTreeSet` extraction returns archive_read_data first;
// the author's actual sequence starts at archive_read_new. Any assertion using only
// `contains()` passes under both and is therefore an alibi, not a control.
#[cfg(test)]
mod order_tests {
    use super::extract_calls;

    #[test]
    fn mined_calls_keep_the_authors_order_rather_than_the_alphabets() {
        let body = "
            int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) {
                struct archive *a = archive_read_new();
                archive_read_support_filter_all(a);
                archive_read_support_format_all(a);
                archive_read_open_memory(a, d, n);
                archive_read_next_header(a, &e);
                archive_read_data(a, buf, sizeof(buf));
                archive_read_free(a);
            }
        ";
        let calls = extract_calls(body);
        assert_eq!(
            calls,
            vec![
                "archive_read_new",
                "archive_read_support_filter_all",
                "archive_read_support_format_all",
                "archive_read_open_memory",
                "archive_read_next_header",
                "archive_read_data",
                "archive_read_free",
            ],
            "alphabetical order would lead with archive_read_data"
        );
    }

    // zlib's `examples/gun.c` is the tree this was measured on: `Copyright` was mined as the
    // fourth call in the sequence the ladder chose, out of the text of an fprintf argument.
    // The fixture names a REAL library function inside the literal, because that is the case
    // that costs something - an unreal name is only noise in the length key, but a real one
    // is replayed as setup and votes on the direction verdict.
    #[test]
    fn a_function_name_inside_a_string_literal_is_not_a_call() {
        let calls = extract_calls(
            r#"
            int main(void) {
                fprintf(stderr, "Copyright (C) 2003-2010 Mark Adler\n");
                fputs("usage: inflateInit(strm) then inflate(strm)\n", stderr);
                inflateEnd(&strm);
            }
        "#,
        );
        assert_eq!(
            calls,
            vec!["main", "fprintf", "fputs", "inflateEnd"],
            "Copyright, inflateInit and inflate are all text, not calls"
        );
    }

    // Isolates the literal strip from the comment strip: an escaped quote must not end the
    // literal early, or the tail of the string leaks back in as callable text.
    #[test]
    fn an_escaped_quote_does_not_end_the_literal_early() {
        let calls = extract_calls(r#"void f(void) { puts("a \" inflate(x) b"); }"#);
        assert_eq!(calls, vec!["f", "puts"]);
    }

    #[test]
    fn a_call_repeated_later_keeps_only_its_first_position() {
        let calls = extract_calls("zulu(); alpha(); zulu();");
        assert_eq!(calls, vec!["zulu", "alpha"]);
    }

    // Isolates comment stripping. Every libjpeg-turbo target mined `Copyright`, `DAMAGES`
    // and `TORT` from its licence header. The danger is not the noise: a comment naming a
    // real function would have made that function "authored", and authorship decides which
    // candidates the synthesizer is allowed to fall through to.
    #[test]
    fn a_function_named_in_a_comment_was_never_called() {
        let calls = super::extract_calls(
            "/* Copyright (C) 2009. Do not call png_init_io(fp) here. */\n\
             // see also png_read_png(p)\n\
             png_read_info(p, i);",
        );
        assert_eq!(calls, vec!["png_read_info"], "{calls:?}");
    }

    // B36. openjpeg's own J2K fuzzer parks a tile-size check behind `#if 0`, and both calls in
    // it were mined into the sequence the ladder chose - `opj_get_cstr_info` and
    // `opj_destroy_cstr_info`, neither of which that program ever makes.
    #[test]
    fn a_call_inside_an_if_zero_block_is_not_a_call_this_program_makes() {
        let calls = super::extract_calls("#if 0\n  dead_call(x);\n#endif\n  live_call(y);");
        assert_eq!(calls, vec!["live_call"], "{calls:?}");
    }

    // The nesting has to be tracked or the FIRST `#endif` reopens mining inside a block that is
    // still switched off.
    #[test]
    fn a_nested_directive_does_not_reopen_the_disabled_block_early() {
        let calls = super::extract_calls(
            "#if 0\n#ifdef SOMETHING\n  dead_call(x);\n#endif\n  also_dead(y);\n#endif\n  live_call(z);",
        );
        assert_eq!(calls, vec!["live_call"], "{calls:?}");
    }

    // libpng's `example.c` opens with `#if 0 /* in case someone actually tries to compile this */`
    // and wraps the whole file, so its `main` made a documentation file libpng says must not
    // compile into the 28th consumer of the tree. The trailing comment is why the directive is
    // read AFTER comments are stripped rather than before.
    #[test]
    fn a_disabled_block_is_recognised_with_a_comment_on_the_directive() {
        let calls = super::extract_calls(
            "#if 0 /* in case someone actually tries to compile this */\nint main(int c) { png_read_png(p); }\n#endif\n",
        );
        assert!(calls.is_empty(), "{calls:?}");
    }

    // A directive LINE is never a call site either: the macro's own name and its body both
    // mined, so `#define WRAP(x) inner_call(x)` produced two calls nothing made.
    #[test]
    fn a_macro_definition_contributes_neither_its_name_nor_its_body() {
        let calls = super::extract_calls("#define WRAP(x) inner_call(x)\n  live_call(y);");
        assert_eq!(calls, vec!["live_call"], "{calls:?}");
    }

    #[test]
    fn a_multi_line_macro_definition_does_not_leak_its_tail() {
        let calls = super::extract_calls(
            "#define WRAP(x) \\\n    inner_call(x); \\\n    second_call(x)\n  live_call(y);",
        );
        assert_eq!(calls, vec!["live_call"], "{calls:?}");
    }

    // A prototype is the author saying the function EXISTS, not that this program calls it.
    // Mined as a call it makes the function "reached", and a reached function is suppressed as
    // a target, so a declaration demotes the very entry point it names.
    #[test]
    fn a_prototype_is_not_a_call_but_a_definition_still_is() {
        let calls = super::extract_calls("int declared_only(void);\n  live_call(y);");
        assert_eq!(calls, vec!["live_call"], "{calls:?}");

        // The other half, and it is load-bearing: `defines_a_program` finds a consumer by
        // seeing `main` call-shaped, so filtering every declarator would empty the ladder's
        // consumer tier. Only the form ending in `;` is a declaration.
        let defined = super::extract_calls("int main(int argc, char **argv)\n{\n  work(argc);\n}");
        assert_eq!(defined, vec!["main", "work"], "{defined:?}");
    }

    // libpng's `contrib/pngminus/png2pnm.c` does both, in that order, and it must stay a
    // consumer.
    #[test]
    fn a_file_that_declares_and_then_defines_main_is_still_a_program() {
        let source = "int main (int argc, char *argv[]);\n\nint main (int argc, char *argv[])\n{\n  png2pnm(argc);\n}";
        assert!(
            super::defines_a_program(source),
            "{:?}",
            super::extract_calls(source)
        );
    }

    // Isolates body scoping. zlib's `test/infcover.c` defines twenty functions, so
    // first-occurrence order over the FILE put `inflate` at position 25 with `inflateInit`
    // nowhere before it, and the setup replay found nothing to replay. The fixture keeps
    // that shape: file order and entry-body order disagree about what comes first.
    #[test]
    fn the_order_mined_is_the_entry_functions_own_not_the_files() {
        let source = "\
static void helper(void) { inflateReset(&s); }
int LLVMFuzzerTestOneInput(const uint8_t *d, size_t n) {
  inflateInit(&s);
  inflate(&s, 0);
  return 0;
}
static void later(void) { inflateEnd(&s); }
";
        let body = super::body_of(source, super::ENTRY_POINT).expect("the entry has a body");
        assert_eq!(super::extract_calls(&body), vec!["inflateInit", "inflate"]);
        assert_eq!(
            super::extract_calls(source).first().map(String::as_str),
            Some("helper"),
            "whole-file order leads with a function defined above the entry point"
        );
    }

    #[test]
    fn a_declaration_is_not_a_body_and_a_missing_function_has_none() {
        assert!(
            super::body_of(
                "int LLVMFuzzerTestOneInput(const uint8_t*, size_t);",
                super::ENTRY_POINT
            )
            .is_none()
        );
        assert!(super::body_of("int main(void) { return 0; }", super::ENTRY_POINT).is_none());
    }

    #[test]
    fn a_program_is_found_by_its_definition_and_not_by_the_word_domain() {
        assert!(super::defines_a_program(
            "int main(void) { work(); return 0; }"
        ));
        assert!(!super::defines_a_program(
            "const char *domain(void);\nstatic int remaining;\n"
        ));
    }
}

#[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 = lisdex_core::scratch::path(&format!("surface-harness-{label}"));
        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());
    }
}