]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
let the permission of a new pointer depend on the type only
[rust.git] / src / stacked_borrows.rs
1 use std::cell::RefCell;
2 use std::collections::HashSet;
3 use std::rc::Rc;
4 use std::fmt;
5 use std::num::NonZeroU64;
6
7 use rustc::ty::{self, layout::Size};
8 use rustc::hir::{MutMutable, MutImmutable};
9 use rustc::mir::RetagKind;
10
11 use crate::{
12     EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
13     MemoryKind, MiriMemoryKind, RangeMap, Allocation, AllocationExtra,
14     Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
15 };
16
17 pub type PtrId = NonZeroU64;
18 pub type CallId = u64;
19
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
22 pub enum Tag {
23     Tagged(PtrId),
24     Untagged,
25 }
26
27 impl fmt::Display for Tag {
28     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
29         match self {
30             Tag::Tagged(id) => write!(f, "{}", id),
31             Tag::Untagged => write!(f, "<untagged>"),
32         }
33     }
34 }
35
36 /// Indicates which permission is granted (by this item to some pointers)
37 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
38 pub enum Permission {
39     /// Grants unique mutable access.
40     Unique,
41     /// Grants shared mutable access.
42     SharedReadWrite,
43     /// Greants shared read-only access.
44     SharedReadOnly,
45 }
46
47 /// An item in the per-location borrow stack.
48 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
49 pub enum Item {
50     /// Grants the given permission for pointers with this tag.
51     Permission(Permission, Tag),
52     /// A barrier, tracking the function it belongs to by its index on the call stack.
53     FnBarrier(CallId),
54 }
55
56 impl fmt::Display for Item {
57     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58         match self {
59             Item::Permission(perm, tag) => write!(f, "[{:?} for {}]", perm, tag),
60             Item::FnBarrier(call) => write!(f, "[barrier {}]", call),
61         }
62     }
63 }
64
65 /// Extra per-location state.
66 #[derive(Clone, Debug, PartialEq, Eq)]
67 pub struct Stack {
68     /// Used *mostly* as a stack; never empty.
69     /// We sometimes push into the middle but never remove from the middle.
70     /// The same tag may occur multiple times, e.g. from a two-phase borrow.
71     /// Invariants:
72     /// * Above a `SharedReadOnly` there can only be barriers and more `SharedReadOnly`.
73     borrows: Vec<Item>,
74 }
75
76
77 /// Extra per-allocation state.
78 #[derive(Clone, Debug)]
79 pub struct Stacks {
80     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
81     stacks: RefCell<RangeMap<Stack>>,
82     // Pointer to global state
83     global: MemoryState,
84 }
85
86 /// Extra global state, available to the memory access hooks.
87 #[derive(Debug)]
88 pub struct GlobalState {
89     next_ptr_id: PtrId,
90     next_call_id: CallId,
91     active_calls: HashSet<CallId>,
92 }
93 pub type MemoryState = Rc<RefCell<GlobalState>>;
94
95 /// Indicates which kind of access is being performed.
96 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
97 pub enum AccessKind {
98     Read,
99     Write,
100 }
101
102 impl fmt::Display for AccessKind {
103     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
104         match self {
105             AccessKind::Read => write!(f, "read"),
106             AccessKind::Write => write!(f, "write"),
107         }
108     }
109 }
110
111 /// Indicates which kind of reference is being created.
112 /// Used by high-level `reborrow` to compute which permissions to grant to the
113 /// new pointer.
114 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
115 pub enum RefKind {
116     /// `&mut` and `Box`.
117     Unique,
118     /// `&` with or without interior mutability.
119     Shared,
120     /// `*mut`/`*const` (raw pointers).
121     Raw { mutable: bool },
122 }
123
124 impl fmt::Display for RefKind {
125     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126         match self {
127             RefKind::Unique => write!(f, "unique"),
128             RefKind::Shared => write!(f, "shared"),
129             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
130             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
131         }
132     }
133 }
134
135 /// Utilities for initialization and ID generation
136 impl Default for GlobalState {
137     fn default() -> Self {
138         GlobalState {
139             next_ptr_id: NonZeroU64::new(1).unwrap(),
140             next_call_id: 0,
141             active_calls: HashSet::default(),
142         }
143     }
144 }
145
146 impl GlobalState {
147     pub fn new_ptr(&mut self) -> PtrId {
148         let id = self.next_ptr_id;
149         self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
150         id
151     }
152
153     pub fn new_call(&mut self) -> CallId {
154         let id = self.next_call_id;
155         trace!("new_call: Assigning ID {}", id);
156         self.active_calls.insert(id);
157         self.next_call_id = id+1;
158         id
159     }
160
161     pub fn end_call(&mut self, id: CallId) {
162         assert!(self.active_calls.remove(&id));
163     }
164
165     fn is_active(&self, id: CallId) -> bool {
166         self.active_calls.contains(&id)
167     }
168 }
169
170 // # Stacked Borrows Core Begin
171
172 /// We need to make at least the following things true:
173 ///
174 /// U1: After creating a `Uniq`, it is at the top.
175 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
176 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
177 ///
178 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
179 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
180 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
181 ///          gets popped.
182 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
183 /// F3: If an access happens with an `&` outside `UnsafeCell`,
184 ///     it requires the `SharedReadOnly` to still be in the stack.
185
186 impl Default for Tag {
187     #[inline(always)]
188     fn default() -> Tag {
189         Tag::Untagged
190     }
191 }
192
193 /// Core relations on `Permission` define which accesses are allowed:
194 /// On every access, we try to find a *granting* item, and then we remove all
195 /// *incompatible* items above it.
196 impl Permission {
197     /// This defines for a given permission, whether it permits the given kind of access.
198     fn grants(self, access: AccessKind) -> bool {
199         match (self, access) {
200             // Unique and SharedReadWrite allow any kind of access.
201             (Permission::Unique, _) |
202             (Permission::SharedReadWrite, _) =>
203                 true,
204             // SharedReadOnly only permits read access.
205             (Permission::SharedReadOnly, AccessKind::Read) =>
206                 true,
207             (Permission::SharedReadOnly, AccessKind::Write) =>
208                 false,
209         }
210     }
211
212     /// This defines for a given permission, which other permissions it can tolerate "above" itself
213     /// for which kinds of accesses.
214     /// If true, then `other` is allowed to remain on top of `self` when `access` happens.
215     fn compatible_with(self, access: AccessKind, other: Permission) -> bool {
216         use self::Permission::*;
217
218         match (self, access, other) {
219             // Some cases are impossible.
220             (SharedReadOnly, _, SharedReadWrite) |
221             (SharedReadOnly, _, Unique) =>
222                 bug!("There can never be a SharedReadWrite or a Unique on top of a SharedReadOnly"),
223             // When `other` is `SharedReadOnly`, that is NEVER compatible with
224             // write accesses.
225             // This makes sure read-only pointers become invalid on write accesses (ensures F2a).
226             (_, AccessKind::Write, SharedReadOnly) =>
227                 false,
228             // When `other` is `Unique`, that is compatible with nothing.
229             // This makes sure unique pointers become invalid on incompatible accesses (ensures U2).
230             (_, _, Unique) =>
231                 false,
232             // When we are unique and this is a write/dealloc, we tolerate nothing.
233             // This makes sure we re-assert uniqueness ("being on top") on write accesses.
234             // (This is particularily important such that when a new mutable ref gets created, it gets
235             // pushed into the right item -- this behaves like a write and we assert uniqueness of the
236             // pointer from which this comes, *if* it was a unique pointer.)
237             (Unique, AccessKind::Write, _) =>
238                 false,
239             // `SharedReadWrite` items can tolerate any other akin items for any kind of access.
240             (SharedReadWrite, _, SharedReadWrite) =>
241                 true,
242             // Any item can tolerate read accesses for shared items.
243             // This includes unique items!  Reads from unique pointers do not invalidate
244             // other pointers.
245             (_, AccessKind::Read, SharedReadWrite) |
246             (_, AccessKind::Read, SharedReadOnly) =>
247                 true,
248             // That's it.
249         }
250     }
251 }
252
253 /// Core per-location operations: access, dealloc, reborrow.
254 impl<'tcx> Stack {
255     /// Find the item granting the given kind of access to the given tag, and where that item is in the stack.
256     fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<(usize, Permission)> {
257         self.borrows.iter()
258             .enumerate() // we also need to know *where* in the stack
259             .rev() // search top-to-bottom
260             // Return permission of first item that grants access.
261             // We require a permission with the right tag, ensuring U3 and F3.
262             .filter_map(|(idx, item)| match item {
263                 &Item::Permission(perm, item_tag) if perm.grants(access) && tag == item_tag =>
264                     Some((idx, perm)),
265                 _ => None,
266             })
267             .next()
268     }
269
270     /// Test if a memory `access` using pointer tagged `tag` is granted.
271     /// If yes, return the index of the item that granted it.
272     fn access(
273         &mut self,
274         access: AccessKind,
275         tag: Tag,
276         global: &GlobalState,
277     ) -> EvalResult<'tcx, usize> {
278         // Two main steps: Find granting item, remove all incompatible items above.
279         // The second step is where barriers get implemented: they "protect" the items
280         // below them, meaning that if we remove an item and then further up encounter a barrier,
281         // we raise an error.
282
283         // Step 1: Find granting item.
284         let (granting_idx, granting_perm) = self.find_granting(access, tag)
285             .ok_or_else(|| InterpError::MachineError(format!(
286                     "no item granting {} access to tag {} found in borrow stack",
287                     access, tag,
288             )))?;
289
290         // Step 2: Remove everything incompatible above them.
291         // Items below an active barrier however may not be removed, so we check that as well.
292         // We do *not* maintain a stack discipline here.  We could, in principle, decide to only
293         // keep the items immediately above `granting_idx` that are compatible, and then pop the rest.
294         // However, that kills off entire "branches" of pointer derivation too easily:
295         // in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement would pop the `Unique`
296         // from the reborrow of the first statement, and subequently also pop the `SharedReadWrite` for `raw`.
297         {
298             // Implemented with indices because there does not seem to be a nice iterator and range-based
299             // API for this.
300             let mut cur = granting_idx + 1;
301             let mut removed_item = None;
302             while let Some(item) = self.borrows.get(cur) {
303                 match *item {
304                     Item::Permission(perm, _) => {
305                         if granting_perm.compatible_with(access, perm) {
306                             // Keep this, check next.
307                             cur += 1;
308                         } else {
309                             // Aha! This is a bad one, remove it.
310                             let item = self.borrows.remove(cur);
311                             trace!("access: removing item {}", item);
312                             removed_item = Some(item);
313                         }
314                     }
315                     Item::FnBarrier(call) if !global.is_active(call) => {
316                         // An inactive barrier, just get rid of it. (Housekeeping.)
317                         self.borrows.remove(cur);
318                     }
319                     Item::FnBarrier(call) => {
320                         // We hit an active barrier!  If we have already removed an item,
321                         // we got a problem!  The barrier was supposed to protect this item.
322                         if let Some(removed_item) = removed_item {
323                             return err!(MachineError(format!(
324                                     "not granting {} access to tag {} because barrier ({}) protects incompatible item {}",
325                                     access, tag, call, removed_item
326                                 )));
327                         }
328                         // Keep this, check next.
329                         cur += 1;
330                     }
331                 }
332             }
333         }
334
335         // Done.
336         return Ok(granting_idx);
337     }
338
339     /// Deallocate a location: Like a write access, but also there must be no
340     /// barriers at all.
341     fn dealloc(
342         &mut self,
343         tag: Tag,
344         global: &GlobalState,
345     ) -> EvalResult<'tcx> {
346         // Step 1: Find granting item.
347         self.find_granting(AccessKind::Write, tag)
348             .ok_or_else(|| InterpError::MachineError(format!(
349                     "no item granting write access for deallocation to tag {} found in borrow stack",
350                     tag,
351             )))?;
352
353         // We must make sure there are no active barriers remaining on the stack.
354         // Also clear the stack, no more accesses are possible.
355         while let Some(itm) = self.borrows.pop() {
356             match itm {
357                 Item::FnBarrier(call) if global.is_active(call) => {
358                     return err!(MachineError(format!(
359                         "deallocating with active barrier ({})", call
360                     )))
361                 }
362                 _ => {},
363             }
364         }
365
366         Ok(())
367     }
368
369     /// `reborrow` helper function.
370     /// Grant `permisson` to new pointer tagged `tag`, added at `position` in the stack.
371     fn grant(&mut self, perm: Permission, tag: Tag, position: usize) {
372         // Simply add it to the "stack" -- this might add in the middle.
373         // As an optimization, do nothing if the new item is identical to one of its neighbors.
374         let item = Item::Permission(perm, tag);
375         if self.borrows[position-1] == item || self.borrows.get(position) == Some(&item) {
376             // Optimization applies, done.
377             trace!("reborrow: avoiding redundant item {}", item);
378             return;
379         }
380         trace!("reborrow: adding item {}", item);
381         self.borrows.insert(position, item);
382     }
383
384     /// `reborrow` helper function.
385     /// Adds a barrier.
386     fn barrier(&mut self, call: CallId) {
387         let itm = Item::FnBarrier(call);
388         if *self.borrows.last().unwrap() == itm {
389             // This is just an optimization, no functional change: Avoid stacking
390             // multiple identical barriers on top of each other.
391             // This can happen when a function receives several shared references
392             // that overlap.
393             trace!("reborrow: avoiding redundant extra barrier");
394         } else {
395             trace!("reborrow: adding barrier for call {}", call);
396             self.borrows.push(itm);
397         }
398     }
399
400     /// `reborrow` helper function: test that the stack invariants are still maintained.
401     fn test_invariants(&self) {
402         let mut saw_shared_read_only = false;
403         for item in self.borrows.iter() {
404             match item {
405                 Item::Permission(Permission::SharedReadOnly, _) => {
406                     saw_shared_read_only = true;
407                 }
408                 Item::Permission(perm, _) if saw_shared_read_only => {
409                     panic!("Found {:?} on top of a SharedReadOnly!", perm);
410                 }
411                 _ => {}
412             }
413         }
414     }
415
416     /// Derived a new pointer from one with the given tag.
417     fn reborrow(
418         &mut self,
419         derived_from: Tag,
420         barrier: Option<CallId>,
421         new_perm: Permission,
422         new_tag: Tag,
423         global: &GlobalState,
424     ) -> EvalResult<'tcx> {
425         // Figure out which access `perm` corresponds to.
426         let access = if new_perm.grants(AccessKind::Write) {
427                 AccessKind::Write
428             } else {
429                 AccessKind::Read
430             };
431         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
432         // We use that to determine where to put the new item.
433         let (derived_from_idx, _) = self.find_granting(access, derived_from)
434             .ok_or_else(|| InterpError::MachineError(format!(
435                     "no item to reborrow for {:?} from tag {} found in borrow stack", new_perm, derived_from,
436             )))?;
437
438         // We behave very differently for the "unsafe" case of a shared-read-write pointer
439         // ("unsafe" because this also applies to shared references with interior mutability).
440         // This is because such pointers may be reborrowed to unique pointers that actually
441         // remain valid when their "parents" get further reborrows!
442         // However, either way, we ensure that we insert the new item in a way that between
443         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
444         if new_perm == Permission::SharedReadWrite {
445             // A very liberal reborrow because the new pointer does not expect any kind of aliasing guarantee.
446             // Just insert new permission as child of old permission, and maintain everything else.
447             // This inserts "as far down as possible", which is good because it makes this pointer as
448             // long-lived as possible *and* we want all the items that are incompatible with this
449             // to actually get removed from the stack.  If we pushed a `SharedReadWrite` on top of
450             // a `SharedReadOnly`, we'd violate the invariant that `SaredReadOnly` are at the top
451             // and we'd allow write access without invalidating frozen shared references!
452             // This ensures F2b for `SharedReadWrite` by adding the new item below any
453             // potentially existing `SharedReadOnly`.
454             self.grant(new_perm, new_tag, derived_from_idx+1);
455
456             // No barrier. They can rightfully alias with `&mut`.
457             // FIXME: This means that the `dereferencable` attribute on non-frozen shared references
458             // is incorrect! They are dereferencable when the function is called, but might become
459             // non-dereferencable during the course of execution.
460             // Also see [1], [2].
461             //
462             // [1]: <https://internals.rust-lang.org/t/
463             //       is-it-possible-to-be-memory-safe-with-deallocated-self/8457/8>,
464             // [2]: <https://lists.llvm.org/pipermail/llvm-dev/2018-July/124555.html>
465         } else {
466             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
467             // Here, creating a reference actually counts as an access, and pops incompatible
468             // stuff off the stack.
469             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
470             let check_idx = self.access(access, derived_from, global)?;
471             assert_eq!(check_idx, derived_from_idx, "somehow we saw different items??");
472
473             // We insert "as far up as possible": We know only compatible items are remaining
474             // on top of `derived_from`, and we want the new item at the top so that we
475             // get the strongest possible guarantees.
476             // This ensures U1 and F1.
477             self.grant(new_perm, new_tag, self.borrows.len());
478
479             // Now is a good time to add the barrier, protecting the item we just added.
480             if let Some(call) = barrier {
481                 self.barrier(call);
482             }
483         }
484
485         // Make sure that after all this, the stack's invariant is still maintained.
486         if cfg!(debug_assertions) {
487             self.test_invariants();
488         }
489
490         Ok(())
491     }
492 }
493 // # Stacked Borrows Core End
494
495 /// Higher-level per-location operations: deref, access, dealloc, reborrow.
496 impl<'tcx> Stacks {
497     /// Creates new stack with initial tag.
498     pub(crate) fn new(
499         size: Size,
500         tag: Tag,
501         extra: MemoryState,
502     ) -> Self {
503         let item = Item::Permission(Permission::Unique, tag);
504         let stack = Stack {
505             borrows: vec![item],
506         };
507         Stacks {
508             stacks: RefCell::new(RangeMap::new(size, stack)),
509             global: extra,
510         }
511     }
512
513     /// `ptr` got used, reflect that in the stack.
514     fn access(
515         &self,
516         ptr: Pointer<Tag>,
517         size: Size,
518         access: AccessKind,
519     ) -> EvalResult<'tcx> {
520         trace!("{} access of tag {}: {:?}, size {}", access, ptr.tag, ptr, size.bytes());
521         // Even reads can have a side-effect, by invalidating other references.
522         // This is fundamentally necessary since `&mut` asserts that there
523         // are no accesses through other references, not even reads.
524         let global = self.global.borrow();
525         let mut stacks = self.stacks.borrow_mut();
526         for stack in stacks.iter_mut(ptr.offset, size) {
527             stack.access(access, ptr.tag, &*global)?;
528         }
529         Ok(())
530     }
531
532     /// `ptr` is used to deallocate.
533     fn dealloc(
534         &self,
535         ptr: Pointer<Tag>,
536         size: Size,
537     ) -> EvalResult<'tcx> {
538         trace!("deallocation with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
539         // Even reads can have a side-effect, by invalidating other references.
540         // This is fundamentally necessary since `&mut` asserts that there
541         // are no accesses through other references, not even reads.
542         let global = self.global.borrow();
543         let mut stacks = self.stacks.borrow_mut();
544         for stack in stacks.iter_mut(ptr.offset, size) {
545             stack.dealloc(ptr.tag, &*global)?;
546         }
547         Ok(())
548     }
549
550     /// Reborrow the given pointer to the new tag for the given kind of reference.
551     /// This works on `&self` because we might encounter references to constant memory.
552     fn reborrow(
553         &self,
554         ptr: Pointer<Tag>,
555         size: Size,
556         barrier: Option<CallId>,
557         new_perm: Permission,
558         new_tag: Tag,
559     ) -> EvalResult<'tcx> {
560         trace!(
561             "reborrow tag {} as {:?} {}: {:?}, size {}",
562             ptr.tag, new_perm, new_tag, ptr, size.bytes(),
563         );
564         let global = self.global.borrow();
565         let mut stacks = self.stacks.borrow_mut();
566         for stack in stacks.iter_mut(ptr.offset, size) {
567             stack.reborrow(ptr.tag, barrier, new_perm, new_tag, &*global)?;
568         }
569         Ok(())
570     }
571 }
572
573 /// Glue code to connect with Miri Machine Hooks
574 impl Stacks {
575     pub fn new_allocation(
576         size: Size,
577         extra: &MemoryState,
578         kind: MemoryKind<MiriMemoryKind>,
579     ) -> (Self, Tag) {
580         let tag = match kind {
581             MemoryKind::Stack => {
582                 // New unique borrow. This `Uniq` is not accessible by the program,
583                 // so it will only ever be used when using the local directly (i.e.,
584                 // not through a pointer). That is, whenever we directly use a local, this will pop
585                 // everything else off the stack, invalidating all previous pointers,
586                 // and in particular, *all* raw pointers. This subsumes the explicit
587                 // `reset` which the blog post [1] says to perform when accessing a local.
588                 //
589                 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
590                 Tag::Tagged(extra.borrow_mut().new_ptr())
591             }
592             _ => {
593                 Tag::Untagged
594             }
595         };
596         let stack = Stacks::new(size, tag, Rc::clone(extra));
597         (stack, tag)
598     }
599 }
600
601 impl AllocationExtra<Tag> for Stacks {
602     #[inline(always)]
603     fn memory_read<'tcx>(
604         alloc: &Allocation<Tag, Stacks>,
605         ptr: Pointer<Tag>,
606         size: Size,
607     ) -> EvalResult<'tcx> {
608         alloc.extra.access(ptr, size, AccessKind::Read)
609     }
610
611     #[inline(always)]
612     fn memory_written<'tcx>(
613         alloc: &mut Allocation<Tag, Stacks>,
614         ptr: Pointer<Tag>,
615         size: Size,
616     ) -> EvalResult<'tcx> {
617         alloc.extra.access(ptr, size, AccessKind::Write)
618     }
619
620     #[inline(always)]
621     fn memory_deallocated<'tcx>(
622         alloc: &mut Allocation<Tag, Stacks>,
623         ptr: Pointer<Tag>,
624         size: Size,
625     ) -> EvalResult<'tcx> {
626         alloc.extra.dealloc(ptr, size)
627     }
628 }
629
630 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
631 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
632     /// High-level `reborrow` operation.  This decides which reference gets which kind
633     /// of permission!
634     fn reborrow(
635         &mut self,
636         place: MPlaceTy<'tcx, Tag>,
637         size: Size,
638         kind: RefKind,
639         new_tag: Tag,
640         fn_barrier: bool,
641     ) -> EvalResult<'tcx> {
642         let this = self.eval_context_mut();
643         let barrier = if fn_barrier { Some(this.frame().extra) } else { None };
644         let ptr = place.ptr.to_ptr()?;
645         trace!("reborrow: creating new reference for {:?} (pointee {}): {}, {:?}",
646             ptr, place.layout.ty, kind, new_tag);
647
648         // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
649         let alloc = this.memory().get(ptr.alloc_id)?;
650         alloc.check_bounds(this, ptr, size)?;
651         // Update the stacks.
652         let perm = match kind {
653             RefKind::Unique => Permission::Unique,
654             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
655             RefKind::Shared | RefKind::Raw { mutable: false } => {
656                 // Shared references and *const are a whole different kind of game, the
657                 // permission is not uniform across the entire range!
658                 // We need a frozen-sensitive reborrow.
659                 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
660                     // We are only ever `SharedReadOnly` inside the frozen bits.
661                     let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
662                     alloc.extra.reborrow(cur_ptr, size, barrier, perm, new_tag)
663                 });
664             }
665         };
666         debug_assert_ne!(perm, Permission::SharedReadOnly, "SharedReadOnly must be used frozen-sensitive");
667         return alloc.extra.reborrow(ptr, size, barrier, perm, new_tag);
668     }
669
670     /// Retags an indidual pointer, returning the retagged version.
671     /// `mutbl` can be `None` to make this a raw pointer.
672     fn retag_reference(
673         &mut self,
674         val: ImmTy<'tcx, Tag>,
675         kind: RefKind,
676         fn_barrier: bool,
677         two_phase: bool,
678     ) -> EvalResult<'tcx, Immediate<Tag>> {
679         let this = self.eval_context_mut();
680         // We want a place for where the ptr *points to*, so we get one.
681         let place = this.ref_to_mplace(val)?;
682         let size = this.size_and_align_of_mplace(place)?
683             .map(|(size, _)| size)
684             .unwrap_or_else(|| place.layout.size);
685         if size == Size::ZERO {
686             // Nothing to do for ZSTs.
687             return Ok(*val);
688         }
689
690         // Compute new borrow.
691         let new_tag = match kind {
692             RefKind::Raw { .. } => Tag::Untagged,
693             _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
694         };
695
696         // Reborrow.
697         this.reborrow(place, size, kind, new_tag, fn_barrier)?;
698         let new_place = place.replace_tag(new_tag);
699         // Handle two-phase borrows.
700         if two_phase {
701             assert!(kind == RefKind::Unique, "two-phase shared borrows make no sense");
702             // Grant read access *to the parent pointer* with the old tag.  This means the same pointer
703             // has multiple items in the stack now!
704             // FIXME: Think about this some more, in particular about the interaction with cast-to-raw.
705             // Maybe find a better way to express 2-phase, now that we have a "more expressive language"
706             // in the stack.
707             let old_tag = place.ptr.to_ptr().unwrap().tag;
708             this.reborrow(new_place, size, RefKind::Shared, old_tag, /* fn_barrier: */ false)?;
709         }
710
711         // Return new pointer.
712         Ok(new_place.to_ref())
713     }
714 }
715
716 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
717 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
718     fn retag(
719         &mut self,
720         kind: RetagKind,
721         place: PlaceTy<'tcx, Tag>
722     ) -> EvalResult<'tcx> {
723         let this = self.eval_context_mut();
724         // Determine mutability and whether to add a barrier.
725         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
726         // making it useless.
727         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
728             match ty.sty {
729                 // References are simple.
730                 ty::Ref(_, _, MutMutable) =>
731                     Some((RefKind::Unique, kind == RetagKind::FnEntry)),
732                 ty::Ref(_, _, MutImmutable) =>
733                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
734                 // Raw pointers need to be enabled.
735                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
736                     Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
737                 // Boxes do not get a barrier: barriers reflect that references outlive the call
738                 // they were passed in to; that's just not the case for boxes.
739                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique, false)),
740                 _ => None,
741             }
742         }
743
744         // We need a visitor to visit all references. However, that requires
745         // a `MemPlace`, so we have a fast path for reference types that
746         // avoids allocating.
747         if let Some((mutbl, barrier)) = qualify(place.layout.ty, kind) {
748             // Fast path.
749             let val = this.read_immediate(this.place_to_op(place)?)?;
750             let val = this.retag_reference(val, mutbl, barrier, kind == RetagKind::TwoPhase)?;
751             this.write_immediate(val, place)?;
752             return Ok(());
753         }
754         let place = this.force_allocation(place)?;
755
756         let mut visitor = RetagVisitor { ecx: this, kind };
757         visitor.visit_value(place)?;
758
759         // The actual visitor.
760         struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
761             ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
762             kind: RetagKind,
763         }
764         impl<'ecx, 'a, 'mir, 'tcx>
765             MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
766         for
767             RetagVisitor<'ecx, 'a, 'mir, 'tcx>
768         {
769             type V = MPlaceTy<'tcx, Tag>;
770
771             #[inline(always)]
772             fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
773                 &mut self.ecx
774             }
775
776             // Primitives of reference type, that is the one thing we are interested in.
777             fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
778             {
779                 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
780                 // making it useless.
781                 if let Some((mutbl, barrier)) = qualify(place.layout.ty, self.kind) {
782                     let val = self.ecx.read_immediate(place.into())?;
783                     let val = self.ecx.retag_reference(
784                         val,
785                         mutbl,
786                         barrier,
787                         self.kind == RetagKind::TwoPhase
788                     )?;
789                     self.ecx.write_immediate(val, place.into())?;
790                 }
791                 Ok(())
792             }
793         }
794
795         Ok(())
796     }
797 }