Add checks and tests for computing abs(offset_bytes)

The previous code paniced if offset_bytes == i64::MIN. This commit:
  - Properly computes the absoulte value to avoid this panic
  - Adds a test for this edge case

Signed-off-by: Joe Richey <joerichey@google.com>
This commit is contained in:
Joe Richey 2020-05-26 02:00:02 -07:00
parent 6367b544b7
commit 71ef8414bd
3 changed files with 22 additions and 3 deletions

View file

@ -19,4 +19,7 @@ pub const DANGLING: *const u8 = unsafe { ptr::NonNull::<u8>::dangling().as_ptr()
// Right now, a zero offset from null is UB
pub const NULL_OFFSET_ZERO: *const u8 = unsafe { ptr::null::<u8>().offset(0) }; //~NOTE
// Make sure that we don't panic when computing abs(offset*size_of::<T>())
pub const UNDERFLOW_ABS: *const u8 = unsafe { (usize::MAX as *const u8).offset(isize::MIN) }; //~NOTE
fn main() {}

View file

@ -150,5 +150,20 @@ LL | intrinsics::offset(self, count)
LL | pub const NULL_OFFSET_ZERO: *const u8 = unsafe { ptr::null::<u8>().offset(0) };
| -------------------------------------------------------------------------------
error: aborting due to 10 previous errors
error: any use of this value will cause an error
--> $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL
|
LL | intrinsics::offset(self, count)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| unable to turn bytes into a pointer
| inside `std::ptr::const_ptr::<impl *const u8>::offset` at $SRC_DIR/libcore/ptr/const_ptr.rs:LL:COL
| inside `UNDERFLOW_ABS` at $DIR/offset_ub.rs:23:47
|
::: $DIR/offset_ub.rs:23:1
|
LL | pub const UNDERFLOW_ABS: *const u8 = unsafe { (usize::MAX as *const u8).offset(isize::MIN) };
| ---------------------------------------------------------------------------------------------
error: aborting due to 11 previous errors