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 AnnotationDocument {
pub revision: u32,
pub sha256: String,
pub size: u64,
pub mapping: StoredMapping,
pub annotations: Vec<AnnotationRow>,
}
#[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>,
) -> 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,
};
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);
}
}
}
}
#[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"));
}
}