Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company đŸ‘‡

feat(lisdex): B82 - the header states the size, so it is a fact rather than a guess

CarterPerez-dev58d1e82a8375
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs
index b22a5181..d900693f 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/emit.rs
@@ -298,6 +298,29 @@ fn render_stmt(out: &mut String, statement: &Stmt, plan: &HarnessPlan) {
Stmt::BailIfZero { local } => {
render_bail(out, &format!("{local} == 0"), plan);
}
+ Stmt::AllocSized {
+ local,
+ length,
+ size,
+ frees,
+ } => {
+ let _ = writeln!(out, " size_t {length} = (size_t)({size});");
+ // Not allocated at all when the size is zero, which is two separate facts. A
+ // zero-byte block is not a smaller version of the same offer - ASAN hands back a
+ // valid pointer with no writable byte behind it, so the first thing the library
+ // stores lands in a redzone and is reported against the library. And `malloc(0)`
+ // is a live allocation LSAN tracks, so bailing past it leaks on every seed whose
+ // header failed to parse, which is D15's forged crash arriving through the guard.
+ let _ = writeln!(
+ out,
+ " unsigned char *{local} = {length} ? (unsigned char *)malloc({length}) : NULL;"
+ );
+ render_bail_with(out, &format!("{local} == NULL"), plan, frees);
+ let _ = writeln!(out, " memset({local}, 0, {length});");
+ }
+ Stmt::FreeSized { local } => {
+ let _ = writeln!(out, " free({local});");
+ }
}
}
@@ -305,6 +328,10 @@ fn render_stmt(out: &mut String, statement: &Stmt, plan: &HarnessPlan) {
// the direct oracle run enforces LeakSanitizer - so a bail that skips the free reports a
// leak in the target on every replay, which is exactly the forged crash D15 warns about.
fn render_bail(out: &mut String, condition: &str, plan: &HarnessPlan) {
+ render_bail_with(out, condition, plan, &[]);
+}
+
+fn render_bail_with(out: &mut String, condition: &str, plan: &HarnessPlan, extra: &[String]) {
let _ = writeln!(out, " if ({condition}) {{");
if plan.needs_nul_copy {
let _ = writeln!(out, " free({NUL_COPY_LOCAL});");
@@ -315,6 +342,9 @@ fn render_bail(out: &mut String, condition: &str, plan: &HarnessPlan) {
if plan.needs_aux_buffer {
let _ = writeln!(out, " free({AUX_LOCAL});");
}
+ for local in extra {
+ let _ = writeln!(out, " free({local});");
+ }
let _ = writeln!(out, " return 0;");
let _ = writeln!(out, " }}");
}
@@ -343,6 +373,10 @@ fn render_value(value: &Value) -> String {
None => AUX_LOCAL.to_owned(),
},
Value::AuxCapacity => AUX_CAPACITY.to_owned(),
+ Value::SizedBuffer { local, cast } => match cast {
+ Some(ty) => format!("({ty}){local}"),
+ None => local.clone(),
+ },
}
}
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs
index 0c3c83e9..694bee1f 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/plan.rs
@@ -14,6 +14,8 @@ pub const OUT_CAPACITY: &str = "LISDEX_OUT_CAPACITY";
pub const MAX_OUT_BYTES: usize = 65536;
pub const AUX_LOCAL: &str = "lisdex_aux";
pub const FILLED_LOCAL: &str = "lisdex_filled";
+pub const SIZED_LOCAL: &str = "lisdex_sized";
+pub const SIZED_LEN_SUFFIX: &str = "_len";
pub const AUX_CAPACITY: &str = "LISDEX_AUX_CAPACITY";
// lz4's own decompress_fuzzer.c uses `64 * 1024 - 1` for its large external dictionary, so
// this is that size rather than a round number: a dictionary at or above 64 KiB takes a
@@ -48,6 +50,12 @@ pub enum Value {
// that it is distinct memory, not its contents.
AuxBuffer { cast: Option<String> },
AuxCapacity,
+ // A buffer whose extent no PARAMETER states but a MACRO does. It is not the same thing as
+ // `OutBuffer`: that one is a capacity the harness invented and the library is under
+ // contract to honour, while this one is a size the header itself computes from a record
+ // the library has already filled in. `PNG_IMAGE_SIZE(image)` is libpng saying, in its own
+ // header, exactly how many bytes `png_image_finish_read` is going to write.
+ SizedBuffer { local: String, cast: Option<String> },
}
impl Value {
@@ -97,6 +105,22 @@ pub enum Stmt {
BailIfZero {
local: String,
},
+ // Allocated where it is USED rather than in the prologue, and that placement is the whole
+ // reason it is a statement instead of a scaffolding flag. The size comes from a macro read
+ // over a record the library fills in, so it states nothing until the call that fills it has
+ // run - `PNG_IMAGE_SIZE(image)` before `png_image_begin_read_from_memory` is zero.
+ //
+ // `frees` names the sized buffers allocated BEFORE this one, because they are the only ones
+ // in scope at this bail. The prologue's own three are emitted from the plan's flags.
+ AllocSized {
+ local: String,
+ length: String,
+ size: String,
+ frees: Vec<String>,
+ },
+ FreeSized {
+ local: String,
+ },
}
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/search.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/search.rs
index 8a69f776..9deef2c4 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/search.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/search.rs
@@ -363,6 +363,7 @@ mod tests {
args: vec![Value::Local("ctx".to_owned())],
capture: None,
},
+ releases: Vec::new(),
})
.collect(),
}
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
index 4775eb78..590bb500 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-harness/src/synth.rs
@@ -11,7 +11,10 @@ use lisdex_surface::signature::{
Analysis, Fuzzability, Param, ParamRole, Pointee, Shape, handle_key,
};
-use crate::plan::{Binding, FILLED_LOCAL, HarnessPlan, Init, OUT_LEN_LOCAL, Stmt, Value};
+use crate::plan::{
+ Binding, FILLED_LOCAL, HarnessPlan, Init, OUT_LEN_LOCAL, SIZED_LEN_SUFFIX, SIZED_LOCAL, Stmt,
+ Value,
+};
pub const CONTEXT_LOCAL: &str = "ctx";
pub const RESULT_LOCAL: &str = "rc";
@@ -293,19 +296,44 @@ fn teardown_calls(
#[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> {
+ let unary: Vec<&str> = vocabulary
+ .sizers
+ .iter()
+ .filter(|(_, arity)| **arity == 1)
+ .map(|(name, _)| name.as_str())
+ .collect();
+ param
+ .and_then(|name| macro_by_affinity(record, &format!("{name}_size"), unary.iter().copied()))
+ .or_else(|| macro_by_affinity(record, "size", unary.iter().copied()))
+}
+
+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 vocabulary.macros.contains(&direct) {
+ 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 vocabulary
- .macros
- .iter()
- .filter(|name| name.ends_with(&suffix))
- {
+ 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;
@@ -315,7 +343,7 @@ pub fn macro_for_field(record: &str, field: &str, vocabulary: &Vocabulary) -> Op
Some((top, _)) if score < *top => {}
Some((top, _)) if score == *top => tied = true,
_ => {
- best = Some((score, name.clone()));
+ best = Some((score, name.to_owned()));
tied = false;
}
}
@@ -536,7 +564,17 @@ fn bind_all(
.zip(&candidate.analysis.roles)
.enumerate()
.map(|(index, (param, role))| {
- bind(index, param, *role, locals, filled, &candidate.analysis)
+ // `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()
}
@@ -552,6 +590,74 @@ fn filled_declarations(filled: &BTreeMap<usize, (String, String)>) -> Vec<Stmt>
.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.
+struct Sizing<'a> {
+ vocabulary: &'a Vocabulary,
+ record: String,
+ local: 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,
+ allocations: Vec<Stmt>,
+ buffers: Vec<String>,
+}
+
+impl Sizing<'_> {
+ fn offer(&mut self, param: &Param) -> Option<Value> {
+ let stated = sizing_macro(&self.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.allocations.push(Stmt::AllocSized {
+ length: format!("{local}{SIZED_LEN_SUFFIX}"),
+ size: format!("{stated}({})", self.local),
+ 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,
+ sizing: Option<&mut Sizing>,
+) -> Option<Value> {
+ let sizing = sizing?;
+ // 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, .. } = &param.shape else {
+ return None;
+ };
+ if !pointee.is_byte_sized() || analysis.extents.contains_key(&index) {
+ return None;
+ }
+ sizing.offer(param)
+}
+
fn bind(
index: usize,
param: &Param,
@@ -559,6 +665,7 @@ fn bind(
locals: &BTreeMap<String, Held>,
filled: &BTreeMap<usize, (String, String)>,
analysis: &Analysis,
+ sizing: Option<&mut Sizing>,
) -> Result<Value, Refusal> {
let label = param.name.clone().unwrap_or_else(|| param.spelling.clone());
match role {
@@ -654,6 +761,8 @@ fn bind(
Ok(Value::OutBuffer {
cast: cast_for(param)?,
})
+ } else if let Some(value) = sized_by_macro(index, param, analysis, sizing) {
+ Ok(value)
} else {
Err(Refusal::UnsizedOutParam { param: label })
}
@@ -668,15 +777,23 @@ fn bind(
// 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.
- let handle = handle_key(&param.spelling, &param.shape).ok_or_else(|| {
- Refusal::UnsupportedShape {
- param: label.clone(),
- }
- })?;
- locals
- .get(&handle)
- .map(Held::reference)
- .ok_or(Refusal::OpaqueContext { record: handle })
+ let handle = handle_key(&param.spelling, &param.shape);
+ if let Some(handle) = &handle
+ && let Some(held) = locals.get(handle)
+ {
+ return Ok(held.reference());
+ }
+ // Asked only AFTER the handle map has had its answer, so a byte pointer the plan
+ // is already holding under an opaque typedef keeps the local it was bound to.
+ // `void *buffer` is what falls through to here: it names no handle at all, which
+ // is why the B67 arm above never sees the parameter B82 was written for.
+ if let Some(value) = sized_by_macro(index, param, analysis, sizing) {
+ return Ok(value);
+ }
+ match handle {
+ Some(record) => Err(Refusal::OpaqueContext { record }),
+ None => Err(Refusal::UnsupportedShape { param: label }),
+ }
}
}
}
@@ -931,6 +1048,10 @@ pub struct Extension {
// 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
@@ -992,6 +1113,7 @@ pub fn upward_steps(
let mut steps: Vec<Extension> = Vec::new();
let mut declared = filled_locals(&candidate.params, &candidate.analysis.roles, 0).len();
+ let mut allocated = 0usize;
for name in tail_run(sequence, &candidate.name) {
if steps.len() == MAX_UPWARD_STEPS {
break;
@@ -1033,32 +1155,82 @@ pub fn upward_steps(
}
let analysis = signature::analyze_named(name, params, &BTreeSet::new());
let filled = filled_locals(params, &analysis.roles, declared);
- let bound: Result<Vec<Value>, Refusal> = params
+ // 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 sizing = ordered
.iter()
- .zip(&analysis.roles)
- .enumerate()
- .map(|(index, (param, role))| bind(index, param, *role, &locals, &filled, &analysis))
- .collect();
- let Ok(args) = bound else {
+ .find(|(_, held)| !held.by_value)
+ .map(|(handle, held)| Sizing {
+ vocabulary,
+ record: handle.clone(),
+ local: held.local.clone(),
+ first: allocated,
+ allocations: Vec::new(),
+ buffers: Vec::new(),
+ });
+ let Some(args) = bind_step(params, &analysis, &locals, &filled, sizing.as_mut()) else {
break;
};
if !args.iter().all(is_replayable_value) {
break;
}
+ let (allocations, buffers) = sizing
+ .map(|sizing| (sizing.allocations, sizing.buffers))
+ .unwrap_or_default();
declared += filled.len();
+ let mut preamble = filled_declarations(&filled);
+ preamble.extend(allocations);
+ // 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: filled_declarations(&filled),
+ 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 Sizing` 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)>,
+ sizing: Option<&mut Sizing>,
+) -> Option<Vec<Value>> {
+ let mut sizing = sizing;
+ 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
@@ -1082,6 +1254,7 @@ fn is_replayable_value(value: &Value) -> bool {
| Value::OutCapacity
| Value::AuxBuffer { .. }
| Value::AuxCapacity
+ | Value::SizedBuffer { .. }
| Value::Local(_)
| Value::AddressOf(_)
| Value::AddressOfField { .. } => true,
@@ -1138,6 +1311,9 @@ pub fn extend(plan: &HarnessPlan, steps: &[Extension]) -> HarnessPlan {
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());
@@ -2731,6 +2907,294 @@ mod tests {
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(),
+ ]
+ }
+
+ // 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, &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, &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, &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,
+ &[
+ "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, &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, &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, &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}");
+ }
+
#[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();
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
index 86bca1ee..eb61724c 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/extract.rs
@@ -95,6 +95,11 @@ pub struct Record {
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Vocabulary {
pub macros: BTreeSet<String>,
+ // Kept apart from `macros` because the two are spelled differently at every use site: an
+ // object-like macro is a value and a function-like one is only a value once it is applied
+ // to something. Emitting `PNG_IMAGE_SIZE` where `PNG_IMAGE_VERSION` was meant does not
+ // compile, so the arity travels with the name rather than being rediscovered.
+ pub sizers: BTreeMap<String, usize>,
pub records: BTreeMap<String, Record>,
pub produced: BTreeSet<String>,
pub destructors: BTreeMap<String, BTreeSet<String>>,
@@ -108,6 +113,9 @@ pub struct Vocabulary {
impl Vocabulary {
pub fn absorb(&mut self, other: Vocabulary) {
self.macros.extend(other.macros);
+ for (name, arity) in other.sizers {
+ self.sizers.entry(name).or_insert(arity);
+ }
for (name, record) in other.records {
self.records.entry(name).or_insert(record);
}
@@ -479,12 +487,46 @@ fn collect_relations(entity: &Entity, target: &Path, into: &mut Vocabulary) {
}
}
+// libclang exposes a function-like macro's parameters nowhere but the raw tokens, and the
+// count is what decides whether the harness can apply it at all: `PNG_IMAGE_SIZE(image)`
+// takes the record it is written about, while `PNG_IMAGE_BUFFER_SIZE(image, row_stride)`
+// takes a second number the caller owns - and supplying that number is the guess B67 refuses.
+fn macro_arity(entity: &Entity) -> Option<usize> {
+ let tokens = entity.get_range()?.tokenize();
+ let open = tokens
+ .iter()
+ .position(|token| token.get_spelling() == "(")?;
+ let mut depth = 0usize;
+ let mut names = 0usize;
+ for token in &tokens[open..] {
+ match token.get_spelling().as_str() {
+ "(" => depth += 1,
+ ")" => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(names);
+ }
+ }
+ "," => {}
+ _ if depth == 1 => names += 1,
+ _ => {}
+ }
+ }
+ None
+}
+
fn collect_vocabulary(entity: &Entity, target: &Path, into: &mut Vocabulary) {
for child in entity.get_children() {
match child.get_kind() {
EntityKind::FunctionDecl => collect_relations(&child, target, into),
EntityKind::MacroDefinition => {
- if child.is_builtin_macro() || child.is_function_like_macro() {
+ if child.is_builtin_macro() {
+ continue;
+ }
+ if child.is_function_like_macro() {
+ if let (Some(name), Some(arity)) = (child.get_name(), macro_arity(&child)) {
+ into.sizers.insert(name, arity);
+ }
continue;
}
if let Some(name) = child.get_name() {
@@ -1012,6 +1054,39 @@ void WebPFreeDecBuffer(WebPDecBuffer *buffer);
assert!(!vocab.macros.contains("__LINE__"));
}
+ // B82. libpng's real definitions, verbatim in shape: the size macro is written in terms of
+ // two more, so its BODY carries nested parentheses and a comma. A count that walked the
+ // whole definition instead of stopping at the parameter list would call it four.
+ const SIZE_MACROS: &str = r"
+#define PNG_IMAGE_VERSION 1
+#define PNG_IMAGE_ROW_STRIDE(image) ((image).width)
+#define PNG_IMAGE_BUFFER_SIZE(image, row_stride) ((image).height * (row_stride))
+#define PNG_IMAGE_SIZE(image) PNG_IMAGE_BUFFER_SIZE(image, PNG_IMAGE_ROW_STRIDE(image))
+#define PNG_IMAGE_NOTHING() 0
+typedef struct png_image { unsigned int version; unsigned int width; } png_image;
+int png_image_finish_read(png_image *image, void *buffer);
+";
+
+ #[test]
+ fn a_function_like_macro_is_collected_with_the_number_of_arguments_it_takes() {
+ let vocab = vocabulary("sizers", SIZE_MACROS);
+ assert_eq!(vocab.sizers.get("PNG_IMAGE_SIZE"), Some(&1));
+ assert_eq!(vocab.sizers.get("PNG_IMAGE_ROW_STRIDE"), Some(&1));
+ assert_eq!(vocab.sizers.get("PNG_IMAGE_BUFFER_SIZE"), Some(&2));
+ assert_eq!(vocab.sizers.get("PNG_IMAGE_NOTHING"), Some(&0));
+ }
+
+ // The two maps are separate because the two are spelled differently at every use site.
+ // `field_bindings` writes a macro name verbatim into `ctx.version = X;`, and doing that
+ // with `PNG_IMAGE_SIZE` does not compile.
+ #[test]
+ fn a_function_like_macro_never_reaches_the_map_that_populates_a_field() {
+ let vocab = vocabulary("sizers_apart", SIZE_MACROS);
+ assert!(vocab.macros.contains("PNG_IMAGE_VERSION"));
+ assert!(!vocab.macros.contains("PNG_IMAGE_SIZE"));
+ assert!(!vocab.sizers.contains_key("PNG_IMAGE_VERSION"));
+ }
+
#[test]
fn a_record_is_keyed_the_same_way_a_pointee_is() {
let vocab = vocabulary("records", SIMPLIFIED_API);
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh
index 6cd07072..89e0a5de 100755
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh
@@ -614,6 +614,123 @@ else
fi
rm -rf "$WORK/filled"
+# B82. B67 refuses an out-param with no extent because the size is knowledge the caller is
+# expected to hold and inventing it manufactures the overflow. A library that ships a MACRO
+# computing that size has the knowledge in its own header, and libpng's own example writes
+# `malloc(PNG_IMAGE_SIZE(image))` on the line above `png_image_finish_read`.
+#
+# Three trees, each differing from the first by exactly ONE #define, because two rules are new
+# and each has to be shown to be doing work ALONE: the affinity rule (a macro naming this
+# record's size exists) and the arity filter (it takes only the record, not a second number the
+# caller owns). Censused over ten tree-runs before the rule was written: of 30 refused
+# byte-sized parameters with no extent, exactly 2 have a macro that answers - both on libpng's
+# `png_image_finish_read` - so the accepting direction has no real tree yet and is asserted here.
+banner "M5 MACRO-STATED CAPACITY"
+
+sizelib_tree() {
+ local root="$1"
+ local sizers="$2"
+ rm -rf "$root"
+ mkdir -p "$root/include" "$root/fuzz"
+ cat >"$root/include/sizelib.h" <<SIZE_H
+#include <stddef.h>
+
+typedef struct sizelib_image {
+ void *opaque;
+ unsigned int version;
+ unsigned int width;
+ unsigned int height;
+} sizelib_image;
+
+#define SIZELIB_IMAGE_VERSION 1
+$sizers
+
+int sizelib_begin_read(sizelib_image *image, const void *memory, size_t size);
+int sizelib_finish_read(sizelib_image *image, void *buffer);
+SIZE_H
+ cat >"$root/fuzz/sizelib_fuzzer.c" <<'SIZE_FUZZ'
+#include <stdint.h>
+#include <stdlib.h>
+
+#include "sizelib.h"
+
+int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
+{
+ sizelib_image image;
+ void *buffer;
+
+ memset(&image, 0, sizeof image);
+ image.version = SIZELIB_IMAGE_VERSION;
+ sizelib_begin_read(&image, data, size);
+ buffer = malloc(SIZELIB_IMAGE_SIZE(image));
+ sizelib_finish_read(&image, buffer);
+ free(buffer);
+ return 0;
+}
+SIZE_FUZZ
+}
+
+SIZEROOT="$WORK/sized"
+rm -rf "$SIZEROOT"
+sizelib_tree "$SIZEROOT/stated" \
+ '#define SIZELIB_IMAGE_SIZE(image) ((image).width * (image).height)'
+SIZEPLAN="$OUT/sized-plan.txt"
+"$LISDEX" harness "$SIZEROOT/stated" --out "$OUT/sized-out" --plan-only --top 10 \
+ >"$SIZEPLAN" 2>&1
+if grep -q 'extending \["sizelib_finish_read"\]' "$SIZEPLAN"; then
+ ok "a buffer whose size the header's own macro states is allocated and the climb copies it"
+else
+ bad "the macro-stated capacity did not reach the climb: $(cat "$SIZEPLAN")"
+fi
+# The isolating control for the AFFINITY rule, and the one that keeps B67 whole. Identical
+# tree, identical signature, identical record - one #define removed. This is `png_read_image`
+# and `tj3Decompress8`, which must stay refused for exactly the reason B67 gives.
+sizelib_tree "$SIZEROOT/silent" '/* no macro states the size */'
+"$LISDEX" harness "$SIZEROOT/silent" --out "$OUT/sized-silent-out" --plan-only --top 10 \
+ >"$OUT/sized-silent.txt" 2>&1
+if grep 'extending' "$OUT/sized-silent.txt" | grep -q 'sizelib_finish_read'; then
+ bad "an out-param no macro states the size of was still bound: \
+$(grep extending "$OUT/sized-silent.txt")"
+else
+ ok "and with no macro naming it the same out-param still refuses, so B67 is intact"
+fi
+# 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 rather than zeroed.
+sizelib_tree "$SIZEROOT/two-arg" \
+ '#define SIZELIB_IMAGE_SIZE(image, row_stride) ((image).height * (row_stride))'
+"$LISDEX" harness "$SIZEROOT/two-arg" --out "$OUT/sized-two-out" --plan-only --top 10 \
+ >"$OUT/sized-two.txt" 2>&1
+if grep 'extending' "$OUT/sized-two.txt" | grep -q 'sizelib_finish_read'; then
+ bad "a macro needing a number the caller owns was applied anyway: \
+$(grep extending "$OUT/sized-two.txt")"
+else
+ ok "and a macro that needs a second argument states nothing, so the climb stops"
+fi
+# The isolating control for the AFFINITY half, which the silent tree above cannot give: here a
+# macro DOES state a size and takes exactly one argument, and it is about a different record.
+# Without the affinity test any `*_SIZE` in the header would answer for any buffer in the tree,
+# and libpng ships nine of them.
+sizelib_tree "$SIZEROOT/foreign" \
+ '#define OTHERLIB_FRAME_SIZE(frame) ((frame).width * (frame).height)'
+"$LISDEX" harness "$SIZEROOT/foreign" --out "$OUT/sized-foreign-out" --plan-only --top 10 \
+ >"$OUT/sized-foreign.txt" 2>&1
+if grep 'extending' "$OUT/sized-foreign.txt" | grep -q 'sizelib_finish_read'; then
+ bad "a size macro belonging to another record was applied anyway: \
+$(grep extending "$OUT/sized-foreign.txt")"
+else
+ ok "and a size macro with no affinity to this record answers for nothing"
+fi
+# The reach is from the CLIMB, not from the ranking. It has to be: the macro reads fields the
+# library writes, so as an entry point it would read a zeroed record and state zero - and a
+# zero-byte buffer handed to a decoder is the manufactured crash wearing the header's authority.
+if grep -q 'PLANS sizelib_finish_read' "$SIZEPLAN"; then
+ bad "sizelib_finish_read planned as an entry point, where the macro can only read zeros"
+else
+ ok "and the sized call cannot stand alone as an entry point, so only the climb reaches it"
+fi
+rm -rf "$SIZEROOT"
+
# The negative control the ladder must REFUSE to help: a tree with nothing to mine has no
# authored floor, so the ranking alone decides and no setup is invented.
BARE="$WORK/ladder-bare"
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m4-gate.sh b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m4-gate.sh
index 62af8e84..dbe14155 100755
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m4-gate.sh
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m4-gate.sh
@@ -41,11 +41,11 @@ fi
mkdir -p "$GATE"
-log "stage 1/13: build lisdex"
+log "stage 1/14: build lisdex"
cargo build -p lisdex
[ -x "$LISDEX_BIN" ] || die "lisdex binary not found at $LISDEX_BIN"
-log "stage 2/13: every oracle answers for itself"
+log "stage 2/14: every oracle answers for itself"
# The end-to-end controls below cannot isolate one coverage oracle from another: the stub
# and the unpopulated variant are each rejected by BOTH 3a and 3c, so either one alone
# keeps the gate green while the other is gutted. Each oracle owns unit tests that no
@@ -57,7 +57,7 @@ else
fail "the oracle crate's own tests do not pass - one of the four oracles is not doing its job"
fi
-log "stage 3/13: assemble the two corpora the oracles need"
+log "stage 3/14: assemble the two corpora the oracles need"
mkdir -p "$GATE"
rm -rf "$CORPUS" "$INVALID" "$CONTROLS"
mkdir -p "$CORPUS" "$INVALID" "$CONTROLS"
@@ -98,7 +98,7 @@ lisdex_verify() {
"$LISDEX_BIN" verify "$SRC" --include "$REPO" --work "$SCRATCH" "${FLAGS[@]}"
}
-log "stage 4/13: lisdex synthesizes AND self-verifies a harness with NO LLM"
+log "stage 4/14: lisdex synthesizes AND self-verifies a harness with NO LLM"
rm -rf "$SYNTH"
mapfile -d '' HARNESS_FLAGS < <(oracle_flags)
"$LISDEX_BIN" harness "$REPO" --out "$SYNTH" --top "$TOP" "${HARNESS_FLAGS[@]}" \
@@ -175,7 +175,7 @@ build_harness() {
)
}
-log "stage 5/13: independent cross-check - it compiles and every valid seed runs clean"
+log "stage 5/14: independent cross-check - it compiles and every valid seed runs clean"
if build_harness "$ENTRY" "$GATE/harness" afl 2>"$GATE/compile.log"; then
pass "synthesized harness compiles and links"
else
@@ -199,7 +199,7 @@ else
fail "$CRASHED/$SEEDS valid seeds crash or leak - the oracle would be unsound"
fi
-log "stage 6/13: the shipped judge ACCEPTS the harness it chose"
+log "stage 6/14: the shipped judge ACCEPTS the harness it chose"
if lisdex_verify "$ENTRY" "$GATE/verify-accepted" > "$GATE/verify-accepted.log" 2>&1; then
EDGES="$(grep -m1 -oE 'ACCEPTED.* - [0-9]+ edges' "$GATE/verify-accepted.log" \
| grep -oE '[0-9]+ edges' | grep -oE '^[0-9]+' || echo 0)"
@@ -213,7 +213,7 @@ else
fail "the shipped judge rejects the harness lisdex itself accepted"
fi
-log "stage 7/13: NEGATIVE CONTROL - a stub that ignores its input must be REJECTED"
+log "stage 7/14: NEGATIVE CONTROL - a stub that ignores its input must be REJECTED"
cat > "$CONTROLS/stub.c" <<'STUB'
// ©AngelaMos | 2026
// stub.c
@@ -241,7 +241,7 @@ else
fi
fi
-log "stage 8/13: NEGATIVE CONTROL - the unpopulated struct variant must be REJECTED"
+log "stage 8/14: NEGATIVE CONTROL - the unpopulated struct variant must be REJECTED"
VARIANTS="$(find "$SYNTH/candidates" -maxdepth 1 -name "$ENTRY_NAME.v*.c" | sort -V)"
VARIANT_COUNT="$(printf '%s\n' "$VARIANTS" | grep -c . || true)"
if [ "${VARIANT_COUNT:-0}" -lt 2 ]; then
@@ -256,7 +256,7 @@ else
fi
fi
-log "stage 9/13: NEGATIVE CONTROL - a harness that crashes on a valid seed must be REJECTED"
+log "stage 9/14: NEGATIVE CONTROL - a harness that crashes on a valid seed must be REJECTED"
cat > "$CONTROLS/crasher.c" <<'CRASHER'
// ©AngelaMos | 2026
// crasher.c
@@ -294,7 +294,7 @@ else
fi
fi
-log "stage 10/13: NEGATIVE CONTROL - a harness that leaks on a valid seed must be REJECTED"
+log "stage 10/14: NEGATIVE CONTROL - a harness that leaks on a valid seed must be REJECTED"
cat > "$CONTROLS/leaker.c" <<'LEAKER'
// ©AngelaMos | 2026
// leaker.c
@@ -331,7 +331,7 @@ else
fi
fi
-log "stage 11/13: lisdex drives a campaign against the SYNTHESIZED harness"
+log "stage 11/14: lisdex drives a campaign against the SYNTHESIZED harness"
rm -rf "$FINDINGS" "$DB"
"$LISDEX_BIN" fuzz \
--target "$GATE/harness" \
@@ -374,7 +374,7 @@ else
fail "crash is not an attributable magma canary trigger"
fi
-log "stage 12/13: oracle 3b judges an UPWARD extension, in both directions"
+log "stage 12/14: oracle 3b judges an UPWARD extension, in both directions"
# B51(b). Oracle 3b measures a candidate against the shorter call sequence it EXTENDS, so it
# needs a library whose author sequence continues past the entry point with a call this harness
# can copy. The census says no tree in the validation set has one - libpng's tail is
@@ -569,11 +569,126 @@ LAB_SEEDS
# harness renumbered every library edge - a parent's {13, 15, 32} became the child's
# {12, 14, 31, 35} for the same seed, sharing NOTHING - and the per-seed gains then varied with
# map size rather than with the input, which ACCEPTED a call doing identical work on every seed.
+# B82. Kept in its OWN header and its own translation unit, because the trees above take their
+# candidate list from `mylib.h` and two more exported functions there would move every ranking
+# stages 11-13 depend on. One archive, two objects; the trees see one header each.
+cat >"$LAB/lib/mylib_image.h" <<'IMAGE_H'
+#include <stddef.h>
+
+typedef struct mylib_image {
+ unsigned int version;
+ unsigned int width;
+ unsigned int height;
+ unsigned int acc;
+} mylib_image;
+
+#define MYLIB_IMAGE_VERSION 1
+#define MYLIB_IMAGE_SIZE(image) ((size_t)(image).width * (size_t)(image).height)
+#define MYLIB_IMAGE_BUFFER_SIZE(image, row_stride) \
+ ((size_t)(image).height * (size_t)(row_stride))
+
+int mylib_begin_read(mylib_image *image, const void *buff, size_t size);
+int mylib_finish_read(mylib_image *image, void *buffer);
+IMAGE_H
+cat >"$LAB/lib/mylib_image.c" <<'IMAGE_C'
+#include "mylib_image.h"
+
+/* Eight distinct blocks, for the same reason mylib.c has them: the PARENT harness has to clear
+ oracle 3a's inter-seed divergence floor of 5 edges before there is an extension to judge. The
+ bodies must have a lasting effect - a first version added and subtracted the same constant,
+ which the optimizer folded to nothing and identical-code-folding then merged into ONE edge. */
+#define TINT(n) static void tint##n(mylib_image *i) { i->acc += n * 7u + 1u; }
+TINT(0) TINT(1) TINT(2) TINT(3) TINT(4) TINT(5) TINT(6) TINT(7)
+
+/* The header reads the dimensions and nothing else, exactly as png_image_begin_read_from_memory
+ does, so MYLIB_IMAGE_SIZE states nothing until this has run. */
+int mylib_begin_read(mylib_image *image, const void *buff, size_t size)
+{
+ const unsigned char *bytes = (const unsigned char *)buff;
+ size_t at;
+
+ if (image == NULL || image->version != MYLIB_IMAGE_VERSION) { return 0; }
+ if (bytes == NULL || size < 2) { return 0; }
+ for (at = 0; at < size && at < 24; at++) {
+ switch (bytes[at] & 7u) {
+ case 0: tint0(image); break;
+ case 1: tint1(image); break;
+ case 2: tint2(image); break;
+ case 3: tint3(image); break;
+ case 4: tint4(image); break;
+ case 5: tint5(image); break;
+ case 6: tint6(image); break;
+ default: tint7(image); break;
+ }
+ }
+ image->width = (unsigned int)bytes[0] + 1u;
+ image->height = (unsigned int)bytes[1] + 1u;
+ return 1;
+}
+
+/* Writes the WHOLE buffer on purpose. That is what makes this stage a measurement rather than a
+ compile check: a harness that allocated anything less than MYLIB_IMAGE_SIZE bytes is a
+ heap-buffer-overflow with the library's frames on top, which is the D12 crash B82 is built to
+ avoid, and ASAN reports it here instead of in a real target. */
+int mylib_finish_read(mylib_image *image, void *buffer)
+{
+ unsigned char *out = (unsigned char *)buffer;
+ size_t total;
+ size_t at;
+
+ if (image == NULL || out == NULL) { return 0; }
+ total = MYLIB_IMAGE_SIZE(*image);
+ if (total == 0) { return 0; }
+ for (at = 0; at < total; at++) {
+ out[at] = (unsigned char)(at ^ (size_t)image->width);
+ }
+ switch (image->height & 7u) {
+ case 0: out[0] ^= 1u; break;
+ case 1: out[0] ^= 2u; break;
+ case 2: out[0] ^= 4u; break;
+ case 3: out[0] ^= 8u; break;
+ case 4: out[0] ^= 16u; break;
+ case 5: out[0] ^= 32u; break;
+ case 6: out[0] ^= 64u; break;
+ default: out[0] ^= 128u; break;
+ }
+ return 1;
+}
+IMAGE_C
+mkdir -p "$LAB/sized/include" "$LAB/sized/fuzz"
+cp "$LAB/lib/mylib_image.h" "$LAB/sized/include/mylib_image.h"
+cat >"$LAB/sized/fuzz/mylib_image_fuzzer.c" <<'IMAGE_FUZZ'
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "mylib_image.h"
+
+int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size)
+{
+ mylib_image image;
+ void *buffer;
+
+ memset(&image, 0, sizeof image);
+ image.version = MYLIB_IMAGE_VERSION;
+ if (mylib_begin_read(&image, data, size)) {
+ buffer = malloc(MYLIB_IMAGE_SIZE(image));
+ if (buffer != NULL) {
+ mylib_finish_read(&image, buffer);
+ free(buffer);
+ }
+ }
+ return 0;
+}
+IMAGE_FUZZ
+
(
cd "$LAB/lib"
env AFL_USE_ASAN=1 AFL_USE_UBSAN=1 AFL_QUIET=1 \
afl-clang-fast -g -O1 -I. -c mylib.c -o mylib.o
- llvm-ar rcs libmylib.a mylib.o
+ env AFL_USE_ASAN=1 AFL_USE_UBSAN=1 AFL_QUIET=1 \
+ afl-clang-fast -g -O1 -I. -c mylib_image.c -o mylib_image.o
+ llvm-ar rcs libmylib.a mylib.o mylib_image.o
) >"$LAB/build.log" 2>&1 || die "the synthetic oracle-3b library does not build"
lab_run() {
@@ -628,7 +743,7 @@ else
fail "the incomparable-map guard did not fire on a relinked LTO archive"
fi
-log "stage 13/13: a library-filled out-param compiles and runs against the real header"
+log "stage 13/14: a library-filled out-param compiles and runs against the real header"
# B81. m3 asserts the PLAN says AddressOf and the emitted C declares the slot. Those are claims
# about text. This is the claim text cannot make: the same library, a third tree, and the appended
# `mylib_next_entry(ctx, &lisdex_filled)` has to type-check against the real header, link, and run
@@ -669,6 +784,59 @@ else
fail "a measurable cross-harness total was suppressed against an object archive"
fi
+log "stage 14/14: a macro-stated capacity is allocated, is the right size, and is released"
+# B82. m3 asserts the PLAN appends the call and the three controls each go red alone. Those are
+# claims about text. This is the claim text cannot make: the appended
+# `mylib_finish_read(&ctx, (void *)lisdex_sized)` has to type-check against the real header,
+# link, and run clean on every seed with ASAN watching - and `mylib_finish_read` writes every
+# byte MYLIB_IMAGE_SIZE claims, so a buffer even one byte short is a heap-buffer-overflow here
+# rather than in a real target.
+#
+# The VERDICT is deliberately not asserted, for the same reason stage 13 does not assert one:
+# whether oracle 3b can judge the relink is B80's remaining half, not B82's.
+lab_run sized
+if grep -qE 'extended by 1 author call\(s\): mylib_finish_read|appending mylib_finish_read' \
+ "$LAB/sized.log" && ! grep -q 'does not compile' "$LAB/sized.log"; then
+ pass "a buffer sized by the header's own macro compiles and runs against the real header"
+else
+ tail -6 "$LAB/sized.log" >&2
+ fail "the macro-sized extension never reached the oracle that judges it"
+fi
+# The size itself, which is the assertion this whole stage exists for, and the phrasing is the
+# result of a gutting pass rather than a guess: a first version grepped the log for
+# `AddressSanitizer`, and lisdex does not print that - it reports "crashed on seed X" - so the
+# assertion stayed green with the guard gutted AND with the free gutted. `crashed` is the word
+# that moves. An under-allocated buffer is a heap-buffer-overflow, a missing free is a
+# LeakSanitizer report, and a missing NULL guard is a memset through NULL; all three arrive here.
+if grep -q 'appending mylib_finish_read' "$LAB/sized.log" \
+ && ! grep -q 'appending mylib_finish_read - crashed on seed' "$LAB/sized.log"; then
+ pass "and every byte the library claimed was writable and released, on every seed"
+else
+ grep -m2 'appending mylib_finish_read' "$LAB/sized.log" >&2
+ fail "the macro-sized buffer did not survive execution against the real library"
+fi
+# The EXTENDED candidate by name, never `find | head -1`: the candidates directory also holds
+# the two unextended variants, and reading one of those would assert nothing about the climb.
+SIZED_C="$(find "$LAB/out-sized" -maxdepth 2 -name '*.up1.c' | head -1)"
+if [ -n "$SIZED_C" ] \
+ && grep -q 'size_t lisdex_sized_len = (size_t)(MYLIB_IMAGE_SIZE(ctx));' "$SIZED_C" \
+ && grep -q 'malloc(lisdex_sized_len) : NULL;' "$SIZED_C" \
+ && grep -q 'if (lisdex_sized == NULL) {' "$SIZED_C" \
+ && grep -q 'free(lisdex_sized);' "$SIZED_C"; then
+ pass "the emitted C states the size from the macro, bails on a failed or empty allocation, frees it"
+else
+ fail "the emitted C does not own the buffer it sized: \
+$(grep -n 'lisdex_sized' "${SIZED_C:-/dev/null}" | head -4)"
+fi
+# The arity filter, in the SHIPPED pipeline rather than in a synthetic plan. The lab header
+# ships `MYLIB_IMAGE_BUFFER_SIZE(image, row_stride)`, which is named for this parameter and
+# sorts ahead of the record's own macro - applying it would mean inventing the stride.
+if [ -n "$SIZED_C" ] && ! grep -q 'MYLIB_IMAGE_BUFFER_SIZE' "$SIZED_C"; then
+ pass "and the two-argument macro named for the parameter was passed over, not given a zero"
+else
+ fail "a macro needing a number the caller owns reached the emitted harness"
+fi
+
printf '\n'
if [ "$FAILURES" -eq 0 ]; then
printf '[m4] M4 EXIT GATE PASSED - the none tier synthesized and self-verified a harness with no LLM\n'