use crate::analyzers::{Analyzer, Annotation, AnnotationKind, Limits};
use crate::binary::Binary;
const CONTAINER_PATTERNS: &[&str] = &[
".rodata",
".data.rel.ro",
".rdata",
"__cstring",
"__const",
"__DATA,__const",
];
#[derive(Debug, Clone)]
pub struct StringsAnalyzer {
pub limits: Limits,
}
impl Default for StringsAnalyzer {
fn default() -> Self {
Self::new()
}
}
impl StringsAnalyzer {
#[must_use]
pub fn new() -> Self {
Self {
limits: Limits::default(),
}
}
#[must_use]
pub const fn with_limits(limits: Limits) -> Self {
Self { limits }
}
}
impl Analyzer for StringsAnalyzer {
fn name(&self) -> &'static str {
"strings"
}
fn analyze(&self, bin: &Binary) -> Vec<Annotation> {
let mut out = Vec::new();
let ws = if bin.is_64 { 8usize } else { 4 };
let max = self.limits.max_string_len;
for sec in bin.sections() {
if !is_container_section(&sec.name) {
continue;
}
scan_section(bin, sec, ws, max, &mut out);
}
out
}
}
fn scan_section(
bin: &Binary,
sec: &crate::binary::Section,
ws: usize,
max: usize,
out: &mut Vec<Annotation>,
) {
let data = sec.data.as_slice();
if data.len() < ws.saturating_mul(2) {
return;
}
let mut off = 0usize;
while off.checked_add(ws * 2).is_some_and(|e| e <= data.len()) {
let Some(lookup) = sec.vaddr.checked_add(off as u64) else {
break;
};
let Some(ptr) = bin.read_ptr(lookup) else {
off = off.saturating_add(ws);
continue;
};
let Some(len) = bin.read_ptr(lookup.wrapping_add(ws as u64)) else {
off = off.saturating_add(ws);
continue;
};
if len < 1 || (usize::try_from(len).map_or(true, |n: usize| n > max)) {
off = off.saturating_add(ws);
continue;
}
if !bin.vaddr_in_string_section(ptr, len) {
off = off.saturating_add(ws);
continue;
}
let Some(bytes) = bin.read_at_vaddr(ptr, usize::try_from(len).unwrap_or(usize::MAX)) else {
off = off.saturating_add(ws);
continue;
};
if !is_reasonable_string(bytes) {
off = off.saturating_add(ws);
continue;
}
let text = String::from_utf8_lossy(bytes).into_owned();
if text.is_empty() {
off = off.saturating_add(ws);
continue;
}
let label = truncate(&text, 80);
out.push(Annotation {
vaddr: ptr,
kind: AnnotationKind::String,
label,
comment: Some(text),
});
off = off.saturating_add(ws);
}
}
fn is_container_section(name: &str) -> bool {
for p in CONTAINER_PATTERNS {
if name == *p {
return true;
}
if name.starts_with(p) {
return true;
}
if name.contains(p) {
return true;
}
}
false
}
fn is_reasonable_string(b: &[u8]) -> bool {
let Ok(s) = std::str::from_utf8(b) else {
return false;
};
if s.is_empty() {
return false;
}
!s.chars().any(char::is_control) && s.chars().any(char::is_alphanumeric)
}
fn truncate(s: &str, n: usize) -> String {
if s.chars().count() <= n {
s.to_string()
} else {
let mut out: String = s.chars().take(n).collect();
out.push('\u{2026}');
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::binary::{Binary, BinaryFormat as Bf, Section};
#[test]
fn empty_string_rejected() {
assert!(!is_reasonable_string(b""));
assert!(!is_reasonable_string(b"\x00\x00\x00"));
}
#[test]
fn control_chars_rejected() {
assert!(!is_reasonable_string(b"hello\x00world"));
assert!(!is_reasonable_string(b"hello\nworld"));
}
#[test]
fn alphanumeric_required() {
assert!(is_reasonable_string(b"hello world"));
assert!(is_reasonable_string(b"src/foo.rs:42"));
assert!(is_reasonable_string(b"v1.2.3-rc1"));
assert!(is_reasonable_string(b"~/path/to/{x}"));
}
#[test]
fn punctuation_only_rejected() {
assert!(!is_reasonable_string(b"--"));
assert!(!is_reasonable_string(b"::"));
assert!(!is_reasonable_string(b"..."));
assert!(!is_reasonable_string(b"()"));
}
#[test]
fn truncate_keeps_ellipsis() {
let t = truncate(&"a".repeat(120), 10);
assert!(t.chars().count() <= 11);
assert!(t.ends_with('\u{2026}'));
}
#[test]
fn analyzer_name_returns_strings() {
assert_eq!(StringsAnalyzer::new().name(), "strings");
}
#[test]
fn is_container_section_rejects_non_rodata() {
assert!(!is_container_section(".text"));
assert!(!is_container_section(".data"));
assert!(!is_container_section(".bss"));
}
#[test]
fn is_container_section_accepts_all_known_patterns() {
assert!(is_container_section(".rodata"));
assert!(is_container_section(".data.rel.ro"));
assert!(is_container_section(".rdata"));
assert!(is_container_section("__cstring"));
assert!(is_container_section("__const"));
}
#[test]
fn is_container_section_accepts_starts_with_patterns() {
assert!(is_container_section(".rodata.abc"));
assert!(is_container_section(".rdata.foo"));
assert!(is_container_section(".data.rel.ro.local"));
assert!(is_container_section("__cstring.extra"));
}
#[test]
fn is_container_section_accepts_contains_patterns() {
assert!(is_container_section("segment.__const.extra"));
assert!(is_container_section("foo.__cstring.bar"));
}
#[test]
fn scan_accepts_data_exactly_ws2() {
let sv = 0x4000u64;
let text = b"hello";
let mut rd = ptr_len(sv, text.len() as u64);
rd.pop(); let bin = string_bin(rd, sv, text.to_vec());
assert!(
StringsAnalyzer::new().analyze(&bin).is_empty(),
"section with 15 bytes (< ws*2=16) must be rejected"
);
}
fn string_bin(rodata_data: Vec<u8>, str_vaddr: u64, str_data: Vec<u8>) -> Binary {
Binary::from_test_parts(
Bf::Elf,
true,
true,
vec![
Section {
name: ".rodata".into(),
vaddr: 0x1000,
size: rodata_data.len() as u64,
data: rodata_data,
},
Section {
name: ".rodata.str".into(),
vaddr: str_vaddr,
size: str_data.len() as u64,
data: str_data,
},
],
vec![],
vec![0, 1],
)
}
fn ptr_len(ptr: u64, len: u64) -> Vec<u8> {
let mut b = Vec::with_capacity(16);
b.extend_from_slice(&ptr.to_le_bytes());
b.extend_from_slice(&len.to_le_bytes());
b
}
#[test]
fn scan_finds_string_at_exact_min_section_size() {
let sv = 0x4000u64;
let text = b"hello";
let rd = ptr_len(sv, text.len() as u64);
assert_eq!(rd.len(), 16);
let bin = string_bin(rd, sv, text.to_vec());
let anns = StringsAnalyzer::new().analyze(&bin);
assert_eq!(anns.len(), 1);
assert_eq!(anns[0].label, "hello");
}
#[test]
fn scan_rejects_section_smaller_than_min() {
let sv = 0x4000u64;
let mut rd = ptr_len(sv, 5);
rd.pop();
let bin = string_bin(rd, sv, b"hello".to_vec());
assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
}
#[test]
fn scan_rejects_zero_length_string() {
let sv = 0x4000u64;
let rd = ptr_len(sv, 0);
let bin = string_bin(rd, sv, b"hello".to_vec());
assert!(StringsAnalyzer::new().analyze(&bin).is_empty());
}
#[test]
fn scan_accepts_len_at_max_boundary() {
let lim = Limits {
max_string_len: 5,
..Limits::default()
};
let sv = 0x4000u64;
let text = b"hello";
let rd = ptr_len(sv, text.len() as u64);
let bin = string_bin(rd, sv, text.to_vec());
assert_eq!(StringsAnalyzer::with_limits(lim).analyze(&bin).len(), 1);
}
#[test]
fn scan_rejects_len_above_max() {
let lim = Limits {
max_string_len: 3,
..Limits::default()
};
let sv = 0x4000u64;
let text = b"hello";
let rd = ptr_len(sv, text.len() as u64);
let bin = string_bin(rd, sv, text.to_vec());
assert!(StringsAnalyzer::with_limits(lim).analyze(&bin).is_empty());
}
#[test]
fn scan_accepts_len_one() {
let sv = 0x4000u64;
let text = b"x";
let rd = ptr_len(sv, 1);
let bin = string_bin(rd, sv, text.to_vec());
let anns = StringsAnalyzer::new().analyze(&bin);
assert_eq!(anns.len(), 1, "len=1 with alphanumeric must be accepted");
}
#[test]
fn is_container_section_accepts_substring_match() {
assert!(is_container_section("foo.__cstring.bar"));
assert!(is_container_section("segment.__const.extra"));
}
#[test]
fn is_container_section_rejects_empty_and_random() {
assert!(!is_container_section(""));
assert!(!is_container_section("random_section_name"));
assert!(!is_container_section(".debug_info"));
}
}