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 AllocExtra = 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)
504 fn expose_tag(&mut self, tag: BorTag) {
505 self.exposed_tags.insert(tag);
509 /// Retagging/reborrowing. There is some policy in here, such as which permissions
510 /// to grant for which references, and when to add protectors.
511 impl<'mir: 'ecx, 'tcx: 'mir, 'ecx> EvalContextPrivExt<'mir, 'tcx, 'ecx>
512 for crate::MiriInterpCx<'mir, 'tcx>
515 trait EvalContextPrivExt<'mir: 'ecx, 'tcx: 'mir, 'ecx>: crate::MiriInterpCxExt<'mir, 'tcx> {
516 /// Returns the `AllocId` the reborrow was done in, if some actual borrow stack manipulation
520 place: &MPlaceTy<'tcx, Provenance>,
523 retag_cause: RetagCause, // What caused this retag, for diagnostics only
525 protect: Option<ProtectorKind>,
526 ) -> InterpResult<'tcx, Option<AllocId>> {
527 let this = self.eval_context_mut();
529 // It is crucial that this gets called on all code paths, to ensure we track tag creation.
530 let log_creation = |this: &MiriInterpCx<'mir, 'tcx>,
531 loc: Option<(AllocId, Size, ProvenanceExtra)>| // alloc_id, base_offset, orig_tag
532 -> InterpResult<'tcx> {
533 let global = this.machine.borrow_tracker.as_ref().unwrap().borrow();
534 let ty = place.layout.ty;
535 if global.tracked_pointer_tags.contains(&new_tag) {
536 let mut kind_str = format!("{kind}");
538 RefKind::Unique { two_phase: false }
539 if !ty.is_unpin(*this.tcx, this.param_env()) =>
541 write!(kind_str, " (!Unpin pointee type {ty})").unwrap()
544 if !ty.is_freeze(*this.tcx, this.param_env()) =>
546 write!(kind_str, " (!Freeze pointee type {ty})").unwrap()
548 _ => write!(kind_str, " (pointee type {ty})").unwrap(),
550 this.emit_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(
553 loc.map(|(alloc_id, base_offset, orig_tag)| (alloc_id, alloc_range(base_offset, size), orig_tag)),
556 drop(global); // don't hold that reference any longer than we have to
558 let Some((alloc_id, base_offset, orig_tag)) = loc else {
562 let (_size, _align, alloc_kind) = this.get_alloc_info(alloc_id);
564 AllocKind::LiveData => {
565 // This should have alloc_extra data, but `get_alloc_extra` can still fail
566 // if converting this alloc_id from a global to a local one
567 // uncovers a non-supported `extern static`.
568 let extra = this.get_alloc_extra(alloc_id)?;
569 let mut stacked_borrows = extra
572 .expect("We should have borrow tracking data")
575 // Note that we create a *second* `DiagnosticCxBuilder` below for the actual retag.
576 // FIXME: can this be done cleaner?
577 let dcx = DiagnosticCxBuilder::retag(
582 alloc_range(base_offset, size),
584 let mut dcx = dcx.build(&mut stacked_borrows.history, base_offset);
586 if protect.is_some() {
590 AllocKind::Function | AllocKind::VTable | AllocKind::Dead => {
591 // No stacked borrows on these allocations.
597 if size == Size::ZERO {
599 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
605 // Don't update any stacks for a zero-sized access; borrow stacks are per-byte and this
606 // touches no bytes so there is no stack to put this tag in.
607 // However, if the pointer for this operation points at a real allocation we still
608 // record where it was created so that we can issue a helpful diagnostic if there is an
609 // attempt to use it for a non-zero-sized access.
610 // Dangling slices are a common case here; it's valid to get their length but with raw
611 // pointer tagging for example all calls to get_unchecked on them are invalid.
612 if let Ok((alloc_id, base_offset, orig_tag)) = this.ptr_try_get_alloc_id(place.ptr) {
613 log_creation(this, Some((alloc_id, base_offset, orig_tag)))?;
614 return Ok(Some(alloc_id));
616 // This pointer doesn't come with an AllocId. :shrug:
617 log_creation(this, None)?;
621 let (alloc_id, base_offset, orig_tag) = this.ptr_get_alloc_id(place.ptr)?;
622 log_creation(this, Some((alloc_id, base_offset, orig_tag)))?;
624 // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
625 let (alloc_size, _) = this.get_live_alloc_size_and_align(alloc_id)?;
626 if base_offset + size > alloc_size {
627 throw_ub!(PointerOutOfBounds {
630 ptr_offset: this.machine_usize_to_isize(base_offset.bytes()),
632 msg: CheckInAllocMsg::InboundsTest
637 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
642 Pointer::new(alloc_id, base_offset),
646 if let Some(protect) = protect {
647 // See comment in `Stack::item_invalidated` for why we store the tag twice.
648 this.frame_mut().extra.borrow_tracker.as_mut().unwrap().protected_tags.push(new_tag);
655 .insert(new_tag, protect);
658 // Update the stacks.
659 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
660 // There could be existing unique pointers reborrowed from them that should remain valid!
661 let (perm, access) = match kind {
662 RefKind::Unique { two_phase } => {
663 // Permission is Unique only if the type is `Unpin` and this is not twophase
664 let perm = if !two_phase && place.layout.ty.is_unpin(*this.tcx, this.param_env()) {
667 Permission::SharedReadWrite
669 // We do an access for all full borrows, even if `!Unpin`.
670 let access = if !two_phase { Some(AccessKind::Write) } else { None };
673 RefKind::Raw { mutable: true } => {
674 // Creating a raw ptr does not count as an access
675 (Permission::SharedReadWrite, None)
677 RefKind::Shared | RefKind::Raw { mutable: false } => {
678 // Shared references and *const are a whole different kind of game, the
679 // permission is not uniform across the entire range!
680 // We need a frozen-sensitive reborrow.
681 // We have to use shared references to alloc/memory_extra here since
682 // `visit_freeze_sensitive` needs to access the global state.
683 let alloc_extra = this.get_alloc_extra(alloc_id)?;
684 let mut stacked_borrows = alloc_extra
687 .expect("We should have borrow tracking data")
690 this.visit_freeze_sensitive(place, size, |mut range, frozen| {
692 range.start += base_offset;
693 // We are only ever `SharedReadOnly` inside the frozen bits.
694 let (perm, access) = if frozen {
695 (Permission::SharedReadOnly, Some(AccessKind::Read))
697 // Inside UnsafeCell, this does *not* count as an access, as there
698 // might actually be mutable references further up the stack that
699 // we have to keep alive.
700 (Permission::SharedReadWrite, None)
702 let protected = if frozen {
705 // We do not protect inside UnsafeCell.
706 // This fixes https://github.com/rust-lang/rust/issues/55005.
709 let item = Item::new(new_tag, perm, protected);
710 let global = this.machine.borrow_tracker.as_ref().unwrap().borrow();
711 let dcx = DiagnosticCxBuilder::retag(
716 alloc_range(base_offset, size),
718 stacked_borrows.for_each(range, dcx, |stack, dcx, exposed_tags| {
719 stack.grant(orig_tag, item, access, &global, dcx, exposed_tags)
722 if let Some(access) = access {
723 assert_eq!(access, AccessKind::Read);
724 // Make sure the data race model also knows about this.
725 if let Some(data_race) = alloc_extra.data_race.as_ref() {
726 data_race.read(alloc_id, range, &this.machine)?;
731 return Ok(Some(alloc_id));
735 // Here we can avoid `borrow()` calls because we have mutable references.
736 // Note that this asserts that the allocation is mutable -- but since we are creating a
737 // mutable pointer, that seems reasonable.
738 let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc_id)?;
739 let stacked_borrows = alloc_extra
742 .expect("We should have borrow tracking data")
745 let item = Item::new(new_tag, perm, protect.is_some());
746 let range = alloc_range(base_offset, size);
747 let global = machine.borrow_tracker.as_ref().unwrap().borrow();
748 let dcx = DiagnosticCxBuilder::retag(
753 alloc_range(base_offset, size),
755 stacked_borrows.for_each(range, dcx, |stack, dcx, exposed_tags| {
756 stack.grant(orig_tag, item, access, &global, dcx, exposed_tags)
759 if let Some(access) = access {
760 assert_eq!(access, AccessKind::Write);
761 // Make sure the data race model also knows about this.
762 if let Some(data_race) = alloc_extra.data_race.as_mut() {
763 data_race.write(alloc_id, range, machine)?;
770 /// Retags an indidual pointer, returning the retagged version.
771 /// `kind` indicates what kind of reference is being created.
772 fn sb_retag_reference(
774 val: &ImmTy<'tcx, Provenance>,
776 retag_cause: RetagCause, // What caused this retag, for diagnostics only
777 protect: Option<ProtectorKind>,
778 ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> {
779 let this = self.eval_context_mut();
780 // We want a place for where the ptr *points to*, so we get one.
781 let place = this.ref_to_mplace(val)?;
782 let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
783 // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
784 // bail out -- we cannot reasonably figure out which memory range to reborrow.
785 // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
786 let size = match size {
788 None => return Ok(val.clone()),
791 // Compute new borrow.
792 let new_tag = this.machine.borrow_tracker.as_mut().unwrap().get_mut().new_ptr();
795 let alloc_id = this.sb_reborrow(&place, size, kind, retag_cause, new_tag, protect)?;
798 let new_place = place.map_provenance(|p| {
802 // If `reborrow` could figure out the AllocId of this ptr, hard-code it into the new one.
803 // Even if we started out with a wildcard, this newly retagged pointer is tied to that allocation.
804 Provenance::Concrete { alloc_id, tag: new_tag }
807 // Looks like this has to stay a wildcard pointer.
808 assert!(matches!(prov, Provenance::Wildcard));
815 // Return new pointer.
816 Ok(ImmTy::from_immediate(new_place.to_ref(this), val.layout))
820 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriInterpCx<'mir, 'tcx> {}
821 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriInterpCxExt<'mir, 'tcx> {
825 place: &PlaceTy<'tcx, Provenance>,
826 ) -> InterpResult<'tcx> {
827 let this = self.eval_context_mut();
828 let retag_fields = this.machine.borrow_tracker.as_mut().unwrap().get_mut().retag_fields;
829 let retag_cause = match kind {
830 RetagKind::TwoPhase { .. } => RetagCause::TwoPhase,
831 RetagKind::FnEntry => RetagCause::FnEntry,
832 RetagKind::Raw | RetagKind::Default => RetagCause::Normal,
834 let mut visitor = RetagVisitor { ecx: this, kind, retag_cause, retag_fields };
835 return visitor.visit_value(place);
837 // The actual visitor.
838 struct RetagVisitor<'ecx, 'mir, 'tcx> {
839 ecx: &'ecx mut MiriInterpCx<'mir, 'tcx>,
841 retag_cause: RetagCause,
842 retag_fields: RetagFields,
844 impl<'ecx, 'mir, 'tcx> RetagVisitor<'ecx, 'mir, 'tcx> {
845 #[inline(always)] // yes this helps in our benchmarks
848 place: &PlaceTy<'tcx, Provenance>,
850 retag_cause: RetagCause,
851 protector: Option<ProtectorKind>,
852 ) -> InterpResult<'tcx> {
853 let val = self.ecx.read_immediate(&self.ecx.place_to_op(place)?)?;
854 let val = self.ecx.sb_retag_reference(&val, ref_kind, retag_cause, protector)?;
855 self.ecx.write_immediate(*val, place)?;
859 impl<'ecx, 'mir, 'tcx> MutValueVisitor<'mir, 'tcx, MiriMachine<'mir, 'tcx>>
860 for RetagVisitor<'ecx, 'mir, 'tcx>
862 type V = PlaceTy<'tcx, Provenance>;
865 fn ecx(&mut self) -> &mut MiriInterpCx<'mir, 'tcx> {
869 fn visit_box(&mut self, place: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
870 // Boxes get a weak protectors, since they may be deallocated.
873 RefKind::Unique { two_phase: false },
876 (self.kind == RetagKind::FnEntry).then_some(ProtectorKind::WeakProtector),
880 fn visit_value(&mut self, place: &PlaceTy<'tcx, Provenance>) -> InterpResult<'tcx> {
881 // If this place is smaller than a pointer, we know that it can't contain any
882 // pointers we need to retag, so we can stop recursion early.
883 // This optimization is crucial for ZSTs, because they can contain way more fields
884 // than we can ever visit.
885 if place.layout.is_sized() && place.layout.size < self.ecx.pointer_size() {
889 // Check the type of this value to see what to do with it (retag, or recurse).
890 match place.layout.ty.kind() {
891 ty::Ref(_, _, mutbl) => {
892 let ref_kind = match mutbl {
894 RefKind::Unique { two_phase: self.kind == RetagKind::TwoPhase },
895 Mutability::Not => RefKind::Shared,
902 (self.kind == RetagKind::FnEntry)
903 .then_some(ProtectorKind::StrongProtector),
907 // We definitely do *not* want to recurse into raw pointers -- wide raw
908 // pointers have fields, and for dyn Trait pointees those can have reference
910 if self.kind == RetagKind::Raw {
911 // Raw pointers need to be enabled.
914 RefKind::Raw { mutable: tym.mutbl == Mutability::Mut },
920 _ if place.layout.ty.ty_adt_def().is_some_and(|adt| adt.is_box()) => {
921 // Recurse for boxes, they require some tricky handling and will end up in `visit_box` above.
922 // (Yes this means we technically also recursively retag the allocator itself
923 // even if field retagging is not enabled. *shrug*)
924 self.walk_value(place)?;
927 // Not a reference/pointer/box. Only recurse if configured appropriately.
928 let recurse = match self.retag_fields {
929 RetagFields::No => false,
930 RetagFields::Yes => true,
931 RetagFields::OnlyScalar => {
932 // Matching `ArgAbi::new` at the time of writing, only fields of
933 // `Scalar` and `ScalarPair` ABI are considered.
934 matches!(place.layout.abi, Abi::Scalar(..) | Abi::ScalarPair(..))
938 self.walk_value(place)?;
948 /// After a stack frame got pushed, retag the return place so that we are sure
949 /// it does not alias with anything.
951 /// This is a HACK because there is nothing in MIR that would make the retag
952 /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>.
953 fn sb_retag_return_place(&mut self) -> InterpResult<'tcx> {
954 let this = self.eval_context_mut();
955 let return_place = &this.frame().return_place;
956 if return_place.layout.is_zst() {
957 // There may not be any memory here, nothing to do.
960 // We need this to be in-memory to use tagged pointers.
961 let return_place = this.force_allocation(&return_place.clone())?;
963 // We have to turn the place into a pointer to use the existing code.
964 // (The pointer type does not matter, so we use a raw pointer.)
965 let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
966 let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout);
967 // Reborrow it. With protection! That is part of the point.
968 let val = this.sb_retag_reference(
970 RefKind::Unique { two_phase: false },
971 RetagCause::FnReturn,
972 /*protector*/ Some(ProtectorKind::StrongProtector),
974 // And use reborrowed pointer for return place.
975 let return_place = this.ref_to_mplace(&val)?;
976 this.frame_mut().return_place = return_place.into();
981 /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
982 fn sb_expose_tag(&mut self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> {
983 let this = self.eval_context_mut();
985 // Function pointers and dead objects don't have an alloc_extra so we ignore them.
986 // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks.
987 // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
988 let (_size, _align, kind) = this.get_alloc_info(alloc_id);
990 AllocKind::LiveData => {
991 // This should have alloc_extra data, but `get_alloc_extra` can still fail
992 // if converting this alloc_id from a global to a local one
993 // uncovers a non-supported `extern static`.
994 let alloc_extra = this.get_alloc_extra(alloc_id)?;
995 trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id:?}");
999 .expect("We should have borrow tracking data")
1004 AllocKind::Function | AllocKind::VTable | AllocKind::Dead => {
1005 // No stacked borrows on these allocations.
1011 fn print_stacks(&mut self, alloc_id: AllocId) -> InterpResult<'tcx> {
1012 let this = self.eval_context_mut();
1013 let alloc_extra = this.get_alloc_extra(alloc_id)?;
1014 let stacks = alloc_extra
1017 .expect("We should have borrow tracking data")
1020 for (range, stack) in stacks.stacks.iter_all() {
1021 print!("{range:?}: [");
1022 if let Some(bottom) = stack.unknown_bottom() {
1023 print!(" unknown-bottom(..{bottom:?})");
1025 for i in 0..stack.len() {
1026 let item = stack.get(i).unwrap();
1027 print!(" {:?}{:?}", item.perm(), item.tag());