Skip to content

Commit 2e181e0

Browse files
authored
Rollup merge of rust-lang#124030 - RalfJung:adjust_alloc_base_pointer, r=oli-obk
interpret: pass MemoryKind to adjust_alloc_base_pointer Another puzzle piece for rust-lang/miri#3475. The 2nd commit renames base_pointer -> root_pointer; that's how Tree Borrows already calls them and I think the term is more clear than "base pointer". In particular, this distinguishes it from "base address", since a root pointer can point anywhere into an allocation, not just its base address. rust-lang#124018 has been rolled up already so I couldn't add it there any more. r? `@oli-obk`
2 parents 6c6b302 + ae7b07f commit 2e181e0

File tree

14 files changed

+85
-65
lines changed

14 files changed

+85
-65
lines changed

compiler/rustc_const_eval/src/interpret/machine.rs

+21-14
Original file line numberDiff line numberDiff line change
@@ -288,28 +288,19 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized {
288288
}
289289

290290
/// Return the `AllocId` for the given thread-local static in the current thread.
291-
fn thread_local_static_base_pointer(
291+
fn thread_local_static_pointer(
292292
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
293293
def_id: DefId,
294294
) -> InterpResult<'tcx, Pointer<Self::Provenance>> {
295295
throw_unsup!(ThreadLocalStatic(def_id))
296296
}
297297

298-
/// Return the root pointer for the given `extern static`.
299-
fn extern_static_base_pointer(
298+
/// Return the `AllocId` for the given `extern static`.
299+
fn extern_static_pointer(
300300
ecx: &InterpCx<'mir, 'tcx, Self>,
301301
def_id: DefId,
302302
) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
303303

304-
/// Return a "base" pointer for the given allocation: the one that is used for direct
305-
/// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
306-
///
307-
/// Not called on `extern` or thread-local statics (those use the methods above).
308-
fn adjust_alloc_base_pointer(
309-
ecx: &InterpCx<'mir, 'tcx, Self>,
310-
ptr: Pointer,
311-
) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
312-
313304
/// "Int-to-pointer cast"
314305
fn ptr_from_addr_cast(
315306
ecx: &InterpCx<'mir, 'tcx, Self>,
@@ -336,6 +327,8 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized {
336327

337328
/// Called to adjust allocations to the Provenance and AllocExtra of this machine.
338329
///
330+
/// If `alloc` contains pointers, then they are all pointing to globals.
331+
///
339332
/// The way we construct allocations is to always first construct it without extra and then add
340333
/// the extra. This keeps uniform code paths for handling both allocations created by CTFE for
341334
/// globals, and allocations created by Miri during evaluation.
@@ -354,6 +347,19 @@ pub trait Machine<'mir, 'tcx: 'mir>: Sized {
354347
kind: Option<MemoryKind<Self::MemoryKind>>,
355348
) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>;
356349

350+
/// Return a "root" pointer for the given allocation: the one that is used for direct
351+
/// accesses to this static/const/fn allocation, or the one returned from the heap allocator.
352+
///
353+
/// Not called on `extern` or thread-local statics (those use the methods above).
354+
///
355+
/// `kind` is the kind of the allocation the pointer points to; it can be `None` when
356+
/// it's a global and `GLOBAL_KIND` is `None`.
357+
fn adjust_alloc_root_pointer(
358+
ecx: &InterpCx<'mir, 'tcx, Self>,
359+
ptr: Pointer,
360+
kind: Option<MemoryKind<Self::MemoryKind>>,
361+
) -> InterpResult<'tcx, Pointer<Self::Provenance>>;
362+
357363
/// Evaluate the inline assembly.
358364
///
359365
/// This should take care of jumping to the next block (one of `targets`) when asm goto
@@ -592,7 +598,7 @@ pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) {
592598
Ok(alloc)
593599
}
594600

595-
fn extern_static_base_pointer(
601+
fn extern_static_pointer(
596602
ecx: &InterpCx<$mir, $tcx, Self>,
597603
def_id: DefId,
598604
) -> InterpResult<$tcx, Pointer> {
@@ -601,9 +607,10 @@ pub macro compile_time_machine(<$mir: lifetime, $tcx: lifetime>) {
601607
}
602608

603609
#[inline(always)]
604-
fn adjust_alloc_base_pointer(
610+
fn adjust_alloc_root_pointer(
605611
_ecx: &InterpCx<$mir, $tcx, Self>,
606612
ptr: Pointer<CtfeProvenance>,
613+
_kind: Option<MemoryKind<Self::MemoryKind>>,
607614
) -> InterpResult<$tcx, Pointer<CtfeProvenance>> {
608615
Ok(ptr)
609616
}

compiler/rustc_const_eval/src/interpret/memory.rs

+12-6
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
165165
///
166166
/// This function can fail only if `ptr` points to an `extern static`.
167167
#[inline]
168-
pub fn global_base_pointer(
168+
pub fn global_root_pointer(
169169
&self,
170170
ptr: Pointer<CtfeProvenance>,
171171
) -> InterpResult<'tcx, Pointer<M::Provenance>> {
@@ -178,12 +178,18 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
178178
bug!("global memory cannot point to thread-local static")
179179
}
180180
Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
181-
return M::extern_static_base_pointer(self, def_id);
181+
return M::extern_static_pointer(self, def_id);
182+
}
183+
None => {
184+
assert!(
185+
self.memory.extra_fn_ptr_map.contains_key(&alloc_id),
186+
"{alloc_id:?} is neither global nor a function pointer"
187+
);
182188
}
183189
_ => {}
184190
}
185191
// And we need to get the provenance.
186-
M::adjust_alloc_base_pointer(self, ptr)
192+
M::adjust_alloc_root_pointer(self, ptr, M::GLOBAL_KIND.map(MemoryKind::Machine))
187193
}
188194

189195
pub fn fn_ptr(&mut self, fn_val: FnVal<'tcx, M::ExtraFnVal>) -> Pointer<M::Provenance> {
@@ -197,9 +203,9 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
197203
id
198204
}
199205
};
200-
// Functions are global allocations, so make sure we get the right base pointer.
206+
// Functions are global allocations, so make sure we get the right root pointer.
201207
// We know this is not an `extern static` so this cannot fail.
202-
self.global_base_pointer(Pointer::from(id)).unwrap()
208+
self.global_root_pointer(Pointer::from(id)).unwrap()
203209
}
204210

