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