]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
Fix merge conflicts
[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::{MutMutable, MutImmutable};
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 }
109 /// Memory extra state gives us interior mutable access to the global state.
110 pub type MemoryExtra = Rc<RefCell<GlobalState>>;
111
112 /// Indicates which kind of access is being performed.
113 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
114 pub enum AccessKind {
115     Read,
116     Write,
117 }
118
119 impl fmt::Display for AccessKind {
120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121         match self {
122             AccessKind::Read => write!(f, "read access"),
123             AccessKind::Write => write!(f, "write access"),
124         }
125     }
126 }
127
128 /// Indicates which kind of reference is being created.
129 /// Used by high-level `reborrow` to compute which permissions to grant to the
130 /// new pointer.
131 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
132 pub enum RefKind {
133     /// `&mut` and `Box`.
134     Unique { two_phase: bool },
135     /// `&` with or without interior mutability.
136     Shared,
137     /// `*mut`/`*const` (raw pointers).
138     Raw { mutable: bool },
139 }
140
141 impl fmt::Display for RefKind {
142     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143         match self {
144             RefKind::Unique { two_phase: false } => write!(f, "unique"),
145             RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
146             RefKind::Shared => write!(f, "shared"),
147             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
148             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
149         }
150     }
151 }
152
153 /// Utilities for initialization and ID generation
154 impl Default for GlobalState {
155     fn default() -> Self {
156         GlobalState {
157             next_ptr_id: NonZeroU64::new(1).unwrap(),
158             base_ptr_ids: HashMap::default(),
159             next_call_id: NonZeroU64::new(1).unwrap(),
160             active_calls: HashSet::default(),
161         }
162     }
163 }
164
165 impl GlobalState {
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 static_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 // # Stacked Borrows Core Begin
199
200 /// We need to make at least the following things true:
201 ///
202 /// U1: After creating a `Uniq`, it is at the top.
203 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
204 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
205 ///
206 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
207 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
208 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
209 ///          gets popped.
210 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
211 /// F3: If an access happens with an `&` outside `UnsafeCell`,
212 ///     it requires the `SharedReadOnly` to still be in the stack.
213
214 /// Core relation on `Permission` to define which accesses are allowed
215 impl Permission {
216     /// This defines for a given permission, whether it permits the given kind of access.
217     fn grants(self, access: AccessKind) -> bool {
218         // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
219         self != Permission::Disabled && (access == AccessKind::Read || self != Permission::SharedReadOnly)
220     }
221 }
222
223 /// Core per-location operations: access, dealloc, reborrow.
224 impl<'tcx> Stack {
225     /// Find the item granting the given kind of access to the given tag, and return where
226     /// it is on the stack.
227     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
228         self.borrows.iter()
229             .enumerate() // we also need to know *where* in the stack
230             .rev() // search top-to-bottom
231             // Return permission of first item that grants access.
232             // We require a permission with the right tag, ensuring U3 and F3.
233             .find_map(|(idx, item)|
234                 if tag == item.tag && item.perm.grants(access) {
235                     Some(idx)
236                 } else {
237                     None
238                 }
239             )
240     }
241
242     /// Find the first write-incompatible item above the given one --
243     /// i.e, find the height to which the stack will be truncated when writing to `granting`.
244     fn find_first_write_incompaible(&self, granting: usize) -> usize {
245         let perm = self.borrows[granting].perm;
246         match perm {
247             Permission::SharedReadOnly =>
248                 bug!("Cannot use SharedReadOnly for writing"),
249             Permission::Disabled =>
250                 bug!("Cannot use Disabled for anything"),
251             Permission::Unique =>
252                 // On a write, everything above us is incompatible.
253                 granting + 1,
254             Permission::SharedReadWrite => {
255                 // The SharedReadWrite *just* above us are compatible, to skip those.
256                 let mut idx = granting + 1;
257                 while let Some(item) = self.borrows.get(idx) {
258                     if item.perm == Permission::SharedReadWrite {
259                         // Go on.
260                         idx += 1;
261                     } else {
262                         // Found first incompatible!
263                         break;
264                     }
265                 }
266                 idx
267             }
268         }
269     }
270
271     /// Check if the given item is protected.
272     fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
273         if let Some(call) = item.protector {
274             if global.is_active(call) {
275                 if let Some(tag) = tag {
276                     throw_ub!(UbExperimental(format!(
277                         "not granting access to tag {:?} because incompatible item is protected: {:?}",
278                         tag, item
279                     )));
280                 } else {
281                     throw_ub!(UbExperimental(format!(
282                         "deallocating while item is protected: {:?}", item
283                     )));
284                 }
285             }
286         }
287         Ok(())
288     }
289
290     /// Test if a memory `access` using pointer tagged `tag` is granted.
291     /// If yes, return the index of the item that granted it.
292     fn access(
293         &mut self,
294         access: AccessKind,
295         tag: Tag,
296         global: &GlobalState,
297     ) -> InterpResult<'tcx> {
298         // Two main steps: Find granting item, remove incompatible items above.
299
300         // Step 1: Find granting item.
301         let granting_idx = self.find_granting(access, tag)
302             .ok_or_else(|| err_ub!(UbExperimental(format!(
303                 "no item granting {} to tag {:?} found in borrow stack",
304                 access, tag,
305             ))))?;
306
307         // Step 2: Remove incompatible items above them.  Make sure we do not remove protected
308         // items.  Behavior differs for reads and writes.
309         if access == AccessKind::Write {
310             // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
311             // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
312             let first_incompatible_idx = self.find_first_write_incompaible(granting_idx);
313             for item in self.borrows.drain(first_incompatible_idx..).rev() {
314                 trace!("access: popping item {:?}", item);
315                 Stack::check_protector(&item, Some(tag), global)?;
316             }
317         } else {
318             // On a read, *disable* all `Unique` above the granting item.  This ensures U2 for read accesses.
319             // The reason this is not following the stack discipline (by removing the first Unique and
320             // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
321             // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
322             // `SharedReadWrite` for `raw`.
323             // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
324             // reference and use that.
325             // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
326             for idx in (granting_idx+1 .. self.borrows.len()).rev() {
327                 let item = &mut self.borrows[idx];
328                 if item.perm == Permission::Unique {
329                     trace!("access: disabling item {:?}", item);
330                     Stack::check_protector(item, Some(tag), global)?;
331                     item.perm = Permission::Disabled;
332                 }
333             }
334         }
335
336         // Done.
337         Ok(())
338     }
339
340     /// Deallocate a location: Like a write access, but also there must be no
341     /// active protectors at all because we will remove all items.
342     fn dealloc(
343         &mut self,
344         tag: Tag,
345         global: &GlobalState,
346     ) -> InterpResult<'tcx> {
347         // Step 1: Find granting item.
348         self.find_granting(AccessKind::Write, tag)
349             .ok_or_else(|| err_ub!(UbExperimental(format!(
350                 "no item granting write access for deallocation to tag {:?} found in borrow stack",
351                 tag,
352             ))))?;
353
354         // Step 2: Remove all items.  Also checks for protectors.
355         for item in self.borrows.drain(..).rev() {
356             Stack::check_protector(&item, None, global)?;
357         }
358
359         Ok(())
360     }
361
362     /// Derived a new pointer from one with the given tag.
363     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
364     /// an access, and they add the new item directly on top of the one it is derived
365     /// from instead of all the way at the top of the stack.
366     fn grant(
367         &mut self,
368         derived_from: Tag,
369         new: Item,
370         global: &GlobalState,
371     ) -> InterpResult<'tcx> {
372         // Figure out which access `perm` corresponds to.
373         let access = if new.perm.grants(AccessKind::Write) {
374             AccessKind::Write
375         } else {
376             AccessKind::Read
377         };
378         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
379         // We use that to determine where to put the new item.
380         let granting_idx = self.find_granting(access, derived_from)
381             .ok_or_else(|| err_ub!(UbExperimental(format!(
382                 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack", new.perm, derived_from,
383             ))))?;
384
385         // Compute where to put the new item.
386         // Either way, we ensure that we insert the new item in a way such that between
387         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
388         let new_idx = if new.perm == Permission::SharedReadWrite {
389             assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
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_incompaible(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(
426         size: Size,
427         perm: Permission,
428         tag: Tag,
429         extra: MemoryExtra,
430     ) -> Self {
431         let item = Item { perm, tag, protector: None };
432         let stack = Stack {
433             borrows: vec![item],
434         };
435
436         Stacks {
437             stacks: RefCell::new(RangeMap::new(size, stack)),
438             global: extra,
439         }
440     }
441
442     /// Call `f` on every stack in the range.
443     fn for_each(
444         &self,
445         ptr: Pointer<Tag>,
446         size: Size,
447         f: impl Fn(&mut Stack, &GlobalState) -> InterpResult<'tcx>,
448     ) -> InterpResult<'tcx> {
449         let global = self.global.borrow();
450         let mut stacks = self.stacks.borrow_mut();
451         for stack in stacks.iter_mut(ptr.offset, size) {
452             f(stack, &*global)?;
453         }
454         Ok(())
455     }
456 }
457
458 /// Glue code to connect with Miri Machine Hooks
459 impl Stacks {
460     pub fn new_allocation(
461         id: AllocId,
462         size: Size,
463         extra: MemoryExtra,
464         kind: MemoryKind<MiriMemoryKind>,
465     ) -> (Self, Tag) {
466         let (tag, perm) = match kind {
467             MemoryKind::Stack =>
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                 (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
474             MemoryKind::Machine(MiriMemoryKind::Static) =>
475                 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
476             _ =>
477                 (Tag::Untagged, Permission::SharedReadWrite),
478         };
479         let stack = Stacks::new(size, perm, tag, extra);
480         (stack, tag)
481     }
482
483     #[inline(always)]
484     pub fn memory_read<'tcx>(
485         &self,
486         ptr: Pointer<Tag>,
487         size: Size,
488     ) -> InterpResult<'tcx> {
489         trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
490         self.for_each(ptr, size, |stack, global| {
491             stack.access(AccessKind::Read, ptr.tag, global)?;
492             Ok(())
493         })
494     }
495
496     #[inline(always)]
497     pub fn memory_written<'tcx>(
498         &mut self,
499         ptr: Pointer<Tag>,
500         size: Size,
501     ) -> InterpResult<'tcx> {
502         trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
503         self.for_each(ptr, size, |stack, global| {
504             stack.access(AccessKind::Write, ptr.tag, global)?;
505             Ok(())
506         })
507     }
508
509     #[inline(always)]
510     pub fn memory_deallocated<'tcx>(
511         &mut self,
512         ptr: Pointer<Tag>,
513         size: Size,
514     ) -> InterpResult<'tcx> {
515         trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
516         self.for_each(ptr, size, |stack, global| {
517             stack.dealloc(ptr.tag, global)
518         })
519     }
520 }
521
522 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
523 /// to grant for which references, and when to add protectors.
524 impl<'mir, 'tcx> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
525 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
526     fn reborrow(
527         &mut self,
528         place: MPlaceTy<'tcx, Tag>,
529         size: Size,
530         kind: RefKind,
531         new_tag: Tag,
532         protect: bool,
533     ) -> InterpResult<'tcx> {
534         let this = self.eval_context_mut();
535         let protector = if protect { Some(this.frame().extra) } else { None };
536         let ptr = this.memory.check_ptr_access(place.ptr, size, place.align)
537             .expect("validity checks should have excluded dangling/unaligned pointer")
538             .expect("we shouldn't get here for ZST");
539         trace!("reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
540             kind, new_tag, ptr.tag, place.layout.ty, ptr.erase_tag(), size.bytes());
541
542         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
543         let alloc = this.memory.get(ptr.alloc_id)?;
544         let stacked_borrows = alloc.extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
545         // Update the stacks.
546         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
547         // There could be existing unique pointers reborrowed from them that should remain valid!
548         let perm = match kind {
549             RefKind::Unique { two_phase: false } => Permission::Unique,
550             RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
551             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
552             RefKind::Shared | RefKind::Raw { mutable: false } => {
553                 // Shared references and *const are a whole different kind of game, the
554                 // permission is not uniform across the entire range!
555                 // We need a frozen-sensitive reborrow.
556                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
557                     // We are only ever `SharedReadOnly` inside the frozen bits.
558                     let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
559                     let item = Item { perm, tag: new_tag, protector };
560                     stacked_borrows.for_each(cur_ptr, size, |stack, global| {
561                         stack.grant(cur_ptr.tag, item, global)
562                     })
563                 });
564             }
565         };
566         let item = Item { perm, tag: new_tag, protector };
567         stacked_borrows.for_each(ptr, size, |stack, global| {
568             stack.grant(ptr.tag, item, global)
569         })
570     }
571
572     /// Retags an indidual pointer, returning the retagged version.
573     /// `mutbl` can be `None` to make this a raw pointer.
574     fn retag_reference(
575         &mut self,
576         val: ImmTy<'tcx, Tag>,
577         kind: RefKind,
578         protect: bool,
579     ) -> InterpResult<'tcx, Immediate<Tag>> {
580         let this = self.eval_context_mut();
581         // We want a place for where the ptr *points to*, so we get one.
582         let place = this.ref_to_mplace(val)?;
583         let size = this.size_and_align_of_mplace(place)?
584             .map(|(size, _)| size)
585             .unwrap_or_else(|| place.layout.size);
586         if size == Size::ZERO {
587             // Nothing to do for ZSTs.
588             return Ok(*val);
589         }
590         let place = this.force_mplace_ptr(place)?;
591
592         // Compute new borrow.
593         let new_tag = match kind {
594             RefKind::Raw { .. } => Tag::Untagged,
595             _ => Tag::Tagged(this.memory.extra.stacked_borrows.borrow_mut().new_ptr()),
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(
610         &mut self,
611         kind: RetagKind,
612         place: PlaceTy<'tcx, Tag>
613     ) -> InterpResult<'tcx> {
614         let this = self.eval_context_mut();
615         // Determine mutability and whether to add a protector.
616         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
617         // making it useless.
618         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
619             match ty.kind {
620                 // References are simple.
621                 ty::Ref(_, _, MutMutable) =>
622                     Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
623                 ty::Ref(_, _, MutImmutable) =>
624                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
625                 // Raw pointers need to be enabled.
626                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
627                     Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
628                 // Boxes do not get a protector: protectors reflect that references outlive the call
629                 // they were passed in to; that's just not the case for boxes.
630                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
631                 _ => None,
632             }
633         }
634
635         // We only reborrow "bare" references/boxes.
636         // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
637         // but might also cost us optimization and analyses. We will have to experiment more with this.
638         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
639             // Fast path.
640             let val = this.read_immediate(this.place_to_op(place)?)?;
641             let val = this.retag_reference(val, mutbl, protector)?;
642             this.write_immediate(val, place)?;
643         }
644
645         Ok(())
646     }
647 }