Skip to content

Commit f68bba9

Browse files
committed
test casting a dangling ptr back from an int
1 parent eee22ff commit f68bba9

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

tests/run-pass/intptrcast.rs

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,20 @@ fn cast() {
1212
assert_eq!(z, y % 256);
1313
}
1414

15+
/// Test usize->ptr cast for dangling and OOB address.
16+
/// That is safe, and thus has to work.
17+
fn cast_dangling() {
18+
let b = Box::new(0);
19+
let x = &*b as *const i32 as usize;
20+
drop(b);
21+
let _val = x as *const i32;
22+
23+
let b = Box::new(0);
24+
let mut x = &*b as *const i32 as usize;
25+
x += 0x100;
26+
let _val = x as *const i32;
27+
}
28+
1529
fn format() {
1630
// Pointer string formatting! We can't check the output as it changes when libstd changes,
1731
// but we can make sure Miri does not error.
@@ -47,8 +61,7 @@ fn ptr_eq_dangling() {
4761
drop(b);
4862
let b = Box::new(0);
4963
let y = &*b as *const i32; // different allocation
50-
// We cannot compare these even though both are inbounds -- they *could* be
51-
// equal if memory was reused.
64+
// They *could* be equal if memory was reused, but probably are not.
5265
assert!(x != y);
5366
}
5467

@@ -57,27 +70,27 @@ fn ptr_eq_out_of_bounds() {
5770
let x = (&*b as *const i32).wrapping_sub(0x800); // out-of-bounds
5871
let b = Box::new(0);
5972
let y = &*b as *const i32; // different allocation
60-
// We cannot compare these even though both allocations are live -- they *could* be
61-
// equal (with the right base addresses).
73+
// They *could* be equal (with the right base addresses), but probably are not.
6274
assert!(x != y);
6375
}
6476

6577
fn ptr_eq_out_of_bounds_null() {
6678
let b = Box::new(0);
6779
let x = (&*b as *const i32).wrapping_sub(0x800); // out-of-bounds
68-
// We cannot compare this with NULL. After all, this *could* be NULL (with the right base address).
80+
// This *could* be NULL (with the right base address), but probably is not.
6981
assert!(x != std::ptr::null());
7082
}
7183

7284
fn ptr_eq_integer() {
7385
let b = Box::new(0);
7486
let x = &*b as *const i32;
75-
// We cannot compare this with a non-NULL integer. After all, these *could* be equal (with the right base address).
87+
// These *could* be equal (with the right base address), but probably are not.
7688
assert!(x != 64 as *const i32);
7789
}
7890

7991
fn main() {
8092
cast();
93+
cast_dangling();
8194
format();
8295
transmute();
8396
ptr_bitops1();

0 commit comments

Comments
 (0)