205211
pub fn allocate_ptr(
@@ -240,7 +246,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
240246
);
241247
let alloc = M::adjust_allocation(self, id, Cow::Owned(alloc), Some(kind))?;
242248
self.memory.alloc_map.insert(id, (kind, alloc.into_owned()));
243-
M::adjust_alloc_base_pointer(self, Pointer::from(id))
249+
M::adjust_alloc_root_pointer(self, Pointer::from(id), Some(kind))
244250
}
245251

246252
pub fn reallocate_ptr(

compiler/rustc_const_eval/src/interpret/operand.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -764,15 +764,15 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
764764
// Other cases need layout.
765765
let adjust_scalar = |scalar| -> InterpResult<'tcx, _> {
766766
Ok(match scalar {
767-
Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size),
767+
Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_root_pointer(ptr)?, size),
768768
Scalar::Int(int) => Scalar::Int(int),
769769
})
770770
};
771771
let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?;
772772
let imm = match val_val {
773773
mir::ConstValue::Indirect { alloc_id, offset } => {
774774
// This is const data, no mutation allowed.
775-
let ptr = self.global_base_pointer(Pointer::new(
775+
let ptr = self.global_root_pointer(Pointer::new(
776776
CtfeProvenance::from(alloc_id).as_immutable(),
777777
offset,
778778
))?;
@@ -784,7 +784,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
784784
// This is const data, no mutation allowed.
785785
let alloc_id = self.tcx.reserve_and_set_memory_alloc(data);
786786
let ptr = Pointer::new(CtfeProvenance::from(alloc_id).as_immutable(), Size::ZERO);
787-
Immediate::new_slice(self.global_base_pointer(ptr)?.into(), meta, self)
787+
Immediate::new_slice(self.global_root_pointer(ptr)?.into(), meta, self)
788788
}
789789
};
790790
Ok(OpTy { op: Operand::Immediate(imm), layout })

compiler/rustc_const_eval/src/interpret/place.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1010,7 +1010,7 @@ where
10101010
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::Provenance>> {
10111011
// This must be an allocation in `tcx`
10121012
let _ = self.tcx.global_alloc(raw.alloc_id);
1013-
let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
1013+
let ptr = self.global_root_pointer(Pointer::from(raw.alloc_id))?;
10141014
let layout = self.layout_of(raw.ty)?;
10151015
Ok(self.ptr_to_mplace(ptr.into(), layout))
10161016
}

compiler/rustc_const_eval/src/interpret/step.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
144144
use rustc_middle::mir::Rvalue::*;
145145
match *rvalue {
146146
ThreadLocalRef(did) => {
147-
let ptr = M::thread_local_static_base_pointer(self, did)?;
147+
let ptr = M::thread_local_static_pointer(self, did)?;
148148
self.write_pointer(ptr, &dest)?;
149149
}
150150

compiler/rustc_const_eval/src/interpret/traits.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
2828
ensure_monomorphic_enough(*self.tcx, poly_trait_ref)?;
2929

3030
let vtable_symbolic_allocation = self.tcx.reserve_and_set_vtable_alloc(ty, poly_trait_ref);
31-
let vtable_ptr = self.global_base_pointer(Pointer::from(vtable_symbolic_allocation))?;
31+
let vtable_ptr = self.global_root_pointer(Pointer::from(vtable_symbolic_allocation))?;
3232
Ok(vtable_ptr.into())
3333
}
3434

src/tools/miri/src/alloc_addresses/mod.rs

+10-5
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,11 @@ trait EvalContextExtPriv<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
141141
}
142142
}
143143

