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 = 5;
pub use crate::analysis::ANALYSIS_REVISION;
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_SNAPSHOT_DIAGNOSTICS: usize = 100_000;
pub const MAX_SNAPSHOT_INFERRED_EDGES: usize = 100_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");
const DIAGNOSTICS: TableDefinition<String, String> = TableDefinition::new("diagnostics");
#[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 s = binary.as_os_str().to_owned();
s.push(".rsdbg.redb");
PathBuf::from(s)
}
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::Coff => "coff",
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),
"coff" => Ok(BinaryFormat::Coff),
"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)]
#[serde(tag = "mode", rename_all = "lowercase")]
pub enum StoredMapping {
Auto,
Explicit {
arch: String,
base: u64,
entry: Option<u64>,
},
Fat {
arch: String,
},
}
impl StoredMapping {
#[must_use]
pub fn for_request(raw: Option<crate::loader::RawOptions>) -> Self {
match raw {
None => Self::Auto,
Some(opts) => Self::Explicit {
arch: arch_name(opts.arch).to_string(),
base: opts.base,
entry: opts.entry,
},
}
}
#[must_use]
pub fn for_fat_slice(arch: &str) -> Self {
Self::Fat {
arch: arch.to_lowercase(),
}
}
#[must_use]
pub fn describe(&self) -> String {
match self {
Self::Auto => "auto".to_string(),
Self::Explicit { arch, base, entry } => match entry {
Some(e) => format!("explicit raw {arch} base {base:#x} entry {e:#x}"),
None => format!("explicit raw {arch} base {base:#x}"),
},
Self::Fat { arch } => format!("fat slice {arch}"),
}
}
}
fn mapping_conflict(
stored: &StoredMapping,
stored_count: usize,
expected: &StoredMapping,
) -> Error {
Error::Storage(format!(
"mapping mismatch: project db holds {stored_count} annotation(s) under {}, but current open requests {}; use a separate --db PATH for this mapping (annotations are never remapped)",
stored.describe(),
expected.describe(),
))
}
fn legacy_ambiguous(stored_count: usize, version: u32) -> Error {
Error::Storage(format!(
"mapping mismatch: project db holds {stored_count} annotation(s) under an unknown legacy mapping (schema v{version}); use a separate --db PATH for this mapping (annotations are never remapped)"
))
}
#[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>,
#[serde(default)]
pub mapping: Option<StoredMapping>,
#[serde(default)]
pub analysis_rev: Option<u32>,
#[serde(default)]
pub diagnostics_truncated: bool,
#[serde(default)]
pub diagnostics_omitted: usize,
#[serde(default)]
pub inferred_truncated: bool,
#[serde(default)]
pub inferred_omitted: usize,
}
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>,
#[serde(default)]
pub reasons: Vec<crate::analysis::DiscoveryReason>,
}
#[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>,
#[serde(default)]
pub inferred_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,
#[serde(default = "default_protocol")]
pub protocol: u32,
#[serde(default = "default_mode")]
pub mode: String,
#[serde(default)]
pub base: Option<u64>,
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,
#[serde(default)]
pub diagnostics: usize,
#[serde(default)]
pub diagnostics_truncated: bool,
#[serde(default)]
pub diagnostics_omitted: usize,
#[serde(default)]
pub inferred_truncated: bool,
#[serde(default)]
pub inferred_omitted: usize,
#[serde(default)]
pub analysis_revision: u32,
}
fn default_protocol() -> u32 {
crate::WIRE_PROTOCOL
}
fn default_mode() -> String {
"auto".to_string()
}
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", 27)?;
st.serialize_field("binary", &self.binary)?;
st.serialize_field("db_path", &self.db_path)?;
st.serialize_field("version", &self.version)?;
st.serialize_field("protocol", &self.protocol)?;
st.serialize_field("mode", &self.mode)?;
st.serialize_field("base", &self.base)?;
st.serialize_field("base_hex", &self.base.map(crate::addr_hex))?;
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.serialize_field("diagnostics", &self.diagnostics)?;
st.serialize_field("diagnostics_truncated", &self.diagnostics_truncated)?;
st.serialize_field("diagnostics_omitted", &self.diagnostics_omitted)?;
st.serialize_field("inferred_truncated", &self.inferred_truncated)?;
st.serialize_field("inferred_omitted", &self.inferred_omitted)?;
st.serialize_field("analysis_revision", &self.analysis_revision)?;
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 diagnostics: Vec<crate::analysis::Diagnostic>,
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,
crate::analysis::Diagnostics {
records: self.diagnostics,
truncated: self.meta.diagnostics_truncated,
omitted: self.meta.diagnostics_omitted,
inferred_truncated: self.meta.inferred_truncated,
inferred_omitted: self.meta.inferred_omitted,
},
)
}
}
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",
crate::analysis::XrefKind::InferredCode => "inferred-code",
}
}
fn xref_key(x: &Xref) -> String {
format!("{:016x}:{}:{:016x}", x.from, xref_kind_name(x.kind), x.to)
}
fn diagnostic_kind_name(kind: crate::analysis::DiagnosticKind) -> &'static str {
match kind {
crate::analysis::DiagnosticKind::UnresolvedIndirectJump => "indirect_jump",
crate::analysis::DiagnosticKind::UnresolvedIndirectCall => "indirect_call",
crate::analysis::DiagnosticKind::DecodeFailure => "decode_failure",
}
}
fn diagnostic_key(d: &crate::analysis::Diagnostic) -> String {
format!("{:016x}:{}", d.addr, diagnostic_kind_name(d.kind))
}
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()));
}
if analysis.diagnostics.records.len() > MAX_SNAPSHOT_DIAGNOSTICS {
return Err(Error::Limit("snapshot diagnostics exceed cap".to_string()));
}
let inferred: usize = analysis
.functions
.values()
.map(|f| f.inferred_edges().len())
.sum();
if inferred > MAX_SNAPSHOT_INFERRED_EDGES {
return Err(Error::Limit(
"snapshot inferred edges 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),
"diagnostics" => wtxn.delete_table(DIAGNOSTICS),
_ => 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}"))),
}
}
fn live_annotations_in_wtxn(wtxn: &redb::WriteTransaction) -> Result<usize> {
let t = wtxn
.open_table(ANNOTATIONS)
.map_err(|e| Error::Storage(format!("open annotations: {e}")))?;
let mut live = 0usize;
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read annotations: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read annotations: {e}")))?;
let ann: Annotation = decode(&v.value())?;
check_annotation_text(&ann)?;
if !ann.is_empty() {
live += 1;
}
}
Ok(live)
}
#[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.mapping != meta.mapping {
let live = live_annotations_in_wtxn(&wtxn)?;
if live > 0 {
let expected = meta.mapping.clone().unwrap_or(StoredMapping::Auto);
match persisted.mapping {
Some(stored) => return Err(mapping_conflict(&stored, live, &expected)),
None => return Err(legacy_ambiguous(live, persisted.version)),
}
}
return Ok(AnnotationSave::NeedsFull);
}
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_annotation_batch(
db: &Database,
meta: &BinaryMeta,
changes: &BTreeMap<u64, Option<Annotation>>,
) -> Result<AnnotationSave> {
for ann in changes.values().flatten() {
check_annotation_text(ann)?;
}
if changes.is_empty() {
return Ok(AnnotationSave::Fast);
}
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.mapping != meta.mapping {
let live = live_annotations_in_wtxn(&wtxn)?;
if live > 0 {
let expected = meta.mapping.clone().unwrap_or(StoredMapping::Auto);
match persisted.mapping {
Some(stored) => return Err(mapping_conflict(&stored, live, &expected)),
None => return Err(legacy_ambiguous(live, persisted.version)),
}
}
return Ok(AnnotationSave::NeedsFull);
}
if persisted != *meta {
return Ok(AnnotationSave::NeedsFull);
}
}
{
let mut t = wtxn
.open_table(ANNOTATIONS)
.map_err(|e| Error::Storage(format!("open annotations: {e}")))?;
for (&addr, next) in changes {
match next {
Some(ann) => {
t.insert(addr, json(ann)?)
.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)
}
fn reject_mapping_overwrite(wtxn: &redb::WriteTransaction, meta: &BinaryMeta) -> Result<()> {
let version: Option<String> = {
let t = wtxn
.open_table(META)
.map_err(|e| Error::Storage(format!("open meta: {e}")))?;
t.get("version")
.map_err(|e| Error::Storage(format!("read meta: {e}")))?
.map(|v| v.value())
};
let Some(_) = version else {
return Ok(());
};
let persisted: Option<BinaryMeta> = {
let t = wtxn
.open_table(BINARIES)
.map_err(|e| Error::Storage(format!("open binaries: {e}")))?;
match t
.get(0u64)
.map_err(|e| Error::Storage(format!("read binaries: {e}")))?
{
Some(row) => Some(decode(&row.value())?),
None => None,
}
};
let Some(persisted) = persisted else {
return Ok(());
};
if persisted.mapping == meta.mapping {
return Ok(());
}
let live = live_annotations_in_wtxn(wtxn)?;
if live == 0 {
return Ok(());
}
let expected = meta.mapping.clone().unwrap_or(StoredMapping::Auto);
match persisted.mapping {
Some(stored) => Err(mapping_conflict(&stored, live, &expected)),
None => Err(legacy_ambiguous(live, persisted.version)),
}
}
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}")))?;
reject_mapping_overwrite(&wtxn, meta)?;
for t in [
"meta",
"binaries",
"functions",
"blocks",
"xrefs",
"strings",
"annotations",
"diagnostics",
] {
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(),
reasons: f.reasons.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(),
inferred_succs: b.inferred_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}")))?;
}
}
{
let mut t = wtxn
.open_table(DIAGNOSTICS)
.map_err(|e| Error::Storage(format!("open diagnostics: {e}")))?;
for d in &analysis.diagnostics.records {
t.insert(diagnostic_key(d), json(d)?)
.map_err(|e| Error::Storage(format!("write diagnostics: {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>,
diagnostics: Vec<crate::analysis::Diagnostic>,
}
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 mut inferred_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)?;
inferred_count += rec.inferred_succs.len();
if inferred_count > MAX_SNAPSHOT_INFERRED_EDGES {
return Err(Error::Limit(
"snapshot inferred edges exceed cap".to_string(),
));
}
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,
inferred_succs: rec.inferred_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);
let mut reasons = rec.reasons.clone();
reasons.sort_unstable();
reasons.dedup();
functions.push(FunctionLayout {
entry,
name: rec.name.clone(),
calls: rec.calls.clone(),
blocks,
reasons,
});
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)?);
}
}
let diagnostics = read_diagnostics(rtxn)?;
Ok(SnapshotParts {
functions,
call_edges,
xrefs,
strings,
diagnostics,
})
}
fn read_diagnostics(rtxn: &redb::ReadTransaction) -> Result<Vec<crate::analysis::Diagnostic>> {
let t = rtxn
.open_table(DIAGNOSTICS)
.map_err(|e| Error::Storage(format!("open diagnostics: {e}")))?;
let mut diagnostics: Vec<crate::analysis::Diagnostic> = Vec::new();
for row in t
.iter()
.map_err(|e| Error::Storage(format!("read diagnostics: {e}")))?
{
let (_, v) = row.map_err(|e| Error::Storage(format!("read diagnostics: {e}")))?;
let raw = v.value();
if diagnostics.len() >= MAX_SNAPSHOT_DIAGNOSTICS {
return Err(Error::Limit("snapshot diagnostics exceed cap".to_string()));
}
diagnostics.push(decode(&raw)?);
}
diagnostics.sort_unstable();
diagnostics.dedup();
Ok(diagnostics)
}
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)
}
#[allow(clippy::large_enum_variant)]
#[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,
expected_mapping: &StoredMapping,
) -> 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.version != SCHEMA_VERSION {
let annotations = read_annotations_or_empty(&rtxn)?;
if !annotations.is_empty() {
match meta.mapping.clone() {
None => return Err(legacy_ambiguous(annotations.len(), meta.version)),
Some(stored) if &stored != expected_mapping => {
return Err(mapping_conflict(
&stored,
annotations.len(),
expected_mapping,
));
}
Some(_) => {}
}
}
return Ok(Snapshot::Stale { meta, annotations });
}
if meta.mapping.as_ref() != Some(expected_mapping) {
let annotations = read_annotations_or_empty(&rtxn)?;
if !annotations.is_empty() {
match meta.mapping.clone() {
Some(stored) => {
return Err(mapping_conflict(
&stored,
annotations.len(),
expected_mapping,
));
}
None => return Err(legacy_ambiguous(annotations.len(), meta.version)),
}
}
return Ok(Snapshot::Stale { meta, annotations });
}
if meta.content_hash != expected_hash || meta.analysis_rev != Some(ANALYSIS_REVISION) {
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,
diagnostics: parts.diagnostics,
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,
diagnostics: parts.diagnostics,
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::Coff,
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()
);
}
#[test]
fn default_db_path_appends_suffix() {
assert_eq!(
default_db_path(Path::new("foo.exe")),
PathBuf::from("foo.exe.rsdbg.redb")
);
assert_eq!(
default_db_path(Path::new("foo.dll")),
PathBuf::from("foo.dll.rsdbg.redb")
);
assert_ne!(
default_db_path(Path::new("foo.exe")),
default_db_path(Path::new("foo.dll"))
);
assert_eq!(
default_db_path(Path::new("ls.arm64e")),
PathBuf::from("ls.arm64e.rsdbg.redb")
);
assert_eq!(
default_db_path(Path::new("prog")),
PathBuf::from("prog.rsdbg.redb")
);
}
}