Skip to content

Commit 872bea4

Browse files
committed
Auto merge of #2516 - RalfJung:read-pointer-as-bytes, r=RalfJung
Adjust for supporting more implicit ptr-to-int transmutation This is the Miri side of rust-lang/rust#101101. Fixes #2456.
2 parents da45adc + d936f3a commit 872bea4

19 files changed

+126
-78
lines changed

rust-version

+1-1
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
94b2b15e63c5d2b2a6a0910e3dae554ce9415bf9
1+
0631ea5d73f4a3199c776687b12c20c50a91f0d2

src/diagnostics.rs

+4-3
Original file line numberDiff line numberDiff line change
@@ -224,13 +224,14 @@ pub fn report_error<'tcx, 'mir>(
224224
let helps = match e.kind() {
225225
Unsupported(
226226
UnsupportedOpInfo::ThreadLocalStatic(_) |
227-
UnsupportedOpInfo::ReadExternStatic(_)
227+
UnsupportedOpInfo::ReadExternStatic(_) |
228+
UnsupportedOpInfo::PartialPointerOverwrite(_) | // we make memory uninit instead
229+
UnsupportedOpInfo::ReadPointerAsBytes
228230
) =>
229231
panic!("Error should never be raised by Miri: {kind:?}", kind = e.kind()),
230232
Unsupported(
231233
UnsupportedOpInfo::Unsupported(_) |
232-
UnsupportedOpInfo::PartialPointerOverwrite(_) |
233-
UnsupportedOpInfo::ReadPointerAsBytes
234+
UnsupportedOpInfo::PartialPointerCopy(_)
234235
) =>
235236
vec![(None, format!("this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support"))],
236237
UndefinedBehavior(UndefinedBehaviorInfo::AlignmentCheckFailed { .. })

src/helpers.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -757,7 +757,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
757757
}
758758

759759
// Step 2: get the bytes.
760-
this.read_bytes_ptr(ptr, len)
760+
this.read_bytes_ptr_strip_provenance(ptr, len)
761761
}
762762

763763
fn read_wide_str(&self, mut ptr: Pointer<Option<Provenance>>) -> InterpResult<'tcx, Vec<u16>> {

src/machine.rs

+15
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,21 @@ impl interpret::Provenance for Provenance {
205205
Provenance::Wildcard => None,
206206
}
207207
}
208+
209+
fn join(left: Option<Self>, right: Option<Self>) -> Option<Self> {
210+
match (left, right) {
211+
// If both are the *same* concrete tag, that is the result.
212+
(
213+
Some(Provenance::Concrete { alloc_id: left_alloc, sb: left_sb }),
214+
Some(Provenance::Concrete { alloc_id: right_alloc, sb: right_sb }),
215+
) if left_alloc == right_alloc && left_sb == right_sb => left,
216+
// If one side is a wildcard, the best possible outcome is that it is equal to the other
217+
// one, and we use that.
218+
(Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o,
219+
// Otherwise, fall back to `None`.
220+
_ => None,
221+
}
222+
}
208223
}
209224

