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 👇

26.5 KB
Raw Blame
// ©AngelaMos | 2026
// emit.rs

use std::fmt::Write;

use crate::plan::{
    AUX_CAPACITY, AUX_LOCAL, CALLBACK_BUDGET, CURSOR_LOCAL, CURSOR_STRUCT, CallbackKind,
    CallbackStub, FUZZ_DATA, FUZZ_SIZE, HarnessPlan, Init, MAX_AUX_BYTES, MAX_CALLBACK_CALLS,
    MAX_OUT_BYTES, NUL_COPY_LOCAL, OUT_CAPACITY, OUT_LOCAL, Stmt, Value,
};

pub const CALLBACK_COUNTER: &str = "lisdex_callback_calls";
pub const ENTRY_SYMBOL: &str = "LLVMFuzzerTestOneInput";
pub const SYSTEM_INCLUDES: &[&str] = &["stddef.h", "stdint.h", "stdlib.h", "string.h"];

#[must_use]
pub fn render(plan: &HarnessPlan, filename: &str) -> String {
    let mut out = String::new();
    render_header(&mut out, filename);
    render_includes(&mut out, plan);
    render_support(&mut out, plan);
    render_callbacks(&mut out, plan);
    render_entry(&mut out, plan);
    out
}

fn render_header(out: &mut String, filename: &str) {
    let _ = writeln!(out, "// ©AngelaMos | 2026");
    let _ = writeln!(out, "// {filename}");
    let _ = writeln!(out);
}

fn render_includes(out: &mut String, plan: &HarnessPlan) {
    for header in SYSTEM_INCLUDES {
        let _ = writeln!(out, "#include <{header}>");
    }
    if !plan.includes.is_empty() {
        let _ = writeln!(out);
    }
    for header in &plan.includes {
        let _ = writeln!(out, "#include \"{header}\"");
    }
    let _ = writeln!(out);
}

fn render_support(out: &mut String, plan: &HarnessPlan) {
    if plan.needs_aux_buffer {
        let _ = writeln!(out, "#define {AUX_CAPACITY} {MAX_AUX_BYTES}");
    }
    if plan.needs_out_buffer {
        let _ = writeln!(out, "#define {OUT_CAPACITY} {MAX_OUT_BYTES}");
    }
    if plan.needs_aux_buffer || plan.needs_out_buffer {
        let _ = writeln!(out);
    }
    if !plan.needs_cursor && plan.callbacks.is_empty() {
        return;
    }
    let _ = writeln!(out, "#define {CALLBACK_BUDGET} {MAX_CALLBACK_CALLS}");
    let _ = writeln!(out);
    if plan.needs_cursor {
        let _ = writeln!(out, "typedef struct {{");
        let _ = writeln!(out, "    const uint8_t *data;");
        let _ = writeln!(out, "    size_t size;");
        let _ = writeln!(out, "    size_t offset;");
        let _ = writeln!(out, "}} {CURSOR_STRUCT};");
        let _ = writeln!(out);
        let _ = writeln!(out, "static {CURSOR_STRUCT} {CURSOR_LOCAL};");
    }
    if !plan.callbacks.is_empty() {
        let _ = writeln!(out, "static unsigned {CALLBACK_COUNTER};");
    }
    let _ = writeln!(out);
}

fn render_callbacks(out: &mut String, plan: &HarnessPlan) {
    for stub in &plan.callbacks {
        render_callback(out, stub);
        let _ = writeln!(out);
    }
}

fn signature(stub: &CallbackStub) -> String {
    let params = if stub.params.is_empty() {
        "void".to_owned()
    } else {
        stub.params
            .iter()
            .enumerate()
            .map(|(index, ty)| format!("{ty} a{index}"))
            .collect::<Vec<_>>()
            .join(", ")
    };
    format!("static {} {}({params})", stub.return_ty, stub.name)
}

fn render_callback(out: &mut String, stub: &CallbackStub) {
    let _ = writeln!(out, "{}", signature(stub));
    let _ = writeln!(out, "{{");
    for index in 0..stub.params.len() {
        if !touches(stub, index) {
            let _ = writeln!(out, "    (void)a{index};");
        }
    }
    let _ = writeln!(out, "    if ({CALLBACK_COUNTER} >= {CALLBACK_BUDGET}) {{");
    let _ = writeln!(out, "        {}", bail(stub));
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "    {CALLBACK_COUNTER}++;");
    if let CallbackKind::ReadFromCursor { buffer, count } = stub.kind {
        render_cursor_read(out, buffer, count);
    }
    let _ = writeln!(out, "    {}", bail(stub));
    let _ = writeln!(out, "}}");
}

