use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
use serde::{Deserialize, Serialize};
use crate::analysis::{Analysis, FunctionLayout, Xref};
use crate::disasm::Arch;
use crate::error::{Error, Result};
use crate::loader::BinaryFormat;
use crate::loader::strings::StringHit;
pub const SCHEMA_VERSION: u32 = 2;
pub const MAX_SNAPSHOT_FUNCTIONS: usize = 100_000;
pub const MAX_SNAPSHOT_BLOCKS: usize = 1_000_000;
pub const MAX_SNAPSHOT_XREFS: usize = 3_000_000;
pub const MAX_SNAPSHOT_STRINGS: usize = 3_000_000;
pub const MAX_SNAPSHOT_ANNOTATIONS: usize = 10_000;
pub const MAX_ANNOTATION_BYTES: usize = 8192;
const META: TableDefinition<&str, String> = TableDefinition::new("meta");
const BINARIES: TableDefinition<u64, String> = TableDefinition::new("binaries");
const FUNCTIONS: TableDefinition<u64, String> = TableDefinition::new("functions");
const BLOCKS: TableDefinition<String, String> = TableDefinition::new("blocks");
const XREFS: TableDefinition<String, String> = TableDefinition::new("xrefs");
const STRINGS: TableDefinition<u64, String> = TableDefinition::new("strings");
const ANNOTATIONS: TableDefinition<u64, String> = TableDefinition::new("annotations");
#[must_use]
pub fn content_hash(bytes: &[u8]) -> u64 {
const OFFSET: u64 = 0xcbf29ce484222325;
const PRIME: u64 = 0x100000001b3;
let mut h = OFFSET;
for &b in bytes {
h ^= u64::from(b);
h = h.wrapping_mul(PRIME);
}
h
}
#[must_use]
pub fn default_db_path(binary: &Path) -> PathBuf {
let mut p = binary.to_path_buf();
p.set_extension("rsdbg.redb");
p
}
pub fn db_file_size(path: &Path) -> Result<u64> {
match std::fs::metadata(path) {
Ok(m) => Ok(m.len()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(0),
Err(e) => Err(Error::Storage(format!("stat {}: {e}", path.display()))),
}
}
pub fn compact_db(path: &Path) -> Result<bool> {
let mut db = open_db(path)?;
db.compact()
.map_err(|e| Error::Storage(format!("compact {}: {e}", path.display())))
}
#[must_use]
pub fn arch_name(arch: Arch) -> &'static str {
match arch {
Arch::X86_64 => "x86_64",
Arch::X86_32 => "x86_32",
Arch::Aarch64 => "aarch64",
Arch::Arm32 => "arm32",
Arch::Thumb => "thumb",
}
}
pub fn parse_arch(s: &str) -> Result<Arch> {
match s {
"x86_64" => Ok(Arch::X86_64),
"x86_32" => Ok(Arch::X86_32),
"aarch64" => Ok(Arch::Aarch64),
"arm32" => Ok(Arch::Arm32),
"thumb" => Ok(Arch::Thumb),
other => Err(Error::Storage(format!(
"unknown arch in project db: {other}"
))),
}
}
#[must_use]
pub fn format_name(format: BinaryFormat) -> &'static str {
match format {
BinaryFormat::Elf => "elf",
BinaryFormat::Pe => "pe",
BinaryFormat::MachO => "macho",
BinaryFormat::Le => "le",
BinaryFormat::Raw => "raw",
}
}
pub fn parse_format(s: &str) -> Result<BinaryFormat> {
match s {
"elf" => Ok(BinaryFormat::Elf),
"pe" => Ok(BinaryFormat::Pe),
"macho" => Ok(BinaryFormat::MachO),
"le" => Ok(BinaryFormat::Le),
"raw" => Ok(BinaryFormat::Raw),
other => Err(Error::Storage(format!(
"unknown format in project db: {other}"
))),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BinaryMeta {
pub version: u32,
pub binary_path: String,
pub content_hash: u64,
pub size: u64,
pub arch: String,
pub format: String,
pub entry: Option<u64>,
#[serde(default = "default_supported")]
pub supported: bool,
#[serde(default)]
pub reason: Option<String>,
}
fn default_supported() -> bool {
true
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionRecord {
pub entry: u64,
pub name: Option<String>,
pub calls: Vec<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlockRecord {
pub func_entry: u64,
pub start: u64,
pub end: u64,
pub insns: Vec<crate::analysis::InsnLayout>,
pub succs: Vec<u64>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Annotation {
pub name: Option<String>,
pub comment: Option<String>,
}
impl Annotation {
#[must_use]
pub fn is_empty(&self) -> bool {
self.name.as_deref().is_none_or(str::is_empty)
&& self.comment.as_deref().is_none_or(str::is_empty)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ProjectInfo {
pub binary: String,
pub db_path: String,
pub version: String,
pub arch: String,
pub format: String,
pub entry: Option<u64>,
pub content_hash: u64,
pub size: u64,
#[serde(default = "default_supported")]
pub supported: bool,
#[serde(default)]
pub reason: Option<String>,
pub functions: usize,
pub blocks: usize,
pub insns: usize,
pub xrefs: usize,
pub strings: usize,
pub annotations: usize,
}
impl Serialize for ProjectInfo {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("ProjectInfo", 17)?;
st.serialize_field("binary", &self.binary)?;
st.serialize_field("db_path", &self.db_path)?;
st.serialize_field("version", &self.version)?;
st.serialize_field("arch", &self.arch)?;
st.serialize_field("format", &self.format)?;
st.serialize_field("entry", &self.entry)?;
st.serialize_field("entry_hex", &self.entry.map(crate::addr_hex))?;
st.serialize_field("content_hash", &self.content_hash)?;
st.serialize_field("size", &self.size)?;
st.serialize_field("supported", &self.supported)?;
st.serialize_field("reason", &self.reason)?;
st.serialize_field("functions", &self.functions)?;
st.serialize_field("blocks", &self.blocks)?;
st.serialize_field("insns", &self.insns)?;
st.serialize_field("xrefs", &self.xrefs)?;
st.serialize_field("strings", &self.strings)?;
st.serialize_field("annotations", &self.annotations)?;
st.end()
}
}
#[derive(Debug)]
pub struct Loaded {
pub meta: BinaryMeta,
pub arch: Arch,
pub functions: Vec<FunctionLayout>,
pub call_edges: Vec<(u64, u64)>,
pub xrefs: Vec<Xref>,
pub strings: Vec<StringHit>,
pub annotations: BTreeMap<u64, Annotation>,
}
impl Loaded {
pub fn rebuild(self, bin: &crate::loader::LoadedBinary) -> Result<Analysis> {
crate::analysis::rebuild(
self.arch,
bin,
&self.functions,
&self.call_edges,
self.xrefs,
self.strings,
)
}
}
pub fn open_db(path: &Path) -> Result<Database> {
Database::create(path).map_err(|e| Error::Storage(format!("open db: {e}")))
}
pub fn open_db_read_only(path: &Path) -> Result<redb::ReadOnlyDatabase> {
redb::Database::builder()
.open_read_only(path)
.map_err(|e| Error::Storage(format!("open db: {e}")))
}
fn block_key(func_entry: u64, start: u64) -> String {
format!("{func_entry:016x}:{start:016x}")
}
fn xref_kind_name(kind: crate::analysis::XrefKind) -> &'static str {
match kind {
crate::analysis::XrefKind::Code => "code",
crate::analysis::XrefKind::Data => "data",
crate::analysis::XrefKind::String => "string",
}
}
fn xref_key(x: &Xref) -> String {
format!("{:016x}:{}:{:016x}", x.from, xref_kind_name(x.kind), x.to)
}
fn json<T: Serialize>(v: &T) -> Result<String> {
serde_json::to_string(v).map_err(|e| Error::Storage(format!("encode row: {e}")))
}
fn decode<T: for<'de> Deserialize<'de>>(s: &str) -> Result<T> {
serde_json::from_str(s).map_err(|e| Error::Storage(format!("decode row: {e}")))
}
fn check_annotation_text(ann: &Annotation) -> Result<()> {
for (label, s) in [("name", &ann.name), ("comment", &ann.comment)] {
if let Some(t) = s
&& t.len() > MAX_ANNOTATION_BYTES
{
return Err(Error::Limit(format!(
"annotation {label} of {} bytes exceeds {MAX_ANNOTATION_BYTES}",
t.len()
)));
}
}
Ok(())
}
fn check_analysis_budgets(
analysis: &Analysis,
annotations: &BTreeMap<u64, Annotation>,
) -> Result<()> {
if analysis.functions.len() > MAX_SNAPSHOT_FUNCTIONS {
return Err(Error::Limit("snapshot functions exceed cap".to_string()));
}
let blocks: usize = analysis.functions.values().map(|f| f.blocks.len()).sum();
if blocks > MAX_SNAPSHOT_BLOCKS {
return Err(Error::Limit("snapshot blocks exceed cap".to_string()));
}
if analysis.xrefs.len() > MAX_SNAPSHOT_XREFS {
return Err(Error::Limit("snapshot xrefs exceed cap".to_string()));
}
if analysis.strings.len() > MAX_SNAPSHOT_STRINGS {
return Err(Error::Limit("snapshot strings exceed cap".to_string()));
}
let live = annotations.values().filter(|a| !a.is_empty()).count();
if live > MAX_SNAPSHOT_ANNOTATIONS {
return Err(Error::Limit("snapshot annotations exceed cap".to_string()));
}
for ann in annotations.values() {
if !ann.is_empty() {
check_annotation_text(ann)?;
}
}
Ok(())
}
fn delete_if_exists(wtxn: &redb::WriteTransaction, table: &str) -> Result<()> {
let deleted = match table {
"meta" => wtxn.delete_table(META),
"binaries" => wtxn.delete_table(BINARIES),
"functions" => wtxn.delete_table(FUNCTIONS),
"blocks" => wtxn.delete_table(BLOCKS),
"xrefs" => wtxn.delete_table(XREFS),
"strings" => wtxn.delete_table(STRINGS),
"annotations" => wtxn.delete_table(ANNOTATIONS),
_ => return Err(Error::Storage(format!("unknown table {table}"))),
};
match deleted {
Ok(_) => Ok(()),
Err(redb::TableError::TableDoesNotExist(_)) => Ok(()),
Err(e) => Err(Error::Storage(format!("clear {table}: {e}"))),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnotationSave {
Fast,
NeedsFull,
}
pub fn save_annotation(
db: &Database,
meta: &BinaryMeta,
addr: u64,
ann: Option<&Annotation>,
) -> Result<AnnotationSave> {
if let Some(a) = ann
&& !a.is_empty()
{
check_annotation_text(a)?;
}
let encoded: Option<String> = match ann {
Some(a) if !a.is_empty() => Some(json(a)?),
_ => None,
};
let wtxn = db
.begin_write()
.map_err(|e| Error::Storage(format!("begin write: {e}")))?;
{
let meta_table = wtxn
.open_table(META)
.map_err(|e| Error::Storage(format!("open meta: {e}")))?;
let version = meta_table
.get("version")
.map_err(|e| Error::Storage(format!("read meta: {e}")))?;
if version.is_none() {
return Ok(AnnotationSave::NeedsFull);
}
}
{
let binaries = wtxn
.open_table(BINARIES)
.map_err(|e| Error::Storage(format!("open binaries: {e}")))?;
let row = binaries
.get(0u64)
.map_err(|e| Error::Storage(format!("read binaries: {e}")))?;
let Some(row) = row else {
return Ok(AnnotationSave::NeedsFull);
};
let persisted: BinaryMeta = decode(&row.value())?;
if persisted != *meta {
return Ok(AnnotationSave::NeedsFull);
}
}
{
let mut t = wtxn
.open_table(ANNOTATIONS)
.map_err(|e| Error::Storage(format!("open annotations: {e}")))?;
match encoded {
Some(s) => {
t.insert(addr, s)
.map_err(|e| Error::Storage(format!("write annotations: {e}")))?;
}
None => {
t.remove(addr)
.map_err(|e| Error::Storage(format!("remove annotations: {e}")))?;
}
}
}
wtxn.commit()
.map_err(|e| Error::Storage(format!("commit: {e}")))?;
Ok(AnnotationSave::Fast)
}
pub fn save(
db: &Database,
meta: &BinaryMeta,
analysis: &Analysis,
annotations: &BTreeMap<u64, Annotation>,
) -> Result<()> {
check_analysis_budgets(analysis, annotations)?;
let wtxn = db
.begin_write()
.map_err(|e| Error::Storage(format!("begin write: {e}")))?;
for t in [
"meta",
"binaries",
"functions",
"blocks",
"xrefs",
"strings",
"annotations",
] {
delete_if_exists(&wtxn, t)?;
}
{
let mut t = wtxn
.open_table(META)
.map_err(|e| Error::Storage(format!("open meta: {e}")))?;
t.insert("version", SCHEMA_VERSION.to_string())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert("binary_path", meta.binary_path.clone())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert("content_hash", meta.content_hash.to_string())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert("size", meta.size.to_string())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert("arch", meta.arch.clone())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert("format", meta.format.clone())
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
t.insert(
"entry",
meta.entry.map(|e| e.to_string()).unwrap_or_default(),
)
.map_err(|e| Error::Storage(format!("write meta: {e}")))?;
}
{
let mut t = wtxn
.open_table(BINARIES)
.map_err(|e| Error::Storage(format!("open binaries: {e}")))?;
t.insert(0u64, json(meta)?)
.map_err(|e| Error::Storage(format!("write binaries: {e}")))?;
}
let layouts = crate::analysis::layout(analysis);
{
let mut t = wtxn
.open_table(FUNCTIONS)
.map_err(|e| Error::Storage(format!("open functions: {e}")))?;
for f in &layouts {
let rec = FunctionRecord {
entry: f.entry,
name: f.name.clone(),
calls: f.calls.clone(),
};
t.insert(f.entry, json(&rec)?)
.map_err(|e| Error::Storage(format!("write functions: {e}")))?;
}
}
{
let mut t = wtxn
.open_table(BLOCKS)
.map_err(|e| Error::Storage(format!("open blocks: {e}")))?;
for f in &layouts {
for b in &f.blocks {
let rec = BlockRecord {
func_entry: f.entry,
start: b.start,
end: b.end,
insns: b.insns.clone(),
succs: b.succs.clone(),
};
t.insert(block_key(f.entry, b.start), json(&rec)?)
.map_err(|e| Error::Storage(format!("write blocks: {e}")))?;
}
}
}
{
let mut t = wtxn
.open_table(XREFS)
.map_err(|e| Error::Storage(format!("open xrefs: {e}")))?;
for x in &analysis.xrefs {
t.insert(xref_key(x), json(x)?)
.map_err(|e| Error::Storage(format!("write xrefs: {e}")))?;
}
}
{
let mut t = wtxn
.open_table(STRINGS)
.map_err(|e| Error::Storage(format!("open strings: {e}")))?;
for (i, h) in analysis.strings.iter().enumerate() {
t.insert(i as u64, json(h)?)
.map_err(|e| Error::Storage(format!("write strings: {e}")))?;
}
}
{
let mut t = wtxn
.open_table(ANNOTATIONS)
.map_err(|e| Error::Storage(format!("open annotations: {e}")))?;
for (&addr, ann) in annotations {
if ann.is_empty() {
continue;
}
t.insert(addr, json(ann)?)
.map_err(|e| Error::Storage(format!("write annotations: {e}")))?;
}
}
wtxn.commit()
.map_err(|e| Error::Storage(format!("commit: {e}")))?;
Ok(())
}
fn read_meta_row(rtxn: &redb::ReadTransaction) -> Result<Option<BinaryMeta>> {
let meta_table = match rtxn.open_table(META) {
Ok(t) => t,
Err(redb::TableError::TableDoesNotExist(_)) => return Ok(None),
Err(e) => return Err(Error::Storage(format!("open meta: {e}"))),
};
let has_version = meta_table
.get("version")
.map_err(|e| Error::Storage(format!("read meta: {e}")))?;
if has_version.is_none() {
return Ok(None);
}
drop(meta_table);
let t = rtxn
.open_table(BINARIES)
.map_err(|e| Error::Storage(format!("open binaries: {e}")))?;
let row = t
.get(0u64)
.map_err(|e| Error::Storage(format!("read binaries: {e}")))?
.ok_or_else(|| Error::Storage("project db has meta but no binary row".to_string()))?;
Ok(Some(decode(&row.value())?))
}
struct SnapshotParts {
functions: Vec<FunctionLayout>,
call_edges: Vec<(u64, u64)>,
xrefs: Vec<Xref>,
strings: Vec<StringHit>,
}
fn read_snapshot_parts(rtxn: &redb::ReadTransaction) -> Result<SnapshotParts> {
let mut records: Vec<FunctionRecord> = Vec::new();
{
let t = rtxn
.open_table(FUNCTIONS)
.map_err(|e| Error::Storage(format!("open functions: {e}")))?;
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read functions: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read functions: {e}")))?;
let raw = v.value();
if records.len() >= MAX_SNAPSHOT_FUNCTIONS {
return Err(Error::Limit("snapshot functions exceed cap".to_string()));
}
records.push(decode(&raw)?);
}
}
let mut blocks_by_func: BTreeMap<u64, Vec<crate::analysis::BlockLayout>> = BTreeMap::new();
let mut block_count: usize = 0;
{
let t = rtxn
.open_table(BLOCKS)
.map_err(|e| Error::Storage(format!("open blocks: {e}")))?;
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read blocks: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read blocks: {e}")))?;
let raw = v.value();
block_count += 1;
if block_count > MAX_SNAPSHOT_BLOCKS {
return Err(Error::Limit("snapshot blocks exceed cap".to_string()));
}
let rec: BlockRecord = decode(&raw)?;
blocks_by_func
.entry(rec.func_entry)
.or_default()
.push(crate::analysis::BlockLayout {
start: rec.start,
end: rec.end,
insns: rec.insns,
succs: rec.succs,
});
}
}
let mut functions: Vec<FunctionLayout> = Vec::new();
let mut call_edges: Vec<(u64, u64)> = Vec::new();
for rec in records {
let entry = rec.entry;
let mut blocks = blocks_by_func.remove(&entry).unwrap_or_default();
blocks.sort_by_key(|b| b.start);
functions.push(FunctionLayout {
entry,
name: rec.name.clone(),
calls: rec.calls.clone(),
blocks,
});
call_edges.extend(rec.calls.into_iter().map(|c| (entry, c)));
}
let mut xrefs: Vec<Xref> = Vec::new();
{
let t = rtxn
.open_table(XREFS)
.map_err(|e| Error::Storage(format!("open xrefs: {e}")))?;
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read xrefs: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read xrefs: {e}")))?;
let raw = v.value();
if xrefs.len() >= MAX_SNAPSHOT_XREFS {
return Err(Error::Limit("snapshot xrefs exceed cap".to_string()));
}
xrefs.push(decode(&raw)?);
}
}
xrefs.sort_by_key(|a| (a.from, a.kind, a.to));
let mut strings: Vec<StringHit> = Vec::new();
{
let t = rtxn
.open_table(STRINGS)
.map_err(|e| Error::Storage(format!("open strings: {e}")))?;
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read strings: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read strings: {e}")))?;
let raw = v.value();
if strings.len() >= MAX_SNAPSHOT_STRINGS {
return Err(Error::Limit("snapshot strings exceed cap".to_string()));
}
strings.push(decode(&raw)?);
}
}
Ok(SnapshotParts {
functions,
call_edges,
xrefs,
strings,
})
}
fn read_annotations(rtxn: &redb::ReadTransaction) -> Result<BTreeMap<u64, Annotation>> {
let t = rtxn
.open_table(ANNOTATIONS)
.map_err(|e| Error::Storage(format!("open annotations: {e}")))?;
let mut annotations: BTreeMap<u64, Annotation> = BTreeMap::new();
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read annotations: {e}")))?
{
let (k, v) = row.map_err(|e| Error::Storage(format!("read annotations: {e}")))?;
let raw = v.value();
if annotations.len() >= MAX_SNAPSHOT_ANNOTATIONS {
return Err(Error::Limit("snapshot annotations exceed cap".to_string()));
}
let ann: Annotation = decode(&raw)?;
check_annotation_text(&ann)?;
if !ann.is_empty() {
annotations.insert(k.value(), ann);
}
}
Ok(annotations)
}
fn read_annotations_or_empty(rtxn: &redb::ReadTransaction) -> Result<BTreeMap<u64, Annotation>> {
let t = match rtxn.open_table(ANNOTATIONS) {
Ok(t) => t,
Err(redb::TableError::TableDoesNotExist(_)) => return Ok(BTreeMap::new()),
Err(e) => return Err(Error::Storage(format!("open annotations: {e}"))),
};
let mut annotations: BTreeMap<u64, Annotation> = BTreeMap::new();
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read annotations: {e}")))?
{
let (k, v) = row.map_err(|e| Error::Storage(format!("read annotations: {e}")))?;
let raw = v.value();
if annotations.len() >= MAX_SNAPSHOT_ANNOTATIONS {
return Err(Error::Limit("snapshot annotations exceed cap".to_string()));
}
let ann: Annotation = decode(&raw)?;
check_annotation_text(&ann)?;
if !ann.is_empty() {
annotations.insert(k.value(), ann);
}
}
Ok(annotations)
}
#[derive(Debug)]
pub enum Snapshot {
Hit(Box<Loaded>),
Stale {
meta: BinaryMeta,
annotations: BTreeMap<u64, Annotation>,
},
Miss,
}
pub fn load_cached(db: &impl ReadableDatabase, expected_hash: u64) -> Result<Snapshot> {
let rtxn = db
.begin_read()
.map_err(|e| Error::Storage(format!("begin read: {e}")))?;
let meta = match read_meta_row(&rtxn)? {
None => return Ok(Snapshot::Miss),
Some(meta) => meta,
};
if meta.content_hash != expected_hash || meta.version != SCHEMA_VERSION {
let annotations = read_annotations_or_empty(&rtxn)?;
return Ok(Snapshot::Stale { meta, annotations });
}
let arch = parse_arch(&meta.arch)?;
parse_format(&meta.format)?;
let parts = read_snapshot_parts(&rtxn)?;
let annotations = read_annotations(&rtxn)?;
Ok(Snapshot::Hit(Box::new(Loaded {
meta,
arch,
functions: parts.functions,
call_edges: parts.call_edges,
xrefs: parts.xrefs,
strings: parts.strings,
annotations,
})))
}
pub fn load(db: &Database) -> Result<Option<Loaded>> {
let rtxn = db
.begin_read()
.map_err(|e| Error::Storage(format!("begin read: {e}")))?;
let meta = match read_meta_row(&rtxn)? {
None => return Ok(None),
Some(meta) => meta,
};
if meta.version != SCHEMA_VERSION {
return Err(Error::Storage(format!(
"project db version {} != {}",
meta.version, SCHEMA_VERSION
)));
}
let arch = parse_arch(&meta.arch)?;
parse_format(&meta.format)?;
let parts = read_snapshot_parts(&rtxn)?;
let annotations = read_annotations(&rtxn)?;
Ok(Some(Loaded {
meta,
arch,
functions: parts.functions,
call_edges: parts.call_edges,
xrefs: parts.xrefs,
strings: parts.strings,
annotations,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hash_is_deterministic_and_sensitive() {
assert_eq!(content_hash(b"abc"), content_hash(b"abc"));
assert_ne!(content_hash(b"abc"), content_hash(b"abd"));
assert_ne!(content_hash(b"abc"), content_hash(b""));
}
#[test]
fn arch_and_format_round_trip() {
for a in [
Arch::X86_64,
Arch::X86_32,
Arch::Aarch64,
Arch::Arm32,
Arch::Thumb,
] {
assert_eq!(parse_arch(arch_name(a)).unwrap(), a);
}
for f in [
BinaryFormat::Elf,
BinaryFormat::Pe,
BinaryFormat::MachO,
BinaryFormat::Le,
BinaryFormat::Raw,
] {
assert_eq!(parse_format(format_name(f)).unwrap(), f);
}
assert!(parse_arch("mips").is_err());
assert!(parse_format("wasm").is_err());
}
#[test]
fn empty_annotation_prunes() {
assert!(Annotation::default().is_empty());
assert!(
!Annotation {
name: Some("f".to_string()),
comment: None,
}
.is_empty()
);
assert!(
!Annotation {
name: Some(String::new()),
comment: Some("c".to_string()),
}
.is_empty()
);
}
}