1 //! Implements "Stacked Borrows". See <https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md>
2 //! for further information.
5 use std::cell::RefCell;
7 use std::num::NonZeroU64;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_hir::Mutability;
11 use rustc_middle::mir::RetagKind;
13 use rustc_target::abi::{Align, LayoutOf, Size};
17 pub type PtrId = NonZeroU64;
18 pub type CallId = NonZeroU64;
19 pub type AllocExtra = Stacks;
21 /// Tracking pointer provenance
22 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
28 impl fmt::Debug for Tag {
29 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 Tag::Tagged(id) => write!(f, "<{}>", id),
32 Tag::Untagged => write!(f, "<untagged>"),
37 /// Indicates which permission is granted (by this item to some pointers)
38 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
40 /// Grants unique mutable access.
42 /// Grants shared mutable access.
44 /// Grants shared read-only access.
46 /// Grants no access, but separates two groups of SharedReadWrite so they are not
47 /// all considered mutually compatible.
51 /// An item in the per-location borrow stack.
52 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
54 /// The permission this item grants.
56 /// The pointers the permission is granted to.
58 /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
59 protector: Option<CallId>,
62 impl fmt::Debug for Item {
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
65 if let Some(call) = self.protector {
66 write!(f, " (call {})", call)?;
73 /// Extra per-location state.
74 #[derive(Clone, Debug, PartialEq, Eq)]
76 /// Used *mostly* as a stack; never empty.
78 /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
79 /// * Except for `Untagged`, no tag occurs in the stack more than once.
83 /// Extra per-allocation state.
84 #[derive(Clone, Debug)]
86 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
87 stacks: RefCell<RangeMap<Stack>>,
90 /// Extra global state, available to the memory access hooks.
92 pub struct GlobalState {
93 /// Next unused pointer ID (tag).
95 /// Table storing the "base" tag for each allocation.
96 /// The base tag is the one used for the initial pointer.
97 /// We need this in a separate table to handle cyclic statics.
98 base_ptr_ids: FxHashMap<AllocId, Tag>,
99 /// Next unused call ID (for protectors).
100 next_call_id: CallId,
101 /// Those call IDs corresponding to functions that are still running.
102 active_calls: FxHashSet<CallId>,
103 /// The pointer id to trace
104 tracked_pointer_tag: Option<PtrId>,
105 /// The call id to trace
106 tracked_call_id: Option<CallId>,
107 /// Whether to track raw pointers.
110 /// Memory extra state gives us interior mutable access to the global state.
111 pub type MemoryExtra = RefCell<GlobalState>;
113 /// Indicates which kind of access is being performed.
114 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
115 pub enum AccessKind {
120 impl fmt::Display for AccessKind {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 AccessKind::Read => write!(f, "read access"),
124 AccessKind::Write => write!(f, "write access"),
129 /// Indicates which kind of reference is being created.
130 /// Used by high-level `reborrow` to compute which permissions to grant to the
132 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
134 /// `&mut` and `Box`.
135 Unique { two_phase: bool },
136 /// `&` with or without interior mutability.
138 /// `*mut`/`*const` (raw pointers).
139 Raw { mutable: bool },
142 impl fmt::Display for RefKind {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 RefKind::Unique { two_phase: false } => write!(f, "unique"),
146 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
147 RefKind::Shared => write!(f, "shared"),
148 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
149 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
154 /// Utilities for initialization and ID generation
157 tracked_pointer_tag: Option<PtrId>,
158 tracked_call_id: Option<CallId>,
162 next_ptr_id: NonZeroU64::new(1).unwrap(),
163 base_ptr_ids: FxHashMap::default(),
164 next_call_id: NonZeroU64::new(1).unwrap(),
165 active_calls: FxHashSet::default(),
172 fn new_ptr(&mut self) -> PtrId {
173 let id = self.next_ptr_id;
174 if Some(id) == self.tracked_pointer_tag {
175 register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id));
177 self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
181 pub fn new_call(&mut self) -> CallId {
182 let id = self.next_call_id;
183 trace!("new_call: Assigning ID {}", id);
184 if Some(id) == self.tracked_call_id {
185 register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
187 assert!(self.active_calls.insert(id));
188 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
192 pub fn end_call(&mut self, id: CallId) {
193 assert!(self.active_calls.remove(&id));
196 fn is_active(&self, id: CallId) -> bool {
197 self.active_calls.contains(&id)
200 pub fn global_base_ptr(&mut self, id: AllocId) -> Tag {
201 self.base_ptr_ids.get(&id).copied().unwrap_or_else(|| {
202 let tag = Tag::Tagged(self.new_ptr());
203 trace!("New allocation {:?} has base tag {:?}", id, tag);
204 self.base_ptr_ids.try_insert(id, tag).unwrap();
211 fn err_sb_ub(msg: String) -> InterpError<'static> {
212 err_machine_stop!(TerminationInfo::ExperimentalUb {
215 "https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md"
220 // # Stacked Borrows Core Begin
222 /// We need to make at least the following things true:
224 /// U1: After creating a `Uniq`, it is at the top.
225 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
226 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
228 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
229 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
230 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
232 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
233 /// F3: If an access happens with an `&` outside `UnsafeCell`,
234 /// it requires the `SharedReadOnly` to still be in the stack.
236 /// Core relation on `Permission` to define which accesses are allowed
238 /// This defines for a given permission, whether it permits the given kind of access.
239 fn grants(self, access: AccessKind) -> bool {
240 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
241 self != Permission::Disabled
242 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
246 /// Core per-location operations: access, dealloc, reborrow.
248 /// Find the item granting the given kind of access to the given tag, and return where
249 /// it is on the stack.
250 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
253 .enumerate() // we also need to know *where* in the stack
254 .rev() // search top-to-bottom
255 // Return permission of first item that grants access.
256 // We require a permission with the right tag, ensuring U3 and F3.
259 if tag == item.tag && item.perm.grants(access) { Some(idx) } else { None }
264 /// Find the first write-incompatible item above the given one --
265 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
266 fn find_first_write_incompatible(&self, granting: usize) -> usize {
267 let perm = self.borrows[granting].perm;
269 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
270 Permission::Disabled => bug!("Cannot use Disabled for anything"),
271 // On a write, everything above us is incompatible.
272 Permission::Unique => granting + 1,
273 Permission::SharedReadWrite => {
274 // The SharedReadWrite *just* above us are compatible, to skip those.
275 let mut idx = granting + 1;
276 while let Some(item) = self.borrows.get(idx) {
277 if item.perm == Permission::SharedReadWrite {
281 // Found first incompatible!
290 /// Check if the given item is protected.
291 fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
292 if let Tag::Tagged(id) = item.tag {
293 if Some(id) == global.tracked_pointer_tag {
294 register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(item.clone()));
297 if let Some(call) = item.protector {
298 if global.is_active(call) {
299 if let Some(tag) = tag {
300 Err(err_sb_ub(format!(
301 "not granting access to tag {:?} because incompatible item is protected: {:?}",
305 Err(err_sb_ub(format!("deallocating while item is protected: {:?}", item)))?
312 /// Test if a memory `access` using pointer tagged `tag` is granted.
313 /// If yes, return the index of the item that granted it.
318 global: &GlobalState,
319 ) -> InterpResult<'tcx> {
320 // Two main steps: Find granting item, remove incompatible items above.
322 // Step 1: Find granting item.
323 let granting_idx = self.find_granting(access, ptr.tag).ok_or_else(|| {
325 "no item granting {} to tag {:?} at {} found in borrow stack.",
332 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
333 // items. Behavior differs for reads and writes.
334 if access == AccessKind::Write {
335 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
336 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
337 let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
338 for item in self.borrows.drain(first_incompatible_idx..).rev() {
339 trace!("access: popping item {:?}", item);
340 Stack::check_protector(&item, Some(ptr.tag), global)?;
343 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
344 // The reason this is not following the stack discipline (by removing the first Unique and
345 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
346 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
347 // `SharedReadWrite` for `raw`.
348 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
349 // reference and use that.
350 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
351 for idx in ((granting_idx + 1)..self.borrows.len()).rev() {
352 let item = &mut self.borrows[idx];
353 if item.perm == Permission::Unique {
354 trace!("access: disabling item {:?}", item);
355 Stack::check_protector(item, Some(ptr.tag), global)?;
356 item.perm = Permission::Disabled;
365 /// Deallocate a location: Like a write access, but also there must be no
366 /// active protectors at all because we will remove all items.
367 fn dealloc(&mut self, ptr: Pointer<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
368 // Step 1: Find granting item.
369 self.find_granting(AccessKind::Write, ptr.tag).ok_or_else(|| {
371 "no item granting write access for deallocation to tag {:?} at {} found in borrow stack",
372 ptr.tag, ptr.erase_tag(),
376 // Step 2: Remove all items. Also checks for protectors.
377 for item in self.borrows.drain(..).rev() {
378 Stack::check_protector(&item, None, global)?;
384 /// Derive a new pointer from one with the given tag.
385 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
386 /// an access, and they add the new item directly on top of the one it is derived
387 /// from instead of all the way at the top of the stack.
390 derived_from: Pointer<Tag>,
392 global: &GlobalState,
393 ) -> InterpResult<'tcx> {
394 // Figure out which access `perm` corresponds to.
396 if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
397 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
398 // We use that to determine where to put the new item.
399 let granting_idx = self.find_granting(access, derived_from.tag)
400 .ok_or_else(|| err_sb_ub(format!(
401 "trying to reborrow for {:?} at {}, but parent tag {:?} does not have an appropriate item in the borrow stack",
402 new.perm, derived_from.erase_tag(), derived_from.tag,
405 // Compute where to put the new item.
406 // Either way, we ensure that we insert the new item in a way such that between
407 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
408 let new_idx = if new.perm == Permission::SharedReadWrite {
410 access == AccessKind::Write,
411 "this case only makes sense for stack-like accesses"
413 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
414 // access. Instead of popping the stack, we insert the item at the place the stack would
415 // be popped to (i.e., we insert it above all the write-compatible items).
416 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
417 self.find_first_write_incompatible(granting_idx)
419 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
420 // Here, creating a reference actually counts as an access.
421 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
422 self.access(access, derived_from, global)?;
424 // We insert "as far up as possible": We know only compatible items are remaining
425 // on top of `derived_from`, and we want the new item at the top so that we
426 // get the strongest possible guarantees.
427 // This ensures U1 and F1.
431 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
432 if self.borrows[new_idx - 1] == new || self.borrows.get(new_idx) == Some(&new) {
433 // Optimization applies, done.
434 trace!("reborrow: avoiding adding redundant item {:?}", new);
436 trace!("reborrow: adding item {:?}", new);
437 self.borrows.insert(new_idx, new);
443 // # Stacked Borrows Core End
445 /// Map per-stack operations to higher-level per-location-range operations.
447 /// Creates new stack with initial tag.
448 fn new(size: Size, perm: Permission, tag: Tag) -> Self {
449 let item = Item { perm, tag, protector: None };
450 let stack = Stack { borrows: vec![item] };
452 Stacks { stacks: RefCell::new(RangeMap::new(size, stack)) }
455 /// Call `f` on every stack in the range.
460 f: impl Fn(Pointer<Tag>, &mut Stack) -> InterpResult<'tcx>,
461 ) -> InterpResult<'tcx> {
462 let mut stacks = self.stacks.borrow_mut();
463 for (offset, stack) in stacks.iter_mut(ptr.offset, size) {
464 let mut cur_ptr = ptr;
465 cur_ptr.offset = offset;
471 /// Call `f` on every stack in the range.
476 f: impl Fn(Pointer<Tag>, &mut Stack) -> InterpResult<'tcx>,
477 ) -> InterpResult<'tcx> {
478 let stacks = self.stacks.get_mut();
479 for (offset, stack) in stacks.iter_mut(ptr.offset, size) {
480 let mut cur_ptr = ptr;
481 cur_ptr.offset = offset;
488 /// Glue code to connect with Miri Machine Hooks
490 pub fn new_allocation(
494 kind: MemoryKind<MiriMemoryKind>,
496 let mut extra = extra.borrow_mut();
497 let (tag, perm) = match kind {
498 // New unique borrow. This tag is not accessible by the program,
499 // so it will only ever be used when using the local directly (i.e.,
500 // not through a pointer). That is, whenever we directly write to a local, this will pop
501 // everything else off the stack, invalidating all previous pointers,
502 // and in particular, *all* raw pointers.
503 MemoryKind::Stack => (Tag::Tagged(extra.new_ptr()), Permission::Unique),
504 // `Global` memory can be referenced by global pointers from `tcx`.
505 // Thus we call `global_base_ptr` such that the global pointers get the same tag
506 // as what we use here.
507 // `ExternStatic` is used for extern statics, and thus must also be listed here.
508 // `Env` we list because we can get away with precise tracking there.
509 // The base pointer is not unique, so the base permission is `SharedReadWrite`.
511 MiriMemoryKind::Global
512 | MiriMemoryKind::ExternStatic
513 | MiriMemoryKind::Tls
514 | MiriMemoryKind::Env,
515 ) => (extra.global_base_ptr(id), Permission::SharedReadWrite),
516 // Everything else we handle like raw pointers for now.
519 if extra.track_raw { Tag::Tagged(extra.new_ptr()) } else { Tag::Untagged };
520 (tag, Permission::SharedReadWrite)
523 (Stacks::new(size, perm, tag), tag)
527 pub fn memory_read<'tcx>(
532 ) -> InterpResult<'tcx> {
533 trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
534 let global = &*extra.borrow();
535 self.for_each(ptr, size, move |ptr, stack| stack.access(AccessKind::Read, ptr, global))
539 pub fn memory_written<'tcx>(
543 extra: &mut MemoryExtra,
544 ) -> InterpResult<'tcx> {
545 trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
546 let global = extra.get_mut();
547 self.for_each_mut(ptr, size, move |ptr, stack| stack.access(AccessKind::Write, ptr, global))
551 pub fn memory_deallocated<'tcx>(
555 extra: &mut MemoryExtra,
556 ) -> InterpResult<'tcx> {
557 trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
558 let global = extra.get_mut();
559 self.for_each_mut(ptr, size, move |ptr, stack| stack.dealloc(ptr, global))
563 /// Retagging/reborrowing. There is some policy in here, such as which permissions
564 /// to grant for which references, and when to add protectors.
565 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
566 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
569 place: &MPlaceTy<'tcx, Tag>,
574 ) -> InterpResult<'tcx> {
575 // Nothing to do for ZSTs.
576 if size == Size::ZERO {
578 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
587 let this = self.eval_context_mut();
588 let protector = if protect { Some(this.frame().extra.call_id) } else { None };
589 let ptr = place.ptr.assert_ptr();
591 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
600 // Update the stacks.
601 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
602 // There could be existing unique pointers reborrowed from them that should remain valid!
603 let perm = match kind {
604 RefKind::Unique { two_phase: false } => Permission::Unique,
605 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
606 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
607 RefKind::Shared | RefKind::Raw { mutable: false } => {
608 // Shared references and *const are a whole different kind of game, the
609 // permission is not uniform across the entire range!
610 // We need a frozen-sensitive reborrow.
611 // We have to use shared references to alloc/memory_extra here since
612 // `visit_freeze_sensitive` needs to access the global state.
613 let extra = this.memory.get_alloc_extra(ptr.alloc_id)?;
614 let stacked_borrows =
615 extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
616 let global = this.memory.extra.stacked_borrows.as_ref().unwrap().borrow();
617 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
618 // We are only ever `SharedReadOnly` inside the frozen bits.
619 let perm = if frozen {
620 Permission::SharedReadOnly
622 Permission::SharedReadWrite
624 let item = Item { perm, tag: new_tag, protector };
625 stacked_borrows.for_each(cur_ptr, size, |cur_ptr, stack| {
626 stack.grant(cur_ptr, item, &*global)
631 // Here we can avoid `borrow()` calls because we have mutable references.
632 // Note that this asserts that the allocation is mutable -- but since we are creating a
633 // mutable pointer, that seems reasonable.
634 let (alloc_extra, memory_extra) = this.memory.get_alloc_extra_mut(ptr.alloc_id)?;
635 let stacked_borrows =
636 alloc_extra.stacked_borrows.as_mut().expect("we should have Stacked Borrows data");
637 let global = memory_extra.stacked_borrows.as_mut().unwrap().get_mut();
638 let item = Item { perm, tag: new_tag, protector };
639 stacked_borrows.for_each_mut(ptr, size, |ptr, stack| stack.grant(ptr, item, global))
642 /// Retags an indidual pointer, returning the retagged version.
643 /// `mutbl` can be `None` to make this a raw pointer.
646 val: &ImmTy<'tcx, Tag>,
649 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
650 let this = self.eval_context_mut();
651 // We want a place for where the ptr *points to*, so we get one.
652 let place = this.ref_to_mplace(val)?;
653 let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
654 // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
655 // bail out -- we cannot reasonably figure out which memory range to reborrow.
656 // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
657 let size = match size {
659 None => return Ok(*val),
661 // `reborrow` relies on getting a `Pointer` and everything being in-bounds,
662 // so let's ensure that. However, we do not care about alignment.
663 // We can see dangling ptrs in here e.g. after a Box's `Unique` was
664 // updated using "self.0 = ..." (can happen in Box::from_raw) so we cannot ICE; see miri#1050.
665 let place = this.mplace_access_checked(place, Some(Align::from_bytes(1).unwrap()))?;
667 // Compute new borrow.
669 let mem_extra = this.memory.extra.stacked_borrows.as_mut().unwrap().get_mut();
671 // Give up tracking for raw pointers.
672 RefKind::Raw { .. } if !mem_extra.track_raw => Tag::Untagged,
673 // All other pointers are properly tracked.
674 _ => Tag::Tagged(mem_extra.new_ptr()),
679 this.reborrow(&place, size, kind, new_tag, protect)?;
680 let new_place = place.replace_tag(new_tag);
682 // Return new pointer.
683 Ok(ImmTy::from_immediate(new_place.to_ref(), val.layout))
687 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
688 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
689 fn retag(&mut self, kind: RetagKind, place: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
690 let this = self.eval_context_mut();
691 // Determine mutability and whether to add a protector.
692 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
693 // making it useless.
694 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
696 // References are simple.
697 ty::Ref(_, _, Mutability::Mut) => Some((
698 RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
699 kind == RetagKind::FnEntry,
701 ty::Ref(_, _, Mutability::Not) =>
702 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
703 // Raw pointers need to be enabled.
704 ty::RawPtr(tym) if kind == RetagKind::Raw =>
705 Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
706 // Boxes do not get a protector: protectors reflect that references outlive the call
707 // they were passed in to; that's just not the case for boxes.
708 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
713 // We only reborrow "bare" references/boxes.
714 // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
715 // but might also cost us optimization and analyses. We will have to experiment more with this.
716 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
718 let val = this.read_immediate(&this.place_to_op(place)?)?;
719 let val = this.retag_reference(&val, mutbl, protector)?;
720 this.write_immediate(*val, place)?;
726 /// After a stack frame got pushed, retag the return place so that we are sure
727 /// it does not alias with anything.
729 /// This is a HACK because there is nothing in MIR that would make the retag
730 /// explicit. Also see https://github.com/rust-lang/rust/issues/71117.
731 fn retag_return_place(&mut self) -> InterpResult<'tcx> {
732 let this = self.eval_context_mut();
733 let return_place = if let Some(return_place) = this.frame_mut().return_place {
736 // No return place, nothing to do.
739 if return_place.layout.is_zst() {
740 // There may not be any memory here, nothing to do.
743 // We need this to be in-memory to use tagged pointers.
744 let return_place = this.force_allocation(&return_place)?;
746 // We have to turn the place into a pointer to use the existing code.
747 // (The pointer type does not matter, so we use a raw pointer.)
748 let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
749 let val = ImmTy::from_immediate(return_place.to_ref(), ptr_layout);
751 let val = this.retag_reference(
753 RefKind::Unique { two_phase: false },
756 // And use reborrowed pointer for return place.
757 let return_place = this.ref_to_mplace(&val)?;
758 this.frame_mut().return_place = Some(return_place.into());