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(levm): handle sdiv with zero dividend and negative divisor #1241

Merged
merged 4 commits into from
Nov 25, 2024
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
21 changes: 11 additions & 10 deletions crates/vm/levm/src/opcode_handlers/arithmetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ impl VM {

let dividend = current_call_frame.stack.pop()?;
let divisor = current_call_frame.stack.pop()?;
if divisor.is_zero() {
if divisor.is_zero() || dividend.is_zero() {
current_call_frame.stack.push(U256::zero())?;
return Ok(OpcodeSuccess::Continue);
}
Expand All @@ -92,15 +92,16 @@ impl VM {
} else {
divisor
};
let Some(quotient) = dividend.checked_div(divisor) else {
current_call_frame.stack.push(U256::zero())?;
return Ok(OpcodeSuccess::Continue);
};
let quotient_is_negative = dividend_is_negative ^ divisor_is_negative;
let quotient = if quotient_is_negative {
negate(quotient)
} else {
quotient
let quotient = match dividend.checked_div(divisor) {
Some(quot) => {
let quotient_is_negative = dividend_is_negative ^ divisor_is_negative;
if quotient_is_negative {
negate(quot)
} else {
quot
}
}
None => U256::zero(),
};

current_call_frame.stack.push(quotient)?;
Expand Down
13 changes: 13 additions & 0 deletions crates/vm/levm/tests/edge_case_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,16 @@ fn test_is_negative() {
let mut current_call_frame = vm.call_frames.pop().unwrap();
vm.execute(&mut current_call_frame);
}

#[test]
fn test_sdiv_zero_dividend_and_negative_divisor() {
let mut vm = new_vm_with_bytecode(Bytes::copy_from_slice(&[
0x7F, 0xC5, 0xD2, 0x46, 0x01, 0x86, 0xF7, 0x23, 0x3C, 0x92, 0x7E, 0x7D, 0xB2, 0xDC, 0xC7,
0x03, 0xC0, 0xE5, 0x00, 0xB6, 0x53, 0xCA, 0x82, 0x27, 0x3B, 0x7B, 0xFA, 0xD8, 0x04, 0x5D,
0x85, 0xA4, 0x70, 0x5F, 0x05,
]))
.unwrap();
let mut current_call_frame = vm.call_frames.pop().unwrap();
vm.execute(&mut current_call_frame);
assert_eq!(current_call_frame.stack.pop().unwrap(), U256::zero());
}
Loading