Skip to main content

foundry_evm_traces/backtrace/
mod.rs

1//! Solidity stack trace support for test failures.
2
3use 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/// Linked library information for backtrace resolution.
17///
18/// Contains the path, name, and deployed address of a linked library
19/// to enable proper frame resolution in backtraces.
20#[derive(Debug, Clone)]
21struct LinkedLib {
22    /// The source file path of the library
23    path: PathBuf,
24    /// The name of the library contract
25    name: String,
26    /// The deployed address of the library
27    address: Address,
28}
29
30/// Holds a reference to [`ProjectCompileOutput`] to fetch artifacts and sources for backtrace
31/// generation.
32pub struct BacktraceBuilder<'a> {
33    /// Linked libraries from configuration
34    linked_libraries: Vec<LinkedLib>,
35    /// Reference to project output for on-demand source loading
36    output: &'a ProjectCompileOutput,
37    /// Project root
38    root: PathBuf,
39    /// Disable source locations
40    ///
41    /// Source locations will be inaccurately reported if the files have been compiled with via-ir
42    disable_source_locs: bool,
43    /// Sources grouped by [`ArtifactId::build_id`] to avoid re-reading files for artifacts from
44    /// the same build
45    ///
46    /// The source [`Vec`] is indexed by the compiler source ID, and contains the source path,
47    /// source content, and preprocessor edits.
48    build_sources_cache: HashMap<String, Vec<BuildSource>>,
49}
50
51impl<'a> BacktraceBuilder<'a> {
52    /// Instantiates a backtrace builder from a [`ProjectCompileOutput`].
53    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    /// Generates a backtrace from a [`SparsedTraceArena`].
87    pub fn from_traces(&mut self, arena: &SparsedTraceArena) -> Backtrace<'_> {
88        // Resolve addresses to artifacts using trace labels and linked libraries
89        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    /// Resolves contract addresses to [`ArtifactId`] and their [`SourceData`] from trace labels and
109    /// linked libraries.
110    fn resolve_addresses(
111        &self,
112        arena: &SparsedTraceArena,
113    ) -> HashMap<Address, (ArtifactId, SourceData)> {
114        let mut artifacts_by_address = HashMap::default();
115
116        // Collect all labels from traces first
117        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        // Build linked library target IDs
131        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            // Match and insert artifacts using trace labels
150            if let Some(address) = label_to_address.get(artifact_id.name.as_str())
151                && let Some((source_map, bytecode)) = get_source(artifact)
152            {
153                // Match and insert artifacts using trace labels
154                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                    // Match and insert the linked library artifacts
159                    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                // Insert linked libraries
169                artifacts_by_address
170                    .insert(lib_address, (artifact_id, SourceData { source_map, bytecode }));
171            }
172        }
173
174        artifacts_by_address
175    }
176}
177
178/// A Solidity stack trace for a test failure.
179///
180/// Generates a backtrace from a [`SparsedTraceArena`] by leveraging source maps and bytecode.
181///
182/// It uses the program counter (PC) from the traces to map to a specific source location for the
183/// call.
184///
185/// Each step/call in the backtrace is classified as a BacktraceFrame
186#[non_exhaustive]
187pub struct Backtrace<'a> {
188    /// The frames of the backtrace, from innermost (where the revert happened) to outermost.
189    frames: Vec<BacktraceFrame>,
190    /// Map from address to PcSourceMapper
191    pc_mappers: HashMap<Address, PcSourceMapper<'a>>,
192    /// Linked libraries from configuration
193    linked_libraries: Vec<LinkedLib>,
194    /// Disable pinpointing source locations in files
195    ///
196    /// Should be disabled when via-ir is enabled
197    disable_source_locs: bool,
198}
199
200impl<'a> Backtrace<'a> {
201    /// Creates a backtrace from collected artifacts and sources.
202    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        // Build PC source mappers for each contract
212        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    /// Extracts backtrace frames from a trace arena.
230    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        // Find the deepest failed node (where the actual revert happened)
238        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        // Build the call stack by walking from the deepest node back to root
253        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    /// Creates a frame from a call trace.
266    fn create_frame(&self, trace: &CallTrace) -> Option<BacktraceFrame> {
267        let contract_address = trace.address;
268        let mut frame = BacktraceFrame::new(contract_address);
269
270        // Try to get source location from PC mapper
271        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    /// Returns true if the backtrace is empty.
306    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/// A single frame in a backtrace.
330#[derive(Debug, Clone)]
331struct BacktraceFrame {
332    /// The contract address where this frame is executing.
333    pub contract_address: Address,
334    /// The contract name, if known.
335    pub contract_name: Option<String>,
336    /// The function name, if known.
337    pub function_name: Option<String>,
338    /// The source file path.
339    pub file: Option<PathBuf>,
340    /// The line number in the source file.
341    pub line: Option<usize>,
342    /// The column number in the source file.
343    pub column: Option<usize>,
344    /// The byte offset in the source file.
345    pub byte_offset: Option<usize>,
346}
347
348impl BacktraceFrame {
349    /// Creates a new backtrace frame.
350    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    /// Sets the contract name.
363    fn with_contract_name(mut self, name: String) -> Self {
364        self.contract_name = Some(name);
365        self
366    }
367
368    /// Sets the function name.
369    fn with_function_name(mut self, name: String) -> Self {
370        self.function_name = Some(name);
371        self
372    }
373
374    /// Sets the source location.
375    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    /// Sets the byte offset.
383    const fn with_byte_offset(mut self, offset: usize) -> Self {
384        self.byte_offset = Some(offset);
385        self
386    }
387}
388
389// Format: <CONTRACT_NAME>.<FUNCTION_NAME> (FILE:LINE:COL)
390impl fmt::Display for BacktraceFrame {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        let mut result = String::new();
393
394        // No contract name, show address
395        result.push_str(self.contract_name.as_ref().unwrap_or(&self.contract_address.to_string()));
396
397        // Add function name if available
398        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        // Add location in parentheses if available
414        if self.file.is_some() || self.line.is_some() {
415            result.push(')');
416        }
417
418        write!(f, "{result}")
419    }
420}