]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
Stacked Borrows: print affected memory location on errors
[rust.git] / src / stacked_borrows.rs
1 //! Implements "Stacked Borrows".  See <https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md>
2 //! for further information.
3
4 use std::cell::RefCell;
5 use std::fmt;
6 use std::num::NonZeroU64;
7 use std::rc::Rc;
8
9 use log::trace;
10
11 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12 use rustc_middle::mir::RetagKind;
13 use rustc_middle::ty;
14 use rustc_target::abi::{Align, LayoutOf, Size};
15 use rustc_hir::Mutability;
16
17 use crate::*;
18
19 pub type PtrId = NonZeroU64;
20 pub type CallId = NonZeroU64;
21 pub type AllocExtra = Stacks;
22
23 /// Tracking pointer provenance
24 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
25 pub enum Tag {
26     Tagged(PtrId),
27     Untagged,
28 }
29
30 impl fmt::Debug for Tag {
31     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32         match self {
33             Tag::Tagged(id) => write!(f, "<{}>", id),
34             Tag::Untagged => write!(f, "<untagged>"),
35         }
36     }
37 }
38
39 /// Indicates which permission is granted (by this item to some pointers)
40 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
41 pub enum Permission {
42     /// Grants unique mutable access.
43     Unique,
44     /// Grants shared mutable access.
45     SharedReadWrite,
46     /// Grants shared read-only access.
47     SharedReadOnly,
48     /// Grants no access, but separates two groups of SharedReadWrite so they are not
49     /// all considered mutually compatible.
50     Disabled,
51 }
52
53 /// An item in the per-location borrow stack.
54 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
55 pub struct Item {
56     /// The permission this item grants.
57     perm: Permission,
58     /// The pointers the permission is granted to.
59     tag: Tag,
60     /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
61     protector: Option<CallId>,
62 }
63
64 impl fmt::Debug for Item {
65     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66         write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
67         if let Some(call) = self.protector {
68             write!(f, " (call {})", call)?;
69         }
70         write!(f, "]")?;
71         Ok(())
72     }
73 }
74
75 /// Extra per-location state.
76 #[derive(Clone, Debug, PartialEq, Eq)]
77 pub struct Stack {
78     /// Used *mostly* as a stack; never empty.
79     /// Invariants:
80     /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
81     /// * Except for `Untagged`, no tag occurs in the stack more than once.
82     borrows: Vec<Item>,
83 }
84
85 /// Extra per-allocation state.
86 #[derive(Clone, Debug)]
87 pub struct Stacks {
88     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
89     stacks: RefCell<RangeMap<Stack>>,
90     // Pointer to global state
91     global: MemoryExtra,
92 }
93
94 /// Extra global state, available to the memory access hooks.
95 #[derive(Debug)]
96 pub struct GlobalState {
97     /// Next unused pointer ID (tag).
98     next_ptr_id: PtrId,
99     /// Table storing the "base" tag for each allocation.
100     /// The base tag is the one used for the initial pointer.
101     /// We need this in a separate table to handle cyclic statics.
102     base_ptr_ids: FxHashMap<AllocId, Tag>,
103     /// Next unused call ID (for protectors).
104     next_call_id: CallId,
105     /// Those call IDs corresponding to functions that are still running.
106     active_calls: FxHashSet<CallId>,
107     /// The pointer id to trace
108     tracked_pointer_tag: Option<PtrId>,
109     /// The call id to trace
110     tracked_call_id: Option<CallId>,
111 }
112 /// Memory extra state gives us interior mutable access to the global state.
113 pub type MemoryExtra = Rc<RefCell<GlobalState>>;
114
115 /// Indicates which kind of access is being performed.
116 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
117 pub enum AccessKind {
118     Read,
119     Write,
120 }
121
122 impl fmt::Display for AccessKind {
123     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124         match self {
125             AccessKind::Read => write!(f, "read access"),
126             AccessKind::Write => write!(f, "write access"),
127         }
128     }
129 }
130
131 /// Indicates which kind of reference is being created.
132 /// Used by high-level `reborrow` to compute which permissions to grant to the
133 /// new pointer.
134 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
135 pub enum RefKind {
136     /// `&mut` and `Box`.
137     Unique { two_phase: bool },
138     /// `&` with or without interior mutability.
139     Shared,
140     /// `*mut`/`*const` (raw pointers).
141     Raw { mutable: bool },
142 }
143
144 impl fmt::Display for RefKind {
145     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146         match self {
147             RefKind::Unique { two_phase: false } => write!(f, "unique"),
148             RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
149             RefKind::Shared => write!(f, "shared"),
150             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
151             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
152         }
153     }
154 }
155
156 /// Utilities for initialization and ID generation
157 impl GlobalState {
158     pub fn new(tracked_pointer_tag: Option<PtrId>, tracked_call_id: Option<CallId>) -> Self {
159         GlobalState {
160             next_ptr_id: NonZeroU64::new(1).unwrap(),
161             base_ptr_ids: FxHashMap::default(),
162             next_call_id: NonZeroU64::new(1).unwrap(),
163             active_calls: FxHashSet::default(),
164             tracked_pointer_tag,
165             tracked_call_id,
166         }
167     }
168
169     fn new_ptr(&mut self) -> PtrId {
170         let id = self.next_ptr_id;
171         if Some(id) == self.tracked_pointer_tag {
172             register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id));
173         }
174         self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
175         id
176     }
177
178     pub fn new_call(&mut self) -> CallId {
179         let id = self.next_call_id;
180         trace!("new_call: Assigning ID {}", id);
181         if Some(id) == self.tracked_call_id {
182             register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
183         }
184         assert!(self.active_calls.insert(id));
185         self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
186         id
187     }
188
189     pub fn end_call(&mut self, id: CallId) {
190         assert!(self.active_calls.remove(&id));
191     }
192
193     fn is_active(&self, id: CallId) -> bool {
194         self.active_calls.contains(&id)
195     }
196
197     pub fn global_base_ptr(&mut self, id: AllocId) -> Tag {
198         self.base_ptr_ids.get(&id).copied().unwrap_or_else(|| {
199             let tag = Tag::Tagged(self.new_ptr());
200             trace!("New allocation {:?} has base tag {:?}", id, tag);
201             self.base_ptr_ids.insert(id, tag).unwrap_none();
202             tag
203         })
204     }
205 }
206
207 /// Error reporting
208 fn err_sb_ub(msg: String) -> InterpError<'static> {
209     err_machine_stop!(TerminationInfo::ExperimentalUb {
210         msg,
211         url: format!("https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md"),
212     })
213 }
214
215 // # Stacked Borrows Core Begin
216
217 /// We need to make at least the following things true:
218 ///
219 /// U1: After creating a `Uniq`, it is at the top.
220 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
221 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
222 ///
223 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
224 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
225 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
226 ///          gets popped.
227 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
228 /// F3: If an access happens with an `&` outside `UnsafeCell`,
229 ///     it requires the `SharedReadOnly` to still be in the stack.
230
231 /// Core relation on `Permission` to define which accesses are allowed
232 impl Permission {
233     /// This defines for a given permission, whether it permits the given kind of access.
234     fn grants(self, access: AccessKind) -> bool {
235         // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
236         self != Permission::Disabled
237             && (access == AccessKind::Read || self != Permission::SharedReadOnly)
238     }
239 }
240
241 /// Core per-location operations: access, dealloc, reborrow.
242 impl<'tcx> Stack {
243     /// Find the item granting the given kind of access to the given tag, and return where
244     /// it is on the stack.
245     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
246         self.borrows
247             .iter()
248             .enumerate() // we also need to know *where* in the stack
249             .rev() // search top-to-bottom
250             // Return permission of first item that grants access.
251             // We require a permission with the right tag, ensuring U3 and F3.
252             .find_map(
253                 |(idx, item)| {
254                     if tag == item.tag && item.perm.grants(access) { Some(idx) } else { None }
255                 },
256             )
257     }
258
259     /// Find the first write-incompatible item above the given one --
260     /// i.e, find the height to which the stack will be truncated when writing to `granting`.
261     fn find_first_write_incompatible(&self, granting: usize) -> usize {
262         let perm = self.borrows[granting].perm;
263         match perm {
264             Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
265             Permission::Disabled => bug!("Cannot use Disabled for anything"),
266             // On a write, everything above us is incompatible.
267             Permission::Unique => granting + 1,
268             Permission::SharedReadWrite => {
269                 // The SharedReadWrite *just* above us are compatible, to skip those.
270                 let mut idx = granting + 1;
271                 while let Some(item) = self.borrows.get(idx) {
272                     if item.perm == Permission::SharedReadWrite {
273                         // Go on.
274                         idx += 1;
275                     } else {
276                         // Found first incompatible!
277                         break;
278                     }
279                 }
280                 idx
281             }
282         }
283     }
284
285     /// Check if the given item is protected.
286     fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
287         if let Tag::Tagged(id) = item.tag {
288             if Some(id) == global.tracked_pointer_tag {
289                 register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(item.clone()));
290             }
291         }
292         if let Some(call) = item.protector {
293             if global.is_active(call) {
294                 if let Some(tag) = tag {
295                     Err(err_sb_ub(format!(
296                         "not granting access to tag {:?} because incompatible item is protected: {:?}",
297                         tag, item
298                     )))?
299                 } else {
300                     Err(err_sb_ub(format!(
301                         "deallocating while item is protected: {:?}",
302                         item
303                     )))?
304                 }
305             }
306         }
307         Ok(())
308     }
309
310     /// Test if a memory `access` using pointer tagged `tag` is granted.
311     /// If yes, return the index of the item that granted it.
312     fn access(&mut self, access: AccessKind, ptr: Pointer<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
313         // Two main steps: Find granting item, remove incompatible items above.
314
315         // Step 1: Find granting item.
316         let granting_idx = self.find_granting(access, ptr.tag).ok_or_else(|| {
317             err_sb_ub(format!(
318                 "no item granting {} to tag {:?} at {} found in borrow stack.",
319                 access, ptr.tag, ptr.erase_tag(),
320             ))
321         })?;
322
323         // Step 2: Remove incompatible items above them.  Make sure we do not remove protected
324         // items.  Behavior differs for reads and writes.
325         if access == AccessKind::Write {
326             // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
327             // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
328             let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
329             for item in self.borrows.drain(first_incompatible_idx..).rev() {
330                 trace!("access: popping item {:?}", item);
331                 Stack::check_protector(&item, Some(ptr.tag), global)?;
332             }
333         } else {
334             // On a read, *disable* all `Unique` above the granting item.  This ensures U2 for read accesses.
335             // The reason this is not following the stack discipline (by removing the first Unique and
336             // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
337             // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
338             // `SharedReadWrite` for `raw`.
339             // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
340             // reference and use that.
341             // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
342             for idx in ((granting_idx + 1)..self.borrows.len()).rev() {
343                 let item = &mut self.borrows[idx];
344                 if item.perm == Permission::Unique {
345                     trace!("access: disabling item {:?}", item);
346                     Stack::check_protector(item, Some(ptr.tag), global)?;
347                     item.perm = Permission::Disabled;
348                 }
349             }
350         }
351
352         // Done.
353         Ok(())
354     }
355
356     /// Deallocate a location: Like a write access, but also there must be no
357     /// active protectors at all because we will remove all items.
358     fn dealloc(&mut self, ptr: Pointer<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
359         // Step 1: Find granting item.
360         self.find_granting(AccessKind::Write, ptr.tag).ok_or_else(|| {
361             err_sb_ub(format!(
362                 "no item granting write access for deallocation to tag {:?} at {} found in borrow stack",
363                 ptr.tag, ptr.erase_tag(),
364             ))
365         })?;
366
367         // Step 2: Remove all items.  Also checks for protectors.
368         for item in self.borrows.drain(..).rev() {
369             Stack::check_protector(&item, None, global)?;
370         }
371
372         Ok(())
373     }
374
375     /// Derive a new pointer from one with the given tag.
376     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
377     /// an access, and they add the new item directly on top of the one it is derived
378     /// from instead of all the way at the top of the stack.
379     fn grant(&mut self, derived_from: Pointer<Tag>, new: Item, global: &GlobalState) -> InterpResult<'tcx> {
380         // Figure out which access `perm` corresponds to.
381         let access =
382             if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
383         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
384         // We use that to determine where to put the new item.
385         let granting_idx = self.find_granting(access, derived_from.tag)
386             .ok_or_else(|| err_sb_ub(format!(
387                 "trying to reborrow for {:?} at {}, but parent tag {:?} does not have an appropriate item in the borrow stack",
388                 new.perm, derived_from.erase_tag(), derived_from.tag,
389             )))?;
390
391         // Compute where to put the new item.
392         // Either way, we ensure that we insert the new item in a way such that between
393         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
394         let new_idx = if new.perm == Permission::SharedReadWrite {
395             assert!(
396                 access == AccessKind::Write,
397                 "this case only makes sense for stack-like accesses"
398             );
399             // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
400             // access.  Instead of popping the stack, we insert the item at the place the stack would
401             // be popped to (i.e., we insert it above all the write-compatible items).
402             // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
403             self.find_first_write_incompatible(granting_idx)
404         } else {
405             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
406             // Here, creating a reference actually counts as an access.
407             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
408             self.access(access, derived_from, global)?;
409
410             // We insert "as far up as possible": We know only compatible items are remaining
411             // on top of `derived_from`, and we want the new item at the top so that we
412             // get the strongest possible guarantees.
413             // This ensures U1 and F1.
414             self.borrows.len()
415         };
416
417         // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
418         if self.borrows[new_idx - 1] == new || self.borrows.get(new_idx) == Some(&new) {
419             // Optimization applies, done.
420             trace!("reborrow: avoiding adding redundant item {:?}", new);
421         } else {
422             trace!("reborrow: adding item {:?}", new);
423             self.borrows.insert(new_idx, new);
424         }
425
426         Ok(())
427     }
428 }
429 // # Stacked Borrows Core End
430
431 /// Map per-stack operations to higher-level per-location-range operations.
432 impl<'tcx> Stacks {
433     /// Creates new stack with initial tag.
434     fn new(size: Size, perm: Permission, tag: Tag, extra: MemoryExtra) -> Self {
435         let item = Item { perm, tag, protector: None };
436         let stack = Stack { borrows: vec![item] };
437
438         Stacks { stacks: RefCell::new(RangeMap::new(size, stack)), global: extra }
439     }
440
441     /// Call `f` on every stack in the range.
442     fn for_each(
443         &self,
444         ptr: Pointer<Tag>,
445         size: Size,
446         f: impl Fn(Pointer<Tag>, &mut Stack, &GlobalState) -> InterpResult<'tcx>,
447     ) -> InterpResult<'tcx> {
448         let global = self.global.borrow();
449         let mut stacks = self.stacks.borrow_mut();
450         for (offset, stack) in stacks.iter_mut(ptr.offset, size) {
451             let mut cur_ptr = ptr;
452             cur_ptr.offset = offset;
453             f(cur_ptr, stack, &*global)?;
454         }
455         Ok(())
456     }
457 }
458
459 /// Glue code to connect with Miri Machine Hooks
460 impl Stacks {
461     pub fn new_allocation(
462         id: AllocId,
463         size: Size,
464         extra: MemoryExtra,
465         kind: MemoryKind<MiriMemoryKind>,
466     ) -> (Self, Tag) {
467         let (tag, perm) = match kind {
468             // New unique borrow. This tag is not accessible by the program,
469             // so it will only ever be used when using the local directly (i.e.,
470             // not through a pointer). That is, whenever we directly write to a local, this will pop
471             // everything else off the stack, invalidating all previous pointers,
472             // and in particular, *all* raw pointers.
473             MemoryKind::Stack => (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
474             // `Global` memory can be referenced by global pointers from `tcx`.
475             // Thus we call `global_base_ptr` such that the global pointers get the same tag
476             // as what we use here.
477             // `ExternStatic` is used for extern statics, and thus must also be listed here.
478             // `Env` we list because we can get away with precise tracking there.
479             // The base pointer is not unique, so the base permission is `SharedReadWrite`.
480             MemoryKind::Machine(MiriMemoryKind::Global | MiriMemoryKind::ExternStatic | MiriMemoryKind::Tls | MiriMemoryKind::Env) =>
481                 (extra.borrow_mut().global_base_ptr(id), Permission::SharedReadWrite),
482             // Everything else we handle entirely untagged for now.
483             // FIXME: experiment with more precise tracking.
484             _ => (Tag::Untagged, Permission::SharedReadWrite),
485         };
486         (Stacks::new(size, perm, tag, extra), tag)
487     }
488
489     #[inline(always)]
490     pub fn memory_read<'tcx>(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
491         trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
492         self.for_each(ptr, size, |ptr, stack, global| stack.access(AccessKind::Read, ptr, global))
493     }
494
495     #[inline(always)]
496     pub fn memory_written<'tcx>(&mut self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
497         trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
498         self.for_each(ptr, size, |ptr, stack, global| stack.access(AccessKind::Write, ptr, global))
499     }
500
501     #[inline(always)]
502     pub fn memory_deallocated<'tcx>(
503         &mut self,
504         ptr: Pointer<Tag>,
505         size: Size,
506     ) -> InterpResult<'tcx> {
507         trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
508         self.for_each(ptr, size, |ptr, stack, global| stack.dealloc(ptr, global))
509     }
510 }
511
512 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
513 /// to grant for which references, and when to add protectors.
514 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
515 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
516     fn reborrow(
517         &mut self,
518         place: MPlaceTy<'tcx, Tag>,
519         size: Size,
520         kind: RefKind,
521         new_tag: Tag,
522         protect: bool,
523     ) -> InterpResult<'tcx> {
524         let this = self.eval_context_mut();
525         let protector = if protect { Some(this.frame().extra.call_id) } else { None };
526         let ptr = place.ptr.assert_ptr();
527         trace!(
528             "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
529             kind,
530             new_tag,
531             ptr.tag,
532             place.layout.ty,
533             ptr.erase_tag(),
534             size.bytes()
535         );
536
537         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
538         let extra = &this.memory.get_raw(ptr.alloc_id)?.extra;
539         let stacked_borrows =
540             extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
541         // Update the stacks.
542         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
543         // There could be existing unique pointers reborrowed from them that should remain valid!
544         let perm = match kind {
545             RefKind::Unique { two_phase: false } => Permission::Unique,
546             RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
547             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
548             RefKind::Shared | RefKind::Raw { mutable: false } => {
549                 // Shared references and *const are a whole different kind of game, the
550                 // permission is not uniform across the entire range!
551                 // We need a frozen-sensitive reborrow.
552                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
553                     // We are only ever `SharedReadOnly` inside the frozen bits.
554                     let perm = if frozen {
555                         Permission::SharedReadOnly
556                     } else {
557                         Permission::SharedReadWrite
558                     };
559                     let item = Item { perm, tag: new_tag, protector };
560                     stacked_borrows.for_each(cur_ptr, size, |cur_ptr, stack, global| {
561                         stack.grant(cur_ptr, item, global)
562                     })
563                 });
564             }
565         };
566         let item = Item { perm, tag: new_tag, protector };
567         stacked_borrows.for_each(ptr, size, |ptr, stack, global| stack.grant(ptr, item, global))
568     }
569
570     /// Retags an indidual pointer, returning the retagged version.
571     /// `mutbl` can be `None` to make this a raw pointer.
572     fn retag_reference(
573         &mut self,
574         val: ImmTy<'tcx, Tag>,
575         kind: RefKind,
576         protect: bool,
577     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
578         let this = self.eval_context_mut();
579         // We want a place for where the ptr *points to*, so we get one.
580         let place = this.ref_to_mplace(val)?;
581         let size = this
582             .size_and_align_of_mplace(place)?
583             .map(|(size, _)| size)
584             .unwrap_or_else(|| place.layout.size);
585         // `reborrow` relies on getting a `Pointer` and everything being in-bounds,
586         // so let's ensure that. However, we do not care about alignment.
587         // We can see dangling ptrs in here e.g. after a Box's `Unique` was
588         // updated using "self.0 = ..." (can happen in Box::from_raw) so we cannot ICE; see miri#1050.
589         let place = this.mplace_access_checked(place, Some(Align::from_bytes(1).unwrap()))?;
590         // Nothing to do for ZSTs.
591         if size == Size::ZERO {
592             return Ok(val);
593         }
594
595         // Compute new borrow.
596         let new_tag = match kind {
597             // Give up tracking for raw pointers.
598             // FIXME: Experiment with more precise tracking. Blocked on `&raw`
599             // because `Rc::into_raw` currently creates intermediate references,
600             // breaking `Rc::from_raw`.
601             RefKind::Raw { .. } => Tag::Untagged,
602             // All other pointesr are properly tracked.
603             _ => Tag::Tagged(
604                 this.memory.extra.stacked_borrows.as_ref().unwrap().borrow_mut().new_ptr(),
605             ),
606         };
607
608         // Reborrow.
609         this.reborrow(place, size, kind, new_tag, protect)?;
610         let new_place = place.replace_tag(new_tag);
611
612         // Return new pointer.
613         Ok(ImmTy::from_immediate(new_place.to_ref(), val.layout))
614     }
615 }
616
617 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
618 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
619     fn retag(&mut self, kind: RetagKind, place: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
620         let this = self.eval_context_mut();
621         // Determine mutability and whether to add a protector.
622         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
623         // making it useless.
624         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
625             match ty.kind() {
626                 // References are simple.
627                 ty::Ref(_, _, Mutability::Mut) => Some((
628                     RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
629                     kind == RetagKind::FnEntry,
630                 )),
631                 ty::Ref(_, _, Mutability::Not) =>
632                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
633                 // Raw pointers need to be enabled.
634                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
635                     Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
636                 // Boxes do not get a protector: protectors reflect that references outlive the call
637                 // they were passed in to; that's just not the case for boxes.
638                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
639                 _ => None,
640             }
641         }
642
643         // We only reborrow "bare" references/boxes.
644         // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
645         // but might also cost us optimization and analyses. We will have to experiment more with this.
646         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
647             // Fast path.
648             let val = this.read_immediate(this.place_to_op(place)?)?;
649             let val = this.retag_reference(val, mutbl, protector)?;
650             this.write_immediate(*val, place)?;
651         }
652
653         Ok(())
654     }
655
656     /// After a stack frame got pushed, retag the return place so that we are sure
657     /// it does not alias with anything.
658     /// 
659     /// This is a HACK because there is nothing in MIR that would make the retag
660     /// explicit. Also see https://github.com/rust-lang/rust/issues/71117.
661     fn retag_return_place(&mut self) -> InterpResult<'tcx> {
662         let this = self.eval_context_mut();
663         let return_place = if let Some(return_place) = this.frame_mut().return_place {
664             return_place
665         } else {
666             // No return place, nothing to do.
667             return Ok(());
668         };
669         if return_place.layout.is_zst() {
670             // There may not be any memory here, nothing to do.
671             return Ok(());
672         }
673         // We need this to be in-memory to use tagged pointers.
674         let return_place = this.force_allocation(return_place)?;
675
676         // We have to turn the place into a pointer to use the existing code.
677         // (The pointer type does not matter, so we use a raw pointer.)
678         let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
679         let val = ImmTy::from_immediate(return_place.to_ref(), ptr_layout);
680         // Reborrow it.
681         let val = this.retag_reference(val, RefKind::Unique { two_phase: false }, /*protector*/ true)?;
682         // And use reborrowed pointer for return place.
683         let return_place = this.ref_to_mplace(val)?;
684         this.frame_mut().return_place = Some(return_place.into());
685
686         Ok(())
687     }
688 }