fn touches(stub: &CallbackStub, index: usize) -> bool {
    match stub.kind {
        CallbackKind::Benign => false,
        CallbackKind::ReadFromCursor { buffer, count } => index == buffer || index == count,
    }
}

fn bail(stub: &CallbackStub) -> String {
    if stub.return_ty.trim() == "void" {
        "return;".to_owned()
    } else {
        "return 0;".to_owned()
    }
}

fn render_cursor_read(out: &mut String, buffer: usize, count: usize) {
    let _ = writeln!(out, "    size_t available = 0;");
    let _ = writeln!(
        out,
        "    if ({CURSOR_LOCAL}.offset < {CURSOR_LOCAL}.size) {{"
    );
    let _ = writeln!(
        out,
        "        available = {CURSOR_LOCAL}.size - {CURSOR_LOCAL}.offset;"
    );
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "    if (available > (size_t)a{count}) {{");
    let _ = writeln!(out, "        available = (size_t)a{count};");
    let _ = writeln!(out, "    }}");
    let _ = writeln!(out, "    if (available > 0 && a{buffer} != NULL) {{");
    let _ = writeln!(
        out,
        "        memcpy(a{buffer}, {CURSOR_LOCAL}.data + {CURSOR_LOCAL}.offset, available);"
    );
    let _ = writeln!(out, "        {CURSOR_LOCAL}.offset += available;");
    let _ = writeln!(out, "    }}");
}

fn render_entry(out: &mut String, plan: &HarnessPlan) {
    let _ = writeln!(
        out,
        "int {ENTRY_SYMBOL}(const uint8_t *{FUZZ_DATA}, size_t {FUZZ_SIZE})"
    );
    let _ = writeln!(out, "{{");
    render_prologue(out, plan);
    for statement in &plan.body {
        render_stmt(out, statement, plan);
    }
    if plan.needs_nul_copy {
        let _ = writeln!(out, "    free({NUL_COPY_LOCAL});");
    }
    if plan.needs_out_buffer {
        let _ = writeln!(out, "    free({OUT_LOCAL});");
    }
    if plan.needs_aux_buffer {
        let _ = writeln!(out, "    free({AUX_LOCAL});");
    }
    let _ = writeln!(out, "    return 0;");
    let _ = writeln!(out, "}}");
}

fn render_prologue(out: &mut String, plan: &HarnessPlan) {
    let mut wrote = false;
    // A char-family buffer handed the raw AFL testcase is not NUL-terminated, and the
    // driver poisons the byte just past `size`. libarchive's date parser read off the
    // end and ASAN blamed libarchive, not the harness.
    if plan.needs_nul_copy {
        let _ = writeln!(
            out,
            "    char *{NUL_COPY_LOCAL} = (char *)malloc({FUZZ_SIZE} + 1);"
        );
        let _ = writeln!(out, "    if ({NUL_COPY_LOCAL} == NULL) {{");
        let _ = writeln!(out, "        return 0;");
        let _ = writeln!(out, "    }}");
        let _ = writeln!(
            out,
            "    memcpy({NUL_COPY_LOCAL}, {FUZZ_DATA}, {FUZZ_SIZE});"
        );
        let _ = writeln!(out, "    {NUL_COPY_LOCAL}[{FUZZ_SIZE}] = '\\0';");
        wrote = true;
    }
    // Heap rather than a stack array so ASAN's redzones bound it exactly: an overrun is
    // reported as a heap-buffer-overflow with the library's own frames on top, instead of
    // smashing the harness frame and being read as a stack exhaustion in a deep parser.
    if plan.needs_out_buffer {
        let _ = writeln!(
            out,
            "    unsigned char *{OUT_LOCAL} = (unsigned char *)malloc({OUT_CAPACITY});"
        );
        let _ = writeln!(out, "    if ({OUT_LOCAL} == NULL) {{");
        if plan.needs_nul_copy {
            let _ = writeln!(out, "        free({NUL_COPY_LOCAL});");
        }
        let _ = writeln!(out, "        return 0;");
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "    memset({OUT_LOCAL}, 0, {OUT_CAPACITY});");
        wrote = true;
    }
    // Zeroed on purpose, not filled from the corpus: lz4's own fuzzer memsets its dictionary
    // and says in a comment that the contents do not matter. Spending corpus bytes here would
    // take them away from the buffer that IS being parsed.
    if plan.needs_aux_buffer {
        let _ = writeln!(
            out,
            "    unsigned char *{AUX_LOCAL} = (unsigned char *)malloc({AUX_CAPACITY});"
        );
        let _ = writeln!(out, "    if ({AUX_LOCAL} == NULL) {{");
        if plan.needs_nul_copy {
            let _ = writeln!(out, "        free({NUL_COPY_LOCAL});");
        }
        if plan.needs_out_buffer {
            let _ = writeln!(out, "        free({OUT_LOCAL});");
        }
        let _ = writeln!(out, "        return 0;");
        let _ = writeln!(out, "    }}");
        let _ = writeln!(out, "    memset({AUX_LOCAL}, 0, {AUX_CAPACITY});");
        wrote = true;
    }
    if plan.needs_cursor {
        let _ = writeln!(out, "    {CURSOR_LOCAL}.data = {FUZZ_DATA};");
        let _ = writeln!(out, "    {CURSOR_LOCAL}.size = {FUZZ_SIZE};");
        let _ = writeln!(out, "    {CURSOR_LOCAL}.offset = 0;");
        wrote = true;
    }
    if !plan.callbacks.is_empty() {
        let _ = writeln!(out, "    {CALLBACK_COUNTER} = 0;");
        wrote = true;
    }
    if wrote {
        let _ = writeln!(out);
    }
}

