1 //! Implements "Stacked Borrows". See <https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md>
2 //! for further information.
6 use std::fmt::{self, Write};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_middle::mir::{Mutability, RetagKind};
10 use rustc_middle::ty::{
12 layout::{HasParamEnv, LayoutOf},
14 use rustc_target::abi::{Abi, Size};
16 use crate::borrow_tracker::{
17 stacked_borrows::diagnostics::{AllocHistory, DiagnosticCx, DiagnosticCxBuilder, TagHistory},
18 AccessKind, GlobalStateInner, ProtectorKind, RetagCause, RetagFields,
23 pub use item::{Item, Permission};
28 pub type AllocState = Stacks;
30 /// Extra per-allocation state.
31 #[derive(Clone, Debug)]
33 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
34 stacks: RangeMap<Stack>,
35 /// Stores past operations on this allocation
36 history: AllocHistory,
37 /// The set of tags that have been exposed inside this allocation.
38 exposed_tags: FxHashSet<BorTag>,
39 /// Whether this memory has been modified since the last time the tag GC ran
40 modified_since_last_gc: bool,
43 /// Indicates which kind of reference is being created.
44 /// Used by high-level `reborrow` to compute which permissions to grant to the
46 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
49 Unique { two_phase: bool },
50 /// `&` with or without interior mutability.
52 /// `*mut`/`*const` (raw pointers).
53 Raw { mutable: bool },
56 impl fmt::Display for RefKind {
57 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 RefKind::Unique { two_phase: false } => write!(f, "unique reference"),
60 RefKind::Unique { two_phase: true } => write!(f, "unique reference (two-phase)"),
61 RefKind::Shared => write!(f, "shared reference"),
62 RefKind::Raw { mutable: true } => write!(f, "raw (mutable) pointer"),
63 RefKind::Raw { mutable: false } => write!(f, "raw (constant) pointer"),
69 pub fn err_sb_ub<'tcx>(
72 history: Option<TagHistory>,
73 ) -> InterpError<'tcx> {
74 err_machine_stop!(TerminationInfo::StackedBorrowsUb { msg, help, history })
77 // # Stacked Borrows Core Begin
79 /// We need to make at least the following things true:
81 /// U1: After creating a `Uniq`, it is at the top.
82 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it.
83 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
85 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
86 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
87 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
89 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
90 /// F3: If an access happens with an `&` outside `UnsafeCell`,
91 /// it requires the `SharedReadOnly` to still be in the stack.
93 /// Core relation on `Permission` to define which accesses are allowed
95 /// This defines for a given permission, whether it permits the given kind of access.
96 fn grants(self, access: AccessKind) -> bool {
97 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
98 self != Permission::Disabled
99 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
103 /// Determines whether an item was invalidated by a conflicting access, or by deallocation.
104 #[derive(Copy, Clone, Debug)]
105 enum ItemInvalidationCause {
110 /// Core per-location operations: access, dealloc, reborrow.
112 /// Find the first write-incompatible item above the given one --
113 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
114 fn find_first_write_incompatible(&self, granting: usize) -> usize {
115 let perm = self.get(granting).unwrap().perm();
117 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
118 Permission::Disabled => bug!("Cannot use Disabled for anything"),
119 Permission::Unique => {
120 // On a write, everything above us is incompatible.
123 Permission::SharedReadWrite => {
124 // The SharedReadWrite *just* above us are compatible, to skip those.
125 let mut idx = granting + 1;
126 while let Some(item) = self.get(idx) {
127 if item.perm() == Permission::SharedReadWrite {
131 // Found first incompatible!
140 /// The given item was invalidated -- check its protectors for whether that will cause UB.
143 global: &GlobalStateInner,
144 dcx: &mut DiagnosticCx<'_, '_, '_, 'tcx>,
145 cause: ItemInvalidationCause,
146 ) -> InterpResult<'tcx> {
147 if !global.tracked_pointer_tags.is_empty() {
148 dcx.check_tracked_tag_popped(item, global);
151 if !item.protected() {
155 // We store tags twice, once in global.protected_tags and once in each call frame.
156 // We do this because consulting a single global set in this function is faster
157 // than attempting to search all call frames in the program for the `FrameExtra`
158 // (if any) which is protecting the popped tag.
160 // This duplication trades off making `end_call` slower to make this function faster. This
161 // trade-off is profitable in practice for a combination of two reasons.
162 // 1. A single protected tag can (and does in some programs) protect thousands of `Item`s.
163 // Therefore, adding overhead in function call/return is profitable even if it only
164 // saves a little work in this function.
165 // 2. Most frames protect only one or two tags. So this duplicative global turns a search
166 // which ends up about linear in the number of protected tags in the program into a
167 // constant time check (and a slow linear, because the tags in the frames aren't contiguous).
168 if let Some(&protector_kind) = global.protected_tags.get(&item.tag()) {
169 // The only way this is okay is if the protector is weak and we are deallocating with
170 // the right pointer.
171 let allowed = matches!(cause, ItemInvalidationCause::Dealloc)
172 && matches!(protector_kind, ProtectorKind::WeakProtector);
174 return Err(dcx.protector_error(item, protector_kind).into());
180 /// Test if a memory `access` using pointer tagged `tag` is granted.
181 /// If yes, return the index of the item that granted it.
182 /// `range` refers the entire operation, and `offset` refers to the specific offset into the
183 /// allocation that we are currently checking.
187 tag: ProvenanceExtra,
188 global: &GlobalStateInner,
189 dcx: &mut DiagnosticCx<'_, '_, '_, 'tcx>,
190 exposed_tags: &FxHashSet<BorTag>,
191 ) -> InterpResult<'tcx> {
192 // Two main steps: Find granting item, remove incompatible items above.
194 // Step 1: Find granting item.
196 self.find_granting(access, tag, exposed_tags).map_err(|()| dcx.access_error(self))?;
198 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
199 // items. Behavior differs for reads and writes.
200 // In case of wildcards/unknown matches, we remove everything that is *definitely* gone.
201 if access == AccessKind::Write {
202 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
203 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
204 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
205 // The granting_idx *might* be approximate, but any lower idx would remove more
206 // things. Even if this is a Unique and the lower idx is an SRW (which removes
207 // less), there is an SRW group boundary here so strictly more would get removed.
208 self.find_first_write_incompatible(granting_idx)
210 // We are writing to something in the unknown part.
211 // There is a SRW group boundary between the unknown and the known, so everything is incompatible.
214 self.pop_items_after(first_incompatible_idx, |item| {
215 Stack::item_invalidated(&item, global, dcx, ItemInvalidationCause::Conflict)?;
216 dcx.log_invalidation(item.tag());
220 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
221 // The reason this is not following the stack discipline (by removing the first Unique and
222 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
223 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
224 // `SharedReadWrite` for `raw`.
225 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
226 // reference and use that.
227 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
228 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
229 // The granting_idx *might* be approximate, but any lower idx would disable more things.
232 // We are reading from something in the unknown part. That means *all* `Unique` we know about are dead now.
235 self.disable_uniques_starting_at(first_incompatible_idx, |item| {
236 Stack::item_invalidated(&item, global, dcx, ItemInvalidationCause::Conflict)?;
237 dcx.log_invalidation(item.tag());
242 // If this was an approximate action, we now collapse everything into an unknown.
243 if granting_idx.is_none() || matches!(tag, ProvenanceExtra::Wildcard) {
244 // Compute the upper bound of the items that remain.
245 // (This is why we did all the work above: to reduce the items we have to consider here.)
246 let mut max = BorTag::one();
247 for i in 0..self.len() {
248 let item = self.get(i).unwrap();
249 // Skip disabled items, they cannot be matched anyway.
250 if !matches!(item.perm(), Permission::Disabled) {
251 // We are looking for a strict upper bound, so add 1 to this tag.
252 max = cmp::max(item.tag().succ().unwrap(), max);
255 if let Some(unk) = self.unknown_bottom() {
256 max = cmp::max(unk, max);
258 // Use `max` as new strict upper bound for everything.
260 "access: forgetting stack to upper bound {max} due to wildcard or unknown access",
263 self.set_unknown_bottom(max);
270 /// Deallocate a location: Like a write access, but also there must be no
271 /// active protectors at all because we will remove all items.
274 tag: ProvenanceExtra,
275 global: &GlobalStateInner,
276 dcx: &mut DiagnosticCx<'_, '_, '_, 'tcx>,
277 exposed_tags: &FxHashSet<BorTag>,
278 ) -> InterpResult<'tcx> {
279 // Step 1: Make a write access.
280 // As part of this we do regular protector checking, i.e. even weakly protected items cause UB when popped.
281 self.access(AccessKind::Write, tag, global, dcx, exposed_tags)?;
283 // Step 2: Pretend we remove the remaining items, checking if any are strongly protected.
284 for idx in (0..self.len()).rev() {
285 let item = self.get(idx).unwrap();
286 Stack::item_invalidated(&item, global, dcx, ItemInvalidationCause::Dealloc)?;
292 /// Derive a new pointer from one with the given tag.
294 /// `access` indicates which kind of memory access this retag itself should correspond to.
297 derived_from: ProvenanceExtra,
299 access: Option<AccessKind>,
300 global: &GlobalStateInner,
301 dcx: &mut DiagnosticCx<'_, '_, '_, 'tcx>,
302 exposed_tags: &FxHashSet<BorTag>,
303 ) -> InterpResult<'tcx> {
304 dcx.start_grant(new.perm());
306 // Compute where to put the new item.
307 // Either way, we ensure that we insert the new item in a way such that between
308 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
309 let new_idx = if let Some(access) = access {
310 // Simple case: We are just a regular memory access, and then push our thing on top,
311 // like a regular stack.
312 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
313 self.access(access, derived_from, global, dcx, exposed_tags)?;
315 // We insert "as far up as possible": We know only compatible items are remaining
316 // on top of `derived_from`, and we want the new item at the top so that we
317 // get the strongest possible guarantees.
318 // This ensures U1 and F1.
321 // The tricky case: creating a new SRW permission without actually being an access.
322 assert!(new.perm() == Permission::SharedReadWrite);
324 // First we figure out which item grants our parent (`derived_from`) this kind of access.
325 // We use that to determine where to put the new item.
326 let granting_idx = self
327 .find_granting(AccessKind::Write, derived_from, exposed_tags)
328 .map_err(|()| dcx.grant_error(self))?;
330 let (Some(granting_idx), ProvenanceExtra::Concrete(_)) = (granting_idx, derived_from) else {
331 // The parent is a wildcard pointer or matched the unknown bottom.
332 // This is approximate. Nobody knows what happened, so forget everything.
333 // The new thing is SRW anyway, so we cannot push it "on top of the unkown part"
334 // (for all we know, it might join an SRW group inside the unknown).
335 trace!("reborrow: forgetting stack entirely due to SharedReadWrite reborrow from wildcard or unknown");
336 self.set_unknown_bottom(global.next_ptr_tag);
340 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
341 // access. Instead of popping the stack, we insert the item at the place the stack would
342 // be popped to (i.e., we insert it above all the write-compatible items).
343 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
344 self.find_first_write_incompatible(granting_idx)
347 // Put the new item there.
348 trace!("reborrow: adding item {:?}", new);
349 self.insert(new_idx, new);
353 // # Stacked Borrows Core End
355 /// Integration with the BorTag garbage collector
357 pub fn remove_unreachable_tags(&mut self, live_tags: &FxHashSet<BorTag>) {
358 if self.modified_since_last_gc {
359 for stack in self.stacks.iter_mut_all() {
360 if stack.len() > 64 {
361 stack.retain(live_tags);
364 self.modified_since_last_gc = false;
369 impl VisitTags for Stacks {
370 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
371 for tag in self.exposed_tags.iter().copied() {
377 /// Map per-stack operations to higher-level per-location-range operations.
379 /// Creates a new stack with an initial tag. For diagnostic purposes, we also need to know
380 /// the [`AllocId`] of the allocation this is associated with.
386 machine: &MiriMachine<'_, '_>,
388 let item = Item::new(tag, perm, false);
389 let stack = Stack::new(item);
392 stacks: RangeMap::new(size, stack),
393 history: AllocHistory::new(id, item, machine),
394 exposed_tags: FxHashSet::default(),
395 modified_since_last_gc: false,
399 /// Call `f` on every stack in the range.
403 mut dcx_builder: DiagnosticCxBuilder<'_, '_, 'tcx>,
406 &mut DiagnosticCx<'_, '_, '_, 'tcx>,
407 &mut FxHashSet<BorTag>,
408 ) -> InterpResult<'tcx>,
409 ) -> InterpResult<'tcx> {
410 self.modified_since_last_gc = true;
411 for (offset, stack) in self.stacks.iter_mut(range.start, range.size) {
412 let mut dcx = dcx_builder.build(&mut self.history, offset);
413 f(stack, &mut dcx, &mut self.exposed_tags)?;
414 dcx_builder = dcx.unbuild();
420 /// Glue code to connect with Miri Machine Hooks
422 pub fn new_allocation(
425 state: &mut GlobalStateInner,
426 kind: MemoryKind<MiriMemoryKind>,
427 machine: &MiriMachine<'_, '_>,
429 let (base_tag, perm) = match kind {
430 // New unique borrow. This tag is not accessible by the program,
431 // so it will only ever be used when using the local directly (i.e.,
432 // not through a pointer). That is, whenever we directly write to a local, this will pop
433 // everything else off the stack, invalidating all previous pointers,
434 // and in particular, *all* raw pointers.
435 MemoryKind::Stack => (state.base_ptr_tag(id, machine), Permission::Unique),
436 // Everything else is shared by default.
437 _ => (state.base_ptr_tag(id, machine), Permission::SharedReadWrite),
439 Stacks::new(size, perm, base_tag, id, machine)
443 pub fn before_memory_read<'tcx, 'mir, 'ecx>(
446 tag: ProvenanceExtra,
448 machine: &'ecx MiriMachine<'mir, 'tcx>,
449 ) -> InterpResult<'tcx>
454 "read access with tag {:?}: {:?}, size {}",
456 Pointer::new(alloc_id, range.start),
459 let dcx = DiagnosticCxBuilder::read(machine, tag, range);
460 let state = machine.borrow_tracker.as_ref().unwrap().borrow();
461 self.for_each(range, dcx, |stack, dcx, exposed_tags| {
462 stack.access(AccessKind::Read, tag, &state, dcx, exposed_tags)
467 pub fn before_memory_write<'tcx>(
470 tag: ProvenanceExtra,
472 machine: &mut MiriMachine<'_, 'tcx>,
473 ) -> InterpResult<'tcx> {
475 "write access with tag {:?}: {:?}, size {}",
477 Pointer::new(alloc_id, range.start),
480 let dcx = DiagnosticCxBuilder::write(machine, tag, range);
481 let state = machine.borrow_tracker.as_ref().unwrap().borrow();
482 self.for_each(range, dcx, |stack, dcx, exposed_tags| {
483 stack.access(AccessKind::Write, tag, &state, dcx, exposed_tags)
488 pub fn before_memory_deallocation<'tcx>(
491 tag: ProvenanceExtra,
493 machine: &mut MiriMachine<'_, 'tcx>,
494 ) -> InterpResult<'tcx> {
495 trace!("deallocation with tag {:?}: {:?}, size {}", tag, alloc_id, range.size.bytes());
496 let dcx = DiagnosticCxBuilder::dealloc(machine, tag);
497 let state = machine.borrow_tracker.as_ref().unwrap().borrow();
498 self.for_each(range, dcx, |stack, dcx, exposed_tags| {
499 stack.dealloc(tag, &state, dcx, exposed_tags)
505 /// Retagging/reborrowing. There is some policy in here, such as which permissions
506 /// to grant for which references, and when to add protectors.
507 impl<'mir: 'ecx, 'tcx: 'mir, 'ecx> EvalContextPrivExt<'mir, 'tcx, 'ecx>
508 for crate::MiriInterpCx<'mir, 'tcx>
511 trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<'mir, 'tcx> {
512 /// Returns the `AllocId` the reborrow was done in, if some actual borrow stack manipulation
516 place: &MPlaceTy<'tcx, Provenance>,
519 retag_cause: RetagCause, // What caused this retag, for diagnostics only
521 protect: Option<ProtectorKind>,
522 ) -> InterpResult<'tcx, Option<AllocId>> {
523 let this = self.eval_context_mut();
525 // It is crucial that this gets called on all code paths, to ensure we track tag creation.
526 let log_creation = |this: &MiriInterpCx<'mir, 'tcx>,
527 loc: Option<(AllocId, Size, ProvenanceExtra)>| // alloc_id, base_offset, orig_tag
528 -> InterpResult<'tcx> {
529 let global = this.machine.borrow_tracker.as_ref().unwrap().borrow();
530 let ty = place.layout.ty;
531 if global.tracked_pointer_tags.contains(&new_tag) {
532 let mut kind_str = format!("{kind}");
534 RefKind::Unique { two_phase: false }
535 if !ty.is_unpin(*this.tcx, this.param_env()) =>
537 write!(kind_str, " (!Unpin pointee type {ty})").unwrap()
540 if !ty.is_freeze(*this.tcx, this.param_env()) =>
542 write!(kind_str, " (!Freeze pointee type {ty})").unwrap()
544 _ => write!(kind_str, " (pointee type {ty})").unwrap(),
546 this.emit_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(
549 loc.map(|(alloc_id, base_offset, orig_tag)| (alloc_id, alloc_range(base_offset, size), orig_tag)),
552 drop(global); // don't hold that reference any longer than we have to
554 let Some((alloc_id, base_offset, orig_tag)) = loc else {
558 let (_size, _align, alloc_kind) = this.get_alloc_info(alloc_id);
560 AllocKind::LiveData => {
561 // This should have alloc_extra data, but `get_alloc_extra` can still fail
562 // if converting this alloc_id from a global to a local one
563 // uncovers a non-supported `extern static`.
564 let extra = this.get_alloc_extra(alloc_id)?;
565 let mut stacked_borrows = extra
568 // Note that we create a *second* `DiagnosticCxBuilder` below for the actual retag.
569 // FIXME: can this be done cleaner?
570 let dcx = DiagnosticCxBuilder::retag(
575 alloc_range(base_offset, size),
577 let mut dcx = dcx.build(&mut stacked_borrows.history, base_offset);
579 if protect.is_some() {
583 AllocKind::Function | AllocKind::VTable | AllocKind::Dead => {
584 // No stacked borrows on these allocations.
590 if size == Size::ZERO {
592 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
598 // Don't update any stacks for a zero-sized access; borrow stacks are per-byte and this
599 // touches no bytes so there is no stack to put this tag in.
600 // However, if the pointer for this operation points at a real allocation we still
601 // record where it was created so that we can issue a helpful diagnostic if there is an
602 // attempt to use it for a non-zero-sized access.
603 // Dangling slices are a common case here; it's valid to get their length but with raw
604 // pointer tagging for example all calls to get_unchecked on them are invalid.
605 if let Ok((alloc_id, base_offset, orig_tag)) = this.ptr_try_get_alloc_id(place.ptr) {
606 log_creation(this, Some((alloc_id, base_offset, orig_tag)))?;
607 return Ok(Some(alloc_id));
609 // This pointer doesn't come with an AllocId. :shrug:
610 log_creation(this, None)?;
614 let (alloc_id, base_offset, orig_tag) = this.ptr_get_alloc_id(place.ptr)?;
615 log_creation(this, Some((alloc_id, base_offset, orig_tag)))?;
617 // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
618 let (alloc_size, _) = this.get_live_alloc_size_and_align(alloc_id)?;
619 if base_offset + size > alloc_size {
620 throw_ub!(PointerOutOfBounds {
623 ptr_offset: this.machine_usize_to_isize(base_offset.bytes()),
625 msg: CheckInAllocMsg::InboundsTest
630 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
635 Pointer::new(alloc_id, base_offset),
639 if let Some(protect) = protect {
640 // See comment in `Stack::item_invalidated` for why we store the tag twice.
641 this.frame_mut().extra.borrow_tracker.as_mut().unwrap().protected_tags.push(new_tag);
648 .insert(new_tag, protect);
651 // Update the stacks.
652 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
653 // There could be existing unique pointers reborrowed from them that should remain valid!
654 let (perm, access) = match kind {
655 RefKind::Unique { two_phase } => {
656 // Permission is Unique only if the type is `Unpin` and this is not twophase
657 let perm = if !two_phase && place.layout.ty.is_unpin(*this.tcx, this.param_env()) {
660 Permission::SharedReadWrite
662 // We do an access for all full borrows, even if `!Unpin`.
663 let access = if !two_phase { Some(AccessKind::Write) } else { None };
666 RefKind::Raw { mutable: true } => {
667 // Creating a raw ptr does not count as an access
668 (Permission::SharedReadWrite, None)
670 RefKind::Shared | RefKind::Raw { mutable: false } => {
671 // Shared references and *const are a whole different kind of game, the
672 // permission is not uniform across the entire range!
673 // We need a frozen-sensitive reborrow.
674 // We have to use shared references to alloc/memory_extra here since
675 // `visit_freeze_sensitive` needs to access the global state.
676 let alloc_extra = this.get_alloc_extra(alloc_id)?;
677 let mut stacked_borrows = alloc_extra.borrow_tracker_sb().borrow_mut();
678 this.visit_freeze_sensitive(place, size, |mut range, frozen| {
680 range.start += base_offset;
681 // We are only ever `SharedReadOnly` inside the frozen bits.
682 let (perm, access) = if frozen {
683 (Permission::SharedReadOnly, Some(AccessKind::Read))
685 // Inside UnsafeCell, this does *not* count as an access, as there
686 // might actually be mutable references further up the stack that
687 // we have to keep alive.
688 (Permission::SharedReadWrite, None)
690 let protected = if frozen {
693 // We do not protect inside UnsafeCell.
694 // This fixes https://github.com/rust-lang/rust/issues/55005.
697 let item = Item::new(new_tag, perm, protected);
698 let global = this.machine.borrow_tracker.as_ref().unwrap().borrow();
699 let dcx = DiagnosticCxBuilder::retag(
704 alloc_range(base_offset, size),
706 stacked_borrows.for_each(range, dcx, |stack, dcx, exposed_tags| {
707 stack.grant(orig_tag, item, access, &global, dcx, exposed_tags)
710 if let Some(access) = access {
711 assert_eq!(access, AccessKind::Read);
712 // Make sure the data race model also knows about this.
713 if let Some(data_race) = alloc_extra.data_race.as_ref() {
714 data_race.read(alloc_id, range, &this.machine)?;
719 return Ok(Some(alloc_id));
723 // Here we can avoid `borrow()` calls because we have mutable references.
724 // Note that this asserts that the allocation is mutable -- but since we are creating a
725 // mutable pointer, that seems reasonable.
726 let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc_id)?;
727 let stacked_borrows = alloc_extra.borrow_tracker_sb_mut().get_mut();
728 let item = Item::new(new_tag, perm, protect.is_some());
729 let range = alloc_range(base_offset, size);
730 let global = machine.borrow_tracker.as_ref().unwrap().borrow();
731 let dcx = DiagnosticCxBuilder::retag(
736 alloc_range(base_offset, size),
738 stacked_borrows.for_each(range, dcx, |stack, dcx, exposed_tags| {
739 stack.grant(orig_tag, item, access, &global, dcx, exposed_tags)
742 if let Some(access) = access {
743 assert_eq!(access, AccessKind::Write);
744 // Make sure the data race model also knows about this.
745 if let Some(data_race) = alloc_extra.data_race.as_mut() {
746 data_race.write(alloc_id, range, machine)?;
753 /// Retags an indidual pointer, returning the retagged version.
754 /// `kind` indicates what kind of reference is being created.
755 fn sb_retag_reference(
757 val: &ImmTy<'tcx, Provenance>,
759 retag_cause: RetagCause, // What caused this retag, for diagnostics only
760 protect: Option<ProtectorKind>,
761 ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> {
762 let this = self.eval_context_mut();
763 // We want a place for where the ptr *points to*, so we get one.
764 let place = this.ref_to_mplace(val)?;
765 let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
766 // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
767 // bail out -- we cannot reasonably figure out which memory range to reborrow.
768 // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
769 let size = match size {
771 None => return Ok(val.clone()),
774 // Compute new borrow.
775 let new_tag = this.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr();
778 let alloc_id = this.sb_reborrow(&place, size, kind, retag_cause, new_tag, protect)?;
781 let new_place = place.map_provenance(|p| {
785 // If `reborrow` could figure out the AllocId of this ptr, hard-code it into the new one.
786 // Even if we started out with a wildcard, this newly retagged pointer is tied to that allocation.
787 Provenance::Concrete { alloc_id, tag: new_tag }
790 // Looks like this has to stay a wildcard pointer.
791 assert!(matches!(prov, Provenance::Wildcard));
798 // Return new pointer.
799 Ok(ImmTy::from_immediate(new_place.to_ref(this), val.layout))
803 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
804 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
808 place: &PlaceTy<'tcx, Provenance>,
809 ) -> InterpResult<'tcx> {
810 let this = self.eval_context_mut();
811 let retag_fields = this.machine.borrow_tracker.as_mut().unwrap().get_mut().retag_fields;
812 let retag_cause = match kind {
813 RetagKind::TwoPhase { .. } => RetagCause::TwoPhase,
814 RetagKind::FnEntry => RetagCause::FnEntry,
815 RetagKind::Raw | RetagKind::Default => RetagCause::Normal,
817 let mut visitor = RetagVisitor { ecx: this, kind, retag_cause, retag_fields };
818 return visitor.visit_value(place);
820 // The actual visitor.
821 struct RetagVisitor<'ecx, 'mir, 'tcx> {
822 ecx: &'ecx mut MiriInterpCx<'mir, 'tcx>,
824 retag_cause: RetagCause,
825 retag_fields: RetagFields,
827 impl<'ecx, 'mir, 'tcx> RetagVisitor<'ecx, 'mir, 'tcx> {
828 #[inline(always)] // yes this helps in our benchmarks
831 place: &PlaceTy<'tcx, Provenance>,
833 retag_cause: RetagCause,
834 protector: Option<ProtectorKind>,
835 ) -> InterpResult<'tcx> {
836 let val = self.ecx.read_immediate(&self.ecx.place_to_op(place)?)?;
837 let val = self.ecx.sb_retag_reference(&val, ref_kind, retag_cause, protector)?;
838 self.ecx.write_immediate(*val, place)?;
842 impl<'ecx, 'mir, 'tcx> MutValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
843 for RetagVisitor<'ecx, 'mir, 'tcx>
845 type V = PlaceTy<'tcx, Provenance>;
848 fn ecx(&mut self) -> &mut MiriInterpCx<'mir, 'tcx> {
852 fn visit_box(&mut self, place: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
853 // Boxes get a weak protectors, since they may be deallocated.
856 RefKind::Unique { two_phase: false },
859 (self.kind == RetagKind::FnEntry).then_some(ProtectorKind::WeakProtector),
863 fn visit_value(&mut self, place: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
864 // If this place is smaller than a pointer, we know that it can't contain any
865 // pointers we need to retag, so we can stop recursion early.
866 // This optimization is crucial for ZSTs, because they can contain way more fields
867 // than we can ever visit.
868 if place.layout.is_sized() && place.layout.size < self.ecx.pointer_size() {
872 // Check the type of this value to see what to do with it (retag, or recurse).
873 match place.layout.ty.kind() {
874 ty::Ref(_, _, mutbl) => {
875 let ref_kind = match mutbl {
877 RefKind::Unique { two_phase: self.kind == RetagKind::TwoPhase },
878 Mutability::Not => RefKind::Shared,
885 (self.kind == RetagKind::FnEntry)
886 .then_some(ProtectorKind::StrongProtector),
890 // We definitely do *not* want to recurse into raw pointers -- wide raw
891 // pointers have fields, and for dyn Trait pointees those can have reference
893 if self.kind == RetagKind::Raw {
894 // Raw pointers need to be enabled.
897 RefKind::Raw { mutable: tym.mutbl == Mutability::Mut },
903 _ if place.layout.ty.ty_adt_def().is_some_and(|adt| adt.is_box()) => {
904 // Recurse for boxes, they require some tricky handling and will end up in `visit_box` above.
905 // (Yes this means we technically also recursively retag the allocator itself
906 // even if field retagging is not enabled. *shrug*)
907 self.walk_value(place)?;
910 // Not a reference/pointer/box. Only recurse if configured appropriately.
911 let recurse = match self.retag_fields {
912 RetagFields::No => false,
913 RetagFields::Yes => true,
914 RetagFields::OnlyScalar => {
915 // Matching `ArgAbi::new` at the time of writing, only fields of
916 // `Scalar` and `ScalarPair` ABI are considered.
917 matches!(place.layout.abi, Abi::Scalar(..) | Abi::ScalarPair(..))
921 self.walk_value(place)?;
931 /// After a stack frame got pushed, retag the return place so that we are sure
932 /// it does not alias with anything.
934 /// This is a HACK because there is nothing in MIR that would make the retag
935 /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>.
936 fn sb_retag_return_place(&mut self) -> InterpResult<'tcx> {
937 let this = self.eval_context_mut();
938 let return_place = &this.frame().return_place;
939 if return_place.layout.is_zst() {
940 // There may not be any memory here, nothing to do.
943 // We need this to be in-memory to use tagged pointers.
944 let return_place = this.force_allocation(&return_place.clone())?;
946 // We have to turn the place into a pointer to use the existing code.
947 // (The pointer type does not matter, so we use a raw pointer.)
948 let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
949 let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout);
950 // Reborrow it. With protection! That is part of the point.
951 let val = this.sb_retag_reference(
953 RefKind::Unique { two_phase: false },
954 RetagCause::FnReturn,
955 /*protector*/ Some(ProtectorKind::StrongProtector),
957 // And use reborrowed pointer for return place.
958 let return_place = this.ref_to_mplace(&val)?;
959 this.frame_mut().return_place = return_place.into();
964 /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
965 fn sb_expose_tag(&mut self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> {
966 let this = self.eval_context_mut();
968 // Function pointers and dead objects don't have an alloc_extra so we ignore them.
969 // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks.
970 // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
971 let (_size, _align, kind) = this.get_alloc_info(alloc_id);
973 AllocKind::LiveData => {
974 // This should have alloc_extra data, but `get_alloc_extra` can still fail
975 // if converting this alloc_id from a global to a local one
976 // uncovers a non-supported `extern static`.
977 let alloc_extra = this.get_alloc_extra(alloc_id)?;
978 trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id:?}");
979 alloc_extra.borrow_tracker_sb().borrow_mut().exposed_tags.insert(tag);
981 AllocKind::Function | AllocKind::VTable | AllocKind::Dead => {
982 // No stacked borrows on these allocations.
988 fn print_stacks(&mut self, alloc_id: AllocId) -> InterpResult<'tcx> {
989 let this = self.eval_context_mut();
990 let alloc_extra = this.get_alloc_extra(alloc_id)?;
991 let stacks = alloc_extra.borrow_tracker_sb().borrow();
992 for (range, stack) in stacks.stacks.iter_all() {
993 print!("{range:?}: [");
994 if let Some(bottom) = stack.unknown_bottom() {
995 print!(" unknown-bottom(..{bottom:?})");
997 for i in 0..stack.len() {
998 let item = stack.get(i).unwrap();
999 print!(" {:?}{:?}", item.perm(), item.tag());