Skip to content

Commit cb580ff

Browse files
committed
Auto merge of rust-lang#122243 - RalfJung:local-place-sanity-check, r=oli-obk
interpret: ensure that Place is never used for a different frame We store the address where the stack frame stores its `locals`. The idea is that even if we pop and push, or switch to a different thread with a larger number of frames, then the `locals` address will most likely change so we'll notice that problem. This is made possible by some recent changes by `@WaffleLapkin,` where we no longer use `Place` across things that change the number of stack frames. I made these debug assertions for now, just to make sure this can't cost us any perf. The first commit is unrelated but it's a one-line comment change so it didn't warrant a separate PR... r? `@oli-obk`
2 parents 6f3eb1c + c3342b4 commit cb580ff

File tree

10 files changed

+62
-74
lines changed

10 files changed

+62
-74
lines changed

compiler/rustc_const_eval/src/interpret/eval_context.rs

+12-10
Original file line numberDiff line numberDiff line change
@@ -220,9 +220,6 @@ impl<'tcx, Prov: Provenance> LocalState<'tcx, Prov> {
220220

221221
/// Overwrite the local. If the local can be overwritten in place, return a reference
222222
/// to do so; otherwise return the `MemPlace` to consult instead.
223-
///
224-
/// Note: Before calling this, call the `before_access_local_mut` machine hook! You may be
225-
/// invalidating machine invariants otherwise!
226223
#[inline(always)]
227224
pub(super) fn access_mut(&mut self) -> InterpResult<'tcx, &mut Operand<Prov>> {
228225
match &mut self.value {
@@ -279,6 +276,13 @@ impl<'mir, 'tcx, Prov: Provenance, Extra> Frame<'mir, 'tcx, Prov, Extra> {
279276
}
280277
})
281278
}
279+
280+
/// Returns the address of the buffer where the locals are stored. This is used by `Place` as a
281+
/// sanity check to detect bugs where we mix up which stack frame a place refers to.
282+
#[inline(always)]
283+
pub(super) fn locals_addr(&self) -> usize {
284+
self.locals.raw.as_ptr().addr()
285+
}
282286
}
283287

284288
// FIXME: only used by miri, should be removed once translatable.
@@ -645,7 +649,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
645649
}
646650

