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): B31 - a static name means one function per file, and 84% of the row's "lost" danger was correctly discarded

CarterPerez-dev106bf64c3c87
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs
index ee2d45cc..9db8120f 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/complexity.rs
@@ -2,7 +2,7 @@
// complexity.rs
use std::collections::{BTreeMap, BTreeSet, VecDeque};
-use std::path::Path;
+use std::path::{Path, PathBuf};
use clang::{Entity, EntityKind, Linkage};
@@ -10,14 +10,46 @@ use crate::extract::{self, ExtractError, ParseOptions};
pub const BASE_COMPLEXITY: u32 = 1;
+// C gives a name meaning only within a linkage. An external name is one function across the
+// whole program, so the name alone identifies it. An internal name is one function per
+// definition site, and libarchive has 71 names that mean different bodies in different files
+// - `free_data` is eleven unrelated functions. Keying those on the name alone discarded 107
+// distinct bodies and 912 danger. The definition site is what separates them, and it also
+// merges the opposite case: openjpeg's `opj_int_ceildiv` is one `static` body in a header
+// that 30 translation units each see, and all 30 share this key.
+#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
+pub struct Symbol {
+ pub name: String,
+ pub unit: Option<PathBuf>,
+}
+
+impl Symbol {
+ #[must_use]
+ pub fn exported(name: impl Into<String>) -> Self {
+ Self {
+ name: name.into(),
+ unit: None,
+ }
+ }
+
+ #[must_use]
+ pub fn internal(name: impl Into<String>, unit: impl Into<PathBuf>) -> Self {
+ Self {
+ name: name.into(),
+ unit: Some(unit.into()),
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct Defined {
pub name: String,
+ pub origin: PathBuf,
pub own: u32,
pub loops: u32,
pub nested_loops: u32,
pub max_nesting: u32,
- pub calls: Vec<String>,
+ pub calls: Vec<Symbol>,
pub exported: bool,
}
@@ -29,6 +61,15 @@ impl Defined {
.saturating_add(self.nested_loops)
.saturating_add(self.max_nesting)
}
+
+ #[must_use]
+ pub fn symbol(&self) -> Symbol {
+ if self.exported {
+ Symbol::exported(self.name.clone())
+ } else {
+ Symbol::internal(self.name.clone(), self.origin.clone())
+ }
+ }
}
#[must_use]
@@ -64,7 +105,23 @@ struct Metrics {
loops: u32,
nested_loops: u32,
max_nesting: u32,
- calls: BTreeSet<String>,
+ calls: BTreeSet<Symbol>,
+}
+
+fn origin_of(entity: &Entity) -> Option<PathBuf> {
+ Some(entity.get_location()?.get_file_location().file?.get_path())
+}
+
+// The callee's own linkage decides how it is named, and clang has already resolved the
+// reference, so the answer is exact rather than a guess from the call site's file.
+fn callee(target: &Entity) -> Option<Symbol> {
+ let name = target.get_name()?;
+ if target.get_linkage() == Some(Linkage::Internal) {
+ let body = target.get_definition().unwrap_or(*target);
+ Some(Symbol::internal(name, origin_of(&body)?))
+ } else {
+ Some(Symbol::exported(name))
+ }
}
fn walk(entity: &Entity, metrics: &mut Metrics, depth: u32, loop_depth: u32) {
@@ -86,9 +143,9 @@ fn walk(entity: &Entity, metrics: &mut Metrics, depth: u32, loop_depth: u32) {
if kind == EntityKind::CallExpr
&& let Some(target) = child.get_reference()
&& target.get_kind() == EntityKind::FunctionDecl
- && let Some(name) = target.get_name()
+ && let Some(symbol) = callee(&target)
{
- metrics.calls.insert(name);
+ metrics.calls.insert(symbol);
}
let chained_else = parent_is_if && kind == EntityKind::IfStmt && position == last;
let next_depth = if is_nesting(kind) && !chained_else {
@@ -149,6 +206,9 @@ fn collect(entity: &Entity, found: &mut Vec<Defined>, seen: &mut BTreeSet<String
let Some(name) = entity.get_name() else {
return;
};
+ let Some(origin) = origin_of(entity) else {
+ return;
+ };
if !seen.insert(name.clone()) {
return;
}
@@ -156,6 +216,7 @@ fn collect(entity: &Entity, found: &mut Vec<Defined>, seen: &mut BTreeSet<String
walk(entity, &mut metrics, 0, 0);
found.push(Defined {
name,
+ origin,
own: BASE_COMPLEXITY + metrics.decisions,
loops: metrics.loops,
nested_loops: metrics.nested_loops,
@@ -175,7 +236,7 @@ fn collect(entity: &Entity, found: &mut Vec<Defined>, seen: &mut BTreeSet<String
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CallGraph {
- nodes: BTreeMap<String, Defined>,
+ nodes: BTreeMap<Symbol, Defined>,
}
impl From<Vec<Defined>> for CallGraph {
@@ -183,50 +244,64 @@ impl From<Vec<Defined>> for CallGraph {
Self {
nodes: defined
.into_iter()
- .map(|item| (item.name.clone(), item))
+ .map(|item| (item.symbol(), item))
.collect(),
}
}
}
impl CallGraph {
- #[must_use]
- pub fn get(&self, name: &str) -> Option<&Defined> {
- self.nodes.get(name)
+ // Every by-name query on this graph carries a name a public header declared, and a header
+ // declares each name once. Resolving it by name rather than by key keeps that query
+ // answerable for the one library that declares a `static inline` in its own header, whose
+ // node exists only under an internal key. External linkage sorts first, so an exported
+ // definition always wins over a same-named internal one.
+ fn resolve(&self, name: &str) -> Option<(&Symbol, &Defined)> {
+ self.nodes
+ .range(Symbol::exported(name)..)
+ .take_while(|(symbol, _)| symbol.name == name)
+ .next()
}
#[must_use]
- pub fn own(&self, name: &str) -> u32 {
- self.nodes.get(name).map_or(0, |node| node.own)
+ pub fn get(&self, name: &str) -> Option<&Defined> {
+ self.resolve(name).map(|(_, node)| node)
}
- pub fn names(&self) -> impl Iterator<Item = &String> {
- self.nodes.keys()
+ #[must_use]
+ pub fn own(&self, symbol: &Symbol) -> u32 {
+ self.nodes.get(symbol).map_or(0, |node| node.own)
}
#[must_use]
- pub fn reachable_from(&self, seeds: &[String]) -> BTreeSet<String> {
+ pub fn reachable_from(&self, seeds: &[String]) -> BTreeSet<Symbol> {
let mut visited = BTreeSet::new();
- let mut queue: VecDeque<&str> = VecDeque::new();
- for seed in seeds {
- queue.push_back(seed.as_str());
- }
- while let Some(name) = queue.pop_front() {
- let Some(node) = self.nodes.get(name) else {
+ let mut queue: VecDeque<Symbol> = seeds
+ .iter()
+ .filter_map(|seed| self.resolve(seed).map(|(symbol, _)| symbol.clone()))
+ .collect();
+ while let Some(symbol) = queue.pop_front() {
+ let Some(node) = self.nodes.get(&symbol) else {
continue;
};
- if !visited.insert(node.name.clone()) {
+ if !visited.insert(symbol) {
continue;
}
for call in &node.calls {
if !visited.contains(call) {
- queue.push_back(call.as_str());
+ queue.push_back(call.clone());
}
}
}
visited
}
+ #[must_use]
+ pub fn reaches(&self, reached: &BTreeSet<Symbol>, name: &str) -> bool {
+ self.resolve(name)
+ .is_some_and(|(symbol, _)| reached.contains(symbol))
+ }
+
#[must_use]
pub fn accumulated(&self, name: &str) -> u32 {
self.reachable_from(std::slice::from_ref(&name.to_owned()))
@@ -237,23 +312,28 @@ impl CallGraph {
#[must_use]
pub fn danger(&self, name: &str) -> u32 {
- self.nodes.get(name).map_or(0, Defined::danger)
+ self.get(name).map_or(0, Defined::danger)
+ }
+
+ #[must_use]
+ pub fn danger_of(&self, symbol: &Symbol) -> u32 {
+ self.nodes.get(symbol).map_or(0, Defined::danger)
}
#[must_use]
pub fn accumulated_danger(&self, name: &str) -> u32 {
self.reachable_from(std::slice::from_ref(&name.to_owned()))
.iter()
- .map(|reached| self.danger(reached))
+ .map(|reached| self.danger_of(reached))
.sum()
}
#[must_use]
- pub fn undiscovered_danger(&self, name: &str, already: &BTreeSet<String>) -> u32 {
+ pub fn undiscovered_danger(&self, name: &str, already: &BTreeSet<Symbol>) -> u32 {
self.reachable_from(std::slice::from_ref(&name.to_owned()))
.iter()
.filter(|reached| !already.contains(*reached))
- .map(|reached| self.danger(reached))
+ .map(|reached| self.danger_of(reached))
.sum()
}
}
@@ -326,8 +406,8 @@ mod tests {
int f(int a) { return helper(a) + other(a); }\n",
);
let calls = &find(&found, "f").calls;
- assert!(calls.contains(&"helper".to_owned()), "{calls:?}");
- assert!(calls.contains(&"other".to_owned()), "{calls:?}");
+ assert!(calls.contains(&Symbol::exported("helper")), "{calls:?}");
+ assert!(calls.contains(&Symbol::exported("other")), "{calls:?}");
}
#[test]
@@ -433,6 +513,7 @@ mod tests {
fn danger_combines_cyclomatic_complexity_with_the_loop_metrics() {
let plain = Defined {
name: "plain".to_owned(),
+ origin: PathBuf::new(),
own: 5,
loops: 0,
nested_loops: 0,
@@ -457,11 +538,15 @@ mod tests {
#[test]
fn undiscovered_danger_excludes_what_an_existing_harness_already_reaches() {
let graph = CallGraph::from(vec![
- node("entry", 2, vec!["covered", "fresh"]),
+ node(
+ "entry",
+ 2,
+ vec![Symbol::exported("covered"), Symbol::exported("fresh")],
+ ),
node("covered", 10, vec![]),
node("fresh", 20, vec![]),
]);
- let already = BTreeSet::from(["covered".to_owned()]);
+ let already = BTreeSet::from([Symbol::exported("covered")]);
assert_eq!(graph.accumulated_danger("entry"), 32);
assert_eq!(graph.undiscovered_danger("entry", &already), 22);
}
@@ -469,7 +554,7 @@ mod tests {
#[test]
fn undiscovered_equals_accumulated_when_no_harness_exists() {
let graph = CallGraph::from(vec![
- node("entry", 3, vec!["leaf"]),
+ node("entry", 3, vec![Symbol::exported("leaf")]),
node("leaf", 9, vec![]),
]);
let nothing = BTreeSet::new();
@@ -480,42 +565,43 @@ mod tests {
);
}
- fn node(name: &str, danger: u32, calls: Vec<&str>) -> Defined {
+ fn node(name: &str, danger: u32, calls: Vec<Symbol>) -> Defined {
Defined {
name: name.to_owned(),
+ origin: PathBuf::new(),
own: danger,
loops: 0,
nested_loops: 0,
max_nesting: 0,
- calls: calls.into_iter().map(str::to_owned).collect(),
+ calls,
exported: true,
}
}
+ fn hidden(name: &str, unit: &str, danger: u32, calls: Vec<Symbol>) -> Defined {
+ Defined {
+ name: name.to_owned(),
+ origin: PathBuf::from(unit),
+ own: danger,
+ loops: 0,
+ nested_loops: 0,
+ max_nesting: 0,
+ calls,
+ exported: false,
+ }
+ }
+
#[test]
fn accumulated_complexity_sums_the_whole_reachable_call_tree() {
let graph = CallGraph::from(vec![
- Defined {
- name: "entry".to_owned(),
- own: 2,
- calls: vec!["middle".to_owned()],
- exported: true,
- ..Defined::default()
- },
- Defined {
- name: "middle".to_owned(),
- own: 5,
- calls: vec!["leaf".to_owned()],
- exported: false,
- ..Defined::default()
- },
- Defined {
- name: "leaf".to_owned(),
- own: 10,
- calls: Vec::new(),
- exported: false,
- ..Defined::default()
- },
+ node("entry", 2, vec![Symbol::internal("middle", "unit.c")]),
+ hidden(
+ "middle",
+ "unit.c",
+ 5,
+ vec![Symbol::internal("leaf", "unit.c")],
+ ),
+ hidden("leaf", "unit.c", 10, vec![]),
]);
assert_eq!(graph.accumulated("entry"), 17);
assert_eq!(graph.accumulated("middle"), 15);
@@ -525,27 +611,14 @@ mod tests {
#[test]
fn a_recursive_cycle_does_not_hang_or_double_count() {
let graph = CallGraph::from(vec![
- Defined {
- name: "a".to_owned(),
- own: 1,
- calls: vec!["b".to_owned()],
- exported: true,
- ..Defined::default()
- },
- Defined {
- name: "b".to_owned(),
- own: 2,
- calls: vec!["a".to_owned(), "c".to_owned()],
- exported: false,
- ..Defined::default()
- },
- Defined {
- name: "c".to_owned(),
- own: 4,
- calls: vec!["b".to_owned()],
- exported: false,
- ..Defined::default()
- },
+ node("a", 1, vec![Symbol::internal("b", "unit.c")]),
+ hidden(
+ "b",
+ "unit.c",
+ 2,
+ vec![Symbol::exported("a"), Symbol::internal("c", "unit.c")],
+ ),
+ hidden("c", "unit.c", 4, vec![Symbol::internal("b", "unit.c")]),
]);
assert_eq!(graph.accumulated("a"), 7);
}
@@ -558,44 +631,119 @@ mod tests {
#[test]
fn calls_into_functions_with_no_definition_are_ignored_not_counted() {
- let graph = CallGraph::from(vec![Defined {
- name: "entry".to_owned(),
- own: 3,
- calls: vec!["memcpy".to_owned(), "malloc".to_owned()],
- exported: true,
- ..Defined::default()
- }]);
+ let graph = CallGraph::from(vec![node(
+ "entry",
+ 3,
+ vec![Symbol::exported("memcpy"), Symbol::exported("malloc")],
+ )]);
assert_eq!(graph.accumulated("entry"), 3);
}
#[test]
fn the_set_of_functions_reachable_from_a_seed_is_the_novelty_frontier() {
let graph = CallGraph::from(vec![
- Defined {
- name: "harness_calls_this".to_owned(),
- own: 1,
- calls: vec!["deep".to_owned()],
- exported: true,
- ..Defined::default()
- },
- Defined {
- name: "deep".to_owned(),
- own: 1,
- calls: Vec::new(),
- exported: false,
- ..Defined::default()
- },
- Defined {
- name: "untouched".to_owned(),
- own: 1,
- calls: Vec::new(),
- exported: true,
- ..Defined::default()
- },
+ node(
+ "harness_calls_this",
+ 1,
+ vec![Symbol::internal("deep", "unit.c")],
+ ),
+ hidden("deep", "unit.c", 1, vec![]),
+ node("untouched", 1, vec![]),
]);
let reached = graph.reachable_from(&["harness_calls_this".to_owned()]);
- assert!(reached.contains("harness_calls_this"));
- assert!(reached.contains("deep"));
- assert!(!reached.contains("untouched"));
+ assert!(graph.reaches(&reached, "harness_calls_this"));
+ assert!(graph.reaches(&reached, "deep"));
+ assert!(!graph.reaches(&reached, "untouched"));
+ }
+
+ #[test]
+ fn a_static_name_in_two_files_is_two_nodes_not_one() {
+ let graph = CallGraph::from(vec![
+ node("entry_a", 1, vec![Symbol::internal("init", "a.c")]),
+ node("entry_b", 1, vec![Symbol::internal("init", "b.c")]),
+ hidden("init", "a.c", 3, vec![]),
+ hidden("init", "b.c", 12, vec![]),
+ ]);
+ assert_eq!(
+ graph.accumulated_danger("entry_a"),
+ 4,
+ "libarchive has 71 names that mean a different body in a different file"
+ );
+ assert_eq!(
+ graph.accumulated_danger("entry_b"),
+ 13,
+ "keying on the bare name reported this as 4 as well, discarding the larger body"
+ );
+ }
+
+ #[test]
+ fn one_static_body_a_header_shares_is_still_a_single_node() {
+ let shared = Symbol::internal("inlined", "shared.h");
+ let graph = CallGraph::from(vec![
+ node("entry_a", 1, vec![shared.clone()]),
+ node("entry_b", 1, vec![shared.clone()]),
+ hidden("inlined", "shared.h", 7, vec![]),
+ hidden("inlined", "shared.h", 7, vec![]),
+ ]);
+ assert_eq!(
+ graph.accumulated_danger("entry_a"),
+ 8,
+ "openjpeg's opj_int_ceildiv is one body that 30 units each see, so separating \
+ the copies would have inflated the tree instead of correcting it"
+ );
+ assert_eq!(graph.reachable_from(&["entry_a".to_owned()]).len(), 2);
+ }
+
+ #[test]
+ fn an_exported_definition_answers_a_name_query_before_an_internal_one() {
+ let graph = CallGraph::from(vec![
+ hidden("shared", "front_end.c", 40, vec![]),
+ node("shared", 3, vec![]),
+ ]);
+ assert_eq!(
+ graph.danger("shared"),
+ 3,
+ "a name a public header declares is the exported definition, never a front-end \
+ static that happens to match"
+ );
+ }
+
+ #[test]
+ fn two_units_defining_the_same_static_keep_both_measured_bodies() {
+ let dir = lisdex_core::scratch::path("complexity-tucollide");
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ let small = dir.join("a.c");
+ let large = dir.join("b.c");
+ std::fs::write(
+ &small,
+ "static int init(void) { return 0; }\n\
+ int entry_a(void) { return init(); }\n",
+ )
+ .unwrap();
+ std::fs::write(
+ &large,
+ "static int init(int a) {\n\
+ if (a) { return 1; }\n\
+ if (a > 1) { return 2; }\n\
+ if (a > 2) { return 3; }\n\
+ return 0;\n\
+ }\n\
+ int entry_b(void) { return init(0); }\n",
+ )
+ .unwrap();
+
+ let options = ParseOptions::default();
+ let mut all = parse_source(&small, &options).unwrap();
+ all.extend(parse_source(&large, &options).unwrap());
+ let graph = CallGraph::from(all);
+
+ assert_eq!(graph.accumulated_danger("entry_a"), 2);
+ assert_eq!(
+ graph.accumulated_danger("entry_b"),
+ 6,
+ "b.c's init is four decisions deep; keying on the bare name kept only a.c's \
+ one-line body and reported this as 2"
+ );
}
}
diff --git a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs
index 23ea4bb5..c356ee21 100644
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/crates/lisdex-surface/src/surface.rs
@@ -267,7 +267,7 @@ fn read_sources(
match complexity::parse_source(&source, &parse) {
Ok(found) => {
for item in found {
- if seen.insert(item.name.clone()) {
+ if seen.insert(item.symbol()) {
defined.push(item);
}
}
@@ -377,7 +377,7 @@ pub fn analyze(options: &SurfaceOptions) -> Result<Surface, SurfaceError> {
accumulated: graph.accumulated_danger(&item.name),
undiscovered: graph.undiscovered_danger(&item.name, &reached),
},
- reachable_from_harness: reached.contains(&item.name)
+ reachable_from_harness: graph.reaches(&reached, &item.name)
|| directly_called.contains(&item.name),
})
.collect();
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 6ad62b5f..f73d2493 100755
--- a/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh
+++ b/PROJECTS/advanced/zero-day-vulnerability-scanner/scripts/m3-gate.sh
@@ -918,6 +918,127 @@ else
fi
rm -rf "$BARE"
+banner "B31 A STATIC NAME MEANS ONE FUNCTION PER FILE, NOT ONE PER TREE"
+# Two assertions, pointing opposite ways, because the two failure modes are opposite and a
+# single one alibis the other. Keying nodes on the bare name merges bodies that are not the
+# same function (libarchive: 71 names, 107 bodies, 912 danger discarded). Keying them on the
+# TRANSLATION UNIT rather than the definition site splits a body that IS the same function
+# (openjpeg: `opj_int_ceildiv` is one `static` in a header that 30 units each see). Neither
+# assertion carries a threshold, so upstream drift in the cloned trees cannot move them.
+B31ROOT="$WORK/b31"
+B31SRC="$B31ROOT/collide"
+rm -rf "$B31ROOT"
+mkdir -p "$B31SRC/include"
+cat >"$B31SRC/include/collide.h" <<'EOF'
+#ifndef COLLIDE_H
+#define COLLIDE_H
+#include <stddef.h>
+int entry_large(const unsigned char *data, size_t size);
+int entry_small(const unsigned char *data, size_t size);
+int entry_left(const unsigned char *data, size_t size);
+int entry_right(const unsigned char *data, size_t size);
+#endif
+EOF
+cat >"$B31SRC/shared.h" <<'EOF'
+#ifndef COLLIDE_SHARED_H
+#define COLLIDE_SHARED_H
+#include <stddef.h>
+static int shared_helper(const unsigned char *d, size_t n)
+{
+ int total = 0;
+ size_t i;
+ for (i = 0; i < n; i++) {
+ if (d[i] > 8) { total++; }
+ }
+ return total;
+}
+#endif
+EOF
+# a_ and z_ prefixes fix the walk order: the large body is parsed FIRST, so under bare-name
+# keying it is the one that survives and entry_small inherits complexity it does not have.
+cat >"$B31SRC/a_large.c" <<'EOF'
+#include "collide.h"
+static int helper(const unsigned char *d, size_t n)
+{
+ int total = 0;
+ size_t i;
+ for (i = 0; i < n; i++) {
+ if (d[i] == 1) { total += 1; }
+ if (d[i] == 2) { total += 2; }
+ if (d[i] == 3) { total += 3; }
+ if (d[i] == 4) { total += 4; }
+ }
+ return total;
+}
+int entry_large(const unsigned char *data, size_t size) { return helper(data, size); }
+EOF
+cat >"$B31SRC/z_small.c" <<'EOF'
+#include "collide.h"
+static int helper(const unsigned char *d, size_t n) { return n > 0 ? d[0] : 0; }
+int entry_small(const unsigned char *data, size_t size) { return helper(data, size); }
+EOF
+cat >"$B31SRC/left.c" <<'EOF'
+#include "collide.h"
+#include "shared.h"
+int entry_left(const unsigned char *data, size_t size) { return shared_helper(data, size); }
+EOF
+cat >"$B31SRC/right.c" <<'EOF'
+#include "collide.h"
+#include "shared.h"
+int entry_right(const unsigned char *data, size_t size) { return shared_helper(data, size); }
+EOF
+
+accumulated_of() {
+ python3 - "$1" "$2" <<'PY'
+import json, sys
+data = json.load(open(sys.argv[1]))
+for candidate in data["ranking"]["candidates"]:
+ if candidate["name"] == sys.argv[2]:
+ print(candidate["complexity"]["accumulated"])
+ break
+else:
+ print(-1)
+PY
+}
+
+defined_of() {
+ python3 - "$1" <<'PY'
+import json, sys
+print(json.load(open(sys.argv[1]))["defined"])
+PY
+}
+
+# The fixture holds exactly seven bodies: four entry points, a_large's helper, z_small's
+# helper, and the one shared_helper the header gives both left.c and right.c. That count is
+# a three-way discriminator and the reason this stage does not compare left against right -
+# splitting one shared body per unit yields two nodes of IDENTICAL danger, so accumulated
+# stays equal on both sides and the comparison could never see it.
+B31_EXPECTED_BODIES=7
+if "$LISDEX" surface "$B31SRC" --json >"$OUT/b31.json" 2>"$OUT/b31.err"; then
+ B31_LARGE="$(accumulated_of "$OUT/b31.json" entry_large)"
+ B31_SMALL="$(accumulated_of "$OUT/b31.json" entry_small)"
+ B31_BODIES="$(defined_of "$OUT/b31.json")"
+ if [ "$B31_LARGE" -lt 0 ] || [ "$B31_SMALL" -lt 0 ]; then
+ bad "the b31 fixture did not rank entry_large and entry_small (see $OUT/b31.json)"
+ elif [ "$B31_LARGE" -gt "$B31_SMALL" ]; then
+ ok "a same-named static in two files stays two bodies (large $B31_LARGE > small $B31_SMALL)"
+ else
+ bad "two unrelated statics named helper were merged (large $B31_LARGE, small $B31_SMALL)"
+ fi
+ if [ "$B31_BODIES" -eq "$B31_EXPECTED_BODIES" ]; then
+ ok "the fixture graph holds $B31_BODIES bodies, one per definition site"
+ elif [ "$B31_BODIES" -lt "$B31_EXPECTED_BODIES" ]; then
+ bad "only $B31_BODIES of $B31_EXPECTED_BODIES bodies survived; a name-keyed graph \
+discards the helper that sorts second"
+ else
+ bad "$B31_BODIES bodies for $B31_EXPECTED_BODIES definition sites; keying on the \
+translation unit splits the one body the shared header gives both units"
+ fi
+else
+ bad "surface refused the b31 fixture: $(head -1 "$OUT/b31.err")"
+fi
+rm -rf "$B31ROOT"
+
banner "B29 RANKING MEASURED AGAINST AN UNINFORMED ORDERING"
# The band assertions above check six hand-picked functions. They cannot say whether the
# ORDERING carries information, because a ranking that put those six first and everything