use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use petgraph::graphmap::DiGraphMap;
use serde::{Deserialize, Serialize};
use crate::disasm::{Arch, Insn, resolve_adrp_pair};
use crate::error::{Error, Result};
use crate::ir::IrOp;
use crate::loader::strings::{self, Encoding, StringHit};
use crate::loader::{BinaryFormat, LoadedBinary, RawOptions, Section, Segment, load_raw};
pub const MAX_TOTAL_INSNS: usize = 1_000_000;
pub const MAX_FUNCTIONS: usize = 100_000;
pub const MAX_XREFS_PER_KIND: usize = 1_000_000;
pub const MAX_SEEDS: usize = 100_000;
pub const ANALYSIS_REVISION: u32 = 5;
pub const MAX_DIAGNOSTICS: usize = 100_000;
pub const MAX_INFERRED_PER_SITE: usize = 1;
pub const MAX_TABLE_ENTRIES_PER_SITE: usize = 8;
pub const MIN_TABLE_ENTRIES_PER_SITE: usize = 2;
pub const MAX_TABLE_GUARD_BACKTRACK: usize = 4;
pub const MAX_INFERRED_EDGES: usize = 100_000;
pub const MAX_PAGE: usize = 1024;
pub const MAX_CALL_DEPTH: usize = 64;
pub const MAX_SLICE_DEPTH: usize = 64;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum XrefKind {
Code,
Data,
String,
#[serde(rename = "inferred-code")]
InferredCode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct Xref {
pub from: u64,
pub to: u64,
pub kind: XrefKind,
}
impl Serialize for Xref {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("Xref", 5)?;
st.serialize_field("from", &self.from)?;
st.serialize_field("from_hex", &crate::addr_hex(self.from))?;
st.serialize_field("to", &self.to)?;
st.serialize_field("to_hex", &crate::addr_hex(self.to))?;
st.serialize_field("kind", &self.kind)?;
st.end()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiscoveryReason {
#[serde(alias = "Entry")]
Entry,
#[serde(alias = "Export")]
Export,
#[serde(alias = "DirectCall")]
DirectCall,
#[serde(alias = "Prologue")]
Prologue,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DiagnosticKind {
#[serde(alias = "UnresolvedIndirectJump")]
UnresolvedIndirectJump,
#[serde(alias = "UnresolvedIndirectCall")]
UnresolvedIndirectCall,
#[serde(alias = "DecodeFailure")]
DecodeFailure,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)]
pub struct Diagnostic {
pub addr: u64,
pub kind: DiagnosticKind,
}
impl Serialize for Diagnostic {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("Diagnostic", 3)?;
st.serialize_field("addr", &self.addr)?;
st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
st.serialize_field("kind", &self.kind)?;
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct DiagnosticRow {
pub kind: DiagnosticKind,
pub addr: u64,
pub func: Option<u64>,
pub detail: String,
}
impl Serialize for DiagnosticRow {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("DiagnosticRow", 6)?;
st.serialize_field("kind", &self.kind)?;
st.serialize_field("addr", &self.addr)?;
st.serialize_field("addr_hex", &crate::addr_hex(self.addr))?;
st.serialize_field("func", &self.func)?;
st.serialize_field("func_hex", &self.func.map(crate::addr_hex))?;
st.serialize_field("detail", &self.detail)?;
st.end()
}
}
#[must_use]
pub fn diagnostic_detail(kind: DiagnosticKind) -> &'static str {
match kind {
DiagnosticKind::UnresolvedIndirectJump => {
"indirect jump without a direct target; the site stays edgeless"
}
DiagnosticKind::UnresolvedIndirectCall => {
"indirect call without a direct target; the site stays edgeless"
}
DiagnosticKind::DecodeFailure => {
"executable bytes at a queued discovery address that did not decode"
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Diagnostics {
pub records: Vec<Diagnostic>,
pub truncated: bool,
pub omitted: usize,
pub inferred_truncated: bool,
pub inferred_omitted: usize,
}
impl Diagnostics {
#[must_use]
pub fn empty() -> Self {
Self::default()
}
#[must_use]
pub fn collect(records: Vec<Diagnostic>, truncated: bool, omitted: usize) -> Self {
let mut sorted = records;
sorted.sort_unstable();
sorted.dedup();
if sorted.len() > MAX_DIAGNOSTICS {
let excess = sorted.len() - MAX_DIAGNOSTICS;
sorted.truncate(MAX_DIAGNOSTICS);
Self {
records: sorted,
truncated: true,
omitted: omitted.saturating_add(excess),
inferred_truncated: false,
inferred_omitted: 0,
}
} else {
Self {
records: sorted,
truncated,
omitted,
inferred_truncated: false,
inferred_omitted: 0,
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BasicBlock {
pub start: u64,
pub insns: Vec<Insn>,
}
impl BasicBlock {
#[must_use]
pub fn end(&self) -> u64 {
self.insns
.last()
.map(|i| i.addr.wrapping_add(u64::from(i.size)))
.unwrap_or(self.start)
}
#[must_use]
pub fn id(&self, func_entry: u64) -> String {
format!("block@{func_entry:#x}+{:#x}", self.start)
}
}
#[derive(Debug, Clone)]
pub struct Function {
pub entry: u64,
pub name: Option<String>,
pub blocks: BTreeMap<u64, BasicBlock>,
cfg: DiGraphMap<u64, ()>,
inferred: BTreeSet<(u64, u64)>,
pub reasons: BTreeSet<DiscoveryReason>,
}
impl Function {
#[must_use]
pub fn id(&self) -> String {
format!("func@{:#x}", self.entry)
}
#[must_use]
pub fn insn_count(&self) -> usize {
self.blocks.values().map(|b| b.insns.len()).sum()
}
#[must_use]
pub fn successors(&self, block: u64) -> Vec<u64> {
self.cfg.neighbors(block).collect()
}
#[must_use]
pub fn predecessors(&self, block: u64) -> Vec<u64> {
self.cfg
.neighbors_directed(block, petgraph::Direction::Incoming)
.collect()
}
#[must_use]
pub fn edges(&self) -> Vec<(u64, u64)> {
self.cfg.all_edges().map(|(a, b, _)| (a, b)).collect()
}
#[must_use]
pub fn inferred_edges(&self) -> Vec<(u64, u64)> {
self.inferred.iter().copied().collect()
}
#[must_use]
pub fn reason_list(&self) -> Vec<DiscoveryReason> {
self.reasons.iter().copied().collect()
}
#[must_use]
pub fn from_parts(
entry: u64,
name: Option<String>,
blocks: BTreeMap<u64, BasicBlock>,
edges: &[(u64, u64)],
reasons: Vec<DiscoveryReason>,
inferred: &[(u64, u64)],
) -> Self {
let mut cfg = DiGraphMap::new();
for &start in blocks.keys() {
cfg.add_node(start);
}
for &(a, b) in edges {
if blocks.contains_key(&a) && blocks.contains_key(&b) {
cfg.add_edge(a, b, ());
}
}
let mut inferred_set = BTreeSet::new();
for &(a, b) in inferred {
if blocks.contains_key(&a) && blocks.contains_key(&b) {
inferred_set.insert((a, b));
}
}
Self {
entry,
name,
blocks,
cfg,
inferred: inferred_set,
reasons: reasons.into_iter().collect(),
}
}
}
pub const STRUCTURE_WARNING: &str = "approximate structure over CFG+IR: back edges and two-successor branch sites are syntactic hints, not verified loops/ifs; not a decompiler";
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct LoopInfo {
pub header: u64,
pub latches: Vec<u64>,
}
impl Serialize for LoopInfo {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("LoopInfo", 3)?;
st.serialize_field("header", &self.header)?;
st.serialize_field("header_hex", &crate::addr_hex(self.header))?;
st.serialize_field("latches", &self.latches)?;
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct IfInfo {
pub cond: u64,
pub then_target: u64,
pub else_target: u64,
}
impl Serialize for IfInfo {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("IfInfo", 6)?;
st.serialize_field("cond", &self.cond)?;
st.serialize_field("cond_hex", &crate::addr_hex(self.cond))?;
st.serialize_field("then_target", &self.then_target)?;
st.serialize_field("then_hex", &crate::addr_hex(self.then_target))?;
st.serialize_field("else_target", &self.else_target)?;
st.serialize_field("else_hex", &crate::addr_hex(self.else_target))?;
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FuncStructure {
pub loops: Vec<LoopInfo>,
pub ifs: Vec<IfInfo>,
pub warning: String,
}
impl Function {
#[must_use]
pub fn structure(&self, arch: Arch) -> FuncStructure {
let mut gray: BTreeSet<u64> = BTreeSet::new();
let mut black: BTreeSet<u64> = BTreeSet::new();
let mut back_edges: Vec<(u64, u64)> = Vec::new();
for &root in self.blocks.keys() {
if gray.contains(&root) || black.contains(&root) {
continue;
}
gray.insert(root);
let mut stack: Vec<(u64, std::vec::IntoIter<u64>)> =
vec![(root, sorted_succs(self, root))];
while let Some((node, nexts)) = stack.last_mut() {
let node = *node;
match nexts.next() {
Some(next) => {
if gray.contains(&next) {
back_edges.push((node, next));
} else if !black.contains(&next) {
gray.insert(next);
stack.push((next, sorted_succs(self, next)));
}
}
None => {
let (done, _) = stack.pop().expect("nonempty stack pops");
gray.remove(&done);
black.insert(done);
}
}
}
}
let mut by_header: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
for (latch, header) in back_edges {
by_header.entry(header).or_default().push(latch);
}
let loops = by_header
.into_iter()
.map(|(header, mut latches)| {
latches.sort_unstable();
latches.dedup();
LoopInfo { header, latches }
})
.collect();
let mut ifs: Vec<IfInfo> = Vec::new();
for (start, block) in &self.blocks {
let Some(last) = block.insns.last() else {
continue;
};
let lifted = crate::ir::lift(arch, last);
let is_cbranch = matches!(lifted.first(), Some(row) if row.op == IrOp::CBranch);
if !is_cbranch {
continue;
}
let mut succs = self.successors(*start);
if succs.len() != 2 {
continue;
}
succs.sort_unstable();
let target = lifted.first().and_then(|row| row.target);
let (then_target, else_target) = match target {
Some(t) if succs.contains(&t) => {
(t, if succs[0] == t { succs[1] } else { succs[0] })
}
_ => (succs[0], succs[1]),
};
ifs.push(IfInfo {
cond: *start,
then_target,
else_target,
});
}
ifs.sort_by_key(|i| i.cond);
FuncStructure {
loops,
ifs,
warning: STRUCTURE_WARNING.to_string(),
}
}
}
fn sorted_succs(func: &Function, block: u64) -> std::vec::IntoIter<u64> {
let mut succs = func.successors(block);
succs.sort_unstable();
succs.into_iter()
}
#[derive(Debug, Clone)]
pub struct Analysis {
pub arch: Arch,
pub functions: BTreeMap<u64, Function>,
callgraph: DiGraphMap<u64, ()>,
pub xrefs: Vec<Xref>,
pub strings: Vec<StringHit>,
pub diagnostics: Diagnostics,
}
impl Analysis {
#[must_use]
pub fn containing_function(&self, va: u64) -> Option<u64> {
let (&entry, func) = self.functions.range(..=va).next_back()?;
func.blocks
.values()
.any(|b| va >= b.start && va < b.end())
.then_some(entry)
}
#[must_use]
pub fn calls_of(&self, entry: u64) -> Vec<u64> {
let mut v: Vec<u64> = self.callgraph.neighbors(entry).collect();
v.sort_unstable();
v
}
#[must_use]
pub fn calls_count(&self, entry: u64) -> usize {
self.callgraph.neighbors(entry).count()
}
#[must_use]
pub fn callers_of(&self, entry: u64) -> Vec<u64> {
let mut v: Vec<u64> = self
.callgraph
.neighbors_directed(entry, petgraph::Direction::Incoming)
.collect();
v.sort_unstable();
v
}
#[must_use]
pub fn callees_transitive(&self, entry: u64, max_depth: usize) -> Vec<(u64, usize)> {
self.reachable(entry, max_depth, petgraph::Direction::Outgoing)
}
#[must_use]
pub fn callers_transitive(&self, entry: u64, max_depth: usize) -> Vec<(u64, usize)> {
self.reachable(entry, max_depth, petgraph::Direction::Incoming)
}
#[must_use]
pub fn slice_to(&self, addr: u64, max_depth: usize) -> Vec<(u64, usize)> {
use std::collections::{HashMap, HashSet, VecDeque};
let cap = max_depth.min(MAX_SLICE_DEPTH);
if cap == 0 {
return Vec::new();
}
let mut xref_preds: HashMap<u64, Vec<u64>> = HashMap::new();
for x in &self.xrefs {
xref_preds.entry(x.to).or_default().push(x.from);
}
let mut seen: HashSet<u64> = HashSet::from([addr]);
let mut queue: VecDeque<(u64, usize)> = VecDeque::from([(addr, 0)]);
let mut out: Vec<(u64, usize)> = Vec::new();
while let Some((cur, depth)) = queue.pop_front() {
if depth >= cap {
continue;
}
let mut next: Vec<u64> = Vec::new();
if let Some(v) = xref_preds.get(&cur) {
next.extend(v.iter().copied());
}
next.extend(self.insn_preds(cur));
next.sort_unstable();
next.dedup();
for n in next {
if seen.insert(n) {
out.push((n, depth + 1));
queue.push_back((n, depth + 1));
}
}
}
out.sort_unstable();
out
}
fn insn_preds(&self, cur: u64) -> Vec<u64> {
let Some(entry) = self.containing_function(cur) else {
return Vec::new();
};
let Some(f) = self.functions.get(&entry) else {
return Vec::new();
};
let Some((&start, block)) = f
.blocks
.range(..=cur)
.next_back()
.filter(|(_, b)| cur < b.end())
else {
return Vec::new();
};
let addrs: Vec<u64> = block.insns.iter().map(|i| i.addr).collect();
match addrs.iter().position(|&a| a == cur) {
Some(i) if i > 0 => vec![addrs[i - 1]],
Some(_) => {
let mut preds = f.predecessors(start);
preds.sort_unstable();
let mut out = Vec::new();
for p in preds {
if let Some(last) = f.blocks.get(&p).and_then(|b| b.insns.last()) {
out.push(last.addr);
}
}
out
}
None => Vec::new(),
}
}
fn reachable(
&self,
entry: u64,
max_depth: usize,
dir: petgraph::Direction,
) -> Vec<(u64, usize)> {
use std::collections::{HashSet, VecDeque};
let cap = max_depth.min(MAX_CALL_DEPTH);
if cap == 0 || !self.callgraph.contains_node(entry) {
return Vec::new();
}
let mut seen: HashSet<u64> = HashSet::from([entry]);
let mut queue: VecDeque<(u64, usize)> = VecDeque::new();
queue.push_back((entry, 0));
let mut out: Vec<(u64, usize)> = Vec::new();
while let Some((cur, depth)) = queue.pop_front() {
if depth >= cap {
continue;
}
let mut next: Vec<u64> = self.callgraph.neighbors_directed(cur, dir).collect();
next.sort_unstable();
for n in next {
if seen.insert(n) {
out.push((n, depth + 1));
queue.push_back((n, depth + 1));
}
}
}
out.sort_unstable();
out
}
#[must_use]
pub fn structure_of(&self, entry: u64) -> Option<FuncStructure> {
self.functions.get(&entry).map(|f| f.structure(self.arch))
}
#[must_use]
pub fn call_edges(&self) -> Vec<(u64, u64)> {
self.callgraph.all_edges().map(|(a, b, _)| (a, b)).collect()
}
#[must_use]
pub fn from_parts(
arch: Arch,
functions: BTreeMap<u64, Function>,
call_edges: &[(u64, u64)],
xrefs: Vec<Xref>,
strings: Vec<StringHit>,
diagnostics: Diagnostics,
) -> Self {
let mut callgraph = DiGraphMap::<u64, ()>::new();
for e in functions.keys() {
callgraph.add_node(*e);
}
for &(a, b) in call_edges {
if functions.contains_key(&a) && functions.contains_key(&b) {
callgraph.add_edge(a, b, ());
}
}
let inferred_truncated = diagnostics.inferred_truncated;
let inferred_omitted = diagnostics.inferred_omitted;
let mut diagnostics = Diagnostics::collect(
diagnostics.records,
diagnostics.truncated,
diagnostics.omitted,
);
diagnostics.inferred_truncated = inferred_truncated;
diagnostics.inferred_omitted = inferred_omitted;
Self {
arch,
functions,
callgraph,
xrefs,
strings,
diagnostics,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BlockLayout {
pub start: u64,
pub end: u64,
pub insns: Vec<InsnLayout>,
pub succs: Vec<u64>,
#[serde(default)]
pub inferred_succs: Vec<u64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct InsnLayout {
pub addr: u64,
pub size: u8,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionLayout {
pub entry: u64,
pub name: Option<String>,
pub calls: Vec<u64>,
pub blocks: Vec<BlockLayout>,
#[serde(default)]
pub reasons: Vec<DiscoveryReason>,
}
#[must_use]
pub fn layout(analysis: &Analysis) -> Vec<FunctionLayout> {
analysis
.functions
.values()
.map(|f| {
let mut calls = analysis.calls_of(f.entry);
calls.sort_unstable();
let blocks = f
.blocks
.values()
.map(|b| {
let mut succs = f.successors(b.start);
succs.sort_unstable();
let insns = b
.insns
.iter()
.map(|i| InsnLayout {
addr: i.addr,
size: i.size,
})
.collect();
let mut inferred_succs: Vec<u64> = f
.inferred_edges()
.into_iter()
.filter(|(a, _)| *a == b.start)
.map(|(_, t)| t)
.collect();
inferred_succs.sort_unstable();
BlockLayout {
start: b.start,
end: b.end(),
insns,
succs,
inferred_succs,
}
})
.collect();
FunctionLayout {
entry: f.entry,
name: f.name.clone(),
calls,
blocks,
reasons: f.reason_list(),
}
})
.collect()
}
pub fn rebuild(
arch: Arch,
bin: &LoadedBinary,
functions: &[FunctionLayout],
call_edges: &[(u64, u64)],
xrefs: Vec<Xref>,
strings: Vec<StringHit>,
diagnostics: Diagnostics,
) -> Result<Analysis> {
if functions.len() > MAX_FUNCTIONS {
return Err(Error::Limit(format!("more than {MAX_FUNCTIONS} functions")));
}
if diagnostics.records.len() > MAX_DIAGNOSTICS + diagnostics.omitted {
return Err(Error::Limit(format!(
"more than {MAX_DIAGNOSTICS} diagnostics"
)));
}
let space = AddrSpace::new(bin);
let mapped: u64 = bin.segments.iter().map(|s| s.data.len() as u64).sum();
let mut ranged: u64 = 0;
let mut rebuilt: BTreeMap<u64, Function> = BTreeMap::new();
for f in functions {
let mut blocks: BTreeMap<u64, BasicBlock> = BTreeMap::new();
let mut edges: Vec<(u64, u64)> = Vec::new();
let mut inferred: Vec<(u64, u64)> = Vec::new();
for b in &f.blocks {
let len = b.end.wrapping_sub(b.start);
ranged = ranged
.checked_add(len)
.filter(|m| *m <= mapped)
.ok_or_else(|| {
Error::Storage(format!(
"snapshot block {:#x} exceeds mapped bytes",
b.start
))
})?;
blocks.insert(b.start, decode_block(arch, &space, b)?);
edges.extend(b.succs.iter().map(|s| (b.start, *s)));
inferred.extend(b.inferred_succs.iter().map(|s| (b.start, *s)));
}
rebuilt.insert(
f.entry,
Function::from_parts(
f.entry,
f.name.clone(),
blocks,
&edges,
f.reasons.clone(),
&inferred,
),
);
}
Ok(Analysis::from_parts(
arch,
rebuilt,
call_edges,
xrefs,
strings,
diagnostics,
))
}
fn decode_block(arch: Arch, space: &AddrSpace, layout: &BlockLayout) -> Result<BasicBlock> {
let mut insns = Vec::with_capacity(layout.insns.len());
for boundary in &layout.insns {
let bytes = space.code_bytes(boundary.addr).ok_or_else(|| {
Error::Storage(format!(
"snapshot block {:#x} leaves executable bytes",
layout.start
))
})?;
let Some(insn) = crate::disasm::disasm_first(arch, bytes, boundary.addr).map_err(|e| {
Error::Storage(format!(
"snapshot block {:#x} does not decode: {e}",
layout.start
))
})?
else {
return Err(Error::Storage(format!(
"snapshot block {:#x} has no bytes at {:#x}",
layout.start, boundary.addr
)));
};
if insn.size != boundary.size {
return Err(Error::Storage(format!(
"snapshot block {:#x} decodes {:#x} as {} bytes, not {}",
layout.start, boundary.addr, insn.size, boundary.size
)));
}
insns.push(insn);
}
let block = BasicBlock {
start: layout.start,
insns,
};
if block.end() != layout.end {
return Err(Error::Storage(format!(
"snapshot block {:#x} ends at {:#x}, not {:#x}",
layout.start,
block.end(),
layout.end
)));
}
Ok(block)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct AnalysisSummary {
pub functions: usize,
pub blocks: usize,
pub insns: usize,
pub xrefs: usize,
pub strings: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct FunctionSummary {
pub id: String,
pub entry: u64,
pub name: Option<String>,
pub blocks: usize,
pub insns: usize,
pub calls: Vec<u64>,
}
impl Serialize for FunctionSummary {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("FunctionSummary", 7)?;
st.serialize_field("id", &self.id)?;
st.serialize_field("entry", &self.entry)?;
st.serialize_field("entry_hex", &crate::addr_hex(self.entry))?;
st.serialize_field("name", &self.name)?;
st.serialize_field("blocks", &self.blocks)?;
st.serialize_field("insns", &self.insns)?;
st.serialize_field("calls", &self.calls)?;
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct BlockSummary {
pub id: String,
pub start: u64,
pub end: u64,
pub insns: usize,
pub succs: Vec<u64>,
}
impl Serialize for BlockSummary {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut st = serializer.serialize_struct("BlockSummary", 7)?;
st.serialize_field("id", &self.id)?;
st.serialize_field("start", &self.start)?;
st.serialize_field("start_hex", &crate::addr_hex(self.start))?;
st.serialize_field("end", &self.end)?;
st.serialize_field("end_hex", &crate::addr_hex(self.end))?;
st.serialize_field("insns", &self.insns)?;
st.serialize_field("succs", &self.succs)?;
st.end()
}
}
fn truncate_limit(limit: usize) -> usize {
limit.min(MAX_PAGE)
}
#[derive(Debug, Clone)]
pub struct StringsFilter {
pub pattern: Option<String>,
pub min_len: Option<usize>,
pub section: Option<String>,
pub include_code: bool,
pub start: usize,
pub limit: usize,
}
impl Default for StringsFilter {
fn default() -> Self {
Self {
pattern: None,
min_len: None,
section: None,
include_code: false,
start: 0,
limit: 50,
}
}
}
fn page_slice<T: Clone>(items: &[T], offset: usize, limit: usize) -> Vec<T> {
items
.iter()
.skip(offset)
.take(truncate_limit(limit))
.cloned()
.collect()
}
impl Analysis {
#[must_use]
pub fn summary(&self) -> AnalysisSummary {
AnalysisSummary {
functions: self.functions.len(),
blocks: self.functions.values().map(|f| f.blocks.len()).sum(),
insns: self.functions.values().map(|f| f.insn_count()).sum(),
xrefs: self.xrefs.len(),
strings: self.strings.len(),
}
}
#[must_use]
pub fn functions_page(&self, offset: usize, limit: usize) -> Vec<FunctionSummary> {
self.functions
.values()
.skip(offset)
.take(truncate_limit(limit))
.map(|f| FunctionSummary {
id: f.id(),
entry: f.entry,
name: f.name.clone(),
blocks: f.blocks.len(),
insns: f.insn_count(),
calls: self.calls_of(f.entry),
})
.collect()
}
#[must_use]
pub fn blocks_page(
&self,
func_entry: u64,
offset: usize,
limit: usize,
) -> Option<Vec<BlockSummary>> {
let f = self.functions.get(&func_entry)?;
Some(
f.blocks
.values()
.skip(offset)
.take(truncate_limit(limit))
.map(|b| BlockSummary {
id: b.id(func_entry),
start: b.start,
end: b.end(),
insns: b.insns.len(),
succs: f.successors(b.start),
})
.collect(),
)
}
#[must_use]
pub fn block_insns(
&self,
func_entry: u64,
block_start: u64,
offset: usize,
limit: usize,
) -> Option<Vec<Insn>> {
let b = self.functions.get(&func_entry)?.blocks.get(&block_start)?;
Some(page_slice(&b.insns, offset, limit))
}
#[must_use]
pub fn xrefs_page(&self, kind: Option<XrefKind>, offset: usize, limit: usize) -> Vec<Xref> {
let cap = truncate_limit(limit);
match kind {
Some(k) => self
.xrefs
.iter()
.copied()
.filter(|x| x.kind == k)
.skip(offset)
.take(cap)
.collect(),
None => self.xrefs.iter().copied().skip(offset).take(cap).collect(),
}
}
#[must_use]
pub fn xrefs_to(&self, addr: u64) -> Vec<Xref> {
self.xrefs
.iter()
.copied()
.filter(|x| x.to == addr)
.collect()
}
#[must_use]
pub fn xrefs_from(&self, addr: u64) -> Vec<Xref> {
self.xrefs
.iter()
.copied()
.filter(|x| x.from == addr)
.collect()
}
#[must_use]
pub fn diagnostics_matching(
&self,
kind: Option<DiagnosticKind>,
func: Option<u64>,
) -> Vec<Diagnostic> {
let mut out: Vec<Diagnostic> = self
.diagnostics
.records
.iter()
.copied()
.filter(|d| kind.is_none_or(|k| d.kind == k))
.filter(|d| func.is_none_or(|e| self.containing_function(d.addr) == Some(e)))
.collect();
out.sort_by_key(|d| (d.kind, d.addr));
out
}
#[must_use]
pub fn strings_page(&self, offset: usize, limit: usize) -> Vec<StringHit> {
page_slice(&self.strings, offset, limit)
}
pub fn strings_page_filtered(&self, filter: &StringsFilter) -> Result<Vec<StringHit>> {
filter_string_hits(&self.strings, filter)
}
pub fn strings_decoded_view(
&self,
bin: &LoadedBinary,
filter: &StringsFilter,
decode: strings::DecodeSpec,
) -> Result<Vec<StringHit>> {
let mut hits: Vec<StringHit> = Vec::new();
for seg in &bin.segments {
let decoded = decode.apply(&seg.data);
for mut h in strings::extract(
&decoded,
strings::DEFAULT_MIN_LEN,
strings::DEFAULT_MAX_HITS,
Some(seg.vaddr),
) {
let (section, executable) = locate_hit(&bin.sections, seg, h.vaddr);
h.section = section;
h.executable = executable;
hits.push(h);
}
}
hits.sort_by_key(|h| h.vaddr.unwrap_or(u64::MAX));
filter_string_hits(&hits, filter)
}
}
fn filter_string_hits(hits: &[StringHit], filter: &StringsFilter) -> Result<Vec<StringHit>> {
let show_code = filter.include_code || filter.section.is_some() || filter.pattern.is_some();
let mut matcher: Option<strings::PatternMatcher<'_>> = None;
let cap = truncate_limit(filter.limit);
let start = filter.start;
let mut out: Vec<StringHit> = Vec::new();
let mut matched: usize = 0;
for h in hits {
if h.executable && !show_code {
continue;
}
if let Some(sec) = &filter.section
&& h.section.as_deref() != Some(sec.as_str())
{
continue;
}
if let Some(min) = filter.min_len
&& h.value.chars().count() < min
{
continue;
}
if let Some(pat) = &filter.pattern {
if matcher.is_none() {
matcher = Some(strings::PatternMatcher::compile(pat)?);
}
let Some(m) = matcher.as_ref() else {
continue;
};
if !m.is_match(&h.value) {
continue;
}
}
if matched >= start && out.len() < cap {
out.push(h.clone());
}
matched += 1;
if out.len() >= cap && (filter.pattern.is_none() || matcher.is_some()) {
break;
}
}
Ok(out)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Flow {
Seq,
Branch { target: Option<u64> },
CBranch { target: Option<u64> },
Call { target: Option<u64> },
Ret,
}
impl Flow {
fn ends_block(self) -> bool {
!matches!(self, Self::Seq)
}
}
fn classify(arch: Arch, insn: &Insn) -> Flow {
match crate::ir::lift(arch, insn)
.first()
.map(|i| (i.op, i.target))
{
Some((IrOp::Branch, target)) => Flow::Branch { target },
Some((IrOp::CBranch, target)) => Flow::CBranch { target },
Some((IrOp::Call, target)) => Flow::Call { target },
Some((IrOp::Return, _)) => Flow::Ret,
_ => Flow::Seq,
}
}
fn locate_hit(sections: &[Section], seg: &Segment, vaddr: Option<u64>) -> (Option<String>, bool) {
let Some(va) = vaddr else {
return (None, false);
};
if let Some(sec) = sections
.iter()
.find(|s| va >= s.vaddr && va.wrapping_sub(s.vaddr) < s.size)
{
return (Some(sec.name.clone()), sec.executable);
}
(None, seg.executable)
}
struct AddrSpace<'a> {
exec: Vec<&'a Segment>,
all: Vec<&'a Segment>,
}
impl<'a> AddrSpace<'a> {
fn new(bin: &'a LoadedBinary) -> Self {
Self {
exec: bin.segments.iter().filter(|s| s.executable).collect(),
all: bin.segments.iter().collect(),
}
}
fn seg_at(segs: &[&'a Segment], va: u64) -> Option<&'a Segment> {
segs.iter()
.find(|s| va >= s.vaddr && va.wrapping_sub(s.vaddr) < s.mem_size)
.copied()
}
fn code_bytes(&self, va: u64) -> Option<&'a [u8]> {
let seg = Self::seg_at(&self.exec, va)?;
let off = va.wrapping_sub(seg.vaddr) as usize;
seg.data.get(off..)
}
fn file_bytes_at(&self, va: u64, len: usize) -> Option<&'a [u8]> {
for seg in &self.all {
let Some(off) = va.checked_sub(seg.vaddr) else {
continue;
};
let Ok(off) = usize::try_from(off) else {
continue;
};
let Some(end) = off.checked_add(len) else {
continue;
};
if end <= seg.data.len() {
return seg.data.get(off..end);
}
}
None
}
fn contains(&self, va: u64) -> bool {
Self::seg_at(&self.all, va).is_some()
}
fn first_exec_base(&self) -> Option<u64> {
self.exec.iter().map(|s| s.vaddr).min()
}
}
fn decode_one(arch: Arch, space: &AddrSpace, va: u64) -> Result<Option<Insn>> {
let bytes = match space.code_bytes(va) {
Some(b) if !b.is_empty() => b,
_ => return Ok(None),
};
match crate::disasm::disasm_first(arch, bytes, va) {
Ok(v) => Ok(v),
Err(Error::Invalid(_)) => Ok(None),
Err(e) => Err(e),
}
}
struct Decoded {
insn: Insn,
flow: Flow,
}
fn authoritative_seeds(space: &AddrSpace, bin: &LoadedBinary) -> Vec<u64> {
let mut seeds: Vec<u64> = Vec::new();
if let Some(entry) = bin.entry
&& space.code_bytes(entry).is_some()
{
seeds.push(entry);
}
for exp in &bin.exports {
if let Some(addr) = exp.address
&& seeds.len() < MAX_SEEDS
&& space.code_bytes(addr).is_some()
{
seeds.push(addr);
}
}
for imp in &bin.imports {
if let Some(addr) = imp.address
&& seeds.len() < MAX_SEEDS
&& space.code_bytes(addr).is_some()
{
seeds.push(addr);
}
}
if seeds.is_empty()
&& let Some(base) = space.first_exec_base()
{
seeds.push(base);
}
seeds.sort_unstable();
seeds.dedup();
seeds
}
fn prologue_seeds(arch: Arch, space: &AddrSpace, reached: &BTreeSet<u64>) -> Result<Vec<u64>> {
let mut streams: Vec<CandStream<'_>> = space
.exec
.iter()
.map(|seg| CandStream::new(seg, arch))
.collect();
let mut heap: BinaryHeap<(Reverse<u64>, usize)> = BinaryHeap::with_capacity(streams.len());
for (idx, stream) in streams.iter_mut().enumerate() {
if let Some(va) = stream.next_candidate() {
heap.push((Reverse(va), idx));
}
}
let mut seeds: Vec<u64> = Vec::new();
let mut last: Option<u64> = None;
while seeds.len() < MAX_SEEDS {
let Some((Reverse(va), idx)) = heap.pop() else {
break;
};
if let Some(nxt) = streams[idx].next_candidate() {
heap.push((Reverse(nxt), idx));
}
if last == Some(va) {
continue;
}
last = Some(va);
if !reached.contains(&va) && decode_one(arch, space, va)?.is_some() {
seeds.push(va);
}
}
Ok(seeds)
}
fn prologue_patterns(arch: Arch) -> &'static [&'static [u8]] {
match arch {
Arch::X86_64 => &[
&[0x48, 0x89, 0xE5],
&[0x48, 0x83, 0xEC],
&[0x48, 0x81, 0xEC],
&[0xF3, 0x0F, 0x1E, 0xFA],
],
Arch::X86_32 => &[&[0x89, 0xE5], &[0x83, 0xEC], &[0x81, 0xEC]],
Arch::Aarch64 | Arch::Arm32 | Arch::Thumb => &[],
}
}
#[derive(Debug, Clone, Copy)]
enum CandMatch {
Aarch64,
ArmPush,
Thumb,
X86,
}
struct CandStream<'a> {
data: &'a [u8],
vaddr: u64,
arch: Arch,
kind: CandMatch,
stride: usize,
min_width: usize,
split: usize,
cur: usize,
phase: u8,
stash: Option<u64>,
}
impl<'a> CandStream<'a> {
fn new(seg: &'a Segment, arch: Arch) -> Self {
let (kind, stride, min_width) = match arch {
Arch::Aarch64 => (CandMatch::Aarch64, 4, 4),
Arch::Arm32 => (CandMatch::ArmPush, 4, 4),
Arch::Thumb => (CandMatch::Thumb, 2, 2),
Arch::X86_64 | Arch::X86_32 => (CandMatch::X86, 1, 2),
};
let len = seg.data.len();
let wrap_off = u64::MAX.wrapping_sub(seg.vaddr).wrapping_add(1);
let split = (wrap_off.min(len as u64) as usize)
.div_ceil(stride)
.saturating_mul(stride)
.min(len);
Self {
data: &seg.data,
vaddr: seg.vaddr,
arch,
kind,
stride,
min_width,
split,
cur: split,
phase: 0,
stash: None,
}
}
fn next_candidate(&mut self) -> Option<u64> {
loop {
if self.phase == 0 {
if self.cur >= self.data.len() {
self.phase = 1;
self.cur = 0;
continue;
}
let off = self.cur;
self.cur += self.stride;
if off + self.min_width > self.data.len() {
self.cur = self.data.len();
continue;
}
if let Some(va) = self.match_at(off) {
if matches!(self.kind, CandMatch::X86)
&& va == u64::MAX
&& self.vaddr.wrapping_add(off as u64) == 0
{
self.stash = Some(va);
continue;
}
return Some(va);
}
} else if self.phase == 1 {
if self.cur >= self.split {
self.phase = 2;
continue;
}
let off = self.cur;
self.cur += self.stride;
if off + self.min_width > self.data.len() {
self.cur = self.split;
continue;
}
if let Some(va) = self.match_at(off) {
return Some(va);
}
} else {
return self.stash.take();
}
}
}
fn match_at(&self, off: usize) -> Option<u64> {
let va = self.vaddr.wrapping_add(off as u64);
match self.kind {
CandMatch::Aarch64 => {
let raw = self.data.get(off..off + 4)?;
let w = u32::from_le_bytes(raw.try_into().ok()?);
((w & 0xFFC0_7FFF) == 0xA980_7BFD).then_some(va)
}
CandMatch::ArmPush => {
let raw = self.data.get(off..off + 4)?;
let w = u32::from_le_bytes(raw.try_into().ok()?);
is_arm_push_lr(w).then_some(va)
}
CandMatch::Thumb => {
let raw = self.data.get(off..off + 2)?;
let hw = u16::from_le_bytes(raw.try_into().ok()?);
if (hw & 0xFF00) == 0xB500 && (hw & 0x0100) != 0 {
Some(va)
} else if off + 4 <= self.data.len() {
let raw = self.data.get(off..off + 4)?;
let w = u32::from_le_bytes(raw.try_into().ok()?);
is_arm_push_lr(w).then_some(va)
} else {
None
}
}
CandMatch::X86 => {
for pat in prologue_patterns(self.arch) {
let Some(win) = self.data.get(off..off + pat.len()) else {
continue;
};
if win == *pat {
if off > 0 && self.data[off - 1] == 0x55 {
return Some(va.wrapping_sub(1));
}
return Some(va);
}
}
None
}
}
}
}
fn is_arm_push_lr(word: u32) -> bool {
(word & 0x0FFF_4000) == 0x092D_4000
}
struct Walker<'a> {
arch: Arch,
space: &'a AddrSpace<'a>,
decoded: BTreeMap<u64, Decoded>,
jump_targets: BTreeSet<u64>,
fallthroughs: BTreeSet<u64>,
call_targets: BTreeSet<u64>,
diagnostics: BTreeSet<Diagnostic>,
}
impl<'a> Walker<'a> {
fn new(arch: Arch, space: &'a AddrSpace<'a>) -> Self {
Self {
arch,
space,
decoded: BTreeMap::new(),
jump_targets: BTreeSet::new(),
fallthroughs: BTreeSet::new(),
call_targets: BTreeSet::new(),
diagnostics: BTreeSet::new(),
}
}
fn run(&mut self, seeds: Vec<u64>) -> Result<()> {
let mut stack = seeds;
while let Some(va) = stack.pop() {
if self.decoded.contains_key(&va) {
continue;
}
if self.decoded.len() >= MAX_TOTAL_INSNS {
return Err(Error::Limit(format!(
"more than {MAX_TOTAL_INSNS} instructions"
)));
}
let Some(bytes) = self.space.code_bytes(va).filter(|b| !b.is_empty()) else {
continue;
};
let insn = match crate::disasm::disasm_first(self.arch, bytes, va) {
Ok(Some(insn)) => insn,
Ok(None) => continue,
Err(Error::Invalid(_)) => {
self.diagnostics.insert(Diagnostic {
addr: va,
kind: DiagnosticKind::DecodeFailure,
});
continue;
}
Err(e) => return Err(e),
};
let flow = classify(self.arch, &insn);
match flow {
Flow::Branch { target: None } | Flow::CBranch { target: None } => {
self.diagnostics.insert(Diagnostic {
addr: va,
kind: DiagnosticKind::UnresolvedIndirectJump,
});
}
Flow::Call { target: None } => {
self.diagnostics.insert(Diagnostic {
addr: va,
kind: DiagnosticKind::UnresolvedIndirectCall,
});
}
_ => {}
}
let next = va.wrapping_add(u64::from(insn.size));
match flow {
Flow::Seq => stack.push(next),
Flow::Branch { target } => {
if let Some(t) = target {
self.jump_targets.insert(t);
stack.push(t);
}
}
Flow::CBranch { target } => {
if let Some(t) = target {
self.jump_targets.insert(t);
stack.push(t);
}
self.fallthroughs.insert(next);
stack.push(next);
}
Flow::Call { target } => {
if let Some(t) = target {
self.jump_targets.insert(t);
self.call_targets.insert(t);
stack.push(t);
}
self.fallthroughs.insert(next);
stack.push(next);
}
Flow::Ret => {}
}
self.decoded.insert(va, Decoded { insn, flow });
}
Ok(())
}
}
#[must_use]
pub fn function_owner(entries: &[u64], va: u64) -> u64 {
let idx = entries.partition_point(|e| *e <= va);
if idx == 0 {
entries[0]
} else {
entries[idx - 1]
}
}
struct InferredJumps {
pairs: Vec<(u64, u64)>,
slots: Vec<(u64, u64)>,
truncated: bool,
omitted: usize,
}
fn resolve_indirect_site(
arch: Arch,
format: BinaryFormat,
space: &AddrSpace,
decoded: &BTreeMap<u64, Decoded>,
entries: &[u64],
site: u64,
) -> Option<u64> {
let found = decoded.get(&site)?;
if found.insn.mnem != "jmp" {
return None;
}
if !matches!(found.flow, Flow::Branch { target: None }) {
return None;
}
if found.insn.branch_target.is_some() {
return None;
}
let slot = found.insn.mem_target?;
let width: usize = match arch {
Arch::X86_32 => 4,
Arch::X86_64 => 8,
Arch::Aarch64 | Arch::Arm32 | Arch::Thumb => return None,
};
if format != BinaryFormat::Raw {
return None;
}
let raw = space.file_bytes_at(slot, width)?;
let target = match width {
4 => u64::from(u32::from_le_bytes(raw.try_into().ok()?)),
_ => u64::from_le_bytes(raw.try_into().ok()?),
};
let target_bytes = space.code_bytes(target)?;
if !matches!(
crate::disasm::disasm_first(arch, target_bytes, target),
Ok(Some(_))
) {
return None;
}
if entries.is_empty() {
return None;
}
if function_owner(entries, target) != function_owner(entries, site) {
return None;
}
Some(target)
}
fn resolve_table_site(
arch: Arch,
format: BinaryFormat,
space: &AddrSpace,
decoded: &BTreeMap<u64, Decoded>,
entries: &[u64],
site: u64,
) -> Option<TableResolution> {
let found = decoded.get(&site)?;
if found.insn.mnem != "jmp" {
return None;
}
if !matches!(found.flow, Flow::Branch { target: None }) {
return None;
}
if found.insn.branch_target.is_some() {
return None;
}
let base = found.insn.table_base?;
let width: usize = match arch {
Arch::X86_32 => 4,
Arch::X86_64 => 8,
Arch::Aarch64 | Arch::Arm32 | Arch::Thumb => return None,
};
if format != BinaryFormat::Raw {
return None;
}
if entries.is_empty() {
return None;
}
let owner = function_owner(entries, site);
if !table_guard_present(decoded, entries, site, owner) {
return None;
}
let mut targets = BTreeSet::new();
let mut slots = Vec::new();
for i in 0..MAX_TABLE_ENTRIES_PER_SITE {
let slot = base.wrapping_add((i as u64).wrapping_mul(width as u64));
let Some(target) = table_slot_target(arch, space, entries, owner, slot, width) else {
break;
};
slots.push(slot);
targets.insert(target);
}
if slots.len() < MIN_TABLE_ENTRIES_PER_SITE {
return None;
}
let probe = base.wrapping_add((MAX_TABLE_ENTRIES_PER_SITE as u64).wrapping_mul(width as u64));
if table_slot_target(arch, space, entries, owner, probe, width).is_some() {
return None;
}
Some(TableResolution {
targets: targets.into_iter().collect(),
slots,
})
}
struct TableResolution {
targets: Vec<u64>,
slots: Vec<u64>,
}
fn table_guard_present(
decoded: &BTreeMap<u64, Decoded>,
entries: &[u64],
site: u64,
owner: u64,
) -> bool {
decoded
.range(..site)
.rev()
.take(MAX_TABLE_GUARD_BACKTRACK)
.take_while(|(va, _)| function_owner(entries, **va) == owner)
.any(|(_, d)| matches!(d.flow, Flow::CBranch { target: Some(_) }))
}
fn table_slot_target(
arch: Arch,
space: &AddrSpace,
entries: &[u64],
owner: u64,
slot: u64,
width: usize,
) -> Option<u64> {
let raw = space.file_bytes_at(slot, width)?;
let target = match width {
4 => u64::from(u32::from_le_bytes(raw.try_into().ok()?)),
_ => u64::from_le_bytes(raw.try_into().ok()?),
};
let target_bytes = space.code_bytes(target)?;
if !matches!(
crate::disasm::disasm_first(arch, target_bytes, target),
Ok(Some(_))
) {
return None;
}
if function_owner(entries, target) != owner {
return None;
}
Some(target)
}
fn resolve_indirect_jumps(
walk: &mut Walker,
arch: Arch,
format: BinaryFormat,
space: &AddrSpace,
entries: &[u64],
max_edges: usize,
) -> Result<InferredJumps> {
let mut pairs: Vec<(u64, u64)> = Vec::new();
let mut slots: Vec<(u64, u64)> = Vec::new();
let mut processed: BTreeSet<u64> = BTreeSet::new();
let mut truncated = false;
let mut omitted: usize = 0;
while let Some(site) = walk
.diagnostics
.iter()
.filter(|d| {
d.kind == DiagnosticKind::UnresolvedIndirectJump && !processed.contains(&d.addr)
})
.map(|d| d.addr)
.next()
{
let inserted = processed.insert(site);
debug_assert!(inserted);
if let Some(target) =
resolve_indirect_site(arch, format, space, &walk.decoded, entries, site)
{
if pairs.len() >= max_edges {
truncated = true;
omitted += 1;
continue;
}
pairs.push((site, target));
walk.run(vec![target])?;
walk.jump_targets.insert(target);
} else if let Some(table) =
resolve_table_site(arch, format, space, &walk.decoded, entries, site)
{
let cost = table.targets.len();
if pairs.len().saturating_add(cost) > max_edges {
truncated = true;
omitted += cost;
continue;
}
for target in &table.targets {
pairs.push((site, *target));
walk.jump_targets.insert(*target);
}
for slot in &table.slots {
slots.push((site, *slot));
}
walk.run(table.targets)?;
}
}
debug_assert_eq!(pairs.iter().collect::<BTreeSet<_>>().len(), pairs.len());
Ok(InferredJumps {
pairs,
slots,
truncated,
omitted,
})
}
#[derive(Debug, Clone, Default)]
pub struct StringSpanIndex {
spans: Vec<(u64, u64)>,
prefix_max: Vec<u64>,
}
impl StringSpanIndex {
#[must_use]
pub fn new(spans: Vec<(u64, u64)>) -> Self {
let mut prefix_max = Vec::with_capacity(spans.len());
let mut running: u64 = 0;
for (_, e) in &spans {
running = running.max(*e);
prefix_max.push(running);
}
Self { spans, prefix_max }
}
#[must_use]
pub fn lookup(&self, target: u64) -> Option<u64> {
let cand = self.prefix_max.partition_point(|&m| m <= target);
if cand >= self.spans.len() {
return None;
}
let upto = self.spans.partition_point(|&(s, _)| s <= target);
if cand < upto {
let (s, e) = self.spans[cand];
if target >= s && target < e {
return Some(s);
}
}
None
}
#[must_use]
pub fn len(&self) -> usize {
self.spans.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.spans.is_empty()
}
}
pub fn analyze(bin: &LoadedBinary) -> Result<Analysis> {
let arch = bin.arch;
let space = AddrSpace::new(bin);
let mut walk = Walker::new(arch, &space);
let seeds1 = authoritative_seeds(&space, bin);
walk.run(seeds1.clone())?;
let round1: BTreeSet<u64> = walk.decoded.keys().copied().collect();
let seeds2 = prologue_seeds(arch, &space, &round1)?;
walk.run(seeds2.clone())?;
if walk.decoded.is_empty() {
let diagnostics = Diagnostics::collect(walk.diagnostics.into_iter().collect(), false, 0);
return Ok(Analysis {
arch,
functions: BTreeMap::new(),
callgraph: DiGraphMap::new(),
xrefs: Vec::new(),
strings: Vec::new(),
diagnostics,
});
}
let mut entries: BTreeSet<u64> = BTreeSet::new();
for s in seeds1.iter().chain(seeds2.iter()) {
if walk.decoded.contains_key(s) {
entries.insert(*s);
}
}
for t in &walk.call_targets {
if walk.decoded.contains_key(t) {
entries.insert(*t);
}
}
if entries.is_empty()
&& let Some((&first, _)) = walk.decoded.iter().next()
{
entries.insert(first);
}
if entries.len() > MAX_FUNCTIONS {
return Err(Error::Limit(format!("more than {MAX_FUNCTIONS} functions")));
}
let seeds1_set: BTreeSet<u64> = seeds1.iter().copied().collect();
let seeds2_set: BTreeSet<u64> = seeds2.iter().copied().collect();
let export_addrs: BTreeSet<u64> = bin.exports.iter().filter_map(|e| e.address).collect();
let mut reasons: BTreeMap<u64, BTreeSet<DiscoveryReason>> = BTreeMap::new();
for e in &entries {
let mut r = BTreeSet::new();
if Some(*e) == bin.entry {
r.insert(DiscoveryReason::Entry);
}
if export_addrs.contains(e) {
r.insert(DiscoveryReason::Export);
}
if walk.call_targets.contains(e) {
r.insert(DiscoveryReason::DirectCall);
}
if seeds2_set.contains(e) {
r.insert(DiscoveryReason::Prologue);
}
if r.is_empty() && seeds1_set.contains(e) {
r.insert(DiscoveryReason::Entry);
}
if r.is_empty() {
r.insert(DiscoveryReason::Entry);
}
reasons.insert(*e, r);
}
let entry_list: Vec<u64> = entries.iter().copied().collect();
let owner = |va: u64| -> u64 { function_owner(&entry_list, va) };
let jumps = resolve_indirect_jumps(
&mut walk,
arch,
bin.format,
&space,
&entry_list,
MAX_INFERRED_EDGES,
)?;
let Walker {
decoded,
jump_targets,
fallthroughs,
diagnostics: mut diagnostic_set,
..
} = walk;
let mut starts: BTreeSet<u64> = BTreeSet::new();
starts.extend(entries.iter().copied());
starts.extend(jump_targets.iter().copied());
starts.extend(fallthroughs.iter().copied());
let mut blocks: BTreeMap<u64, BasicBlock> = BTreeMap::new();
let mut cur_start: Option<u64> = None;
let mut cur: Vec<Insn> = Vec::new();
let flush =
|start: &mut Option<u64>, cur: &mut Vec<Insn>, blocks: &mut BTreeMap<u64, BasicBlock>| {
if let Some(s) = start.take()
&& !cur.is_empty()
{
blocks.insert(
s,
BasicBlock {
start: s,
insns: std::mem::take(cur),
},
);
}
};
for (&va, d) in &decoded {
if starts.contains(&va) {
flush(&mut cur_start, &mut cur, &mut blocks);
cur_start = Some(va);
} else if cur_start.is_none() {
cur_start = Some(va);
}
cur.push(d.insn.clone());
if d.flow.ends_block() {
flush(&mut cur_start, &mut cur, &mut blocks);
}
}
flush(&mut cur_start, &mut cur, &mut blocks);
let mut names: BTreeMap<u64, String> = BTreeMap::new();
for exp in &bin.exports {
if let Some(addr) = exp.address {
names.entry(addr).or_insert_with(|| exp.name.clone());
}
}
for imp in &bin.imports {
if let Some(addr) = imp.address {
names.entry(addr).or_insert_with(|| imp.name.clone());
}
}
let mut functions: BTreeMap<u64, Function> = BTreeMap::new();
for e in &entries {
functions.insert(
*e,
Function {
entry: *e,
name: names.get(e).cloned(),
blocks: BTreeMap::new(),
cfg: DiGraphMap::new(),
inferred: BTreeSet::new(),
reasons: reasons.remove(e).unwrap_or_default(),
},
);
}
for (start, block) in blocks {
let o = owner(start);
if let Some(f) = functions.get_mut(&o) {
f.cfg.add_node(start);
f.blocks.insert(start, block);
}
}
functions.retain(|_, f| !f.blocks.is_empty());
let mut block_func: BTreeMap<u64, u64> = BTreeMap::new();
for (entry, f) in &functions {
for start in f.blocks.keys() {
block_func.insert(*start, *entry);
}
}
let mut resolved_sites: BTreeSet<u64> = BTreeSet::new();
for (site, target) in &jumps.pairs {
let mut hit: Option<(u64, u64)> = None;
for (entry, f) in &functions {
if let Some((&start, b)) = f.blocks.range(..=*site).next_back()
&& *site < b.end()
{
hit = Some((*entry, start));
break;
}
}
match (hit, block_func.get(target)) {
(Some((func, site_block)), Some(target_func)) if func == *target_func => {
if let Some(f) = functions.get_mut(&func) {
f.inferred.insert((site_block, *target));
resolved_sites.insert(*site);
}
}
_ => {}
}
}
let mut callgraph = DiGraphMap::<u64, ()>::new();
for e in functions.keys() {
callgraph.add_node(*e);
}
let keys: Vec<u64> = functions.keys().copied().collect();
let mut cfg_edges: Vec<(u64, u64, u64)> = Vec::new();
let mut cg_edges: Vec<(u64, u64)> = Vec::new();
for entry in keys {
let Some(f) = functions.get(&entry) else {
continue;
};
for (start, block) in &f.blocks {
let Some(last) = block.insns.last() else {
continue;
};
let flow = classify(arch, last);
let end = block.end();
match flow {
Flow::Branch { target: Some(t) } => {
if f.blocks.contains_key(&t) {
cfg_edges.push((entry, *start, t));
} else if decoded.contains_key(&t) {
cg_edges.push((entry, owner(t)));
}
}
Flow::Branch { target: None } => {}
Flow::CBranch { target } => {
if let Some(t) = target
&& f.blocks.contains_key(&t)
{
cfg_edges.push((entry, *start, t));
}
if f.blocks.contains_key(&end) {
cfg_edges.push((entry, *start, end));
}
}
Flow::Call { target } => {
if let Some(t) = target
&& decoded.contains_key(&t)
{
cg_edges.push((entry, owner(t)));
}
if f.blocks.contains_key(&end) {
cfg_edges.push((entry, *start, end));
}
}
Flow::Ret => {}
Flow::Seq => {
if f.blocks.contains_key(&end) {
cfg_edges.push((entry, *start, end));
}
}
}
}
}
for (func, a, b) in cfg_edges {
if let Some(f) = functions.get_mut(&func) {
f.cfg.add_edge(a, b, ());
}
}
for (a, b) in cg_edges {
if functions.contains_key(&b) {
callgraph.add_edge(a, b, ());
}
}
let mut xrefs: BTreeSet<(u64, XrefKind, u64)> = BTreeSet::new();
for (&va, d) in &decoded {
let target = match d.flow {
Flow::Branch { target } | Flow::CBranch { target } | Flow::Call { target } => target,
_ => None,
};
if let Some(t) = target {
xrefs.insert((va, XrefKind::Code, t));
}
if let Some(m) = d.insn.mem_target
&& space.contains(m)
{
xrefs.insert((va, XrefKind::Data, m));
}
}
for f in functions.values() {
for block in f.blocks.values() {
for pair in block.insns.windows(2) {
if let Some(final_addr) = resolve_adrp_pair(&pair[0], &pair[1])
&& space.contains(final_addr)
{
xrefs.insert((pair[1].addr, XrefKind::Data, final_addr));
}
}
}
}
for (site, target) in &jumps.pairs {
if resolved_sites.contains(site) {
xrefs.insert((*site, XrefKind::InferredCode, *target));
}
}
for (site, slot) in &jumps.slots {
if resolved_sites.contains(site) {
xrefs.insert((*site, XrefKind::Data, *slot));
}
}
let mut strings: Vec<StringHit> = Vec::new();
for seg in &space.all {
for mut h in strings::extract(
&seg.data,
strings::DEFAULT_MIN_LEN,
strings::DEFAULT_MAX_HITS,
Some(seg.vaddr),
) {
let (section, executable) = locate_hit(&bin.sections, seg, h.vaddr);
h.section = section;
h.executable = executable;
strings.push(h);
}
}
strings.sort_by_key(|h| h.vaddr.unwrap_or(u64::MAX));
let spans: Vec<(u64, u64)> = strings
.iter()
.filter_map(|h| {
h.vaddr.map(|v| {
let len = match h.encoding {
Encoding::Ascii => h.value.len() as u64,
Encoding::Utf16Le | Encoding::Utf16Be => h.value.len() as u64 * 2,
};
(v, v.wrapping_add(len))
})
})
.collect();
let span_index = StringSpanIndex::new(spans);
let data_tos: Vec<(u64, u64)> = xrefs
.iter()
.filter(|(_, k, _)| *k == XrefKind::Data)
.map(|(f, _, t)| (*f, *t))
.collect();
for (from, to) in data_tos {
if let Some(s) = span_index.lookup(to) {
xrefs.insert((from, XrefKind::String, s));
}
}
let xrefs: Vec<Xref> = xrefs
.into_iter()
.map(|(from, kind, to)| Xref { from, to, kind })
.collect();
let code_like = xrefs
.iter()
.filter(|x| matches!(x.kind, XrefKind::Code | XrefKind::InferredCode))
.count();
if code_like > MAX_XREFS_PER_KIND {
return Err(Error::Limit(format!(
"more than {MAX_XREFS_PER_KIND} {:?} xrefs",
XrefKind::Code
)));
}
for kind in [XrefKind::Data, XrefKind::String] {
if xrefs.iter().filter(|x| x.kind == kind).count() > MAX_XREFS_PER_KIND {
return Err(Error::Limit(format!(
"more than {MAX_XREFS_PER_KIND} {kind:?} xrefs"
)));
}
}
for site in &resolved_sites {
diagnostic_set.remove(&Diagnostic {
addr: *site,
kind: DiagnosticKind::UnresolvedIndirectJump,
});
}
let mut diagnostics = Diagnostics::collect(diagnostic_set.into_iter().collect(), false, 0);
diagnostics.inferred_truncated = jumps.truncated;
diagnostics.inferred_omitted = jumps.omitted;
Ok(Analysis {
arch,
functions,
callgraph,
xrefs,
strings,
diagnostics,
})
}
pub fn analyze_raw(bytes: &[u8], base: u64, arch: Arch, entry: Option<u64>) -> Result<Analysis> {
let bin = load_raw(bytes, RawOptions { base, arch, entry })?;
analyze(&bin)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn classify_maps_lift_ops() {
let ret = Insn {
addr: 0x1000,
size: 1,
bytes: vec![0xC3],
mnem: "ret".to_string(),
ops: Vec::new(),
branch_target: None,
mem_target: None,
table_base: None,
};
assert_eq!(classify(Arch::X86_64, &ret), Flow::Ret);
let call = Insn {
addr: 0x1000,
size: 5,
bytes: vec![0xE8, 0, 0, 0, 0],
mnem: "call".to_string(),
ops: vec!["0x1005".to_string()],
branch_target: Some(0x1005),
mem_target: None,
table_base: None,
};
assert_eq!(
classify(Arch::X86_64, &call),
Flow::Call {
target: Some(0x1005)
}
);
}
#[test]
fn pages_truncate_at_max_page() {
let items: Vec<u64> = (0..10).collect();
assert_eq!(page_slice(&items, 0, usize::MAX).len(), 10);
assert!(page_slice(&items, 0, 3) == [0, 1, 2]);
assert!(page_slice(&items, 20, 5).is_empty());
}
#[test]
fn block_id_is_stable() {
let b = BasicBlock {
start: 0x2007,
insns: Vec::new(),
};
assert_eq!(b.id(0x2000), "block@0x2000+0x2007");
}
fn oracle_seeds(arch: Arch, space: &AddrSpace, reached: &BTreeSet<u64>) -> Result<Vec<u64>> {
let mut out: Vec<u64> = Vec::new();
for seg in &space.exec {
if arch == Arch::Aarch64 {
let mut off = 0usize;
while off + 4 <= seg.data.len() {
let raw = seg.data.get(off..off + 4).expect("word in bounds");
let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
if (w & 0xFFC0_7FFF) == 0xA980_7BFD {
out.push(seg.vaddr.wrapping_add(off as u64));
}
off += 4;
}
continue;
}
if arch == Arch::Arm32 {
let mut off = 0usize;
while off + 4 <= seg.data.len() {
let raw = seg.data.get(off..off + 4).expect("word in bounds");
let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
if is_arm_push_lr(w) {
out.push(seg.vaddr.wrapping_add(off as u64));
}
off += 4;
}
continue;
}
if arch == Arch::Thumb {
let mut off = 0usize;
while off + 2 <= seg.data.len() {
let raw = seg.data.get(off..off + 2).expect("halfword in bounds");
let hw = u16::from_le_bytes(raw.try_into().expect("halfword converts"));
if (hw & 0xFF00) == 0xB500 && (hw & 0x0100) != 0 {
out.push(seg.vaddr.wrapping_add(off as u64));
} else if off + 4 <= seg.data.len() {
let raw = seg.data.get(off..off + 4).expect("word in bounds");
let w = u32::from_le_bytes(raw.try_into().expect("word converts"));
if is_arm_push_lr(w) {
out.push(seg.vaddr.wrapping_add(off as u64));
}
}
off += 2;
}
continue;
}
for pat in prologue_patterns(arch) {
for (i, win) in seg.data.windows(pat.len()).enumerate() {
if win != *pat {
continue;
}
let mut va = seg.vaddr.wrapping_add(i as u64);
if i > 0 && seg.data[i - 1] == 0x55 {
va = va.wrapping_sub(1);
}
out.push(va);
}
}
}
out.sort_unstable();
out.dedup();
let mut seeds: Vec<u64> = Vec::new();
for va in out {
if seeds.len() >= MAX_SEEDS {
break;
}
if !reached.contains(&va) && decode_one(arch, space, va)?.is_some() {
seeds.push(va);
}
}
Ok(seeds)
}
fn seed_test_binary(arch: Arch, entry: Option<u64>, segs: Vec<(u64, Vec<u8>)>) -> LoadedBinary {
LoadedBinary {
format: crate::loader::BinaryFormat::Raw,
arch,
entry,
segments: segs
.into_iter()
.map(|(vaddr, data)| Segment {
vaddr,
mem_size: data.len() as u64,
data,
readable: true,
writable: false,
executable: true,
})
.collect(),
sections: Vec::new(),
imports: Vec::new(),
exports: Vec::new(),
}
}
fn seed_words(arch: Arch) -> (&'static [u8], &'static [u8], &'static [u8]) {
match arch {
Arch::Aarch64 => (
&[0xFD, 0x7B, 0x80, 0xA9],
&[0xFD, 0x7B, 0x80, 0xA9],
&[0x1F, 0x20, 0x03, 0xD5],
),
Arch::Arm32 => (
&[0xF0, 0x40, 0x2D, 0xE9],
&[0xF0, 0x40, 0x2D, 0xF9],
&[0x1E, 0xFF, 0x2F, 0xE1],
),
Arch::Thumb => (&[0xF0, 0xB5], &[0xF0, 0xB5], &[0x00, 0xBF]),
Arch::X86_64 => (&[0x48, 0x89, 0xE5], &[0x48, 0x89, 0xE5], &[0x90]),
Arch::X86_32 => (&[0x89, 0xE5], &[0x89, 0xE5], &[0x90]),
}
}
fn tricky_segments(arch: Arch) -> Vec<(u64, Vec<u8>)> {
let (m, u, j) = seed_words(arch);
let mut hi = Vec::new();
for w in [m, j, m, u, j, m] {
hi.extend_from_slice(w);
}
hi.push(0x00);
if arch == Arch::Thumb {
hi.push(0x00);
hi.extend_from_slice(&[0xF0, 0x40, 0x2D, 0xE9]);
}
if arch == Arch::X86_64 || arch == Arch::X86_32 {
hi.push(0x55);
hi.extend_from_slice(m);
}
let mut lo = Vec::new();
lo.extend_from_slice(j);
lo.extend_from_slice(j);
lo.extend_from_slice(&hi[..0x18.min(hi.len())]);
let mut wrap = Vec::new();
while wrap.len() + m.len() + j.len() <= 16 {
wrap.extend_from_slice(m);
wrap.extend_from_slice(j);
}
wrap.truncate(16 - m.len());
wrap.extend_from_slice(m);
let mut zero = Vec::new();
for w in [m, j, m] {
zero.extend_from_slice(w);
}
vec![
(0x5000, hi),
(0x4FF0, lo),
(u64::MAX - 8, wrap),
(0x6000, Vec::new()),
(0x6100, vec![0x90]),
(0, zero),
]
}
#[test]
fn seed_streams_match_eager_oracle() {
for arch in [
Arch::Aarch64,
Arch::Arm32,
Arch::Thumb,
Arch::X86_64,
Arch::X86_32,
] {
let bin = seed_test_binary(arch, None, tricky_segments(arch));
let space = AddrSpace::new(&bin);
let reached: BTreeSet<u64> = [0x5000, 0x5001, 0x5002, 0x5003, 0x4FF0, u64::MAX, 1]
.into_iter()
.collect();
let got = prologue_seeds(arch, &space, &reached).expect("streaming seeds");
let want = oracle_seeds(arch, &space, &reached).expect("oracle seeds");
assert_eq!(got, want, "seed mismatch for {arch:?}");
assert!(
got.windows(2).all(|w| w[0] < w[1]),
"seeds must be sorted and deduped for {arch:?}"
);
}
}
#[test]
fn x86_wrap_edge_step_back_sorts_last() {
let vaddr = u64::MAX - 4;
let data = vec![
0x48, 0x89, 0xE5, 0x90, 0x55, 0x48, 0x89, 0xE5, 0x48, 0x89, 0xE5,
];
let bin = seed_test_binary(Arch::X86_64, None, vec![(vaddr, data)]);
let space = AddrSpace::new(&bin);
let reached = BTreeSet::new();
let got = prologue_seeds(Arch::X86_64, &space, &reached).expect("seeds");
assert_eq!(got, [vaddr, u64::MAX]);
let want = oracle_seeds(Arch::X86_64, &space, &reached).expect("oracle");
assert_eq!(got, want);
}
fn run_inferred_cap(
bytes: &[u8],
max_edges: usize,
) -> (Vec<(u64, u64)>, bool, usize, Vec<u64>) {
let bin = load_raw(
bytes,
RawOptions {
base: 0x1000,
arch: Arch::X86_32,
entry: Some(0x1000),
},
)
.expect("raw loads");
let space = AddrSpace::new(&bin);
let mut walk = Walker::new(Arch::X86_32, &space);
let seeds = authoritative_seeds(&space, &bin);
walk.run(seeds.clone()).expect("round one walks");
let round1: BTreeSet<u64> = walk.decoded.keys().copied().collect();
let seeds2 = prologue_seeds(Arch::X86_32, &space, &round1).expect("prologue scans");
walk.run(seeds2.clone()).expect("round two walks");
let mut entries: BTreeSet<u64> = BTreeSet::new();
for s in seeds.iter().chain(seeds2.iter()) {
if walk.decoded.contains_key(s) {
entries.insert(*s);
}
}
let targets: Vec<u64> = walk.call_targets.iter().copied().collect();
for t in targets {
if walk.decoded.contains_key(&t) {
entries.insert(t);
}
}
let entry_list: Vec<u64> = entries.into_iter().collect();
let jumps = resolve_indirect_jumps(
&mut walk,
Arch::X86_32,
BinaryFormat::Raw,
&space,
&entry_list,
max_edges,
)
.expect("resolution walks");
(jumps.pairs, jumps.truncated, jumps.omitted, entry_list)
}
#[test]
fn inferred_cap_reports_omissions_without_clipping() {
let bytes = vec![
0xE8, 0x0B, 0x00, 0x00, 0x00, 0xFF, 0x25, 0x0B, 0x10, 0x00, 0x00, 0x0F, 0x10, 0x00, 0x00, 0xC3, 0xFF, 0x25, 0x16, 0x10, 0x00, 0x00, 0x1A, 0x10, 0x00, 0x00, 0xC3, ];
assert_eq!(bytes.len(), 27);
let (pairs, truncated, omitted, entries) = run_inferred_cap(&bytes, 1);
assert_eq!(entries, [0x1000, 0x1010]);
assert_eq!(pairs, [(0x1005, 0x100F)]);
assert!(truncated);
assert_eq!(omitted, 1);
let (pairs, truncated, omitted, _) = run_inferred_cap(&bytes, MAX_INFERRED_EDGES);
assert_eq!(pairs, [(0x1005, 0x100F), (0x1010, 0x101A)]);
assert!(!truncated);
assert_eq!(omitted, 0);
}
#[test]
fn table_cap_counts_unique_edges_against_shared_budget() {
let mut bytes = vec![
0x83, 0xF8, 0x01, 0x73, 0x07, 0xFF, 0x24, 0x85, 0x12, 0x10, 0x00, 0x00, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x22, 0x10, 0x00, 0x00, 0x23, 0x10, 0x00, 0x00, ];
bytes.extend([0x90; 8]); bytes.extend([0xC3, 0xC3]); assert_eq!(bytes.len(), 36);
let (pairs, truncated, omitted, entries) = run_inferred_cap(&bytes, 1);
assert_eq!(entries, [0x1000]);
assert!(pairs.is_empty());
assert!(truncated);
assert_eq!(omitted, 2);
let (pairs, truncated, omitted, _) = run_inferred_cap(&bytes, MAX_INFERRED_EDGES);
assert_eq!(pairs, [(0x1005, 0x1022), (0x1005, 0x1023)]);
assert!(!truncated);
assert_eq!(omitted, 0);
}
#[test]
fn seed_budget_truncates_accepted_prefix() {
for arch in [
Arch::Aarch64,
Arch::Arm32,
Arch::Thumb,
Arch::X86_64,
Arch::X86_32,
] {
let (m, _, _) = seed_words(arch);
let base: u64 = 0x1_0000;
let period = m.len() as u64;
let raw: usize = 120_000;
let mut data = Vec::with_capacity(raw * m.len());
for _ in 0..raw {
data.extend_from_slice(m);
}
let bin = seed_test_binary(arch, None, vec![(base, data)]);
let space = AddrSpace::new(&bin);
let reached: BTreeSet<u64> = (0..12_000).map(|i| base + i * period).collect();
let got = prologue_seeds(arch, &space, &reached).expect("streaming seeds");
let want = oracle_seeds(arch, &space, &reached).expect("oracle seeds");
assert_eq!(got.len(), MAX_SEEDS, "budget must fill for {arch:?}");
assert_eq!(got, want, "truncated prefix mismatch for {arch:?}");
assert_eq!(got[0], base + 12_000 * period);
assert!(got.windows(2).all(|w| w[0] < w[1]));
}
}
}