Skip to content

Commit 1d9efbb

Browse files
committed
Miri: replace canonical_alloc_id mechanism by extern_static_alloc_id which is called only when a pointer is 'imported' into the machine
1 parent 2bbfa02 commit 1d9efbb

File tree

7 files changed

+78
-97
lines changed

7 files changed

+78
-97
lines changed

src/librustc_middle/mir/interpret/error.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -502,8 +502,6 @@ impl fmt::Display for UndefinedBehaviorInfo<'_> {
502502
pub enum UnsupportedOpInfo {
503503
/// Free-form case. Only for errors that are never caught!
504504
Unsupported(String),
505-
/// Accessing an unsupported foreign static.
506-
ReadForeignStatic(DefId),
507505
/// Could not find MIR for a function.
508506
NoMirFor(DefId),
509507
/// Encountered a pointer where we needed raw bytes.
@@ -515,15 +513,17 @@ pub enum UnsupportedOpInfo {
515513
ReadBytesAsPointer,
516514
/// Accessing thread local statics
517515
ThreadLocalStatic(DefId),
516+
/// Accessing an unsupported extern static.
517+
ReadExternStatic(DefId),
518518
}
519519

520520
impl fmt::Display for UnsupportedOpInfo {
521521
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522522
use UnsupportedOpInfo::*;
523523
match self {
524524
Unsupported(ref msg) => write!(f, "{}", msg),
525-
ReadForeignStatic(did) => {
526-
write!(f, "cannot read from foreign (extern) static ({:?})", did)
525+
ReadExternStatic(did) => {
526+
write!(f, "cannot read from extern static ({:?})", did)
527527
}
528528
NoMirFor(did) => write!(f, "no MIR body is available for {:?}", did),
529529
ReadPointerAsBytes => write!(f, "unable to turn pointer into raw bytes",),

src/librustc_mir/interpret/eval_context.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -323,14 +323,17 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
323323
}
324324

325325
/// Call this to turn untagged "global" pointers (obtained via `tcx`) into
326-
/// the *canonical* machine pointer to the allocation. Must never be used
327-
/// for any other pointers!
326+
/// the machine pointer to the allocation. Must never be used
327+
/// for any other pointers, nor for TLS statics.
328328
///
329-
/// This represents a *direct* access to that memory, as opposed to access
330-
/// through a pointer that was created by the program.
329+
/// Using the resulting pointer represents a *direct* access to that memory
330+
/// (e.g. by directly using a `static`),
331+
/// as opposed to access through a pointer that was created by the program.
332+
///
333+
/// This function can fail only if `ptr` points to an `extern static`.
331334
#[inline(always)]
332-
pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
333-
self.memory.tag_global_base_pointer(ptr)
335+
pub fn global_base_pointer(&self, ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
336+
self.memory.global_base_pointer(ptr)
334337
}
335338

336339
#[inline(always)]

src/librustc_mir/interpret/machine.rs

Lines changed: 20 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -238,45 +238,30 @@ pub trait Machine<'mir, 'tcx>: Sized {
238238
Ok(())
239239
}
240240

241-
/// Called for *every* memory access to determine the real ID of the given allocation.
242-
/// This provides a way for the machine to "redirect" certain allocations as it sees fit.
243-
///
244-
/// This is used by Miri to redirect extern statics to real allocations.
245-
///
246-
/// This function must be idempotent.
247-
#[inline]
248-
fn canonical_alloc_id(_mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
249-
id
241+
/// Return the `AllocId` for the given thread-local static in the current thread.
242+
fn thread_local_static_alloc_id(
243+
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
244+
def_id: DefId,
245+
) -> InterpResult<'tcx, AllocId> {
246+
throw_unsup!(ThreadLocalStatic(def_id))
250247
}
251248

252-
/// Called when converting a `ty::Const` to an operand (in
253-
/// `eval_const_to_op`).
254-
///
255-
/// Miri uses this callback for creating per thread allocations for thread
256-
/// locals. In Rust, one way of creating a thread local is by marking a
257-
/// static with `#[thread_local]`. On supported platforms this gets
258-
/// translated to a LLVM thread local for which LLVM automatically ensures
259-
/// that each thread gets its own copy. Since LLVM automatically handles
260-
/// thread locals, the Rust compiler just treats thread local statics as
261-
/// regular statics even though accessing a thread local static should be an
262-
/// effectful computation that depends on the current thread. The long term
263-
/// plan is to change MIR to make accesses to thread locals explicit
264-
/// (https://github.com/rust-lang/rust/issues/70685). While the issue 70685
265-
/// is not fixed, our current workaround in Miri is to use this function to
266-
/// make per-thread copies of thread locals. Please note that we cannot make
267-
/// these copies in `canonical_alloc_id` because that is too late: for
268-
/// example, if one created a pointer in thread `t1` to a thread local and
269-
/// sent it to another thread `t2`, resolving the access in
270-
/// `canonical_alloc_id` would result in pointer pointing to `t2`'s thread
271-
/// local and not `t1` as it should.
272-
#[inline]
273-
fn adjust_global_const(
274-
_ecx: &InterpCx<'mir, 'tcx, Self>,
275-
val: mir::interpret::ConstValue<'tcx>,
276-
) -> InterpResult<'tcx, mir::interpret::ConstValue<'tcx>> {
277-
Ok(val)
249+
/// Return the `AllocId` backing the given `extern static`.
250+
fn extern_static_alloc_id(
251+
mem: &Memory<'mir, 'tcx, Self>,
252+
def_id: DefId,
253+
) -> InterpResult<'tcx, AllocId> {
254+
// Use the `AllocId` associated with the `DefId`. Any actual *access* will fail.
255+
Ok(mem.tcx.create_static_alloc(def_id))
278256
}
279257

258+
/// Return the "base" tag for the given *global* allocation: the one that is used for direct
259+
/// accesses to this static/const/fn allocation. If `id` is not a global allocation,
260+
/// this will return an unusable tag (i.e., accesses will be UB)!
261+
///
262+
/// Called on the id returned by `thread_local_static_alloc_id` and `extern_static_alloc_id`, if needed.
263+
fn tag_global_base_pointer(memory_extra: &Self::MemoryExtra, id: AllocId) -> Self::PointerTag;
264+
280265
/// Called to initialize the "extra" state of an allocation and make the pointers
281266
/// it contains (in relocations) tagged. The way we construct allocations is
282267
/// to always first construct it without extra and then add the extra.
@@ -309,13 +294,6 @@ pub trait Machine<'mir, 'tcx>: Sized {
309294
Ok(())
310295
}
311296

312-
/// Return the "base" tag for the given *global* allocation: the one that is used for direct
313-
/// accesses to this static/const/fn allocation. If `id` is not a global allocation,
314-
/// this will return an unusable tag (i.e., accesses will be UB)!
315-
///
316-
/// Expects `id` to be already canonical, if needed.
317-
fn tag_global_base_pointer(memory_extra: &Self::MemoryExtra, id: AllocId) -> Self::PointerTag;
318-
319297
/// Executes a retagging operation
320298
#[inline]
321299
fn retag(
@@ -375,13 +353,6 @@ pub trait Machine<'mir, 'tcx>: Sized {
375353
_mem: &Memory<'mir, 'tcx, Self>,
376354
_ptr: Pointer<Self::PointerTag>,
377355
) -> InterpResult<'tcx, u64>;
378-
379-
fn thread_local_alloc_id(
380-
_ecx: &mut InterpCx<'mir, 'tcx, Self>,
381-
did: DefId,
382-
) -> InterpResult<'tcx, AllocId> {
383-
throw_unsup!(ThreadLocalStatic(did))
384-
}
385356
}
386357

387358
// A lot of the flexibility above is just needed for `Miri`, but all "compile-time" machines

src/librustc_mir/interpret/memory.rs

Lines changed: 34 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -137,15 +137,33 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
137137
}
138138

139139
/// Call this to turn untagged "global" pointers (obtained via `tcx`) into
140-
/// the *canonical* machine pointer to the allocation. Must never be used
141-
/// for any other pointers!
140+
/// the machine pointer to the allocation. Must never be used
141+
/// for any other pointers, nor for TLS statics.
142142
///
143-
/// This represents a *direct* access to that memory, as opposed to access
144-
/// through a pointer that was created by the program.
143+
/// Using the resulting pointer represents a *direct* access to that memory
144+
/// (e.g. by directly using a `static`),
145+
/// as opposed to access through a pointer that was created by the program.
146+
///
147+
/// This function can fail only if `ptr` points to an `extern static`.
145148
#[inline]
146-
pub fn tag_global_base_pointer(&self, ptr: Pointer) -> Pointer<M::PointerTag> {
147-
let id = M::canonical_alloc_id(self, ptr.alloc_id);
148-
ptr.with_tag(M::tag_global_base_pointer(&self.extra, id))
149+
pub fn global_base_pointer(&self, mut ptr: Pointer) -> InterpResult<'tcx, Pointer<M::PointerTag>> {
150+
// We need to handle `extern static`.
151+
let ptr = match self.tcx.get_global_alloc(ptr.alloc_id) {
152+
Some(GlobalAlloc::Static(def_id)) if self.tcx.is_thread_local_static(def_id) => {
153+
bug!("global memory cannot point to thread-local static")
154+
}
155+
Some(GlobalAlloc::Static(def_id)) if self.tcx.is_foreign_item(def_id) => {
156+
ptr.alloc_id = M::extern_static_alloc_id(self, def_id)?;
157+
ptr
158+
}
159+
_ => {
160+
// No need to change the `AllocId`.
161+
ptr
162+
}
163+
};
164+
// And we need to get the tag.
165+
let tag = M::tag_global_base_pointer(&self.extra, ptr.alloc_id);
166+
Ok(ptr.with_tag(tag))
149167
}
150168

151169
pub fn create_fn_alloc(
@@ -162,7 +180,9 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
162180
id
163181
}
164182
};
165-
self.tag_global_base_pointer(Pointer::from(id))
183+
// Functions are global allocations, so make sure we get the right base pointer.
184+
// We know this is not an `extern static` so this cannmot fail.
185+
self.global_base_pointer(Pointer::from(id)).unwrap()
166186
}
167187

