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