use std::collections::{BTreeMap, BTreeSet};
use std::ops::Range;
use binbun_decompile::data::{Data, Object};
use binbun_loader::{Image, Import, Section, SymbolKind};
use binbun_print::c::{Image as Printing, ThreadPointer, Unlifted};
use binbun_semantics::ir::RegisterId;
use binbun_ssa::constant::ReadOnly as _;
use crate::lift::{ImageEnvironment, disassemble, unlifted};
use crate::memory::ImageMemory;
use crate::target::{convention, thread_pointer};
use crate::user::data_model;
const MAX_STRING: u64 = 4096;
const METADATA: [&str; 29] = [
".interp",
".note",
".hash",
".gnu.hash",
".dynsym",
".dynstr",
".gnu.version",
".rela.",
".rel.",
".relr.dyn",
".dynamic",
".eh_frame",
".gcc_except_table",
".sframe",
".stapsdt",
".symtab",
".strtab",
".debug",
".pdata",
".xdata",
".reloc",
".idata",
".didat",
".edata",
".rsrc",
".tbss",
"__TEXT,__unwind_info",
"__TEXT,__eh_frame",
"__TEXT,__gcc_except_tab",
];
pub fn program_data<'a>(image: &'a Image<'_>) -> Vec<&'a Section> {
let mut sections: Vec<&Section> = image
.sections
.iter()
.filter(|section| section.start != 0 && section.size != 0)
.filter(|section| image.is_mapped(section.start) && !image.is_code(section.start))
.filter(|section| {
!METADATA
.iter()
.any(|prefix| section.name.starts_with(prefix))
})
.collect();
sections.sort_by_key(|section| (section.start, section.size));
sections
}
#[derive(Debug)]
pub struct ImageData<'a> {
image: &'a Image<'a>,
memory: ImageMemory<'a>,
relocatable: bool,
sections: Vec<Range<u64>>,
code_data: BTreeMap<u64, u64>,
objects: BTreeMap<u64, (u64, bool)>,
names: BTreeMap<u64, String>,
fixed: BTreeMap<u64, String>,
slots: BTreeSet<u64>,
thread_pointer: ThreadPointer,
long_width: u16,
thread_register: Option<RegisterId>,
}
impl<'a> ImageData<'a> {
pub fn new(
image: &'a Image<'a>,
mut names: BTreeMap<u64, String>,
objects: &[(u64, u64)],
code_data: &BTreeMap<u64, u64>,
) -> Self {
let memory = ImageMemory::new(image);
let mut sections: Vec<Range<u64>> = image
.sections
.iter()
.filter(|section| section.start != 0 && section.size != 0)
.filter(|section| image.is_mapped(section.start) && !image.is_code(section.start))
.map(|section| section.start..section.start.saturating_add(section.size))
.chain(code_data.iter().map(|(&start, &end)| start..end))
.collect();
sections.sort_by_key(|range| (range.start, range.end));
for import in &image.imports {
names
.entry(import.slot)
.or_insert_with(|| format!("{}_ptr", import.name));
}
let mut data = Self {
image,
memory,
relocatable: image.position_independent,
sections,
code_data: code_data.clone(),
objects: BTreeMap::new(),
names,
fixed: image
.imports
.iter()
.filter(|import| import.fixed)
.map(|import| (import.slot, import_name(import)))
.collect(),
slots: image.imports.iter().map(|import| import.slot).collect(),
thread_pointer: thread_pointer(image),
long_width: u16::from(data_model(image).long) * 8,
thread_register: ImageEnvironment::new(image, &[])
.ok()
.and_then(|environment| {
convention(image, environment.declarations()).thread_pointer
}),
};
let mut candidates: Vec<(u64, u64)> = image
.symbols
.iter()
.filter(|symbol| matches!(symbol.kind, SymbolKind::Data | SymbolKind::Other))
.filter_map(|symbol| Some((symbol.address, symbol.size?)))
.chain(
image
.imports
.iter()
.map(|import| (import.slot, u64::from(import.size))),
)
.chain(objects.iter().copied())
.filter(|&(start, size)| size > 0 && data.in_data(start, size))
.collect();
candidates.sort_by_key(|&(start, size)| (start, std::cmp::Reverse(size)));
let mut end = 0;
for (start, size) in candidates {
if start < end {
continue;
}
end = start.saturating_add(size);
let read_only = data.memory.unchanging(start, end);
data.objects.insert(start, (size, read_only));
}
data
}
fn in_data(&self, address: u64, bytes: u64) -> bool {
let Some(end) = address.checked_add(bytes) else {
return false;
};
let after = self
.sections
.partition_point(|section| section.start <= address);
self.sections
.get(..after)
.unwrap_or_default()
.iter()
.any(|section| section.contains(&address) && end <= section.end)
}
pub fn code_data(&self) -> &BTreeMap<u64, u64> {
&self.code_data
}
fn byte(&self, address: u64) -> Option<u8> {
let bits = self.memory.read(address, 1)?;
u8::try_from(bits.low_u64()).ok()
}
}
fn import_name(import: &Import) -> String {
let Some(ordinal) = import.name.strip_prefix('#') else {
return import.name.clone();
};
let module = import.library.as_deref().map_or("import", |library| {
library.split('.').next().unwrap_or(library)
});
format!("{module}_ordinal_{ordinal}")
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
.collect()
}
impl Data for ImageData<'_> {
fn object(&self, address: u64) -> Option<Object> {
let (&start, &(size, read_only)) = self.objects.range(..=address).next_back()?;
let object = Object {
start,
size,
read_only,
};
object.holds(address, 1).then_some(object)
}
fn data(&self, address: u64, bytes: u64) -> Option<bool> {
self.in_data(address, bytes).then(|| {
self.memory
.unchanging(address, address.saturating_add(bytes))
})
}
fn string(&self, address: u64) -> Option<u64> {
for length in 0..=MAX_STRING {
let at = address.checked_add(length)?;
if !self.in_data(at, 1) {
return None;
}
if self.byte(at)? == 0 {
return Some(length);
}
}
None
}
fn constant(&self, address: u64, bytes: u64) -> Option<Vec<u8>> {
Printing::constant(self, address, bytes)
}
fn wide_string(&self, address: u64) -> Option<u64> {
if !address.is_multiple_of(2) {
return None;
}
for length in 0..=MAX_STRING / 2 {
let at = address.checked_add(2 * length)?;
if !self.in_data(at, 2) {
return None;
}
match (self.byte(at)?, self.byte(at + 1)?) {
(0, 0) => return Some(length),
(_, 0) => {}
_ => return None,
}
}
None
}
fn relocatable(&self) -> bool {
self.relocatable
}
fn fixed_import(&self, slot: u64, bytes: u16) -> bool {
self.memory.fixed_slot(slot, bytes)
}
fn import_slot(&self, slot: u64) -> bool {
self.slots.contains(&slot)
}
}
impl Printing for ImageData<'_> {
fn symbol(&self, address: u64) -> Option<String> {
self.names.get(&address).cloned()
}
fn import(&self, slot: u64) -> Option<String> {
self.fixed.get(&slot).cloned()
}
fn read_only(&self, address: u64, bytes: u64) -> bool {
address
.checked_add(bytes)
.is_some_and(|end| bytes > 0 && self.memory.unchanging(address, end))
}
fn constant(&self, address: u64, bytes: u64) -> Option<Vec<u8>> {
(0..bytes)
.map(|offset| self.byte(address.checked_add(offset)?))
.collect()
}
fn string(&self, address: u64) -> Option<Vec<u8>> {
let length = Data::string(self, address)?;
if !Printing::read_only(self, address, length.checked_add(1)?) {
return None;
}
Printing::constant(self, address, length)
}
fn thread_pointer(&self) -> ThreadPointer {
self.thread_pointer
}
fn long_width(&self) -> u16 {
self.long_width
}
fn is_thread_pointer(&self, register: RegisterId) -> bool {
self.thread_register == Some(register)
}
fn unlifted(&self, address: u64) -> Option<Unlifted> {
unlifted(self.image, address).ok()
}
fn instruction(&self, address: u64) -> Option<String> {
let (text, _) = disassemble(self.image, address).ok()?;
Some(text.trim_end().to_owned())
}
}