Skip to main content

foundry_evm_traces/debug/
mod.rs

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