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