Skip to main content

foundry_evm_traces/debug/
mod.rs

1mod recording;
2mod sources;
3
4use crate::{CallTraceNode, CallTraceStep, DecodedInternalCall, DecodedTraceStep};
5use alloy_dyn_abi::{
6    DynSolType, DynSolValue, Specifier,
7    parser::{Parameters, Storage},
8};
9use alloy_primitives::U256;
10use evm2::interpreter::opcode::OpCode;
11use foundry_common::fmt::format_token;
12use foundry_compilers::artifacts::sourcemap::{Jump, SourceElement};
13pub use recording::{
14    DebugRecording, DebugStepSink, RecordedFrame, StepConverter, StepStorage, quantity, step_record,
15};
16pub use sources::{ArtifactData, ContractSources, SourceData};
17
18#[derive(Clone, Debug)]
19pub struct DebugTraceIdentifier {
20    /// Source map of contract sources
21    contracts_sources: ContractSources,
22}
23
24impl DebugTraceIdentifier {
25    pub const fn new(contracts_sources: ContractSources) -> Self {
26        Self { contracts_sources }
27    }
28
29    /// Identifies internal function invocations in a given [CallTraceNode].
30    ///
31    /// Accepts the node itself and identified name of the contract which node corresponds to.
32    pub fn identify_node_steps(&self, node: &mut CallTraceNode, contract_name: &str) {
33        Self::identify_node_steps_with_sources(node, &self.contracts_sources, contract_name);
34    }
35
36    /// Identifies internal function invocations without taking ownership of source metadata.
37    pub fn identify_node_steps_with_sources(
38        node: &mut CallTraceNode,
39        sources: &ContractSources,
40        contract_name: &str,
41    ) {
42        DebugStepsWalker::new(node, sources, contract_name).walk();
43    }
44}
45
46/// Walks through the [CallTraceStep]s attempting to match JUMPs to internal functions.
47///
48/// This is done by looking up jump kinds in the source maps. The structure of internal function
49/// call always looks like this:
50///     - JUMP
51///     - JUMPDEST
52///     ... function steps ...
53///     - JUMP
54///     - JUMPDEST
55///
56/// The assumption we rely on is that first JUMP into function will be marked as [Jump::In] in
57/// source map, and second JUMP out of the function will be marked as [Jump::Out].
58///
59/// Also, we rely on JUMPDEST after first JUMP pointing to the source location of the body of
60/// function which was entered. We pass this source part to [parse_function_from_loc] to extract the
61/// function name.
62///
63/// When we find a [Jump::In] and identify the function name, we push it to the stack.
64///
65/// When we find a [Jump::Out] we try to find a matching [Jump::In] in the stack. A match is found
66/// when source location of the JUMP-in matches the source location of final JUMPDEST (this would be
67/// the location of the function invocation), or when source location of first JUMODEST matches the
68/// source location of the JUMP-out (this would be the location of function body).
69///
70/// When a match is found, all items which were pushed after the matched function are removed. There
71/// is a lot of such items due to source maps getting malformed during optimization.
72struct DebugStepsWalker<'a> {
73    node: &'a mut CallTraceNode,
74    current_step: usize,
75    stack: Vec<(String, usize)>,
76    sources: &'a ContractSources,
77    contract_name: &'a str,
78}
79
80impl<'a> DebugStepsWalker<'a> {
81    pub const fn new(
82        node: &'a mut CallTraceNode,
83        sources: &'a ContractSources,
84        contract_name: &'a str,
85    ) -> Self {
86        Self { node, current_step: 0, stack: Vec::new(), sources, contract_name }
87    }
88
89    fn current_step(&self) -> &CallTraceStep {
90        &self.node.trace.steps[self.current_step]
91    }
92
93    fn src_map(&self, step: usize) -> Option<(SourceElement, &SourceData)> {
94        self.sources.find_source_mapping(
95            self.contract_name,
96            self.node.trace.steps[step].pc as u32,
97            self.node.trace.kind.is_any_create(),
98        )
99    }
100
101    fn prev_src_map(&self) -> Option<(SourceElement, &SourceData)> {
102        if self.current_step == 0 {
103            return None;
104        }
105
106        self.src_map(self.current_step - 1)
107    }
108
109    fn is_same_loc(&self, step: usize, other: usize) -> bool {
110        let Some((loc, _)) = self.src_map(step) else {
111            return false;
112        };
113        let Some((other_loc, _)) = self.src_map(other) else {
114            return false;
115        };
116
117        same_loc(&loc, &other_loc)
118    }
119
120    /// Invoked when current step is a JUMPDEST preceded by a JUMP marked as [Jump::In].
121    ///
122    /// `prev_source_element` is the source element of the JUMP.
123    fn jump_in(&mut self, prev_source_element: &SourceElement) {
124        let Some((source_element, source)) = self.src_map(self.current_step) else {
125            return;
126        };
127
128        // This usually means that this is a jump into the external function which is an
129        // entrypoint for the current frame. We don't want to include this to avoid
130        // duplicating traces.
131        if same_loc(&source_element, prev_source_element) {
132            return;
133        }
134
135        if let Some(name) = parse_function_from_loc(source, &source_element) {
136            self.stack.push((name, self.current_step - 1));
137        }
138    }
139
140    /// Invoked when current step is a JUMPDEST preceded by a JUMP marked as [Jump::Out].
141    fn jump_out(&mut self) {
142        let Some((i, _)) = self.stack.iter().enumerate().rfind(|(_, (_, step_idx))| {
143            self.is_same_loc(*step_idx, self.current_step)
144                || self.is_same_loc(step_idx + 1, self.current_step - 1)
145        }) else {
146            return;
147        };
148        // We've found a match, remove all records between start and end, those
149        // are considered invalid.
150        let (func_name, start_idx) = self.stack.split_off(i).swap_remove(0);
151
152        // Try to decode function inputs and outputs from the stack and memory.
153        let (inputs, outputs) = self
154            .src_map(start_idx + 1)
155            .and_then(|(source_element, source)| {
156                let start = source_element.offset() as usize;
157                let (fn_definition, _) =
158                    source_span(&source.source, start, source_element.length() as usize)?;
159                let fn_definition = fn_definition.replace('\n', "");
160                let (inputs, outputs) = parse_types(&fn_definition);
161
162                Some((
163                    inputs.and_then(|t| {
164                        decode_step_parameters(
165                            &t,
166                            &self.node.trace.steps[start_idx + 1],
167                            Some(self.node.trace.data.as_ref()),
168                        )
169                    }),
170                    outputs.and_then(|t| decode_step_parameters(&t, self.current_step(), None)),
171                ))
172            })
173            .unwrap_or_default();
174
175        self.node.trace.steps[start_idx].decoded = Some(Box::new(DecodedTraceStep::InternalCall(
176            DecodedInternalCall { func_name, args: inputs, return_data: outputs },
177            self.current_step,
178        )));
179    }
180
181    fn process(&mut self) {
182        // We are only interested in JUMPs.
183        if self.current_step().op != OpCode::JUMP && self.current_step().op != OpCode::JUMPDEST {
184            return;
185        }
186
187        let Some((prev_source_element, _)) = self.prev_src_map() else {
188            return;
189        };
190
191        match prev_source_element.jump() {
192            Jump::In => self.jump_in(&prev_source_element),
193            Jump::Out => self.jump_out(),
194            _ => {}
195        };
196    }
197
198    fn step(&mut self) {
199        self.process();
200        self.current_step += 1;
201    }
202
203    pub fn walk(mut self) {
204        while self.current_step < self.node.trace.steps.len() {
205            self.step();
206        }
207    }
208}
209
210/// Returns whether both source elements refer to the same source location.
211fn same_loc(loc: &SourceElement, other: &SourceElement) -> bool {
212    loc.offset() == other.offset() && loc.length() == other.length() && loc.index() == other.index()
213}
214
215/// Tries to parse the function name from the source code and detect the contract name which
216/// contains the given function.
217///
218/// Returns a string in the format `Contract::function(types)` when parameters can be resolved,
219/// falling back to `Contract::function`.
220fn parse_function_from_loc(source: &SourceData, loc: &SourceElement) -> Option<String> {
221    let start = loc.offset() as usize;
222    let (source_part, end) = source_span(&source.source, start, loc.length() as usize)?;
223
224    if !source_part.starts_with("function") {
225        return None;
226    }
227    let function_name = source_part.split_once("function")?.1.split('(').next()?.trim();
228    let contract_name = source.find_contract_name(start, end)?;
229
230    Some(internal_function_identifier(contract_name, function_name, source_part))
231}
232
233fn internal_function_identifier(
234    contract_name: &str,
235    function_name: &str,
236    source_part: &str,
237) -> String {
238    let signature = canonical_function_signature(function_name, source_part)
239        .unwrap_or_else(|| function_name.to_string());
240    format!("{contract_name}::{signature}")
241}
242
243fn canonical_function_signature(function_name: &str, source_part: &str) -> Option<String> {
244    let source_part = source_part.replace('\n', "");
245    let (inputs, _) = parse_types(&source_part);
246    let inputs = inputs?;
247    let types =
248        inputs.params.iter().map(|param| param.resolve().ok()).collect::<Option<Vec<_>>>()?;
249    Some(function_signature(function_name, &types))
250}
251
252/// Formats an ABI-style function signature from a name and canonical parameter types.
253pub fn function_signature(function_name: &str, types: &[DynSolType]) -> String {
254    let mut signature = String::new();
255    signature.push_str(function_name);
256    signature.push('(');
257    for (i, ty) in types.iter().enumerate() {
258        if i > 0 {
259            signature.push(',');
260        }
261        signature.push_str(&ty.sol_type_name());
262    }
263    signature.push(')');
264    signature
265}
266
267fn source_span(source: &str, start: usize, len: usize) -> Option<(&str, usize)> {
268    let end = start.checked_add(len)?;
269
270    Some((source.get(start..end)?, end))
271}
272
273/// Parses function input and output types into [Parameters].
274fn parse_types(source: &str) -> (Option<Parameters<'_>>, Option<Parameters<'_>>) {
275    let inputs = source.find('(').and_then(|params_start| {
276        let params_end = params_start + source[params_start..].find(')')?;
277        Parameters::parse(&source[params_start..params_end + 1]).ok()
278    });
279    let outputs = source.find("returns").and_then(|returns_start| {
280        let return_params_start = returns_start + source[returns_start..].find('(')?;
281        let return_params_end = return_params_start + source[return_params_start..].find(')')?;
282        Parameters::parse(&source[return_params_start..return_params_end + 1]).ok()
283    });
284
285    (inputs, outputs)
286}
287
288/// Given [Parameters] and [CallTraceStep], tries to decode parameters by using stack, memory, and
289/// call data.
290pub fn decode_step_parameters(
291    args: &Parameters<'_>,
292    step: &CallTraceStep,
293    calldata: Option<&[u8]>,
294) -> Option<Vec<String>> {
295    let params = &args.params;
296
297    if params.is_empty() {
298        return Some(vec![]);
299    }
300
301    let types = params
302        .iter()
303        .map(|p| {
304            p.resolve().ok().map(|t| {
305                let slots = stack_slots(&t, p.storage);
306                (t, p.storage, slots)
307            })
308        })
309        .collect::<Vec<_>>();
310
311    let stack = step.stack.as_ref()?;
312    let stack_slots =
313        types.iter().map(|type_| type_.as_ref().map_or(1, |(_, _, slots)| *slots)).sum::<usize>();
314
315    if stack.len() < stack_slots {
316        return None;
317    }
318
319    let inputs = &stack[stack.len() - stack_slots..];
320    let memory = step.memory.as_ref().map(|memory| memory.as_bytes().as_ref());
321    let mut input_idx = 0;
322    let mut decoded = Vec::with_capacity(types.len());
323
324    for type_and_storage in &types {
325        let Some((type_, storage, slots)) = type_and_storage.as_ref() else {
326            input_idx += 1;
327            decoded.push("<unknown>".to_string());
328            continue;
329        };
330        let input = &inputs[input_idx..input_idx + *slots];
331        input_idx += *slots;
332
333        decoded.push(
334            decode_parameter(type_, *storage, input, memory, calldata)
335                .as_ref()
336                .map(format_token)
337                .unwrap_or_else(|| "<unknown>".to_string()),
338        );
339    }
340
341    Some(decoded)
342}
343
344const fn stack_slots(ty: &DynSolType, storage: Option<Storage>) -> usize {
345    match (ty, storage) {
346        (
347            DynSolType::String | DynSolType::Bytes | DynSolType::Array(_),
348            Some(Storage::Calldata),
349        ) => 2,
350        _ => 1,
351    }
352}
353
354fn decode_parameter(
355    ty: &DynSolType,
356    storage: Option<Storage>,
357    stack_words: &[U256],
358    memory: Option<&[u8]>,
359    calldata: Option<&[u8]>,
360) -> Option<DynSolValue> {
361    let input = stack_words.first()?;
362
363    match (ty, storage) {
364        // HACK: alloy parser treats user-defined types as uint8: https://github.com/alloy-rs/core/pull/386
365        //
366        // filter out `uint8` params which are marked as storage, memory, or calldata as this
367        // is not possible in Solidity and means that type is user-defined
368        (DynSolType::Uint(8), Some(Storage::Memory | Storage::Storage | Storage::Calldata)) => None,
369        (_, Some(Storage::Storage)) => None,
370        (_, Some(Storage::Memory)) => decode_from_memory(ty, memory?, input.try_into().ok()?),
371        (_, Some(Storage::Calldata)) => decode_from_calldata(ty, calldata?, stack_words),
372        // Read other types from stack
373        _ => ty.abi_decode(&input.to_be_bytes::<32>()).ok(),
374    }
375}
376
377fn decode_from_calldata(
378    ty: &DynSolType,
379    calldata: &[u8],
380    stack_words: &[U256],
381) -> Option<DynSolValue> {
382    let offset: usize = stack_words.first()?.try_into().ok()?;
383
384    match ty {
385        // For calldata `string` and `bytes`, Solidity keeps the byte offset and length on stack.
386        DynSolType::String | DynSolType::Bytes => {
387            let length: usize = stack_words.get(1)?.try_into().ok()?;
388            let data = memory_range(calldata, offset, length)?;
389
390            match ty {
391                DynSolType::Bytes => Some(DynSolValue::Bytes(data.to_vec())),
392                DynSolType::String => {
393                    Some(DynSolValue::String(String::from_utf8_lossy(data).to_string()))
394                }
395                _ => unreachable!(),
396            }
397        }
398        _ => None,
399    }
400}
401
402/// Decodes given [DynSolType] from memory.
403fn decode_from_memory(ty: &DynSolType, memory: &[u8], location: usize) -> Option<DynSolValue> {
404    let first_word = memory_range(memory, location, 32)?;
405
406    match ty {
407        // For `string` and `bytes` layout is a word with length followed by the data
408        DynSolType::String | DynSolType::Bytes => {
409            let length: usize = U256::from_be_slice(first_word).try_into().ok()?;
410            let data = memory_range(memory, location.checked_add(32)?, length)?;
411
412            match ty {
413                DynSolType::Bytes => Some(DynSolValue::Bytes(data.to_vec())),
414                DynSolType::String => {
415                    Some(DynSolValue::String(String::from_utf8_lossy(data).to_string()))
416                }
417                _ => unreachable!(),
418            }
419        }
420        // Dynamic arrays are encoded as a word with length followed by words with elements
421        // Fixed arrays are encoded as words with elements
422        DynSolType::Array(inner) | DynSolType::FixedArray(inner, _) => {
423            let (length, start) = match ty {
424                DynSolType::FixedArray(_, length) => (*length, location),
425                DynSolType::Array(_) => {
426                    (U256::from_be_slice(first_word).try_into().ok()?, location.checked_add(32)?)
427                }
428                _ => unreachable!(),
429            };
430            memory_range(memory, start, length.checked_mul(32)?)?;
431            let mut decoded = Vec::with_capacity(length);
432
433            for i in 0..length {
434                let offset = start.checked_add(i.checked_mul(32)?)?;
435                let location = match inner.as_ref() {
436                    // Arrays of variable length types are arrays of pointers to the values
437                    DynSolType::String | DynSolType::Bytes | DynSolType::Array(_) => {
438                        U256::from_be_slice(memory_range(memory, offset, 32)?).try_into().ok()?
439                    }
440                    _ => offset,
441                };
442
443                decoded.push(decode_from_memory(inner, memory, location)?);
444            }
445
446            Some(DynSolValue::Array(decoded))
447        }
448        _ => ty.abi_decode(first_word).ok(),
449    }
450}
451
452fn memory_range(memory: &[u8], start: usize, len: usize) -> Option<&[u8]> {
453    memory.get(start..start.checked_add(len)?)
454}
455
456#[cfg(test)]
457mod tests {
458    use super::*;
459    use alloy_primitives::Bytes;
460    use evm2::interpreter::InstrStop;
461
462    fn trace_step(stack: Vec<U256>) -> CallTraceStep {
463        CallTraceStep {
464            pc: 0,
465            op: OpCode::STOP,
466            stack: Some(stack.into_boxed_slice()),
467            push_stack: None,
468            memory: None,
469            returndata: Bytes::new(),
470            gas_remaining: 0,
471            gas_refund_counter: 0,
472            gas_cost: 0,
473            state_gas_cost: None,
474            state_gas_reservoir: None,
475            state_gas_spent: 0,
476            storage_change: None,
477            status: Some(InstrStop::Stop),
478            immediate_bytes: None,
479            decoded: None,
480        }
481    }
482
483    #[test]
484    fn source_span_returns_none_for_invalid_ranges() {
485        assert_eq!(source_span("abcdef", 2, 3), Some(("cde", 5)));
486        assert_eq!(source_span("abcdef", 7, 1), None);
487        assert_eq!(source_span("abcdef", usize::MAX, 1), None);
488    }
489
490    #[test]
491    fn internal_function_identifier_includes_canonical_signature() {
492        assert_eq!(
493            internal_function_identifier(
494                "DebugMe",
495                "foo",
496                "function foo(uint256 amount, bool ok) internal returns (uint256) {",
497            ),
498            "DebugMe::foo(uint256,bool)"
499        );
500    }
501
502    #[test]
503    fn decode_from_memory_rejects_overflow_location() {
504        assert_eq!(decode_from_memory(&DynSolType::Bytes, &[0; 64], usize::MAX), None);
505    }
506
507    #[test]
508    fn decode_from_memory_rejects_oversized_dynamic_array_length() {
509        let memory = U256::from(1_000_000).to_be_bytes::<32>();
510        let ty = DynSolType::Array(Box::new(DynSolType::Uint(256)));
511
512        assert_eq!(decode_from_memory(&ty, &memory, 0), None);
513    }
514
515    #[test]
516    fn decode_step_parameters_marks_storage_params_unknown() {
517        let params = Parameters::parse("(uint256[] storage values)").unwrap();
518        let step = trace_step(vec![U256::from(5)]);
519
520        assert_eq!(
521            decode_step_parameters(&params, &step, None),
522            Some(vec!["<unknown>".to_string()])
523        );
524    }
525
526    #[test]
527    fn decode_step_parameters_aligns_static_arg_before_calldata_bytes() {
528        let params = Parameters::parse("(bytes32 digest, bytes calldata signature)").unwrap();
529        let digest = U256::from(0x1234);
530        let offset = 0x44;
531        let mut calldata = vec![0; offset];
532        calldata.extend_from_slice(&[0x11, 0x22, 0x33]);
533        let step = trace_step(vec![digest, U256::from(offset), U256::from(3)]);
534
535        assert_eq!(
536            decode_step_parameters(&params, &step, Some(&calldata)),
537            Some(vec![
538                "0x0000000000000000000000000000000000000000000000000000000000001234".to_string(),
539                "0x112233".to_string(),
540            ])
541        );
542    }
543
544    #[test]
545    fn decode_step_parameters_marks_calldata_bytes_unknown_without_calldata() {
546        let params = Parameters::parse("(bytes calldata signature)").unwrap();
547        let step = trace_step(vec![U256::from(0x44), U256::from(3)]);
548
549        assert_eq!(
550            decode_step_parameters(&params, &step, None),
551            Some(vec!["<unknown>".to_string()])
552        );
553    }
554
555    #[test]
556    fn decode_step_parameters_aligns_static_arg_after_unsupported_calldata_array() {
557        let params = Parameters::parse("(uint256[] calldata values, bytes32 digest)").unwrap();
558        let digest = U256::from(0x1234);
559        let step = trace_step(vec![U256::from(0x44), U256::from(2), digest]);
560
561        assert_eq!(
562            decode_step_parameters(&params, &step, Some(&[])),
563            Some(vec![
564                "<unknown>".to_string(),
565                "0x0000000000000000000000000000000000000000000000000000000000001234".to_string(),
566            ])
567        );
568    }
569}