210225
impl fmt::Debug for ProvenanceExtra {

src/shims/foreign_items.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -560,8 +560,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
560560
let n = Size::from_bytes(this.read_scalar(n)?.to_machine_usize(this)?);
561561

562562
let result = {
563-
let left_bytes = this.read_bytes_ptr(left, n)?;
564-
let right_bytes = this.read_bytes_ptr(right, n)?;
563+
let left_bytes = this.read_bytes_ptr_strip_provenance(left, n)?;
564+
let right_bytes = this.read_bytes_ptr_strip_provenance(right, n)?;
565565

566566
use std::cmp::Ordering::*;
567567
match left_bytes.cmp(right_bytes) {
@@ -583,7 +583,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
583583
let val = val as u8;
584584

585585
if let Some(idx) = this
586-
.read_bytes_ptr(ptr, Size::from_bytes(num))?
586+
.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
587587
.iter()
588588
.rev()
589589
.position(|&c| c == val)
@@ -606,7 +606,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
606606
let val = val as u8;
607607

608608
let idx = this
609-
.read_bytes_ptr(ptr, Size::from_bytes(num))?
609+
.read_bytes_ptr_strip_provenance(ptr, Size::from_bytes(num))?
610610
.iter()
611611
.position(|&c| c == val);
612612
if let Some(idx) = idx {

src/shims/unix/fs.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -761,7 +761,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
761761
let communicate = this.machine.communicate();
762762

763763
if let Some(file_descriptor) = this.machine.file_handler.handles.get(&fd) {
764-
let bytes = this.read_bytes_ptr(buf, Size::from_bytes(count))?;
764+
let bytes = this.read_bytes_ptr_strip_provenance(buf, Size::from_bytes(count))?;
765765
let result =
766766
file_descriptor.write(communicate, bytes)?.map(|c| i64::try_from(c).unwrap());
767767
this.try_unwrap_io_result(result)

src/shims/windows/dlsym.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx
7878
// stdout/stderr
7979
use std::io::{self, Write};
8080

81-
let buf_cont = this.read_bytes_ptr(buf, Size::from_bytes(u64::from(n)))?;
81+
let buf_cont =
82+
this.read_bytes_ptr_strip_provenance(buf, Size::from_bytes(u64::from(n)))?;
8283
let res = if this.machine.mute_stdout_stderr {
8384
Ok(buf_cont.len())
8485
} else if handle == -11 {

tests/fail/copy_half_a_pointer.rs

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#![allow(dead_code)]
2+
3+
// We use packed structs to get around alignment restrictions
4+
#[repr(packed)]
5+
struct Data {
6+
pad: u8,
7+
ptr: &'static i32,
8+
}
9+
10+
static G: i32 = 0;
11+
12+
fn main() {
13+
let mut d = Data { pad: 0, ptr: &G };
14+
15+
// Get a pointer to the beginning of the Data struct (one u8 byte, then the pointer bytes).
16+
let d_alias = &mut d as *mut _ as *mut *const u8;
17+
unsafe {
18+
let _x = d_alias.read_unaligned(); //~ERROR: unable to copy parts of a pointer
19+
}
20+
}

tests/fail/copy_half_a_pointer.stderr

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error: unsupported operation: unable to copy parts of a pointer from memory at ALLOC+0x8
2+
--> $DIR/copy_half_a_pointer.rs:LL:CC
3+
|
4+
LL | let _x = d_alias.read_unaligned();
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^ unable to copy parts of a pointer from memory at ALLOC+0x8
6+
|
7+
= help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support
8+
= note: backtrace:
9+
= note: inside `main` at $DIR/copy_half_a_pointer.rs:LL:CC
10+
11+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
12+
13+
error: aborting due to previous error
14+

tests/fail/intrinsics/raw_eq_on_ptr.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,5 @@ extern "rust-intrinsic" {
66

77
fn main() {
88
let x = &0;
9-
// FIXME: the error message is not great (should be UB rather than 'unsupported')
10-
unsafe { raw_eq(&x, &x) }; //~ERROR: unsupported operation
9+
unsafe { raw_eq(&x, &x) }; //~ERROR: `raw_eq` on bytes with provenance
1110
}

tests/fail/intrinsics/raw_eq_on_ptr.stderr

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
error: unsupported operation: unable to turn pointer into raw bytes
1+
error: Undefined Behavior: `raw_eq` on bytes with provenance
22
--> $DIR/raw_eq_on_ptr.rs:LL:CC
33
|
44
LL | unsafe { raw_eq(&x, &x) };
5-
| ^^^^^^^^^^^^^^ unable to turn pointer into raw bytes
5+
| ^^^^^^^^^^^^^^ `raw_eq` on bytes with provenance
66
|
7-
= help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support
7+
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
8+
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
89
= note: backtrace:
910
= note: inside `main` at $DIR/raw_eq_on_ptr.rs:LL:CC
1011

tests/fail/reading_half_a_pointer.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ fn main() {
2424
// starts 1 byte to the right, so using it would actually be wrong!
2525
let d_alias = &mut w.data as *mut _ as *mut *const u8;
2626
unsafe {
27-
let _x = *d_alias; //~ ERROR: unable to turn pointer into raw bytes
27+
let x = *d_alias;
28+
let _val = *x; //~ERROR: is a dangling pointer (it has no provenance)
2829
}
2930
}

tests/fail/reading_half_a_pointer.stderr

+5-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
error: unsupported operation: unable to turn pointer into raw bytes
1+
error: Undefined Behavior: dereferencing pointer failed: $HEX[noalloc] is a dangling pointer (it has no provenance)
22
--> $DIR/reading_half_a_pointer.rs:LL:CC
33
|
4-
LL | let _x = *d_alias;
5-
| ^^^^^^^^ unable to turn pointer into raw bytes
4+
LL | let _val = *x;
5+
| ^^ dereferencing pointer failed: $HEX[noalloc] is a dangling pointer (it has no provenance)
66
|
7-
= help: this is likely not a bug in the program; it indicates that the program performed an operation that the interpreter does not support
7+
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
8+
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
89
= note: backtrace:
910
= note: inside `main` at $DIR/reading_half_a_pointer.rs:LL:CC
1011

tests/fail/transmute_fat1.rs

-13
This file was deleted.

tests/fail/transmute_fat1.stderr

-15
This file was deleted.

tests/fail/validity/ptr_integer_array_transmute.rs

-4
This file was deleted.

tests/fail/validity/ptr_integer_array_transmute.stderr

-15
This file was deleted.

tests/pass/transmute_fat.rs

-10
This file was deleted.

tests/pass/transmute_ptr.rs

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
#![feature(strict_provenance)]
2+
use std::{mem, ptr};
3+
4+
fn t1() {
5+
// If we are careful, we can exploit data layout...
6+
// This is a tricky case since we are transmuting a ScalarPair type to a non-ScalarPair type.
7+
let raw = unsafe { mem::transmute::<&[u8], [*const u8; 2]>(&[42]) };
8+
let ptr: *const u8 = unsafe { mem::transmute_copy(&raw) };
9+
assert_eq!(unsafe { *ptr }, 42);
10+
}
11+
12+
#[cfg(target_pointer_width = "64")]
13+
const PTR_SIZE: usize = 8;
14+
#[cfg(target_pointer_width = "32")]
15+
const PTR_SIZE: usize = 4;
16+
17+
fn t2() {
18+
let bad = unsafe { mem::transmute::<&[u8], [u8; 2 * PTR_SIZE]>(&[1u8]) };
19+
let _val = bad[0] + bad[bad.len() - 1];
20+
}
21+
22+
fn ptr_integer_array() {
23+
let r = &mut 42;
24+
let _i: [usize; 1] = unsafe { mem::transmute(r) };
25+
26+
let _x: [u8; PTR_SIZE] = unsafe { mem::transmute(&0) };
27+
}
28+
29+
fn ptr_in_two_halves() {
30+
unsafe {
31+
let ptr = &0 as *const i32;
32+
let arr = [ptr; 2];
33+
// We want to do a scalar read of a pointer at offset PTR_SIZE/2 into this array. But we
34+
// cannot use a packed struct or `read_unaligned`, as those use the memcpy code path in
35+
// Miri. So instead we shift the entire array by a bit and then the actual read we want to
36+
// do is perfectly aligned.
37+
let mut target_arr = [ptr::null::<i32>(); 3];
38+
let target = target_arr.as_mut_ptr().cast::<u8>();
39+
target.add(PTR_SIZE / 2).cast::<[*const i32; 2]>().write_unaligned(arr);
40+
// Now target_arr[1] is a mix of the two `ptr` we had stored in `arr`.
41+
let strange_ptr = target_arr[1];
42+
// Check that the provenance works out.
43+
assert_eq!(*strange_ptr.with_addr(ptr.addr()), 0);
44+
}
45+
}
46+
47+
fn main() {
48+
t1();
49+
t2();
50+
ptr_integer_array();
51+
ptr_in_two_halves();
52+
}

0 commit comments

Comments
 (0)