Skip to main content

foundry_cheatcodes/evm/
record_debug_step.rs

1use alloy_primitives::{Bytes, U256};
2use evm2::interpreter::opcode::OpCode;
3use foundry_evm_core::buffer::{BufferKind, get_buffer_accesses};
4use foundry_evm_traces::{
5    CallTraceArena, CallTraceNode, CallTraceStep, RecordedMemory, TraceMemberOrder,
6};
7use spec::Vm::DebugStep;
8
9// Context for a CallTraceStep, includes depth and contract address.
10pub(crate) struct CallTraceCtx<'a> {
11    pub node: &'a CallTraceNode,
12    pub step: &'a CallTraceStep,
13}
14
15// Do a depth first traverse of the nodes and steps and return steps
16// that are after `node_start_idx`
17pub(crate) fn flatten_call_trace<'a>(
18    root: usize,
19    arena: &'a CallTraceArena,
20    node_start_idx: usize,
21) -> Vec<CallTraceCtx<'a>> {
22    let mut steps = Vec::new();
23    let mut record_started = false;
24
25    // Start the recursion from the root node
26    recursive_flatten_call_trace(root, arena, node_start_idx, &mut record_started, &mut steps);
27    steps
28}
29
30// Inner recursive function to process nodes.
31// This implementation directly mutates `record_started` and `flatten_steps`.
32// So the recursive call can change the `record_started` flag even for the parent
33// unfinished processing, and append steps to the `flatten_steps` as the final result.
34fn recursive_flatten_call_trace<'a>(
35    node_idx: usize,
36    arena: &'a CallTraceArena,
37    node_start_idx: usize,
38    record_started: &mut bool,
39    flatten_steps: &mut Vec<CallTraceCtx<'a>>,
40) {
41    // Once node_idx exceeds node_start_idx, start recording steps
42    // for all the recursive processing.
43    if !*record_started && node_idx >= node_start_idx {
44        *record_started = true;
45    }
46
47    let node = &arena.nodes()[node_idx];
48
49    for order in &node.ordering {
50        match order {
51            TraceMemberOrder::Step(step_idx) if *record_started => {
52                let step = &node.trace.steps[*step_idx];
53                flatten_steps.push(CallTraceCtx { node, step });
54            }
55            TraceMemberOrder::Call(call_idx) => {
56                let child_node_idx = node.children[*call_idx];
57                recursive_flatten_call_trace(
58                    child_node_idx,
59                    arena,
60                    node_start_idx,
61                    record_started,
62                    flatten_steps,
63                );
64            }
65            _ => {}
66        }
67    }
68}
69
70// Function to convert CallTraceStep to DebugStep
71pub(crate) fn convert_call_trace_ctx_to_debug_step(ctx: &CallTraceCtx) -> DebugStep {
72    let opcode = ctx.step.op.get();
73    let stack = get_stack_inputs_for_opcode(opcode, ctx.step.stack.as_deref());
74
75    let memory =
76        get_memory_input_for_opcode(opcode, ctx.step.stack.as_deref(), ctx.step.memory.as_ref());
77
78    let is_out_of_gas = ctx.step.status.is_some_and(|status| status.is_out_of_gas());
79
80    let depth = ctx.node.trace.depth as u64 + 1;
81    let contract_addr = ctx.node.execution_address();
82
83    DebugStep {
84        stack,
85        memoryInput: memory,
86        opcode: ctx.step.op.get(),
87        depth,
88        isOutOfGas: is_out_of_gas,
89        contractAddr: contract_addr,
90    }
91}
92
93// The expected `stack` here is from the trace stack, where the top of the stack
94// is the last value of the vector
95fn get_memory_input_for_opcode(
96    opcode: u8,
97    stack: Option<&[U256]>,
98    memory: Option<&RecordedMemory>,
99) -> Bytes {
100    let mut memory_input = Bytes::new();
101    let Some(stack_data) = stack else { return memory_input };
102    let Some(memory_data) = memory else { return memory_input };
103
104    if let Some(accesses) = get_buffer_accesses(opcode, stack_data)
105        && let Some((BufferKind::Memory, access)) = accesses.read
106    {
107        memory_input = get_slice_from_memory(memory_data.as_bytes(), access.offset, access.len);
108    };
109
110    memory_input
111}
112
113// The expected `stack` here is from the trace stack, where the top of the stack
114// is the last value of the vector.
115//
116// A step that fails with a stack underflow is recorded with fewer items than its opcode
117// consumes, so only the items that are actually present are returned.
118fn get_stack_inputs_for_opcode(opcode: u8, stack: Option<&[U256]>) -> Vec<U256> {
119    let Some(op) = OpCode::new(opcode) else { return Vec::new() };
120    let Some(stack_data) = stack else { return Vec::new() };
121
122    let stack_input_size = (op.inputs() as usize).min(stack_data.len());
123    stack_data.iter().rev().take(stack_input_size).copied().collect()
124}
125
126fn get_slice_from_memory(memory: &Bytes, start_index: usize, size: usize) -> Bytes {
127    let memory_len = memory.len();
128
129    let end_bound = start_index + size;
130
131    // Return the bytes if data is within the range.
132    if start_index < memory_len && end_bound <= memory_len {
133        return memory.slice(start_index..end_bound);
134    }
135
136    // Pad zero bytes if attempting to load memory partially out of range.
137    if start_index < memory_len && end_bound > memory_len {
138        let mut result = memory.slice(start_index..memory_len).to_vec();
139        result.resize(size, 0u8);
140        return Bytes::from(result);
141    }
142
143    // Return empty bytes with the size if not in range at all.
144    Bytes::from(vec![0u8; size])
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150    use evm2::interpreter::op as opcode;
151
152    #[test]
153    fn stack_inputs_are_taken_from_the_top() {
154        let stack = [U256::ONE, U256::from(2), U256::from(3)];
155        assert_eq!(
156            get_stack_inputs_for_opcode(opcode::ADD, Some(&stack)),
157            vec![U256::from(3), U256::from(2)]
158        );
159    }
160
161    #[test]
162    fn stack_inputs_are_truncated_on_underflow() {
163        assert_eq!(get_stack_inputs_for_opcode(opcode::ADD, Some(&[])), Vec::<U256>::new());
164        assert_eq!(
165            get_stack_inputs_for_opcode(opcode::ADD, Some(&[U256::from(7)])),
166            vec![U256::from(7)]
167        );
168    }
169}