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