fn render_stmt(out: &mut String, statement: &Stmt, plan: &HarnessPlan) {
    match statement {
        Stmt::Declare { ty, name, init } => match init {
            Init::Null => {
                let _ = writeln!(out, "    {ty} {name} = NULL;");
            }
            Init::ZeroBytes => {
                let _ = writeln!(out, "    {ty} {name};");
                let _ = writeln!(out, "    memset(&{name}, 0, sizeof {name});");
            }
            Init::Uninitialised => {
                let _ = writeln!(out, "    {ty} {name};");
            }
            Init::Capacity => {
                let _ = writeln!(out, "    {ty} {name} = {OUT_CAPACITY};");
            }
        },
        Stmt::SetField {
            local,
            field,
            value,
        } => {
            let _ = writeln!(out, "    {local}.{field} = {};", render_value(value));
        }
        Stmt::Call {
            function,
            args,
            capture,
        } => {
            let rendered = args.iter().map(render_value).collect::<Vec<_>>().join(", ");
            match capture {
                Some(binding) => {
                    let _ = writeln!(
                        out,
                        "    {} {} = {function}({rendered});",
                        binding.ty, binding.name
                    );
                }
                None => {
                    let _ = writeln!(out, "    {function}({rendered});");
                }
            }
        }
        Stmt::Discard { local } => {
            let _ = writeln!(out, "    (void){local};");
        }
        Stmt::BailIfNull { local } => {
            render_bail(out, &format!("{local} == NULL"), plan);
        }
        Stmt::BailIfZero { local } => {
            render_bail(out, &format!("{local} == 0"), plan);
        }
        Stmt::AllocSized {
            local,
            length,
            size,
            frees,
        } => {
            let _ = writeln!(out, "    size_t {length} = (size_t)({size});");
            // Not allocated at all when the size is zero, which is two separate facts. A
            // zero-byte block is not a smaller version of the same offer - ASAN hands back a
            // valid pointer with no writable byte behind it, so the first thing the library
            // stores lands in a redzone and is reported against the library. And `malloc(0)`
            // is a live allocation LSAN tracks, so bailing past it leaks on every seed whose
            // header failed to parse, which is D15's forged crash arriving through the guard.
            let _ = writeln!(
                out,
                "    unsigned char *{local} = {length} ? (unsigned char *)malloc({length}) : NULL;"
            );
            render_bail_with(out, &format!("{local} == NULL"), plan, frees);
            let _ = writeln!(out, "    memset({local}, 0, {length});");
        }
        Stmt::FreeSized { local } => {
            let _ = writeln!(out, "    free({local});");
        }
    }
}

// A producer that failed bails out of a body the NUL copy was already allocated for, and
// the direct oracle run enforces LeakSanitizer - so a bail that skips the free reports a
// leak in the target on every replay, which is exactly the forged crash D15 warns about.
fn render_bail(out: &mut String, condition: &str, plan: &HarnessPlan) {
    render_bail_with(out, condition, plan, &[]);
}

