1 //! Implements "Stacked Borrows". See <https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md>
2 //! for further information.
5 use std::cell::RefCell;
8 use std::num::NonZeroU64;
10 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
11 use rustc_hir::Mutability;
12 use rustc_middle::mir::RetagKind;
13 use rustc_middle::ty::{
15 layout::{HasParamEnv, LayoutOf},
17 use rustc_span::DUMMY_SP;
18 use rustc_target::abi::Size;
19 use std::collections::HashSet;
24 use diagnostics::{AllocHistory, TagHistory};
29 pub type PtrId = NonZeroU64;
30 pub type CallId = NonZeroU64;
32 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
33 pub type AllocExtra = RefCell<Stacks>;
35 /// Tracking pointer provenance
36 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
37 pub struct SbTag(NonZeroU64);
40 pub fn new(i: u64) -> Option<Self> {
41 NonZeroU64::new(i).map(SbTag)
44 // The default to be used when SB is disabled
45 pub fn default() -> Self {
50 impl fmt::Debug for SbTag {
51 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52 write!(f, "<{}>", self.0)
56 /// The "extra" information an SB pointer has over a regular AllocId.
57 /// Newtype for `Option<SbTag>`.
58 #[derive(Copy, Clone)]
64 impl fmt::Debug for SbTagExtra {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 SbTagExtra::Concrete(pid) => write!(f, "{pid:?}"),
68 SbTagExtra::Wildcard => write!(f, "<wildcard>"),
74 fn and_then<T>(self, f: impl FnOnce(SbTag) -> Option<T>) -> Option<T> {
76 SbTagExtra::Concrete(pid) => f(pid),
77 SbTagExtra::Wildcard => None,
82 /// Indicates which permission is granted (by this item to some pointers)
83 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
85 /// Grants unique mutable access.
87 /// Grants shared mutable access.
89 /// Grants shared read-only access.
91 /// Grants no access, but separates two groups of SharedReadWrite so they are not
92 /// all considered mutually compatible.
96 /// An item in the per-location borrow stack.
97 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
99 /// The permission this item grants.
101 /// The pointers the permission is granted to.
103 /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
104 protector: Option<CallId>,
107 impl fmt::Debug for Item {
108 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109 write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
110 if let Some(call) = self.protector {
111 write!(f, " (call {})", call)?;
118 /// Extra per-allocation state.
119 #[derive(Clone, Debug)]
121 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
122 stacks: RangeMap<Stack>,
123 /// Stores past operations on this allocation
124 history: AllocHistory,
125 /// The set of tags that have been exposed inside this allocation.
126 exposed_tags: FxHashSet<SbTag>,
129 /// Extra global state, available to the memory access hooks.
131 pub struct GlobalStateInner {
132 /// Next unused pointer ID (tag).
134 /// Table storing the "base" tag for each allocation.
135 /// The base tag is the one used for the initial pointer.
136 /// We need this in a separate table to handle cyclic statics.
137 base_ptr_tags: FxHashMap<AllocId, SbTag>,
138 /// Next unused call ID (for protectors).
139 next_call_id: CallId,
140 /// Those call IDs corresponding to functions that are still running.
141 active_calls: FxHashSet<CallId>,
142 /// The pointer ids to trace
143 tracked_pointer_tags: HashSet<SbTag>,
144 /// The call ids to trace
145 tracked_call_ids: HashSet<CallId>,
146 /// Whether to recurse into datatypes when searching for pointers to retag.
150 /// We need interior mutable access to the global state.
151 pub type GlobalState = RefCell<GlobalStateInner>;
153 /// Indicates which kind of access is being performed.
154 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
155 pub enum AccessKind {
160 impl fmt::Display for AccessKind {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 AccessKind::Read => write!(f, "read access"),
164 AccessKind::Write => write!(f, "write access"),
169 /// Indicates which kind of reference is being created.
170 /// Used by high-level `reborrow` to compute which permissions to grant to the
172 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
174 /// `&mut` and `Box`.
175 Unique { two_phase: bool },
176 /// `&` with or without interior mutability.
178 /// `*mut`/`*const` (raw pointers).
179 Raw { mutable: bool },
182 impl fmt::Display for RefKind {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 RefKind::Unique { two_phase: false } => write!(f, "unique"),
186 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
187 RefKind::Shared => write!(f, "shared"),
188 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
189 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
194 /// Utilities for initialization and ID generation
195 impl GlobalStateInner {
197 tracked_pointer_tags: HashSet<SbTag>,
198 tracked_call_ids: HashSet<CallId>,
202 next_ptr_tag: SbTag(NonZeroU64::new(1).unwrap()),
203 base_ptr_tags: FxHashMap::default(),
204 next_call_id: NonZeroU64::new(1).unwrap(),
205 active_calls: FxHashSet::default(),
206 tracked_pointer_tags,
212 fn new_ptr(&mut self) -> SbTag {
213 let id = self.next_ptr_tag;
214 if self.tracked_pointer_tags.contains(&id) {
215 register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id.0));
217 self.next_ptr_tag = SbTag(NonZeroU64::new(id.0.get() + 1).unwrap());
221 pub fn new_call(&mut self) -> CallId {
222 let id = self.next_call_id;
223 trace!("new_call: Assigning ID {}", id);
224 if self.tracked_call_ids.contains(&id) {
225 register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
227 assert!(self.active_calls.insert(id));
228 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
232 pub fn end_call(&mut self, id: CallId) {
233 assert!(self.active_calls.remove(&id));
236 fn is_active(&self, id: CallId) -> bool {
237 self.active_calls.contains(&id)
240 pub fn base_ptr_tag(&mut self, id: AllocId) -> SbTag {
241 self.base_ptr_tags.get(&id).copied().unwrap_or_else(|| {
242 let tag = self.new_ptr();
243 trace!("New allocation {:?} has base tag {:?}", id, tag);
244 self.base_ptr_tags.try_insert(id, tag).unwrap();
251 pub fn err_sb_ub<'tcx>(
253 help: Option<String>,
254 history: Option<TagHistory>,
255 ) -> InterpError<'tcx> {
256 err_machine_stop!(TerminationInfo::StackedBorrowsUb { msg, help, history })
259 // # Stacked Borrows Core Begin
261 /// We need to make at least the following things true:
263 /// U1: After creating a `Uniq`, it is at the top.
264 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
265 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
267 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
268 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
269 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
271 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
272 /// F3: If an access happens with an `&` outside `UnsafeCell`,
273 /// it requires the `SharedReadOnly` to still be in the stack.
275 /// Core relation on `Permission` to define which accesses are allowed
277 /// This defines for a given permission, whether it permits the given kind of access.
278 fn grants(self, access: AccessKind) -> bool {
279 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
280 self != Permission::Disabled
281 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
285 /// Core per-location operations: access, dealloc, reborrow.
287 /// Find the first write-incompatible item above the given one --
288 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
289 fn find_first_write_incompatible(&self, granting: usize) -> usize {
290 let perm = self.get(granting).unwrap().perm;
292 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
293 Permission::Disabled => bug!("Cannot use Disabled for anything"),
294 Permission::Unique => {
295 // On a write, everything above us is incompatible.
298 Permission::SharedReadWrite => {
299 // The SharedReadWrite *just* above us are compatible, to skip those.
300 let mut idx = granting + 1;
301 while let Some(item) = self.get(idx) {
302 if item.perm == Permission::SharedReadWrite {
306 // Found first incompatible!
315 /// Check if the given item is protected.
317 /// The `provoking_access` argument is only used to produce diagnostics.
318 /// It is `Some` when we are granting the contained access for said tag, and it is
319 /// `None` during a deallocation.
320 /// Within `provoking_access, the `AllocRange` refers the entire operation, and
321 /// the `Size` refers to the specific location in the `AllocRange` that we are
322 /// currently checking.
325 provoking_access: Option<(SbTagExtra, AllocRange, Size, AccessKind)>, // just for debug printing and error messages
326 global: &GlobalStateInner,
327 alloc_history: &mut AllocHistory,
328 ) -> InterpResult<'tcx> {
329 if global.tracked_pointer_tags.contains(&item.tag) {
330 register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(
332 provoking_access.map(|(tag, _alloc_range, _size, access)| (tag, access)),
336 if let Some(call) = item.protector {
337 if global.is_active(call) {
338 if let Some((tag, _alloc_range, _offset, _access)) = provoking_access {
341 "not granting access to tag {:?} because incompatible item is protected: {:?}",
345 tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, Some(item.tag))),
349 format!("deallocating while item is protected: {:?}", item),
359 /// Test if a memory `access` using pointer tagged `tag` is granted.
360 /// If yes, return the index of the item that granted it.
361 /// `range` refers the entire operation, and `offset` refers to the specific offset into the
362 /// allocation that we are currently checking.
367 (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
368 global: &mut GlobalStateInner,
369 current_span: &mut CurrentSpan<'_, '_, 'tcx>,
370 alloc_history: &mut AllocHistory,
371 exposed_tags: &FxHashSet<SbTag>,
372 ) -> InterpResult<'tcx> {
373 // Two main steps: Find granting item, remove incompatible items above.
375 // Step 1: Find granting item.
376 let granting_idx = self.find_granting(access, tag, exposed_tags).map_err(|_| {
377 alloc_history.access_error(access, tag, alloc_id, alloc_range, offset, self)
380 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
381 // items. Behavior differs for reads and writes.
382 // In case of wildcards/unknown matches, we remove everything that is *definitely* gone.
383 if access == AccessKind::Write {
384 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
385 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
386 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
387 // The granting_idx *might* be approximate, but any lower idx would remove more
388 // things. Even if this is a Unique and the lower idx is an SRW (which removes
389 // less), there is an SRW group boundary here so strictly more would get removed.
390 self.find_first_write_incompatible(granting_idx)
392 // We are writing to something in the unknown part.
393 // There is a SRW group boundary between the unknown and the known, so everything is incompatible.
396 self.pop_items_after(first_incompatible_idx, |item| {
399 Some((tag, alloc_range, offset, access)),
403 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
407 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
408 // The reason this is not following the stack discipline (by removing the first Unique and
409 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
410 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
411 // `SharedReadWrite` for `raw`.
412 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
413 // reference and use that.
414 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
415 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
416 // The granting_idx *might* be approximate, but any lower idx would disable more things.
419 // We are reading from something in the unknown part. That means *all* `Unique` we know about are dead now.
422 self.disable_uniques_starting_at(first_incompatible_idx, |item| {
425 Some((tag, alloc_range, offset, access)),
429 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
434 // If this was an approximate action, we now collapse everything into an unknown.
435 if granting_idx.is_none() || matches!(tag, SbTagExtra::Wildcard) {
436 // Compute the upper bound of the items that remain.
437 // (This is why we did all the work above: to reduce the items we have to consider here.)
438 let mut max = NonZeroU64::new(1).unwrap();
439 for i in 0..self.len() {
440 let item = self.get(i).unwrap();
441 // Skip disabled items, they cannot be matched anyway.
442 if !matches!(item.perm, Permission::Disabled) {
443 // We are looking for a strict upper bound, so add 1 to this tag.
444 max = cmp::max(item.tag.0.checked_add(1).unwrap(), max);
447 if let Some(unk) = self.unknown_bottom() {
448 max = cmp::max(unk.0, max);
450 // Use `max` as new strict upper bound for everything.
452 "access: forgetting stack to upper bound {max} due to wildcard or unknown access"
454 self.set_unknown_bottom(SbTag(max));
461 /// Deallocate a location: Like a write access, but also there must be no
462 /// active protectors at all because we will remove all items.
466 (alloc_id, _alloc_range, _offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
467 global: &GlobalStateInner,
468 alloc_history: &mut AllocHistory,
469 exposed_tags: &FxHashSet<SbTag>,
470 ) -> InterpResult<'tcx> {
471 // Step 1: Make sure there is a granting item.
472 self.find_granting(AccessKind::Write, tag, exposed_tags).map_err(|_| {
474 "no item granting write access for deallocation to tag {:?} at {:?} found in borrow stack",
478 tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, None)),
482 // Step 2: Remove all items. Also checks for protectors.
483 for idx in (0..self.len()).rev() {
484 let item = self.get(idx).unwrap();
485 Stack::item_popped(&item, None, global, alloc_history)?;
490 /// Derive a new pointer from one with the given tag.
491 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
492 /// an access, and they add the new item directly on top of the one it is derived
493 /// from instead of all the way at the top of the stack.
494 /// `range` refers the entire operation, and `offset` refers to the specific location in
495 /// `range` that we are currently checking.
498 derived_from: SbTagExtra,
500 (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
501 global: &mut GlobalStateInner,
502 current_span: &mut CurrentSpan<'_, '_, 'tcx>,
503 alloc_history: &mut AllocHistory,
504 exposed_tags: &FxHashSet<SbTag>,
505 ) -> InterpResult<'tcx> {
506 // Figure out which access `perm` corresponds to.
508 if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
510 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
511 // We use that to determine where to put the new item.
513 self.find_granting(access, derived_from, exposed_tags).map_err(|_| {
514 alloc_history.grant_error(derived_from, new, alloc_id, alloc_range, offset, self)
517 // Compute where to put the new item.
518 // Either way, we ensure that we insert the new item in a way such that between
519 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
520 let new_idx = if new.perm == Permission::SharedReadWrite {
522 access == AccessKind::Write,
523 "this case only makes sense for stack-like accesses"
526 let (Some(granting_idx), SbTagExtra::Concrete(_)) = (granting_idx, derived_from) else {
527 // The parent is a wildcard pointer or matched the unknown bottom.
528 // This is approximate. Nobody knows what happened, so forget everything.
529 // The new thing is SRW anyway, so we cannot push it "on top of the unkown part"
530 // (for all we know, it might join an SRW group inside the unknown).
531 trace!("reborrow: forgetting stack entirely due to SharedReadWrite reborrow from wildcard or unknown");
532 self.set_unknown_bottom(global.next_ptr_tag);
536 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
537 // access. Instead of popping the stack, we insert the item at the place the stack would
538 // be popped to (i.e., we insert it above all the write-compatible items).
539 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
540 self.find_first_write_incompatible(granting_idx)
542 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
543 // Here, creating a reference actually counts as an access.
544 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
548 (alloc_id, alloc_range, offset),
555 // We insert "as far up as possible": We know only compatible items are remaining
556 // on top of `derived_from`, and we want the new item at the top so that we
557 // get the strongest possible guarantees.
558 // This ensures U1 and F1.
562 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
563 // `new_idx` might be 0 if we just cleared the entire stack.
564 if self.get(new_idx) == Some(new) || (new_idx > 0 && self.get(new_idx - 1).unwrap() == new)
566 // Optimization applies, done.
567 trace!("reborrow: avoiding adding redundant item {:?}", new);
569 trace!("reborrow: adding item {:?}", new);
570 self.insert(new_idx, new);
575 // # Stacked Borrows Core End
577 /// Map per-stack operations to higher-level per-location-range operations.
579 /// Creates new stack with initial tag.
580 fn new(size: Size, perm: Permission, tag: SbTag) -> Self {
581 let item = Item { perm, tag, protector: None };
583 let stack = Stack::new(item);
585 stacks: RangeMap::new(size, stack),
586 history: AllocHistory::new(),
587 exposed_tags: FxHashSet::default(),
591 /// Call `f` on every stack in the range.
599 &mut FxHashSet<SbTag>,
600 ) -> InterpResult<'tcx>,
601 ) -> InterpResult<'tcx> {
602 for (offset, stack) in self.stacks.iter_mut(range.start, range.size) {
603 f(offset, stack, &mut self.history, &mut self.exposed_tags)?;
609 /// Glue code to connect with Miri Machine Hooks
611 pub fn new_allocation(
615 kind: MemoryKind<MiriMemoryKind>,
616 mut current_span: CurrentSpan<'_, '_, '_>,
618 let mut extra = state.borrow_mut();
619 let (base_tag, perm) = match kind {
620 // New unique borrow. This tag is not accessible by the program,
621 // so it will only ever be used when using the local directly (i.e.,
622 // not through a pointer). That is, whenever we directly write to a local, this will pop
623 // everything else off the stack, invalidating all previous pointers,
624 // and in particular, *all* raw pointers.
625 MemoryKind::Stack => (extra.base_ptr_tag(id), Permission::Unique),
626 // Everything else is shared by default.
627 _ => (extra.base_ptr_tag(id), Permission::SharedReadWrite),
629 let mut stacks = Stacks::new(size, perm, base_tag);
630 stacks.history.log_creation(
633 alloc_range(Size::ZERO, size),
640 pub fn memory_read<'tcx>(
646 mut current_span: CurrentSpan<'_, '_, 'tcx>,
647 ) -> InterpResult<'tcx> {
649 "read access with tag {:?}: {:?}, size {}",
651 Pointer::new(alloc_id, range.start),
654 let mut state = state.borrow_mut();
655 self.for_each(range, |offset, stack, history, exposed_tags| {
659 (alloc_id, range, offset),
669 pub fn memory_written<'tcx>(
675 mut current_span: CurrentSpan<'_, '_, 'tcx>,
676 ) -> InterpResult<'tcx> {
678 "write access with tag {:?}: {:?}, size {}",
680 Pointer::new(alloc_id, range.start),
683 let mut state = state.borrow_mut();
684 self.for_each(range, |offset, stack, history, exposed_tags| {
688 (alloc_id, range, offset),
698 pub fn memory_deallocated<'tcx>(
704 ) -> InterpResult<'tcx> {
705 trace!("deallocation with tag {:?}: {:?}, size {}", tag, alloc_id, range.size.bytes());
706 let state = state.borrow();
707 self.for_each(range, |offset, stack, history, exposed_tags| {
708 stack.dealloc(tag, (alloc_id, range, offset), &state, history, exposed_tags)
714 /// Retagging/reborrowing. There is some policy in here, such as which permissions
715 /// to grant for which references, and when to add protectors.
716 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
717 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
718 /// Returns the `AllocId` the reborrow was done in, if some actual borrow stack manipulation
722 place: &MPlaceTy<'tcx, Tag>,
727 ) -> InterpResult<'tcx, Option<AllocId>> {
728 let this = self.eval_context_mut();
729 let current_span = &mut this.machine.current_span();
731 let log_creation = |this: &MiriEvalContext<'mir, 'tcx>,
732 current_span: &mut CurrentSpan<'_, 'mir, 'tcx>,
736 -> InterpResult<'tcx> {
737 let SbTagExtra::Concrete(orig_tag) = orig_tag else {
738 // FIXME: should we log this?
741 let extra = this.get_alloc_extra(alloc_id)?;
742 let mut stacked_borrows = extra
745 .expect("we should have Stacked Borrows data")
747 stacked_borrows.history.log_creation(
750 alloc_range(base_offset, size),
754 stacked_borrows.history.log_protector(orig_tag, new_tag, current_span);
759 if size == Size::ZERO {
761 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
767 // Don't update any stacks for a zero-sized access; borrow stacks are per-byte and this
768 // touches no bytes so there is no stack to put this tag in.
769 // However, if the pointer for this operation points at a real allocation we still
770 // record where it was created so that we can issue a helpful diagnostic if there is an
771 // attempt to use it for a non-zero-sized access.
772 // Dangling slices are a common case here; it's valid to get their length but with raw
773 // pointer tagging for example all calls to get_unchecked on them are invalid.
774 if let Ok((alloc_id, base_offset, orig_tag)) = this.ptr_try_get_alloc_id(place.ptr) {
775 log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
776 return Ok(Some(alloc_id));
778 // This pointer doesn't come with an AllocId. :shrug:
781 let (alloc_id, base_offset, orig_tag) = this.ptr_get_alloc_id(place.ptr)?;
782 log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
784 // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
785 let (alloc_size, _) = this.get_live_alloc_size_and_align(alloc_id)?;
786 if base_offset + size > alloc_size {
787 throw_ub!(PointerOutOfBounds {
790 ptr_offset: this.machine_usize_to_isize(base_offset.bytes()),
792 msg: CheckInAllocMsg::InboundsTest
796 let protector = if protect { Some(this.frame().extra.call_id) } else { None };
798 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
803 Pointer::new(alloc_id, base_offset),
807 // Update the stacks.
808 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
809 // There could be existing unique pointers reborrowed from them that should remain valid!
810 let perm = match kind {
811 RefKind::Unique { two_phase: false }
812 if place.layout.ty.is_unpin(this.tcx.at(DUMMY_SP), this.param_env()) =>
814 // Only if the type is unpin do we actually enforce uniqueness
817 RefKind::Unique { .. } => {
818 // Two-phase references and !Unpin references are treated as SharedReadWrite
819 Permission::SharedReadWrite
821 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
822 RefKind::Shared | RefKind::Raw { mutable: false } => {
823 // Shared references and *const are a whole different kind of game, the
824 // permission is not uniform across the entire range!
825 // We need a frozen-sensitive reborrow.
826 // We have to use shared references to alloc/memory_extra here since
827 // `visit_freeze_sensitive` needs to access the global state.
828 let extra = this.get_alloc_extra(alloc_id)?;
830 let mut stacked_borrows = extra
833 .expect("we should have Stacked Borrows data")
835 let mut current_span = this.machine.current_span();
837 this.visit_freeze_sensitive(place, size, |mut range, frozen| {
839 range.start += base_offset;
840 // We are only ever `SharedReadOnly` inside the frozen bits.
841 let perm = if frozen {
842 Permission::SharedReadOnly
844 Permission::SharedReadWrite
846 let protector = if frozen {
849 // We do not protect inside UnsafeCell.
850 // This fixes https://github.com/rust-lang/rust/issues/55005.
853 let item = Item { perm, tag: new_tag, protector };
854 let mut global = this.machine.stacked_borrows.as_ref().unwrap().borrow_mut();
855 stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
859 (alloc_id, range, offset),
867 return Ok(Some(alloc_id));
870 // Here we can avoid `borrow()` calls because we have mutable references.
871 // Note that this asserts that the allocation is mutable -- but since we are creating a
872 // mutable pointer, that seems reasonable.
873 let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc_id)?;
874 let mut stacked_borrows = alloc_extra
877 .expect("we should have Stacked Borrows data")
879 let item = Item { perm, tag: new_tag, protector };
880 let range = alloc_range(base_offset, size);
881 let mut global = machine.stacked_borrows.as_ref().unwrap().borrow_mut();
882 let current_span = &mut machine.current_span(); // `get_alloc_extra_mut` invalidated our old `current_span`
883 stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
887 (alloc_id, range, offset),
898 /// Retags an indidual pointer, returning the retagged version.
899 /// `mutbl` can be `None` to make this a raw pointer.
902 val: &ImmTy<'tcx, Tag>,
905 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
906 let this = self.eval_context_mut();
907 // We want a place for where the ptr *points to*, so we get one.
908 let place = this.ref_to_mplace(val)?;
909 let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
910 // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
911 // bail out -- we cannot reasonably figure out which memory range to reborrow.
912 // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
913 let size = match size {
915 None => return Ok(*val),
918 // Compute new borrow.
919 let new_tag = this.machine.stacked_borrows.as_mut().unwrap().get_mut().new_ptr();
922 let alloc_id = this.reborrow(&place, size, kind, new_tag, protect)?;
925 let new_place = place.map_provenance(|p| {
929 // If `reborrow` could figure out the AllocId of this ptr, hard-code it into the new one.
930 // Even if we started out with a wildcard, this newly retagged pointer is tied to that allocation.
931 Tag::Concrete { alloc_id, sb: new_tag }
934 // Looks like this has to stay a wildcard pointer.
935 assert!(matches!(prov, Tag::Wildcard));
942 // Return new pointer.
943 Ok(ImmTy::from_immediate(new_place.to_ref(this), val.layout))
947 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
948 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
949 fn retag(&mut self, kind: RetagKind, place: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
950 let this = self.eval_context_mut();
951 // Determine mutability and whether to add a protector.
952 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
953 // making it useless.
954 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
956 // References are simple.
957 ty::Ref(_, _, Mutability::Mut) =>
959 RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
960 kind == RetagKind::FnEntry,
962 ty::Ref(_, _, Mutability::Not) =>
963 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
964 // Raw pointers need to be enabled.
965 ty::RawPtr(tym) if kind == RetagKind::Raw =>
966 Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
967 // Boxes do not get a protector: protectors reflect that references outlive the call
968 // they were passed in to; that's just not the case for boxes.
969 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
974 // We need a visitor to visit all references. However, that requires
975 // a `MPlaceTy` (or `OpTy), so we have a fast path for reference types that
976 // avoids allocating.
978 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
980 let val = this.read_immediate(&this.place_to_op(place)?)?;
981 let val = this.retag_reference(&val, mutbl, protector)?;
982 this.write_immediate(*val, place)?;
986 // If we don't want to recurse, we are already done.
987 if !this.machine.stacked_borrows.as_mut().unwrap().get_mut().retag_fields {
991 // Skip some types that have no further structure we might care about.
993 place.layout.ty.kind(),
1004 // Now go visit this thing.
1005 let place = this.force_allocation(place)?;
1007 let mut visitor = RetagVisitor { ecx: this, kind };
1008 return visitor.visit_value(&place);
1010 // The actual visitor.
1011 struct RetagVisitor<'ecx, 'mir, 'tcx> {
1012 ecx: &'ecx mut MiriEvalContext<'mir, 'tcx>,
1015 impl<'ecx, 'mir, 'tcx> MutValueVisitor<'mir, 'tcx, Evaluator<'mir, 'tcx>>
1016 for RetagVisitor<'ecx, 'mir, 'tcx>
1018 type V = MPlaceTy<'tcx, Tag>;
1021 fn ecx(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
1025 fn visit_value(&mut self, place: &MPlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
1026 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
1027 let val = self.ecx.read_immediate(&place.into())?;
1028 let val = self.ecx.retag_reference(&val, mutbl, protector)?;
1029 self.ecx.write_immediate(*val, &place.into())?;
1031 // Maybe we need to go deeper.
1032 self.walk_value(place)?;
1039 /// After a stack frame got pushed, retag the return place so that we are sure
1040 /// it does not alias with anything.
1042 /// This is a HACK because there is nothing in MIR that would make the retag
1043 /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>.
1044 fn retag_return_place(&mut self) -> InterpResult<'tcx> {
1045 let this = self.eval_context_mut();
1046 let return_place = this.frame_mut().return_place;
1047 if return_place.layout.is_zst() {
1048 // There may not be any memory here, nothing to do.
1051 // We need this to be in-memory to use tagged pointers.
1052 let return_place = this.force_allocation(&return_place)?;
1054 // We have to turn the place into a pointer to use the existing code.
1055 // (The pointer type does not matter, so we use a raw pointer.)
1056 let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
1057 let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout);
1059 let val = this.retag_reference(
1061 RefKind::Unique { two_phase: false },
1064 // And use reborrowed pointer for return place.
1065 let return_place = this.ref_to_mplace(&val)?;
1066 this.frame_mut().return_place = return_place.into();
1071 /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
1072 fn expose_tag(&mut self, alloc_id: AllocId, tag: SbTag) {
1073 let this = self.eval_context_mut();
1075 // Function pointers and dead objects don't have an alloc_extra so we ignore them.
1076 // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks.
1077 // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
1078 let (_size, _align, kind) = this.get_alloc_info(alloc_id);
1080 AllocKind::LiveData => {
1081 // This should have alloc_extra data.
1082 let alloc_extra = this.get_alloc_extra(alloc_id).unwrap();
1083 trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id}");
1084 alloc_extra.stacked_borrows.as_ref().unwrap().borrow_mut().exposed_tags.insert(tag);
1086 AllocKind::Function | AllocKind::Dead => {
1087 // No stacked borrows on these allocations.