1 //! Implements "Stacked Borrows". See <https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md>
2 //! for further information.
4 use std::cell::RefCell;
6 use std::num::NonZeroU64;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc::mir::RetagKind;
11 use rustc::ty::{self, layout::Size};
12 use rustc_hir::Mutability;
16 pub type PtrId = NonZeroU64;
17 pub type CallId = NonZeroU64;
18 pub type AllocExtra = Stacks;
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
27 impl fmt::Debug for Tag {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30 Tag::Tagged(id) => write!(f, "<{}>", id),
31 Tag::Untagged => write!(f, "<untagged>"),
36 /// Indicates which permission is granted (by this item to some pointers)
37 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
39 /// Grants unique mutable access.
41 /// Grants shared mutable access.
43 /// Grants shared read-only access.
45 /// Grants no access, but separates two groups of SharedReadWrite so they are not
46 /// all considered mutually compatible.
50 /// An item in the per-location borrow stack.
51 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
53 /// The permission this item grants.
55 /// The pointers the permission is granted to.
57 /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
58 protector: Option<CallId>,
61 impl fmt::Debug for Item {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
64 if let Some(call) = self.protector {
65 write!(f, " (call {})", call)?;
72 /// Extra per-location state.
73 #[derive(Clone, Debug, PartialEq, Eq)]
75 /// Used *mostly* as a stack; never empty.
77 /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
78 /// * Except for `Untagged`, no tag occurs in the stack more than once.
82 /// Extra per-allocation state.
83 #[derive(Clone, Debug)]
85 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
86 stacks: RefCell<RangeMap<Stack>>,
87 // Pointer to global state
91 /// Extra global state, available to the memory access hooks.
93 pub struct GlobalState {
94 /// Next unused pointer ID (tag).
96 /// Table storing the "base" tag for each allocation.
97 /// The base tag is the one used for the initial pointer.
98 /// We need this in a separate table to handle cyclic statics.
99 base_ptr_ids: FxHashMap<AllocId, Tag>,
100 /// Next unused call ID (for protectors).
101 next_call_id: CallId,
102 /// Those call IDs corresponding to functions that are still running.
103 active_calls: FxHashSet<CallId>,
104 /// The id to trace in this execution run
105 tracked_pointer_tag: Option<PtrId>,
107 /// Memory extra state gives us interior mutable access to the global state.
108 pub type MemoryExtra = Rc<RefCell<GlobalState>>;
110 /// Indicates which kind of access is being performed.
111 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
112 pub enum AccessKind {
117 impl fmt::Display for AccessKind {
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120 AccessKind::Read => write!(f, "read access"),
121 AccessKind::Write => write!(f, "write access"),
126 /// Indicates which kind of reference is being created.
127 /// Used by high-level `reborrow` to compute which permissions to grant to the
129 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
131 /// `&mut` and `Box`.
132 Unique { two_phase: bool },
133 /// `&` with or without interior mutability.
135 /// `*mut`/`*const` (raw pointers).
136 Raw { mutable: bool },
139 impl fmt::Display for RefKind {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142 RefKind::Unique { two_phase: false } => write!(f, "unique"),
143 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
144 RefKind::Shared => write!(f, "shared"),
145 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
146 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
151 /// Utilities for initialization and ID generation
153 pub fn new(tracked_pointer_tag: Option<PtrId>) -> Self {
155 next_ptr_id: NonZeroU64::new(1).unwrap(),
156 base_ptr_ids: FxHashMap::default(),
157 next_call_id: NonZeroU64::new(1).unwrap(),
158 active_calls: FxHashSet::default(),
163 fn new_ptr(&mut self) -> PtrId {
164 let id = self.next_ptr_id;
165 self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
169 pub fn new_call(&mut self) -> CallId {
170 let id = self.next_call_id;
171 trace!("new_call: Assigning ID {}", id);
172 assert!(self.active_calls.insert(id));
173 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
177 pub fn end_call(&mut self, id: CallId) {
178 assert!(self.active_calls.remove(&id));
181 fn is_active(&self, id: CallId) -> bool {
182 self.active_calls.contains(&id)
185 pub fn static_base_ptr(&mut self, id: AllocId) -> Tag {
186 self.base_ptr_ids.get(&id).copied().unwrap_or_else(|| {
187 let tag = Tag::Tagged(self.new_ptr());
188 trace!("New allocation {:?} has base tag {:?}", id, tag);
189 self.base_ptr_ids.insert(id, tag).unwrap_none();
196 fn err_sb_ub(msg: String) -> InterpError<'static> {
197 // FIXME: use `err_machine_stop!` macro, once that exists.
198 InterpError::MachineStop(Box::new(TerminationInfo::ExperimentalUb {
200 url: format!("https://github.com/rust-lang/unsafe-code-guidelines/blob/master/wip/stacked-borrows.md"),
204 // # Stacked Borrows Core Begin
206 /// We need to make at least the following things true:
208 /// U1: After creating a `Uniq`, it is at the top.
209 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
210 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
212 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
213 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
214 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
216 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
217 /// F3: If an access happens with an `&` outside `UnsafeCell`,
218 /// it requires the `SharedReadOnly` to still be in the stack.
220 /// Core relation on `Permission` to define which accesses are allowed
222 /// This defines for a given permission, whether it permits the given kind of access.
223 fn grants(self, access: AccessKind) -> bool {
224 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
225 self != Permission::Disabled
226 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
230 /// Core per-location operations: access, dealloc, reborrow.
232 /// Find the item granting the given kind of access to the given tag, and return where
233 /// it is on the stack.
234 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
237 .enumerate() // we also need to know *where* in the stack
238 .rev() // search top-to-bottom
239 // Return permission of first item that grants access.
240 // We require a permission with the right tag, ensuring U3 and F3.
243 if tag == item.tag && item.perm.grants(access) { Some(idx) } else { None }
248 /// Find the first write-incompatible item above the given one --
249 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
250 fn find_first_write_incompatible(&self, granting: usize) -> usize {
251 let perm = self.borrows[granting].perm;
253 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
254 Permission::Disabled => bug!("Cannot use Disabled for anything"),
255 // On a write, everything above us is incompatible.
256 Permission::Unique => granting + 1,
257 Permission::SharedReadWrite => {
258 // The SharedReadWrite *just* above us are compatible, to skip those.
259 let mut idx = granting + 1;
260 while let Some(item) = self.borrows.get(idx) {
261 if item.perm == Permission::SharedReadWrite {
265 // Found first incompatible!
274 /// Check if the given item is protected.
275 fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
276 if let Tag::Tagged(id) = item.tag {
277 if Some(id) == global.tracked_pointer_tag {
278 register_diagnostic(NonHaltingDiagnostic::PoppedTrackedPointerTag(item.clone()));
281 if let Some(call) = item.protector {
282 if global.is_active(call) {
283 if let Some(tag) = tag {
284 Err(err_sb_ub(format!(
285 "not granting access to tag {:?} because incompatible item is protected: {:?}",
289 Err(err_sb_ub(format!(
290 "deallocating while item is protected: {:?}",
299 /// Test if a memory `access` using pointer tagged `tag` is granted.
300 /// If yes, return the index of the item that granted it.
301 fn access(&mut self, access: AccessKind, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
302 // Two main steps: Find granting item, remove incompatible items above.
304 // Step 1: Find granting item.
305 let granting_idx = self.find_granting(access, tag).ok_or_else(|| {
307 "no item granting {} to tag {:?} found in borrow stack.",
312 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
313 // items. Behavior differs for reads and writes.
314 if access == AccessKind::Write {
315 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
316 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
317 let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
318 for item in self.borrows.drain(first_incompatible_idx..).rev() {
319 trace!("access: popping item {:?}", item);
320 Stack::check_protector(&item, Some(tag), global)?;
323 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
324 // The reason this is not following the stack discipline (by removing the first Unique and
325 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
326 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
327 // `SharedReadWrite` for `raw`.
328 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
329 // reference and use that.
330 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
331 for idx in ((granting_idx + 1)..self.borrows.len()).rev() {
332 let item = &mut self.borrows[idx];
333 if item.perm == Permission::Unique {
334 trace!("access: disabling item {:?}", item);
335 Stack::check_protector(item, Some(tag), global)?;
336 item.perm = Permission::Disabled;
345 /// Deallocate a location: Like a write access, but also there must be no
346 /// active protectors at all because we will remove all items.
347 fn dealloc(&mut self, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
348 // Step 1: Find granting item.
349 self.find_granting(AccessKind::Write, tag).ok_or_else(|| {
351 "no item granting write access for deallocation to tag {:?} found in borrow stack",
356 // Step 2: Remove all items. Also checks for protectors.
357 for item in self.borrows.drain(..).rev() {
358 Stack::check_protector(&item, None, global)?;
364 /// Derived a new pointer from one with the given tag.
365 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
366 /// an access, and they add the new item directly on top of the one it is derived
367 /// from instead of all the way at the top of the stack.
368 fn grant(&mut self, derived_from: Tag, new: Item, global: &GlobalState) -> InterpResult<'tcx> {
369 // Figure out which access `perm` corresponds to.
371 if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
372 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
373 // We use that to determine where to put the new item.
374 let granting_idx = self.find_granting(access, derived_from)
375 .ok_or_else(|| err_sb_ub(format!(
376 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack",
377 new.perm, derived_from,
380 // Compute where to put the new item.
381 // Either way, we ensure that we insert the new item in a way such that between
382 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
383 let new_idx = if new.perm == Permission::SharedReadWrite {
385 access == AccessKind::Write,
386 "this case only makes sense for stack-like accesses"
388 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
389 // access. Instead of popping the stack, we insert the item at the place the stack would
390 // be popped to (i.e., we insert it above all the write-compatible items).
391 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
392 self.find_first_write_incompatible(granting_idx)
394 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
395 // Here, creating a reference actually counts as an access.
396 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
397 self.access(access, derived_from, global)?;
399 // We insert "as far up as possible": We know only compatible items are remaining
400 // on top of `derived_from`, and we want the new item at the top so that we
401 // get the strongest possible guarantees.
402 // This ensures U1 and F1.
406 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
407 if self.borrows[new_idx - 1] == new || self.borrows.get(new_idx) == Some(&new) {
408 // Optimization applies, done.
409 trace!("reborrow: avoiding adding redundant item {:?}", new);
411 trace!("reborrow: adding item {:?}", new);
412 self.borrows.insert(new_idx, new);
418 // # Stacked Borrows Core End
420 /// Map per-stack operations to higher-level per-location-range operations.
422 /// Creates new stack with initial tag.
423 fn new(size: Size, perm: Permission, tag: Tag, extra: MemoryExtra) -> Self {
424 let item = Item { perm, tag, protector: None };
425 let stack = Stack { borrows: vec![item] };
427 Stacks { stacks: RefCell::new(RangeMap::new(size, stack)), global: extra }
430 /// Call `f` on every stack in the range.
435 f: impl Fn(&mut Stack, &GlobalState) -> InterpResult<'tcx>,
436 ) -> InterpResult<'tcx> {
437 let global = self.global.borrow();
438 let mut stacks = self.stacks.borrow_mut();
439 for stack in stacks.iter_mut(ptr.offset, size) {
446 /// Glue code to connect with Miri Machine Hooks
448 pub fn new_allocation(
452 kind: MemoryKind<MiriMemoryKind>,
454 let (tag, perm) = match kind {
455 // New unique borrow. This tag is not accessible by the program,
456 // so it will only ever be used when using the local directly (i.e.,
457 // not through a pointer). That is, whenever we directly write to a local, this will pop
458 // everything else off the stack, invalidating all previous pointers,
459 // and in particular, *all* raw pointers.
460 MemoryKind::Stack => (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
461 // Static memory can be referenced by "global" pointers from `tcx`.
462 // Thus we call `static_base_ptr` such that the global pointers get the same tag
463 // as what we use here.
464 // The base pointer is not unique, so the base permission is `SharedReadWrite`.
465 MemoryKind::Machine(MiriMemoryKind::Static) | MemoryKind::Machine(MiriMemoryKind::Machine) =>
466 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
467 // Everything else we handle entirely untagged for now.
468 // FIXME: experiment with more precise tracking.
469 _ => (Tag::Untagged, Permission::SharedReadWrite),
471 (Stacks::new(size, perm, tag, extra), tag)
475 pub fn memory_read<'tcx>(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
476 trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
477 self.for_each(ptr, size, |stack, global| {
478 stack.access(AccessKind::Read, ptr.tag, global)?;
484 pub fn memory_written<'tcx>(&mut self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
485 trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
486 self.for_each(ptr, size, |stack, global| {
487 stack.access(AccessKind::Write, ptr.tag, global)?;
493 pub fn memory_deallocated<'tcx>(
497 ) -> InterpResult<'tcx> {
498 trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
499 self.for_each(ptr, size, |stack, global| stack.dealloc(ptr.tag, global))
503 /// Retagging/reborrowing. There is some policy in here, such as which permissions
504 /// to grant for which references, and when to add protectors.
505 impl<'mir, 'tcx> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
506 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
509 place: MPlaceTy<'tcx, Tag>,
514 ) -> InterpResult<'tcx> {
515 let this = self.eval_context_mut();
516 let protector = if protect { Some(this.frame().extra.call_id) } else { None };
517 let ptr = place.ptr.assert_ptr();
519 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
528 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
529 let extra = &this.memory.get_raw(ptr.alloc_id)?.extra;
530 let stacked_borrows =
531 extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
532 // Update the stacks.
533 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
534 // There could be existing unique pointers reborrowed from them that should remain valid!
535 let perm = match kind {
536 RefKind::Unique { two_phase: false } => Permission::Unique,
537 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
538 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
539 RefKind::Shared | RefKind::Raw { mutable: false } => {
540 // Shared references and *const are a whole different kind of game, the
541 // permission is not uniform across the entire range!
542 // We need a frozen-sensitive reborrow.
543 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
544 // We are only ever `SharedReadOnly` inside the frozen bits.
545 let perm = if frozen {
546 Permission::SharedReadOnly
548 Permission::SharedReadWrite
550 let item = Item { perm, tag: new_tag, protector };
551 stacked_borrows.for_each(cur_ptr, size, |stack, global| {
552 stack.grant(cur_ptr.tag, item, global)
557 let item = Item { perm, tag: new_tag, protector };
558 stacked_borrows.for_each(ptr, size, |stack, global| stack.grant(ptr.tag, item, global))
561 /// Retags an indidual pointer, returning the retagged version.
562 /// `mutbl` can be `None` to make this a raw pointer.
565 val: ImmTy<'tcx, Tag>,
568 ) -> InterpResult<'tcx, Immediate<Tag>> {
569 let this = self.eval_context_mut();
570 // We want a place for where the ptr *points to*, so we get one.
571 let place = this.ref_to_mplace(val)?;
573 .size_and_align_of_mplace(place)?
574 .map(|(size, _)| size)
575 .unwrap_or_else(|| place.layout.size);
576 // We can see dangling ptrs in here e.g. after a Box's `Unique` was
577 // updated using "self.0 = ..." (can happen in Box::from_raw); see miri#1050.
578 let place = this.mplace_access_checked(place)?;
579 if size == Size::ZERO {
580 // Nothing to do for ZSTs.
584 // Compute new borrow.
585 let new_tag = match kind {
586 // Give up tracking for raw pointers.
587 // FIXME: Experiment with more precise tracking. Blocked on `&raw`
588 // because `Rc::into_raw` currently creates intermediate references,
589 // breaking `Rc::from_raw`.
590 RefKind::Raw { .. } => Tag::Untagged,
591 // All other pointesr are properly tracked.
593 this.memory.extra.stacked_borrows.as_ref().unwrap().borrow_mut().new_ptr(),
598 this.reborrow(place, size, kind, new_tag, protect)?;
599 let new_place = place.replace_tag(new_tag);
601 // Return new pointer.
602 Ok(new_place.to_ref())
606 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
607 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
608 fn retag(&mut self, kind: RetagKind, place: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
609 let this = self.eval_context_mut();
610 // Determine mutability and whether to add a protector.
611 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
612 // making it useless.
613 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
615 // References are simple.
616 ty::Ref(_, _, Mutability::Mut) => Some((
617 RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
618 kind == RetagKind::FnEntry,
620 ty::Ref(_, _, Mutability::Not) =>
621 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
622 // Raw pointers need to be enabled.
623 ty::RawPtr(tym) if kind == RetagKind::Raw =>
624 Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
625 // Boxes do not get a protector: protectors reflect that references outlive the call
626 // they were passed in to; that's just not the case for boxes.
627 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
632 // We only reborrow "bare" references/boxes.
633 // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
634 // but might also cost us optimization and analyses. We will have to experiment more with this.
635 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
637 let val = this.read_immediate(this.place_to_op(place)?)?;
638 let val = this.retag_reference(val, mutbl, protector)?;
639 this.write_immediate(val, place)?;