Skip to content

Commit

Permalink
Explicitly use u64 operations for safe u8 arithmetic
Browse files Browse the repository at this point in the history
Fixes #5449

Without this fix, because we use `u8` load and store instructions,
the overflow check (which relies on `u64` arithmetic) gets nullified.
  • Loading branch information
vaivaswatha committed Jan 24, 2024
1 parent c43b57f commit 596b842
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 8 deletions.
34 changes: 28 additions & 6 deletions sway-lib-core/src/ops.sw
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,22 @@ impl Add for u16 {

impl Add for u8 {
fn add(self, other: Self) -> Self {
let res = __add(self, other);
if __gt(res, Self::max()) {
let self_u64 = asm(input: self) {
input: u64
};
let other_u64 = asm(input: other) {
input: u64
};
let res_u64 = __add(self_u64, other_u64);
let max_u8_u64 = asm(input: Self::max()) {
input: u64
};
if __gt(res_u64, max_u8_u64) {
__revert(0)
} else {
res
asm(input: res_u64) {
input: u8
}
}
}
}
Expand Down Expand Up @@ -239,11 +250,22 @@ impl Multiply for u16 {

impl Multiply for u8 {
fn multiply(self, other: Self) -> Self {
let res = __mul(self, other);
if __gt(res, Self::max()) {
let self_u64 = asm(input: self) {
input: u64
};
let other_u64 = asm(input: other) {
input: u64
};
let res_u64 = __mul(self_u64, other_u64);
let max_u8_u64 = asm(input: Self::max()) {
input: u64
};
if __gt(res_u64, max_u8_u64) {
__revert(0)
} else {
res
asm(input: res_u64) {
input: u8
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
category = "disabled"
category = "run"
expected_result = { action = "revert", value = 0 }
validate_abi = false
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
category = "disabled"
category = "run"
expected_result = { action = "revert", value = 0 }
validate_abi = false

0 comments on commit 596b842

Please sign in to comment.