647651
#[inline(always)]
648-
pub fn layout_of_local(
652+
pub(super) fn layout_of_local(
649653
&self,
650654
frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
651655
local: mir::Local,
@@ -896,7 +900,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
896900
// Copy return value. Must of course happen *before* we deallocate the locals.
897901
let copy_ret_result = if !unwinding {
898902
let op = self
899-
.local_to_op(self.frame(), mir::RETURN_PLACE, None)
903+
.local_to_op(mir::RETURN_PLACE, None)
900904
.expect("return place should always be live");
901905
let dest = self.frame().return_place.clone();
902906
let err = if self.stack().len() == 1 {
@@ -1212,18 +1216,16 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> std::fmt::Debug
12121216
{
12131217
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12141218
match self.place {
1215-
Place::Local { frame, local, offset } => {
1219+
Place::Local { local, offset, locals_addr } => {
1220+
debug_assert_eq!(locals_addr, self.ecx.frame().locals_addr());
12161221
let mut allocs = Vec::new();
12171222
write!(fmt, "{local:?}")?;
12181223
if let Some(offset) = offset {
12191224
write!(fmt, "+{:#x}", offset.bytes())?;
12201225
}
1221-
if frame != self.ecx.frame_idx() {
1222-
write!(fmt, " ({} frames up)", self.ecx.frame_idx() - frame)?;
1223-
}
12241226
write!(fmt, ":")?;
12251227

1226-
match self.ecx.stack()[frame].locals[local].value {
1228+
match self.ecx.frame().locals[local].value {
12271229
LocalValue::Dead => write!(fmt, " is dead")?,
12281230
LocalValue::Live(Operand::Immediate(Immediate::Uninit)) => {
12291231
write!(fmt, " is uninitialized")?

compiler/rustc_const_eval/src/interpret/machine.rs

-19
Original file line numberDiff line numberDiff line change
@@ -260,24 +260,6 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized {
260260
F2::NAN
261261
}
262262

263-
/// Called before writing the specified `local` of the `frame`.
264-
/// Since writing a ZST is not actually accessing memory or locals, this is never invoked
265-
/// for ZST reads.
266-
///
267-
/// Due to borrow checker trouble, we indicate the `frame` as an index rather than an `&mut
268-
/// Frame`.
269-
#[inline(always)]
270-
fn before_access_local_mut<'a>(
271-
_ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
272-
_frame: usize,
273-
_local: mir::Local,
274-
) -> InterpResult<'tcx>
275-
where
276-
'tcx: 'mir,
277-
{
278-
Ok(())
279-
}
280-
281263
/// Called before a basic block terminator is executed.
282264
#[inline]
283265
fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
@@ -531,7 +513,6 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized {
531513
#[inline(always)]
532514
fn after_local_allocated(
533515
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
534-
_frame: usize,
535516
_local: mir::Local,
536517
_mplace: &MPlaceTy<'tcx, Self::Provenance>,
537518
) -> InterpResult<'tcx> {

compiler/rustc_const_eval/src/interpret/operand.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ use rustc_middle::{mir, ty};
1313
use rustc_target::abi::{self, Abi, HasDataLayout, Size};
1414

1515
use super::{
16-
alloc_range, from_known_layout, mir_assign_valid_types, CtfeProvenance, Frame, InterpCx,
17-
InterpResult, MPlaceTy, Machine, MemPlace, MemPlaceMeta, OffsetMode, PlaceTy, Pointer,
18-
Projectable, Provenance, Scalar,
16+
alloc_range, from_known_layout, mir_assign_valid_types, CtfeProvenance, InterpCx, InterpResult,
17+
MPlaceTy, Machine, MemPlace, MemPlaceMeta, OffsetMode, PlaceTy, Pointer, Projectable,
18+
Provenance, Scalar,
1919
};
2020

2121
/// An `Immediate` represents a single immediate self-contained Rust value.
@@ -633,17 +633,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
633633
}
634634
}
635635

636-
/// Read from a local.
636+
/// Read from a local of the current frame.
637637
/// Will not access memory, instead an indirect `Operand` is returned.
638638
///
639639
/// This is public because it is used by [priroda](https://github.com/oli-obk/priroda) to get an
640640
/// OpTy from a local.
641641
pub fn local_to_op(
642642
&self,
643-
frame: &Frame<'mir, 'tcx, M::Provenance, M::FrameExtra>,
644643
local: mir::Local,
645644
layout: Option<TyAndLayout<'tcx>>,
646645
) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
646+
let frame = self.frame();
647647
let layout = self.layout_of_local(frame, local, layout)?;
648648
let op = *frame.locals[local].access()?;
649649
if matches!(op, Operand::Immediate(_)) {
@@ -661,9 +661,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
661661
) -> InterpResult<'tcx, OpTy<'tcx, M::Provenance>> {
662662
match place.as_mplace_or_local() {
663663
Left(mplace) => Ok(mplace.into()),
664-
Right((frame, local, offset)) => {
664+
Right((local, offset, locals_addr)) => {
665665
debug_assert!(place.layout.is_sized()); // only sized locals can ever be `Place::Local`.
666-
let base = self.local_to_op(&self.stack()[frame], local, None)?;
666+
debug_assert_eq!(locals_addr, self.frame().locals_addr());
667+
let base = self.local_to_op(local, None)?;
667668
Ok(match offset {
668669
Some(offset) => base.offset(offset, place.layout, self)?,
669670
None => {
@@ -687,7 +688,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
687688
// here is not the entire place.
688689
let layout = if mir_place.projection.is_empty() { layout } else { None };
689690

690-
let mut op = self.local_to_op(self.frame(), mir_place.local, layout)?;
691+
let mut op = self.local_to_op(mir_place.local, layout)?;
691692
// Using `try_fold` turned out to be bad for performance, hence the loop.
692693
for elem in mir_place.projection.iter() {
693694
op = self.project(&op, elem)?

compiler/rustc_const_eval/src/interpret/place.rs

+35-31
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,13 @@ pub(super) enum Place<Prov: Provenance = CtfeProvenance> {
187187
/// where in the local this place is located; if it is `None`, no projection has been applied.
188188
/// Such projections are meaningful even if the offset is 0, since they can change layouts.
189189
/// (Without that optimization, we'd just always be a `MemPlace`.)
190-
/// Note that this only stores the frame index, not the thread this frame belongs to -- that is
191-
/// implicit. This means a `Place` must never be moved across interpreter thread boundaries!
190+
/// `Local` places always refer to the current stack frame, so they are unstable under
191+
/// function calls/returns and switching betweens stacks of different threads!
192+
/// We carry around the address of the `locals` buffer of the correct stack frame as a sanity
193+
/// chec to be able to catch some cases of using a dangling `Place`.
192194
///
193195
/// This variant shall not be used for unsized types -- those must always live in memory.
194-
Local { frame: usize, local: mir::Local, offset: Option<Size> },
196+
Local { local: mir::Local, offset: Option<Size>, locals_addr: usize },
195197
}
196198

197199
/// An evaluated place, together with its type.
@@ -233,10 +235,10 @@ impl<'tcx, Prov: Provenance> PlaceTy<'tcx, Prov> {
233235
#[inline(always)]
234236
pub fn as_mplace_or_local(
235237
&self,
236-
) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>)> {
238+
) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize)> {
237239
match self.place {
238240
Place::Ptr(mplace) => Left(MPlaceTy { mplace, layout: self.layout }),
239-
Place::Local { frame, local, offset } => Right((frame, local, offset)),
241+
Place::Local { local, offset, locals_addr } => Right((local, offset, locals_addr)),
240242
}
241243
}
242244

@@ -279,7 +281,7 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
279281
) -> InterpResult<'tcx, Self> {
280282
Ok(match self.as_mplace_or_local() {
281283
Left(mplace) => mplace.offset_with_meta(offset, mode, meta, layout, ecx)?.into(),
282-
Right((frame, local, old_offset)) => {
284+
Right((local, old_offset, locals_addr)) => {
283285
debug_assert!(layout.is_sized(), "unsized locals should live in memory");
284286
assert_matches!(meta, MemPlaceMeta::None); // we couldn't store it anyway...
285287
// `Place::Local` are always in-bounds of their surrounding local, so we can just
@@ -292,7 +294,10 @@ impl<'tcx, Prov: Provenance> Projectable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
292294
.offset(old_offset.unwrap_or(Size::ZERO).bytes(), offset.bytes())?,
293295
);
294296

295-
PlaceTy { place: Place::Local { frame, local, offset: Some(new_offset) }, layout }
297+
PlaceTy {
298+
place: Place::Local { local, offset: Some(new_offset), locals_addr },
299+
layout,
300+
}
296301
}
297302
})
298303
}
@@ -331,7 +336,7 @@ impl<'tcx, Prov: Provenance> OpTy<'tcx, Prov> {
331336
pub trait Writeable<'tcx, Prov: Provenance>: Projectable<'tcx, Prov> {
332337
fn as_mplace_or_local(
333338
&self,
334-
) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, TyAndLayout<'tcx>)>;
339+
) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)>;
335340

336341
fn force_mplace<'mir, M: Machine<'mir, 'tcx, Provenance = Prov>>(
337342
&self,
@@ -343,9 +348,9 @@ impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for PlaceTy<'tcx, Prov> {
343348
#[inline(always)]
344349
fn as_mplace_or_local(
345350
&self,
346-
) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, TyAndLayout<'tcx>)> {
351+
) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)> {
347352
self.as_mplace_or_local()
348-
.map_right(|(frame, local, offset)| (frame, local, offset, self.layout))
353+
.map_right(|(local, offset, locals_addr)| (local, offset, locals_addr, self.layout))
349354
}
350355

351356
#[inline(always)]
@@ -361,7 +366,7 @@ impl<'tcx, Prov: Provenance> Writeable<'tcx, Prov> for MPlaceTy<'tcx, Prov> {
361366
#[inline(always)]
362367
fn as_mplace_or_local(
363368
&self,
364-
) -> Either<MPlaceTy<'tcx, Prov>, (usize, mir::Local, Option<Size>, TyAndLayout<'tcx>)> {
369+
) -> Either<MPlaceTy<'tcx, Prov>, (mir::Local, Option<Size>, usize, TyAndLayout<'tcx>)> {
365370
Left(self.clone())
366371
}
367372

@@ -501,21 +506,21 @@ where
501506
Ok((mplace, len))
502507
}
503508

509+
/// Turn a local in the current frame into a place.
504510
pub fn local_to_place(
505511
&self,
506-
frame: usize,
507512
local: mir::Local,
508513
) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
509514
// Other parts of the system rely on `Place::Local` never being unsized.
510515
// So we eagerly check here if this local has an MPlace, and if yes we use it.
511-
let frame_ref = &self.stack()[frame];
512-
let layout = self.layout_of_local(frame_ref, local, None)?;
516+
let frame = self.frame();
517+
let layout = self.layout_of_local(frame, local, None)?;
513518
let place = if layout.is_sized() {
514519
// We can just always use the `Local` for sized values.
515-
Place::Local { frame, local, offset: None }
520+
Place::Local { local, offset: None, locals_addr: frame.locals_addr() }
516521
} else {
517522
// Unsized `Local` isn't okay (we cannot store the metadata).
518-
match frame_ref.locals[local].access()? {
523+
match frame.locals[local].access()? {
519524
Operand::Immediate(_) => bug!(),
520525
Operand::Indirect(mplace) => Place::Ptr(*mplace),
521526
}
@@ -530,7 +535,7 @@ where
530535
&self,
531536
mir_place: mir::Place<'tcx>,
532537
) -> InterpResult<'tcx, PlaceTy<'tcx, M::Provenance>> {
533-
let mut place = self.local_to_place(self.frame_idx(), mir_place.local)?;
538+
let mut place = self.local_to_place(mir_place.local)?;
534539
// Using `try_fold` turned out to be bad for performance, hence the loop.
535540
for elem in mir_place.projection.iter() {
536541
place = self.project(&place, elem)?
@@ -611,23 +616,23 @@ where
611616
// See if we can avoid an allocation. This is the counterpart to `read_immediate_raw`,
612617
// but not factored as a separate function.
613618
let mplace = match dest.as_mplace_or_local() {
614-
Right((frame, local, offset, layout)) => {
619+
Right((local, offset, locals_addr, layout)) => {
615620
if offset.is_some() {
616621
// This has been projected to a part of this local. We could have complicated
617622
// logic to still keep this local as an `Operand`... but it's much easier to
618623
// just fall back to the indirect path.
619624
dest.force_mplace(self)?
620625
} else {
621-
M::before_access_local_mut(self, frame, local)?;
622-
match self.stack_mut()[frame].locals[local].access_mut()? {
626+
debug_assert_eq!(locals_addr, self.frame().locals_addr());
627+
match self.frame_mut().locals[local].access_mut()? {
623628
Operand::Immediate(local_val) => {
624629
// Local can be updated in-place.
625630
*local_val = src;
626631
// Double-check that the value we are storing and the local fit to each other.
627632
// (*After* doing the update for borrow checker reasons.)
628633
if cfg!(debug_assertions) {
629634
let local_layout =
630-
self.layout_of_local(&self.stack()[frame], local, None)?;
635+
self.layout_of_local(&self.frame(), local, None)?;
631636
match (src, local_layout.abi) {
632637
(Immediate::Scalar(scalar), Abi::Scalar(s)) => {
633638
assert_eq!(scalar.size(), s.size(self))
@@ -725,16 +730,16 @@ where
725730
) -> InterpResult<'tcx> {
726731
let mplace = match dest.as_mplace_or_local() {
727732
Left(mplace) => mplace,
728-
Right((frame, local, offset, layout)) => {
733+
Right((local, offset, locals_addr, layout)) => {
729734
if offset.is_some() {
730735
// This has been projected to a part of this local. We could have complicated
731736
// logic to still keep this local as an `Operand`... but it's much easier to
732737
// just fall back to the indirect path.
733738
// FIXME: share the logic with `write_immediate_no_validate`.
734739
dest.force_mplace(self)?
735740
} else {
736-
M::before_access_local_mut(self, frame, local)?;
737-
match self.stack_mut()[frame].locals[local].access_mut()? {
741+
debug_assert_eq!(locals_addr, self.frame().locals_addr());
742+
match self.frame_mut().locals[local].access_mut()? {
738743
Operand::Immediate(local) => {
739744
*local = Immediate::Uninit;
740745
return Ok(());
@@ -912,17 +917,16 @@ where
912917
place: &PlaceTy<'tcx, M::Provenance>,
913918
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
914919
let mplace = match place.place {
915-
Place::Local { frame, local, offset } => {
916-
M::before_access_local_mut(self, frame, local)?;
917-
let whole_local = match self.stack_mut()[frame].locals[local].access_mut()? {
920+
Place::Local { local, offset, locals_addr } => {
921+
debug_assert_eq!(locals_addr, self.frame().locals_addr());
922+
let whole_local = match self.frame_mut().locals[local].access_mut()? {
918923
&mut Operand::Immediate(local_val) => {
919924
// We need to make an allocation.
920925

921926
// We need the layout of the local. We can NOT use the layout we got,
922927
// that might e.g., be an inner field of a struct with `Scalar` layout,
923928
// that has different alignment than the outer field.
924-
let local_layout =
925-
self.layout_of_local(&self.stack()[frame], local, None)?;
929+
let local_layout = self.layout_of_local(&self.frame(), local, None)?;
926930
assert!(local_layout.is_sized(), "unsized locals cannot be immediate");
927931
let mplace = self.allocate(local_layout, MemoryKind::Stack)?;
928932
// Preserve old value. (As an optimization, we can skip this if it was uninit.)
@@ -936,11 +940,11 @@ where
936940
mplace.mplace,
937941
)?;
938942
}
939-
M::after_local_allocated(self, frame, local, &mplace)?;
943+
M::after_local_allocated(self, local, &mplace)?;
940944
// Now we can call `access_mut` again, asserting it goes well, and actually
941945
// overwrite things. This points to the entire allocation, not just the part
942946
// the place refers to, i.e. we do this before we apply `offset`.
943-
*self.stack_mut()[frame].locals[local].access_mut().unwrap() =
947+
*self.frame_mut().locals[local].access_mut().unwrap() =
944948
Operand::Indirect(mplace.mplace);
945949
mplace.mplace
946950
}

compiler/rustc_const_eval/src/interpret/projection.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -357,7 +357,7 @@ where
357357
Deref => self.deref_pointer(&base.to_op(self)?)?.into(),
358358
Index(local) => {
359359
let layout = self.layout_of(self.tcx.types.usize)?;
360-
let n = self.local_to_op(self.frame(), local, Some(layout))?;
360+
let n = self.local_to_op(local, Some(layout))?;
361361
let n = self.read_target_usize(&n)?;
362362
self.project_index(base, n)?
363363
}

compiler/rustc_const_eval/src/interpret/terminator.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
631631
body.args_iter()
632632
.map(|local| (
633633
local,
634-
self.layout_of_local(self.frame(), local, None).unwrap().ty
634+
self.layout_of_local(self.frame(), local, None).unwrap().ty,
635635
))
636636
.collect::<Vec<_>>()
637637
);

compiler/rustc_const_eval/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ Rust MIR: a lowered representation of Rust.
1414
#![feature(generic_nonzero)]
1515
#![feature(let_chains)]
1616
#![feature(slice_ptr_get)]
17+
#![feature(strict_provenance)]
1718
#![feature(never_type)]
1819
#![feature(trait_alias)]
1920
#![feature(try_blocks)]

compiler/rustc_mir_transform/src/add_retag.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ impl<'tcx> MirPass<'tcx> for AddRetag {
118118
}
119119

120120
// PART 3
121-
// Add retag after assignments where data "enters" this function: the RHS is behind a deref and the LHS is not.
121+
// Add retag after assignments.
122122
for block_data in basic_blocks {
123123
// We want to insert statements as we iterate. To this end, we
124124
// iterate backwards using indices.

0 commit comments

Comments
 (0)