crates/kleene-index/tests/call_sites.rs
//! Address to call site: a set whose `site` table has the address column `site.addr` gets a
//! static search tree over those addresses, and an address gives back the site row (the
//! site id), as a map from address to its first row would. A set without the column has
//! no such index.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use graphar::mapped::{IntColumn, IntEdges, IntGraphWriter};
use kleene_gar::GarGraph;
use kleene_index::{IndexSet, SITE_ADDR, Store};
use kleene_sparse::CpuDevice;
/// xorshift64*: a fixed stream per seed.
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_f491_4f6c_dd1d)
}
}
struct Tmp(PathBuf);
impl Tmp {
fn new(tag: &str) -> Tmp {
let d = std::env::temp_dir().join(format!("kleene-sites-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
Tmp(d)
}
}
impl Drop for Tmp {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A set of `n` instructions and one site per entry of `addrs` (site `i` at instruction
/// `i % n`, at address `addrs[i]` when `with_addr`), with a root hash.
fn write_set(dir: &Path, n: u32, addrs: &[u64], with_addr: bool) {
let mut w = IntGraphWriter::new(dir, "X").unwrap();
w.vertices("inst", n, vec![]).unwrap();
let mut cols = vec![(
"iid".to_string(),
IntColumn::U32((0..addrs.len() as u32).map(|i| i % n).collect()),
)];
if with_addr {
cols.push((SITE_ADDR.1.to_string(), IntColumn::U64(addrs.to_vec())));
}
w.vertices(SITE_ADDR.0, addrs.len() as u32, cols).unwrap();
let e = IntEdges::from_pairs(("inst", "icall", "inst"), (n, n), &[0], &[1], vec![]).unwrap();
w.edges(e).unwrap();
w.finish().unwrap();
std::fs::write(dir.join("root"), [7u8; 32]).unwrap();
}
fn open(set: &Path, kix: &Path) -> IndexSet {
IndexSet::with(
GarGraph::open(set).unwrap(),
Store::at(set, kix).unwrap(),
CpuDevice::default(),
)
}
/// Call-site addresses as a linker lays them out: rising within a function, functions in
/// any order, a few sites sharing an address (two candidates of one call).
fn addresses(n: usize, seed: u64) -> Vec<u64> {
let mut r = Rng(seed);
let mut funcs: Vec<Vec<u64>> = Vec::new();
let mut at = 0x40_1000u64;
while funcs.iter().map(Vec::len).sum::<usize>() < n {
let k = 1 + (r.next() % 12) as usize;
let mut f = Vec::with_capacity(k);
for _ in 0..k {
at += 2 + r.next() % 40;
f.push(at);
if r.next().is_multiple_of(16) {
f.push(at);
}
}
at += 64 + r.next() % 4096;
funcs.push(f);
}
// functions out of address order
for i in (1..funcs.len()).rev() {
let j = (r.next() % (i as u64 + 1)) as usize;
funcs.swap(i, j);
}
let mut all: Vec<u64> = funcs.into_iter().flatten().collect();
all.truncate(n);
all
}
#[test]
fn an_address_gives_its_call_site_as_a_map_does() {
let t = Tmp::new("map");
let set = t.0.join("set");
let addrs = addresses(20_000, 11);
write_set(&set, 5000, &addrs, true);
let mut first: HashMap<u64, u32> = HashMap::new();
for (i, &a) in addrs.iter().enumerate() {
first.entry(a).or_insert(i as u32);
}
let kix = t.0.join("set.kix");
let idx = open(&set, &kix);
let rules = idx.build_rules().unwrap();
let sites = rules.site_addr.as_ref().expect("the set has site.addr");
let look = sites.lookup().unwrap();
assert!(look.is_tree());
for &a in &addrs {
assert_eq!(look.exact(a), first.get(&a).copied(), "address {a:#x}");
}
// addresses between, before and after the sites are no call site
let (lo, hi) = (*addrs.iter().min().unwrap(), *addrs.iter().max().unwrap());
let mut r = Rng(5);
let probes: Vec<u64> = (0..50_000)
.map(|_| lo - 100 + r.next() % (hi - lo + 200))
.chain([0, lo - 1, hi + 1, u64::MAX])
.collect();
for &a in &probes {
assert_eq!(look.exact(a), first.get(&a).copied(), "probe {a:#x}");
}
// batched: the same answers
let mut got = vec![Some(u32::MAX); probes.len()];
look.exact_batch(&probes, &mut got);
for (&a, g) in probes.iter().zip(&got) {
assert_eq!(*g, first.get(&a).copied(), "batched probe {a:#x}");
}
// the index is kept beside the set and read back the next time
let again = open(&set, &kix);
let rules2 = again.build_rules().unwrap();
let entry = again
.timings()
.entries
.into_iter()
.find(|e| e.0 == format!("addr.{}.{}", SITE_ADDR.0, SITE_ADDR.1))
.expect("timed");
assert!(!entry.2, "read back, not built again");
let look2 = rules2.site_addr.as_ref().unwrap().lookup().unwrap();
for &a in addrs.iter().step_by(7) {
assert_eq!(look2.exact(a), first.get(&a).copied());
}
}
#[test]
fn a_set_without_site_addresses_has_no_call_site_index() {
let t = Tmp::new("none");
let set = t.0.join("set");
write_set(&set, 100, &addresses(300, 3), false);
let idx = open(&set, &t.0.join("set.kix"));
assert!(idx.call_sites().unwrap().is_none());
assert!(idx.build_rules().unwrap().site_addr.is_none());
}
#[test]
fn rising_site_addresses_are_searched_in_the_sets_own_column() {
let t = Tmp::new("rising");
let set = t.0.join("set");
let mut addrs = addresses(4000, 9);
addrs.sort_unstable();
addrs.dedup();
write_set(&set, 1000, &addrs, true);
let idx = open(&set, &t.0.join("set.kix"));
let sites = idx.call_sites().unwrap().expect("the set has site.addr");
assert!(sites.is_shared(), "no copy of a column that already rises");
let look = sites.lookup().unwrap();
for (i, &a) in addrs.iter().enumerate() {
assert_eq!(look.exact(a), Some(i as u32));
assert_eq!(
look.exact(a + 1).is_some(),
addrs.binary_search(&(a + 1)).is_ok()
);
}
}