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