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