168188
pub fn allocate(
@@ -195,6 +215,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
195215
M::GLOBAL_KIND.map(MemoryKind::Machine),
196216
"dynamically allocating global memory"
197217
);
218+
// This is a new allocation, not a new global one, so no `global_base_ptr`.
198219
let (alloc, tag) = M::init_allocation_extra(&self.extra, id, Cow::Owned(alloc), Some(kind));
199220
self.alloc_map.insert(id, (kind, alloc.into_owned()));
200221
Pointer::from(id).with_tag(tag)
@@ -437,6 +458,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
437458
Some(GlobalAlloc::Function(..)) => throw_ub!(DerefFunctionPointer(id)),
438459
None => throw_ub!(PointerUseAfterFree(id)),
439460
Some(GlobalAlloc::Static(def_id)) => {
461+
assert!(tcx.is_static(def_id));
440462
assert!(!tcx.is_thread_local_static(def_id));
441463
// Notice that every static has two `AllocId` that will resolve to the same
442464
// thing here: one maps to `GlobalAlloc::Static`, this is the "lazy" ID,
@@ -448,24 +470,15 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
448470
// The `GlobalAlloc::Memory` branch here is still reachable though; when a static
449471
// contains a reference to memory that was created during its evaluation (i.e., not
450472
// to another static), those inner references only exist in "resolved" form.
451-
//
452-
// Assumes `id` is already canonical.
453473
if tcx.is_foreign_item(def_id) {
454-
trace!("get_global_alloc: foreign item {:?}", def_id);
455-
throw_unsup!(ReadForeignStatic(def_id))
474+
throw_unsup!(ReadExternStatic(def_id));
456475
}
457476
trace!("get_global_alloc: Need to compute {:?}", def_id);
458477
let instance = Instance::mono(tcx, def_id);
459478
let gid = GlobalId { instance, promoted: None };
460479
// Use the raw query here to break validation cycles. Later uses of the static
461480
// will call the full query anyway.
462-
let raw_const =
463-
tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
464-
// no need to report anything, the const_eval call takes care of that
465-
// for statics
466-
assert!(tcx.is_static(def_id));
467-
err
468-
})?;
481+
let raw_const = tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid))?;
469482
// Make sure we use the ID of the resolved memory, not the lazy one!
470483
let id = raw_const.alloc_id;
471484
let allocation = tcx.global_alloc(id).unwrap_memory();
@@ -482,6 +495,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
482495
alloc,
483496
M::GLOBAL_KIND.map(MemoryKind::Machine),
484497
);
498+
// Sanity check that this is the same pointer we would have gotten via `global_base_pointer`.
485499
debug_assert_eq!(tag, M::tag_global_base_pointer(memory_extra, id));
486500
Ok(alloc)
487501
}
@@ -492,7 +506,6 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
492506
&self,
493507
id: AllocId,
494508
) -> InterpResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
495-
let id = M::canonical_alloc_id(self, id);
496509
// The error type of the inner closure here is somewhat funny. We have two
497510
// ways of "erroring": An actual error, or because we got a reference from
498511
// `get_global_alloc` that we can actually use directly without inserting anything anywhere.
@@ -529,7 +542,6 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
529542
&mut self,
530543
id: AllocId,
531544
) -> InterpResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
532-
let id = M::canonical_alloc_id(self, id);
533545
let tcx = self.tcx;
534546
let memory_extra = &self.extra;
535547
let a = self.alloc_map.get_mut_or(id, || {
@@ -568,7 +580,6 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
568580
id: AllocId,
569581
liveness: AllocCheck,
570582
) -> InterpResult<'static, (Size, Align)> {
571-
let id = M::canonical_alloc_id(self, id);
572583
// # Regular allocations
573584
// Don't use `self.get_raw` here as that will
574585
// a) cause cycles in case `id` refers to a static
@@ -621,7 +632,6 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
621632
}
622633
}
623634

