]> git.lizzy.rs Git - rust.git/blob - src/stacked_borrows.rs
3a4b4ad65fa1a6f0a98f4493cce6b4fb80e649ac
[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::cmp;
7 use std::fmt;
8 use std::num::NonZeroU64;
9
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::Mutability;
12 use rustc_middle::mir::RetagKind;
13 use rustc_middle::ty::{
14     self,
15     layout::{HasParamEnv, LayoutOf},
16 };
17 use rustc_span::DUMMY_SP;
18 use rustc_target::abi::Size;
19 use std::collections::HashSet;
20
21 use crate::*;
22
23 pub mod diagnostics;
24 use diagnostics::{AllocHistory, TagHistory};
25
26 pub mod stack;
27 use stack::Stack;
28
29 pub type PtrId = NonZeroU64;
30 pub type CallId = NonZeroU64;
31
32 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
33 pub type AllocExtra = RefCell<Stacks>;
34
35 /// Tracking pointer provenance
36 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
37 pub struct SbTag(NonZeroU64);
38
39 impl SbTag {
40     pub fn new(i: u64) -> Option<Self> {
41         NonZeroU64::new(i).map(SbTag)
42     }
43
44     // The default to be used when SB is disabled
45     pub fn default() -> Self {
46         Self::new(1).unwrap()
47     }
48 }
49
50 impl fmt::Debug for SbTag {
51     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52         write!(f, "<{}>", self.0)
53     }
54 }
55
56 /// The "extra" information an SB pointer has over a regular AllocId.
57 /// Newtype for `Option<SbTag>`.
58 #[derive(Copy, Clone)]
59 pub enum SbTagExtra {
60     Concrete(SbTag),
61     Wildcard,
62 }
63
64 impl fmt::Debug for SbTagExtra {
65     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66         match self {
67             SbTagExtra::Concrete(pid) => write!(f, "{pid:?}"),
68             SbTagExtra::Wildcard => write!(f, "<wildcard>"),
69         }
70     }
71 }
72
73 impl SbTagExtra {
74     fn and_then<T>(self, f: impl FnOnce(SbTag) -> Option<T>) -> Option<T> {
75         match self {
76             SbTagExtra::Concrete(pid) => f(pid),
77             SbTagExtra::Wildcard => None,
78         }
79     }
80 }
81
82 /// Indicates which permission is granted (by this item to some pointers)
83 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
84 pub enum Permission {
85     /// Grants unique mutable access.
86     Unique,
87     /// Grants shared mutable access.
88     SharedReadWrite,
89     /// Grants shared read-only access.
90     SharedReadOnly,
91     /// Grants no access, but separates two groups of SharedReadWrite so they are not
92     /// all considered mutually compatible.
93     Disabled,
94 }
95
96 /// An item in the per-location borrow stack.
97 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
98 pub struct Item {
99     /// The permission this item grants.
100     perm: Permission,
101     /// The pointers the permission is granted to.
102     tag: SbTag,
103     /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
104     protector: Option<CallId>,
105 }
106
107 impl fmt::Debug for Item {
108     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109         write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
110         if let Some(call) = self.protector {
111             write!(f, " (call {})", call)?;
112         }
113         write!(f, "]")?;
114         Ok(())
115     }
116 }
117
118 /// Extra per-allocation state.
119 #[derive(Clone, Debug)]
120 pub struct Stacks {
121     // Even reading memory can have effects on the stack, so we need a `RefCell` here.
122     stacks: RangeMap<Stack>,
123     /// Stores past operations on this allocation
124     history: AllocHistory,
125     /// The set of tags that have been exposed inside this allocation.
126     exposed_tags: FxHashSet<SbTag>,
127 }
128
129 /// Extra global state, available to the memory access hooks.
130 #[derive(Debug)]
131 pub struct GlobalStateInner {
132     /// Next unused pointer ID (tag).
133     next_ptr_tag: SbTag,
134     /// Table storing the "base" tag for each allocation.
135     /// The base tag is the one used for the initial pointer.
136     /// We need this in a separate table to handle cyclic statics.
137     base_ptr_tags: FxHashMap<AllocId, SbTag>,
138     /// Next unused call ID (for protectors).
139     next_call_id: CallId,
140     /// Those call IDs corresponding to functions that are still running.
141     active_calls: FxHashSet<CallId>,
142     /// The pointer ids to trace
143     tracked_pointer_tags: HashSet<SbTag>,
144     /// The call ids to trace
145     tracked_call_ids: HashSet<CallId>,
146     /// Whether to recurse into datatypes when searching for pointers to retag.
147     retag_fields: bool,
148 }
149
150 /// We need interior mutable access to the global state.
151 pub type GlobalState = RefCell<GlobalStateInner>;
152
153 /// Indicates which kind of access is being performed.
154 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
155 pub enum AccessKind {
156     Read,
157     Write,
158 }
159
160 impl fmt::Display for AccessKind {
161     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162         match self {
163             AccessKind::Read => write!(f, "read access"),
164             AccessKind::Write => write!(f, "write access"),
165         }
166     }
167 }
168
169 /// Indicates which kind of reference is being created.
170 /// Used by high-level `reborrow` to compute which permissions to grant to the
171 /// new pointer.
172 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
173 pub enum RefKind {
174     /// `&mut` and `Box`.
175     Unique { two_phase: bool },
176     /// `&` with or without interior mutability.
177     Shared,
178     /// `*mut`/`*const` (raw pointers).
179     Raw { mutable: bool },
180 }
181
182 impl fmt::Display for RefKind {
183     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184         match self {
185             RefKind::Unique { two_phase: false } => write!(f, "unique"),
186             RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
187             RefKind::Shared => write!(f, "shared"),
188             RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
189             RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
190         }
191     }
192 }
193
194 /// Utilities for initialization and ID generation
195 impl GlobalStateInner {
196     pub fn new(
197         tracked_pointer_tags: HashSet<SbTag>,
198         tracked_call_ids: HashSet<CallId>,
199         retag_fields: bool,
200     ) -> Self {
201         GlobalStateInner {
202             next_ptr_tag: SbTag(NonZeroU64::new(1).unwrap()),
203             base_ptr_tags: FxHashMap::default(),
204             next_call_id: NonZeroU64::new(1).unwrap(),
205             active_calls: FxHashSet::default(),
206             tracked_pointer_tags,
207             tracked_call_ids,
208             retag_fields,
209         }
210     }
211
212     fn new_ptr(&mut self) -> SbTag {
213         let id = self.next_ptr_tag;
214         if self.tracked_pointer_tags.contains(&id) {
215             register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id.0));
216         }
217         self.next_ptr_tag = SbTag(NonZeroU64::new(id.0.get() + 1).unwrap());
218         id
219     }
220
221     pub fn new_call(&mut self) -> CallId {
222         let id = self.next_call_id;
223         trace!("new_call: Assigning ID {}", id);
224         if self.tracked_call_ids.contains(&id) {
225             register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
226         }
227         assert!(self.active_calls.insert(id));
228         self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
229         id
230     }
231
232     pub fn end_call(&mut self, id: CallId) {
233         assert!(self.active_calls.remove(&id));
234     }
235
236     fn is_active(&self, id: CallId) -> bool {
237         self.active_calls.contains(&id)
238     }
239
240     pub fn base_ptr_tag(&mut self, id: AllocId) -> SbTag {
241         self.base_ptr_tags.get(&id).copied().unwrap_or_else(|| {
242             let tag = self.new_ptr();
243             trace!("New allocation {:?} has base tag {:?}", id, tag);
244             self.base_ptr_tags.try_insert(id, tag).unwrap();
245             tag
246         })
247     }
248 }
249
250 /// Error reporting
251 pub fn err_sb_ub<'tcx>(
252     msg: String,
253     help: Option<String>,
254     history: Option<TagHistory>,
255 ) -> InterpError<'tcx> {
256     err_machine_stop!(TerminationInfo::StackedBorrowsUb { msg, help, history })
257 }
258
259 // # Stacked Borrows Core Begin
260
261 /// We need to make at least the following things true:
262 ///
263 /// U1: After creating a `Uniq`, it is at the top.
264 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
265 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
266 ///
267 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
268 /// F2: If a write access happens, it pops the `SharedReadOnly`.  This has three pieces:
269 ///     F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
270 ///          gets popped.
271 ///     F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
272 /// F3: If an access happens with an `&` outside `UnsafeCell`,
273 ///     it requires the `SharedReadOnly` to still be in the stack.
274
275 /// Core relation on `Permission` to define which accesses are allowed
276 impl Permission {
277     /// This defines for a given permission, whether it permits the given kind of access.
278     fn grants(self, access: AccessKind) -> bool {
279         // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
280         self != Permission::Disabled
281             && (access == AccessKind::Read || self != Permission::SharedReadOnly)
282     }
283 }
284
285 /// Core per-location operations: access, dealloc, reborrow.
286 impl<'tcx> Stack {
287     /// Find the first write-incompatible item above the given one --
288     /// i.e, find the height to which the stack will be truncated when writing to `granting`.
289     fn find_first_write_incompatible(&self, granting: usize) -> usize {
290         let perm = self.get(granting).unwrap().perm;
291         match perm {
292             Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
293             Permission::Disabled => bug!("Cannot use Disabled for anything"),
294             Permission::Unique => {
295                 // On a write, everything above us is incompatible.
296                 granting + 1
297             }
298             Permission::SharedReadWrite => {
299                 // The SharedReadWrite *just* above us are compatible, to skip those.
300                 let mut idx = granting + 1;
301                 while let Some(item) = self.get(idx) {
302                     if item.perm == Permission::SharedReadWrite {
303                         // Go on.
304                         idx += 1;
305                     } else {
306                         // Found first incompatible!
307                         break;
308                     }
309                 }
310                 idx
311             }
312         }
313     }
314
315     /// Check if the given item is protected.
316     ///
317     /// The `provoking_access` argument is only used to produce diagnostics.
318     /// It is `Some` when we are granting the contained access for said tag, and it is
319     /// `None` during a deallocation.
320     /// Within `provoking_access, the `AllocRange` refers the entire operation, and
321     /// the `Size` refers to the specific location in the `AllocRange` that we are
322     /// currently checking.
323     fn item_popped(
324         item: &Item,
325         provoking_access: Option<(SbTagExtra, AllocRange, Size, AccessKind)>, // just for debug printing and error messages
326         global: &GlobalStateInner,
327         alloc_history: &mut AllocHistory,
328     ) -> InterpResult<'tcx> {
329         if global.tracked_pointer_tags.contains(&item.tag) {
330             register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(
331                 *item,
332                 provoking_access.map(|(tag, _alloc_range, _size, access)| (tag, access)),
333             ));
334         }
335
336         if let Some(call) = item.protector {
337             if global.is_active(call) {
338                 if let Some((tag, _alloc_range, _offset, _access)) = provoking_access {
339                     Err(err_sb_ub(
340                         format!(
341                             "not granting access to tag {:?} because incompatible item is protected: {:?}",
342                             tag, item
343                         ),
344                         None,
345                         tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, Some(item.tag))),
346                     ))?
347                 } else {
348                     Err(err_sb_ub(
349                         format!("deallocating while item is protected: {:?}", item),
350                         None,
351                         None,
352                     ))?
353                 }
354             }
355         }
356         Ok(())
357     }
358
359     /// Test if a memory `access` using pointer tagged `tag` is granted.
360     /// If yes, return the index of the item that granted it.
361     /// `range` refers the entire operation, and `offset` refers to the specific offset into the
362     /// allocation that we are currently checking.
363     fn access(
364         &mut self,
365         access: AccessKind,
366         tag: SbTagExtra,
367         (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
368         global: &mut GlobalStateInner,
369         current_span: &mut CurrentSpan<'_, '_, 'tcx>,
370         alloc_history: &mut AllocHistory,
371         exposed_tags: &FxHashSet<SbTag>,
372     ) -> InterpResult<'tcx> {
373         // Two main steps: Find granting item, remove incompatible items above.
374
375         // Step 1: Find granting item.
376         let granting_idx = self.find_granting(access, tag, exposed_tags).map_err(|_| {
377             alloc_history.access_error(access, tag, alloc_id, alloc_range, offset, self)
378         })?;
379
380         // Step 2: Remove incompatible items above them.  Make sure we do not remove protected
381         // items.  Behavior differs for reads and writes.
382         // In case of wildcards/unknown matches, we remove everything that is *definitely* gone.
383         if access == AccessKind::Write {
384             // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
385             // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
386             let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
387                 // The granting_idx *might* be approximate, but any lower idx would remove more
388                 // things. Even if this is a Unique and the lower idx is an SRW (which removes
389                 // less), there is an SRW group boundary here so strictly more would get removed.
390                 self.find_first_write_incompatible(granting_idx)
391             } else {
392                 // We are writing to something in the unknown part.
393                 // There is a SRW group boundary between the unknown and the known, so everything is incompatible.
394                 0
395             };
396             self.pop_items_after(first_incompatible_idx, |item| {
397                 Stack::item_popped(
398                     &item,
399                     Some((tag, alloc_range, offset, access)),
400                     global,
401                     alloc_history,
402                 )?;
403                 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
404                 Ok(())
405             })?;
406         } else {
407             // On a read, *disable* all `Unique` above the granting item.  This ensures U2 for read accesses.
408             // The reason this is not following the stack discipline (by removing the first Unique and
409             // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
410             // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
411             // `SharedReadWrite` for `raw`.
412             // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
413             // reference and use that.
414             // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
415             let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
416                 // The granting_idx *might* be approximate, but any lower idx would disable more things.
417                 granting_idx + 1
418             } else {
419                 // We are reading from something in the unknown part. That means *all* `Unique` we know about are dead now.
420                 0
421             };
422             self.disable_uniques_starting_at(first_incompatible_idx, |item| {
423                 Stack::item_popped(
424                     &item,
425                     Some((tag, alloc_range, offset, access)),
426                     global,
427                     alloc_history,
428                 )?;
429                 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
430                 Ok(())
431             })?;
432         }
433
434         // If this was an approximate action, we now collapse everything into an unknown.
435         if granting_idx.is_none() || matches!(tag, SbTagExtra::Wildcard) {
436             // Compute the upper bound of the items that remain.
437             // (This is why we did all the work above: to reduce the items we have to consider here.)
438             let mut max = NonZeroU64::new(1).unwrap();
439             for i in 0..self.len() {
440                 let item = self.get(i).unwrap();
441                 // Skip disabled items, they cannot be matched anyway.
442                 if !matches!(item.perm, Permission::Disabled) {
443                     // We are looking for a strict upper bound, so add 1 to this tag.
444                     max = cmp::max(item.tag.0.checked_add(1).unwrap(), max);
445                 }
446             }
447             if let Some(unk) = self.unknown_bottom() {
448                 max = cmp::max(unk.0, max);
449             }
450             // Use `max` as new strict upper bound for everything.
451             trace!(
452                 "access: forgetting stack to upper bound {max} due to wildcard or unknown access"
453             );
454             self.set_unknown_bottom(SbTag(max));
455         }
456
457         // Done.
458         Ok(())
459     }
460
461     /// Deallocate a location: Like a write access, but also there must be no
462     /// active protectors at all because we will remove all items.
463     fn dealloc(
464         &mut self,
465         tag: SbTagExtra,
466         (alloc_id, _alloc_range, _offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
467         global: &GlobalStateInner,
468         alloc_history: &mut AllocHistory,
469         exposed_tags: &FxHashSet<SbTag>,
470     ) -> InterpResult<'tcx> {
471         // Step 1: Make sure there is a granting item.
472         self.find_granting(AccessKind::Write, tag, exposed_tags).map_err(|_| {
473             err_sb_ub(format!(
474                 "no item granting write access for deallocation to tag {:?} at {:?} found in borrow stack",
475                 tag, alloc_id,
476                 ),
477                 None,
478                 tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, None)),
479             )
480         })?;
481
482         // Step 2: Remove all items.  Also checks for protectors.
483         for idx in (0..self.len()).rev() {
484             let item = self.get(idx).unwrap();
485             Stack::item_popped(&item, None, global, alloc_history)?;
486         }
487         Ok(())
488     }
489
490     /// Derive a new pointer from one with the given tag.
491     /// `weak` controls whether this operation is weak or strong: weak granting does not act as
492     /// an access, and they add the new item directly on top of the one it is derived
493     /// from instead of all the way at the top of the stack.
494     /// `range` refers the entire operation, and `offset` refers to the specific location in
495     /// `range` that we are currently checking.
496     fn grant(
497         &mut self,
498         derived_from: SbTagExtra,
499         new: Item,
500         (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
501         global: &mut GlobalStateInner,
502         current_span: &mut CurrentSpan<'_, '_, 'tcx>,
503         alloc_history: &mut AllocHistory,
504         exposed_tags: &FxHashSet<SbTag>,
505     ) -> InterpResult<'tcx> {
506         // Figure out which access `perm` corresponds to.
507         let access =
508             if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
509
510         // Now we figure out which item grants our parent (`derived_from`) this kind of access.
511         // We use that to determine where to put the new item.
512         let granting_idx =
513             self.find_granting(access, derived_from, exposed_tags).map_err(|_| {
514                 alloc_history.grant_error(derived_from, new, alloc_id, alloc_range, offset, self)
515             })?;
516
517         // Compute where to put the new item.
518         // Either way, we ensure that we insert the new item in a way such that between
519         // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
520         let new_idx = if new.perm == Permission::SharedReadWrite {
521             assert!(
522                 access == AccessKind::Write,
523                 "this case only makes sense for stack-like accesses"
524             );
525
526             let (Some(granting_idx), SbTagExtra::Concrete(_)) = (granting_idx, derived_from) else {
527                 // The parent is a wildcard pointer or matched the unknown bottom.
528                 // This is approximate. Nobody knows what happened, so forget everything.
529                 // The new thing is SRW anyway, so we cannot push it "on top of the unkown part"
530                 // (for all we know, it might join an SRW group inside the unknown).
531                 trace!("reborrow: forgetting stack entirely due to SharedReadWrite reborrow from wildcard or unknown");
532                 self.set_unknown_bottom(global.next_ptr_tag);
533                 return Ok(());
534             };
535
536             // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
537             // access.  Instead of popping the stack, we insert the item at the place the stack would
538             // be popped to (i.e., we insert it above all the write-compatible items).
539             // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
540             self.find_first_write_incompatible(granting_idx)
541         } else {
542             // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
543             // Here, creating a reference actually counts as an access.
544             // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
545             self.access(
546                 access,
547                 derived_from,
548                 (alloc_id, alloc_range, offset),
549                 global,
550                 current_span,
551                 alloc_history,
552                 exposed_tags,
553             )?;
554
555             // We insert "as far up as possible": We know only compatible items are remaining
556             // on top of `derived_from`, and we want the new item at the top so that we
557             // get the strongest possible guarantees.
558             // This ensures U1 and F1.
559             self.len()
560         };
561
562         // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
563         // `new_idx` might be 0 if we just cleared the entire stack.
564         if self.get(new_idx) == Some(new) || (new_idx > 0 && self.get(new_idx - 1).unwrap() == new)
565         {
566             // Optimization applies, done.
567             trace!("reborrow: avoiding adding redundant item {:?}", new);
568         } else {
569             trace!("reborrow: adding item {:?}", new);
570             self.insert(new_idx, new);
571         }
572         Ok(())
573     }
574 }
575 // # Stacked Borrows Core End
576
577 /// Map per-stack operations to higher-level per-location-range operations.
578 impl<'tcx> Stacks {
579     /// Creates new stack with initial tag.
580     fn new(size: Size, perm: Permission, tag: SbTag) -> Self {
581         let item = Item { perm, tag, protector: None };
582
583         let stack = Stack::new(item);
584         Stacks {
585             stacks: RangeMap::new(size, stack),
586             history: AllocHistory::new(),
587             exposed_tags: FxHashSet::default(),
588         }
589     }
590
591     /// Call `f` on every stack in the range.
592     fn for_each(
593         &mut self,
594         range: AllocRange,
595         mut f: impl FnMut(
596             Size,
597             &mut Stack,
598             &mut AllocHistory,
599             &mut FxHashSet<SbTag>,
600         ) -> InterpResult<'tcx>,
601     ) -> InterpResult<'tcx> {
602         for (offset, stack) in self.stacks.iter_mut(range.start, range.size) {
603             f(offset, stack, &mut self.history, &mut self.exposed_tags)?;
604         }
605         Ok(())
606     }
607 }
608
609 /// Glue code to connect with Miri Machine Hooks
610 impl Stacks {
611     pub fn new_allocation(
612         id: AllocId,
613         size: Size,
614         state: &GlobalState,
615         kind: MemoryKind<MiriMemoryKind>,
616         mut current_span: CurrentSpan<'_, '_, '_>,
617     ) -> Self {
618         let mut extra = state.borrow_mut();
619         let (base_tag, perm) = match kind {
620             // New unique borrow. This tag is not accessible by the program,
621             // so it will only ever be used when using the local directly (i.e.,
622             // not through a pointer). That is, whenever we directly write to a local, this will pop
623             // everything else off the stack, invalidating all previous pointers,
624             // and in particular, *all* raw pointers.
625             MemoryKind::Stack => (extra.base_ptr_tag(id), Permission::Unique),
626             // Everything else is shared by default.
627             _ => (extra.base_ptr_tag(id), Permission::SharedReadWrite),
628         };
629         let mut stacks = Stacks::new(size, perm, base_tag);
630         stacks.history.log_creation(
631             None,
632             base_tag,
633             alloc_range(Size::ZERO, size),
634             &mut current_span,
635         );
636         stacks
637     }
638
639     #[inline(always)]
640     pub fn memory_read<'tcx>(
641         &mut self,
642         alloc_id: AllocId,
643         tag: SbTagExtra,
644         range: AllocRange,
645         state: &GlobalState,
646         mut current_span: CurrentSpan<'_, '_, 'tcx>,
647     ) -> InterpResult<'tcx> {
648         trace!(
649             "read access with tag {:?}: {:?}, size {}",
650             tag,
651             Pointer::new(alloc_id, range.start),
652             range.size.bytes()
653         );
654         let mut state = state.borrow_mut();
655         self.for_each(range, |offset, stack, history, exposed_tags| {
656             stack.access(
657                 AccessKind::Read,
658                 tag,
659                 (alloc_id, range, offset),
660                 &mut state,
661                 &mut current_span,
662                 history,
663                 exposed_tags,
664             )
665         })
666     }
667
668     #[inline(always)]
669     pub fn memory_written<'tcx>(
670         &mut self,
671         alloc_id: AllocId,
672         tag: SbTagExtra,
673         range: AllocRange,
674         state: &GlobalState,
675         mut current_span: CurrentSpan<'_, '_, 'tcx>,
676     ) -> InterpResult<'tcx> {
677         trace!(
678             "write access with tag {:?}: {:?}, size {}",
679             tag,
680             Pointer::new(alloc_id, range.start),
681             range.size.bytes()
682         );
683         let mut state = state.borrow_mut();
684         self.for_each(range, |offset, stack, history, exposed_tags| {
685             stack.access(
686                 AccessKind::Write,
687                 tag,
688                 (alloc_id, range, offset),
689                 &mut state,
690                 &mut current_span,
691                 history,
692                 exposed_tags,
693             )
694         })
695     }
696
697     #[inline(always)]
698     pub fn memory_deallocated<'tcx>(
699         &mut self,
700         alloc_id: AllocId,
701         tag: SbTagExtra,
702         range: AllocRange,
703         state: &GlobalState,
704     ) -> InterpResult<'tcx> {
705         trace!("deallocation with tag {:?}: {:?}, size {}", tag, alloc_id, range.size.bytes());
706         let state = state.borrow();
707         self.for_each(range, |offset, stack, history, exposed_tags| {
708             stack.dealloc(tag, (alloc_id, range, offset), &state, history, exposed_tags)
709         })?;
710         Ok(())
711     }
712 }
713
714 /// Retagging/reborrowing.  There is some policy in here, such as which permissions
715 /// to grant for which references, and when to add protectors.
716 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
717 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
718     /// Returns the `AllocId` the reborrow was done in, if some actual borrow stack manipulation
719     /// happened.
720     fn reborrow(
721         &mut self,
722         place: &MPlaceTy<'tcx, Tag>,
723         size: Size,
724         kind: RefKind,
725         new_tag: SbTag,
726         protect: bool,
727     ) -> InterpResult<'tcx, Option<AllocId>> {
728         let this = self.eval_context_mut();
729         let current_span = &mut this.machine.current_span();
730
731         let log_creation = |this: &MiriEvalContext<'mir, 'tcx>,
732                             current_span: &mut CurrentSpan<'_, 'mir, 'tcx>,
733                             alloc_id,
734                             base_offset,
735                             orig_tag|
736          -> InterpResult<'tcx> {
737             let SbTagExtra::Concrete(orig_tag) = orig_tag else {
738                 // FIXME: should we log this?
739                 return Ok(())
740             };
741             let extra = this.get_alloc_extra(alloc_id)?;
742             let mut stacked_borrows = extra
743                 .stacked_borrows
744                 .as_ref()
745                 .expect("we should have Stacked Borrows data")
746                 .borrow_mut();
747             stacked_borrows.history.log_creation(
748                 Some(orig_tag),
749                 new_tag,
750                 alloc_range(base_offset, size),
751                 current_span,
752             );
753             if protect {
754                 stacked_borrows.history.log_protector(orig_tag, new_tag, current_span);
755             }
756             Ok(())
757         };
758
759         if size == Size::ZERO {
760             trace!(
761                 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
762                 kind,
763                 new_tag,
764                 place.ptr,
765                 place.layout.ty,
766             );
767             // Don't update any stacks for a zero-sized access; borrow stacks are per-byte and this
768             // touches no bytes so there is no stack to put this tag in.
769             // However, if the pointer for this operation points at a real allocation we still
770             // record where it was created so that we can issue a helpful diagnostic if there is an
771             // attempt to use it for a non-zero-sized access.
772             // Dangling slices are a common case here; it's valid to get their length but with raw
773             // pointer tagging for example all calls to get_unchecked on them are invalid.
774             if let Ok((alloc_id, base_offset, orig_tag)) = this.ptr_try_get_alloc_id(place.ptr) {
775                 log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
776                 return Ok(Some(alloc_id));
777             }
778             // This pointer doesn't come with an AllocId. :shrug:
779             return Ok(None);
780         }
781         let (alloc_id, base_offset, orig_tag) = this.ptr_get_alloc_id(place.ptr)?;
782         log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
783
784         // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
785         let (alloc_size, _) = this.get_live_alloc_size_and_align(alloc_id)?;
786         if base_offset + size > alloc_size {
787             throw_ub!(PointerOutOfBounds {
788                 alloc_id,
789                 alloc_size,
790                 ptr_offset: this.machine_usize_to_isize(base_offset.bytes()),
791                 ptr_size: size,
792                 msg: CheckInAllocMsg::InboundsTest
793             });
794         }
795
796         let protector = if protect { Some(this.frame().extra.call_id) } else { None };
797         trace!(
798             "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
799             kind,
800             new_tag,
801             orig_tag,
802             place.layout.ty,
803             Pointer::new(alloc_id, base_offset),
804             size.bytes()
805         );
806
807         // Update the stacks.
808         // Make sure that raw pointers and mutable shared references are reborrowed "weak":
809         // There could be existing unique pointers reborrowed from them that should remain valid!
810         let perm = match kind {
811             RefKind::Unique { two_phase: false }
812                 if place.layout.ty.is_unpin(this.tcx.at(DUMMY_SP), this.param_env()) =>
813             {
814                 // Only if the type is unpin do we actually enforce uniqueness
815                 Permission::Unique
816             }
817             RefKind::Unique { .. } => {
818                 // Two-phase references and !Unpin references are treated as SharedReadWrite
819                 Permission::SharedReadWrite
820             }
821             RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
822             RefKind::Shared | RefKind::Raw { mutable: false } => {
823                 // Shared references and *const are a whole different kind of game, the
824                 // permission is not uniform across the entire range!
825                 // We need a frozen-sensitive reborrow.
826                 // We have to use shared references to alloc/memory_extra here since
827                 // `visit_freeze_sensitive` needs to access the global state.
828                 let extra = this.get_alloc_extra(alloc_id)?;
829
830                 let mut stacked_borrows = extra
831                     .stacked_borrows
832                     .as_ref()
833                     .expect("we should have Stacked Borrows data")
834                     .borrow_mut();
835                 let mut current_span = this.machine.current_span();
836
837                 this.visit_freeze_sensitive(place, size, |mut range, frozen| {
838                     // Adjust range.
839                     range.start += base_offset;
840                     // We are only ever `SharedReadOnly` inside the frozen bits.
841                     let perm = if frozen {
842                         Permission::SharedReadOnly
843                     } else {
844                         Permission::SharedReadWrite
845                     };
846                     let protector = if frozen {
847                         protector
848                     } else {
849                         // We do not protect inside UnsafeCell.
850                         // This fixes https://github.com/rust-lang/rust/issues/55005.
851                         None
852                     };
853                     let item = Item { perm, tag: new_tag, protector };
854                     let mut global = this.machine.stacked_borrows.as_ref().unwrap().borrow_mut();
855                     stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
856                         stack.grant(
857                             orig_tag,
858                             item,
859                             (alloc_id, range, offset),
860                             &mut global,
861                             &mut current_span,
862                             history,
863                             exposed_tags,
864                         )
865                     })
866                 })?;
867                 return Ok(Some(alloc_id));
868             }
869         };
870         // Here we can avoid `borrow()` calls because we have mutable references.
871         // Note that this asserts that the allocation is mutable -- but since we are creating a
872         // mutable pointer, that seems reasonable.
873         let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc_id)?;
874         let mut stacked_borrows = alloc_extra
875             .stacked_borrows
876             .as_mut()
877             .expect("we should have Stacked Borrows data")
878             .borrow_mut();
879         let item = Item { perm, tag: new_tag, protector };
880         let range = alloc_range(base_offset, size);
881         let mut global = machine.stacked_borrows.as_ref().unwrap().borrow_mut();
882         let current_span = &mut machine.current_span(); // `get_alloc_extra_mut` invalidated our old `current_span`
883         stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
884             stack.grant(
885                 orig_tag,
886                 item,
887                 (alloc_id, range, offset),
888                 &mut global,
889                 current_span,
890                 history,
891                 exposed_tags,
892             )
893         })?;
894
895         Ok(Some(alloc_id))
896     }
897
898     /// Retags an indidual pointer, returning the retagged version.
899     /// `mutbl` can be `None` to make this a raw pointer.
900     fn retag_reference(
901         &mut self,
902         val: &ImmTy<'tcx, Tag>,
903         kind: RefKind,
904         protect: bool,
905     ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
906         let this = self.eval_context_mut();
907         // We want a place for where the ptr *points to*, so we get one.
908         let place = this.ref_to_mplace(val)?;
909         let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
910         // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
911         // bail out -- we cannot reasonably figure out which memory range to reborrow.
912         // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
913         let size = match size {
914             Some(size) => size,
915             None => return Ok(*val),
916         };
917
918         // Compute new borrow.
919         let new_tag = this.machine.stacked_borrows.as_mut().unwrap().get_mut().new_ptr();
920
921         // Reborrow.
922         let alloc_id = this.reborrow(&place, size, kind, new_tag, protect)?;
923
924         // Adjust pointer.
925         let new_place = place.map_provenance(|p| {
926             p.map(|prov| {
927                 match alloc_id {
928                     Some(alloc_id) => {
929                         // If `reborrow` could figure out the AllocId of this ptr, hard-code it into the new one.
930                         // Even if we started out with a wildcard, this newly retagged pointer is tied to that allocation.
931                         Tag::Concrete { alloc_id, sb: new_tag }
932                     }
933                     None => {
934                         // Looks like this has to stay a wildcard pointer.
935                         assert!(matches!(prov, Tag::Wildcard));
936                         Tag::Wildcard
937                     }
938                 }
939             })
940         });
941
942         // Return new pointer.
943         Ok(ImmTy::from_immediate(new_place.to_ref(this), val.layout))
944     }
945 }
946
947 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
948 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
949     fn retag(&mut self, kind: RetagKind, place: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
950         let this = self.eval_context_mut();
951         // Determine mutability and whether to add a protector.
952         // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
953         // making it useless.
954         fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
955             match ty.kind() {
956                 // References are simple.
957                 ty::Ref(_, _, Mutability::Mut) =>
958                     Some((
959                         RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
960                         kind == RetagKind::FnEntry,
961                     )),
962                 ty::Ref(_, _, Mutability::Not) =>
963                     Some((RefKind::Shared, kind == RetagKind::FnEntry)),
964                 // Raw pointers need to be enabled.
965                 ty::RawPtr(tym) if kind == RetagKind::Raw =>
966                     Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
967                 // Boxes do not get a protector: protectors reflect that references outlive the call
968                 // they were passed in to; that's just not the case for boxes.
969                 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
970                 _ => None,
971             }
972         }
973
974         // We need a visitor to visit all references. However, that requires
975         // a `MPlaceTy` (or `OpTy), so we have a fast path for reference types that
976         // avoids allocating.
977
978         if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
979             // Fast path.
980             let val = this.read_immediate(&this.place_to_op(place)?)?;
981             let val = this.retag_reference(&val, mutbl, protector)?;
982             this.write_immediate(*val, place)?;
983             return Ok(());
984         }
985
986         // If we don't want to recurse, we are already done.
987         if !this.machine.stacked_borrows.as_mut().unwrap().get_mut().retag_fields {
988             return Ok(());
989         }
990
991         // Skip some types that have no further structure we might care about.
992         if matches!(
993             place.layout.ty.kind(),
994             ty::RawPtr(..)
995                 | ty::Ref(..)
996                 | ty::Int(..)
997                 | ty::Uint(..)
998                 | ty::Float(..)
999                 | ty::Bool
1000                 | ty::Char
1001         ) {
1002             return Ok(());
1003         }
1004         // Now go visit this thing.
1005         let place = this.force_allocation(place)?;
1006
1007         let mut visitor = RetagVisitor { ecx: this, kind };
1008         return visitor.visit_value(&place);
1009
1010         // The actual visitor.
1011         struct RetagVisitor<'ecx, 'mir, 'tcx> {
1012             ecx: &'ecx mut MiriEvalContext<'mir, 'tcx>,
1013             kind: RetagKind,
1014         }
1015         impl<'ecx, 'mir, 'tcx> MutValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
1016             for RetagVisitor<'ecx, 'mir, 'tcx>
1017         {
1018             type V = MPlaceTy<'tcx, Tag>;
1019
1020             #[inline(always)]
1021             fn ecx(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
1022                 self.ecx
1023             }
1024
1025             fn visit_value(&mut self, place: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
1026                 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
1027                     let val = self.ecx.read_immediate(&place.into())?;
1028                     let val = self.ecx.retag_reference(&val, mutbl, protector)?;
1029                     self.ecx.write_immediate(*val, &place.into())?;
1030                 } else {
1031                     // Maybe we need to go deeper.
1032                     self.walk_value(place)?;
1033                 }
1034                 Ok(())
1035             }
1036         }
1037     }
1038
1039     /// After a stack frame got pushed, retag the return place so that we are sure
1040     /// it does not alias with anything.
1041     ///
1042     /// This is a HACK because there is nothing in MIR that would make the retag
1043     /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>.
1044     fn retag_return_place(&mut self) -> InterpResult<'tcx> {
1045         let this = self.eval_context_mut();
1046         let return_place = this.frame_mut().return_place;
1047         if return_place.layout.is_zst() {
1048             // There may not be any memory here, nothing to do.
1049             return Ok(());
1050         }
1051         // We need this to be in-memory to use tagged pointers.
1052         let return_place = this.force_allocation(&return_place)?;
1053
1054         // We have to turn the place into a pointer to use the existing code.
1055         // (The pointer type does not matter, so we use a raw pointer.)
1056         let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
1057         let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout);
1058         // Reborrow it.
1059         let val = this.retag_reference(
1060             &val,
1061             RefKind::Unique { two_phase: false },
1062             /*protector*/ true,
1063         )?;
1064         // And use reborrowed pointer for return place.
1065         let return_place = this.ref_to_mplace(&val)?;
1066         this.frame_mut().return_place = return_place.into();
1067
1068         Ok(())
1069     }
1070
1071     /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
1072     fn expose_tag(&mut self, alloc_id: AllocId, tag: SbTag) {
1073         let this = self.eval_context_mut();
1074
1075         // Function pointers and dead objects don't have an alloc_extra so we ignore them.
1076         // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks.
1077         // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
1078         let (_size, _align, kind) = this.get_alloc_info(alloc_id);
1079         match kind {
1080             AllocKind::LiveData => {
1081                 // This should have alloc_extra data.
1082                 let alloc_extra = this.get_alloc_extra(alloc_id).unwrap();
1083                 trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id}");
1084                 alloc_extra.stacked_borrows.as_ref().unwrap().borrow_mut().exposed_tags.insert(tag);
1085             }
1086             AllocKind::Function | AllocKind::Dead => {
1087                 // No stacked borrows on these allocations.
1088             }
1089         }
1090     }
1091 }