crates/kleene-index/src/set.rs
//! A set's indexes: each read from the index directory when stored there, else built from
//! the set and stored.
use std::sync::Mutex;
use std::time::{Duration, Instant};
use arrow_array::cast::AsArray;
use arrow_array::types::{Int32Type, Int64Type, UInt8Type, UInt16Type, UInt32Type, UInt64Type};
use arrow_array::{Array, ArrayRef};
use arrow_buffer::ScalarBuffer;
use arrow_schema::DataType;
use kleene_gar::{EdgeAdjacency, GarGraph};
use kleene_sparse::CpuDevice;
use crate::error::{Result, bad, gar};
use crate::exec::Gatling;
use crate::store::{Store, col32, col64};
use crate::{
AddrColumn, Groups, Intervals, Kinds, Names, Nesting, ParentTree, Reach, ReverseReach,
};
/// The most bytes [`IndexSet::kinds`] gives a column's bitmaps (kinds x vertices / 8).
pub const KINDS_MAX_BYTES: usize = 1 << 30;
/// The call-site address column, `(table, column)`: `site.addr`, the address of each call
/// site's instruction as a `u64` (or `i64`) column. es's ELF set work adds it; a set
/// without it has no call-site index.
pub const SITE_ADDR: (&str, &str) = ("site", "addr");
/// How long each index took, and whether it was built (else read from the directory).
#[derive(Clone, Debug, Default)]
pub struct Timings {
/// `(index name, time, built)` in the order asked for.
pub entries: Vec<(String, Duration, bool)>,
}
/// A set and its index directory.
pub struct IndexSet {
graph: GarGraph,
store: Store,
device: CpuDevice,
timings: Mutex<Timings>,
}
impl IndexSet {
/// The set at `dir` with its indexes in `<dir>.kix`; builds run on gatling (one worker
/// per core).
pub fn open(dir: impl AsRef<std::path::Path>) -> Result<Self> {
let dir = dir.as_ref();
let graph = GarGraph::open(dir).map_err(gar)?;
let store = Store::beside(dir)?;
let device = Gatling::device(0);
Ok(IndexSet::with(graph, store, device))
}
/// A set, its store and the device builds run on.
pub fn with(graph: GarGraph, store: Store, device: CpuDevice) -> Self {
IndexSet {
graph,
store,
device,
timings: Mutex::new(Timings::default()),
}
}
/// The set.
pub fn graph(&self) -> &GarGraph {
&self.graph
}
/// The index directory.
pub fn store(&self) -> &Store {
&self.store
}
/// The time each index took so far.
pub fn timings(&self) -> Timings {
self.timings
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
fn timed<T>(&self, name: &str, f: impl FnOnce() -> Result<(T, bool)>) -> Result<T> {
let t0 = Instant::now();
let (v, built) = f()?;
self.timings
.lock()
.unwrap_or_else(|e| e.into_inner())
.entries
.push((name.to_string(), t0.elapsed(), built));
Ok(v)
}
/// A vertex column as `u64` (64-bit columns shared, narrower ones widened).
pub fn column_u64(&self, table: &str, col: &str) -> Result<ScalarBuffer<u64>> {
let a = self.graph.vertex_column(table, col).map_err(gar)?;
as_u64(&a).ok_or_else(|| {
bad(format!(
"{table}.{col} is {}, not an integer",
a.data_type()
))
})
}
/// A vertex column as `u32` (32-bit columns shared, 64-bit ones narrowed; a value past
/// `u32` is refused).
pub fn column_u32(&self, table: &str, col: &str) -> Result<ScalarBuffer<u32>> {
let a = self.graph.vertex_column(table, col).map_err(gar)?;
as_u32(&a, false).ok_or_else(|| {
bad(format!(
"{table}.{col} is {} or holds a value past u32",
a.data_type()
))
})
}
fn edges(&self, edge: &str, square: bool) -> Result<EdgeAdjacency> {
let t = self
.graph
.edge_type(edge)
.ok_or_else(|| bad(format!("the set has no edge table {edge}")))?
.clone();
let adj = self.graph.adjacency(&t).map_err(gar)?;
if square && adj.sources != adj.destinations {
return Err(bad(format!(
"{edge} joins {} sources to {} destinations: not one vertex type",
adj.sources, adj.destinations
)));
}
Ok(adj)
}
/// Address to row of `table` by its `start` column (and `end`, when given).
pub fn addr(&self, table: &str, start: &str, end: Option<&str>) -> Result<AddrColumn> {
let name = format!("addr.{table}.{start}");
self.timed(&name, || {
let ends = || end.map(|e| self.column_u64(table, e)).transpose();
if let Some(s) = self.store.load(&name)? {
if !s.has("keys") {
let col = AddrColumn::build(self.column_u64(table, start)?, ends()?)?;
return Ok((col, false));
}
let col = AddrColumn::from_parts(
s.u64("keys")?,
Some(s.u32("rows")?),
if s.has("ends") {
Some(s.u64("ends")?)
} else {
None
},
)?;
return Ok((col, false));
}
let col = AddrColumn::build(self.column_u64(table, start)?, ends()?)?;
let (keys, rows, ends) = col.parts();
let mut cols = Vec::new();
if let Some(rows) = rows {
cols.push(("keys", col64(keys.clone())));
cols.push(("rows", col32(rows.clone())));
if let Some(e) = ends {
cols.push(("ends", col64(e.clone())));
}
}
self.store.save(&name, cols)?;
Ok((col, true))
})
}
/// Address to call site: the static search tree over [`SITE_ADDR`] (an address gives
/// its site row, the site id, through [`AddrColumn::lookup`] and `exact`); none when
/// the set has no such column. A site address held by several rows gives the first.
pub fn call_sites(&self) -> Result<Option<AddrColumn>> {
let (table, col) = SITE_ADDR;
let has = self.graph.vertex_types().iter().any(|v| v == table)
&& self.graph.vertex_column(table, col).is_ok();
if !has {
return Ok(None);
}
self.addr(table, col, None).map(Some)
}
/// "Can A reach B" over the edge table `edge` (one vertex type at both ends).
pub fn reach(&self, edge: &str) -> Result<Reach> {
let name = format!("reach.{edge}");
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
let r = Reach::from_parts(
[s.u64("out_off")?, s.u64("in_off")?],
[s.u32("comp")?, s.u32("out_lab")?, s.u32("in_lab")?],
)?;
return Ok((r, false));
}
let adj = self.edges(edge, true)?;
let r = Reach::build(&adj.out_offsets, &adj.out_neighbours)?;
let ([oo, io], [c, ol, il]) = r.parts();
self.store.save(
&name,
vec![
("out_off", col64(oo.clone())),
("in_off", col64(io.clone())),
("comp", col32(c.clone())),
("out_lab", col32(ol.clone())),
("in_lab", col32(il.clone())),
],
)?;
Ok((r, true))
})
}
/// Who reaches each of `sets` over `edge`, stored under `label` (which must name the
/// sets: a stored index is only as right as its label).
pub fn reverse_reach(
&self,
edge: &str,
label: &str,
sets: &[Vec<u32>],
) -> Result<ReverseReach> {
let name = format!("rreach.{edge}.{label}");
self.timed(&name, || {
let adj = self.edges(edge, true)?;
if let Some(s) = self.store.load(&name)? {
let r = ReverseReach::from_parts(adj.destinations, s.u64("bits")?)?;
if r.sets() == sets.len() {
return Ok((r, false));
}
}
let r = ReverseReach::build(&adj.in_offsets, &adj.in_neighbours, sets)?;
self.store
.save(&name, vec![("bits", col64(r.words().clone()))])?;
Ok((r, true))
})
}
/// The why chains from `root` over `edge`.
pub fn parents(&self, edge: &str, root: u32) -> Result<ParentTree> {
let name = format!("parents.{edge}.{root}");
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
return Ok((ParentTree::from_parts(root, s.u32("parent")?)?, false));
}
let adj = self.edges(edge, true)?;
let t = ParentTree::build(adj.out_offsets, adj.out_neighbours, root, &self.device)?;
self.store
.save(&name, vec![("parent", col32(t.parents().clone()))])?;
Ok((t, true))
})
}
/// Pre/post numbers of `table`'s forest by its `parent` column (a value past the rows,
/// or the row itself, is a root).
pub fn nesting(&self, table: &str, parent: &str) -> Result<Nesting> {
let name = format!("nest.{table}.{parent}");
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
return Ok((Nesting::from_parts(s.u64("order")?)?, false));
}
let a = self.graph.vertex_column(table, parent).map_err(gar)?;
let p = as_u32(&a, true).ok_or_else(|| {
bad(format!(
"{table}.{parent} is {}, not an integer",
a.data_type()
))
})?;
let nest = Nesting::from_parents(&p)?;
self.store
.save(&name, vec![("order", col64(nest.words().clone()))])?;
Ok((nest, true))
})
}
/// The ranges `start..end` of `table`'s rows, each with its row as id, or with
/// `owner = (table, lo)` the owner row whose ranges begin at `lo` (owner `i` holds rows
/// `lo[i]..lo[i + 1]`, the last one to the end).
pub fn intervals(
&self,
table: &str,
start: &str,
end: &str,
owner: Option<(&str, &str)>,
) -> Result<Intervals> {
let name = match owner {
None => format!("ivl.{table}.{start}.{end}"),
Some((o, lo)) => format!("ivl.{table}.{start}.{end}.{o}.{lo}"),
};
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
let t = Intervals::from_parts(
s.u64("starts")?,
s.u64("ends")?,
s.u32("ids")?,
s.u64("max_end")?,
)?;
return Ok((t, false));
}
let st = self.column_u64(table, start)?;
let en = self.column_u64(table, end)?;
let ids: Vec<u32> = match owner {
None => (0..st.len() as u32).collect(),
Some((o, lo)) => {
let lo = self.column_u32(o, lo)?;
if lo.windows(2).any(|w| w[0] > w[1])
|| lo.last().is_some_and(|&l| l as usize > st.len())
{
return Err(bad(format!("{o} owns no rising runs of {table}")));
}
(0..st.len())
.map(|r| {
(lo.partition_point(|&l| l as usize <= r) as u32).saturating_sub(1)
})
.collect()
}
};
let t = Intervals::build(&st, &en, &ids)?;
let p = t.parts();
self.store.save(
&name,
vec![
("starts", col64(p.starts.clone())),
("ends", col64(p.ends.clone())),
("ids", col32(p.ids.clone())),
("max_end", col64(p.max_end.clone())),
],
)?;
Ok((t, true))
})
}
/// `table`'s `id` column grouped by its two-word key `(hi, lo)`.
pub fn groups(&self, table: &str, hi: &str, lo: &str, id: &str) -> Result<Groups> {
let name = format!("groups.{table}.{hi}.{lo}.{id}");
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
let g =
Groups::from_parts([s.u64("hi")?, s.u64("lo")?, s.u64("off")?], s.u32("ids")?)?;
return Ok((g, false));
}
let g = Groups::build(
&self.column_u64(table, hi)?,
&self.column_u64(table, lo)?,
&self.column_u32(table, id)?,
)?;
let ([h, l, o], i) = g.parts();
self.store.save(
&name,
vec![
("hi", col64(h.clone())),
("lo", col64(l.clone())),
("off", col64(o.clone())),
("ids", col32(i.clone())),
],
)?;
Ok((g, true))
})
}
}
impl IndexSet {
/// Name to id over `table`'s string column `col` ([`Names`]): built once, kept beside
/// the set under its root hash, the column itself read from the set.
pub fn names(&self, table: &str, col: &str) -> Result<Names> {
let name = format!("names.{table}.{col}");
let strings = self.graph.vertex_column(table, col).map_err(gar)?;
self.timed(&name, || {
if let Some(s) = self.store.load(&name)? {
let parts = (
s.u64("meta")?,
s.u64("pilots")?,
s.u32("remap")?,
s.u32("rows")?,
);
return Ok((Names::from_parts(&strings, parts)?, false));
}
let n = Names::build(&strings)?;
let (meta, pilots, remap, rows) = n.parts();
self.store.save(
&name,
vec![
("meta", col64(meta)),
("pilots", col64(pilots)),
("remap", col32(remap)),
("rows", col32(rows)),
],
)?;
Ok((n, true))
})
}
/// A bitmap per value of `table`'s kind column `col` ([`Kinds`]), kept beside the set
/// under its root hash; refused past [`KINDS_MAX_BYTES`].
pub fn kinds(&self, table: &str, col: &str) -> Result<Kinds> {
let name = format!("kinds.{table}.{col}");
self.timed(&name, || {
let n = self.graph.vertex_count(table).map_err(gar)? as usize;
if let Some(s) = self.store.load(&name)? {
return Ok((Kinds::from_parts(s.u64("keys")?, s.u64("bits")?, n)?, false));
}
let k = Kinds::build(&self.column_u64(table, col)?, KINDS_MAX_BYTES)?;
let (keys, bits) = k.parts();
self.store.save(
&name,
vec![("keys", col64(keys.clone())), ("bits", col64(bits.clone()))],
)?;
Ok((k, true))
})
}
/// The indexes the rules use, on the tables a set has (missing tables are skipped):
/// address to function, block, line, innermost scope and call site; reach and the why chains per
/// entry over the instruction call graph; reach over the function call graph; who
/// reaches each syscall site; scope nesting and scope ranges; candidate keys.
pub fn build_rules(&self) -> Result<Rules> {
let has = |t: &str| self.graph.vertex_types().iter().any(|v| v == t);
let has_edge = |e: &str| self.graph.edge_type(e).is_some();
let mut r = Rules::default();
if has("func") {
r.func = Some(self.addr("func", "start", Some("end"))?);
}
if has("blk") {
r.blk = Some(self.addr("blk", "start", Some("end"))?);
}
if has("line") {
r.line = Some(self.addr("line", "addr", None)?);
}
if has("scope_at") {
r.scope_at = Some(self.addr("scope_at", "addr", None)?);
}
r.site_addr = self.call_sites()?;
if has_edge("inst_icall_inst") {
r.inst_reach = Some(self.reach("inst_icall_inst")?);
if has("entry") {
for root in self.column_u32("entry", "iid")?.iter() {
r.why.push(self.parents("inst_icall_inst", *root)?);
}
}
if has("site") {
let iid = self.column_u32("site", "iid")?;
let sets: Vec<Vec<u32>> = iid.iter().map(|&i| vec![i]).collect();
r.sites = Some(self.reverse_reach("inst_icall_inst", "site.iid", &sets)?);
}
}
if has_edge("func_fcall_func") {
r.func_reach = Some(self.reach("func_fcall_func")?);
}
if has("scope") {
r.scope_nest = Some(self.nesting("scope", "parent")?);
if has("scope_range") {
r.scope_ranges = Some(self.intervals(
"scope_range",
"start",
"end",
Some(("scope", "range_lo")),
)?);
}
}
if has("cand_key") {
r.cand = Some(self.groups("cand_key", "key_0", "key_1", "iid")?);
}
Ok(r)
}
}
/// The indexes [`IndexSet::build_rules`] made (none where the set lacks the tables).
#[derive(Debug, Default)]
pub struct Rules {
/// Address to function (`func.start`, `func.end`).
pub func: Option<AddrColumn>,
/// Address to block.
pub blk: Option<AddrColumn>,
/// Address to line row.
pub line: Option<AddrColumn>,
/// Address to the innermost scope's change point (`scope_at.scid` holds the scope).
pub scope_at: Option<AddrColumn>,
/// Address to call site (`site.addr`, see [`SITE_ADDR`]), when the set has the column.
pub site_addr: Option<AddrColumn>,
/// Reach over `inst_icall_inst`.
pub inst_reach: Option<Reach>,
/// Reach over `func_fcall_func`.
pub func_reach: Option<Reach>,
/// Who reaches each syscall site (`site.iid`), over `inst_icall_inst`.
pub sites: Option<ReverseReach>,
/// The why chains from each entry (`entry.iid`), over `inst_icall_inst`.
pub why: Vec<ParentTree>,
/// Scope inside scope.
pub scope_nest: Option<Nesting>,
/// Which scopes cover an address (their ranges).
pub scope_ranges: Option<Intervals>,
/// Candidate key to instructions (`cand_key`).
pub cand: Option<Groups>,
}
/// A 64-bit integer column's buffer seen as `u64` (shared), or a narrower one widened.
fn as_u64(a: &ArrayRef) -> Option<ScalarBuffer<u64>> {
if a.null_count() > 0 {
return None;
}
Some(match a.data_type() {
DataType::UInt64 => a.as_primitive::<UInt64Type>().values().clone(),
DataType::Int64 => {
let v = a.as_primitive::<Int64Type>().values();
ScalarBuffer::new(v.inner().clone(), 0, v.len())
}
DataType::UInt32 => a
.as_primitive::<UInt32Type>()
.values()
.iter()
.map(|&x| u64::from(x))
.collect::<Vec<_>>()
.into(),
DataType::UInt16 => a
.as_primitive::<UInt16Type>()
.values()
.iter()
.map(|&x| u64::from(x))
.collect::<Vec<_>>()
.into(),
DataType::UInt8 => a
.as_primitive::<UInt8Type>()
.values()
.iter()
.map(|&x| u64::from(x))
.collect::<Vec<_>>()
.into(),
DataType::Int32 => a
.as_primitive::<Int32Type>()
.values()
.iter()
.map(|&x| x as u32 as u64)
.collect::<Vec<_>>()
.into(),
_ => return None,
})
}
/// An integer column as `u32`: 32-bit shared, 64-bit narrowed. A 64-bit value past `u32`
/// is refused, or with `saturate` becomes `u32::MAX`.
fn as_u32(a: &ArrayRef, saturate: bool) -> Option<ScalarBuffer<u32>> {
if a.null_count() > 0 {
return None;
}
match a.data_type() {
DataType::UInt32 => Some(a.as_primitive::<UInt32Type>().values().clone()),
DataType::Int32 => {
let v = a.as_primitive::<Int32Type>().values();
Some(ScalarBuffer::new(v.inner().clone(), 0, v.len()))
}
DataType::UInt64 | DataType::Int64 | DataType::UInt16 | DataType::UInt8 => {
let w = as_u64(a)?;
let mut out = Vec::with_capacity(w.len());
for &x in w.iter() {
match u32::try_from(x) {
Ok(x) => out.push(x),
Err(_) if saturate => out.push(u32::MAX),
Err(_) => return None,
}
}
Some(out.into())
}
_ => None,
}
}