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