foundry_evm_traces/backtrace/
source_map.rs1use 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
13pub type BuildSource = (PathBuf, String, Vec<SourceEdit>);
15
16#[derive(Debug, Clone)]
18pub struct SourceData {
19 pub source_map: SourceMap,
21 pub bytecode: Bytes,
23}
24
25pub struct PcSourceMapper<'a> {
27 ic_pc_map: IcPcMap,
29 source_data: SourceData,
31 sources: &'a [BuildSource],
33 line_offsets: Vec<OnceLock<Vec<usize>>>,
35}
36
37impl<'a> PcSourceMapper<'a> {
38 pub fn new(source_data: SourceData, sources: &'a [BuildSource]) -> Self {
40 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 pub fn map_pc(&self, pc: usize) -> Option<SourceLocation> {
50 let ic = self.find_instruction_counter(pc)?;
52
53 let element = self.source_data.source_map.get(ic)?;
55
56 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 let (file_path, content, edits) = &self.sources[source_idx];
66
67 let offset = SourceEdit::original_offset(edits, element.offset() as usize);
70
71 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 fn find_instruction_counter(&self, pc: usize) -> Option<usize> {
93 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#[derive(Debug, Clone)]
111pub struct SourceLocation {
112 pub file: PathBuf,
113 pub line: usize,
114 pub column: usize,
115 pub offset: usize,
118}
119
120fn 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
127fn 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
134pub 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 let max_source_id = build_ctx.source_id_to_path.keys().max().map_or(0, |id| *id) as usize;
145
146 let mut sources = vec![(PathBuf::new(), String::new(), Vec::new()); max_source_id + 1];
148
149 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 if source_content.contains('\r') {
159 source_content = source_content.replace("\r\n", "\n");
160 }
161
162 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}