1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
use crate::{Disassembler, FunctionAnalysisState, Result, error::Error};
use std::collections::{HashMap, HashSet};
#[derive(Debug)]
pub struct TailCall {
destination_addr: u64,
destination_function: u64,
}
#[derive(Debug)]
pub struct TailCallAnalyser {
jumps: HashMap<u64, Vec<u64>>,
tmp_jumps: HashMap<u64, Vec<u64>>,
functions: HashMap<u64, FunctionAnalysisState>,
}
impl TailCallAnalyser {
pub fn new() -> TailCallAnalyser {
TailCallAnalyser {
jumps: HashMap::new(),
tmp_jumps: HashMap::new(),
functions: HashMap::new(),
}
}
pub fn init(&mut self) -> Result<()> {
self.tmp_jumps = HashMap::new();
Ok(())
}
pub fn add_jump(&mut self, source: u64, destination: u64) -> Result<()> {
if let Some(s) = self.tmp_jumps.get_mut(&source) {
s.push(destination);
} else {
self.tmp_jumps.insert(source, vec![destination]);
}
Ok(())
}
pub fn finalize_function(
disassembler: &mut Disassembler,
function_state: &FunctionAnalysisState,
) -> Result<()> {
for (source, destinations) in &disassembler.tailcall_analyzer.tmp_jumps {
disassembler
.tailcall_analyzer
.jumps
.insert(*source, destinations.to_vec());
for d in destinations {
_ = disassembler.fc_manager.add_reference_candidate(
*d,
*source,
&disassembler.disassembly,
);
}
}
disassembler.tailcall_analyzer.tmp_jumps.clear();
// Stash the just-finalized function in our intervals table so
// `get_tailcalls` can later spot jumps from outside-the-function
// into this function's body. Pre-0.4.1 this insert was missing
// (TODO in the source), which silently turned `resolve_tailcalls`
// into a no-op for the entire 0.3.x / 0.4.0 lifetime.
disassembler
.tailcall_analyzer
.functions
.insert(function_state.start_addr, function_state.clone());
Ok(())
}
pub fn resolve_tailcalls(
disassembler: &mut Disassembler,
state: &mut FunctionAnalysisState,
high_accuracy: bool,
) -> Result<HashSet<u64>> {
// (0.6.3) Helper — `analyse_function` returns
// `Err(Error::CollisionError(_))` when the requested start
// address is already part of an existing function. For the
// tail-call resolver this is EXPECTED: the whole point of
// tail-call discovery is re-visiting addresses reached from
// multiple call sites, so most candidates are already known.
// The main candidate loop in `analyse_buffer` (lib.rs:1510,
// 1517, 1525) swallows the same Result via `.ok()`; pre-0.6.3
// the four `analyse_function(…)?` sites below propagated
// CollisionError fatally, aborting the WHOLE resolve_tailcalls
// pass — and via `?` in `analyse_buffer:1537` aborting the
// whole `Disassembler::parse` call. On Apple-Silicon /bin/ls
// this manifested as a 95 ms parse-error return from any
// consumer that set `resolve_tailcalls=true` (e.g. capa-rs).
// Other error variants (LogicError, NotEnoughBytesError, …)
// still propagate — only CollisionError is benign here.
fn try_analyse(d: &mut Disassembler, addr: u64, high_accuracy: bool) -> Result<()> {
match d.analyse_function(addr, false, high_accuracy) {
Ok(_) | Err(Error::CollisionError(_)) => Ok(()),
Err(e) => Err(e),
}
}
let mut newly_created_functions = HashSet::new();
for tailcall in disassembler.tailcall_analyzer.get_tailcalls()? {
//# remove the information from the function-analysis state of the disassembly
match disassembler
.tailcall_analyzer
.get_function_by_start_addr(tailcall.destination_function)
{
Ok(f) => {
if disassembler.tailcall_analyzer.functions[&f].is_tailcall_function {
try_analyse(disassembler, tailcall.destination_function, high_accuracy)?;
continue;
}
disassembler
.tailcall_analyzer
.functions
.remove(&f)
.ok_or(Error::LogicError(file!(), line!()))?;
state.revert_analysis()?;
}
_ => {
try_analyse(disassembler, tailcall.destination_function, high_accuracy)?;
continue;
}
}
//# analyze the tailcall destination as function
try_analyse(disassembler, tailcall.destination_addr, high_accuracy)?;
newly_created_functions.insert(tailcall.destination_addr);
if let Ok(addr) = disassembler
.tailcall_analyzer
.get_function_by_start_addr(tailcall.destination_addr)
&& disassembler.tailcall_analyzer.functions[&addr]
.instruction_start_bytes
.contains(&tailcall.destination_function)
{
//# analyze the (previously) broken function a second time
try_analyse(disassembler, tailcall.destination_function, high_accuracy)?;
let addr_function = disassembler
.tailcall_analyzer
.get_function_by_start_addr(tailcall.destination_function)?;
disassembler
.tailcall_analyzer
.functions
.get_mut(&addr_function)
.ok_or(Error::LogicError(file!(), line!()))?
.is_tailcall_function = true;
}
}
Ok(newly_created_functions)
}
pub fn get_tailcalls(&self) -> Result<Vec<TailCall>> {
let mut result = vec![];
//# jumps sorted by (destination, source)
let mut jumps = HashSet::new();
let mut jumps_dest = HashSet::new();
for (s, ds) in &self.jumps {
for d in ds {
jumps.insert((*s, *d));
jumps_dest.insert(*d);
}
}
//# for each function generate the intervals that contain the instructions
for function in self.functions.values() {
//# check if there are any jumps from outside the function to inside the function
let function_intervals = self.get_function_intervals(function);
if function_intervals.is_err() {
//# empty function?
continue;
}
let function_intervals = function_intervals.as_ref().unwrap();
let mut min_addr = 0xFFFFFFFFFFFFFFFF;
let mut max_addr = 0;
for interval in function_intervals {
if min_addr > interval.0 {
min_addr = interval.0;
}
if max_addr < interval.1 {
max_addr = interval.1;
}
}
for (source, destination) in &jumps {
// //}[bisect.bisect_left(jumps_dest,
// min_addr):bisect.bisect_right(jumps_dest,
// max_addr)]:
let mut flag1 = false;
let mut flag2 = true;
for (first, last) in function_intervals {
if first <= destination && destination <= last {
flag1 |= true;
}
if !(source < first || source > last) {
flag2 &= false;
}
}
if
//the jumps destination is different from the functions start address
destination != &function.start_addr &&
//the jumps destination is in one of the functions intervals
flag1 &&
//# the jump originates from outside the function (outside all intervals)
flag2
{
result.push(TailCall {
destination_addr: *destination,
destination_function: function.start_addr,
});
}
}
}
Ok(result)
}
fn get_function_by_start_addr(&self, start_addr: u64) -> Result<u64> {
for function in self.functions.values() {
if function.start_addr == start_addr {
return Ok(function.start_addr);
}
}
Err(Error::LogicError(file!(), line!()))
}
fn get_function_intervals(
&self,
function_state: &FunctionAnalysisState,
) -> Result<Vec<(u64, u64)>> {
let mut intervals = vec![];
let instructions = &function_state.instructions;
if instructions.is_empty() {
return Err(Error::LogicError(file!(), line!()));
}
let mut first_instruction = &instructions[0];
let mut last_instruction = first_instruction;
for instruction in instructions {
if instruction.offset() > last_instruction.offset() + last_instruction.length() as u64 {
intervals.push((first_instruction.offset(), last_instruction.offset()));
first_instruction = instruction;
}
last_instruction = instruction;
}
intervals.push((first_instruction.offset(), last_instruction.offset()));
Ok(intervals)
}
}