mod build;
mod code;
mod data;
mod decl;
mod names;
mod render;
mod text;
use std::collections::{BTreeMap, HashMap};
use std::ops::Range;
use std::sync::{Mutex, PoisonError};
use crate::Database;
use crate::cfg::FunctionId;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
pub opcode_bytes: usize,
pub numbers: Numbers,
pub symbolic: bool,
pub xrefs: usize,
}
impl Default for Options {
fn default() -> Self {
Self {
opcode_bytes: 0,
numbers: Numbers::Masm,
symbolic: true,
xrefs: 2,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Numbers {
Masm,
C,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Item {
Function,
Code,
Data,
Unexplored,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LineKind {
Blank,
SegmentBorder,
SegmentType,
SegmentPermissions,
Banner,
Attributes,
Prototype,
Public,
Proc,
Frame,
Label,
Xref,
Preview,
Instruction,
Data,
Separator,
End,
Comment,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Line {
pub address: u64,
pub item: Item,
pub kind: LineKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Arrow {
pub from: u64,
pub to: u64,
pub conditional: bool,
pub crosses: bool,
pub lane: u16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Jump {
pub(crate) from: u64,
pub(crate) to: u64,
pub(crate) conditional: bool,
pub(crate) crosses: bool,
pub(crate) lane: u16,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Role {
Space,
Prefix,
OpcodeBytes,
Mnemonic,
JumpMnemonic,
CallMnemonic,
ReturnMnemonic,
PaddingMnemonic,
Register,
Number,
Punctuation,
Keyword,
OperandKeyword,
Directive,
CodeName,
DataName,
ImportName,
LocalName,
String,
Comment,
AutoComment,
CodeXref,
DataXref,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Token {
pub text: String,
pub role: Role,
pub target: Option<u64>,
pub automatic: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Rendered {
pub tokens: Vec<Token>,
}
impl Rendered {
pub fn text(&self) -> String {
self.tokens.iter().map(|t| t.text.as_str()).collect()
}
fn width(&self) -> usize {
self.tokens.iter().map(|t| t.text.chars().count()).sum()
}
fn push(&mut self, role: Role, text: impl Into<String>) {
self.tokens.push(Token {
text: text.into(),
role,
target: None,
automatic: false,
});
}
fn push_target(&mut self, role: Role, text: impl Into<String>, target: u64) {
self.tokens.push(Token {
text: text.into(),
role,
target: Some(target),
automatic: false,
});
}
fn push_local(&mut self, text: String) {
self.tokens.push(Token {
text,
role: Role::LocalName,
target: None,
automatic: true,
});
}
fn pad_to(&mut self, column: usize, space: bool) {
let at = self.width();
let n = column.saturating_sub(at).max(usize::from(space && at > 0));
if n > 0 {
self.push(Role::Space, " ".repeat(n));
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Stats {
pub lines: u64,
pub instructions: u64,
pub data_items: u64,
pub dummy_names: u64,
pub string_names: u64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SpanKind {
Instruction {
function: bool,
},
String {
wide: bool,
},
Pointer {
target: u64,
},
Import,
Scalar {
width: u8,
},
Values {
width: u8,
},
Fill {
byte: u8,
},
Uninitialised,
Align,
Table,
Unexplored,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
pub start: u64,
pub end: u64,
pub kind: SpanKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum NameKind {
Code,
Data,
Import,
}
impl NameKind {
fn role(self) -> Role {
match self {
Self::Code => Role::CodeName,
Self::Data => Role::DataName,
Self::Import => Role::ImportName,
}
}
}
#[derive(Clone, Debug)]
struct Name {
text: String,
kind: NameKind,
automatic: bool,
}
impl Name {
fn token(&self, address: u64) -> Token {
Token {
text: self.text.clone(),
role: self.kind.role(),
target: Some(address),
automatic: self.automatic,
}
}
}
#[derive(Clone, Copy, Debug)]
struct Row {
address: u64,
aux: u32,
kind: LineKind,
item: Item,
}
#[derive(Clone, Debug)]
struct Section {
name: String,
start: u64,
end: u64,
file_end: u64,
code: bool,
permissions: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Slot {
offset: i64,
size: u32,
}
#[derive(Clone, Debug)]
struct Function {
id: FunctionId,
end: u64,
limit: u64,
bp_frame: bool,
base: Option<i64>,
noreturn: bool,
public: bool,
prototype: Option<String>,
frame: Vec<Slot>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum DataKind {
String { wide: bool },
Pointer { target: u64 },
Import { index: u32 },
Scalar { width: u8 },
Values { width: u8 },
Fill { byte: u8 },
Uninitialised { width: u8 },
Align { to: u64 },
Table { width: u8, relative: bool },
Unexplored,
}
#[derive(Clone, Copy, Debug)]
struct DataItem {
start: u64,
size: u64,
kind: DataKind,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Decoder {
X86(binbun_x86::Mode),
Aarch64,
}
#[derive(Debug, Default)]
struct EndLines(Mutex<HashMap<u64, u64>>);
impl Clone for EndLines {
fn clone(&self) -> Self {
Self::default()
}
}
#[derive(Clone, Debug)]
pub struct Listing {
options: Options,
rows: Vec<Row>,
sections: Vec<Section>,
names: BTreeMap<u64, Name>,
by_name: HashMap<String, u64>,
functions: BTreeMap<u64, Function>,
owners: Vec<(u64, u64, u64)>,
items: Vec<DataItem>,
jumps: Vec<Jump>,
end_lines: EndLines,
pages: HashMap<u64, u64>,
strings: BTreeMap<u64, String>,
imports: Vec<String>,
digits: usize,
decoder: Option<Decoder>,
relocatable: bool,
pointer_size: u8,
stats: Stats,
comments: BTreeMap<u64, u32>,
}
impl Listing {
pub fn build(db: &Database<'_>, options: &Options) -> Self {
build::build(db, options.clone())
}
pub fn options(&self) -> &Options {
&self.options
}
pub fn len(&self) -> u64 {
self.rows.len() as u64
}
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
pub fn line(&self, n: u64) -> Option<Line> {
let row = self.row(n)?;
Some(Line {
address: row.address,
item: row.item,
kind: row.kind,
})
}
fn row(&self, n: u64) -> Option<&Row> {
self.rows.get(usize::try_from(n).ok()?)
}
pub fn set_comments(&mut self, comments: &BTreeMap<u64, usize>) -> bool {
let wanted: BTreeMap<u64, u32> = comments
.iter()
.filter(|&(&address, &lines)| lines > 1 && self.content_row(address).is_some())
.map(|(&address, &lines)| (address, u32::try_from(lines - 1).unwrap_or(u32::MAX)))
.collect();
if wanted == self.comments {
return false;
}
let more: usize = wanted.values().map(|&k| k as usize).sum();
let old = std::mem::take(&mut self.rows);
let mut rows = Vec::with_capacity(old.len() + more);
let mut content = None;
for row in old {
if row.kind == LineKind::Comment {
continue;
}
rows.push(row);
if matches!(row.kind, LineKind::Instruction | LineKind::Data)
&& content != Some(row.address)
{
content = Some(row.address);
let count = wanted.get(&row.address).copied().unwrap_or(0);
rows.extend((1..=count).map(|k| Row {
aux: k,
kind: LineKind::Comment,
..row
}));
}
}
self.rows = rows;
self.comments = wanted;
self.end_lines
.0
.get_mut()
.unwrap_or_else(PoisonError::into_inner)
.clear();
true
}
fn content_row(&self, address: u64) -> Option<usize> {
let first = self.rows.partition_point(|r| r.address < address);
(first..self.rows.len())
.take_while(|&i| self.rows.get(i).is_some_and(|r| r.address == address))
.find(|&i| {
self.rows
.get(i)
.is_some_and(|r| matches!(r.kind, LineKind::Instruction | LineKind::Data))
})
}
pub fn stats(&self) -> &Stats {
&self.stats
}
pub fn line_of(&self, address: u64) -> u64 {
let after = self.rows.partition_point(|r| r.address <= address);
let Some(last) = after.checked_sub(1) else {
return 0;
};
let head = self.rows.get(last).map_or(0, |r| r.address);
let first = self.rows.partition_point(|r| r.address < head);
let content = (first..after).find(|&i| {
self.rows
.get(i)
.is_some_and(|r| matches!(r.kind, LineKind::Instruction | LineKind::Data))
});
let within = self.item_end(head).is_some_and(|end| address < end);
match content {
Some(i) if within || head == address => i as u64,
_ => after.min(self.rows.len().saturating_sub(1)) as u64,
}
}
fn item_end(&self, head: u64) -> Option<u64> {
let first = self.rows.partition_point(|r| r.address < head);
let row = self
.rows
.get(first..)?
.iter()
.take_while(|r| r.address == head)
.find(|r| matches!(r.kind, LineKind::Instruction | LineKind::Data))?;
match row.kind {
LineKind::Instruction => Some(head + u64::from(row.aux)),
LineKind::Blank
| LineKind::SegmentBorder
| LineKind::SegmentType
| LineKind::SegmentPermissions
| LineKind::Banner
| LineKind::Attributes
| LineKind::Prototype
| LineKind::Public
| LineKind::Proc
| LineKind::Frame
| LineKind::Label
| LineKind::Xref
| LineKind::Preview
| LineKind::Data
| LineKind::Separator
| LineKind::End
| LineKind::Comment => self.item(head).map(|item| item.start + item.size),
}
}
fn item(&self, address: u64) -> Option<&DataItem> {
let i = self.items.partition_point(|item| item.start < address);
self.items.get(i).filter(|item| item.start == address)
}
fn item_holding(&self, address: u64) -> Option<&DataItem> {
let i = self.items.partition_point(|item| item.start <= address);
self.items
.get(i.checked_sub(1)?)
.filter(|item| address < item.start + item.size)
}
pub fn data_of(&self, address: u64) -> Option<u64> {
self.item_holding(address).map(|item| item.start)
}
pub fn name(&self, address: u64) -> Option<&str> {
self.names.get(&address).map(|n| n.text.as_str())
}
pub fn local(&self, address: u64, name: &str) -> Option<(u64, i64)> {
let entry = self
.function_of(address)
.map(|(_, entry)| entry)
.or_else(|| self.functions.contains_key(&address).then_some(address))?;
let function = self.functions.get(&entry)?;
let offset = render::slot_offset(name)?;
if !function.frame.iter().any(|slot| slot.offset == offset) {
return None;
}
Some((entry, function.base?.checked_add(offset)?))
}
pub fn find(&self, wanted: &str) -> Option<u64> {
let wanted = wanted.trim();
if let Some(&a) = self.by_name.get(wanted) {
return Some(a);
}
let hex = wanted.trim_start_matches("0x").trim_end_matches('h');
u64::from_str_radix(hex, 16)
.ok()
.filter(|&a| self.section_of(a).is_some())
}
pub fn describe(&self, address: u64) -> String {
if let Some(name) = self.name(address) {
return name.to_owned();
}
if let Some((_, entry)) = self.function_of(address) {
let name = self.name(entry).unwrap_or("?");
return if address >= entry {
format!("{name}+{:X}", address - entry)
} else {
format!("{name}-{:X}", entry - address)
};
}
if let Some(item) = self.item_holding(address)
&& let Some(name) = self.name(item.start)
{
return format!("{name}+{:X}", address - item.start);
}
let section = self.section_of(address).map_or("?", |s| s.name.as_str());
format!("{section}:{address:0w$X}", w = self.digits)
}
pub fn function_of(&self, address: u64) -> Option<(FunctionId, u64)> {
let i = self
.owners
.partition_point(|&(start, _, _)| start <= address);
let &(_, end, entry) = self.owners.get(i.checked_sub(1)?)?;
if address >= end {
return None;
}
Some((self.functions.get(&entry)?.id, entry))
}
pub fn arrows(&self, lines: Range<u64>) -> Vec<Arrow> {
let (Some(first), Some(last)) = (
self.row(lines.start),
self.row(lines.end.saturating_sub(1).max(lines.start)),
) else {
return Vec::new();
};
let (low, high) = (first.address, last.address);
let inside = |a: u64| (low..=high).contains(&a);
let from = self
.jumps
.partition_point(|j| j.from < low.saturating_sub(1 << 20));
let mut known = self
.end_lines
.0
.lock()
.unwrap_or_else(PoisonError::into_inner);
let mut line_of = |address: u64| {
*known
.entry(address)
.or_insert_with(|| self.line_of(address))
};
self.jumps
.get(from..)
.unwrap_or_default()
.iter()
.take_while(|j| j.from <= high.saturating_add(1 << 20))
.filter(|j| {
let (f, t) = (j.from, j.to);
inside(f) || inside(t) || (f.min(t) < low && f.max(t) > high)
})
.map(|j| Arrow {
from: line_of(j.from),
to: line_of(j.to),
conditional: j.conditional,
crosses: j.crosses,
lane: j.lane,
})
.collect()
}
pub fn spans(&self, addresses: Range<u64>) -> Vec<Span> {
let mut out: Vec<Span> = Vec::new();
let mut push = |span: Span| match out.last_mut() {
Some(last)
if span.kind == SpanKind::Unexplored
&& last.kind == SpanKind::Unexplored
&& last.end == span.start =>
{
last.end = span.end;
}
Some(_) | None => out.push(span),
};
let from = self
.rows
.partition_point(|r| r.address < addresses.start.saturating_sub(16));
let mut items = self
.items
.partition_point(|item| item.start + item.size <= addresses.start);
for row in self.rows.get(from..).unwrap_or_default() {
if row.address >= addresses.end {
break;
}
if row.kind != LineKind::Instruction {
continue;
}
let end = row.address + u64::from(row.aux);
if end <= addresses.start {
continue;
}
while let Some(item) = self.items.get(items).filter(|i| i.start < row.address) {
push(data_span(item));
items += 1;
}
push(Span {
start: row.address,
end,
kind: SpanKind::Instruction {
function: row.item == Item::Function,
},
});
}
while let Some(item) = self.items.get(items).filter(|i| i.start < addresses.end) {
push(data_span(item));
items += 1;
}
out
}
fn section_of(&self, address: u64) -> Option<&Section> {
let i = self.sections.partition_point(|s| s.start <= address);
self.sections
.get(i.checked_sub(1)?)
.filter(|s| address < s.end)
}
pub fn render(&self, db: &Database<'_>, n: u64) -> Rendered {
let mut r = Rendered::default();
if let Some(&row) = self.row(n) {
self.render_row(db, row, &mut r);
}
r
}
}
fn data_span(item: &DataItem) -> Span {
let kind = match item.kind {
DataKind::String { wide } => SpanKind::String { wide },
DataKind::Pointer { target } => SpanKind::Pointer { target },
DataKind::Import { .. } => SpanKind::Import,
DataKind::Scalar { width } => SpanKind::Scalar { width },
DataKind::Values { width } => SpanKind::Values { width },
DataKind::Fill { byte } => SpanKind::Fill { byte },
DataKind::Uninitialised { .. } => SpanKind::Uninitialised,
DataKind::Align { .. } => SpanKind::Align,
DataKind::Table { .. } => SpanKind::Table,
DataKind::Unexplored => SpanKind::Unexplored,
};
Span {
start: item.start,
end: item.start + item.size,
kind,
}
}