Skip to content

Commit 454dec2

Browse files
committed
Auto merge of #117840 - RalfJung:miri-promise-align, r=cjgillot
miri: support 'promising' alignment for symbolic alignment check Then use that ability in `slice::align_to`, so that even with `-Zmiri-symbolic-alignment-check`, it no longer has to return spuriously empty "middle" parts. Fixes #3068
2 parents 52b9bc4 + b4b3ae4 commit 454dec2

9 files changed

+191
-96
lines changed

src/machine.rs

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
//! `Machine` trait.
33
44
use std::borrow::Cow;
5-
use std::cell::RefCell;
5+
use std::cell::{Cell, RefCell};
66
use std::fmt;
77
use std::path::Path;
88
use std::process;
@@ -309,11 +309,20 @@ pub struct AllocExtra<'tcx> {
309309
/// if this allocation is leakable. The backtrace is not
310310
/// pruned yet; that should be done before printing it.
311311
pub backtrace: Option<Vec<FrameInfo<'tcx>>>,
312+
/// An offset inside this allocation that was deemed aligned even for symbolic alignment checks.
313+
/// Invariant: the promised alignment will never be less than the native alignment of this allocation.
314+
pub symbolic_alignment: Cell<Option<(Size, Align)>>,
312315
}
313316

314317
impl VisitProvenance for AllocExtra<'_> {
315318
fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
316-
let AllocExtra { borrow_tracker, data_race, weak_memory, backtrace: _ } = self;
319+
let AllocExtra {
320+
borrow_tracker,
321+
data_race,
322+
weak_memory,
323+
backtrace: _,
324+
symbolic_alignment: _,
325+
} = self;
317326

318327
borrow_tracker.visit_provenance(visit);
319328
data_race.visit_provenance(visit);
@@ -907,8 +916,45 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
907916
}
908917

909918
#[inline(always)]
910-
fn use_addr_for_alignment_check(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
911-
ecx.machine.check_alignment == AlignmentCheck::Int
919+
fn alignment_check(
920+
ecx: &MiriInterpCx<'mir, 'tcx>,
921+
alloc_id: AllocId,
922+
alloc_align: Align,
923+
alloc_kind: AllocKind,
924+
offset: Size,
925+
align: Align,
926+
) -> Option<Misalignment> {
927+
if ecx.machine.check_alignment != AlignmentCheck::Symbolic {
928+
// Just use the built-in check.
929+
return None;
930+
}
931+
if alloc_kind != AllocKind::LiveData {
932+
// Can't have any extra info here.
933+
return None;
934+
}
935+
// Let's see which alignment we have been promised for this allocation.
936+
let alloc_info = ecx.get_alloc_extra(alloc_id).unwrap(); // cannot fail since the allocation is live
937+
let (promised_offset, promised_align) =
938+
alloc_info.symbolic_alignment.get().unwrap_or((Size::ZERO, alloc_align));
939+
if promised_align < align {
940+
// Definitely not enough.
941+
Some(Misalignment { has: promised_align, required: align })
942+
} else {
943+
// What's the offset between us and the promised alignment?
944+
let distance = offset.bytes().wrapping_sub(promised_offset.bytes());
945+
// That must also be aligned.
946+
if distance % align.bytes() == 0 {
947+
// All looking good!
948+
None
949+
} else {
950+
// The biggest power of two through which `distance` is divisible.
951+
let distance_pow2 = 1 << distance.trailing_zeros();
952+
Some(Misalignment {
953+
has: Align::from_bytes(distance_pow2).unwrap(),
954+
required: align,
955+
})
956+
}
957+
}
912958
}
913959

914960
#[inline(always)]
@@ -1112,6 +1158,7 @@ impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
11121158
data_race: race_alloc,
11131159
weak_memory: buffer_alloc,
11141160
backtrace,
1161+
symbolic_alignment: Cell::new(None),
11151162
},
11161163
|ptr| ecx.global_base_pointer(ptr),
11171164
)?;

