Skip to main content

foundry_evm_traces/backtrace/
source_map.rs

1//! Source map decoding and PC mapping utilities.
2
3use alloy_primitives::Bytes;
4use foundry_compilers::{
5    ProjectCompileOutput, artifacts::sourcemap::SourceMap, buildinfo::SourceEdit,
6};
7use foundry_evm_core::ic::IcPcMap;
8use std::{
9    path::{Path, PathBuf},
10    sync::OnceLock,
11};
12
13/// Source path, content on disk, and preprocessor edits of a build source.
14pub type BuildSource = (PathBuf, String, Vec<SourceEdit>);
15
16/// Source data for a single contract.
17#[derive(Debug, Clone)]
18pub struct SourceData {
19    /// Runtime source map for the contract
20    pub source_map: SourceMap,
21    /// Deployed bytecode for accurate PC mapping
22    pub bytecode: Bytes,
23}
24
25/// Maps program counters to source locations.
26pub struct PcSourceMapper<'a> {
27    /// Mapping from instruction counter to program counter.
28    ic_pc_map: IcPcMap,
29    /// Source data consists of the source_map and the deployed bytecode
30    source_data: SourceData,
31    /// Source files i.e source path, content, and preprocessor edits (indexed by source_id).
32    sources: &'a [BuildSource],
33    /// Line offset mappings for each source file, computed on first use.
34    line_offsets: Vec<OnceLock<Vec<usize>>>,
35}
36
37impl<'a> PcSourceMapper<'a> {
38    /// Creates a new PC to source mapper.
39    pub fn new(source_data: SourceData, sources: &'a [BuildSource]) -> Self {
40        // Build instruction counter to program counter mapping
41        let ic_pc_map = IcPcMap::new(source_data.bytecode.as_ref());
42
43        let line_offsets = sources.iter().map(|_| OnceLock::new()).collect();
44
45        Self { ic_pc_map, source_data, sources, line_offsets }
46    }
47
48    /// Maps a program counter to source location.
49    pub fn map_pc(&self, pc: usize) -> Option<SourceLocation> {
50        // Find the instruction counter for this PC
51        let ic = self.find_instruction_counter(pc)?;
52
53        // Get the source element for this instruction
54        let element = self.source_data.source_map.get(ic)?;
55
56        // Get the source file index - returns None if index is -1
57        let source_idx_opt = element.index();
58
59        let source_idx = source_idx_opt? as usize;
60        if source_idx >= self.sources.len() {
61            return None;
62        }
63
64        // Get the source file info
65        let (file_path, content, edits) = &self.sources[source_idx];
66
67        // Convert byte offset to line and column. Offsets refer to the compiled source, which
68        // differs from the file on disk when it was preprocessed.
69        let offset = SourceEdit::original_offset(edits, element.offset() as usize);
70
71        // Check if offset is valid for this source file
72        if offset >= content.len() {
73            return None;
74        }
75
76        let line_offsets =
77            self.line_offsets.get(source_idx)?.get_or_init(|| compute_line_offsets(content));
78        let (line, column) = offset_to_line_column(line_offsets, offset);
79
80        trace!(
81            file = ?file_path,
82            line = line,
83            column = column,
84            offset = offset,
85            "Mapped PC to source location"
86        );
87
88        Some(SourceLocation { file: file_path.clone(), line, column, offset })
89    }
90
91    /// Finds the instruction counter for a given program counter.
92    fn find_instruction_counter(&self, pc: usize) -> Option<usize> {
93        // The IcPcMap maps IC -> PC, we need the reverse
94        // We find the highest IC that has a PC <= our target PC
95        let mut best_ic = None;
96        let mut best_pc = 0;
97
98        for (ic, mapped_pc) in self.ic_pc_map.iter() {
99            let mapped_pc = *mapped_pc as usize;
100            if mapped_pc <= pc && mapped_pc >= best_pc {
101                best_pc = mapped_pc;
102                best_ic = Some(*ic as usize);
103            }
104        }
105
106        best_ic
107    }
108}
109/// Represents a location in source code.
110#[derive(Debug, Clone)]
111pub struct SourceLocation {
112    pub file: PathBuf,
113    pub line: usize,
114    pub column: usize,
115    /// Byte offset in the source file
116    /// This specifically useful when one source file contains multiple contracts / libraries.
117    pub offset: usize,
118}
119
120/// Computes the byte offset where each line starts in source content.
121fn compute_line_offsets(content: &str) -> Vec<usize> {
122    let mut offsets = vec![0];
123    offsets.extend(memchr::memchr_iter(b'\n', content.as_bytes()).map(|offset| offset + 1));
124    offsets
125}
126
127/// Converts a byte offset to 1-indexed line and column numbers.
128fn offset_to_line_column(line_offsets: &[usize], offset: usize) -> (usize, usize) {
129    let line = line_offsets.partition_point(|&line_start| line_start <= offset) - 1;
130    let column = offset - line_offsets[line];
131    (line + 1, column + 1)
132}
133
134/// Loads sources for a specific ArtifactId.build_id
135pub fn load_build_sources(
136    build_id: &str,
137    output: &ProjectCompileOutput,
138    root: &Path,
139) -> Option<Vec<BuildSource>> {
140    let build_ctx = output.builds().find(|(bid, _)| *bid == build_id).map(|(_, ctx)| ctx)?;
141
142    // Determine the size needed for sources vector
143    // Highest source_id
144    let max_source_id = build_ctx.source_id_to_path.keys().max().map_or(0, |id| *id) as usize;
145
146    // Vec of source path, content, and preprocessor edits.
147    let mut sources = vec![(PathBuf::new(), String::new(), Vec::new()); max_source_id + 1];
148
149    // Populate sources at their correct indices
150    for (source_id, source_path) in &build_ctx.source_id_to_path {
151        let idx = *source_id as usize;
152
153        let full_path =
154            if source_path.is_absolute() { source_path.clone() } else { root.join(source_path) };
155        let mut source_content = foundry_common::fs::read_to_string(&full_path).unwrap_or_default();
156
157        // Normalize line endings for windows
158        if source_content.contains('\r') {
159            source_content = source_content.replace("\r\n", "\n");
160        }
161
162        // Convert path to relative PathBuf
163        let path_buf = source_path.strip_prefix(root).unwrap_or(source_path).to_path_buf();
164
165        let edits = build_ctx.source_edits.get(source_id).cloned().unwrap_or_default();
166
167        sources[idx] = (path_buf, source_content, edits);
168    }
169
170    Some(sources)
171}
172
173#[cfg(test)]
174mod tests {
175    use super::{compute_line_offsets, offset_to_line_column};
176
177    fn line_column(content: &str, offset: usize) -> (usize, usize) {
178        offset_to_line_column(&compute_line_offsets(content), offset)
179    }
180
181    #[test]
182    fn maps_byte_offsets_to_line_and_column() {
183        assert_eq!(line_column("abc", 0), (1, 1));
184        assert_eq!(line_column("abc", 2), (1, 3));
185
186        assert_eq!(line_column("abc\ndef", 3), (1, 4));
187        assert_eq!(line_column("abc\ndef", 4), (2, 1));
188        assert_eq!(line_column("abc\ndef", 6), (2, 3));
189
190        assert_eq!(line_column("a\nbc\ndef", 0), (1, 1));
191        assert_eq!(line_column("a\nbc\ndef", 1), (1, 2));
192        assert_eq!(line_column("a\nbc\ndef", 2), (2, 1));
193        assert_eq!(line_column("a\nbc\ndef", 4), (2, 3));
194        assert_eq!(line_column("a\nbc\ndef", 5), (3, 1));
195        assert_eq!(line_column("a\nbc\ndef", 7), (3, 3));
196    }
197}