Skip to content

Commit

Permalink
fix: crash VM when executing swap 0
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-ferdinand committed Oct 17, 2023
1 parent 92d63cd commit 215f2ed
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
16 changes: 16 additions & 0 deletions triton-vm/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub enum InstructionError {
JumpStackIsEmpty,
AssertionFailed(usize, u32, BFieldElement),
VectorAssertionFailed(usize, u32, OpStackElement, BFieldElement, BFieldElement),
SwapST0,
InverseOfZero,
DivisionByZero,
LogarithmOfZero,
Expand All @@ -43,6 +44,7 @@ impl Display for InstructionError {
write!(f, "{rhs} == op_stack[{failing_index_rhs}]. ")?;
write!(f, "ip: {ip}, clk: {clk}")
}
SwapST0 => write!(f, "Cannot swap stack element 0 with itself"),
InverseOfZero => write!(f, "0 does not have a multiplicative inverse"),
DivisionByZero => write!(f, "Division by 0 is impossible"),
LogarithmOfZero => write!(f, "The logarithm of 0 does not exist"),
Expand All @@ -61,7 +63,11 @@ mod tests {
use proptest::prelude::*;
use proptest_arbitrary_interop::arb;

use crate::instruction::AnInstruction::*;
use crate::instruction::LabelledInstruction;
use crate::op_stack::OpStackElement::ST0;
use crate::triton_program;
use crate::Program;

use super::*;

Expand Down Expand Up @@ -111,6 +117,16 @@ mod tests {
program.run([].into(), [].into()).unwrap();
}

#[test]
#[should_panic(expected = "swap stack element 0")]
fn swap_st0() {
// The parser rejects this program. Therefore, construct it manually.
let swap_0 = LabelledInstruction::Instruction(Swap(ST0));
let halt = LabelledInstruction::Instruction(Halt);
let program = Program::new(&[swap_0, halt]);
program.run([].into(), [].into()).unwrap();
}

proptest! {
#[test]
fn assert_unequal_vec(
Expand Down
9 changes: 6 additions & 3 deletions triton-vm/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,7 +217,7 @@ impl<'pgm> VMState<'pgm> {
Push(field_element) => self.push(field_element),
Divine => self.divine()?,
Dup(stack_element) => self.dup(stack_element),
Swap(stack_element) => self.swap(stack_element),
Swap(stack_element) => self.swap(stack_element)?,
Nop => self.nop(),
Skiz => self.skiz()?,
Call(address) => self.call(address),
Expand Down Expand Up @@ -289,10 +289,13 @@ impl<'pgm> VMState<'pgm> {
None
}

fn swap(&mut self, stack_register: OpStackElement) -> Option<CoProcessorCall> {
fn swap(&mut self, stack_register: OpStackElement) -> Result<Option<CoProcessorCall>> {
if stack_register == ST0 {
bail!(SwapST0);
}
self.op_stack.swap_top_with(stack_register);
self.instruction_pointer += 2;
None
Ok(None)
}

fn nop(&mut self) -> Option<CoProcessorCall> {
Expand Down

0 comments on commit 215f2ed

Please sign in to comment.