src/shims/foreign_items.rs

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -467,7 +467,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
467467
let ptr = this.read_pointer(ptr)?;
468468
let (alloc_id, _, _) = this.ptr_get_alloc_id(ptr).map_err(|_e| {
469469
err_machine_stop!(TerminationInfo::Abort(format!(
470-
"pointer passed to miri_get_alloc_id must not be dangling, got {ptr:?}"
470+
"pointer passed to `miri_get_alloc_id` must not be dangling, got {ptr:?}"
471471
)))
472472
})?;
473473
this.write_scalar(Scalar::from_u64(alloc_id.0.get()), dest)?;
@@ -499,7 +499,7 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
499499
let (alloc_id, offset, _) = this.ptr_get_alloc_id(ptr)?;
500500
if offset != Size::ZERO {
501501
throw_unsup_format!(
502-
"pointer passed to miri_static_root must point to beginning of an allocated block"
502+
"pointer passed to `miri_static_root` must point to beginning of an allocated block"
503503
);
504504
}
505505
this.machine.static_roots.push(alloc_id);
@@ -556,6 +556,39 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
556556
};
557557
}
558558

559+
// Promises that a pointer has a given symbolic alignment.
560+
"miri_promise_symbolic_alignment" => {
561+
let [ptr, align] = this.check_shim(abi, Abi::Rust, link_name, args)?;
562+
let ptr = this.read_pointer(ptr)?;
563+
let align = this.read_target_usize(align)?;
564+
let Ok(align) = Align::from_bytes(align) else {
565+
throw_unsup_format!(
566+
"`miri_promise_symbolic_alignment`: alignment must be a power of 2"
567+
);
568+
};
569+
let (_, addr) = ptr.into_parts(); // we know the offset is absolute
570+
if addr.bytes() % align.bytes() != 0 {
571+
throw_unsup_format!(
572+
"`miri_promise_symbolic_alignment`: pointer is not actually aligned"
573+
);
574+
}
575+
if let Ok((alloc_id, offset, ..)) = this.ptr_try_get_alloc_id(ptr) {
576+
let (_size, alloc_align, _kind) = this.get_alloc_info(alloc_id);
577+
// Not `get_alloc_extra_mut`, need to handle read-only allocations!
578+
let alloc_extra = this.get_alloc_extra(alloc_id)?;
579+
// If the newly promised alignment is bigger than the native alignment of this
580+
// allocation, and bigger than the previously promised alignment, then set it.
581+
if align > alloc_align
582+
&& !alloc_extra
583+
.symbolic_alignment
584+
.get()
585+
.is_some_and(|(_, old_align)| align <= old_align)
586+
{
587+
alloc_extra.symbolic_alignment.set(Some((offset, align)));
588+
}
589+
}
590+
}
591+
559592
// Standard C allocation
560593
"malloc" => {
561594
let [size] = this.check_shim(abi, Abi::C { unwind: false }, link_name, args)?;

src/shims/mod.rs

Lines changed: 1 addition & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ use rustc_middle::{mir, ty};
2323
use rustc_target::spec::abi::Abi;
2424

2525
use crate::*;
26-
use helpers::check_arg_count;
2726

2827
impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
2928
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
@@ -39,16 +38,7 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
3938
let this = self.eval_context_mut();
4039
trace!("eval_fn_call: {:#?}, {:?}", instance, dest);
4140

42-
// There are some more lang items we want to hook that CTFE does not hook (yet).
43-
if this.tcx.lang_items().align_offset_fn() == Some(instance.def.def_id()) {
44-
let args = this.copy_fn_args(args)?;
45-
let [ptr, align] = check_arg_count(&args)?;
46-
if this.align_offset(ptr, align, dest, ret, unwind)? {
47-
return Ok(None);
48-
}
49-
}
50-
51-
// Try to see if we can do something about foreign items.
41+
// For foreign items, try to see if we can emulate them.
5242
if this.tcx.is_foreign_item(instance.def_id()) {
5343
// An external function call that does not have a MIR body. We either find MIR elsewhere
5444
// or emulate its effect.
@@ -64,53 +54,4 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
6454
// Otherwise, load the MIR.
6555
Ok(Some((this.load_mir(instance.def, None)?, instance)))
6656
}
67-
68-
/// Returns `true` if the computation was performed, and `false` if we should just evaluate
69-
/// the actual MIR of `align_offset`.
70-
fn align_offset(
71-
&mut self,
72-
ptr_op: &OpTy<'tcx, Provenance>,
73-
align_op: &OpTy<'tcx, Provenance>,
74-
dest: &PlaceTy<'tcx, Provenance>,
75-
ret: Option<mir::BasicBlock>,
76-
unwind: mir::UnwindAction,
77-
) -> InterpResult<'tcx, bool> {
78-
let this = self.eval_context_mut();
79-
let ret = ret.unwrap();
80-
81-
if this.machine.check_alignment != AlignmentCheck::Symbolic {
82-
// Just use actual implementation.
83-
return Ok(false);
84-
}
85-
86-
let req_align = this.read_target_usize(align_op)?;
87-
88-
// Stop if the alignment is not a power of two.
89-
if !req_align.is_power_of_two() {
90-
this.start_panic("align_offset: align is not a power-of-two", unwind)?;
91-
return Ok(true); // nothing left to do
92-
}
93-
94-
let ptr = this.read_pointer(ptr_op)?;
95-
// If this carries no provenance, treat it like an integer.
96-
if ptr.provenance.is_none() {
97-
// Use actual implementation.
98-
return Ok(false);
99-
}
100-
101-
if let Ok((alloc_id, _offset, _)) = this.ptr_try_get_alloc_id(ptr) {
102-
// Only do anything if we can identify the allocation this goes to.
103-
let (_size, cur_align, _kind) = this.get_alloc_info(alloc_id);
104-
if cur_align.bytes() >= req_align {
105-
// If the allocation alignment is at least the required alignment we use the
106-
// real implementation.
107-
return Ok(false);
108-
}
109-
}
110-
111-
// Return error result (usize::MAX), and jump to caller.
112-
this.write_scalar(Scalar::from_target_usize(this.target_usize_max(), this), dest)?;
113-
this.go_to_block(ret);
114-
Ok(true)
115-
}
11657
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
error: unsupported operation: `miri_promise_symbolic_alignment`: pointer is not actually aligned
2+
--> $DIR/promise_alignment.rs:LL:CC
3+
|
4+
LL | unsafe { utils::miri_promise_symbolic_alignment(align8.add(1).cast(), 8) };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `miri_promise_symbolic_alignment`: pointer is not actually aligned
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/promise_alignment.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 1 previous error
14+
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
error: Undefined Behavior: accessing memory based on pointer with alignment ALIGN, but alignment ALIGN is required
2+
--> $DIR/promise_alignment.rs:LL:CC
3+
|
4+
LL | let _val = unsafe { align8.cast::<Align16>().read() };
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ accessing memory based on pointer with alignment ALIGN, but alignment ALIGN is required
6+
|
7+
= help: this usually indicates that your program performed an invalid operation and caused Undefined Behavior
8+
= help: but due to `-Zmiri-symbolic-alignment-check`, alignment errors can also be false positives
9+
= note: BACKTRACE:
10+
= note: inside `main` at $DIR/promise_alignment.rs:LL:CC
11+
12+
note: some details are omitted, run with `MIRIFLAGS=-Zmiri-backtrace=full` for a verbose backtrace
13+
14+
error: aborting due to 1 previous error
15+
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
//@compile-flags: -Zmiri-symbolic-alignment-check
2+
//@revisions: call_unaligned_ptr read_unaligned_ptr
3+
#![feature(strict_provenance)]
4+
5+
#[path = "../../utils/mod.rs"]
6+
mod utils;
7+
8+
#[repr(align(8))]
9+
#[derive(Copy, Clone)]
10+
struct Align8(u64);
11+
12+
fn main() {
13+
let buffer = [0u32; 128]; // get some 4-aligned memory
14+
let buffer = buffer.as_ptr();
15+
// "Promising" the alignment down to 1 must not hurt.
16+
unsafe { utils::miri_promise_symbolic_alignment(buffer.cast(), 1) };
17+
let _val = unsafe { buffer.read() };
18+
19+
// Let's find a place to promise alignment 8.
20+
let align8 = if buffer.addr() % 8 == 0 {
21+
buffer
22+
} else {
23+
buffer.wrapping_add(1)
24+
};
25+
assert!(align8.addr() % 8 == 0);
26+
unsafe { utils::miri_promise_symbolic_alignment(align8.cast(), 8) };
27+
// Promising the alignment down to 1 *again* still must not hurt.
28+
unsafe { utils::miri_promise_symbolic_alignment(buffer.cast(), 1) };
29+
// Now we can do 8-aligned reads here.
30+
let _val = unsafe { align8.cast::<Align8>().read() };
31+
32+
// Make sure we error if the pointer is not actually aligned.
33+
if cfg!(call_unaligned_ptr) {
34+
unsafe { utils::miri_promise_symbolic_alignment(align8.add(1).cast(), 8) };
35+
//~[call_unaligned_ptr]^ ERROR: pointer is not actually aligned
36+
}
37+
38+
// Also don't accept even higher-aligned reads.
39+
if cfg!(read_unaligned_ptr) {
40+
#[repr(align(16))]
41+
#[derive(Copy, Clone)]
42+
struct Align16(u128);
43+
44+
let align16 = if align8.addr() % 16 == 0 {
45+
align8
46+
} else {
47+
align8.wrapping_add(2)
48+
};
49+
assert!(align16.addr() % 16 == 0);
50+
51+
let _val = unsafe { align8.cast::<Align16>().read() };
52+
//~[read_unaligned_ptr]^ ERROR: accessing memory based on pointer with alignment 8, but alignment 16 is required
53+
}
54+
}

