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};
26 pub type CallId = NonZeroU64;
28 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
29 pub type AllocExtra = RefCell<Stacks>;
31 /// Tracking pointer provenance
32 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
33 pub struct SbTag(NonZeroU64);
36 pub fn new(i: u64) -> Option<Self> {
37 NonZeroU64::new(i).map(SbTag)
40 // The default to be used when SB is disabled
41 pub fn default() -> Self {
46 impl fmt::Debug for SbTag {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 write!(f, "<{}>", self.0)
52 /// The "extra" information an SB pointer has over a regular AllocId.
53 /// Newtype for `Option<SbTag>`.
54 #[derive(Copy, Clone)]
60 impl fmt::Debug for SbTagExtra {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 SbTagExtra::Concrete(pid) => write!(f, "{pid:?}"),
64 SbTagExtra::Wildcard => write!(f, "<wildcard>"),
70 fn and_then<T>(self, f: impl FnOnce(SbTag) -> Option<T>) -> Option<T> {
72 SbTagExtra::Concrete(pid) => f(pid),
73 SbTagExtra::Wildcard => None,
78 /// Indicates which permission is granted (by this item to some pointers)
79 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
81 /// Grants unique mutable access.
83 /// Grants shared mutable access.
85 /// Grants shared read-only access.
87 /// Grants no access, but separates two groups of SharedReadWrite so they are not
88 /// all considered mutually compatible.
92 /// An item in the per-location borrow stack.
93 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
95 /// The permission this item grants.
97 /// The pointers the permission is granted to.
99 /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
100 protector: Option<CallId>,
103 impl fmt::Debug for Item {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
106 if let Some(call) = self.protector {
107 write!(f, " (call {})", call)?;
114 /// Extra per-location state.
115 #[derive(Clone, Debug, PartialEq, Eq)]
117 /// Used *mostly* as a stack; never empty.
119 /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
120 /// * No tag occurs in the stack more than once.
122 /// If this is `Some(id)`, then the actual current stack is unknown. This can happen when
123 /// wildcard pointers are used to access this location. What we do know is that `borrows` are at
124 /// the top of the stack, and below it are arbitrarily many items whose `tag` is strictly less
126 /// When the bottom is unknown, `borrows` always has a `SharedReadOnly` or `Unique` at the bottom;
127 /// we never have the unknown-to-known boundary in an SRW group.
128 unknown_bottom: Option<SbTag>,
131 /// Extra per-allocation state.
132 #[derive(Clone, Debug)]
134 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
135 stacks: RangeMap<Stack>,
136 /// Stores past operations on this allocation
137 history: AllocHistory,
138 /// The set of tags that have been exposed inside this allocation.
139 exposed_tags: FxHashSet<SbTag>,
142 /// Extra global state, available to the memory access hooks.
144 pub struct GlobalStateInner {
145 /// Next unused pointer ID (tag).
147 /// Table storing the "base" tag for each allocation.
148 /// The base tag is the one used for the initial pointer.
149 /// We need this in a separate table to handle cyclic statics.
150 base_ptr_tags: FxHashMap<AllocId, SbTag>,
151 /// Next unused call ID (for protectors).
152 next_call_id: CallId,
153 /// Those call IDs corresponding to functions that are still running.
154 active_calls: FxHashSet<CallId>,
155 /// The pointer ids to trace
156 tracked_pointer_tags: HashSet<SbTag>,
157 /// The call ids to trace
158 tracked_call_ids: HashSet<CallId>,
161 /// We need interior mutable access to the global state.
162 pub type GlobalState = RefCell<GlobalStateInner>;
164 /// Indicates which kind of access is being performed.
165 #[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
166 pub enum AccessKind {
171 impl fmt::Display for AccessKind {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 AccessKind::Read => write!(f, "read access"),
175 AccessKind::Write => write!(f, "write access"),
180 /// Indicates which kind of reference is being created.
181 /// Used by high-level `reborrow` to compute which permissions to grant to the
183 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
185 /// `&mut` and `Box`.
186 Unique { two_phase: bool },
187 /// `&` with or without interior mutability.
189 /// `*mut`/`*const` (raw pointers).
190 Raw { mutable: bool },
193 impl fmt::Display for RefKind {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 RefKind::Unique { two_phase: false } => write!(f, "unique"),
197 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
198 RefKind::Shared => write!(f, "shared"),
199 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
200 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
205 /// Utilities for initialization and ID generation
206 impl GlobalStateInner {
207 pub fn new(tracked_pointer_tags: HashSet<SbTag>, tracked_call_ids: HashSet<CallId>) -> Self {
209 next_ptr_tag: SbTag(NonZeroU64::new(1).unwrap()),
210 base_ptr_tags: FxHashMap::default(),
211 next_call_id: NonZeroU64::new(1).unwrap(),
212 active_calls: FxHashSet::default(),
213 tracked_pointer_tags,
218 fn new_ptr(&mut self) -> SbTag {
219 let id = self.next_ptr_tag;
220 if self.tracked_pointer_tags.contains(&id) {
221 register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id.0));
223 self.next_ptr_tag = SbTag(NonZeroU64::new(id.0.get() + 1).unwrap());
227 pub fn new_call(&mut self) -> CallId {
228 let id = self.next_call_id;
229 trace!("new_call: Assigning ID {}", id);
230 if self.tracked_call_ids.contains(&id) {
231 register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
233 assert!(self.active_calls.insert(id));
234 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
238 pub fn end_call(&mut self, id: CallId) {
239 assert!(self.active_calls.remove(&id));
242 fn is_active(&self, id: CallId) -> bool {
243 self.active_calls.contains(&id)
246 pub fn base_ptr_tag(&mut self, id: AllocId) -> SbTag {
247 self.base_ptr_tags.get(&id).copied().unwrap_or_else(|| {
248 let tag = self.new_ptr();
249 trace!("New allocation {:?} has base tag {:?}", id, tag);
250 self.base_ptr_tags.try_insert(id, tag).unwrap();
257 pub fn err_sb_ub<'tcx>(
259 help: Option<String>,
260 history: Option<TagHistory>,
261 ) -> InterpError<'tcx> {
262 err_machine_stop!(TerminationInfo::StackedBorrowsUb { msg, help, history })
265 // # Stacked Borrows Core Begin
267 /// We need to make at least the following things true:
269 /// U1: After creating a `Uniq`, it is at the top.
270 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
271 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
273 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
274 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
275 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
277 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
278 /// F3: If an access happens with an `&` outside `UnsafeCell`,
279 /// it requires the `SharedReadOnly` to still be in the stack.
281 /// Core relation on `Permission` to define which accesses are allowed
283 /// This defines for a given permission, whether it permits the given kind of access.
284 fn grants(self, access: AccessKind) -> bool {
285 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
286 self != Permission::Disabled
287 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
291 /// Core per-location operations: access, dealloc, reborrow.
293 /// Find the item granting the given kind of access to the given tag, and return where
294 /// it is on the stack. For wildcard tags, the given index is approximate, but if *no*
295 /// index is given it means the match was *not* in the known part of the stack.
296 /// `Ok(None)` indicates it matched the "unknown" part of the stack.
297 /// `Err` indicates it was not found.
302 exposed_tags: &FxHashSet<SbTag>,
303 ) -> Result<Option<usize>, ()> {
304 let SbTagExtra::Concrete(tag) = tag else {
305 // Handle the wildcard case.
306 // Go search the stack for an exposed tag.
310 .enumerate() // we also need to know *where* in the stack
311 .rev() // search top-to-bottom
312 .find_map(|(idx, item)| {
313 // If the item fits and *might* be this wildcard, use it.
314 if item.perm.grants(access) && exposed_tags.contains(&item.tag) {
321 return Ok(Some(idx));
323 // If we couldn't find it in the stack, check the unknown bottom.
324 return if self.unknown_bottom.is_some() { Ok(None) } else { Err(()) };
330 .enumerate() // we also need to know *where* in the stack
331 .rev() // search top-to-bottom
332 // Return permission of first item that grants access.
333 // We require a permission with the right tag, ensuring U3 and F3.
334 .find_map(|(idx, item)| {
335 if tag == item.tag && item.perm.grants(access) { Some(idx) } else { None }
338 return Ok(Some(idx));
341 // Couldn't find it in the stack; but if there is an unknown bottom it might be there.
342 let found = self.unknown_bottom.is_some_and(|&unknown_limit| {
343 tag.0 < unknown_limit.0 // unknown_limit is an upper bound for what can be in the unknown bottom.
345 if found { Ok(None) } else { Err(()) }
348 /// Find the first write-incompatible item above the given one --
349 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
350 fn find_first_write_incompatible(&self, granting: usize) -> usize {
351 let perm = self.borrows[granting].perm;
353 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
354 Permission::Disabled => bug!("Cannot use Disabled for anything"),
355 Permission::Unique => {
356 // On a write, everything above us is incompatible.
359 Permission::SharedReadWrite => {
360 // The SharedReadWrite *just* above us are compatible, to skip those.
361 let mut idx = granting + 1;
362 while let Some(item) = self.borrows.get(idx) {
363 if item.perm == Permission::SharedReadWrite {
367 // Found first incompatible!
376 /// Check if the given item is protected.
378 /// The `provoking_access` argument is only used to produce diagnostics.
379 /// It is `Some` when we are granting the contained access for said tag, and it is
380 /// `None` during a deallocation.
381 /// Within `provoking_access, the `AllocRange` refers the entire operation, and
382 /// the `Size` refers to the specific location in the `AllocRange` that we are
383 /// currently checking.
386 provoking_access: Option<(SbTagExtra, AllocRange, Size, AccessKind)>, // just for debug printing and error messages
387 global: &GlobalStateInner,
388 alloc_history: &mut AllocHistory,
389 ) -> InterpResult<'tcx> {
390 if global.tracked_pointer_tags.contains(&item.tag) {
391 register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(
393 provoking_access.map(|(tag, _alloc_range, _size, access)| (tag, access)),
397 if let Some(call) = item.protector {
398 if global.is_active(call) {
399 if let Some((tag, _alloc_range, _offset, _access)) = provoking_access {
402 "not granting access to tag {:?} because incompatible item is protected: {:?}",
406 tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, Some(item.tag))),
410 format!("deallocating while item is protected: {:?}", item),
420 /// Test if a memory `access` using pointer tagged `tag` is granted.
421 /// If yes, return the index of the item that granted it.
422 /// `range` refers the entire operation, and `offset` refers to the specific offset into the
423 /// allocation that we are currently checking.
428 (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
429 global: &mut GlobalStateInner,
430 current_span: &mut CurrentSpan<'_, '_, 'tcx>,
431 alloc_history: &mut AllocHistory,
432 exposed_tags: &FxHashSet<SbTag>,
433 ) -> InterpResult<'tcx> {
434 // Two main steps: Find granting item, remove incompatible items above.
436 // Step 1: Find granting item.
437 let granting_idx = self.find_granting(access, tag, exposed_tags).map_err(|_| {
438 alloc_history.access_error(access, tag, alloc_id, alloc_range, offset, self)
441 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
442 // items. Behavior differs for reads and writes.
443 // In case of wildcards/unknown matches, we remove everything that is *definitely* gone.
444 if access == AccessKind::Write {
445 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
446 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
447 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
448 // The granting_idx *might* be approximate, but any lower idx would remove more
449 // things. Even if this is a Unique and the lower idx is an SRW (which removes
450 // less), there is an SRW group boundary here so strictly more would get removed.
451 self.find_first_write_incompatible(granting_idx)
453 // We are writing to something in the unknown part.
454 // There is a SRW group boundary between the unknown and the known, so everything is incompatible.
457 for item in self.borrows.drain(first_incompatible_idx..).rev() {
458 trace!("access: popping item {:?}", item);
461 Some((tag, alloc_range, offset, access)),
465 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
468 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
469 // The reason this is not following the stack discipline (by removing the first Unique and
470 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
471 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
472 // `SharedReadWrite` for `raw`.
473 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
474 // reference and use that.
475 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
476 let first_incompatible_idx = if let Some(granting_idx) = granting_idx {
477 // The granting_idx *might* be approximate, but any lower idx would disable more things.
480 // We are reading from something in the unknown part. That means *all* `Unique` we know about are dead now.
483 for idx in (first_incompatible_idx..self.borrows.len()).rev() {
484 let item = &mut self.borrows[idx];
486 if item.perm == Permission::Unique {
487 trace!("access: disabling item {:?}", item);
490 Some((tag, alloc_range, offset, access)),
494 item.perm = Permission::Disabled;
495 alloc_history.log_invalidation(item.tag, alloc_range, current_span);
500 // If this was an approximate action, we now collapse everything into an unknown.
501 if granting_idx.is_none() || matches!(tag, SbTagExtra::Wildcard) {
502 // Compute the upper bound of the items that remain.
503 // (This is why we did all the work above: to reduce the items we have to consider here.)
504 let mut max = NonZeroU64::new(1).unwrap();
505 for item in &self.borrows {
506 // Skip disabled items, they cannot be matched anyway.
507 if !matches!(item.perm, Permission::Disabled) {
508 // We are looking for a strict upper bound, so add 1 to this tag.
509 max = cmp::max(item.tag.0.checked_add(1).unwrap(), max);
512 if let Some(unk) = self.unknown_bottom {
513 max = cmp::max(unk.0, max);
515 // Use `max` as new strict upper bound for everything.
517 "access: forgetting stack to upper bound {max} due to wildcard or unknown access"
519 self.borrows.clear();
520 self.unknown_bottom = Some(SbTag(max));
527 /// Deallocate a location: Like a write access, but also there must be no
528 /// active protectors at all because we will remove all items.
532 (alloc_id, _alloc_range, _offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
533 global: &GlobalStateInner,
534 alloc_history: &mut AllocHistory,
535 exposed_tags: &FxHashSet<SbTag>,
536 ) -> InterpResult<'tcx> {
537 // Step 1: Make sure there is a granting item.
538 self.find_granting(AccessKind::Write, tag, exposed_tags).map_err(|_| {
540 "no item granting write access for deallocation to tag {:?} at {:?} found in borrow stack",
544 tag.and_then(|tag| alloc_history.get_logs_relevant_to(tag, None)),
548 // Step 2: Remove all items. Also checks for protectors.
549 for item in self.borrows.drain(..).rev() {
550 Stack::item_popped(&item, None, global, alloc_history)?;
555 /// Derive a new pointer from one with the given tag.
556 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
557 /// an access, and they add the new item directly on top of the one it is derived
558 /// from instead of all the way at the top of the stack.
559 /// `range` refers the entire operation, and `offset` refers to the specific location in
560 /// `range` that we are currently checking.
563 derived_from: SbTagExtra,
565 (alloc_id, alloc_range, offset): (AllocId, AllocRange, Size), // just for debug printing and error messages
566 global: &mut GlobalStateInner,
567 current_span: &mut CurrentSpan<'_, '_, 'tcx>,
568 alloc_history: &mut AllocHistory,
569 exposed_tags: &FxHashSet<SbTag>,
570 ) -> InterpResult<'tcx> {
571 // Figure out which access `perm` corresponds to.
573 if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
575 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
576 // We use that to determine where to put the new item.
578 self.find_granting(access, derived_from, exposed_tags).map_err(|_| {
579 alloc_history.grant_error(derived_from, new, alloc_id, alloc_range, offset, self)
582 // Compute where to put the new item.
583 // Either way, we ensure that we insert the new item in a way such that between
584 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
585 let new_idx = if new.perm == Permission::SharedReadWrite {
587 access == AccessKind::Write,
588 "this case only makes sense for stack-like accesses"
591 let (Some(granting_idx), SbTagExtra::Concrete(_)) = (granting_idx, derived_from) else {
592 // The parent is a wildcard pointer or matched the unknown bottom.
593 // This is approximate. Nobody knows what happened, so forget everything.
594 // The new thing is SRW anyway, so we cannot push it "on top of the unkown part"
595 // (for all we know, it might join an SRW group inside the unknown).
596 trace!("reborrow: forgetting stack entirely due to SharedReadWrite reborrow from wildcard or unknown");
597 self.borrows.clear();
598 self.unknown_bottom = Some(global.next_ptr_tag);
602 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
603 // access. Instead of popping the stack, we insert the item at the place the stack would
604 // be popped to (i.e., we insert it above all the write-compatible items).
605 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
606 self.find_first_write_incompatible(granting_idx)
608 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
609 // Here, creating a reference actually counts as an access.
610 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
614 (alloc_id, alloc_range, offset),
621 // We insert "as far up as possible": We know only compatible items are remaining
622 // on top of `derived_from`, and we want the new item at the top so that we
623 // get the strongest possible guarantees.
624 // This ensures U1 and F1.
628 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
629 // `new_idx` might be 0 if we just cleared the entire stack.
630 if self.borrows.get(new_idx) == Some(&new)
631 || (new_idx > 0 && self.borrows[new_idx - 1] == new)
633 // Optimization applies, done.
634 trace!("reborrow: avoiding adding redundant item {:?}", new);
636 trace!("reborrow: adding item {:?}", new);
637 self.borrows.insert(new_idx, new);
642 // # Stacked Borrows Core End
644 /// Map per-stack operations to higher-level per-location-range operations.
646 /// Creates new stack with initial tag.
647 fn new(size: Size, perm: Permission, tag: SbTag) -> Self {
648 let item = Item { perm, tag, protector: None };
649 let stack = Stack { borrows: vec![item], unknown_bottom: None };
652 stacks: RangeMap::new(size, stack),
653 history: AllocHistory::new(),
654 exposed_tags: FxHashSet::default(),
658 /// Call `f` on every stack in the range.
666 &mut FxHashSet<SbTag>,
667 ) -> InterpResult<'tcx>,
668 ) -> InterpResult<'tcx> {
669 for (offset, stack) in self.stacks.iter_mut(range.start, range.size) {
670 f(offset, stack, &mut self.history, &mut self.exposed_tags)?;
676 /// Glue code to connect with Miri Machine Hooks
678 pub fn new_allocation(
682 kind: MemoryKind<MiriMemoryKind>,
683 mut current_span: CurrentSpan<'_, '_, '_>,
685 let mut extra = state.borrow_mut();
686 let (base_tag, perm) = match kind {
687 // New unique borrow. This tag is not accessible by the program,
688 // so it will only ever be used when using the local directly (i.e.,
689 // not through a pointer). That is, whenever we directly write to a local, this will pop
690 // everything else off the stack, invalidating all previous pointers,
691 // and in particular, *all* raw pointers.
692 MemoryKind::Stack => (extra.base_ptr_tag(id), Permission::Unique),
693 // Everything else is shared by default.
694 _ => (extra.base_ptr_tag(id), Permission::SharedReadWrite),
696 let mut stacks = Stacks::new(size, perm, base_tag);
697 stacks.history.log_creation(
700 alloc_range(Size::ZERO, size),
707 pub fn memory_read<'tcx>(
713 mut current_span: CurrentSpan<'_, '_, 'tcx>,
714 ) -> InterpResult<'tcx> {
716 "read access with tag {:?}: {:?}, size {}",
718 Pointer::new(alloc_id, range.start),
721 let mut state = state.borrow_mut();
722 self.for_each(range, |offset, stack, history, exposed_tags| {
726 (alloc_id, range, offset),
736 pub fn memory_written<'tcx>(
742 mut current_span: CurrentSpan<'_, '_, 'tcx>,
743 ) -> InterpResult<'tcx> {
745 "write access with tag {:?}: {:?}, size {}",
747 Pointer::new(alloc_id, range.start),
750 let mut state = state.borrow_mut();
751 self.for_each(range, |offset, stack, history, exposed_tags| {
755 (alloc_id, range, offset),
765 pub fn memory_deallocated<'tcx>(
771 ) -> InterpResult<'tcx> {
772 trace!("deallocation with tag {:?}: {:?}, size {}", tag, alloc_id, range.size.bytes());
773 let state = state.borrow();
774 self.for_each(range, |offset, stack, history, exposed_tags| {
775 stack.dealloc(tag, (alloc_id, range, offset), &state, history, exposed_tags)
781 /// Retagging/reborrowing. There is some policy in here, such as which permissions
782 /// to grant for which references, and when to add protectors.
783 impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
784 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
785 /// Returns the `AllocId` the reborrow was done in, if some actual borrow stack manipulation
789 place: &MPlaceTy<'tcx, Tag>,
794 ) -> InterpResult<'tcx, Option<AllocId>> {
795 let this = self.eval_context_mut();
796 let current_span = &mut this.machine.current_span();
798 let log_creation = |this: &MiriEvalContext<'mir, 'tcx>,
799 current_span: &mut CurrentSpan<'_, 'mir, 'tcx>,
803 -> InterpResult<'tcx> {
804 let SbTagExtra::Concrete(orig_tag) = orig_tag else {
805 // FIXME: should we log this?
808 let extra = this.get_alloc_extra(alloc_id)?;
809 let mut stacked_borrows = extra
812 .expect("we should have Stacked Borrows data")
814 stacked_borrows.history.log_creation(
817 alloc_range(base_offset, size),
821 stacked_borrows.history.log_protector(orig_tag, new_tag, current_span);
826 if size == Size::ZERO {
828 "reborrow of size 0: {} reference {:?} derived from {:?} (pointee {})",
834 // Don't update any stacks for a zero-sized access; borrow stacks are per-byte and this
835 // touches no bytes so there is no stack to put this tag in.
836 // However, if the pointer for this operation points at a real allocation we still
837 // record where it was created so that we can issue a helpful diagnostic if there is an
838 // attempt to use it for a non-zero-sized access.
839 // Dangling slices are a common case here; it's valid to get their length but with raw
840 // pointer tagging for example all calls to get_unchecked on them are invalid.
841 if let Ok((alloc_id, base_offset, orig_tag)) = this.ptr_try_get_alloc_id(place.ptr) {
842 log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
843 return Ok(Some(alloc_id));
845 // This pointer doesn't come with an AllocId. :shrug:
848 let (alloc_id, base_offset, orig_tag) = this.ptr_get_alloc_id(place.ptr)?;
849 log_creation(this, current_span, alloc_id, base_offset, orig_tag)?;
851 // Ensure we bail out if the pointer goes out-of-bounds (see miri#1050).
852 let (alloc_size, _) =
853 this.get_alloc_size_and_align(alloc_id, AllocCheck::Dereferenceable)?;
854 if base_offset + size > alloc_size {
855 throw_ub!(PointerOutOfBounds {
858 ptr_offset: this.machine_usize_to_isize(base_offset.bytes()),
860 msg: CheckInAllocMsg::InboundsTest
864 let protector = if protect { Some(this.frame().extra.call_id) } else { None };
866 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
871 Pointer::new(alloc_id, base_offset),
875 // Update the stacks.
876 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
877 // There could be existing unique pointers reborrowed from them that should remain valid!
878 let perm = match kind {
879 RefKind::Unique { two_phase: false }
880 if place.layout.ty.is_unpin(this.tcx.at(DUMMY_SP), this.param_env()) =>
882 // Only if the type is unpin do we actually enforce uniqueness
885 RefKind::Unique { .. } => {
886 // Two-phase references and !Unpin references are treated as SharedReadWrite
887 Permission::SharedReadWrite
889 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
890 RefKind::Shared | RefKind::Raw { mutable: false } => {
891 // Shared references and *const are a whole different kind of game, the
892 // permission is not uniform across the entire range!
893 // We need a frozen-sensitive reborrow.
894 // We have to use shared references to alloc/memory_extra here since
895 // `visit_freeze_sensitive` needs to access the global state.
896 let extra = this.get_alloc_extra(alloc_id)?;
897 let mut stacked_borrows = extra
900 .expect("we should have Stacked Borrows data")
902 this.visit_freeze_sensitive(place, size, |mut range, frozen| {
904 range.start += base_offset;
905 // We are only ever `SharedReadOnly` inside the frozen bits.
906 let perm = if frozen {
907 Permission::SharedReadOnly
909 Permission::SharedReadWrite
911 let protector = if frozen {
914 // We do not protect inside UnsafeCell.
915 // This fixes https://github.com/rust-lang/rust/issues/55005.
918 let item = Item { perm, tag: new_tag, protector };
919 let mut global = this.machine.stacked_borrows.as_ref().unwrap().borrow_mut();
920 stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
924 (alloc_id, range, offset),
932 return Ok(Some(alloc_id));
935 // Here we can avoid `borrow()` calls because we have mutable references.
936 // Note that this asserts that the allocation is mutable -- but since we are creating a
937 // mutable pointer, that seems reasonable.
938 let (alloc_extra, machine) = this.get_alloc_extra_mut(alloc_id)?;
939 let mut stacked_borrows = alloc_extra
942 .expect("we should have Stacked Borrows data")
944 let item = Item { perm, tag: new_tag, protector };
945 let range = alloc_range(base_offset, size);
946 let mut global = machine.stacked_borrows.as_ref().unwrap().borrow_mut();
947 let current_span = &mut machine.current_span(); // `get_alloc_extra_mut` invalidated our old `current_span`
948 stacked_borrows.for_each(range, |offset, stack, history, exposed_tags| {
952 (alloc_id, range, offset),
963 /// Retags an indidual pointer, returning the retagged version.
964 /// `mutbl` can be `None` to make this a raw pointer.
967 val: &ImmTy<'tcx, Tag>,
970 ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
971 let this = self.eval_context_mut();
972 // We want a place for where the ptr *points to*, so we get one.
973 let place = this.ref_to_mplace(val)?;
974 let size = this.size_and_align_of_mplace(&place)?.map(|(size, _)| size);
975 // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
976 // bail out -- we cannot reasonably figure out which memory range to reborrow.
977 // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
978 let size = match size {
980 None => return Ok(*val),
983 // Compute new borrow.
984 let new_tag = this.machine.stacked_borrows.as_mut().unwrap().get_mut().new_ptr();
987 let alloc_id = this.reborrow(&place, size, kind, new_tag, protect)?;
990 let new_place = place.map_provenance(|p| {
994 // If `reborrow` could figure out the AllocId of this ptr, hard-code it into the new one.
995 // Even if we started out with a wildcard, this newly retagged pointer is tied to that allocation.
996 Tag::Concrete { alloc_id, sb: new_tag }
999 // Looks like this has to stay a wildcard pointer.
1000 assert!(matches!(prov, Tag::Wildcard));
1007 // Return new pointer.
1008 Ok(ImmTy::from_immediate(new_place.to_ref(this), val.layout))
1012 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
1013 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
1014 fn retag(&mut self, kind: RetagKind, place: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
1015 let this = self.eval_context_mut();
1016 // Determine mutability and whether to add a protector.
1017 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
1018 // making it useless.
1019 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
1021 // References are simple.
1022 ty::Ref(_, _, Mutability::Mut) =>
1024 RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
1025 kind == RetagKind::FnEntry,
1027 ty::Ref(_, _, Mutability::Not) =>
1028 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
1029 // Raw pointers need to be enabled.
1030 ty::RawPtr(tym) if kind == RetagKind::Raw =>
1031 Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
1032 // Boxes do not get a protector: protectors reflect that references outlive the call
1033 // they were passed in to; that's just not the case for boxes.
1034 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
1039 // We only reborrow "bare" references/boxes.
1040 // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
1041 // but might also cost us optimization and analyses. We will have to experiment more with this.
1042 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
1044 let val = this.read_immediate(&this.place_to_op(place)?)?;
1045 let val = this.retag_reference(&val, mutbl, protector)?;
1046 this.write_immediate(*val, place)?;
1052 /// After a stack frame got pushed, retag the return place so that we are sure
1053 /// it does not alias with anything.
1055 /// This is a HACK because there is nothing in MIR that would make the retag
1056 /// explicit. Also see <https://github.com/rust-lang/rust/issues/71117>.
1057 fn retag_return_place(&mut self) -> InterpResult<'tcx> {
1058 let this = self.eval_context_mut();
1059 let return_place = this.frame_mut().return_place;
1060 if return_place.layout.is_zst() {
1061 // There may not be any memory here, nothing to do.
1064 // We need this to be in-memory to use tagged pointers.
1065 let return_place = this.force_allocation(&return_place)?;
1067 // We have to turn the place into a pointer to use the existing code.
1068 // (The pointer type does not matter, so we use a raw pointer.)
1069 let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
1070 let val = ImmTy::from_immediate(return_place.to_ref(this), ptr_layout);
1072 let val = this.retag_reference(
1074 RefKind::Unique { two_phase: false },
1077 // And use reborrowed pointer for return place.
1078 let return_place = this.ref_to_mplace(&val)?;
1079 this.frame_mut().return_place = return_place.into();
1084 /// Mark the given tag as exposed. It was found on a pointer with the given AllocId.
1085 fn expose_tag(&mut self, alloc_id: AllocId, tag: SbTag) {
1086 let this = self.eval_context_mut();
1088 // Function pointers and dead objects don't have an alloc_extra so we ignore them.
1089 // This is okay because accessing them is UB anyway, no need for any Stacked Borrows checks.
1090 // NOT using `get_alloc_extra_mut` since this might be a read-only allocation!
1091 // FIXME: this catches `InterpError`, which we should not usually do.
1092 // We might need a proper fallible API from `memory.rs` to avoid this though.
1093 match this.get_alloc_extra(alloc_id) {
1094 Ok(alloc_extra) => {
1095 trace!("Stacked Borrows tag {tag:?} exposed in {alloc_id}");
1096 alloc_extra.stacked_borrows.as_ref().unwrap().borrow_mut().exposed_tags.insert(tag);
1100 "Not exposing Stacked Borrows tag {tag:?} due to error \
1101 when accessing {alloc_id}: {err}"