fn render_bail_with(out: &mut String, condition: &str, plan: &HarnessPlan, extra: &[String]) {
    let _ = writeln!(out, "    if ({condition}) {{");
    if plan.needs_nul_copy {
        let _ = writeln!(out, "        free({NUL_COPY_LOCAL});");
    }
    if plan.needs_out_buffer {
        let _ = writeln!(out, "        free({OUT_LOCAL});");
    }
    if plan.needs_aux_buffer {
        let _ = writeln!(out, "        free({AUX_LOCAL});");
    }
    for local in extra {
        let _ = writeln!(out, "        free({local});");
    }
    let _ = writeln!(out, "        return 0;");
    let _ = writeln!(out, "    }}");
}

fn render_value(value: &Value) -> String {
    match value {
        Value::Data { cast } => match cast {
            Some(ty) => format!("({ty}){FUZZ_DATA}"),
            None => FUZZ_DATA.to_owned(),
        },
        Value::Size => FUZZ_SIZE.to_owned(),
        Value::Null => "NULL".to_owned(),
        Value::Zero => "0".to_owned(),
        Value::Literal(text) | Value::Local(text) | Value::Callback(text) | Value::Stated(text) => {
            text.clone()
        }
        Value::AddressOf(name) => format!("&{name}"),
        Value::AddressOfField { local, field } => format!("&{local}.{field}"),
        Value::Cursor => format!("&{CURSOR_LOCAL}"),
        Value::NulTerminated => NUL_COPY_LOCAL.to_owned(),
        Value::OutBuffer { cast } => match cast {
            Some(ty) => format!("({ty}){OUT_LOCAL}"),
            None => OUT_LOCAL.to_owned(),
        },
        Value::OutCapacity => OUT_CAPACITY.to_owned(),
        Value::AuxBuffer { cast } => match cast {
            Some(ty) => format!("({ty}){AUX_LOCAL}"),
            None => AUX_LOCAL.to_owned(),
        },
        Value::AuxCapacity => AUX_CAPACITY.to_owned(),
        Value::SizedBuffer { local, cast } => match cast {
            Some(ty) => format!("({ty}){local}"),
            None => local.clone(),
        },
    }
}

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

    fn simplified_libpng() -> HarnessPlan {
        HarnessPlan::new("png_image_begin_read_from_memory")
            .with_include("png.h")
            .with(Stmt::Declare {
                ty: "png_image".to_owned(),
                name: "image".to_owned(),
                init: Init::ZeroBytes,
            })
            .with(Stmt::SetField {
                local: "image".to_owned(),
                field: "version".to_owned(),
                value: Value::Literal("PNG_IMAGE_VERSION".to_owned()),
            })
            .with(Stmt::Call {
                function: "png_image_begin_read_from_memory".to_owned(),
                args: vec![
                    Value::AddressOf("image".to_owned()),
                    Value::Data { cast: None },
                    Value::Size,
                ],
                capture: Some(Binding {
                    ty: "int".to_owned(),
                    name: "started".to_owned(),
                }),
            })
            .with(Stmt::BailIfZero {
                local: "started".to_owned(),
            })
    }

    #[test]
    fn every_harness_carries_the_file_header() {
        let source = render(&simplified_libpng(), "libpng_begin_read.c");
        assert!(source.starts_with("// ©AngelaMos | 2026\n// libpng_begin_read.c\n"));
    }

    #[test]
    fn the_entry_point_has_the_libfuzzer_signature() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.contains("int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)"));
    }

    #[test]
    fn library_headers_are_quoted_and_system_headers_are_bracketed() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.contains("#include <stdint.h>"));
        assert!(source.contains("#include \"png.h\""));
    }

    #[test]
    fn a_record_local_is_zeroed_with_memset() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.contains("    png_image image;"));
        assert!(source.contains("    memset(&image, 0, sizeof image);"));
    }

    #[test]
    fn a_typedefd_pointer_is_nulled_not_memset() {
        let plan = HarnessPlan::new("f").with(Stmt::Declare {
            ty: "png_structp".to_owned(),
            name: "png".to_owned(),
            init: Init::Null,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    png_structp png = NULL;"));
        assert!(!source.contains("memset(&png"));
    }

    #[test]
    fn an_uninitialised_local_gets_no_initialiser() {
        let plan = HarnessPlan::new("f").with(Stmt::Declare {
            ty: "int".to_owned(),
            name: "rc".to_owned(),
            init: Init::Uninitialised,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    int rc;"));
        assert!(!source.contains("memset(&rc"));
        assert!(!source.contains("rc = NULL"));
    }

    #[test]
    fn a_macro_valued_field_is_emitted_verbatim() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.contains("    image.version = PNG_IMAGE_VERSION;"));
    }

    #[test]
    fn a_captured_call_declares_its_binding() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(
            source.contains(
                "    int started = png_image_begin_read_from_memory(&image, data, size);"
            )
        );
    }

    #[test]
    fn a_zero_return_bails_out() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.contains("    if (started == 0) {\n        return 0;\n    }"));
    }

    #[test]
    fn a_plan_without_callbacks_emits_no_cursor_machinery() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(!source.contains(CURSOR_STRUCT));
        assert!(!source.contains(CALLBACK_COUNTER));
    }

    #[test]
    fn a_teardown_call_takes_the_address_of_a_field() {
        let plan = HarnessPlan::new("f").with(Stmt::Call {
            function: "WebPFreeDecBuffer".to_owned(),
            args: vec![Value::AddressOfField {
                local: "ctx".to_owned(),
                field: "output".to_owned(),
            }],
            capture: None,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    WebPFreeDecBuffer(&ctx.output);"));
    }

    #[test]
    fn a_cast_buffer_argument_is_cast() {
        let plan = HarnessPlan::new("f").with(Stmt::Call {
            function: "decode".to_owned(),
            args: vec![
                Value::Data {
                    cast: Some("const char *".to_owned()),
                },
                Value::Size,
            ],
            capture: None,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    decode((const char *)data, size);"));
    }

    fn libpng_read_callback() -> HarnessPlan {
        HarnessPlan::new("png_read_info")
            .with_include("png.h")
            .with_callback(CallbackStub {
                name: "lisdex_read".to_owned(),
                return_ty: "void".to_owned(),
                params: vec![
                    "png_structp".to_owned(),
                    "png_bytep".to_owned(),
                    "size_t".to_owned(),
                ],
                kind: CallbackKind::ReadFromCursor {
                    buffer: 1,
                    count: 2,
                },
            })
            .with(Stmt::Call {
                function: "png_set_read_fn".to_owned(),
                args: vec![
                    Value::Local("png".to_owned()),
                    Value::Cursor,
                    Value::Callback("lisdex_read".to_owned()),
                ],
                capture: None,
            })
    }

    #[test]
    fn a_read_callback_emits_the_cursor_type_and_a_static_instance() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains("typedef struct {"));
        assert!(source.contains(&format!("static {CURSOR_STRUCT} {CURSOR_LOCAL};")));
    }

    #[test]
    fn the_cursor_is_reset_on_every_input() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains(&format!("    {CURSOR_LOCAL}.data = data;")));
        assert!(source.contains(&format!("    {CURSOR_LOCAL}.offset = 0;")));
    }

    #[test]
    fn the_callback_counter_is_reset_on_every_input() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains(&format!("    {CALLBACK_COUNTER} = 0;")));
    }

    #[test]
    fn a_read_callback_serves_bytes_and_never_overruns_the_cursor() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains("if (available > (size_t)a2)"));
        assert!(source.contains(&format!(
            "memcpy(a1, {CURSOR_LOCAL}.data + {CURSOR_LOCAL}.offset, available);"
        )));
    }

    #[test]
    fn a_read_callback_is_bounded_and_returns_rather_than_exiting() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains(&format!("if ({CALLBACK_COUNTER} >= {CALLBACK_BUDGET})")));
        assert!(!source.contains("exit(0)"));
    }

    #[test]
    fn a_benign_callback_returns_a_value_for_a_non_void_return() {
        let plan = HarnessPlan::new("f").with_callback(CallbackStub {
            name: "cb".to_owned(),
            return_ty: "int".to_owned(),
            params: vec!["void *".to_owned()],
            kind: CallbackKind::Benign,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("static int cb(void * a0)"));
        assert!(source.contains("    return 0;"));
        assert!(!source.contains("exit(0)"));
    }

    #[test]
    fn unused_callback_parameters_are_voided_to_keep_the_compile_quiet() {
        let plan = HarnessPlan::new("f").with_callback(CallbackStub {
            name: "cb".to_owned(),
            return_ty: "void".to_owned(),
            params: vec!["int".to_owned(), "int".to_owned()],
            kind: CallbackKind::Benign,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    (void)a0;"));
        assert!(source.contains("    (void)a1;"));
    }

    #[test]
    fn a_read_callback_does_not_void_the_parameters_it_uses() {
        let source = render(&libpng_read_callback(), "x.c");
        assert!(source.contains("    (void)a0;"));
        assert!(!source.contains("    (void)a1;"));
        assert!(!source.contains("    (void)a2;"));
    }

    #[test]
    fn a_callback_with_no_parameters_takes_void() {
        let plan = HarnessPlan::new("f").with_callback(CallbackStub {
            name: "cb".to_owned(),
            return_ty: "void".to_owned(),
            params: Vec::new(),
            kind: CallbackKind::Benign,
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("static void cb(void)"));
    }

    #[test]
    fn a_null_check_bails_out() {
        let plan = HarnessPlan::new("f").with(Stmt::BailIfNull {
            local: "png".to_owned(),
        });
        let source = render(&plan, "x.c");
        assert!(source.contains("    if (png == NULL) {\n        return 0;\n    }"));
    }

    #[test]
    fn a_bail_frees_the_nul_copy_it_was_allocated_after() {
        let plan = HarnessPlan::new("f")
            .with(Stmt::Call {
                function: "archive_entry_new".to_owned(),
                args: vec![Value::NulTerminated],
                capture: Some(Binding {
                    ty: "struct archive_entry *".to_owned(),
                    name: "ctx".to_owned(),
                }),
            })
            .with(Stmt::BailIfNull {
                local: "ctx".to_owned(),
            });
        let source = render(&plan, "x.c");
        assert!(
            source.contains(
                "    if (ctx == NULL) {\n        free(lisdex_text);\n        return 0;\n    }"
            ),
            "the direct oracle run enforces LeakSanitizer, so a bail that skips the free forges a leak inside the target: {source}"
        );
    }

    #[test]
    fn a_bail_with_no_nul_copy_frees_nothing() {
        let plan = HarnessPlan::new("f").with(Stmt::BailIfNull {
            local: "ctx".to_owned(),
        });
        let source = render(&plan, "x.c");
        assert!(!source.contains("free("));
    }

    fn using_dict() -> HarnessPlan {
        HarnessPlan::new("LZ4_decompress_safe_usingDict").with(Stmt::Call {
            function: "LZ4_decompress_safe_usingDict".to_owned(),
            args: vec![
                Value::NulTerminated,
                Value::OutBuffer { cast: None },
                Value::Size,
                Value::OutCapacity,
                Value::AuxBuffer {
                    cast: Some("const char *".to_owned()),
                },
                Value::AuxCapacity,
            ],
            capture: None,
        })
    }

    // Zeroed rather than filled from the corpus, which is what lz4's own fuzzer does to its
    // dictionary, and sized at the authors' own `64 * 1024 - 1` boundary.
    #[test]
    fn the_auxiliary_buffer_is_allocated_zeroed_and_distinct_from_the_corpus() {
        let source = render(&using_dict(), "x.c");
        assert!(
            source.contains("#define LISDEX_AUX_CAPACITY 65535"),
            "{source}"
        );
        assert!(
            source.contains(
                "unsigned char *lisdex_aux = (unsigned char *)malloc(LISDEX_AUX_CAPACITY);"
            ),
            "{source}"
        );
        assert!(
            source.contains("memset(lisdex_aux, 0, LISDEX_AUX_CAPACITY);"),
            "{source}"
        );
        assert!(
            source.contains("(const char *)lisdex_aux, LISDEX_AUX_CAPACITY)"),
            "the dictionary must be its own memory, not a second copy of lisdex_text: {source}"
        );
    }

    // LSAN runs on the direct oracle pass, so an auxiliary allocation that outlives any exit
    // reports a leak attributed to the library - the forged crash D15 warns about.
    #[test]
    fn every_exit_frees_the_auxiliary_buffer() {
        let plan = using_dict().with(Stmt::BailIfNull {
            local: "ctx".to_owned(),
        });
        let source = render(&plan, "x.c");
        assert_eq!(
            source.matches("free(lisdex_aux);").count(),
            2,
            "once on the bail path and once at the end: {source}"
        );
        assert!(
            source.contains(
                "    if (lisdex_aux == NULL) {\n        free(lisdex_text);\n        free(lisdex_out);\n        return 0;\n    }"
            ),
            "its own failed allocation must free the two before it: {source}"
        );
    }

    #[test]
    fn the_body_ends_by_returning_zero() {
        let source = render(&simplified_libpng(), "x.c");
        assert!(source.trim_end().ends_with("    return 0;\n}"));
    }
}