Skip to main content

zksync_vm2/instruction_handlers/
ret.rs

1use primitive_types::U256;
2use zksync_vm2_interface::{
3    opcodes::{self, Normal, Panic, Revert, TypeLevelReturnType},
4    ReturnType, Tracer,
5};
6
7use super::{
8    common::full_boilerplate,
9    far_call::get_calldata,
10    monomorphization::{match_boolean, monomorphize, parameterize},
11};
12use crate::{
13    addressing_modes::{Arguments, Immediate1, Register1, Source, INVALID_INSTRUCTION_COST},
14    callframe::FrameRemnant,
15    instruction::{ExecutionEnd, ExecutionStatus},
16    mode_requirements::ModeRequirements,
17    page_ids::base_page_from_heap,
18    predication::Flags,
19    tracing::VmAndWorld,
20    Instruction, Predicate, VirtualMachine, World,
21};
22
23fn naked_ret<T: Tracer, W: World<T>, RT: TypeLevelReturnType, const TO_LABEL: bool>(
24    vm: &mut VirtualMachine<T, W>,
25    args: &Arguments,
26) -> ExecutionStatus {
27    let mut return_type = RT::VALUE;
28    let near_call_leftover_gas = vm.state.current_frame.gas;
29
30    let (snapshot, leftover_gas) = if let Some(FrameRemnant {
31        exception_handler,
32        snapshot,
33    }) = vm.state.current_frame.pop_near_call()
34    {
35        if TO_LABEL {
36            let pc = Immediate1::get_u16(args);
37            vm.state.current_frame.set_pc_from_u16(pc);
38        } else if return_type.is_failure() {
39            vm.state.current_frame.set_pc_from_u16(exception_handler);
40        }
41
42        (snapshot, near_call_leftover_gas)
43    } else {
44        let (raw_abi, is_pointer) = Register1::get_with_pointer_flag(args, &mut vm.state);
45        let return_value_or_panic = if return_type == ReturnType::Panic {
46            // A panic forwards no returndata, but the return-ABI pointer must still be resolved for
47            // its heap-growth cost: a fresh-heap pointer whose `start + length` overflows `u32`
48            // grows the heap to `u32::MAX`, draining the frame's gas. Passing `already_failed = true`
49            // charges exactly that penalty while discarding the (unused) returndata pointer. This
50            // mirrors the proving circuit and post-#217 zk_evm; see `get_calldata`.
51            get_calldata(raw_abi, is_pointer, vm, true);
52            None
53        } else {
54            let result = get_calldata(raw_abi, is_pointer, vm, false).filter(|pointer| {
55                if vm.state.current_frame.is_kernel {
56                    true
57                } else {
58                    // Non-kernel returndata forwarding must be unidirectional: callers may pass
59                    // pointers down the stack, but callees must not forward pointers to older pages.
60                    // This mirrors zk_evm's restriction based on base memory page checks.
61                    pointer.memory_page.as_u32() >= base_page_from_heap(vm.state.current_frame.heap)
62                        && pointer.memory_page != vm.state.current_frame.calldata_heap
63                }
64            });
65
66            if result.is_none() {
67                return_type = ReturnType::Panic;
68            }
69            result
70        };
71
72        let leftover_gas = vm.state.current_frame.gas;
73
74        let Some(FrameRemnant {
75            exception_handler,
76            snapshot,
77        }) = vm.pop_frame(
78            return_value_or_panic
79                .as_ref()
80                .map(|pointer| pointer.memory_page),
81        )
82        else {
83            // The initial frame is not rolled back, even if it fails.
84            // It is the caller's job to clean up when the execution as a whole fails because
85            // the caller may take external snapshots while the VM is in the initial frame and
86            // these would break were the initial frame to be rolled back.
87
88            // But to continue execution would be nonsensical and can cause UB because there
89            // is no next instruction after a panic arising from some other instruction.
90            vm.state.current_frame.pc = invalid_instruction();
91
92            return if let Some(return_value) = return_value_or_panic {
93                let output = vm.state.heaps[return_value.memory_page]
94                    .read_range_big_endian(
95                        return_value.start..return_value.start + return_value.length,
96                    )
97                    .clone();
98                if return_type == ReturnType::Revert {
99                    ExecutionStatus::Stopped(ExecutionEnd::Reverted(output))
100                } else {
101                    ExecutionStatus::Stopped(ExecutionEnd::ProgramFinished(output))
102                }
103            } else {
104                ExecutionStatus::Stopped(ExecutionEnd::Panicked)
105            };
106        };
107
108        vm.state.set_context_u128(0);
109        vm.state.registers = [U256::zero(); 16];
110
111        if let Some(return_value) = return_value_or_panic {
112            vm.state.registers[1] = return_value.into_u256();
113        }
114        vm.state.register_pointer_flags = 2;
115
116        if return_type.is_failure() {
117            vm.state.current_frame.set_pc_from_u16(exception_handler);
118        }
119
120        (snapshot, leftover_gas)
121    };
122
123    if return_type.is_failure() {
124        vm.world_diff.append_rollback_logs(&snapshot);
125        vm.world_diff.rollback(snapshot);
126    }
127
128    vm.state.flags = Flags::new(return_type == ReturnType::Panic, false, false);
129    vm.state.current_frame.gas += leftover_gas;
130
131    ExecutionStatus::Running
132}
133
134fn ret<T: Tracer, W: World<T>, RT: TypeLevelReturnType, const TO_LABEL: bool>(
135    vm: &mut VirtualMachine<T, W>,
136    world: &mut W,
137    tracer: &mut T,
138) -> ExecutionStatus {
139    full_boilerplate::<opcodes::Ret<RT>, _, _>(vm, world, tracer, |vm, args, _, _| {
140        naked_ret::<T, W, RT, TO_LABEL>(vm, args)
141    })
142}
143
144/// Turn the current instruction into a panic at no extra cost. (Great value, I know.)
145///
146/// Call this when:
147/// - gas runs out when paying for the fixed cost of an instruction
148/// - causing side effects in a static context
149/// - using privileged instructions while not in a system call
150/// - the far call stack overflows
151///
152/// For all other panics, point the instruction pointer at [PANIC] instead.
153pub(crate) fn free_panic<T: Tracer, W: World<T>>(
154    vm: &mut VirtualMachine<T, W>,
155    world: &mut W,
156    tracer: &mut T,
157) -> ExecutionStatus {
158    tracer.before_instruction::<opcodes::Ret<Panic>, _>(&mut VmAndWorld { vm, world });
159    // A spontaneous panic has no return ABI: these empty args encode source register r0, so
160    // naked_ret's return-ABI resolution reads zero and charges no heap growth. (args are otherwise
161    // only consulted for the jump label when TO_LABEL is set, which it isn't here.)
162    naked_ret::<T, W, Panic, false>(
163        vm,
164        &Arguments::new(Predicate::Always, 0, ModeRequirements::none()),
165    )
166    .merge_tracer(tracer.after_instruction::<opcodes::Ret<Panic>, _>(&mut VmAndWorld { vm, world }))
167}
168
169fn invalid<T: Tracer, W: World<T>>(
170    vm: &mut VirtualMachine<T, W>,
171    world: &mut W,
172    tracer: &mut T,
173) -> ExecutionStatus {
174    vm.state.current_frame.gas = 0;
175    free_panic(vm, world, tracer)
176}
177
178trait GenericStatics<T, W> {
179    const PANIC: Instruction<T, W>;
180    const INVALID: Instruction<T, W>;
181}
182
183impl<T: Tracer, W: World<T>> GenericStatics<T, W> for () {
184    const PANIC: Instruction<T, W> = Instruction::from_spontaneous_panic();
185    const INVALID: Instruction<T, W> = Instruction::from_invalid();
186}
187
188// The following functions return references that live for 'static.
189// They aren't marked as such because returning any lifetime is more ergonomic.
190
191/// Point the program counter at this instruction when a panic occurs during the logic of and instruction.
192pub(crate) fn spontaneous_panic<'a, T: Tracer, W: World<T>>() -> &'a Instruction<T, W> {
193    &<()>::PANIC
194}
195
196/// Panics, burning all available gas.
197pub(crate) fn invalid_instruction<'a, T: Tracer, W: World<T>>() -> &'a Instruction<T, W> {
198    &<()>::INVALID
199}
200
201pub(crate) const RETURN_COST: u32 = 5;
202
203/// Variations of [`Ret`](opcodes::Ret) instructions.
204impl<T: Tracer, W: World<T>> Instruction<T, W> {
205    /// Creates a normal [`Ret`](opcodes::Ret) instruction with the provided params.
206    pub fn from_ret(src1: Register1, label: Option<Immediate1>, arguments: Arguments) -> Self {
207        let to_label = label.is_some();
208        Self {
209            handler: monomorphize!(ret [T W Normal] match_boolean to_label),
210            arguments: arguments.write_source(&src1).write_source(&label),
211        }
212    }
213
214    /// Creates a revert [`Ret`](opcodes::Ret) instruction with the provided params.
215    pub fn from_revert(src1: Register1, label: Option<Immediate1>, arguments: Arguments) -> Self {
216        let to_label = label.is_some();
217        Self {
218            handler: monomorphize!(ret [T W Revert] match_boolean to_label),
219            arguments: arguments.write_source(&src1).write_source(&label),
220        }
221    }
222
223    /// Creates a panic [`Ret`](opcodes::Ret) instruction with the provided params.
224    ///
225    /// `src1` carries the return-ABI register. Even though a panic forwards no returndata, the
226    /// register is still resolved for its heap-growth cost (see `naked_ret`).
227    pub fn from_panic(src1: Register1, label: Option<Immediate1>, arguments: Arguments) -> Self {
228        let to_label = label.is_some();
229        Self {
230            handler: monomorphize!(ret [T W Panic] match_boolean to_label),
231            arguments: arguments.write_source(&src1).write_source(&label),
232        }
233    }
234
235    /// Creates the instruction that is executed when anonther instruction encounters
236    /// an error.
237    pub(crate) const fn from_spontaneous_panic() -> Self {
238        Self {
239            handler: ret::<T, W, Panic, false>,
240            arguments: Arguments::new(Predicate::Always, RETURN_COST, ModeRequirements::none()),
241        }
242    }
243
244    /// Creates a *invalid* instruction that will panic by draining all gas.
245    pub const fn from_invalid() -> Self {
246        Self {
247            handler: invalid,
248            arguments: Arguments::new(
249                Predicate::Always,
250                INVALID_INSTRUCTION_COST,
251                ModeRequirements::none(),
252            ),
253        }
254    }
255}