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