foundry_evm_traces/backtrace/
mod.rs1use crate::{CallTrace, SparsedTraceArena};
4use alloy_primitives::{Address, Bytes, map::HashMap};
5use foundry_compilers::{
6 Artifact, ArtifactId, ProjectCompileOutput,
7 artifacts::{ConfigurableContractArtifact, Libraries, sourcemap::SourceMap},
8};
9use std::{fmt, path::PathBuf};
10use yansi::Paint;
11
12mod source_map;
13use source_map::{BuildSource, load_build_sources};
14pub use source_map::{PcSourceMapper, SourceData};
15
16#[derive(Debug, Clone)]
21struct LinkedLib {
22 path: PathBuf,
24 name: String,
26 address: Address,
28}
29
30pub struct BacktraceBuilder<'a> {
33 linked_libraries: Vec<LinkedLib>,
35 output: &'a ProjectCompileOutput,
37 root: PathBuf,
39 disable_source_locs: bool,
43 build_sources_cache: HashMap<String, Vec<BuildSource>>,
49}
50
51impl<'a> BacktraceBuilder<'a> {
52 pub fn new(
54 output: &'a ProjectCompileOutput,
55 root: PathBuf,
56 linked_libraries: Option<Libraries>,
57 disable_source_locs: bool,
58 ) -> Self {
59 let linked_libs = linked_libraries
60 .map(|libs| {
61 libs.libs
62 .iter()
63 .flat_map(|(path, libs_map)| {
64 libs_map.iter().map(move |(name, addr_str)| (path, name, addr_str))
65 })
66 .filter_map(|(path, name, addr_str)| {
67 addr_str.parse().ok().map(|address| LinkedLib {
68 path: path.clone(),
69 name: name.clone(),
70 address,
71 })
72 })
73 .collect()
74 })
75 .unwrap_or_default();
76
77 Self {
78 linked_libraries: linked_libs,
79 output,
80 root,
81 disable_source_locs,
82 build_sources_cache: HashMap::default(),
83 }
84 }
85
86 pub fn from_traces(&mut self, arena: &SparsedTraceArena) -> Backtrace<'_> {
88 let artifacts_by_address = self.resolve_addresses(arena);
90 for (artifact_id, _) in artifacts_by_address.values() {
91 let build_id = &artifact_id.build_id;
92 if !self.build_sources_cache.contains_key(build_id)
93 && let Some(sources) = load_build_sources(build_id, self.output, &self.root)
94 {
95 self.build_sources_cache.insert(build_id.clone(), sources);
96 }
97 }
98
99 Backtrace::new(
100 artifacts_by_address,
101 &self.build_sources_cache,
102 self.linked_libraries.clone(),
103 self.disable_source_locs,
104 arena,
105 )
106 }
107
108 fn resolve_addresses(
111 &self,
112 arena: &SparsedTraceArena,
113 ) -> HashMap<Address, (ArtifactId, SourceData)> {
114 let mut artifacts_by_address = HashMap::default();
115
116 let label_to_address = arena
118 .nodes()
119 .iter()
120 .filter_map(|node| {
121 if let Some(decoded) = &node.trace.decoded
122 && let Some(label) = &decoded.label
123 {
124 return Some((label.as_str(), node.trace.address));
125 }
126 None
127 })
128 .collect::<HashMap<_, _>>();
129
130 let linked_lib_targets = self
132 .linked_libraries
133 .iter()
134 .map(|lib| (format!("{}:{}", lib.path.display(), lib.name), lib.address))
135 .collect::<HashMap<_, _>>();
136
137 let get_source = |artifact: &ConfigurableContractArtifact| -> Option<(SourceMap, Bytes)> {
138 let source_map = artifact.get_source_map_deployed()?.ok()?;
139 let deployed_bytecode = artifact.get_deployed_bytecode_bytes()?.into_owned();
140
141 if deployed_bytecode.is_empty() {
142 return None;
143 }
144
145 Some((source_map, deployed_bytecode))
146 };
147
148 for (artifact_id, artifact) in self.output.artifact_ids() {
149 if let Some(address) = label_to_address.get(artifact_id.name.as_str())
151 && let Some((source_map, bytecode)) = get_source(artifact)
152 {
153 artifacts_by_address
155 .insert(*address, (artifact_id.clone(), SourceData { source_map, bytecode }));
156 } else if !linked_lib_targets.is_empty()
157 && let Some(&lib_address) =
158 linked_lib_targets.get(&artifact_id.identifier()).or_else(|| {
160 let id = artifact_id
161 .clone()
162 .with_stripped_file_prefixes(&self.root)
163 .identifier();
164 linked_lib_targets.get(&id)
165 })
166 && let Some((source_map, bytecode)) = get_source(artifact)
167 {
168 artifacts_by_address
170 .insert(lib_address, (artifact_id, SourceData { source_map, bytecode }));
171 }
172 }
173
174 artifacts_by_address
175 }
176}
177
178#[non_exhaustive]
187pub struct Backtrace<'a> {
188 frames: Vec<BacktraceFrame>,
190 pc_mappers: HashMap<Address, PcSourceMapper<'a>>,
192 linked_libraries: Vec<LinkedLib>,
194 disable_source_locs: bool,
198}
199
200impl<'a> Backtrace<'a> {
201 fn new(
203 artifacts_by_address: HashMap<Address, (ArtifactId, SourceData)>,
204 build_sources: &'a HashMap<String, Vec<BuildSource>>,
205 linked_libraries: Vec<LinkedLib>,
206 disable_source_locs: bool,
207 arena: &SparsedTraceArena,
208 ) -> Self {
209 let mut pc_mappers = HashMap::default();
210
211 if !disable_source_locs {
213 for (addr, (artifact_id, source_data)) in artifacts_by_address {
214 if let Some(sources) = build_sources.get(&artifact_id.build_id) {
215 let mapper = PcSourceMapper::new(source_data, sources);
216 pc_mappers.insert(addr, mapper);
217 }
218 }
219 }
220
221 let mut backtrace =
222 Self { frames: Vec::new(), pc_mappers, linked_libraries, disable_source_locs };
223
224 backtrace.extract_frames(arena);
225
226 backtrace
227 }
228
229 fn extract_frames(&mut self, arena: &SparsedTraceArena) {
231 let resolved_arena = &arena.arena;
232
233 if resolved_arena.nodes().is_empty() {
234 return;
235 }
236
237 let mut current_idx = None;
239 let mut max_depth = 0;
240
241 for (idx, node) in resolved_arena.nodes().iter().enumerate() {
242 if !node.trace.success && node.trace.depth >= max_depth {
243 max_depth = node.trace.depth;
244 current_idx = Some(idx);
245 }
246 }
247
248 if current_idx.is_none() {
249 return;
250 }
251
252 while let Some(idx) = current_idx {
254 let node = &resolved_arena.nodes()[idx];
255 let trace = &node.trace;
256
257 if let Some(frame) = self.create_frame(trace) {
258 self.frames.push(frame);
259 }
260
261 current_idx = node.parent;
262 }
263 }
264
265 fn create_frame(&self, trace: &CallTrace) -> Option<BacktraceFrame> {
267 let contract_address = trace.address;
268 let mut frame = BacktraceFrame::new(contract_address);
269
270 if !self.disable_source_locs
272 && let Some(source_location) = trace.steps.last().and_then(|last_step| {
273 self.pc_mappers.get(&contract_address).and_then(|m| m.map_pc(last_step.pc))
274 })
275 {
276 frame = frame
277 .with_source_location(
278 source_location.file,
279 source_location.line,
280 source_location.column,
281 )
282 .with_byte_offset(source_location.offset);
283 }
284
285 if let Some(decoded) = &trace.decoded {
286 if let Some(label) = &decoded.label {
287 frame = frame.with_contract_name(label.clone());
288 } else if let Some(lib) =
289 self.linked_libraries.iter().find(|l| l.address == contract_address)
290 {
291 frame = frame.with_contract_name(lib.name.clone());
292 }
293
294 if let Some(call_data) = &decoded.call_data {
295 let sig = &call_data.signature;
296 let func_name =
297 if let Some(paren_pos) = sig.find('(') { &sig[..paren_pos] } else { sig };
298 frame = frame.with_function_name(func_name.to_string());
299 }
300 }
301
302 Some(frame)
303 }
304
305 pub const fn is_empty(&self) -> bool {
307 self.frames.is_empty()
308 }
309}
310
311impl fmt::Display for Backtrace<'_> {
312 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
313 if self.frames.is_empty() {
314 return Ok(());
315 }
316
317 writeln!(f, "{}", Paint::yellow("Backtrace:"))?;
318
319 for frame in &self.frames {
320 write!(f, " ")?;
321 write!(f, "at ")?;
322 writeln!(f, "{frame}")?;
323 }
324
325 Ok(())
326 }
327}
328
329#[derive(Debug, Clone)]
331struct BacktraceFrame {
332 pub contract_address: Address,
334 pub contract_name: Option<String>,
336 pub function_name: Option<String>,
338 pub file: Option<PathBuf>,
340 pub line: Option<usize>,
342 pub column: Option<usize>,
344 pub byte_offset: Option<usize>,
346}
347
348impl BacktraceFrame {
349 const fn new(contract_address: Address) -> Self {
351 Self {
352 contract_address,
353 contract_name: None,
354 function_name: None,
355 file: None,
356 line: None,
357 column: None,
358 byte_offset: None,
359 }
360 }
361
362 fn with_contract_name(mut self, name: String) -> Self {
364 self.contract_name = Some(name);
365 self
366 }
367
368 fn with_function_name(mut self, name: String) -> Self {
370 self.function_name = Some(name);
371 self
372 }
373
374 fn with_source_location(mut self, file: PathBuf, line: usize, column: usize) -> Self {
376 self.file = Some(file);
377 self.line = Some(line);
378 self.column = Some(column);
379 self
380 }
381
382 const fn with_byte_offset(mut self, offset: usize) -> Self {
384 self.byte_offset = Some(offset);
385 self
386 }
387}
388
389impl fmt::Display for BacktraceFrame {
391 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392 let mut result = String::new();
393
394 result.push_str(self.contract_name.as_ref().unwrap_or(&self.contract_address.to_string()));
396
397 result.push_str(&self.function_name.as_ref().map_or(String::new(), |f| format!(".{f}")));
399
400 if let Some(file) = &self.file {
401 result.push_str(" (");
402 result.push_str(&file.display().to_string());
403 }
404
405 if let Some(line) = self.line {
406 result.push(':');
407 result.push_str(&line.to_string());
408
409 result.push(':');
410 result.push_str(&self.column.as_ref().map_or("0".to_string(), |c| c.to_string()));
411 }
412
413 if self.file.is_some() || self.line.is_some() {
415 result.push(')');
416 }
417
418 write!(f, "{result}")
419 }
420}