624-
/// Assumes `id` is already canonical.
625635
fn get_fn_alloc(&self, id: AllocId) -> Option<FnVal<'tcx, M::ExtraFnVal>> {
626636
trace!("reading fn ptr: {}", id);
627637
if let Some(extra) = self.extra_fn_ptr_map.get(&id) {
@@ -642,8 +652,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> {
642652
if ptr.offset.bytes() != 0 {
643653
throw_ub!(InvalidFunctionPointer(ptr.erase_tag()))
644654
}
645-
let id = M::canonical_alloc_id(self, ptr.alloc_id);
646-
self.get_fn_alloc(id).ok_or_else(|| err_ub!(InvalidFunctionPointer(ptr.erase_tag())).into())
655+
self.get_fn_alloc(ptr.alloc_id).ok_or_else(|| err_ub!(InvalidFunctionPointer(ptr.erase_tag())).into())
647656
}
648657

649658
pub fn mark_immutable(&mut self, id: AllocId) -> InterpResult<'tcx> {

src/librustc_mir/interpret/operand.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -541,9 +541,11 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
541541
val: &ty::Const<'tcx>,
542542
layout: Option<TyAndLayout<'tcx>>,
543543
) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> {
544-
let tag_scalar = |scalar| match scalar {
545-
Scalar::Ptr(ptr) => Scalar::Ptr(self.tag_global_base_pointer(ptr)),
546-
Scalar::Raw { data, size } => Scalar::Raw { data, size },
544+
let tag_scalar = |scalar| -> InterpResult<'tcx, _> {
545+
Ok(match scalar {
546+
Scalar::Ptr(ptr) => Scalar::Ptr(self.global_base_pointer(ptr)?),
547+
Scalar::Raw { data, size } => Scalar::Raw { data, size },
548+
})
547549
};
548550
// Early-return cases.
549551
let val_val = match val.val {
@@ -570,10 +572,6 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
570572
}
571573
ty::ConstKind::Value(val_val) => val_val,
572574
};
573-
// This call allows the machine to create fresh allocation ids for
574-
// thread-local statics (see the `adjust_global_const` function
575-
// documentation).
576-
let val_val = M::adjust_global_const(self, val_val)?;
577575
// Other cases need layout.
578576
let layout =
579577
from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(val.ty))?;
@@ -582,10 +580,10 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
582580
let id = self.tcx.create_memory_alloc(alloc);
583581
// We rely on mutability being set correctly in that allocation to prevent writes
584582
// where none should happen.
585-
let ptr = self.tag_global_base_pointer(Pointer::new(id, offset));
583+
let ptr = self.global_base_pointer(Pointer::new(id, offset))?;
586584
Operand::Indirect(MemPlace::from_ptr(ptr, layout.align.abi))
587585
}
588-
ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x).into()),
586+
ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()),
589587
ConstValue::Slice { data, start, end } => {
590588
// We rely on mutability being set correctly in `data` to prevent writes
591589
// where none should happen.
@@ -594,7 +592,7 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
594592
Size::from_bytes(start), // offset: `start`
595593
);
596594
Operand::Immediate(Immediate::new_slice(
597-
self.tag_global_base_pointer(ptr).into(),
595+
self.global_base_pointer(ptr)?.into(),
598596
u64::try_from(end.checked_sub(start).unwrap()).unwrap(), // len: `end - start`
599597
self,
600598
))

src/librustc_mir/interpret/place.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1126,7 +1126,7 @@ where
11261126
) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
11271127
// This must be an allocation in `tcx`
11281128
let _ = self.tcx.global_alloc(raw.alloc_id);
1129-
let ptr = self.tag_global_base_pointer(Pointer::from(raw.alloc_id));
1129+
let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?;
11301130
let layout = self.layout_of(raw.ty)?;
11311131
Ok(MPlaceTy::from_aligned_ptr(ptr, layout))
11321132
}

src/librustc_mir/interpret/step.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,8 +141,8 @@ impl<'mir, 'tcx: 'mir, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
141141
use rustc_middle::mir::Rvalue::*;
142142
match *rvalue {
143143
ThreadLocalRef(did) => {
144-
let id = M::thread_local_alloc_id(self, did)?;
145-
let val = Scalar::Ptr(self.tag_global_base_pointer(id.into()));
144+
let id = M::thread_local_static_alloc_id(self, did)?;
145+
let val = self.global_base_pointer(id.into())?;
146146
self.write_scalar(val, dest)?;
147147
}
148148

0 commit comments

Comments
 (0)