Skip to content

Commit be15a1e

Browse files
authored
Merge pull request #535 from farnz/checked_add_addrs
Ensure that addition and subtraction of addresses panics on overflow/underflow
2 parents dc43e5a + c36cfb4 commit be15a1e

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/addr.rs

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ impl Add<u64> for VirtAddr {
366366
type Output = Self;
367367
#[inline]
368368
fn add(self, rhs: u64) -> Self::Output {
369-
VirtAddr::new(self.0 + rhs)
369+
VirtAddr::new(self.0.checked_add(rhs).unwrap())
370370
}
371371
}
372372

@@ -593,7 +593,7 @@ impl Add<u64> for PhysAddr {
593593
type Output = Self;
594594
#[inline]
595595
fn add(self, rhs: u64) -> Self::Output {
596-
PhysAddr::new(self.0 + rhs)
596+
PhysAddr::new(self.0.checked_add(rhs).unwrap())
597597
}
598598
}
599599

@@ -663,6 +663,30 @@ pub const fn align_up(addr: u64, align: u64) -> u64 {
663663
mod tests {
664664
use super::*;
665665

666+
#[test]
667+
#[should_panic]
668+
pub fn add_overflow_virtaddr() {
669+
let _ = VirtAddr::new(0xffff_ffff_ffff_ffff) + 1;
670+
}
671+
672+
#[test]
673+
#[should_panic]
674+
pub fn add_overflow_physaddr() {
675+
let _ = PhysAddr::new(0x000f_ffff_ffff_ffff) + 0xffff_0000_0000_0000;
676+
}
677+
678+
#[test]
679+
#[should_panic]
680+
pub fn sub_underflow_virtaddr() {
681+
let _ = VirtAddr::new(0) - 1;
682+
}
683+
684+
#[test]
685+
#[should_panic]
686+
pub fn sub_overflow_physaddr() {
687+
let _ = PhysAddr::new(0) - 1;
688+
}
689+
666690
#[test]
667691
pub fn virtaddr_new_truncate() {
668692
assert_eq!(VirtAddr::new_truncate(0), VirtAddr(0));

0 commit comments

Comments
 (0)