use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use crate::db::{self, Annotation, StoredMapping};
use crate::error::{Error, Result};
pub const ANNOTATION_FORMAT_REVISION: u32 = 1;
pub const MAX_TRANSFER_BYTES: usize = 16 * 1024 * 1024;
#[must_use]
pub fn sha256_hex(bytes: &[u8]) -> String {
let digest = Sha256::digest(bytes);
let mut s = String::with_capacity(64);
for b in digest {
s.push(char::from_digit(u32::from(b >> 4), 16).expect("hex digit"));
s.push(char::from_digit(u32::from(b & 0xf), 16).expect("hex digit"));
}
s
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnnotationRow {
pub addr: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rename: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comment: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FuncSeedRow {
pub addr: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mode: Option<crate::analysis::SeedMode>,
#[serde(default)]
pub excluded: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnnotationDocument {
pub revision: u32,
pub sha256: String,
pub size: u64,
pub mapping: StoredMapping,
pub annotations: Vec<AnnotationRow>,
#[serde(default)]
pub func_seeds: Vec<FuncSeedRow>,
}
pub const TYPE_HINT_PREFIX: &str = "type-hint:";
const TYPE_HINT_STRUCT_KIND: &str = "struct";
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TypeField {
pub name: String,
pub offset: u64,
pub size: u64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeHint {
pub name: String,
pub size: u64,
pub fields: Vec<TypeField>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
struct WireHint {
kind: String,
name: String,
size: u64,
#[serde(default)]
fields: Vec<TypeField>,
}
impl From<&TypeHint> for WireHint {
fn from(h: &TypeHint) -> Self {
Self {
kind: TYPE_HINT_STRUCT_KIND.to_string(),
name: h.name.clone(),
size: h.size,
fields: h.fields.clone(),
}
}
}
fn check_hint_shape(hint: &TypeHint) -> Result<()> {
if hint.name.trim().is_empty() {
return Err(Error::Invalid(
"type hint needs a non-empty struct name".to_string(),
));
}
if hint.size == 0 {
return Err(Error::Invalid(
"type hint needs a non-zero struct size".to_string(),
));
}
for f in &hint.fields {
if f.name.trim().is_empty() {
return Err(Error::Invalid(
"type hint needs a non-empty field name".to_string(),
));
}
if f.size == 0 {
return Err(Error::Invalid(format!(
"type hint field {:?} needs a non-zero size",
f.name
)));
}
let end = f.offset.checked_add(f.size).ok_or_else(|| {
Error::Invalid(format!(
"type hint field {:?} offset {:#x} plus size {:#x} overflows",
f.name, f.offset, f.size
))
})?;
if end > hint.size {
return Err(Error::Invalid(format!(
"type hint field {:?} ends at {end} past struct size {}",
f.name, hint.size
)));
}
}
Ok(())
}
pub fn parse_type_hint_json(json: &str) -> Result<TypeHint> {
let wire: WireHint = serde_json::from_str(json.trim())
.map_err(|e| Error::Invalid(format!("malformed type hint: {e}")))?;
if wire.kind != TYPE_HINT_STRUCT_KIND {
return Err(Error::Invalid(format!(
"unsupported type hint kind {:?} (expected {TYPE_HINT_STRUCT_KIND:?})",
wire.kind
)));
}
let hint = TypeHint {
name: wire.name,
size: wire.size,
fields: wire.fields,
};
check_hint_shape(&hint)?;
Ok(hint)
}
#[must_use]
pub fn type_hint_json(hint: &TypeHint) -> serde_json::Value {
serde_json::to_value(WireHint::from(hint)).expect("type hint serializes")
}
pub fn format_type_hint(hint: &TypeHint) -> Result<String> {
check_hint_shape(hint)?;
let wire = WireHint::from(hint);
let json = serde_json::to_string(&wire)
.map_err(|e| Error::Storage(format!("encode type hint: {e}")))?;
let text = format!("{TYPE_HINT_PREFIX}{json}");
if text.len() > db::MAX_ANNOTATION_BYTES {
return Err(Error::Limit(format!(
"type hint of {} bytes exceeds {}",
text.len(),
db::MAX_ANNOTATION_BYTES
)));
}
Ok(text)
}
pub fn parse_type_hint(comment: &str) -> Result<Option<TypeHint>> {
let Some(rest) = comment.strip_prefix(TYPE_HINT_PREFIX) else {
return Ok(None);
};
let first = rest.lines().next().unwrap_or("");
parse_type_hint_json(first).map(Some)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ImportSummary {
pub rows: usize,
pub changed: usize,
}
pub fn build_document(
sha256: &str,
size: u64,
mapping: &StoredMapping,
annotations: &BTreeMap<u64, Annotation>,
seeds: &BTreeMap<u64, crate::db::FuncSeed>,
) -> Result<String> {
let mut rows = Vec::new();
for (&addr, ann) in annotations {
if ann.is_empty() {
continue;
}
let rename = ann.name.clone().filter(|s| !s.is_empty());
let comment = ann.comment.clone().filter(|s| !s.is_empty());
if rename.is_none() && comment.is_none() {
continue;
}
if rows.len() >= db::MAX_SNAPSHOT_ANNOTATIONS {
return Err(Error::Limit("annotation export exceeds cap".to_string()));
}
for (label, s) in [("rename", &rename), ("comment", &comment)] {
if let Some(t) = s
&& t.len() > db::MAX_ANNOTATION_BYTES
{
return Err(Error::Limit(format!(
"annotation {label} of {} bytes exceeds {}",
t.len(),
db::MAX_ANNOTATION_BYTES
)));
}
}
rows.push(AnnotationRow {
addr,
rename,
comment,
});
}
let doc = AnnotationDocument {
revision: ANNOTATION_FORMAT_REVISION,
sha256: sha256.to_string(),
size,
mapping: mapping.clone(),
annotations: rows,
func_seeds: seeds
.iter()
.map(|(&addr, s)| FuncSeedRow {
addr,
mode: s.mode,
excluded: s.excluded,
})
.collect(),
};
let text = serde_json::to_string(&doc)
.map_err(|e| Error::Storage(format!("encode annotation document: {e}")))?;
if text.len() > MAX_TRANSFER_BYTES {
return Err(Error::Limit(format!(
"annotation export of {} bytes exceeds the {MAX_TRANSFER_BYTES}-byte import cap; split or clear annotations instead of truncating",
text.len()
)));
}
Ok(text)
}
pub fn parse_document(text: &str) -> Result<AnnotationDocument> {
if text.len() > MAX_TRANSFER_BYTES {
return Err(Error::Limit(format!(
"annotation document of {} bytes exceeds the {MAX_TRANSFER_BYTES}-byte cap",
text.len()
)));
}
serde_json::from_str(text)
.map_err(|e| Error::Invalid(format!("malformed annotation document: {e}")))
}
fn is_digest(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
#[allow(clippy::too_many_arguments)]
pub fn validate_document(
doc: &AnnotationDocument,
expected_sha256: &str,
expected_size: u64,
expected_mapping: &StoredMapping,
is_function: &dyn Fn(u64) -> bool,
current: &BTreeMap<u64, Annotation>,
overwrite: bool,
) -> Result<BTreeMap<u64, Option<Annotation>>> {
if doc.revision != ANNOTATION_FORMAT_REVISION {
return Err(Error::Invalid(format!(
"unsupported annotation revision {} (expected {ANNOTATION_FORMAT_REVISION})",
doc.revision
)));
}
if !is_digest(&doc.sha256) {
return Err(Error::Invalid(
"malformed annotation identity: sha256 must be 64 hex chars".to_string(),
));
}
if doc.sha256 != expected_sha256 || doc.size != expected_size {
return Err(Error::Storage(format!(
"annotation identity mismatch: document is sha256 {} size {}, but project is sha256 {expected_sha256} size {expected_size}",
doc.sha256, doc.size
)));
}
if doc.mapping != *expected_mapping {
return Err(Error::Storage(format!(
"annotation mapping mismatch: document holds annotations under {}, but project uses {}; use the mapping the document was exported from (annotations are never remapped)",
doc.mapping.describe(),
expected_mapping.describe()
)));
}
let mut seen = BTreeSet::new();
for row in &doc.annotations {
if !seen.insert(row.addr) {
return Err(Error::Invalid(format!(
"duplicate annotation address {:#x}",
row.addr
)));
}
if row.rename.is_none() && row.comment.is_none() {
return Err(Error::Invalid(format!(
"annotation row at {:#x} has neither rename nor comment",
row.addr
)));
}
for (label, s) in [("rename", &row.rename), ("comment", &row.comment)] {
if let Some(t) = s
&& t.len() > db::MAX_ANNOTATION_BYTES
{
return Err(Error::Limit(format!(
"annotation {label} of {} bytes exceeds {}",
t.len(),
db::MAX_ANNOTATION_BYTES
)));
}
}
if let Some(name) = &row.rename
&& !name.is_empty()
&& !is_function(row.addr)
{
return Err(Error::NotFound(format!(
"rename target {:#x} is not a known function",
row.addr
)));
}
}
let mut changes: BTreeMap<u64, Option<Annotation>> = BTreeMap::new();
let mut live_after: usize = current.values().filter(|a| !a.is_empty()).count();
for row in &doc.annotations {
let existing = current.get(&row.addr);
let mut merged = existing.cloned().unwrap_or_default();
for (label, supplied) in [("rename", &row.rename), ("comment", &row.comment)] {
if let Some(v) = supplied {
let new_val = (!v.is_empty()).then(|| v.clone());
let old_val = if label == "rename" {
&merged.name
} else {
&merged.comment
};
if !overwrite && old_val.is_some() && *old_val != new_val {
return Err(Error::Invalid(format!(
"annotation conflict at {:#x}: existing {label} differs (import with overwrite to replace supplied fields)",
row.addr
)));
}
if label == "rename" {
merged.name = new_val;
} else {
merged.comment = new_val;
}
}
}
let next = (!merged.is_empty()).then_some(merged);
if next.as_ref() != existing {
match (&existing, &next) {
(None, Some(_)) => live_after += 1,
(Some(_), None) => live_after -= 1,
_ => {}
}
if live_after > db::MAX_SNAPSHOT_ANNOTATIONS {
return Err(Error::Limit("annotation import exceeds cap".to_string()));
}
changes.insert(row.addr, next);
}
}
Ok(changes)
}
pub fn apply_changes(
annotations: &mut BTreeMap<u64, Annotation>,
changes: &BTreeMap<u64, Option<Annotation>>,
) {
for (&addr, next) in changes {
match next {
Some(ann) => {
annotations.insert(addr, ann.clone());
}
None => {
annotations.remove(&addr);
}
}
}
}
pub fn validate_seed_rows(
rows: &[FuncSeedRow],
project_arch: crate::disasm::Arch,
current: &BTreeMap<u64, crate::db::FuncSeed>,
overwrite: bool,
) -> Result<BTreeMap<u64, Option<crate::db::FuncSeed>>> {
use crate::disasm::Arch;
let arm = matches!(project_arch, Arch::Arm32 | Arch::Thumb);
let mut seen = BTreeSet::new();
for row in rows {
if !seen.insert(row.addr) {
return Err(Error::Invalid(format!(
"duplicate func seed address {:#x}",
row.addr
)));
}
if row.mode.is_some() && !arm {
return Err(Error::Invalid(format!(
"func seed mode at {:#x} needs a 32-bit ARM project (arch {})",
row.addr,
crate::db::arch_name(project_arch),
)));
}
}
let mut changes: BTreeMap<u64, Option<crate::db::FuncSeed>> = BTreeMap::new();
let mut total = current.len();
for row in rows {
let next = crate::db::FuncSeed {
mode: row.mode,
excluded: row.excluded,
};
match current.get(&row.addr) {
Some(existing) if *existing == next => {}
Some(_) if !overwrite => {
return Err(Error::Invalid(format!(
"func seed conflict at {:#x} (import with overwrite to replace)",
row.addr
)));
}
None => {
total += 1;
if total > db::MAX_SNAPSHOT_SEEDS {
return Err(Error::Limit("func seed import exceeds cap".to_string()));
}
changes.insert(row.addr, Some(next));
}
Some(_) => {
changes.insert(row.addr, Some(next));
}
}
}
Ok(changes)
}
pub fn apply_seed_changes(
seeds: &mut BTreeMap<u64, crate::db::FuncSeed>,
changes: &BTreeMap<u64, Option<crate::db::FuncSeed>>,
) {
for (&addr, next) in changes {
match next {
Some(seed) => {
seeds.insert(addr, *seed);
}
None => {
seeds.remove(&addr);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn digest_is_stable_lowercase_hex() {
let a = sha256_hex(b"abc");
assert_eq!(a.len(), 64);
assert!(a.bytes().all(|b| b.is_ascii_hexdigit()));
assert_eq!(a, sha256_hex(b"abc"));
assert_ne!(a, sha256_hex(b"abd"));
}
}