144-
fn addr_from_alloc_id(&self, alloc_id: AllocId) -> InterpResult<'tcx, u64> {
144+
fn addr_from_alloc_id(
145+
&self,
146+
alloc_id: AllocId,
147+
_kind: MemoryKind,
148+
) -> InterpResult<'tcx, u64> {
145149
let ecx = self.eval_context_ref();
146150
let mut global_state = ecx.machine.alloc_addresses.borrow_mut();
147151
let global_state = &mut *global_state;
@@ -283,16 +287,17 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
283287
}
284288

285289
/// Convert a relative (tcx) pointer to a Miri pointer.
286-
fn ptr_from_rel_ptr(
290+
fn adjust_alloc_root_pointer(
287291
&self,
288292
ptr: Pointer<CtfeProvenance>,
289293
tag: BorTag,
294+
kind: MemoryKind,
290295
) -> InterpResult<'tcx, Pointer<Provenance>> {
291296
let ecx = self.eval_context_ref();
292297

293298
let (prov, offset) = ptr.into_parts(); // offset is relative (AllocId provenance)
294299
let alloc_id = prov.alloc_id();
295-
let base_addr = ecx.addr_from_alloc_id(alloc_id)?;
300+
let base_addr = ecx.addr_from_alloc_id(alloc_id, kind)?;
296301

297302
// Add offset with the right kind of pointer-overflowing arithmetic.
298303
let dl = ecx.data_layout();
@@ -314,9 +319,9 @@ pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
314319
ecx.alloc_id_from_addr(addr.bytes())?
315320
};
316321

317-
// This cannot fail: since we already have a pointer with that provenance, rel_ptr_to_addr
322+
// This cannot fail: since we already have a pointer with that provenance, adjust_alloc_root_pointer
318323
// must have been called in the past, so we can just look up the address in the map.
319-
let base_addr = ecx.addr_from_alloc_id(alloc_id).unwrap();
324+
let base_addr = *ecx.machine.alloc_addresses.borrow().base_addr.get(&alloc_id).unwrap();
320325

