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 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
// ©AngelaMos | 2026
// synth.rs
use std::collections::{BTreeMap, BTreeSet};
use lisdex_surface::extract::{Vocabulary, carries_word, identifier_words};
use lisdex_surface::naming::polarity_of;
use lisdex_surface::rank::Candidate;
use lisdex_surface::signature;
use lisdex_surface::signature::{
Analysis, Fuzzability, Param, ParamRole, Pointee, Prototype, Shape, handle_key,
};
use crate::plan::{
Binding, CallbackKind, CallbackStub, FILLED_LOCAL, HarnessPlan, Init, OUT_LEN_LOCAL,
SIZED_LEN_SUFFIX, SIZED_LOCAL, Stmt, Value,
};
pub const CALLBACK_STUB_PREFIX: &str = "lisdex_cb";
pub const BYTE_SINK_SPELLINGS: [&str; 4] = ["void *", "char *", "unsigned char *", "signed char *"];
pub const COUNT_SPELLINGS: [&str; 6] = ["int", "long", "unsigned", "size_t", "ssize_t", "short"];
pub const CONTEXT_LOCAL: &str = "ctx";
pub const RESULT_LOCAL: &str = "rc";
pub const MAX_POPULATED_FIELDS: usize = 4;
pub const MAX_PLAN_VARIANTS: usize = 16;
pub const MAX_UPWARD_STEPS: usize = 4;
pub const EXTENT_WORDS: [&str; 15] = [
"size", "sz", "len", "length", "count", "capacity", "cap", "num", "nbytes", "bytes", "max",
"limit", "n", "buflen", "bufsize",
];
pub const FILESYSTEM_VERBS: [&str; 12] = [
"open", "fopen", "unlink", "remove", "rename", "mkdir", "rmdir", "chdir", "chmod", "symlink",
"truncate", "creat",
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Refusal {
NoDataInput,
CorpusNeverBound,
UnsizedOutParam { param: String },
IndirectExtent { param: String },
OpaqueContext { record: String },
UnboundExtent { param: String },
NeedsCallback { param: String },
PathEntry,
UnsizedTextParam { param: String },
FilesystemVerb { verb: String },
UnsupportedShape { param: String },
NoProducer { handle: String },
ProducerNeedsConstant { producer: String, param: String },
UnreleasedReturn { ty: String },
}
impl std::fmt::Display for Refusal {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Refusal::NoDataInput => write!(formatter, "consumes no fuzzable input"),
Refusal::CorpusNeverBound => write!(
formatter,
"the assembled harness never passes the corpus to the library, so every seed drives the same code and any crash it reports is one the harness manufactured"
),
Refusal::UnsizedOutParam { param } => write!(
formatter,
"out-param {param} needs a caller-supplied extent that headers cannot give; guessing it fabricates a crash inside the library"
),
Refusal::IndirectExtent { param } => write!(
formatter,
"extent {param} is passed by address, so the library may rewrite the length of a buffer it does not own"
),
Refusal::OpaqueContext { record } => write!(
formatter,
"context {record} is opaque and needs a producer chain"
),
Refusal::UnboundExtent { param } => write!(
formatter,
"config {param} is an extent that no buffer in this signature claims; guessing it fabricates a crash inside the library"
),
Refusal::NeedsCallback { param } => {
write!(formatter, "parameter {param} needs a synthesized callback")
}
Refusal::PathEntry => write!(formatter, "takes a filesystem path"),
Refusal::UnsizedTextParam { param } => write!(
formatter,
"char parameter {param} has no length beside it, so it is a string rather than a byte buffer; handing it fuzz bytes has already made a target open and truncate files named by the corpus"
),
Refusal::FilesystemVerb { verb } => write!(
formatter,
"the entry point is named for a filesystem operation ({verb}), so an argument it receives may be taken as a path"
),
Refusal::UnsupportedShape { param } => {
write!(formatter, "parameter {param} has no binding rule")
}
Refusal::NoProducer { handle } => write!(
formatter,
"handle {handle} has no producer this harness can call: nothing in the public headers returns one without opening a file or being handed one first"
),
Refusal::ProducerNeedsConstant { producer, param } => write!(
formatter,
"producer {producer} needs an integer {param} that the headers cannot supply; feeding it one hands the library a mode the caller picks in production"
),
Refusal::UnreleasedReturn { ty } => write!(
formatter,
"the entry point returns {ty}, memory the library allocated and nothing here can release; leaving it unfreed makes LeakSanitizer report a leak inside the library on every seed, which is a crash this harness manufactured"
),
}
}
}
fn shared_leading_tokens(left: &str, right: &str) -> usize {
left.split('_')
.zip(right.split('_'))
.take_while(|(one, other)| one == other)
.count()
}
fn shared_leading_words(left: &str, right: &str) -> usize {
identifier_words(left)
.iter()
.zip(identifier_words(right).iter())
.take_while(|(one, other)| one.eq_ignore_ascii_case(other))
.count()
}
#[must_use]
pub fn is_extent_name(name: &str) -> bool {
carries_word(name, &EXTENT_WORDS)
}
fn producer_arguments(producer: &str, params: &[Param]) -> Result<Vec<Value>, Refusal> {
params
.iter()
.map(|param| {
let label = param.name.clone().unwrap_or_else(|| param.spelling.clone());
match ¶m.shape {
Shape::Pointer { .. } => Ok(Value::Null),
// An integer a constructor takes is a MODE, not data: tj3Init's initType
// selects compress versus decompress and inflateInit_'s stream_size is a
// sizeof. Guessing one hands the library a value the caller owns in
// production, which is the fabricated-crash class, so it is refused here
// and satisfied by a macro variant only where affinity names the macro.
_ => Err(Refusal::ProducerNeedsConstant {
producer: producer.to_owned(),
param: label,
}),
}
})
.collect()
}
type Rank<'a> = ((bool, usize), std::cmp::Reverse<(usize, usize, &'a str)>);
struct Chosen<'a> {
affinity: (bool, usize),
name: &'a String,
arguments: Vec<Value>,
arity: usize,
}
impl<'a> Chosen<'a> {
fn rank(&self) -> Rank<'a> {
(
self.affinity,
std::cmp::Reverse((self.arity, self.name.len(), self.name.as_str())),
)
}
}
// D14: for `struct archive *` all five producers take zero arguments and contain `new`,
// so a verb rule and a fewest-parameters rule both tie and alphabetical order picks
// `archive_match_new` - which SIGSEGVs on every input because the read-side vtable is
// never installed. Polarity is what separates them; affinity is what ranks what survives.
fn choose_producer<'a>(
handle: &str,
entry: &str,
vocabulary: &'a Vocabulary,
) -> Result<(&'a str, Vec<Value>), Refusal> {
let missing = || Refusal::NoProducer {
handle: handle.to_owned(),
};
let candidates = vocabulary.producers.get(handle).ok_or_else(missing)?;
let wanted = polarity_of(entry);
let mut best: Option<Chosen<'a>> = None;
let mut refusal: Option<Refusal> = None;
for (name, params) in candidates {
// A producer that consumes the handle it returns is a rebinder, not a
// constructor: XML_ExternalEntityParserCreate takes an XML_Parser and hands one
// back, and sorts first among its four producers.
if name == entry
|| params
.iter()
.any(|param| handle_key(¶m.spelling, ¶m.shape).as_deref() == Some(handle))
{
continue;
}
// A constructor that opens a file cannot be driven from memory, and zlib's gz*
// family already proved what happens when corpus bytes reach one.
if FILESYSTEM_VERBS
.iter()
.any(|verb| carries_word(name, &[verb]))
{
continue;
}
let found = polarity_of(name);
if let (Some(wanted), Some(found)) = (wanted, found)
&& wanted != found
{
continue;
}
let arguments = match producer_arguments(name, params) {
Ok(arguments) => arguments,
Err(reason) => {
refusal.get_or_insert(reason);
continue;
}
};
// Polarity RANKS, it does not merely veto. tj3DecompressHeader's producers are
// tjInitDecompress and the polarity-neutral tjInitTransform; both share exactly
// one leading word with it ("tj", because the 3 splits off), so affinity ties and
// the shorter name wins - handing a decompress entry point a transform handle.
let matched = wanted.is_some() && wanted == found;
let contender = Chosen {
affinity: (matched, shared_leading_words(name, entry)),
name,
arguments,
arity: params.len(),
};
if best
.as_ref()
.is_none_or(|top| contender.rank() > top.rank())
{
best = Some(contender);
}
}
match best {
Some(chosen) => Ok((chosen.name.as_str(), chosen.arguments)),
None => Err(refusal.unwrap_or_else(missing)),
}
}
#[must_use]
pub fn teardown_for(record: &str, entry: &str, vocabulary: &Vocabulary) -> Option<String> {
let candidates = vocabulary.destructors.get(record)?;
let mut best: Option<(usize, &String)> = None;
// Tearing down after an entry point that IS the teardown is a double free.
for name in candidates.iter().filter(|name| name.as_str() != entry) {
let score = shared_leading_words(name, entry);
let better = match best {
None => true,
Some((top, chosen)) => {
score > top || (score == top && (name.len(), name) < (chosen.len(), chosen))
}
};
if better {
best = Some((score, name));
}
}
let (score, chosen) = best?;
let choices = candidates
.iter()
.filter(|name| name.as_str() != entry)
.count();
if score == 0 && choices > 1 {
return None;
}
Some(chosen.clone())
}
fn teardown_calls(
record: &str,
held: &Held,
entry: &str,
vocabulary: &Vocabulary,
) -> Vec<(String, Value)> {
// Calling a field's destructor after the record's own would double free, so a record
// that owns a destructor tears itself down and nothing else runs.
if let Some(function) = teardown_for(record, entry, vocabulary) {
return vec![(function, held.reference())];
}
// A produced handle is opaque by construction: there are no fields to walk, and the
// library owns whatever hangs off it.
if held.by_value {
return Vec::new();
}
let Some(entity) = vocabulary.records.get(record) else {
return Vec::new();
};
entity
.fields
.iter()
.filter_map(|field| match &field.shape {
Shape::Record(nested) => teardown_for(nested, entry, vocabulary).map(|function| {
(
function,
Value::AddressOfField {
local: held.local.clone(),
field: field.name.clone(),
},
)
}),
_ => None,
})
.collect()
}
#[must_use]
pub fn macro_for_field(record: &str, field: &str, vocabulary: &Vocabulary) -> Option<String> {
macro_by_affinity(record, field, vocabulary.macros.iter().map(String::as_str))
}
// The one macro whose name says it states the size of THIS parameter of THIS record. Asked
// most-specific first, and both halves are load-bearing: `PNG_IMAGE_COLORMAP_SIZE(image)`
// answers for `colormap` by name, while `buffer` has no `PNG_IMAGE_BUFFER_SIZE` it can use -
// that macro exists but takes a second argument, so the arity filter drops it - and falls back
// to the record's own `PNG_IMAGE_SIZE(image)`, which is the macro libpng's own example calls.
//
// The fallback can only ever over-allocate relative to a per-parameter macro, never under: it
// is the size of the record's whole payload. Censused over ten tree-runs, it fires on exactly
// one parameter in the entire validation set, which is where that claim is worth what it costs.
fn sizing_macro(record: &str, param: Option<&String>, vocabulary: &Vocabulary) -> Option<String> {
param
.and_then(|name| {
macro_by_affinity(record, &format!("{name}_size"), unary_sizers(vocabulary))
})
.or_else(|| macro_by_affinity(record, "size", unary_sizers(vocabulary)))
}
// A macro taking a second argument is one the caller has to supply a number to, and inventing
// that number is the guess B67 exists to refuse. One filter, read by both the buffer rule and
// the Config rule, so the two cannot drift apart about what a usable macro is.
fn unary_sizers(vocabulary: &Vocabulary) -> impl Iterator<Item = &str> + Clone {
vocabulary
.sizers
.iter()
.filter(|(_, arity)| **arity == 1)
.map(|(name, _)| name.as_str())
}
fn macro_by_affinity<'a>(
record: &str,
field: &str,
names: impl Iterator<Item = &'a str> + Clone,
) -> Option<String> {
let record_upper = record.to_uppercase();
let direct = format!("{record_upper}_{}", field.to_uppercase());
if names.clone().any(|name| name == direct) {
return Some(direct);
}
let suffix = format!("_{}", field.to_uppercase());
let mut best: Option<(usize, String)> = None;
let mut tied = false;
for name in names.filter(|name| name.ends_with(&suffix)) {
let head = &name[..name.len() - suffix.len()];
if !(record_upper.starts_with(head) || head.starts_with(&record_upper)) {
continue;
}
let score = shared_leading_tokens(head, &record_upper);
match &best {
Some((top, _)) if score < *top => {}
Some((top, _)) if score == *top => tied = true,
_ => {
best = Some((score, name.to_owned()));
tied = false;
}
}
}
if tied {
None
} else {
best.map(|(_, name)| name)
}
}
fn is_double_pointer(param: &Param) -> bool {
matches!(
¶m.shape,
Shape::Pointer {
pointee: Pointee::Pointer(_),
..
}
)
}
// `archive_read_next_header(struct archive *, struct archive_entry **)` is not the shape B67
// refuses. The LIBRARY allocates the entry and writes its address into a slot; the harness owns
// nothing but the `struct archive_entry *entry = NULL;` local it passes the address of, and it
// never dereferences what comes back. That is a fact the headers state, the same way an output
// buffer the harness allocated states its own capacity.
//
// Two conditions, and both are load-bearing. The target one indirection down must be a RECORD,
// because `unsigned char **dstPlanes` and `png_bytepp row` are the opposite obligation - the
// caller allocates an array and the library reads it - and canonical types are what tell them
// apart: `png_bytep *` spells a record and IS `unsigned char **`. And the inner type has to be
// SPELLABLE by removing one indirection from what the header wrote, because a declaration the
// harness cannot spell is one it cannot emit; `png_sPLT_tpp` hides both stars in a typedef and
// is refused rather than guessed at, exactly as `indirect_extent_local` refuses.
fn filled_by_library(param: &Param) -> Option<String> {
if signature::record_behind_two_pointers(¶m.shape).is_none() && !is_scalar_slot(param) {
return None;
}
declared_inner(¶m.spelling)
}
// `int *const width` is a const POINTER to a mutable int, so the qualifier trails the star and
// `strip_suffix('*')` alone misses it - which would have dropped libwebp's `VP8GetInfo` and
// `VP8LGetInfo` from the population while keeping their `WebPDecode*` siblings.
fn declared_inner(spelling: &str) -> Option<String> {
let trimmed = spelling.trim();
let without_qualifier = trimmed.strip_suffix("const").unwrap_or(trimmed).trim();
let inner = without_qualifier.strip_suffix('*')?.trim();
(!inner.is_empty()).then(|| inner.to_owned())
}
// B87. A pointer to ONE scalar the library writes is a slot the harness owns, exactly as
// `struct archive_entry **` is: declare it, pass its address, let the library fill it. The
// number does not have to be guessed, so B67's objection does not apply - a pointer to a single
// element has no extent because it points at exactly one.
//
// What it is NOT is a buffer, and the census is why both guards below are the rule rather than
// decoration. Over 10 trees there are 86 non-const `Integral *` parameters on 29 functions, and
// `tj3Decompress12`'s `short *dstBuf` sits in that population beside `WebPDecodeRGBA`'s
// `int *width`. Handing a destination image buffer one stack `short` is a heap overflow this
// harness manufactured, on a rank-1 candidate the authors themselves call - the D12 class.
// A name carrying an OUTPUT word is memory; a PLURAL name is one element per plane or per image
// (`strides`, `dstSizes`). Both directions are refused, because guessing wrong forges a crash
// and refusing only costs reach.
fn is_scalar_slot(param: &Param) -> bool {
if !matches!(
param.shape,
Shape::Pointer {
pointee: Pointee::Integral,
is_const: false,
}
) {
return false;
}
let Some(name) = param.name.as_deref() else {
return false;
};
!signature::matches_vocabulary(name, signature::OUTPUT_NAMES) && !names_many(name)
}
// A trailing `s` that is not `ss`. Deliberately crude and deliberately biased: a singular name it
// misreads as plural is only refused, while a plural it misses is an out-of-bounds write.
fn names_many(name: &str) -> bool {
let lowered = name.to_lowercase();
lowered.ends_with('s') && !lowered.ends_with("ss")
}
// Which parameters the library fills in, and what the harness must declare for each. Shared by
// the entry point and by an upward step so both spell the same local for the same signature.
//
// `standing` is how many such locals the plan already declares. Without it a step that takes a
// library-filled out-param would redeclare the entry point's `lisdex_filled` in the same block,
// which either shadows a slot an earlier call still refers to or does not compile at all.
fn filled_locals(
params: &[Param],
roles: &[ParamRole],
standing: usize,
) -> BTreeMap<usize, (String, String)> {
let mut found = BTreeMap::new();
for (index, (param, role)) in params.iter().zip(roles).enumerate() {
if !matches!(role, ParamRole::Output | ParamRole::Context) {
continue;
}
let Some(ty) = filled_by_library(param) else {
continue;
};
let position = standing + found.len();
let local = if position == 0 {
FILLED_LOCAL.to_owned()
} else {
format!("{FILLED_LOCAL}{position}")
};
found.insert(index, (ty, local));
}
found
}
fn cast_for(param: &Param) -> Result<Option<String>, Refusal> {
let label = || param.name.clone().unwrap_or_else(|| param.spelling.clone());
match ¶m.shape {
Shape::Pointer { pointee, .. } if pointee.is_exact_byte() => Ok(None),
Shape::Pointer { pointee, is_const } => {
let base = match pointee {
Pointee::Void => "void",
Pointee::Char | Pointee::SignedChar | Pointee::UnsignedChar => "char",
_ => return Err(Refusal::UnsupportedShape { param: label() }),
};
Ok(Some(if *is_const {
format!("const {base} *")
} else {
format!("{base} *")
}))
}
_ => Err(Refusal::UnsupportedShape { param: label() }),
}
}
// The entry point's own spelling is what the local must be declared with, but a context
// declared `const` cannot then be handed to a teardown that takes it mutable.
fn declarable(spelling: &str) -> String {
spelling
.trim()
.strip_prefix("const ")
.unwrap_or(spelling.trim())
.to_owned()
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Held {
local: String,
// A stack context is passed by address; a handle the library allocated IS the address
// already. Getting this backwards is how `LZ4_freeStream(&ctx)` reported "attempting
// free on address which was not malloc()-ed" with the frames inside lz4.
by_value: bool,
}
impl Held {
fn reference(&self) -> Value {
if self.by_value {
Value::Local(self.local.clone())
} else {
Value::AddressOf(self.local.clone())
}
}
}
// zlib declares uncompress(Bytef *dest, uLongf *destLen, ...): the caller writes the
// capacity in and the library writes the decoded length back out. The local has to carry
// the library's OWN spelling, because a size_t where a uLongf is wanted is a type error on
// any target where they differ.
fn indirect_extent_local(candidate: &Candidate) -> Option<Stmt> {
let extent = candidate
.analysis
.extents
.iter()
.find(|(pointer, extent)| {
candidate.analysis.roles[**pointer] == ParamRole::Output
&& is_indirect(&candidate.params[**extent])
})
.map(|(_, extent)| *extent)?;
let pointee = candidate.params[extent]
.spelling
.trim()
.strip_suffix('*')?
.trim()
.to_owned();
Some(Stmt::Declare {
ty: declarable(&pointee),
name: OUT_LEN_LOCAL.to_owned(),
init: Init::Capacity,
})
}
// A leftover extent is refused because its MEANING is not header-visible, and the census
// says so: across 306 candidates on seven trees, 23 integrals reach this arm and they are
// four unrelated quantities - libarchive's `read_size` is a block size, libjpeg-turbo's `n`
// is an array element count, libwebp's `chunk_size` is a sub-extent of the input, libpng's
// `num_to_check` IS the buffer's missing length. No single invented value is right for all
// of them, and 0 is not the safe universal it looks like: it makes the library decode
// nothing, which is B74's constant program wearing different clothes.
//
// The one case where the number is a FACT the harness owns rather than a guess is an extent
// that names an OUTPUT quantity in a signature whose output buffer already declares a
// capacity. lz4's own ossfuzz/decompress_fuzzer.c writes exactly that call:
// `LZ4_decompress_safe_partial(data, dst, size, dstCapacity, dstCapacity)`. The harness
// allocated that buffer, so asking the library for at most as much as it holds cannot
// overrun it, and an overrun anyway is the library breaking its contract - the same line
// B67 draws for the capacity itself.
//
// Both halves are load-bearing and the census sizes each: 3 of the 23 name an output, and
// only 1 of those three sits in a signature with a sized output buffer. Dropping the second
// half would hand `LZ4_decompress_safe_partial_usingDict` a capacity for a buffer nothing
// allocated.
fn bounds_the_output(label: &str, analysis: &Analysis) -> bool {
signature::matches_vocabulary(label, signature::OUTPUT_NAMES)
&& analysis
.extents
.keys()
.any(|pointer| analysis.roles[*pointer] == ParamRole::Output)
}
fn owns_this_extent(analysis: &Analysis, extent: usize) -> Option<usize> {
analysis
.extents
.iter()
.find(|(_, owned)| **owned == extent)
.map(|(pointer, _)| *pointer)
}
fn is_indirect(param: &Param) -> bool {
matches!(
¶m.shape,
Shape::Pointer {
pointee: Pointee::Integral,
..
}
)
}
// The corpus is ONE object, so exactly one readable buffer can be it. Position decides,
// because C APIs put the primary input first and every real case in the set agrees:
// `LZ4_decompress_safe_usingDict(src, dst, srcSize, dstCapacity, dictStart, dictSize)`,
// `blake2xb(out, outlen, in, inlen, key, keylen)`, `LZ4F_decompress_usingDict(dctx, dst,
// dstSize, srcBuffer, srcSize, dict, dictSize)`.
//
// The signature's own grade cannot be reused for this. `grade_signature` picks its buffer
// with `max_by_key(buffer_quality)`, and lz4's `src` and `dictStart` are the same type, so
// they score equal - and `max_by_key` returns the LAST maximum, which is `dictStart`. Keying
// on that would have handed the dictionary the corpus and the input a zeroed buffer.
fn primary_buffer(analysis: &Analysis) -> Option<usize> {
analysis
.roles
.iter()
.position(|role| *role == ParamRole::Buffer)
}
fn bind_all(
candidate: &Candidate,
locals: &BTreeMap<String, Held>,
filled: &BTreeMap<usize, (String, String)>,
) -> Result<Vec<Value>, Refusal> {
candidate
.params
.iter()
.zip(&candidate.analysis.roles)
.enumerate()
.map(|(index, (param, role))| {
// `None`: the entry point may not use a macro-stated size. Nothing has filled the
// record yet, so every such macro reads zeros. Structural rather than a check.
bind(
index,
param,
*role,
locals,
filled,
&candidate.analysis,
None,
)
})
.collect()
}
// The declared type decides the initialiser, and it decides it structurally: a slot for a record
// the library allocates is a POINTER and starts NULL, while a scalar slot is a value and starts
// zeroed. `int lisdex_filled = NULL;` is not the same statement - it is a constraint violation
// that a target built with `-Werror` refuses to compile.
fn filled_declarations(filled: &BTreeMap<usize, (String, String)>) -> Vec<Stmt> {
filled
.values()
.map(|(ty, local)| Stmt::Declare {
ty: ty.clone(),
name: local.clone(),
init: if ty.trim_end().ends_with('*') {
Init::Null
} else {
Init::ZeroBytes
},
})
.collect()
}
// B82. The extent of a buffer is knowledge the headers usually do not have, which is what B67
// refuses on - but a library that ships a macro computing it DOES have it, and libpng's own
// example calls `malloc(PNG_IMAGE_SIZE(image))` on the line before `png_image_finish_read`.
//
// Offered only where it is a fact rather than a guess, and each condition was measured:
//
// * the macro is written about a RECORD, so it can only be applied to one the harness itself
// declared - `PNG_IMAGE_SIZE(image)` expands to `(image).format` and needs the object, not
// a pointer to it. This is the line `field_bindings` already draws for the same reason;
// * the macro must take exactly ONE argument, because a second one is a number the caller
// owns and inventing it is the guess B67 exists to refuse (`PNG_IMAGE_BUFFER_SIZE(image,
// row_stride)` is dropped here, not used with a zero);
// * it is offered on an upward STEP and never on the entry point, because the macro reads
// fields the library has not written yet. Before `png_image_begin_read_from_memory` the
// record is zeroed and `PNG_IMAGE_SIZE` is 0, so the entry point would allocate nothing and
// hand the library a pointer to it, which is the manufactured overflow this is avoiding.
//
// B84 gave the same struct a second job. A step binds against the PARENT's local map and has no
// context resolution of its own, so a call needing a record the entry point never took refuses
// however declarable that record is - which is what left `png_image_finish_read` stopped at
// `background` with every other parameter bound.
struct Scope<'a> {
vocabulary: &'a Vocabulary,
// `None` when the parent's contexts are all produced handles. A macro is written about the
// record and needs the object, so there is nothing to apply it to.
sizable: Option<(String, String)>,
// Names are unique across the whole climb because every buffer is a distinct C declaration
// in one block, but `buffers` holds only the ones THIS step allocated - the earlier steps
// freed theirs beside their own call, so listing them in a later bail is a double free.
first: usize,
contexts: usize,
statements: Vec<Stmt>,
buffers: Vec<String>,
declared: BTreeMap<String, String>,
}
impl Scope<'_> {
// The entry point's own ownership rule, applied one level out: a record the header defines
// completely and the library never hands back is the caller's to declare. The third
// condition is this side's alone - a step has nowhere to schedule a teardown, so a record
// with a destructor is refused rather than declared and left unfreed, which would be a
// LeakSanitizer report inside the target on every replay.
fn declare(&mut self, handle: &str) -> Option<Value> {
if let Some(local) = self.declared.get(handle) {
return Some(Value::AddressOf(local.clone()));
}
let record = self.vocabulary.records.get(handle)?;
if self.vocabulary.produced.contains(handle)
|| self.vocabulary.destructors.contains_key(handle)
{
return None;
}
let local = format!("{CONTEXT_LOCAL}{}", self.contexts);
self.contexts += 1;
self.statements.push(Stmt::Declare {
ty: record.spelling.clone(),
name: local.clone(),
init: Init::ZeroBytes,
});
self.declared.insert(handle.to_owned(), local.clone());
Some(Value::AddressOf(local))
}
// The same fact as `offer`, for a NUMBER rather than a buffer. libpng defines
// `PNG_IMAGE_SIZE(image)` as `PNG_IMAGE_BUFFER_SIZE(image, PNG_IMAGE_ROW_STRIDE(image))`, so
// taking the stride from the header rather than pinning it to zero makes the buffer and the
// stride agree BY CONSTRUCTION instead of by trusting the library to substitute a default.
//
// Asked before the extent test, because a number the header states beats a number the tool
// refuses to guess by the same argument B82 makes. The corpus has no extent-named Config
// with a stating macro, so that ordering is asserted by a unit test rather than a tree.
fn stated(&mut self, field: &str) -> Option<Value> {
let (record, held) = self.sizable.clone()?;
let named = macro_by_affinity(&record, field, unary_sizers(self.vocabulary))?;
Some(Value::Stated(format!("{named}({held})")))
}
fn offer(&mut self, param: &Param) -> Option<Value> {
let (record, held) = self.sizable.clone()?;
let stated = sizing_macro(&record, param.name.as_ref(), self.vocabulary)?;
let cast = cast_for(param).ok()?;
let position = self.first + self.buffers.len();
let local = if position == 0 {
SIZED_LOCAL.to_owned()
} else {
format!("{SIZED_LOCAL}{position}")
};
self.statements.push(Stmt::AllocSized {
length: format!("{local}{SIZED_LEN_SUFFIX}"),
size: format!("{stated}({held})"),
frees: self.buffers.clone(),
local: local.clone(),
});
self.buffers.push(local.clone());
Some(Value::SizedBuffer { local, cast })
}
}
fn sized_by_macro(
index: usize,
param: &Param,
analysis: &Analysis,
scope: Option<&mut Scope>,
) -> Option<Value> {
let sizing = scope?;
// No const test, deliberately: `provisional_role` grades every const byte pointer as a
// Buffer, so one cannot reach either arm this is called from and a check for it would be an
// inert rule with no control able to redden it.
let Shape::Pointer { pointee, .. } = ¶m.shape else {
return None;
};
if !pointee.is_byte_sized() || analysis.extents.contains_key(&index) {
return None;
}
sizing.offer(param)
}
#[must_use]
pub fn callback_name(index: usize) -> String {
format!("{CALLBACK_STUB_PREFIX}{index}")
}
fn prototype_of(param: &Param) -> Option<&Prototype> {
match ¶m.shape {
Shape::Pointer {
pointee: Pointee::Function(prototype),
..
} => prototype.as_ref(),
_ => None,
}
}
fn spells_byte_sink(spelling: &str) -> bool {
let text = spelling.trim();
text.ends_with('*')
&& BYTE_SINK_SPELLINGS
.iter()
.any(|prefix| text.starts_with(prefix))
}
fn spells_count(spelling: &str) -> bool {
let text = spelling.trim();
!text.contains('*')
&& COUNT_SPELLINGS
.iter()
.any(|word| text.split_whitespace().any(|token| token == *word))
}
// A read callback is (sink, count) ADJACENT, never the first pointer in the list: libtiff's
// `TIFFReadWriteProc` is `tmsize_t (void *, void *, tmsize_t)` where argument 0 is the opaque
// handle and argument 1 is the sink, and both spell `void *`. Adjacency is what separates
// them, and requiring an integral RETURN is what separates a reader from a writer's twin.
fn read_kind(prototype: &Prototype) -> CallbackKind {
if prototype.returns_void() {
return CallbackKind::Benign;
}
for index in 0..prototype.params.len().saturating_sub(1) {
if spells_byte_sink(&prototype.params[index]) && spells_count(&prototype.params[index + 1])
{
return CallbackKind::ReadFromCursor {
buffer: index,
count: index + 1,
};
}
}
CallbackKind::Benign
}
fn callback_stubs(candidate: &Candidate) -> Vec<CallbackStub> {
candidate
.params
.iter()
.zip(&candidate.analysis.roles)
.enumerate()
.filter(|(_, (_, role))| **role == ParamRole::Callback)
.filter_map(|(index, (param, _))| {
let prototype = prototype_of(param)?;
Some(CallbackStub {
name: callback_name(index),
return_ty: prototype.returns.clone(),
params: prototype.params.clone(),
kind: read_kind(prototype),
})
})
.collect()
}
fn bind(
index: usize,
param: &Param,
role: ParamRole,
locals: &BTreeMap<String, Held>,
filled: &BTreeMap<usize, (String, String)>,
analysis: &Analysis,
scope: Option<&mut Scope>,
) -> Result<Value, Refusal> {
let label = param.name.clone().unwrap_or_else(|| param.spelling.clone());
match role {
// A readable buffer that is not the FIRST one is a second input the fuzzer cannot
// supply. It gets its own zeroed allocation and its own declared size, which is what
// lz4's authors do for the dictionary and what keeps the two pointers distinct.
ParamRole::Buffer if primary_buffer(analysis) != Some(index) => {
if analysis.extents.contains_key(&index) {
Ok(Value::AuxBuffer {
cast: cast_for(param)?,
})
} else {
// Without an extent there is no size to declare, so the library is told
// nothing about how far it may read - the same line B67 draws for outputs.
Err(Refusal::UnsizedTextParam { param: label })
}
}
ParamRole::Buffer => match ¶m.shape {
Shape::Pointer {
pointee: Pointee::Char | Pointee::SignedChar,
..
} => {
// A char pointer with no length OF ITS OWN is a STRING, not a byte buffer.
// zlib's real gzopen prototype is unnamed, so the path detector could not
// fire and both arguments took the fuzz copy: the harness then created and
// TRUNCATED files in the working directory named by corpus bytes. Asking
// whether the SIGNATURE had any length at all was the weaker question -
// LZ4_decompress_safe_partial_usingDict has three and none of them is src's.
if analysis.extents.contains_key(&index) {
Ok(Value::NulTerminated)
} else {
Err(Refusal::UnsizedTextParam { param: label })
}
}
_ => Ok(Value::Data {
cast: cast_for(param)?,
}),
},
ParamRole::Length => {
let owner = owns_this_extent(analysis, index);
// An auxiliary buffer's extent describes memory the HARNESS allocated, exactly
// as an output's does, so it is a fact rather than an inference about the corpus.
if owner.is_some_and(|pointer| {
analysis.roles[pointer] == ParamRole::Buffer
&& primary_buffer(analysis) != Some(pointer)
}) {
return if is_indirect(param) {
Err(Refusal::IndirectExtent { param: label })
} else {
Ok(Value::AuxCapacity)
};
}
let owned_by_output =
owner.is_some_and(|pointer| analysis.roles[pointer] == ParamRole::Output);
if owned_by_output {
// The capacity of a buffer the HARNESS allocated, so it is a fact, not an
// inference. An in/out extent carries it in and the decoded length back out.
return Ok(if is_indirect(param) {
Value::AddressOf(OUT_LEN_LOCAL.to_owned())
} else {
Value::OutCapacity
});
}
// The fuzz data's own length cannot be handed over by address without a local
// the library is then free to overwrite; emitting `size` where `size_t *` is
// wanted does not compile, so say so here rather than spend a compile on it.
if is_indirect(param) {
return Err(Refusal::IndirectExtent { param: label });
}
Ok(Value::Size)
}
ParamRole::Config => {
if let Some(value) = scope.and_then(|scope| scope.stated(&label)) {
return Ok(value);
}
if is_extent_name(&label) {
if bounds_the_output(&label, analysis) {
return Ok(Value::OutCapacity);
}
return Err(Refusal::UnboundExtent { param: label });
}
Ok(Value::Zero)
}
// A stub can only be written from a PROTOTYPE. `FunctionNoPrototype` states a return
// type and nothing else, so a body written for it would guess the arguments the
// library is about to pass, and the refusal stands.
ParamRole::Callback => {
if prototype_of(param).is_some() {
Ok(Value::Callback(callback_name(index)))
} else {
Err(Refusal::NeedsCallback { param: label })
}
}
ParamRole::Path => Err(Refusal::PathEntry),
ParamRole::Stream => Err(Refusal::UnsupportedShape { param: label }),
ParamRole::Output
if matches!(¶m.shape, Shape::Pointer { pointee, .. }
if pointee.is_byte_sized()) =>
{
// The class B67 was written for. WITH a capacity parameter the library is under
// contract not to pass it, so an overrun is the library's bug and ASAN says so.
// WITHOUT one - png_read_image, tj3Decompress8 - the size is knowledge the
// caller is expected to already hold, and guessing it manufactures the crash.
if analysis.extents.contains_key(&index) {
Ok(Value::OutBuffer {
cast: cast_for(param)?,
})
} else if let Some(value) = sized_by_macro(index, param, analysis, scope) {
Ok(value)
} else {
Err(Refusal::UnsizedOutParam { param: label })
}
}
ParamRole::Output | ParamRole::Context => {
bind_context(index, param, label, locals, filled, analysis, scope)
}
}
}
fn bind_context(
index: usize,
param: &Param,
label: String,
locals: &BTreeMap<String, Held>,
filled: &BTreeMap<usize, (String, String)>,
analysis: &Analysis,
scope: Option<&mut Scope>,
) -> Result<Value, Refusal> {
// The map IS the answer to "does the library fill this": `filled_locals` decided it and
// declared the local, so consulting it for every index rather than only for a double pointer
// is what lets B87's scalar slot reach the same binding B81's record slot already had.
if let Some((_, local)) = filled.get(&index) {
return Ok(Value::AddressOf(local.clone()));
}
if is_double_pointer(param) {
return Err(Refusal::UnsizedOutParam { param: label });
}
// Binding every context param to one shared local passed a small struct's address where a
// large one was expected and produced a real ASAN stack-buffer-overflow attributed to the
// library, not the harness.
match handle_key(¶m.spelling, ¶m.shape) {
Some(handle) => {
if let Some(held) = locals.get(&handle) {
return Ok(held.reference());
}
// B84. Asked only after the parent's map has had its answer, so a handle the plan
// already holds keeps the local it was bound to.
scope
.and_then(|scope| scope.declare(&handle))
.ok_or(Refusal::OpaqueContext { record: handle })
}
// A byte pointer names no handle at all, and `void *buffer` is what falls through to
// here - which is why the B67 arm above never sees the parameter B82 was written for.
None => sized_by_macro(index, param, analysis, scope)
.ok_or(Refusal::UnsupportedShape { param: label }),
}
}
fn field_bindings(record: &str, vocabulary: &Vocabulary) -> Vec<(String, String)> {
let Some(entry) = vocabulary.records.get(record) else {
return Vec::new();
};
entry
.fields
.iter()
.filter(|field| field.shape == Shape::Integral)
.filter_map(|field| {
macro_for_field(record, &field.name, vocabulary)
.map(|macro_name| (field.name.clone(), macro_name))
})
.take(MAX_POPULATED_FIELDS)
.collect()
}
#[must_use]
pub fn variant_masks(fields: usize) -> Vec<u32> {
// One wrong macro used to poison the single all-populated plan and the only fallback
// was the empty one, which the coverage oracle rejects, so the candidate was lost.
let mut masks: Vec<u32> = (0..(1u32 << fields.min(MAX_POPULATED_FIELDS))).collect();
masks.sort_by_key(|mask| {
(
std::cmp::Reverse(mask.count_ones()),
std::cmp::Reverse(*mask),
)
});
masks.truncate(MAX_PLAN_VARIANTS);
masks
}
// B87, and it was found by RUNNING the harnesses rather than by reading them. The emitted C for
// `WebPDecodeRGBA(data, size, &w, &h)` is exactly what a human writes and it still failed every
// valid seed: the function RETURNS a freshly allocated RGBA buffer, nothing released it, and
// LeakSanitizer reported `Direct leak of 4096 byte(s)` with the frames inside
// `WebPAllocateDecBuffer` - a crash attributed to the library that the harness manufactured.
// That is D15's forged crash and the same line B84 already draws for a record with a destructor:
// where the plan cannot schedule the teardown, it must refuse rather than leak.
//
// Scoped to a byte-typed return because that is what the census reaches: an `Into`-style decoder
// hands back the caller's own buffer, so the leak only exists when the library allocated it, and
// a plain `int` return (`WebPGetInfo`, `VP8GetInfo`, `VP8LGetInfo`) owns nothing at all.
fn returns_releasable_memory(
candidate: &Candidate,
vocabulary: &Vocabulary,
) -> Result<(), Refusal> {
let result = &candidate.result;
let Shape::Pointer {
pointee,
is_const: false,
} = &result.shape
else {
return Ok(());
};
if !pointee.is_byte_sized() {
return Ok(());
}
// An argument the harness passed in and got back is memory it already owns.
if candidate
.params
.iter()
.any(|param| param.shape == result.shape)
{
return Ok(());
}
let _ = vocabulary;
Err(Refusal::UnreleasedReturn {
ty: result.spelling.clone(),
})
}
fn admissible(candidate: &Candidate) -> Result<(), Refusal> {
if candidate.fuzzability == Fuzzability::NoInput {
return Err(Refusal::NoDataInput);
}
// zlib's gzopen takes two unnamed char pointers, so no parameter-name rule could see
// the path. The function's own name is the signal that an argument becomes a path.
//
// The name alone is not enough, though: keyed on the verb only, this rule refused
// libarchive's `archive_read_open_memory(struct archive *, const void *, size_t)` -
// the ground-truth #1 entry point the M3 gate asserts ranks first - along with four
// more, because the word "open" appears in them. There is no path in that signature
// and a `void *` cannot be handed to the filesystem without a cast. So the verb only
// condemns a signature that also carries somewhere for a path to land, and `char` is
// that place: `unsigned char`/`signed char` are byte buffers, which is the same line
// the unsized-text rule below already draws.
if let Some(verb) = FILESYSTEM_VERBS
.iter()
.find(|verb| carries_word(&candidate.name, &[verb]))
&& candidate.params.iter().any(is_path_capable)
&& !hands_over_its_io(candidate)
{
return Err(Refusal::FilesystemVerb {
verb: (*verb).to_owned(),
});
}
Ok(())
}
// A function whose every parameter is a handle can only configure the library; it has
// nowhere to receive a corpus. A zero-parameter one has nowhere either.
//
// This is the single test behind both halves of the ladder, and both halves were wrong
// before it. Every one of libarchive's 25 fuzz targets calls
// `archive_read_support_format_rar5(struct archive *)`, so treating "the authors call it"
// as "the authors fuzz it" hoisted seven configurators above the entry point the M3 gate
// asserts ranks first. Keying on the corpus instead does not work either: brotli's authored
// data entry `BrotliDecoderDecompressStream` takes its buffer through a `const uint8_t **`
// so it is not a byte taker, and every one of its six parameters carries the Context ROLE,
// so a role-based test called the decoder plumbing and let the fall-through back in. What
// separates them is that five of those six parameters are not handles.
#[must_use]
pub fn is_configuration_shape(params: &[Param]) -> bool {
params
.iter()
.all(|param| handle_key(¶m.spelling, ¶m.shape).is_some())
}
#[must_use]
pub fn is_configurator(candidate: &Candidate) -> bool {
is_configuration_shape(&candidate.params)
}
fn hands_over_its_io(candidate: &Candidate) -> bool {
candidate.analysis.roles.contains(&ParamRole::Callback)
}
fn is_path_capable(param: &Param) -> bool {
matches!(
¶m.shape,
Shape::Pointer {
pointee: Pointee::Char | Pointee::SignedChar,
..
}
)
}
struct Contexts {
locals: BTreeMap<String, Held>,
ordered: Vec<(String, Held)>,
opening: Vec<Stmt>,
}
fn resolve_contexts(candidate: &Candidate, vocabulary: &Vocabulary) -> Result<Contexts, Refusal> {
let mut found = Contexts {
locals: BTreeMap::new(),
ordered: Vec::new(),
opening: Vec::new(),
};
for (param, role) in candidate.params.iter().zip(&candidate.analysis.roles) {
if !matches!(role, ParamRole::Context | ParamRole::Output) || is_double_pointer(param) {
continue;
}
let Some(handle) = handle_key(¶m.spelling, ¶m.shape) else {
continue;
};
if found.locals.contains_key(&handle) {
continue;
}
let local = if found.locals.is_empty() {
CONTEXT_LOCAL.to_owned()
} else {
format!("{CONTEXT_LOCAL}{}", found.locals.len())
};
// A record the header defines completely and the library never hands back is the
// caller's to declare. Everything else - an opaque handle, or a record the library
// allocates and only exposes a prefix of - has to come from a producer.
let owned =
vocabulary.records.contains_key(&handle) && !vocabulary.produced.contains(&handle);
let held = if owned {
found.opening.push(Stmt::Declare {
ty: vocabulary.records[&handle].spelling.clone(),
name: local.clone(),
init: Init::ZeroBytes,
});
Held {
local,
by_value: false,
}
} else {
let (producer, args) = choose_producer(&handle, &candidate.name, vocabulary)?;
found.opening.push(Stmt::Call {
function: producer.to_owned(),
args,
capture: Some(Binding {
ty: declarable(¶m.spelling),
name: local.clone(),
}),
});
// A producer that failed leaves a NULL the entry point will dereference, and
// that crash belongs to the harness, not to the library.
found.opening.push(Stmt::BailIfNull {
local: local.clone(),
});
Held {
local,
by_value: true,
}
};
found.locals.insert(handle.clone(), held.clone());
found.ordered.push((handle, held));
}
Ok(found)
}
// An undeclared name counts as plumbing - zlib writes `inflateInit` as a macro over
// `inflateInit_`, so it is not replayable either way, and stopping the scan on it would cut
// the setup short of the calls that ARE replayable.
fn is_teardown(name: &str, vocabulary: &Vocabulary) -> bool {
vocabulary
.destructors
.values()
.any(|known| known.contains(name))
}
fn is_plumbing(name: &str, vocabulary: &Vocabulary) -> bool {
vocabulary
.functions
.get(name)
.is_none_or(|params| is_configuration_shape(params))
}
// The author's setup is the run of plumbing that opens their sequence. It ends at the first
// call that takes something other than a handle, because that is the call they hand the
// input to - `archive_read_set_options` in libarchive's tar target, `inflate` in zlib's
// zpipe.c - and everything after it is what they did with the result rather than what they
// did to make the call possible.
fn setup_run<'a>(sequence: &'a [String], entry: &str) -> &'a [String] {
let ours = sequence.iter().position(|call| call == entry);
let cut = sequence.len().min(ours.unwrap_or(usize::MAX));
&sequence[..cut]
}
// The author's setup calls are copied, never invented. A call is replayed only when every
// one of its parameters is a context this harness is already holding: that is what makes
// `archive_read_support_format_all(a)` replayable and stops `png_sig_cmp(data, 0, 8)` or
// `memcpy(dst, data, size)` from being guessed at. A zero-argument call is skipped because
// it cannot touch our context - it is the producer we already called.
fn replay_setup(
sequence: &[String],
entry: &str,
locals: &BTreeMap<String, Held>,
emitted: &BTreeSet<String>,
vocabulary: &Vocabulary,
) -> Vec<Stmt> {
let mut replayed = Vec::new();
for name in setup_run(sequence, entry) {
if !is_plumbing(name, vocabulary) {
break;
}
// A destructor takes one handle and is therefore plumbing-shaped, so the run rule
// alone will happily replay one AS SETUP. Measured: zlib's `examples/gun.c` put
// `inflateBackEnd` into the opening run and the harness tore the stream down
// before it was ever used. `emitted` only covers the teardowns THIS plan schedules,
// which is a different set - ours was `inflateEnd`.
if name == entry || emitted.contains(name) || is_teardown(name, vocabulary) {
continue;
}
let Some(params) = vocabulary.functions.get(name) else {
continue;
};
if params.is_empty() {
continue;
}
let bound: Option<Vec<Value>> = params
.iter()
.map(|param| {
handle_key(¶m.spelling, ¶m.shape)
.and_then(|handle| locals.get(&handle))
.map(Held::reference)
})
.collect();
if let Some(args) = bound {
replayed.push(Stmt::Call {
function: name.clone(),
args,
capture: None,
});
}
}
replayed
}
// One further call the author made AFTER the entry point, already bound to this plan's own
// locals. It is a separate type from a plain `Stmt` because the search has to name it in a
// rejection - "the harness plus THIS call was rejected" is a different statement from "the
// harness was rejected".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Extension {
pub function: String,
// A step whose out-param the library fills needs its own NULL local, and the step is the
// only thing that knows the local exists. Carried here rather than hoisted into the plan
// so a step that is later rejected takes its declaration with it.
pub declares: Vec<Stmt>,
pub call: Stmt,
// A macro-sized buffer is freed by the step that allocated it. Keeping the release beside
// the call rather than in the plan's epilogue is what lets a rejected step take its whole
// allocation with it, and it is why the buffer needs no scaffolding flag.
pub releases: Vec<Stmt>,
}
// The mirror of `setup_run`, and the asymmetry is the point. An entry point the authors never
// call has NO tail: `position` returning None yields an empty slice rather than the whole
// sequence, so nothing is invented for a candidate the authors said nothing about. The setup
// side does the opposite deliberately - it scans the whole sequence for replayable plumbing.
//
// B83. "The authors never call it" was answered against ONE sequence - the tree-wide winner of
// the ladder - and that is a different question from whether they called it at all. libarchive
// ships 25 extracted fuzz targets; the ladder chose `libarchive_seek_fuzzer.cc`, which opens
// with `archive_read_open1`, so `archive_read_open_memory` read as uncalled and had no tail.
// `libarchive_roundtrip_fuzzer.cc` calls it directly, and the tail there is the real one:
// `archive_read_next_header, archive_entry_pathname, archive_entry_size, archive_read_data`.
// Every one of those call lists was already extracted and 24 of 25 were discarded.
//
// The chosen sequence is tried FIRST so nothing that has a tail today gets a different one -
// this only ever fills in an empty answer. Censused over ten tree-runs before it was built:
// 4 runs and 6 candidates gain a tail, and no candidate that already had one changes.
fn tail_run<'a>(sequences: &[&'a [String]], entry: &str) -> &'a [String] {
for sequence in sequences {
if let Some(index) = sequence.iter().position(|call| call == entry) {
return &sequence[index + 1..];
}
}
&[]
}
// D4's oracle 3b measures a candidate against the shorter call sequence it EXTENDS, so the
// parent has to be a harness that already passed - never a truncation of one. The extension
// therefore only ever goes UP: start at the accepted entry point and append the next call the
// authors made, bound by the same rules that bound the entry point itself.
//
// A step must TAKE a handle this plan is already holding. Without that requirement the rule
// admits a second stateless entry point - lz4's own decompress_fuzzer.c calls
// `LZ4_decompress_safe_usingDict`, `LZ4_decompress_safe_partial` and
// `LZ4_decompress_safe_partial_usingDict` back to back over the same buffers, and fusing them
// into one file would make a crash unattributable while oracle 4 already keeps them as
// separate survivors. The handle is what makes a sequence a sequence.
//
// Censused over the seven analysable trees before this was built, because the population
// bounds what the oracle can ever be worth. Only THREE candidates that plan appear in their
// own author's sequence at all: libjpeg-turbo's `tj3DecompressHeader` (13-call tail),
// libpng's `png_image_begin_read_from_memory` (tail `png_image_finish_read`) and lz4's two
// partial decoders. The other four trees - brotli, libarchive, libwebp, zlib - plan an entry
// point the chosen sequence never names, so their tail is empty by construction.
pub fn upward_steps(
candidate: &Candidate,
vocabulary: &Vocabulary,
sequences: &[&[String]],
) -> Vec<Extension> {
let Ok(Contexts {
locals,
ordered,
opening,
}) = resolve_contexts(candidate, vocabulary)
else {
return Vec::new();
};
let mut scheduled: BTreeSet<String> = opening
.iter()
.filter_map(|statement| match statement {
Stmt::Call { function, .. } => Some(function.clone()),
_ => None,
})
.collect();
scheduled.extend(
ordered
.iter()
.flat_map(|(handle, held)| teardown_calls(handle, held, &candidate.name, vocabulary))
.map(|(function, _)| function),
);
let mut steps: Vec<Extension> = Vec::new();
let mut declared = filled_locals(&candidate.params, &candidate.analysis.roles, 0).len();
let mut allocated = 0usize;
// `resolve_contexts` names locals `ctx`, `ctx1`, `ctx2` off its own count, so a step's own
// declaration has to start past every one of them AND past every earlier step's.
let mut opened = 0usize;
for name in tail_run(sequences, &candidate.name) {
if steps.len() == MAX_UPWARD_STEPS {
break;
}
// The author's teardown ends the sequence: everything they wrote after it runs on a
// handle they had finished with, and appending it would run on one we had freed.
//
// B83, and the exception is narrow on purpose. The miner flattens SOURCE order, so an
// early-return cleanup branch lands in the middle of the success path: libarchive's
// `if (archive_read_open_memory(...) != ARCHIVE_OK) { archive_read_free(a); return 0; }`
// puts a free between the opener and every call worth making. That free is one THIS
// plan already schedules for the same handle, which is exactly what tells the two
// cases apart - a teardown we emit ourselves at the end is not new knowledge and not a
// gap, and skipping it here leaves the single teardown the plan always had. A teardown
// we do NOT schedule is still the end of the road, because it disposes of something we
// did not know we were holding.
if is_teardown(name, vocabulary) {
if !scheduled.contains(name) {
break;
}
continue;
}
// Skipped rather than stopped on, because none of the three is a gap in the author's
// order: the entry point may appear twice in one sequence, a producer this plan
// already called is a call we HAVE made, and a repeat adds the same statement twice.
if name == &candidate.name
|| scheduled.contains(name)
|| steps.iter().any(|step| &step.function == name)
{
continue;
}
// An undeclared name is not a library call we can reason about at all - the miner
// yields macros, libc and even plain variables (`PNG_IMAGE_SIZE` and `buffer` are both
// in libpng's mined tail) - so it says nothing about the state of our handle and is
// skipped for the same reason the setup replay skips `inflateInit`'s macro.
let Some(params) = vocabulary.functions.get(name) else {
continue;
};
if params.is_empty() {
continue;
}
// Everything below STOPS the climb rather than skipping. A call we cannot copy is a
// gap in the only knowledge we have, and the calls after a gap were written against
// state we did not build. Measured on libarchive, whose real tail is
// `archive_read_next_header, archive_entry_pathname, archive_entry_size,
// archive_read_data`: `archive_read_next_header` takes `struct archive_entry **` and
// cannot bind, and appending `archive_read_data` over the gap would read data from a
// stream whose header was never read - B66's structurally-right-and-semantically-dead
// harness, arriving through the mechanism meant to add depth.
if !holds_a_handle(params, &locals) {
break;
}
let analysis = signature::analyze_named(name, params, &BTreeSet::new());
let filled = filled_locals(params, &analysis.roles, declared);
// The record a macro-stated size can be read off is the FIRST context this plan
// declared for itself. A produced handle is excluded by construction: the macro spells
// the record by value and the harness only has the object for one it declared.
let mut scope = Scope {
vocabulary,
sizable: ordered
.iter()
.find(|(_, held)| !held.by_value)
.map(|(handle, held)| (handle.clone(), held.local.clone())),
first: allocated,
contexts: locals.len() + opened,
statements: Vec::new(),
buffers: Vec::new(),
declared: BTreeMap::new(),
};
let Some(args) = bind_step(params, &analysis, &locals, &filled, Some(&mut scope)) else {
break;
};
if !args.iter().all(is_replayable_value) {
break;
}
let Scope {
statements,
buffers,
declared: opened_here,
..
} = scope;
opened += opened_here.len();
declared += filled.len();
let mut preamble = filled_declarations(&filled);
preamble.extend(statements);
// Freed on the step that allocated it rather than at the end of the harness, because a
// step is dropped whole when a later one is rejected and the free has to go with it.
let releases: Vec<Stmt> = buffers
.iter()
.rev()
.map(|local| Stmt::FreeSized {
local: local.clone(),
})
.collect();
allocated += buffers.len();
steps.push(Extension {
function: name.clone(),
declares: preamble,
call: Stmt::Call {
function: name.clone(),
args,
capture: None,
},
releases,
});
}
steps
}
// Split out of `upward_steps` because a step's binding needs a `&mut Scope` threaded through
// every parameter in turn, and a `map` closure cannot hold that borrow across iterations.
fn bind_step(
params: &[Param],
analysis: &Analysis,
locals: &BTreeMap<String, Held>,
filled: &BTreeMap<usize, (String, String)>,
scope: Option<&mut Scope>,
) -> Option<Vec<Value>> {
let mut sizing = scope;
let mut args = Vec::with_capacity(params.len());
for (index, (param, role)) in params.iter().zip(&analysis.roles).enumerate() {
let bound = bind(
index,
param,
*role,
locals,
filled,
analysis,
sizing.as_deref_mut(),
);
args.push(bound.ok()?);
}
Some(args)
}
// An extension is a COPY of a call the author wrote, so every argument has to be something
// the harness already holds: a handle, the fuzzer's own bytes, or a buffer the harness itself
// allocated and can state the size of. `Value::Zero` is the pinned Config - a number the
// headers never state - and it is what the census caught. libjpeg-turbo's tail is the only
// place any step was found at all, and all four of them were Config-bearing: the author writes
// `tj3Set(handle, TJPARAM_SCANLIMIT, 500)` and this rule would write `tj3Set(ctx, 0, 0)`, which
// is a different program wearing the same function name. `tj3SetScalingFactor` is worse - its
// second parameter is a struct BY VALUE, so the invented 0 does not even compile.
//
// This is the same line `replay_setup` already draws on the setup side, where a call is copied
// only when every parameter is a handle we hold, and it is why `png_sig_cmp(data, 0, 8)` is
// never guessed at. An allow-list rather than a deny-list, so a new `Value` variant has to be
// ruled on here instead of defaulting into an author's call it was never measured against.
fn is_replayable_value(value: &Value) -> bool {
match value {
Value::Data { .. }
| Value::Size
| Value::Cursor
| Value::NulTerminated
| Value::OutBuffer { .. }
| Value::OutCapacity
| Value::AuxBuffer { .. }
| Value::AuxCapacity
| Value::SizedBuffer { .. }
| Value::Stated(_)
| Value::Local(_)
| Value::AddressOf(_)
| Value::AddressOfField { .. } => true,
Value::Zero | Value::Null | Value::Literal(_) | Value::Callback(_) => false,
}
}
fn holds_a_handle(params: &[Param], locals: &BTreeMap<String, Held>) -> bool {
params.iter().any(|param| {
handle_key(¶m.spelling, ¶m.shape).is_some_and(|handle| locals.contains_key(&handle))
})
}
// Where a further call goes: after the entry point and after the statement that discards its
// result, but BEFORE the teardowns. Appending to the end instead would hand every step a
// handle the plan has already freed, which is a use-after-free reported inside the library.
fn insertion_point(plan: &HarnessPlan) -> usize {
let entry = plan.body.iter().position(
|statement| matches!(statement, Stmt::Call { function, .. } if function == &plan.entry),
);
let Some(entry) = entry else {
return plan.body.len();
};
let after = entry + 1;
match plan.body.get(after) {
Some(Stmt::Discard { local }) if local == RESULT_LOCAL => after + 1,
_ => after,
}
}
// Rebuilt through `with` rather than cloned and spliced, so the four scaffolding flags are
// derived from the finished body exactly as they are for a plan that was never extended. A
// step that binds the corpus or an output buffer therefore brings its own scaffolding with it.
#[must_use]
pub fn extend(plan: &HarnessPlan, steps: &[Extension]) -> HarnessPlan {
let mut built = HarnessPlan::new(plan.entry.clone());
built.includes.clone_from(&plan.includes);
built.replayed.clone_from(&plan.replayed);
built.extended = plan
.extended
.iter()
.cloned()
.chain(steps.iter().map(|step| step.function.clone()))
.collect();
for stub in &plan.callbacks {
built = built.with_callback(stub.clone());
}
let cut = insertion_point(plan);
for statement in &plan.body[..cut] {
built = built.with(statement.clone());
}
for step in steps {
for declaration in &step.declares {
built = built.with(declaration.clone());
}
built = built.with(step.call.clone());
for release in &step.releases {
built = built.with(release.clone());
}
}
for statement in &plan.body[cut..] {
built = built.with(statement.clone());
}
built
}
pub fn plan_candidate(
candidate: &Candidate,
include: &str,
vocabulary: &Vocabulary,
) -> Result<Vec<HarnessPlan>, Refusal> {
plan_candidate_with(candidate, include, vocabulary, &[])
}
pub fn plan_candidate_with(
candidate: &Candidate,
include: &str,
vocabulary: &Vocabulary,
setup: &[String],
) -> Result<Vec<HarnessPlan>, Refusal> {
admissible(candidate)?;
returns_releasable_memory(candidate, vocabulary)?;
let Contexts {
locals,
ordered,
opening,
} = resolve_contexts(candidate, vocabulary)?;
let filled = filled_locals(&candidate.params, &candidate.analysis.roles, 0);
let args = bind_all(candidate, &locals, &filled)?;
let mut emitted = BTreeSet::new();
let mut base = HarnessPlan::new(candidate.name.clone()).with_include(include);
for stub in callback_stubs(candidate) {
base = base.with_callback(stub);
}
if let Some(statement) = indirect_extent_local(candidate) {
base = base.with(statement);
}
for statement in filled_declarations(&filled) {
base = base.with(statement);
}
for statement in opening {
if let Stmt::Call { function, .. } = &statement {
emitted.insert(function.clone());
}
base = base.with(statement);
}
// Populating a field only means anything on a record the harness itself declared. A
// produced handle is opaque by construction and its interior belongs to the library.
let bindings = ordered
.first()
.filter(|(_, held)| !held.by_value)
.map(|(handle, _)| field_bindings(handle, vocabulary))
.unwrap_or_default();
let teardowns: Vec<(String, Value)> = ordered
.iter()
.flat_map(|(handle, held)| teardown_calls(handle, held, &candidate.name, vocabulary))
.collect();
// A teardown that the author happened to write BEFORE the entry point must not be
// replayed as setup: it is already scheduled after the call, and running it twice is a
// double free reported inside the library.
emitted.extend(teardowns.iter().map(|(function, _)| function.clone()));
let setup = replay_setup(setup, &candidate.name, &locals, &emitted, vocabulary);
let replayed: Vec<String> = setup
.iter()
.filter_map(|statement| match statement {
Stmt::Call { function, .. } => Some(function.clone()),
_ => None,
})
.collect();
let call = |plan: HarnessPlan| -> HarnessPlan {
let mut plan = plan;
plan.replayed.clone_from(&replayed);
for statement in &setup {
plan = plan.with(statement.clone());
}
let capture = match candidate.result.shape {
Shape::Void | Shape::Other => None,
_ => Some(Binding {
ty: candidate.result.spelling.clone(),
name: RESULT_LOCAL.to_owned(),
}),
};
let captured = capture.is_some();
let mut plan = plan.with(Stmt::Call {
function: candidate.name.clone(),
args: args.clone(),
capture,
});
if captured {
plan = plan.with(Stmt::Discard {
local: RESULT_LOCAL.to_owned(),
});
}
// An allocating context with no teardown reports a LeakSanitizer error inside the
// target on every direct replay, which reads as a crash in the library.
for (function, target) in &teardowns {
plan = plan.with(Stmt::Call {
function: function.clone(),
args: vec![target.clone()],
capture: None,
});
}
plan
};
let plans: Vec<HarnessPlan> = variant_masks(bindings.len())
.into_iter()
.map(|mask| {
let mut plan = base.clone();
for (index, (field, macro_name)) in bindings.iter().enumerate() {
if mask & (1 << index) == 0 {
continue;
}
plan = plan.with(Stmt::SetField {
local: CONTEXT_LOCAL.to_owned(),
field: field.clone(),
value: Value::Literal(macro_name.clone()),
});
}
call(plan)
})
.collect();
// Every variant shares the same arguments and the same replayed setup, so they either
// all reach the library with the corpus or none of them does. Asserted over all of
// them anyway, because a variant differing here would mean the mask changed an
// argument, and that is a defect worth failing on rather than shipping.
if !plans.iter().all(HarnessPlan::binds_corpus) {
return Err(Refusal::CorpusNeverBound);
}
Ok(plans)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::emit;
use lisdex_surface::extract::{Field, Record};
use lisdex_surface::rank::Complexity;
use lisdex_surface::signature::{Analysis, Returns};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
fn call_in(plan: &HarnessPlan) -> &Stmt {
plan.body
.iter()
.find(|statement| {
matches!(statement, Stmt::Call { function, .. } if function == &plan.entry)
})
.expect("the plan calls the entry point")
}
// B87. Each condition of the scalar-slot rule gets its own test, because the two guards have
// NO isolating control on any real tree: `strides` and `dstSizes` sit in signatures whose
// EARLIER parameter (`dstPlanes`, or a leftover extent `n`) refuses first, so gutting the
// plural guard reddens nothing end to end. That is B73's situation exactly - the gate tests
// the rule whole and the halves are isolated here.
fn scalar_ptr(name: &str, spelling: &str) -> Param {
param(
name,
spelling,
Shape::Pointer {
pointee: Pointee::Integral,
is_const: false,
},
)
}
#[test]
fn a_scalar_the_library_writes_is_a_slot_the_harness_declares() {
assert!(is_scalar_slot(&scalar_ptr("width", "int *")));
assert_eq!(
filled_by_library(&scalar_ptr("width", "int *")),
Some("int".to_owned())
);
}
// `int *const width` is a const POINTER to a mutable int - libwebp's VP8GetInfo and
// VP8LGetInfo spell it that way and their WebPDecode* siblings do not.
#[test]
fn a_const_pointer_to_a_mutable_scalar_is_still_a_slot() {
assert_eq!(
filled_by_library(&scalar_ptr("width", "int *const")),
Some("int".to_owned())
);
}
// The guard that keeps `tj3Decompress12`'s `short *dstBuf` out. Handing a destination image
// buffer one stack `short` is an out-of-bounds write this harness manufactured.
#[test]
fn a_scalar_pointer_named_for_an_output_is_memory_and_is_refused() {
assert!(!is_scalar_slot(&scalar_ptr("dstBuf", "short *")));
assert!(filled_by_library(&scalar_ptr("dstBuf", "short *")).is_none());
}
// The guard that keeps `strides` and `dstSizes` out: one element per plane, per image.
#[test]
fn a_plural_scalar_pointer_is_an_array_and_is_refused() {
assert!(!is_scalar_slot(&scalar_ptr("strides", "int *")));
assert!(!is_scalar_slot(&scalar_ptr("dstSizes", "unsigned long *")));
assert!(names_many("strides"));
assert!(!names_many("stride"));
}
// Biased on purpose: a singular name misread as plural is only refused, which costs reach;
// a plural one missed is an out-of-bounds write.
#[test]
fn the_plural_test_errs_toward_refusing() {
assert!(!names_many("has_alpha"));
assert!(!names_many("width"));
assert!(names_many("axis"));
}
#[test]
fn a_byte_pointer_is_never_a_scalar_slot() {
for pointee in [Pointee::UnsignedChar, Pointee::Char, Pointee::Void] {
let shape = Shape::Pointer {
pointee,
is_const: false,
};
assert!(!is_scalar_slot(¶m("out", "char *", shape)));
}
}
#[test]
fn a_const_scalar_pointer_is_an_input_not_a_slot() {
let shape = Shape::Pointer {
pointee: Pointee::Integral,
is_const: true,
};
assert!(!is_scalar_slot(¶m("width", "const int *", shape)));
}
// A record slot is a POINTER and starts NULL; a scalar slot is a value and starts zeroed.
// `int lisdex_filled = NULL;` is a constraint violation, not a slower way of saying zero.
#[test]
fn a_scalar_slot_is_zeroed_while_a_record_slot_is_nulled() {
let mut filled = BTreeMap::new();
filled.insert(0, ("int".to_owned(), "a".to_owned()));
filled.insert(1, ("struct archive_entry *".to_owned(), "b".to_owned()));
let declared = filled_declarations(&filled);
assert_eq!(
declared,
vec![
Stmt::Declare {
ty: "int".to_owned(),
name: "a".to_owned(),
init: Init::ZeroBytes,
},
Stmt::Declare {
ty: "struct archive_entry *".to_owned(),
name: "b".to_owned(),
init: Init::Null,
},
]
);
}
fn byte_ptr_return(spelling: &str) -> Returns {
Returns {
spelling: spelling.to_owned(),
shape: Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: false,
},
}
}
// Reproduces the measurement, not a guess about it: the emitted `WebPDecodeRGBA(data, size,
// &w, &h)` was structurally perfect and LeakSanitizer still reported `Direct leak of 4096
// byte(s)` inside `WebPAllocateDecBuffer` on every valid seed.
#[test]
fn an_entry_point_that_hands_back_library_memory_is_refused() {
let got = returns_releasable_memory(
&candidate(
"WebPDecodeRGBA",
vec![
param(
"data",
"const uint8_t *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
byte_ptr_return("uint8_t *"),
),
&Vocabulary::default(),
);
assert!(
matches!(got, Err(Refusal::UnreleasedReturn { .. })),
"a leaking return was allowed through: {got:?}"
);
}
// The paired positive control, and it is the design rather than decoration: an `Into`-style
// decoder returns the caller's OWN buffer, so refusing every byte-pointer return would take
// `WebPDecodeRGBAInto` and its four siblings with it - all of which survive the oracles today.
#[test]
fn an_entry_point_that_hands_back_the_callers_own_buffer_still_plans() {
let got = returns_releasable_memory(
&candidate(
"WebPDecodeRGBAInto",
vec![
param(
"data",
"const uint8_t *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
param(
"output_buffer",
"uint8_t *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: false,
},
),
],
vec![ParamRole::Buffer, ParamRole::Length, ParamRole::Output],
Fuzzability::DirectBuffer,
byte_ptr_return("uint8_t *"),
),
&Vocabulary::default(),
);
assert!(got.is_ok(), "the caller's own buffer was read as a leak");
}
// `WebPGetInfo` returns an int and owns nothing, which is what leaves B87 any reach at all.
#[test]
fn a_scalar_return_owns_nothing_and_is_not_refused() {
let got = returns_releasable_memory(
&candidate(
"WebPGetInfo",
vec![
param(
"data",
"const uint8_t *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns {
spelling: "int".to_owned(),
shape: Shape::Integral,
},
),
&Vocabulary::default(),
);
assert!(got.is_ok(), "an int return was read as owned memory");
}
fn param(name: &str, spelling: &str, shape: Shape) -> Param {
Param {
name: Some(name.to_owned()),
spelling: spelling.to_owned(),
shape,
}
}
// These fixtures hand-write their role vector to isolate BINDING, so they need an
// extent map to match. Nearest-Length is enough for shapes this simple; the assignment
// rule itself is measured in lisdex-surface, not here.
fn nearest_extents(roles: &[ParamRole]) -> BTreeMap<usize, usize> {
let mut extents = BTreeMap::new();
let mut claimed: BTreeSet<usize> = BTreeSet::new();
for (index, role) in roles.iter().enumerate() {
if !matches!(role, ParamRole::Buffer | ParamRole::Output) {
continue;
}
let found = [index.saturating_add(1), index.wrapping_sub(1)]
.into_iter()
.find(|near| {
roles.get(*near) == Some(&ParamRole::Length) && !claimed.contains(near)
});
if let Some(extent) = found {
extents.insert(index, extent);
claimed.insert(extent);
}
}
extents
}
fn candidate(
name: &str,
params: Vec<Param>,
roles: Vec<ParamRole>,
fuzzability: Fuzzability,
result: Returns,
) -> Candidate {
let extents = nearest_extents(&roles);
Candidate {
name: name.to_owned(),
params,
result,
header: PathBuf::from("png.h"),
line: 1,
fuzzability,
analysis: Analysis {
fuzzability,
roles,
context_args: 1,
extents,
},
complexity: Complexity::default(),
exported: true,
reachable_from_harness: false,
score: 1.0,
reasons: Vec::new(),
}
}
fn opaque_handle_entry(name: &str) -> Candidate {
candidate(
name,
vec![
param(
"handle",
"tjhandle",
Shape::Pointer {
pointee: Pointee::Void,
is_const: false,
},
),
param(
"jpegBuf",
"const unsigned char *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("jpegSize", "size_t", Shape::Integral),
],
vec![ParamRole::Context, ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns::default(),
)
}
fn handle_vocabulary(producers: &[(&str, Vec<Param>)]) -> Vocabulary {
Vocabulary {
producers: BTreeMap::from([(
"tjhandle".to_owned(),
producers
.iter()
.map(|(name, params)| ((*name).to_owned(), params.clone()))
.collect(),
)]),
..Vocabulary::default()
}
}
fn producer_in(plan: &HarnessPlan) -> String {
let Some(Stmt::Call { function, .. }) = plan.body.first() else {
panic!("the plan opens with the producer call")
};
function.clone()
}
fn archive_open(buffer: Param) -> Candidate {
candidate(
"archive_read_open_memory",
vec![
param(
"a",
"struct archive *",
Shape::Pointer {
pointee: Pointee::Record("archive".to_owned()),
is_const: false,
},
),
buffer,
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Context, ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns::default(),
)
}
fn archive_vocabulary() -> Vocabulary {
Vocabulary {
producers: BTreeMap::from([(
"archive".to_owned(),
BTreeMap::from([("archive_read_new".to_owned(), Vec::new())]),
)]),
..Vocabulary::default()
}
}
fn archive_handle() -> Param {
param(
"a",
"struct archive *",
Shape::Pointer {
pointee: Pointee::Record("archive".to_owned()),
is_const: false,
},
)
}
// The replay vocabulary of libarchive's own tar target, cut down to the shapes that
// decide each rule: two registrations that bind, one call that takes a string and so
// cannot, and a destructor that is plumbing-shaped and must never be replayed.
fn replayable_archive_vocabulary() -> Vocabulary {
let mut vocabulary = archive_vocabulary();
vocabulary.functions = BTreeMap::from([
(
"archive_read_support_format_tar".to_owned(),
vec![archive_handle()],
),
(
"archive_read_support_filter_all".to_owned(),
vec![archive_handle()],
),
(
"archive_read_set_options".to_owned(),
vec![
archive_handle(),
param(
"opts",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
],
),
// Declared, plumbing-shaped, and takes a handle this plan does NOT hold. It is
// the only call the binding rule alone can stop: an undeclared name is already
// stopped by the vocabulary lookup, so a fixture of `memcpy` and `png_sig_cmp`
// alibis the rule completely. Passing NULL here would be a crash inside the
// library that the harness manufactured - the D12 class.
(
"archive_entry_clear".to_owned(),
vec![param(
"entry",
"struct archive_entry *",
Shape::Pointer {
pointee: Pointee::Record("archive_entry".to_owned()),
is_const: false,
},
)],
),
("archive_read_new".to_owned(), Vec::new()),
("archive_read_free".to_owned(), vec![archive_handle()]),
("archive_read_finish".to_owned(), vec![archive_handle()]),
// The one shape an upward step can legitimately be built from: our handle, a
// buffer the HARNESS allocated, and the capacity it declared. Its roles come from
// the real grader here rather than from a fixture, because an extension is bound
// by the same `bind` the entry point is and nothing hand-writes roles for it.
(
"archive_read_data".to_owned(),
vec![
archive_handle(),
param(
"buff",
"void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: false,
},
),
param("len", "size_t", Shape::Integral),
],
),
]);
// TWO destructors, and the plan only schedules one. Keyed on a single destructor
// the teardown guard could be gutted with every test still green, because the one
// name it had to catch was already in `emitted` for a different reason - the two
// guards alibied each other. `archive_read_finish` is the one only this rule stops.
vocabulary.destructors = BTreeMap::from([(
"archive".to_owned(),
BTreeSet::from([
"archive_read_free".to_owned(),
"archive_read_finish".to_owned(),
]),
)]);
vocabulary
}
fn open_memory() -> Candidate {
archive_open(param(
"buff",
"const void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
))
}
fn replayed_calls(sequence: &[&str]) -> Vec<String> {
let owned: Vec<String> = sequence.iter().map(|call| (*call).to_owned()).collect();
plan_candidate_with(
&open_memory(),
"archive.h",
&replayable_archive_vocabulary(),
&owned,
)
.unwrap()[0]
.replayed
.clone()
}
// B66: the emitted harness was structurally right and semantically dead - no format
// registered, so `archive_read_open_memory` returned ARCHIVE_FATAL at full exec rate
// with a bitmap that never grew past handle plumbing. The author's own target says
// which registrations have to come first.
#[test]
fn the_authors_registrations_are_replayed_before_the_entry_point() {
assert_eq!(
replayed_calls(&[
"archive_read_new",
"archive_read_support_format_tar",
"archive_read_support_filter_all",
"archive_read_open_memory",
]),
[
"archive_read_support_format_tar",
"archive_read_support_filter_all"
],
"archive_read_new is the producer this plan already called"
);
}
// Only one of libarchive's 25 targets calls `archive_read_open_memory`; the rest reach
// the reader through `archive_read_open` and a callback. Cutting at our own entry would
// have found nothing to replay for the entry the M3 gate asserts ranks first.
#[test]
fn setup_transfers_from_a_target_that_never_calls_our_entry_point() {
assert_eq!(
replayed_calls(&[
"archive_read_new",
"archive_read_support_format_tar",
"archive_read_support_filter_all",
"archive_read_open",
]),
[
"archive_read_support_format_tar",
"archive_read_support_filter_all"
]
);
}
// The run ends at the first call that takes something other than a handle, because
// that is the call the author hands the input to. Everything past it is what they did
// with the result.
#[test]
fn the_replay_stops_at_the_first_call_that_is_not_plumbing() {
assert_eq!(
replayed_calls(&[
"archive_read_new",
"archive_read_support_format_tar",
"archive_read_set_options",
"archive_read_support_filter_all",
]),
["archive_read_support_format_tar"],
"the filter registration sits past the cut and must not be replayed"
);
}
// A destructor takes one handle and is therefore plumbing-shaped. Measured on zlib's
// `examples/gun.c`, which put `inflateBackEnd` into the opening run.
#[test]
fn a_destructor_in_the_opening_run_is_never_replayed_as_setup() {
assert_eq!(
replayed_calls(&[
"archive_read_new",
"archive_read_finish",
"archive_read_support_format_tar",
]),
["archive_read_support_format_tar"],
"replaying a destructor would tear the handle down before it was ever used"
);
}
#[test]
fn an_unknown_name_is_skipped_rather_than_guessed_at() {
assert!(
replayed_calls(&["memcpy", "png_sig_cmp", "archive_read_support_format_tar"])
.contains(&"archive_read_support_format_tar".to_owned()),
"an unknown name is skipped, not guessed at, and does not stop the run"
);
}
#[test]
fn a_call_taking_a_handle_this_plan_does_not_hold_is_left_alone() {
assert_eq!(
replayed_calls(&[
"archive_read_new",
"archive_entry_clear",
"archive_read_support_format_tar",
]),
["archive_read_support_format_tar"],
"handing it a NULL would be a crash inside the library that we manufactured"
);
}
#[test]
fn no_sequence_means_no_replay_and_the_plan_is_what_it_was() {
assert!(replayed_calls(&[]).is_empty());
}
fn upward_of(sequence: &[&str]) -> Vec<String> {
let owned: Vec<String> = sequence.iter().map(|call| (*call).to_owned()).collect();
upward_steps(
&open_memory(),
&replayable_archive_vocabulary(),
&sole(&owned),
)
.into_iter()
.map(|step| step.function)
.collect()
}
// B51(b), the accepting direction, and no tree in the validation set offers it: a call
// taking the handle we hold plus a buffer WE allocated and the capacity we declared. This
// is the shape that pays off - `archive_read_data` is where a libarchive harness stops
// being handle plumbing - and it is exactly what a real sequence would have to contain.
#[test]
fn the_authors_next_call_over_our_own_handle_is_appended_above_the_entry_point() {
assert_eq!(
upward_of(&[
"archive_read_new",
"archive_read_support_format_tar",
"archive_read_open_memory",
"archive_read_data",
]),
["archive_read_data"]
);
}
// The floor M5 step 4 established, stated as a property. `setup_run` deliberately scans
// the WHOLE sequence when the authors never name our entry point - that is why
// `archive_read_open_memory` replays six registrations mined from a target that calls
// `archive_read_open` instead - and the tail must NOT mirror that. If it did, the parent
// for oracle 3b would be a truncation of the author's program rather than an accepted
// harness, which is the prefix ladder this design rejects.
#[test]
fn an_entry_point_the_authors_never_call_has_no_upward_step() {
let sequence = &[
"archive_read_new",
"archive_read_support_format_tar",
"archive_read_open",
"archive_read_data",
];
assert!(
!replayed_calls(sequence).is_empty(),
"the setup side must still replay, or this proves nothing about the tail"
);
assert!(upward_of(sequence).is_empty());
}
// `archive_read_finish` takes our handle and binds perfectly, so nothing but the teardown
// guard stops it. The plan schedules `archive_read_free`, NOT this, and a teardown we do
// not schedule disposes of something we did not know we were holding - so it still ends
// the climb, taking every call written after it.
//
// `archive_read_data` BEHIND the teardown is the whole control and was put there by a
// gutting pass: with the teardown last, breaking on it and stepping over it both yield an
// empty list, so making the skip unconditional reddened nothing. A call after it is what
// makes the two outcomes different.
#[test]
fn a_teardown_the_plan_does_not_schedule_still_ends_the_climb() {
assert!(
upward_of(&[
"archive_read_new",
"archive_read_open_memory",
"archive_read_finish",
"archive_read_data",
])
.is_empty(),
"a teardown we never scheduled frees a handle every later step would use"
);
}
// B83. The miner flattens SOURCE order, so libarchive's early-return cleanup -
// `if (archive_read_open_memory(...) != ARCHIVE_OK) { archive_read_free(a); return 0; }` -
// lands between the opener and every call worth making. That free is the one this plan
// already schedules for the same handle, so it is not new knowledge and not a gap: skipping
// it leaves the single teardown the plan always emitted, at the end where it belongs.
#[test]
fn a_teardown_the_plan_already_schedules_is_stepped_over_rather_than_stopped_on() {
assert_eq!(
upward_of(&[
"archive_read_new",
"archive_read_open_memory",
"archive_read_free",
"archive_read_data",
]),
vec!["archive_read_data".to_owned()],
"the author's error-branch cleanup is not the end of their sequence"
);
}
// And the skip does not put a SECOND free in the harness - it drops the call entirely,
// because the plan's own teardown already covers that handle.
#[test]
fn stepping_over_a_scheduled_teardown_never_appends_it_as_a_step() {
assert!(
!upward_of(&[
"archive_read_new",
"archive_read_open_memory",
"archive_read_free",
"archive_read_data",
])
.contains(&"archive_read_free".to_owned())
);
}
// Isolates the handle requirement, and the case is lz4's real fuzzer: it calls
// `LZ4_decompress_safe_usingDict`, `LZ4_decompress_safe_partial` and
// `LZ4_decompress_safe_partial_usingDict` back to back over the same buffers. Every
// argument of the second call BINDS - the corpus, an out buffer, two capacities - so bind
// cannot stop it. Nothing threads state between them, so fusing them into one file would
// make a crash unattributable, and oracle 4 already keeps them as separate survivors.
#[test]
fn a_stateless_call_beside_ours_is_not_a_sequence_step() {
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.functions.insert(
"LZ4_decompress_safe_partial".to_owned(),
vec![
param(
"src",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
param(
"dst",
"char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: false,
},
),
param("srcSize", "int", Shape::Integral),
param("dstCapacity", "int", Shape::Integral),
],
);
// `archive_read_data` sits BEHIND the stateless call, so skipping instead of stopping
// would append it - a read from a stream the author had already advanced past.
let steps = upward_steps(
&open_memory(),
&vocabulary,
&sole(&[
"archive_read_open_memory".to_owned(),
"LZ4_decompress_safe_partial".to_owned(),
"archive_read_data".to_owned(),
]),
);
assert!(steps.is_empty(), "{steps:?}");
}
// The measured gap, and the reason the climb STOPS rather than skips. A call whose out-param
// the caller must SIZE cannot be copied - `unsigned char **planes` is an array of plane
// pointers the harness would have to allocate - and `archive_read_data` behind it would read
// from a stream whose header was never read.
#[test]
fn a_call_the_climb_cannot_copy_stops_it_rather_than_being_skipped() {
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.functions.insert(
"archive_read_planes".to_owned(),
vec![
archive_handle(),
param(
"planes",
"unsigned char **",
Shape::Pointer {
pointee: Pointee::Pointer(Box::new(Pointee::UnsignedChar)),
is_const: false,
},
),
],
);
let steps = upward_steps(
&open_memory(),
&vocabulary,
&sole(&[
"archive_read_open_memory".to_owned(),
"archive_read_planes".to_owned(),
"archive_read_data".to_owned(),
]),
);
assert!(steps.is_empty(), "{steps:?}");
}
// The same fixture with the ONE thing B81 changed: the target one indirection down is a
// record, so the library allocates it and the harness owns only the NULL local it passes the
// address of. Paired with the test above deliberately - the two differ in nothing but the
// inner pointee, so a rule that stopped asking the question would move both.
#[test]
fn the_climb_copies_a_call_whose_out_param_the_library_fills() {
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.functions.insert(
"archive_read_next_header".to_owned(),
vec![
archive_handle(),
param(
"entry",
"struct archive_entry **",
Shape::Pointer {
pointee: Pointee::Pointer(Box::new(Pointee::Record(
"archive_entry".to_owned(),
))),
is_const: false,
},
),
],
);
let steps = upward_steps(
&open_memory(),
&vocabulary,
&sole(&[
"archive_read_open_memory".to_owned(),
"archive_read_next_header".to_owned(),
]),
);
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(steps[0].function, "archive_read_next_header");
assert_eq!(
steps[0].declares,
vec![Stmt::Declare {
ty: "struct archive_entry *".to_owned(),
name: FILLED_LOCAL.to_owned(),
init: Init::Null,
}]
);
assert_eq!(
steps[0].call,
Stmt::Call {
function: "archive_read_next_header".to_owned(),
args: vec![
Value::Local("ctx".to_owned()),
Value::AddressOf(FILLED_LOCAL.to_owned()),
],
capture: None,
}
);
}
// The second half of `filled_by_library`, isolated. libpng writes `png_get_sPLT(..,
// png_sPLT_tpp entries)`, where the record IS behind two pointers but BOTH stars live inside
// the typedef, so removing one indirection from what the header wrote yields nothing to
// declare. A rule that answered the record question alone would emit a local it cannot spell.
#[test]
fn a_library_filled_out_param_whose_type_hides_both_stars_in_a_typedef_is_refused() {
let entries = param(
"entries",
"png_sPLT_tpp",
Shape::Pointer {
pointee: Pointee::Pointer(Box::new(Pointee::Record("png_sPLT_t".to_owned()))),
is_const: false,
},
);
assert_eq!(filled_by_library(&entries), None);
assert_eq!(
filled_locals(&[entries], &[ParamRole::Output], 0),
BTreeMap::new()
);
}
// The `standing` offset, isolated. The entry point already declares `lisdex_filled`, so the
// step has to declare `lisdex_filled1` - a second declaration of the same name in one block
// either shadows the slot the entry call still refers to or does not compile at all.
#[test]
fn a_step_numbers_its_filled_local_past_the_one_the_entry_point_declares() {
let entry_out = || {
param(
"first",
"struct archive_entry **",
Shape::Pointer {
pointee: Pointee::Pointer(Box::new(Pointee::Record(
"archive_entry".to_owned(),
))),
is_const: false,
},
)
};
let opener = candidate(
"archive_open_entry",
vec![
archive_handle(),
param(
"buff",
"const void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
entry_out(),
],
vec![
ParamRole::Context,
ParamRole::Buffer,
ParamRole::Length,
ParamRole::Context,
],
Fuzzability::CastBuffer,
Returns::default(),
);
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.functions.insert(
"archive_read_next_header".to_owned(),
vec![archive_handle(), entry_out()],
);
let sequence = [
"archive_open_entry".to_owned(),
"archive_read_next_header".to_owned(),
];
let plans = plan_candidate_with(&opener, "archive.h", &vocabulary, &sequence).unwrap();
assert!(
plans[0].body.contains(&Stmt::Declare {
ty: "struct archive_entry *".to_owned(),
name: FILLED_LOCAL.to_owned(),
init: Init::Null,
}),
"{:?}",
plans[0].body
);
let steps = upward_steps(&opener, &vocabulary, &sole(&sequence));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].declares,
vec![Stmt::Declare {
ty: "struct archive_entry *".to_owned(),
name: format!("{FILLED_LOCAL}1"),
init: Init::Null,
}]
);
let extended = extend(&plans[0], &steps);
assert_eq!(
extended
.body
.iter()
.filter(|statement| matches!(statement, Stmt::Declare { name, .. }
if name.starts_with(FILLED_LOCAL)))
.count(),
2,
"{:?}",
extended.body
);
}
// Isolates the invented-value ban. `archive_read_set_format(a, int)` takes our handle and
// every argument resolves - the Config pins to 0 - so both other gates pass it. The author
// wrote a format constant there; a 0 is a different program wearing the same name, and the
// census found this to be the ONLY shape any tail in the validation set offers:
// libjpeg-turbo's `tj3Set(handle, TJPARAM_SCANLIMIT, 500)` would have been emitted as
// `tj3Set(ctx, 0, 0)`, and `tj3SetScalingFactor`'s struct-by-value would not even compile.
#[test]
fn a_step_that_needs_an_invented_constant_is_not_appended() {
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.functions.insert(
"archive_read_set_format".to_owned(),
vec![archive_handle(), param("code", "int", Shape::Integral)],
);
assert!(
upward_steps(
&open_memory(),
&vocabulary,
&sole(&[
"archive_read_open_memory".to_owned(),
"archive_read_set_format".to_owned(),
]),
)
.is_empty()
);
}
#[test]
fn a_step_taking_a_string_is_not_appended_any_more_than_it_is_replayed() {
assert!(
upward_of(&[
"archive_read_open_memory",
"archive_read_set_options",
"archive_read_data",
])
.is_empty(),
"the climb stops at the first call it cannot copy, exactly as the replay does"
);
}
#[test]
fn the_climb_is_capped_however_long_the_tail_is() {
let mut vocabulary = replayable_archive_vocabulary();
let mut sequence = vec!["archive_read_open_memory".to_owned()];
for index in 0..MAX_UPWARD_STEPS + 3 {
let name = format!("archive_read_step{index}");
vocabulary
.functions
.insert(name.clone(), vec![archive_handle()]);
sequence.push(name);
}
assert_eq!(
upward_steps(&open_memory(), &vocabulary, &sole(&sequence)).len(),
MAX_UPWARD_STEPS
);
}
fn extended_body() -> HarnessPlan {
let plans = plan_candidate_with(
&open_memory(),
"archive.h",
&replayable_archive_vocabulary(),
&[
"archive_read_new".to_owned(),
"archive_read_open_memory".to_owned(),
"archive_read_data".to_owned(),
],
)
.unwrap();
let steps = upward_steps(
&open_memory(),
&replayable_archive_vocabulary(),
&sole(&[
"archive_read_open_memory".to_owned(),
"archive_read_data".to_owned(),
]),
);
assert_eq!(steps.len(), 1, "the fixture must offer exactly one step");
extend(&plans[0], &steps)
}
// Isolates the insertion point. Appending to the end of the body instead would put the
// step after `archive_read_free`, which is a use-after-free reported inside the library -
// the D12 fabricated-crash class, arriving through a mechanism meant to add reach.
#[test]
fn an_appended_call_lands_after_the_entry_and_before_the_teardown() {
let plan = extended_body();
let order: Vec<&str> = plan
.body
.iter()
.filter_map(|statement| match statement {
Stmt::Call { function, .. } => Some(function.as_str()),
_ => None,
})
.collect();
let entry = order
.iter()
.position(|call| *call == "archive_read_open_memory")
.unwrap();
let step = order
.iter()
.position(|call| *call == "archive_read_data")
.unwrap();
let teardown = order
.iter()
.position(|call| *call == "archive_read_free")
.unwrap();
assert!(entry < step && step < teardown, "{order:?}");
}
// The reason `extend` rebuilds through `with` rather than cloning and splicing: the step
// binds an out buffer the base plan never needed, and the four scaffolding flags are what
// make the emitter declare it, size it and free it. A spliced body would call the step
// with a variable that was never declared.
#[test]
fn an_appended_call_brings_its_own_scaffolding() {
let plan = extended_body();
assert!(plan.needs_out_buffer);
let rendered = emit::render(&plan, "extended.c");
let out = crate::plan::OUT_LOCAL;
assert!(rendered.contains(out), "{rendered}");
assert!(rendered.contains(&format!("free({out});")), "{rendered}");
}
#[test]
fn the_appended_names_are_recorded_apart_from_the_replayed_ones() {
let plan = extended_body();
assert_eq!(plan.extended, ["archive_read_data"]);
assert!(
!plan.replayed.contains(&"archive_read_data".to_owned()),
"a call the author made AFTER the entry point is not setup"
);
}
// Isolates `is_configuration_shape`, the single test behind both halves of the ladder.
#[test]
fn a_call_taking_only_handles_configures_and_one_taking_a_buffer_does_not() {
assert!(is_configurator(&candidate(
"archive_read_support_format_tar",
vec![archive_handle()],
vec![ParamRole::Context],
Fuzzability::NoInput,
Returns::default(),
)));
assert!(!is_configurator(&open_memory()));
}
#[test]
fn a_filesystem_verb_over_a_void_buffer_is_not_a_path() {
// This is libarchive's ground-truth #1 and the M3 gate asserts it ranks first.
// Refusing it on the word "open" cost five entry points and the whole library.
let plans = plan_candidate(
&archive_open(param(
"buff",
"const void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
)),
"archive.h",
&archive_vocabulary(),
)
.unwrap();
assert_eq!(producer_in(&plans[0]), "archive_read_new");
}
#[test]
fn a_filesystem_verb_over_a_char_buffer_is_still_refused() {
assert_eq!(
plan_candidate(
&archive_open(param(
"path",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
)),
"archive.h",
&archive_vocabulary(),
),
Err(Refusal::FilesystemVerb {
verb: "open".to_owned()
}),
"zlib's gzopen created and TRUNCATED files named by corpus bytes"
);
}
// `archive_read_data(struct archive *, void *, size_t)` is the shape that shipped. Its
// handle is a stream record so the signature grades StreamDriven, which says the corpus
// arrives through some OTHER call - and nothing made the replay bring one. Every
// argument then resolved: a produced handle, an out buffer the harness allocated, and
// the capacity it allocated. The emitted C referenced neither `data` nor `size`.
fn archive_read_data() -> Candidate {
candidate(
"archive_read_data",
vec![
param(
"a",
"struct archive *",
Shape::Pointer {
pointee: Pointee::Record("archive".to_owned()),
is_const: false,
},
),
param(
"buff",
"void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: false,
},
),
param("len", "size_t", Shape::Integral),
],
vec![ParamRole::Context, ParamRole::Output, ParamRole::Length],
Fuzzability::StreamDriven,
Returns::default(),
)
}
#[test]
fn a_plan_whose_every_argument_resolves_is_still_refused_when_none_of_them_is_the_corpus() {
assert_eq!(
plan_candidate(&archive_read_data(), "archive.h", &archive_vocabulary()),
Err(Refusal::CorpusNeverBound),
"this planned and EMITTED at 7f1bb283: six format registrations, an out buffer, \
and an entry call that never saw the fuzzer's bytes"
);
}
// The isolating control for the rule above. Refusing on "the signature has an Output"
// or on "the candidate is StreamDriven" would reject this too, and this is the entry
// point the M3 gate asserts ranks first - so the two tests only pass together if the
// rule is keyed on the assembled body rather than on the shape.
#[test]
fn the_same_handle_and_the_same_stream_still_plan_when_one_argument_is_the_corpus() {
let plans = plan_candidate(
&archive_open(param(
"buff",
"const void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
)),
"archive.h",
&archive_vocabulary(),
)
.unwrap();
assert!(
plans[0].binds_corpus(),
"archive_read_open_memory hands the library `data` and must not be refused"
);
}
#[test]
fn a_typedef_hiding_a_void_pointer_is_keyed_on_the_typedef_not_the_void() {
let plans = plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[("tjInitDecompress", Vec::new())]),
)
.unwrap();
assert_eq!(producer_in(&plans[0]), "tjInitDecompress");
}
#[test]
fn a_matching_polarity_outranks_a_neutral_producer_with_a_shorter_name() {
// Both share exactly one leading word with tj3DecompressHeader, because the 3
// splits off, so affinity ties and the shorter tjInitTransform used to win.
let plans = plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[
("tjInitTransform", Vec::new()),
("tjInitDecompress", Vec::new()),
]),
)
.unwrap();
assert_eq!(
producer_in(&plans[0]),
"tjInitDecompress",
"a decompress entry point handed a transform handle decodes nothing"
);
}
#[test]
fn the_opposite_polarity_is_never_chosen_even_when_it_is_the_only_producer() {
assert_eq!(
plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[("tjInitCompress", Vec::new())]),
),
Err(Refusal::NoProducer {
handle: "tjhandle".to_owned()
}),
"archive_match_new SIGSEGVd on every input because the read-side vtable was never installed"
);
}
#[test]
fn a_producer_that_consumes_the_handle_it_returns_is_not_a_constructor() {
// XML_ExternalEntityParserCreate returns an XML_Parser and takes one, and sorts
// first among its four producers, so without the guard this recurses forever.
let rebinder = vec![param(
"parent",
"tjhandle",
Shape::Pointer {
pointee: Pointee::Void,
is_const: false,
},
)];
assert_eq!(
plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[("tjCloneDecompress", rebinder)]),
),
Err(Refusal::NoProducer {
handle: "tjhandle".to_owned()
})
);
}
#[test]
fn a_producer_that_opens_a_file_is_not_driveable_from_memory() {
assert_eq!(
plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[(
"tjOpenDecompress",
vec![param(
"path",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
)],
)]),
),
Err(Refusal::NoProducer {
handle: "tjhandle".to_owned()
}),
"zlib's gz* family already proved what corpus bytes reaching an opener do"
);
}
#[test]
fn a_producer_needing_an_integer_mode_is_refused_rather_than_guessed() {
assert_eq!(
plan_candidate(
&opaque_handle_entry("tj3DecompressHeader"),
"turbojpeg.h",
&handle_vocabulary(&[
("tj3Init", vec![param("initType", "int", Shape::Integral)],)
]),
),
Err(Refusal::ProducerNeedsConstant {
producer: "tj3Init".to_owned(),
param: "initType".to_owned(),
}),
"tj3Init's initType selects compress versus decompress and the headers cannot say which"
);
}
fn png_image_vocabulary() -> Vocabulary {
Vocabulary {
macros: BTreeSet::from(["PNG_IMAGE_VERSION".to_owned(), "PNG_FORMAT_RGBA".to_owned()]),
records: BTreeMap::from([(
"png_image".to_owned(),
Record {
spelling: "png_image".to_owned(),
fields: vec![
Field {
name: "opaque".to_owned(),
spelling: "png_controlp".to_owned(),
shape: Shape::Pointer {
pointee: Pointee::Record("png_control".to_owned()),
is_const: false,
},
},
Field {
name: "version".to_owned(),
spelling: "png_uint_32".to_owned(),
shape: Shape::Integral,
},
],
},
)]),
..Vocabulary::default()
}
}
fn begin_read() -> Candidate {
candidate(
"png_image_begin_read_from_memory",
vec![
param(
"image",
"png_imagep",
Shape::Pointer {
pointee: Pointee::Record("png_image".to_owned()),
is_const: false,
},
),
param(
"memory",
"png_const_voidp",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Context, ParamRole::Buffer, ParamRole::Length],
Fuzzability::CastBuffer,
Returns {
spelling: "int".to_owned(),
shape: Shape::Integral,
},
)
}
#[test]
fn the_version_field_binds_to_its_macro_by_name_affinity() {
assert_eq!(
macro_for_field("png_image", "version", &png_image_vocabulary()),
Some("PNG_IMAGE_VERSION".to_owned())
);
}
#[test]
fn a_field_with_no_matching_macro_binds_to_nothing() {
assert_eq!(
macro_for_field("png_image", "height", &png_image_vocabulary()),
None
);
}
#[test]
fn macro_affinity_is_case_insensitive_on_the_record_name() {
let mut vocab = png_image_vocabulary();
vocab.macros.insert("Z_STREAM_VERSION".to_owned());
assert_eq!(
macro_for_field("z_stream", "version", &vocab),
Some("Z_STREAM_VERSION".to_owned())
);
}
#[test]
fn the_struct_entry_produces_a_populated_variant_first() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
assert_eq!(plans.len(), 2);
assert!(plans[0].body.contains(&Stmt::SetField {
local: CONTEXT_LOCAL.to_owned(),
field: "version".to_owned(),
value: Value::Literal("PNG_IMAGE_VERSION".to_owned()),
}));
}
#[test]
fn the_unpopulated_variant_is_kept_so_the_oracle_can_choose() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
assert!(
!plans[1]
.body
.iter()
.any(|s| matches!(s, Stmt::SetField { .. }))
);
}
#[test]
fn the_context_is_a_zeroed_stack_local_passed_by_address() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
assert_eq!(
plans[0].body[0],
Stmt::Declare {
ty: "png_image".to_owned(),
name: CONTEXT_LOCAL.to_owned(),
init: Init::ZeroBytes,
}
);
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::AddressOf(CONTEXT_LOCAL.to_owned()));
}
#[test]
fn the_buffer_is_cast_and_the_length_is_the_size() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
args[1],
Value::Data {
cast: Some("const void *".to_owned())
},
"the cast is built from the resolved Shape, never from the typedef spelling"
);
assert_eq!(args[2], Value::Size);
}
#[test]
fn a_non_void_result_is_captured() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
let Stmt::Call { capture, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
capture.as_ref().map(|binding| binding.ty.as_str()),
Some("int")
);
}
#[test]
fn two_distinct_record_contexts_get_two_distinct_locals() {
let mut vocab = png_image_vocabulary();
vocab.records.insert(
"big_out".to_owned(),
Record {
spelling: "struct big_out".to_owned(),
fields: vec![Field {
name: "bytes".to_owned(),
spelling: "unsigned char[256]".to_owned(),
shape: Shape::Other,
}],
},
);
let two = candidate(
"two_parse",
vec![
param(
"small",
"png_imagep",
Shape::Pointer {
pointee: Pointee::Record("png_image".to_owned()),
is_const: false,
},
),
param(
"out",
"struct big_out *",
Shape::Pointer {
pointee: Pointee::Record("big_out".to_owned()),
is_const: false,
},
),
param(
"d",
"const void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
),
param("n", "size_t", Shape::Integral),
],
vec![
ParamRole::Context,
ParamRole::Output,
ParamRole::Buffer,
ParamRole::Length,
],
Fuzzability::CastBuffer,
Returns::default(),
);
let plans = plan_candidate(&two, "x.h", &vocab).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_ne!(
args[0], args[1],
"passing one local's address as two different record types produced a real ASAN stack-buffer-overflow blamed on the library"
);
let declared: Vec<&Stmt> = plans[0]
.body
.iter()
.filter(|s| matches!(s, Stmt::Declare { .. }))
.collect();
assert_eq!(declared.len(), 2);
}
#[test]
fn a_context_that_is_not_a_record_pointer_is_refused() {
let mut with_int_out = begin_read();
with_int_out.params[0] = param(
"outlen",
"int *",
Shape::Pointer {
pointee: Pointee::Integral,
is_const: false,
},
);
assert!(matches!(
plan_candidate(&with_int_out, "png.h", &png_image_vocabulary()),
Err(Refusal::UnsupportedShape { .. })
));
}
#[test]
fn a_record_declares_itself_with_the_spelling_not_the_lookup_key() {
let mut vocab = png_image_vocabulary();
vocab.records.get_mut("png_image").unwrap().spelling = "struct png_image".to_owned();
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
assert_eq!(
plans[0].body[0],
Stmt::Declare {
ty: "struct png_image".to_owned(),
name: CONTEXT_LOCAL.to_owned(),
init: Init::ZeroBytes,
}
);
}
#[test]
fn a_char_buffer_is_nul_terminated_not_handed_the_raw_testcase() {
let dated = candidate(
"archive_parse_date",
vec![
param("now", "time_t", Shape::Integral),
param(
"datestr",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
],
vec![ParamRole::Length, ParamRole::Buffer],
Fuzzability::CastBuffer,
Returns::default(),
);
let plans = plan_candidate(&dated, "archive.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
args[1],
Value::NulTerminated,
"handing the raw AFL testcase to a const char* made libarchive read past the poisoned tail and ASAN blamed libarchive"
);
assert!(plans[0].needs_nul_copy);
}
#[test]
fn a_byte_buffer_still_gets_the_raw_testcase_with_no_copy() {
let decode = candidate(
"decode",
vec![
param(
"data",
"const unsigned char *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("len", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns::default(),
);
let plans = plan_candidate(&decode, "x.h", &Vocabulary::default()).unwrap();
assert!(!plans[0].needs_nul_copy);
}
#[test]
fn a_cast_is_built_from_the_shape_never_from_an_array_spelling() {
let arr = candidate(
"arr_parse",
vec![
param(
"buf",
"const char[]",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::CastBuffer,
Returns::default(),
);
let plans = plan_candidate(&arr, "x.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
args[0],
Value::NulTerminated,
"a char array is a string parameter, so it gets the NUL-terminated copy and the `const char[]` spelling never reaches a cast"
);
assert!(!emit::render(&plans[0], "x.c").contains("[]"));
}
#[test]
fn a_void_buffer_cast_comes_from_the_shape() {
let decode = candidate(
"decode",
vec![
param(
"buf",
"some_voidp",
Shape::Pointer {
pointee: Pointee::Void,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::CastBuffer,
Returns::default(),
);
let plans = plan_candidate(&decode, "x.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
args[0],
Value::Data {
cast: Some("const void *".to_owned())
}
);
}
#[test]
fn a_buffer_whose_shape_yields_no_valid_cast_is_refused() {
let odd = candidate(
"odd_parse",
vec![
param(
"buf",
"const wchar_t *",
Shape::Pointer {
pointee: Pointee::Other,
is_const: true,
},
),
param("size", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::CastBuffer,
Returns::default(),
);
assert!(matches!(
plan_candidate(&odd, "x.h", &Vocabulary::default()),
Err(Refusal::UnsupportedShape { .. })
));
}
#[test]
fn macro_affinity_prefers_the_closest_family_not_the_alphabetically_first() {
let mut vocab = png_image_vocabulary();
vocab.macros.insert("PNG2_VERSION".to_owned());
vocab.macros.insert("PNG_IMAGE_THING_VERSION".to_owned());
vocab.macros.remove("PNG_IMAGE_VERSION");
assert_eq!(
macro_for_field("png_image", "version", &vocab),
Some("PNG_IMAGE_THING_VERSION".to_owned()),
"PNG2_VERSION sorts first in ASCII but shares no token run with png_image"
);
}
#[test]
fn an_ambiguous_macro_family_binds_to_nothing_rather_than_guessing() {
let mut vocab = png_image_vocabulary();
vocab.macros.remove("PNG_IMAGE_VERSION");
vocab.macros.insert("PNG_IMAGE_A_VERSION".to_owned());
vocab.macros.insert("PNG_IMAGE_B_VERSION".to_owned());
assert_eq!(macro_for_field("png_image", "version", &vocab), None);
}
// B82. libpng's simplified read is two calls: `png_image_begin_read_from_memory` fills the
// record from the header and `png_image_finish_read` decodes the rows into a buffer whose
// size the header states with `PNG_IMAGE_SIZE(image)`. Everything below is that pair.
fn sizing_vocabulary(sizers: &[(&str, usize)]) -> Vocabulary {
let mut vocabulary = png_image_vocabulary();
vocabulary.sizers = sizers
.iter()
.map(|(name, arity)| ((*name).to_owned(), *arity))
.collect();
vocabulary
}
fn image_handle() -> Param {
param(
"image",
"png_imagep",
Shape::Pointer {
pointee: Pointee::Record("png_image".to_owned()),
is_const: false,
},
)
}
fn void_out(name: &str) -> Param {
param(
name,
"void *",
Shape::Pointer {
pointee: Pointee::Void,
is_const: false,
},
)
}
fn with_tail(vocabulary: &mut Vocabulary, params: Vec<Param>) {
vocabulary
.functions
.insert("png_image_finish_read".to_owned(), params);
}
fn simplified_read() -> [String; 2] {
[
"png_image_begin_read_from_memory".to_owned(),
"png_image_finish_read".to_owned(),
]
}
// B83 let the tail come from any of the author's targets, so `upward_steps` takes a list.
// Most tests are about one sequence and say so with this.
fn sole(sequence: &[String]) -> [&[String]; 1] {
[sequence]
}
fn owned(calls: &[&str]) -> Vec<String> {
calls.iter().map(|call| (*call).to_owned()).collect()
}
fn steps_over(sequences: &[&[String]]) -> Vec<String> {
upward_steps(&open_memory(), &replayable_archive_vocabulary(), sequences)
.into_iter()
.map(|step| step.function)
.collect()
}
// B83. libarchive ships 25 extracted fuzz targets; the ladder picks ONE tree-wide, and it
// picked `libarchive_seek_fuzzer.cc`, which opens with `archive_read_open1`. Asking that
// one sequence whether the authors ever called `archive_read_open_memory` answers "no",
// while `libarchive_roundtrip_fuzzer.cc` calls it directly. The call lists were all
// extracted already; 24 of 25 were being thrown away.
#[test]
fn a_candidate_the_chosen_sequence_never_names_takes_its_tail_from_one_that_does() {
let chosen = owned(&["archive_read_new", "archive_read_open1"]);
let other = owned(&["archive_read_open_memory", "archive_read_data"]);
assert_eq!(
steps_over(&[&chosen, &other]),
vec!["archive_read_data".to_owned()]
);
}
// The chosen sequence is tried FIRST, so nothing that already had a tail gets a different
// one. Gut the ordering and this goes red while the test above stays green.
#[test]
fn the_chosen_sequence_still_wins_when_both_name_the_candidate() {
let chosen = owned(&["archive_read_open_memory", "archive_read_data"]);
let other = owned(&["archive_read_open_memory", "archive_read_next_header"]);
assert_eq!(
steps_over(&[&chosen, &other]),
vec!["archive_read_data".to_owned()],
"the winner of the ladder is still the harness this plan is shaped like"
);
}
// The isolating control for the search itself: a candidate NO target names still has no
// tail. Without this, returning the whole of some other sequence would pass the two above.
#[test]
fn a_candidate_no_target_names_at_all_still_has_no_tail() {
let chosen = owned(&["archive_read_new", "archive_read_open1"]);
let other = owned(&["archive_read_open_filename", "archive_read_data"]);
assert!(steps_over(&[&chosen, &other]).is_empty());
}
// The accepting direction. `buffer` names no handle and carries no extent, so it reaches
// the same dead end `png_read_image` does - except that libpng's own header computes the
// number, and libpng's own example writes `malloc(PNG_IMAGE_SIZE(image))` on the line above.
#[test]
fn the_climb_sizes_an_out_param_the_headers_own_macro_states() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
with_tail(&mut vocabulary, vec![image_handle(), void_out("buffer")]);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].declares,
vec![Stmt::AllocSized {
local: SIZED_LOCAL.to_owned(),
length: format!("{SIZED_LOCAL}{SIZED_LEN_SUFFIX}"),
size: "PNG_IMAGE_SIZE(ctx)".to_owned(),
frees: Vec::new(),
}]
);
assert_eq!(
steps[0].call,
Stmt::Call {
function: "png_image_finish_read".to_owned(),
args: vec![
Value::AddressOf(CONTEXT_LOCAL.to_owned()),
Value::SizedBuffer {
local: SIZED_LOCAL.to_owned(),
cast: Some("void *".to_owned()),
},
],
capture: None,
}
);
assert_eq!(
steps[0].releases,
vec![Stmt::FreeSized {
local: SIZED_LOCAL.to_owned(),
}]
);
}
// The isolating control for the AFFINITY rule, and the one that keeps B67 whole: the same
// call, the same parameter, the same record - and no macro naming the size. It must stay
// refused, because that is `png_read_image` and `tj3Decompress8`, where the number is
// knowledge the caller is expected to hold and inventing one manufactures the overflow.
#[test]
fn an_out_param_no_macro_states_the_size_of_still_stops_the_climb() {
let mut vocabulary = sizing_vocabulary(&[]);
with_tail(&mut vocabulary, vec![image_handle(), void_out("buffer")]);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert!(steps.is_empty(), "{steps:?}");
}
// The isolating control for the ARITY filter. `PNG_IMAGE_BUFFER_SIZE(image, row_stride)` is
// real, is named for exactly this parameter, and is useless: the second argument is the
// number the caller owns, so applying it means inventing that number. Dropped, not zeroed.
#[test]
fn a_macro_that_needs_a_number_the_caller_owns_states_nothing() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_BUFFER_SIZE", 2)]);
with_tail(&mut vocabulary, vec![image_handle(), void_out("buffer")]);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert!(steps.is_empty(), "{steps:?}");
}
// The isolating control for the STEP-ONLY restriction, and it is the one that separates a
// stated size from a fabricated one. The macro reads fields the library writes, so before
// any call has run it reads a zeroed record and states zero - and a zero-byte buffer handed
// to a decoder is the D12 crash wearing the header's own authority.
#[test]
fn the_entry_point_itself_may_not_size_a_buffer_from_a_macro() {
let vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
let entry = candidate(
"png_image_finish_read",
vec![image_handle(), void_out("buffer")],
vec![ParamRole::Context, ParamRole::Context],
Fuzzability::CastBuffer,
Returns {
spelling: "int".to_owned(),
shape: Shape::Integral,
},
);
assert_eq!(
plan_candidate(&entry, "png.h", &vocabulary),
Err(Refusal::UnsupportedShape {
param: "buffer".to_owned()
})
);
}
// The isolating control for the DECLARED-RECORD restriction. `PNG_IMAGE_SIZE(image)`
// expands to `(image).format`, so it needs the object. A handle the library allocated is
// already a pointer, and the same macro over it does not compile - which is why the offer
// is keyed on the context the harness declared for itself, exactly as field population is.
#[test]
fn a_macro_stated_size_is_not_offered_over_a_handle_the_library_produced() {
let mut vocabulary = replayable_archive_vocabulary();
vocabulary.sizers.insert("ARCHIVE_SIZE".to_owned(), 1);
vocabulary.functions.insert(
"archive_read_block".to_owned(),
vec![archive_handle(), void_out("buffer")],
);
let steps = upward_steps(
&open_memory(),
&vocabulary,
&sole(&[
"archive_read_open_memory".to_owned(),
"archive_read_block".to_owned(),
]),
);
assert!(steps.is_empty(), "{steps:?}");
}
// Most specific first. Both macros have affinity with the record and both state a size, but
// only one of them states THIS parameter's size - and taking the record's own would hand a
// colour table a buffer sized for the whole image.
#[test]
fn the_macro_named_for_the_parameter_wins_over_the_records_own() {
let vocabulary =
sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1), ("PNG_IMAGE_COLORMAP_SIZE", 1)]);
assert_eq!(
sizing_macro("png_image", Some(&"colormap".to_owned()), &vocabulary),
Some("PNG_IMAGE_COLORMAP_SIZE".to_owned())
);
assert_eq!(
sizing_macro("png_image", Some(&"buffer".to_owned()), &vocabulary),
Some("PNG_IMAGE_SIZE".to_owned())
);
}
// The B67 arm, which is a different arm of `bind` from the one `buffer` reaches. A
// parameter NAMED like an output takes the Output role and stops at the unsized refusal;
// the same macro answers for it, and the pair proves one rule serves both dead ends.
#[test]
fn the_same_macro_answers_for_a_parameter_the_grader_calls_an_output() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
with_tail(
&mut vocabulary,
vec![
image_handle(),
param(
"dst",
"png_bytep",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: false,
},
),
],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].call,
Stmt::Call {
function: "png_image_finish_read".to_owned(),
args: vec![
Value::AddressOf(CONTEXT_LOCAL.to_owned()),
Value::SizedBuffer {
local: SIZED_LOCAL.to_owned(),
cast: None,
},
],
capture: None,
}
);
}
// Two buffers on one call, which libpng's real signature has. The names must not collide
// and the SECOND one's bail has to release the first: a `return 0` between the two
// allocations is a leak reported inside the target on every replay, which is D15's forged
// crash arriving through the mechanism meant to avoid one.
#[test]
fn a_second_sized_buffer_is_named_apart_and_releases_the_first_when_it_bails() {
let mut vocabulary =
sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1), ("PNG_IMAGE_COLORMAP_SIZE", 1)]);
with_tail(
&mut vocabulary,
vec![image_handle(), void_out("buffer"), void_out("colormap")],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].declares,
vec![
Stmt::AllocSized {
local: SIZED_LOCAL.to_owned(),
length: format!("{SIZED_LOCAL}{SIZED_LEN_SUFFIX}"),
size: "PNG_IMAGE_SIZE(ctx)".to_owned(),
frees: Vec::new(),
},
Stmt::AllocSized {
local: format!("{SIZED_LOCAL}1"),
length: format!("{SIZED_LOCAL}1{SIZED_LEN_SUFFIX}"),
size: "PNG_IMAGE_COLORMAP_SIZE(ctx)".to_owned(),
frees: vec![SIZED_LOCAL.to_owned()],
},
]
);
assert_eq!(
steps[0].releases,
vec![
Stmt::FreeSized {
local: format!("{SIZED_LOCAL}1"),
},
Stmt::FreeSized {
local: SIZED_LOCAL.to_owned(),
},
]
);
}
// The emitted C, because a plan that is right and does not compile buys nothing. Read
// together with the statement test above: that one fixes the SHAPE, this one fixes the
// TEXT, and the gate then compiles the text against the real header.
#[test]
fn a_macro_sized_buffer_reaches_the_c_with_its_guard_and_its_free() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
with_tail(&mut vocabulary, vec![image_handle(), void_out("buffer")]);
let plans = plan_candidate(&begin_read(), "png.h", &vocabulary).unwrap();
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
let source = emit::render(&extend(&plans[0], &steps), "libpng_finish.c");
assert!(
source.contains("size_t lisdex_sized_len = (size_t)(PNG_IMAGE_SIZE(ctx));"),
"{source}"
);
// Not `malloc(0)` and then a bail: a zero-byte block is a live allocation LSAN tracks,
// so bailing past one leaks inside the target on every seed whose header did not parse.
assert!(
source.contains(
"unsigned char *lisdex_sized = lisdex_sized_len ? \
(unsigned char *)malloc(lisdex_sized_len) : NULL;"
),
"{source}"
);
assert!(source.contains("if (lisdex_sized == NULL) {"), "{source}");
assert!(
source.contains("png_image_finish_read(&ctx, (void *)lisdex_sized);"),
"{source}"
);
assert!(source.contains(" free(lisdex_sized);"), "{source}");
}
// B84. `png_const_colorp background` - a record png.h defines completely, that the library
// also hands back through `png_get_PLTE`'s slot, on a call the entry point never took.
fn colour_record() -> Record {
Record {
spelling: "struct png_color_struct".to_owned(),
fields: vec![Field {
name: "red".to_owned(),
spelling: "png_byte".to_owned(),
shape: Shape::Integral,
}],
}
}
fn background() -> Param {
param(
"background",
"png_const_colorp",
Shape::Pointer {
pointee: Pointee::Record("png_color_struct".to_owned()),
is_const: true,
},
)
}
fn context_vocabulary() -> Vocabulary {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
vocabulary
.records
.insert("png_color_struct".to_owned(), colour_record());
with_tail(
&mut vocabulary,
vec![image_handle(), background(), void_out("buffer")],
);
vocabulary
}
#[test]
fn a_step_declares_the_context_the_entry_point_never_took() {
let vocabulary = context_vocabulary();
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].declares[0],
Stmt::Declare {
ty: "struct png_color_struct".to_owned(),
name: "ctx1".to_owned(),
init: Init::ZeroBytes,
}
);
let Stmt::Call { args, .. } = &steps[0].call else {
panic!("the step is a call");
};
assert_eq!(args[1], Value::AddressOf("ctx1".to_owned()));
}
// The isolating control for the RETURNED rule. `gzFile_s` and `WebPMux` are this shape: the
// header shows a struct and the library hands back one it allocated, whose real layout the
// header only prefixes. Stack-declaring one is a fabricated crash inside the target.
#[test]
fn a_record_the_library_hands_back_from_a_constructor_is_not_declared_by_a_step() {
let mut vocabulary = context_vocabulary();
vocabulary.produced.insert("png_color_struct".to_owned());
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert!(steps.is_empty(), "{steps:?}");
}
// The isolating control for the DESTRUCTOR rule, and it is this side's alone: the entry
// point schedules teardowns for the contexts it declares, and a step has nowhere to put one.
#[test]
fn a_record_something_must_free_is_not_declared_where_no_teardown_can_be_scheduled() {
let mut vocabulary = context_vocabulary();
vocabulary.destructors.insert(
"png_color_struct".to_owned(),
BTreeSet::from(["png_color_free".to_owned()]),
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert!(steps.is_empty(), "{steps:?}");
}
// Two parameters of one record share one declaration. Declaring twice in a block either
// shadows the slot the first argument refers to or does not compile at all.
#[test]
fn two_parameters_of_the_same_record_share_the_local_the_step_declared() {
let mut vocabulary = context_vocabulary();
with_tail(
&mut vocabulary,
vec![
image_handle(),
background(),
param(
"foreground",
"png_const_colorp",
Shape::Pointer {
pointee: Pointee::Record("png_color_struct".to_owned()),
is_const: true,
},
),
],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(steps[0].declares.len(), 1, "{:?}", steps[0].declares);
let Stmt::Call { args, .. } = &steps[0].call else {
panic!("the step is a call");
};
assert_eq!(args[1], args[2]);
}
// The stated number. A Config pinned to zero is the invented constant an upward step may
// not copy - `tj3Set(ctx, 0, 0)` where the author wrote `TJPARAM_SCANLIMIT, 500`. A macro
// naming the record and the parameter is the header stating it instead.
#[test]
fn a_config_a_macro_states_is_read_from_the_header_rather_than_pinned() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_ROW_STRIDE", 1)]);
with_tail(
&mut vocabulary,
vec![
image_handle(),
param("row_stride", "png_int_32", Shape::Integral),
],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
assert_eq!(
steps[0].call,
Stmt::Call {
function: "png_image_finish_read".to_owned(),
args: vec![
Value::AddressOf(CONTEXT_LOCAL.to_owned()),
Value::Stated("PNG_IMAGE_ROW_STRIDE(ctx)".to_owned()),
],
capture: None,
}
);
}
// The isolating control for it: the same call with nothing naming the number stays a pinned
// zero, which `is_replayable_value` refuses, so the climb stops exactly where D32 left it.
#[test]
fn a_config_no_macro_states_is_still_a_pinned_zero_the_climb_will_not_copy() {
let mut vocabulary = sizing_vocabulary(&[]);
with_tail(
&mut vocabulary,
vec![
image_handle(),
param("row_stride", "png_int_32", Shape::Integral),
],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert!(steps.is_empty(), "{steps:?}");
}
// The ordering claim the corpus cannot make: a Config that is ALSO an extent name reaches
// the stated-number offer BEFORE the refusal, because a number the header computes beats a
// number the tool declines to guess. No tree in the validation set has both.
#[test]
fn a_macro_answers_for_an_extent_named_config_the_tool_would_otherwise_refuse() {
let mut vocabulary = sizing_vocabulary(&[("PNG_IMAGE_SIZE", 1)]);
with_tail(
&mut vocabulary,
vec![image_handle(), param("size", "size_t", Shape::Integral)],
);
let steps = upward_steps(&begin_read(), &vocabulary, &sole(&simplified_read()));
assert_eq!(steps.len(), 1, "{steps:?}");
let Stmt::Call { args, .. } = &steps[0].call else {
panic!("the step is a call");
};
assert_eq!(args[1], Value::Stated("PNG_IMAGE_SIZE(ctx)".to_owned()));
}
#[test]
fn a_captured_result_is_discarded_so_wall_werror_targets_still_build() {
let plans = plan_candidate(&begin_read(), "png.h", &png_image_vocabulary()).unwrap();
assert!(plans[0].body.contains(&Stmt::Discard {
local: RESULT_LOCAL.to_owned()
}));
}
#[test]
fn a_record_the_library_allocates_itself_is_never_declared_on_the_stack() {
let mut vocab = png_image_vocabulary();
vocab.produced.insert("png_image".to_owned());
assert_eq!(
plan_candidate(&begin_read(), "png.h", &vocab),
Err(Refusal::NoProducer {
handle: "png_image".to_owned()
}),
"zlib's exposed gzFile_s prefix declared on the stack overflowed it on every input"
);
}
#[test]
fn a_record_the_library_allocates_itself_comes_back_from_its_producer() {
let mut vocab = png_image_vocabulary();
vocab.produced.insert("png_image".to_owned());
vocab.producers.insert(
"png_image".to_owned(),
BTreeMap::from([("png_image_new".to_owned(), Vec::new())]),
);
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
let opening = &plans[0].body[0];
assert_eq!(
opening,
&Stmt::Call {
function: "png_image_new".to_owned(),
args: Vec::new(),
capture: Some(Binding {
ty: "png_imagep".to_owned(),
name: CONTEXT_LOCAL.to_owned(),
}),
},
"a produced record must come from the producer, never from a stack declaration"
);
assert_eq!(
plans[0].body[1],
Stmt::BailIfNull {
local: CONTEXT_LOCAL.to_owned()
},
"a producer that returned NULL must not reach the entry point"
);
assert!(
!plans[0]
.body
.iter()
.any(|statement| matches!(statement, Stmt::Declare { .. })),
"nothing about a library-allocated record may be declared on the stack"
);
}
#[test]
fn a_produced_handle_is_passed_by_value_not_by_address() {
let mut vocab = png_image_vocabulary();
vocab.produced.insert("png_image".to_owned());
vocab.producers.insert(
"png_image".to_owned(),
BTreeMap::from([("png_image_new".to_owned(), Vec::new())]),
);
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(
args[0],
Value::Local(CONTEXT_LOCAL.to_owned()),
"taking the address of a pointer the library already returned is how LZ4_freeStream(&ctx) reported a free of a non-malloc'd address"
);
}
#[test]
fn a_size_like_config_is_refused_rather_than_pinned_or_guessed() {
let lz4 = candidate(
"LZ4_decompress_safe",
vec![
param(
"src",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
param("compressedSize", "int", Shape::Integral),
param("dstCapacity", "int", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length, ParamRole::Config],
Fuzzability::CastBuffer,
Returns::default(),
);
assert_eq!(
plan_candidate(&lz4, "lz4.h", &Vocabulary::default()),
Err(Refusal::UnboundExtent {
param: "dstCapacity".to_owned()
})
);
}
// `LZ4_decompress_safe_partial(src, dst, srcSize, targetOutputSize, dstCapacity)` -
// real, and the only one of the 23 leftover extents on seven trees that binds.
fn lz4_partial() -> Candidate {
let mut entry = candidate(
"LZ4_decompress_safe_partial",
vec![
param(
"src",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
param(
"dst",
"char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: false,
},
),
param("srcSize", "int", Shape::Integral),
param("targetOutputSize", "int", Shape::Integral),
param("dstCapacity", "int", Shape::Integral),
],
vec![
ParamRole::Buffer,
ParamRole::Output,
ParamRole::Length,
ParamRole::Config,
ParamRole::Length,
],
Fuzzability::DirectBuffer,
Returns::default(),
);
entry.analysis.extents = BTreeMap::from([(0, 2), (1, 4)]);
entry
}
// lz4's own ossfuzz/decompress_fuzzer.c writes this call as
// `LZ4_decompress_safe_partial(data, dst, size, dstCapacity, dstCapacity)`, so the
// number is the capacity of a buffer the harness allocated - a fact it owns, not a
// guess about memory it does not.
#[test]
fn an_extent_bounding_the_output_takes_the_capacity_the_harness_allocated() {
let plans = plan_candidate(&lz4_partial(), "lz4.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::NulTerminated, "src is the corpus");
assert_eq!(args[2], Value::Size, "srcSize is the corpus length");
assert_eq!(
args[3],
Value::OutCapacity,
"targetOutputSize is what the authors pass: the output capacity"
);
assert_eq!(args[4], Value::OutCapacity, "and so is dstCapacity");
}
// Isolating control for the NAME half. `read_size` is libarchive's block size and `n`
// is libjpeg-turbo's array element count; both sit beside a sized buffer, and inventing
// 65536 for either is a lie the library acts on. Only a name that says OUTPUT may bind.
#[test]
fn an_extent_that_does_not_name_an_output_quantity_is_still_refused() {
let mut knob = lz4_partial();
knob.params[3].name = Some("read_size".to_owned());
assert_eq!(
plan_candidate(&knob, "lz4.h", &Vocabulary::default()),
Err(Refusal::UnboundExtent {
param: "read_size".to_owned()
})
);
}
// Isolating control for the SIZED-OUTPUT half. The output buffer is REMOVED rather than
// downgraded, because a downgraded one refuses at its own parameter first and alibis
// this rule: flipping `dst` to a Buffer makes it an unsized second input, and flipping
// it to an unsized Output trips B67 - either way index 3 is never reached. With no
// output buffer at all, `maxOutputSize` still names an output quantity and there is
// simply no allocation whose size it could honestly be.
#[test]
fn an_output_extent_without_an_output_buffer_that_declares_a_capacity_is_refused() {
let mut no_output = lz4_partial();
no_output.params.remove(1);
no_output.params[2].name = Some("maxOutputSize".to_owned());
no_output.analysis.roles = vec![ParamRole::Buffer, ParamRole::Length, ParamRole::Config];
no_output.analysis.extents = BTreeMap::from([(0, 1)]);
assert_eq!(
plan_candidate(&no_output, "lz4.h", &Vocabulary::default()),
Err(Refusal::UnboundExtent {
param: "maxOutputSize".to_owned()
})
);
}
// `LZ4_decompress_safe_usingDict(src, dst, srcSize, dstCapacity, dictStart, dictSize)`.
// The extents are written out rather than derived, because this is the buffers-first
// shape where no length is adjacent to the buffer it measures - which is the whole
// reason the ownership map exists.
fn lz4_using_dict() -> Candidate {
let readable = |name: &str| {
param(
name,
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
)
};
let mut entry = candidate(
"LZ4_decompress_safe_usingDict",
vec![
readable("src"),
param(
"dst",
"char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: false,
},
),
param("srcSize", "int", Shape::Integral),
param("dstCapacity", "int", Shape::Integral),
readable("dictStart"),
param("dictSize", "int", Shape::Integral),
],
vec![
ParamRole::Buffer,
ParamRole::Output,
ParamRole::Length,
ParamRole::Length,
ParamRole::Buffer,
ParamRole::Length,
],
Fuzzability::DirectBuffer,
Returns::default(),
);
entry.analysis.extents = BTreeMap::from([(0, 2), (1, 3), (4, 5)]);
entry
}
// Handing the same pointer to both readable buffers is not a memory-safety lie - both
// reads are in bounds - but it is not what the authors do, and lz4's own fuzzer says
// why: `/* Prepare the dictionary. The data doesn't matter for decompression. */` over
// a `memset(dict, 0, dictSize)`.
#[test]
fn a_second_readable_buffer_gets_its_own_allocation_rather_than_a_second_copy_of_the_corpus() {
let plans = plan_candidate(&lz4_using_dict(), "lz4.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::NulTerminated, "src is the corpus");
assert_eq!(args[2], Value::Size, "srcSize is the corpus length");
assert_eq!(
args[4],
Value::AuxBuffer {
cast: Some("const char *".to_owned())
},
"dictStart is a second input the fuzzer cannot supply"
);
assert_eq!(args[5], Value::AuxCapacity, "and it declares its own size");
assert!(plans[0].needs_aux_buffer);
}
// The isolating control for POSITION deciding which buffer is primary. `src` and
// `dictStart` are the same type, so `buffer_quality` scores them equal and the
// signature's own `max_by_key` returns the LAST maximum - reusing that would have given
// the dictionary the corpus and handed the real input a zeroed buffer.
#[test]
fn the_first_readable_buffer_keeps_the_corpus_and_never_swaps_with_the_second() {
let plans = plan_candidate(&lz4_using_dict(), "lz4.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert!(
!matches!(args[0], Value::AuxBuffer { .. }),
"src must never become the auxiliary buffer"
);
assert_ne!(args[2], Value::AuxCapacity, "nor may srcSize");
}
// The other side of the control: one readable buffer means no auxiliary allocation at
// all, so the rule cannot be a blanket "every char buffer gets its own memory".
#[test]
fn a_signature_with_one_readable_buffer_allocates_no_auxiliary() {
let mut single = lz4_using_dict();
single.name = "LZ4_decompress_safe".to_owned();
single.params.truncate(4);
single.analysis.roles.truncate(4);
single.analysis.extents = BTreeMap::from([(0, 2), (1, 3)]);
let plans = plan_candidate(&single, "lz4.h", &Vocabulary::default()).unwrap();
assert!(!plans[0].needs_aux_buffer);
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::NulTerminated);
}
#[test]
fn a_glued_lowercase_extent_name_is_still_an_extent() {
assert!(is_extent_name("maxlen"));
assert!(is_extent_name("bufsize"));
assert!(is_extent_name("dstCapacity"));
assert!(!is_extent_name("isFinal"));
assert!(!is_extent_name("color_type"));
}
#[test]
fn a_word_ending_in_n_is_not_an_extent_because_n_is_a_vocabulary_entry() {
for name in [
"align",
"distortion",
"pattern",
"column",
"origin",
"version",
] {
assert!(
!is_extent_name(name),
"{name} is not an extent; it merely ends in the one-character entry n"
);
}
assert!(is_extent_name("n"), "n itself is still an extent name");
assert!(
is_extent_name("inlen") && is_extent_name("keylen") && is_extent_name("isize"),
"the suffix arm still carries the glued lowercase extents it was added for"
);
}
#[test]
fn a_config_that_is_not_an_extent_still_binds() {
let expat = candidate(
"XML_Parse",
vec![
param(
"s",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
param("len", "int", Shape::Integral),
param("isFinal", "int", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length, ParamRole::Config],
Fuzzability::CastBuffer,
Returns::default(),
);
let plans = plan_candidate(&expat, "expat.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[2], Value::Zero);
}
#[test]
fn a_context_with_a_destructor_is_torn_down_after_the_call() {
let mut vocab = png_image_vocabulary();
vocab.destructors.insert(
"png_image".to_owned(),
BTreeSet::from(["png_image_free".to_owned()]),
);
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
let body = &plans[0].body;
let call = body
.iter()
.position(
|s| matches!(s, Stmt::Call { function, .. } if function == &begin_read().name),
)
.expect("the entry call");
let free = body
.iter()
.position(|s| matches!(s, Stmt::Call { function, .. } if function == "png_image_free"))
.expect("the teardown call");
assert!(free > call);
let Stmt::Call { args, .. } = &body[free] else {
unreachable!()
};
assert_eq!(args, &vec![Value::AddressOf(CONTEXT_LOCAL.to_owned())]);
}
#[test]
fn a_record_field_is_torn_down_when_the_context_itself_owns_no_destructor() {
let mut vocab = png_image_vocabulary();
vocab
.records
.get_mut("png_image")
.unwrap()
.fields
.push(Field {
name: "output".to_owned(),
spelling: "png_buffer".to_owned(),
shape: Shape::Record("png_buffer".to_owned()),
});
vocab.destructors.insert(
"png_buffer".to_owned(),
BTreeSet::from(["png_buffer_free".to_owned()]),
);
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
assert!(plans[0].body.contains(&Stmt::Call {
function: "png_buffer_free".to_owned(),
args: vec![Value::AddressOfField {
local: CONTEXT_LOCAL.to_owned(),
field: "output".to_owned(),
}],
capture: None,
}));
}
#[test]
fn a_record_that_owns_a_destructor_does_not_also_free_its_fields() {
let mut vocab = png_image_vocabulary();
vocab
.records
.get_mut("png_image")
.unwrap()
.fields
.push(Field {
name: "output".to_owned(),
spelling: "png_buffer".to_owned(),
shape: Shape::Record("png_buffer".to_owned()),
});
vocab.destructors.insert(
"png_image".to_owned(),
BTreeSet::from(["png_image_free".to_owned()]),
);
vocab.destructors.insert(
"png_buffer".to_owned(),
BTreeSet::from(["png_buffer_free".to_owned()]),
);
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
assert!(
!plans[0]
.body
.iter()
.any(|s| matches!(s, Stmt::Call { function, .. } if function == "png_buffer_free")),
"freeing a field after its owner is a double free"
);
}
#[test]
fn a_teardown_is_chosen_by_affinity_with_the_entry_point() {
let mut vocab = Vocabulary::default();
vocab.destructors.insert(
"z_stream_s".to_owned(),
BTreeSet::from(["deflateEnd".to_owned(), "inflateEnd".to_owned()]),
);
assert_eq!(
teardown_for("z_stream_s", "inflate", &vocab),
Some("inflateEnd".to_owned()),
"deflateEnd sorts first but shares no leading word with inflate"
);
}
#[test]
fn an_entry_point_that_is_itself_the_teardown_is_not_called_twice() {
let mut vocab = Vocabulary::default();
vocab.destructors.insert(
"png_image".to_owned(),
BTreeSet::from(["png_image_free".to_owned()]),
);
assert_eq!(
teardown_for("png_image", "png_image_free", &vocab),
None,
"tearing down after an entry point that is the teardown is a double free"
);
}
#[test]
fn an_ambiguous_teardown_is_not_guessed() {
let mut vocab = Vocabulary::default();
vocab.destructors.insert(
"thing".to_owned(),
BTreeSet::from(["alpha_free".to_owned(), "beta_free".to_owned()]),
);
assert_eq!(teardown_for("thing", "parse_thing", &vocab), None);
}
#[test]
fn variants_are_real_subsets_ordered_most_populated_first() {
assert_eq!(variant_masks(0), vec![0]);
assert_eq!(variant_masks(1), vec![1, 0]);
assert_eq!(variant_masks(2), vec![3, 2, 1, 0]);
assert_eq!(variant_masks(3), vec![7, 6, 5, 3, 4, 2, 1, 0]);
}
#[test]
fn more_bindable_fields_than_the_cap_still_produce_a_bounded_plan_set() {
let masks = variant_masks(8);
assert!(masks.len() <= MAX_PLAN_VARIANTS);
assert_eq!(masks[0].count_ones() as usize, MAX_POPULATED_FIELDS);
assert_eq!(*masks.last().expect("the empty subset is always last"), 0);
}
#[test]
fn one_wrong_macro_no_longer_costs_the_whole_candidate() {
let mut vocab = png_image_vocabulary();
vocab.macros.insert("PNG_IMAGE_FORMAT".to_owned());
vocab
.records
.get_mut("png_image")
.unwrap()
.fields
.push(Field {
name: "format".to_owned(),
spelling: "png_uint_32".to_owned(),
shape: Shape::Integral,
});
let plans = plan_candidate(&begin_read(), "png.h", &vocab).unwrap();
assert_eq!(plans.len(), 4);
let populated = |plan: &HarnessPlan| {
plan.body
.iter()
.filter(|s| matches!(s, Stmt::SetField { .. }))
.count()
};
assert_eq!(populated(&plans[0]), 2);
assert_eq!(populated(&plans[1]), 1);
assert_eq!(populated(&plans[2]), 1);
assert_eq!(populated(&plans[3]), 0);
}
#[test]
fn an_opaque_context_is_refused_rather_than_guessed() {
let mut opaque = begin_read();
opaque.params[0].shape = Shape::Pointer {
pointee: Pointee::Record("png_struct_def".to_owned()),
is_const: false,
};
assert_eq!(
plan_candidate(&opaque, "png.h", &png_image_vocabulary()),
Err(Refusal::NoProducer {
handle: "png_struct_def".to_owned()
})
);
}
#[test]
fn an_unsized_double_pointer_out_param_is_refused() {
let read_image = candidate(
"png_read_image",
vec![
param(
"png_ptr",
"png_structrp",
Shape::Pointer {
pointee: Pointee::Record("png_image".to_owned()),
is_const: false,
},
),
param(
"row_pointers",
"png_bytepp",
Shape::Pointer {
pointee: Pointee::Pointer(Box::new(Pointee::UnsignedChar)),
is_const: false,
},
),
],
vec![ParamRole::Context, ParamRole::Output],
Fuzzability::CastBuffer,
Returns::default(),
);
assert_eq!(
plan_candidate(&read_image, "png.h", &png_image_vocabulary()),
Err(Refusal::UnsizedOutParam {
param: "row_pointers".to_owned()
})
);
}
#[test]
fn a_callback_parameter_is_refused_until_callback_synthesis_lands() {
let set_read_fn = candidate(
"png_set_read_fn",
vec![
param(
"png_ptr",
"png_structrp",
Shape::Pointer {
pointee: Pointee::Record("png_image".to_owned()),
is_const: false,
},
),
param(
"read_fn",
"png_rw_ptr",
Shape::Pointer {
pointee: Pointee::Function(None),
is_const: false,
},
),
],
vec![ParamRole::Context, ParamRole::Callback],
Fuzzability::CustomStream,
Returns::default(),
);
assert!(matches!(
plan_candidate(&set_read_fn, "png.h", &png_image_vocabulary()),
Err(Refusal::NeedsCallback { .. })
));
}
#[test]
fn an_entry_with_no_data_input_is_refused() {
let mut dead = begin_read();
dead.fuzzability = Fuzzability::NoInput;
assert_eq!(
plan_candidate(&dead, "png.h", &png_image_vocabulary()),
Err(Refusal::NoDataInput)
);
}
#[test]
fn a_plain_buffer_entry_needs_no_context_local() {
let decode = candidate(
"decode",
vec![
param(
"data",
"const uint8_t *",
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const: true,
},
),
param("len", "size_t", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns::default(),
);
let plans = plan_candidate(&decode, "x.h", &Vocabulary::default()).unwrap();
assert_eq!(plans.len(), 1);
assert!(
!plans[0]
.body
.iter()
.any(|s| matches!(s, Stmt::Declare { .. }))
);
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::Data { cast: None });
}
fn byte_pointer(name: &str, spelling: &str, is_const: bool) -> Param {
param(
name,
spelling,
Shape::Pointer {
pointee: Pointee::UnsignedChar,
is_const,
},
)
}
fn owning(mut entry: Candidate, extents: &[(usize, usize)]) -> Candidate {
entry.analysis.extents = extents.iter().copied().collect();
entry
}
// B67. The out-param is caller-allocated AND the signature says how much the library
// may write, so the harness declares the extent rather than inferring it.
#[test]
fn an_out_param_with_a_capacity_gets_a_buffer_the_harness_owns() {
let decode = owning(
candidate(
"lz4_decode",
vec![
byte_pointer("src", "const unsigned char *", true),
byte_pointer("dst", "unsigned char *", false),
param("srcSize", "size_t", Shape::Integral),
param("dstCapacity", "size_t", Shape::Integral),
],
vec![
ParamRole::Buffer,
ParamRole::Output,
ParamRole::Length,
ParamRole::Length,
],
Fuzzability::DirectBuffer,
Returns::default(),
),
&[(0, 2), (1, 3)],
);
let plans = plan_candidate(&decode, "x.h", &Vocabulary::default()).unwrap();
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[0], Value::Data { cast: None });
assert_eq!(args[1], Value::OutBuffer { cast: None });
assert_eq!(args[2], Value::Size, "the fuzz data's own length");
assert_eq!(
args[3],
Value::OutCapacity,
"the capacity the harness actually allocated, not the fuzz size"
);
assert!(plans[0].needs_out_buffer);
}
// The control for the clause above, and the class the refusal was written for.
// tj3Decompress8 takes a dstBuf and no capacity at all: its size is width * height *
// pixel size, which the caller is expected to already know.
#[test]
fn an_out_param_with_no_capacity_anywhere_is_refused_not_guessed() {
let decode = owning(
candidate(
"tj3_decompress",
vec![
byte_pointer("jpegBuf", "const unsigned char *", true),
param("jpegSize", "size_t", Shape::Integral),
byte_pointer("dstBuf", "unsigned char *", false),
],
vec![ParamRole::Buffer, ParamRole::Length, ParamRole::Output],
Fuzzability::DirectBuffer,
Returns::default(),
),
&[(0, 1)],
);
assert!(matches!(
plan_candidate(&decode, "x.h", &Vocabulary::default()),
Err(Refusal::UnsizedOutParam { param }) if param == "dstBuf"
));
}
// Isolates per-buffer sizing from the old whole-signature question. There IS a Length
// here, it just is not src's - and asking only whether the signature had one let
// lz4's src take the fuzz copy on the strength of the OUTPUT's capacity.
#[test]
fn a_char_buffer_is_a_string_when_the_only_extent_belongs_to_another_buffer() {
let decode = owning(
candidate(
"lz4_decode_partial",
vec![
param(
"src",
"const char *",
Shape::Pointer {
pointee: Pointee::Char,
is_const: true,
},
),
byte_pointer("dst", "unsigned char *", false),
param("dstCapacity", "int", Shape::Integral),
],
vec![ParamRole::Buffer, ParamRole::Output, ParamRole::Length],
Fuzzability::CastBuffer,
Returns::default(),
),
&[(1, 2)],
);
assert!(matches!(
plan_candidate(&decode, "x.h", &Vocabulary::default()),
Err(Refusal::UnsizedTextParam { param }) if param == "src"
));
}
// zlib's uncompress writes the decoded length back through destLen, so the local has
// to carry the library's own spelling - uLongf is not size_t everywhere.
#[test]
fn an_in_out_capacity_is_declared_with_the_librarys_own_spelling() {
let decode = owning(
candidate(
"uncompress",
vec![
byte_pointer("dest", "Bytef *", false),
param(
"destLen",
"uLongf *",
Shape::Pointer {
pointee: Pointee::Integral,
is_const: false,
},
),
byte_pointer("source", "const Bytef *", true),
param("sourceLen", "uLong", Shape::Integral),
],
vec![
ParamRole::Output,
ParamRole::Length,
ParamRole::Buffer,
ParamRole::Length,
],
Fuzzability::DirectBuffer,
Returns::default(),
),
&[(0, 1), (2, 3)],
);
let plans = plan_candidate(&decode, "zlib.h", &Vocabulary::default()).unwrap();
assert!(plans[0].body.contains(&Stmt::Declare {
ty: "uLongf".to_owned(),
name: OUT_LEN_LOCAL.to_owned(),
init: Init::Capacity,
}));
let Stmt::Call { args, .. } = call_in(&plans[0]) else {
unreachable!()
};
assert_eq!(args[1], Value::AddressOf(OUT_LEN_LOCAL.to_owned()));
assert_eq!(args[3], Value::Size);
}
// The fuzz data's length cannot be handed over by address: the local would be the
// library's to rewrite, and it describes memory the harness does not own.
#[test]
fn an_input_extent_passed_by_address_is_refused() {
let decode = owning(
candidate(
"uncompress2",
vec![
byte_pointer("source", "const Bytef *", true),
param(
"sourceLen",
"uLong *",
Shape::Pointer {
pointee: Pointee::Integral,
is_const: false,
},
),
],
vec![ParamRole::Buffer, ParamRole::Length],
Fuzzability::DirectBuffer,
Returns::default(),
),
&[(0, 1)],
);
assert!(matches!(
plan_candidate(&decode, "zlib.h", &Vocabulary::default()),
Err(Refusal::IndirectExtent { param }) if param == "sourceLen"
));
}
}