use std::collections::BTreeMap;
use binbun_decompile::data::Data as _;
use binbun_loader::Image;
use binbun_semantics::core::Memory as _;
use crate::data::{ImageData, program_data};
use crate::memory::ImageMemory;
use crate::references::{Kind, References};
pub const MIN_SCANNED: usize = 4;
const MAX_REFERRED: usize = 1 << 16;
pub const MAX_CODE_TEXT: usize = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Encoding {
Utf8,
Utf16,
}
impl Encoding {
pub const fn unit(self) -> u64 {
match self {
Self::Utf8 => 1,
Self::Utf16 => 2,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Literal {
pub address: u64,
pub encoding: Encoding,
pub text: String,
pub bytes: u64,
pub references: usize,
pub read_only: bool,
}
pub fn strings(
image: &Image<'_>,
references: &References,
data: &ImageData<'_>,
min: usize,
) -> Vec<Literal> {
let memory = ImageMemory::new(image);
let mut ranges: Vec<(u64, u64)> = program_data(image)
.into_iter()
.map(|section| (section.start, section.size))
.chain(
data.code_data()
.iter()
.map(|(&start, &end)| (start, end - start)),
)
.collect();
ranges.sort_unstable();
let sections: Vec<(u64, Vec<u8>)> = ranges
.into_iter()
.map(|(start, size)| {
let mut bytes = vec![0; usize::try_from(size).unwrap_or(0)];
let read = image.read(start, &mut bytes).unwrap_or(0);
bytes.truncate(read);
(start, bytes)
})
.collect();
let mut found: BTreeMap<u64, (Encoding, String, u64)> = BTreeMap::new();
let mut previous = None;
for reference in references.all() {
let address = reference.target;
if previous == Some(address) || !matches!(reference.kind, Kind::Address | Kind::Pointer(_))
{
continue;
}
previous = Some(address);
if let Some(string) = referred(§ions, data, address) {
let end = address + string.2 + string.0.unit();
if !memory.unchanging(address, end) && string.1.chars().count() < min {
continue;
}
found.insert(address, string);
}
}
for (start, bytes) in §ions {
for (offset, end, text) in scan_utf8(bytes, min) {
let bytes = (end - offset) as u64;
let string = (Encoding::Utf8, text, bytes);
found.entry(start + offset as u64).or_insert(string);
}
let skip = usize::from(!start.is_multiple_of(2));
for (offset, end, text) in scan_utf16(bytes.get(skip..).unwrap_or_default(), min) {
let bytes = (end - offset) as u64;
let string = (Encoding::Utf16, text, bytes);
found
.entry(start + (skip + offset) as u64)
.or_insert(string);
}
}
found
.into_iter()
.filter_map(|(address, (encoding, text, bytes))| {
let end = address + bytes + encoding.unit();
(!memory.written(address, end)).then(|| Literal {
address,
encoding,
text,
bytes,
references: references.to(address).len(),
read_only: memory.unchanging(address, end),
})
})
.collect()
}
fn referred(
sections: &[(u64, Vec<u8>)],
data: &ImageData<'_>,
address: u64,
) -> Option<(Encoding, String, u64)> {
let index = sections
.partition_point(|(start, _)| *start <= address)
.checked_sub(1)?;
let (start, bytes) = sections.get(index)?;
let offset = usize::try_from(address - start).ok()?;
let bytes = bytes.get(offset..)?;
let bytes = bytes.get(..MAX_REFERRED.min(bytes.len()))?;
let (encoding, text, length) = text_at(address, bytes)?;
if let Some(object) = data.object(address) {
let end = length + encoding.unit();
if object.start != address || end > object.size {
return None;
}
}
Some((encoding, text, length))
}
pub fn text_at(address: u64, bytes: &[u8]) -> Option<(Encoding, String, u64)> {
let utf8 = utf8_at(bytes);
let utf16 = if address.is_multiple_of(2) {
utf16_at(bytes)
} else {
None
};
let characters =
|text: &Option<(String, usize)>| text.as_ref().map_or(0, |(text, _)| text.chars().count());
let wide = characters(&utf16);
let (encoding, (text, length)) = if wide > 1 && wide > characters(&utf8) {
(Encoding::Utf16, utf16?)
} else {
(Encoding::Utf8, utf8?)
};
Some((encoding, text, length as u64))
}
pub fn code_text(address: u64, bytes: &[u8]) -> Option<(Encoding, u64)> {
let (encoding, text, length) = text_at(address, bytes)?;
let ascii = text
.chars()
.all(|c| matches!(c, ' '..='~' | '\t' | '\n' | '\r'));
(ascii && text.chars().count() >= MIN_SCANNED).then_some((encoding, length))
}
fn printable(c: char) -> bool {
matches!(
c,
' '..='~' | '\t' | '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{1b}'
) || (!c.is_ascii() && !c.is_control())
}
fn utf8_at(bytes: &[u8]) -> Option<(String, usize)> {
let end = bytes.iter().position(|&byte| byte == 0)?;
let text = std::str::from_utf8(bytes.get(..end)?).ok()?;
(end > 0 && text.chars().all(printable)).then(|| (text.to_owned(), end))
}
fn utf16_at(bytes: &[u8]) -> Option<(String, usize)> {
let mut text = String::new();
for &[low, high] in bytes.as_chunks::<2>().0 {
match (low, high) {
(0, 0) => {
let length = 2 * text.chars().count();
return (length > 0).then_some((text, length));
}
(low, 0) if printable(char::from(low)) => text.push(char::from(low)),
_ => return None,
}
}
None
}
fn scan_utf8(bytes: &[u8], min: usize) -> Vec<(usize, usize, String)> {
let mut runs = Vec::new();
let (mut start, mut characters) = (0, 0);
let mut at = 0;
while let Some(&byte) = bytes.get(at) {
if byte == 0 {
if characters >= min.max(1)
&& let Some(text) = bytes
.get(start..at)
.and_then(|b| std::str::from_utf8(b).ok())
{
runs.push((start, at, text.to_owned()));
}
at += 1;
(start, characters) = (at, 0);
continue;
}
let width = match byte {
0x00..=0x7f => 1,
0xc2..=0xdf => 2,
0xe0..=0xef => 3,
0xf0..=0xf4 => 4,
0x80..=0xc1 | 0xf5..=0xff => 0,
};
let character = bytes
.get(at..at + width)
.and_then(|b| std::str::from_utf8(b).ok())
.and_then(|text| text.chars().next())
.filter(|&c| width > 0 && printable(c));
if character.is_some() {
characters += 1;
at += width;
} else {
at += 1;
(start, characters) = (at, 0);
}
}
runs
}
fn scan_utf16(bytes: &[u8], min: usize) -> Vec<(usize, usize, String)> {
let mut runs = Vec::new();
let mut text = String::new();
let mut start = 0;
for (index, &[low, high]) in bytes.as_chunks::<2>().0.iter().enumerate() {
let at = 2 * index;
let character = char::from(low);
if high == 0 && low == 0 {
if text.chars().count() >= min.max(1) {
runs.push((start, at, std::mem::take(&mut text)));
}
text.clear();
start = at + 2;
} else if high == 0 && printable(character) {
text.push(character);
} else {
text.clear();
start = at + 2;
}
}
runs
}