321326
// Wrapping "addr - base_addr"
322327
#[allow(clippy::cast_possible_wrap)] // we want to wrap here

src/tools/miri/src/borrow_tracker/mod.rs

+9-9
Original file line numberDiff line numberDiff line change
@@ -89,10 +89,10 @@ pub struct GlobalStateInner {
8989
borrow_tracker_method: BorrowTrackerMethod,
9090
/// Next unused pointer ID (tag).
9191
next_ptr_tag: BorTag,
92-
/// Table storing the "base" tag for each allocation.
93-
/// The base tag is the one used for the initial pointer.
92+
/// Table storing the "root" tag for each allocation.
93+
/// The root tag is the one used for the initial pointer.
9494
/// We need this in a separate table to handle cyclic statics.
95-
base_ptr_tags: FxHashMap<AllocId, BorTag>,
95+
root_ptr_tags: FxHashMap<AllocId, BorTag>,
9696
/// Next unused call ID (for protectors).
9797
next_call_id: CallId,
9898
/// All currently protected tags.
@@ -175,7 +175,7 @@ impl GlobalStateInner {
175175
GlobalStateInner {
176176
borrow_tracker_method,
177177
next_ptr_tag: BorTag::one(),
178-
base_ptr_tags: FxHashMap::default(),
178+
root_ptr_tags: FxHashMap::default(),
179179
next_call_id: NonZero::new(1).unwrap(),
180180
protected_tags: FxHashMap::default(),
181181
tracked_pointer_tags,
@@ -213,8 +213,8 @@ impl GlobalStateInner {
213213
}
214214
}
215215

216-
pub fn base_ptr_tag(&mut self, id: AllocId, machine: &MiriMachine<'_, '_>) -> BorTag {
217-
self.base_ptr_tags.get(&id).copied().unwrap_or_else(|| {
216+
pub fn root_ptr_tag(&mut self, id: AllocId, machine: &MiriMachine<'_, '_>) -> BorTag {
217+
self.root_ptr_tags.get(&id).copied().unwrap_or_else(|| {
218218
let tag = self.new_ptr();
219219
if self.tracked_pointer_tags.contains(&tag) {
220220
machine.emit_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(
@@ -223,14 +223,14 @@ impl GlobalStateInner {
223223
None,
224224
));
225225
}
226-
trace!("New allocation {:?} has base tag {:?}", id, tag);
227-
self.base_ptr_tags.try_insert(id, tag).unwrap();
226+
trace!("New allocation {:?} has rpot tag {:?}", id, tag);
227+
self.root_ptr_tags.try_insert(id, tag).unwrap();
228228
tag
229229
})
230230
}
231231

232232
pub fn remove_unreachable_allocs(&mut self, allocs: &LiveAllocs<'_, '_, '_>) {
233-
self.base_ptr_tags.retain(|id, _| allocs.is_live(*id));
233+
self.root_ptr_tags.retain(|id, _| allocs.is_live(*id));
234234
}
235235
}
236236

src/tools/miri/src/borrow_tracker/stacked_borrows/diagnostics.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ fn err_sb_ub<'tcx>(
2020
#[derive(Clone, Debug)]
2121
pub struct AllocHistory {
2222
id: AllocId,
23-
base: (Item, Span),
23+
root: (Item, Span),
2424
creations: smallvec::SmallVec<[Creation; 1]>,
2525
invalidations: smallvec::SmallVec<[Invalidation; 1]>,
2626
protectors: smallvec::SmallVec<[Protection; 1]>,
@@ -225,7 +225,7 @@ impl AllocHistory {
225225
pub fn new(id: AllocId, item: Item, machine: &MiriMachine<'_, '_>) -> Self {
226226
Self {
227227
id,
228-
base: (item, machine.current_span()),
228+
root: (item, machine.current_span()),
229229
creations: SmallVec::new(),
230230
invalidations: SmallVec::new(),
231231
protectors: SmallVec::new(),
@@ -342,15 +342,15 @@ impl<'history, 'ecx, 'mir, 'tcx> DiagnosticCx<'history, 'ecx, 'mir, 'tcx> {
342342
})
343343
})
344344
.or_else(|| {
345-
// If we didn't find a retag that created this tag, it might be the base tag of
345+
// If we didn't find a retag that created this tag, it might be the root tag of
346346
// this allocation.
347-
if self.history.base.0.tag() == tag {
347+
if self.history.root.0.tag() == tag {
348348
Some((
349349
format!(
350-
"{tag:?} was created here, as the base tag for {:?}",
350+
"{tag:?} was created here, as the root tag for {:?}",
351351
self.history.id
352352
),
353-
self.history.base.1.data(),
353+
self.history.root.1.data(),
354354
))
355355
} else {
356356
None

src/tools/miri/src/borrow_tracker/stacked_borrows/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -518,9 +518,9 @@ impl Stacks {
518518
// not through a pointer). That is, whenever we directly write to a local, this will pop
519519
// everything else off the stack, invalidating all previous pointers,
520520
// and in particular, *all* raw pointers.
521-
MemoryKind::Stack => (state.base_ptr_tag(id, machine), Permission::Unique),
521+
MemoryKind::Stack => (state.root_ptr_tag(id, machine), Permission::Unique),
522522
// Everything else is shared by default.
523-
_ => (state.base_ptr_tag(id, machine), Permission::SharedReadWrite),
523+
_ => (state.root_ptr_tag(id, machine), Permission::SharedReadWrite),
524524
};
525525
Stacks::new(size, perm, base_tag, id, machine)
526526
}

src/tools/miri/src/borrow_tracker/stacked_borrows/stack.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ impl Stack {
4747
let mut first_removed = None;
4848

4949
// We never consider removing the bottom-most tag. For stacks without an unknown
50-
// bottom this preserves the base tag.
50+
// bottom this preserves the root tag.
5151
// Note that the algorithm below is based on considering the tag at read_idx - 1,
5252
// so precisely considering the tag at index 0 for removal when we have an unknown
5353
// bottom would complicate the implementation. The simplification of not considering
@@ -93,7 +93,7 @@ impl Stack {
9393
self.unique_range = 0..self.len();
9494
}
9595

96-
// Replace any Items which have been collected with the base item, a known-good value.
96+
// Replace any Items which have been collected with the root item, a known-good value.
9797
for i in 0..CACHE_LEN {
9898
if self.cache.idx[i] >= first_removed {
9999
self.cache.items[i] = self.borrows[0];
@@ -331,7 +331,7 @@ impl<'tcx> Stack {
331331
self.verify_cache_consistency();
332332
}
333333

334-
/// Construct a new `Stack` using the passed `Item` as the base tag.
334+
/// Construct a new `Stack` using the passed `Item` as the root tag.
335335
pub fn new(item: Item) -> Self {
336336
Stack {
337337
borrows: vec![item],
@@ -438,8 +438,8 @@ impl<'tcx> Stack {
438438
let mut removed = 0;
439439
let mut cursor = 0;
440440
// Remove invalid entries from the cache by rotating them to the end of the cache, then
441-
// keep track of how many invalid elements there are and overwrite them with the base tag.
442-
// The base tag here serves as a harmless default value.
441+
// keep track of how many invalid elements there are and overwrite them with the root tag.
442+
// The root tag here serves as a harmless default value.
443443
for _ in 0..CACHE_LEN - 1 {
444444
if self.cache.idx[cursor] >= start {
445445
self.cache.idx[cursor..CACHE_LEN - removed].rotate_left(1);

src/tools/miri/src/borrow_tracker/tree_borrows/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ impl<'tcx> Tree {
3737
_kind: MemoryKind,
3838
machine: &MiriMachine<'_, 'tcx>,
3939
) -> Self {
40-
let tag = state.base_ptr_tag(id, machine); // Fresh tag for the root
40+
let tag = state.root_ptr_tag(id, machine); // Fresh tag for the root
4141
let span = machine.current_span();
4242
Tree::new(tag, size, span)
4343
}

0 commit comments

Comments
 (0)