Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: failing far call tracing #81

Merged
merged 5 commits into from
Jan 23, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 4 additions & 6 deletions crates/vm2/src/instruction_handlers/far_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use super::{
common::full_boilerplate,
heap_access::grow_heap,
monomorphization::{match_boolean, monomorphize, parameterize},
ret::{panic_from_failed_far_call, RETURN_COST},
AuxHeap, Heap,
};
use crate::{
Expand All @@ -21,7 +20,7 @@ use crate::{
fat_pointer::FatPointer,
instruction::ExecutionStatus,
predication::Flags,
Instruction, VirtualMachine, World,
Instruction, Program, VirtualMachine, World,
};

/// A call to another contract.
Expand Down Expand Up @@ -107,10 +106,9 @@ where
vm.state.current_frame.gas -= normally_passed_gas;
let new_frame_gas = normally_passed_gas + mandated_gas;

let Some((calldata, program, is_evm_interpreter)) = failing_part else {
vm.state.current_frame.gas += new_frame_gas.saturating_sub(RETURN_COST);
return panic_from_failed_far_call(vm, world, tracer, exception_handler);
};
// A far call pushes a new frame and returns from it in the next instruction if it panics.
let (calldata, program, is_evm_interpreter) =
failing_part.unwrap_or_else(|| (U256::zero().into(), Program::new_panicking(), false));

let stipend = if is_evm_interpreter {
EVM_SIMULATOR_STIPEND
Expand Down
37 changes: 10 additions & 27 deletions crates/vm2/src/instruction_handlers/ret.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,29 +153,6 @@ pub(crate) fn free_panic<T: Tracer, W: World<T>>(
.merge_tracer(tracer.after_instruction::<opcodes::Ret<Panic>, _>(&mut VmAndWorld { vm, world }))
}

/// Formally, a far call pushes a new frame and returns from it immediately if it panics.
/// This function instead panics without popping a frame to save on allocation.
pub(crate) fn panic_from_failed_far_call<T: Tracer, W: World<T>>(
vm: &mut VirtualMachine<T, W>,
world: &mut W,
tracer: &mut T,
exception_handler: u16,
) -> ExecutionStatus {
tracer.before_instruction::<opcodes::Ret<Panic>, _>(&mut VmAndWorld { vm, world });

// Gas is already subtracted in the far call code.
// No need to roll back, as no changes are made in this "frame".
vm.state.set_context_u128(0);
vm.state.registers = [U256::zero(); 16];
vm.state.register_pointer_flags = 2;
vm.state.flags = Flags::new(true, false, false);
vm.state.current_frame.set_pc_from_u16(exception_handler);

tracer
.after_instruction::<opcodes::Ret<Panic>, _>(&mut VmAndWorld { vm, world })
.into()
}

fn invalid<T: Tracer, W: World<T>>(
vm: &mut VirtualMachine<T, W>,
world: &mut W,
Expand All @@ -191,10 +168,7 @@ trait GenericStatics<T, W> {
}

impl<T: Tracer, W: World<T>> GenericStatics<T, W> for () {
const PANIC: Instruction<T, W> = Instruction {
handler: ret::<T, W, Panic, false>,
arguments: Arguments::new(Predicate::Always, RETURN_COST, ModeRequirements::none()),
};
const PANIC: Instruction<T, W> = Instruction::from_spontaneous_panic();
const INVALID: Instruction<T, W> = Instruction::from_invalid();
}

Expand Down Expand Up @@ -242,6 +216,15 @@ impl<T: Tracer, W: World<T>> Instruction<T, W> {
}
}

/// Creates the instruction that is executed when anonther instruction encounters
/// an error.
pub(crate) const fn from_spontaneous_panic() -> Self {
Self {
handler: ret::<T, W, Panic, false>,
arguments: Arguments::new(Predicate::Always, RETURN_COST, ModeRequirements::none()),
}
}

/// Creates a *invalid* instruction that will panic by draining all gas.
pub const fn from_invalid() -> Self {
Self {
Expand Down
4 changes: 4 additions & 0 deletions crates/vm2/src/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ impl<T: Tracer, W: World<T>> Program<T, W> {
}
}

pub(crate) fn new_panicking() -> Self {
Self::from_raw(vec![Instruction::from_spontaneous_panic()], vec![])
}

#[doc(hidden)] // should only be used in low-level tests / benchmarks
pub fn from_raw(instructions: Vec<Instruction<T, W>>, code_page: Vec<U256>) -> Self {
Self {
Expand Down
15 changes: 15 additions & 0 deletions crates/vm2/src/single_instruction_test/program.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@ impl<T: Tracer, W: World<T>> Program<T, W> {
code_page: Arc::new([U256::zero(); 1]),
}
}

pub(crate) fn new_panicking() -> Self {
Self {
raw_first_instruction: 0,
first_instruction: MockRead::new(Rc::new([
Instruction::from_spontaneous_panic(),
Instruction::from_invalid(),
])),
other_instruction: MockRead::new(Rc::new(Some([
Instruction::from_invalid(),
Instruction::from_invalid(),
]))),
code_page: Arc::new([U256::zero(); 1]),
}
}
}

impl<T, W> PartialEq for Program<T, W> {
Expand Down
1 change: 1 addition & 0 deletions crates/vm2/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ mod bytecode_behaviour;
mod far_call_decommitment;
mod panic;
mod stipend;
mod trace_failing_far_call;
97 changes: 97 additions & 0 deletions crates/vm2/src/tests/trace_failing_far_call.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
use zkevm_opcode_defs::ethereum_types::Address;

use crate::{
addressing_modes::{Arguments, Immediate1, Register, Register1, Register2},
interface::{
opcodes::Normal, CallingMode, GlobalStateInterface, Opcode, OpcodeType, ReturnType,
ShouldStop, Tracer,
},
testonly::{initial_decommit, TestWorld},
Instruction, ModeRequirements, Predicate, Program, Settings, VirtualMachine,
};

struct ExpectingTracer {
future: Vec<Opcode>,
current: Option<Opcode>,
}

impl ExpectingTracer {
fn new(mut opcodes: Vec<Opcode>) -> Self {
opcodes.reverse();
Self {
future: opcodes,
current: None,
}
}

fn witnessed_all_opcodes(self) -> bool {
self.future.is_empty() && self.current.is_none()
}
}

impl Tracer for ExpectingTracer {
fn before_instruction<OP: OpcodeType, S: GlobalStateInterface>(&mut self, _: &mut S) {
assert!(self.current.is_none(), "expected after_instruction");

let expected = self.future.pop().expect("expected program end");
assert_eq!(OP::VALUE, expected);
self.current = Some(expected);
}
fn after_instruction<OP: OpcodeType, S: GlobalStateInterface>(
&mut self,
_: &mut S,
) -> ShouldStop {
assert_eq!(
OP::VALUE,
self.current.take().expect("expected before_instruction")
);
ShouldStop::Continue
}
}

#[test]
fn trace_failing_far_call() {
let instructions = vec![
Instruction::from_far_call::<Normal>(
Register1(Register::new(0)),
Register2(Register::new(1)),
Immediate1(1),
false,
false,
Arguments::new(Predicate::Always, 25, ModeRequirements::none()),
),
Instruction::from_ret(
Register1(Register::new(0)),
None,
Arguments::new(Predicate::Always, 5, ModeRequirements::none()),
),
];

let program = Program::from_raw(instructions, vec![]);

let address = Address::from_low_u64_be(0x_1234_5678_90ab_cdef);
let mut world = TestWorld::new(&[(address, program)]);
let program = initial_decommit(&mut world, address);

let mut vm = VirtualMachine::new(
address,
program,
Address::zero(),
&[],
1000,
Settings {
default_aa_code_hash: [0; 32],
evm_interpreter_code_hash: [0; 32],
hook_address: 0,
},
);

let mut tracer = ExpectingTracer::new(vec![
Opcode::FarCall(CallingMode::Normal),
Opcode::Ret(ReturnType::Panic),
Opcode::Ret(ReturnType::Normal),
]);
vm.run(&mut world, &mut tracer);

assert!(tracer.witnessed_all_opcodes());
}
Loading