tests/pass/align_offset_symbolic.rs

Lines changed: 15 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,15 @@
11
//@compile-flags: -Zmiri-symbolic-alignment-check
22
#![feature(strict_provenance)]
33

4-
use std::ptr;
5-
6-
fn test_align_offset() {
7-
let d = Box::new([0u32; 4]);
8-
// Get u8 pointer to base
9-
let raw = d.as_ptr() as *const u8;
10-
11-
assert_eq!(raw.align_offset(2), 0);
12-
assert_eq!(raw.align_offset(4), 0);
13-
assert_eq!(raw.align_offset(8), usize::MAX); // requested alignment higher than allocation alignment
14-
15-
assert_eq!(raw.wrapping_offset(1).align_offset(2), 1);
16-
assert_eq!(raw.wrapping_offset(1).align_offset(4), 3);
17-
assert_eq!(raw.wrapping_offset(1).align_offset(8), usize::MAX); // requested alignment higher than allocation alignment
18-
19-
assert_eq!(raw.wrapping_offset(2).align_offset(2), 0);
20-
assert_eq!(raw.wrapping_offset(2).align_offset(4), 2);
21-
assert_eq!(raw.wrapping_offset(2).align_offset(8), usize::MAX); // requested alignment higher than allocation alignment
22-
23-
let p = ptr::invalid::<()>(1);
24-
assert_eq!(p.align_offset(1), 0);
25-
}
26-
274
fn test_align_to() {
285
const N: usize = 4;
296
let d = Box::new([0u32; N]);
307
// Get u8 slice covering the entire thing
318
let s = unsafe { std::slice::from_raw_parts(d.as_ptr() as *const u8, 4 * N) };
329
let raw = s.as_ptr();
3310

11+
// Cases where we get the expected "middle" part without any fuzz, since the allocation is
12+
// 4-aligned.
3413
{
3514
let (l, m, r) = unsafe { s.align_to::<u32>() };
3615
assert_eq!(l.len(), 0);
@@ -63,18 +42,21 @@ fn test_align_to() {
6342
assert_eq!(raw.wrapping_offset(4), m.as_ptr() as *const u8);
6443
}
6544

45+
// Cases where we request more alignment than the allocation has.
6646
{
6747
#[repr(align(8))]
48+
#[derive(Copy, Clone)]
6849
struct Align8(u64);
6950

70-
let (l, m, r) = unsafe { s.align_to::<Align8>() }; // requested alignment higher than allocation alignment
71-
assert_eq!(l.len(), 4 * N);
72-
assert_eq!(r.len(), 0);
73-
assert_eq!(m.len(), 0);
51+
let (_l, m, _r) = unsafe { s.align_to::<Align8>() };
52+
assert!(m.len() > 0);
53+
// Ensure the symbolic alignment check has been informed that this is okay now.
54+
let _val = m[0];
7455
}
7556
}
7657

7758
fn test_from_utf8() {
59+
// uses `align_offset` internally
7860
const N: usize = 10;
7961
let vec = vec![0x4141414141414141u64; N];
8062
let content = unsafe { std::slice::from_raw_parts(vec.as_ptr() as *const u8, 8 * N) };
@@ -103,9 +85,14 @@ fn test_u64_array() {
10385
example(&Data::default());
10486
}
10587

88+
fn test_cstr() {
89+
// uses `align_offset` internally
90+
std::ffi::CStr::from_bytes_with_nul(b"this is a test that is longer than 16 bytes\0").unwrap();
91+
}
92+
10693
fn main() {
107-
test_align_offset();
10894
test_align_to();
10995
test_from_utf8();
11096
test_u64_array();
97+
test_cstr();
11198
}

0 commit comments

Comments
 (0)