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;
5 use std::collections::{HashMap, HashSet};
7 use std::num::NonZeroU64;
10 use rustc_hir::Mutability;
11 use rustc::mir::RetagKind;
12 use rustc::ty::{self, layout::Size};
15 AllocId, HelpersEvalContextExt, ImmTy, Immediate, InterpResult, MPlaceTy, MemoryKind,
16 MiriMemoryKind, PlaceTy, Pointer, RangeMap, TerminationInfo,
19 pub type PtrId = NonZeroU64;
20 pub type CallId = NonZeroU64;
21 pub type AllocExtra = Stacks;
23 /// Tracking pointer provenance
24 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
30 impl fmt::Debug for Tag {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 Tag::Tagged(id) => write!(f, "<{}>", id),
34 Tag::Untagged => write!(f, "<untagged>"),
39 /// Indicates which permission is granted (by this item to some pointers)
40 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
42 /// Grants unique mutable access.
44 /// Grants shared mutable access.
46 /// Grants shared read-only access.
48 /// Grants no access, but separates two groups of SharedReadWrite so they are not
49 /// all considered mutually compatible.
53 /// An item in the per-location borrow stack.
54 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
56 /// The permission this item grants.
58 /// The pointers the permission is granted to.
60 /// An optional protector, ensuring the item cannot get popped until `CallId` is over.
61 protector: Option<CallId>,
64 impl fmt::Debug for Item {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 write!(f, "[{:?} for {:?}", self.perm, self.tag)?;
67 if let Some(call) = self.protector {
68 write!(f, " (call {})", call)?;
75 /// Extra per-location state.
76 #[derive(Clone, Debug, PartialEq, Eq)]
78 /// Used *mostly* as a stack; never empty.
80 /// * Above a `SharedReadOnly` there can only be more `SharedReadOnly`.
81 /// * Except for `Untagged`, no tag occurs in the stack more than once.
85 /// Extra per-allocation state.
86 #[derive(Clone, Debug)]
88 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
89 stacks: RefCell<RangeMap<Stack>>,
90 // Pointer to global state
94 /// Extra global state, available to the memory access hooks.
96 pub struct GlobalState {
97 /// Next unused pointer ID (tag).
99 /// Table storing the "base" tag for each allocation.
100 /// The base tag is the one used for the initial pointer.
101 /// We need this in a separate table to handle cyclic statics.
102 base_ptr_ids: HashMap<AllocId, Tag>,
103 /// Next unused call ID (for protectors).
104 next_call_id: CallId,
105 /// Those call IDs corresponding to functions that are still running.
106 active_calls: HashSet<CallId>,
107 /// The id to trace in this execution run
108 tracked_pointer_tag: Option<PtrId>,
110 /// Memory extra state gives us interior mutable access to the global state.
111 pub type MemoryExtra = Rc<RefCell<GlobalState>>;
113 /// Indicates which kind of access is being performed.
114 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
115 pub enum AccessKind {
120 impl fmt::Display for AccessKind {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123 AccessKind::Read => write!(f, "read access"),
124 AccessKind::Write => write!(f, "write access"),
129 /// Indicates which kind of reference is being created.
130 /// Used by high-level `reborrow` to compute which permissions to grant to the
132 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
134 /// `&mut` and `Box`.
135 Unique { two_phase: bool },
136 /// `&` with or without interior mutability.
138 /// `*mut`/`*const` (raw pointers).
139 Raw { mutable: bool },
142 impl fmt::Display for RefKind {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
145 RefKind::Unique { two_phase: false } => write!(f, "unique"),
146 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
147 RefKind::Shared => write!(f, "shared"),
148 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
149 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
154 /// Utilities for initialization and ID generation
156 pub fn new(tracked_pointer_tag: Option<PtrId>) -> Self {
158 next_ptr_id: NonZeroU64::new(1).unwrap(),
159 base_ptr_ids: HashMap::default(),
160 next_call_id: NonZeroU64::new(1).unwrap(),
161 active_calls: HashSet::default(),
166 fn new_ptr(&mut self) -> PtrId {
167 let id = self.next_ptr_id;
168 self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
172 pub fn new_call(&mut self) -> CallId {
173 let id = self.next_call_id;
174 trace!("new_call: Assigning ID {}", id);
175 assert!(self.active_calls.insert(id));
176 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
180 pub fn end_call(&mut self, id: CallId) {
181 assert!(self.active_calls.remove(&id));
184 fn is_active(&self, id: CallId) -> bool {
185 self.active_calls.contains(&id)
188 pub fn static_base_ptr(&mut self, id: AllocId) -> Tag {
189 self.base_ptr_ids.get(&id).copied().unwrap_or_else(|| {
190 let tag = Tag::Tagged(self.new_ptr());
191 trace!("New allocation {:?} has base tag {:?}", id, tag);
192 self.base_ptr_ids.insert(id, tag).unwrap_none();
198 // # Stacked Borrows Core Begin
200 /// We need to make at least the following things true:
202 /// U1: After creating a `Uniq`, it is at the top.
203 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
204 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
206 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
207 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
208 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
210 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
211 /// F3: If an access happens with an `&` outside `UnsafeCell`,
212 /// it requires the `SharedReadOnly` to still be in the stack.
214 /// Core relation on `Permission` to define which accesses are allowed
216 /// This defines for a given permission, whether it permits the given kind of access.
217 fn grants(self, access: AccessKind) -> bool {
218 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
219 self != Permission::Disabled
220 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
224 /// Core per-location operations: access, dealloc, reborrow.
226 /// Find the item granting the given kind of access to the given tag, and return where
227 /// it is on the stack.
228 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
231 .enumerate() // we also need to know *where* in the stack
232 .rev() // search top-to-bottom
233 // Return permission of first item that grants access.
234 // We require a permission with the right tag, ensuring U3 and F3.
237 if tag == item.tag && item.perm.grants(access) { Some(idx) } else { None }
242 /// Find the first write-incompatible item above the given one --
243 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
244 fn find_first_write_incompatible(&self, granting: usize) -> usize {
245 let perm = self.borrows[granting].perm;
247 Permission::SharedReadOnly => bug!("Cannot use SharedReadOnly for writing"),
248 Permission::Disabled => bug!("Cannot use Disabled for anything"),
249 // On a write, everything above us is incompatible.
250 Permission::Unique => granting + 1,
251 Permission::SharedReadWrite => {
252 // The SharedReadWrite *just* above us are compatible, to skip those.
253 let mut idx = granting + 1;
254 while let Some(item) = self.borrows.get(idx) {
255 if item.perm == Permission::SharedReadWrite {
259 // Found first incompatible!
268 /// Check if the given item is protected.
269 fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
270 if let Tag::Tagged(id) = item.tag {
271 if Some(id) == global.tracked_pointer_tag {
272 throw_machine_stop!(TerminationInfo::PoppedTrackedPointerTag(item.clone()));
275 if let Some(call) = item.protector {
276 if global.is_active(call) {
277 if let Some(tag) = tag {
278 throw_ub!(UbExperimental(format!(
279 "not granting access to tag {:?} because incompatible item is protected: {:?}",
283 throw_ub!(UbExperimental(format!(
284 "deallocating while item is protected: {:?}",
293 /// Test if a memory `access` using pointer tagged `tag` is granted.
294 /// If yes, return the index of the item that granted it.
295 fn access(&mut self, access: AccessKind, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
296 // Two main steps: Find granting item, remove incompatible items above.
298 // Step 1: Find granting item.
299 let granting_idx = self.find_granting(access, tag).ok_or_else(|| {
300 err_ub!(UbExperimental(format!(
301 "no item granting {} to tag {:?} found in borrow stack",
306 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
307 // items. Behavior differs for reads and writes.
308 if access == AccessKind::Write {
309 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
310 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
311 let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
312 for item in self.borrows.drain(first_incompatible_idx..).rev() {
313 trace!("access: popping item {:?}", item);
314 Stack::check_protector(&item, Some(tag), global)?;
317 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
318 // The reason this is not following the stack discipline (by removing the first Unique and
319 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
320 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
321 // `SharedReadWrite` for `raw`.
322 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
323 // reference and use that.
324 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
325 for idx in ((granting_idx + 1)..self.borrows.len()).rev() {
326 let item = &mut self.borrows[idx];
327 if item.perm == Permission::Unique {
328 trace!("access: disabling item {:?}", item);
329 Stack::check_protector(item, Some(tag), global)?;
330 item.perm = Permission::Disabled;
339 /// Deallocate a location: Like a write access, but also there must be no
340 /// active protectors at all because we will remove all items.
341 fn dealloc(&mut self, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
342 // Step 1: Find granting item.
343 self.find_granting(AccessKind::Write, tag).ok_or_else(|| {
344 err_ub!(UbExperimental(format!(
345 "no item granting write access for deallocation to tag {:?} found in borrow stack",
350 // Step 2: Remove all items. Also checks for protectors.
351 for item in self.borrows.drain(..).rev() {
352 Stack::check_protector(&item, None, global)?;
358 /// Derived a new pointer from one with the given tag.
359 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
360 /// an access, and they add the new item directly on top of the one it is derived
361 /// from instead of all the way at the top of the stack.
362 fn grant(&mut self, derived_from: Tag, new: Item, global: &GlobalState) -> InterpResult<'tcx> {
363 // Figure out which access `perm` corresponds to.
365 if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
366 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
367 // We use that to determine where to put the new item.
368 let granting_idx = self.find_granting(access, derived_from)
369 .ok_or_else(|| err_ub!(UbExperimental(format!(
370 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack", new.perm, derived_from,
373 // Compute where to put the new item.
374 // Either way, we ensure that we insert the new item in a way such that between
375 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
376 let new_idx = if new.perm == Permission::SharedReadWrite {
378 access == AccessKind::Write,
379 "this case only makes sense for stack-like accesses"
381 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
382 // access. Instead of popping the stack, we insert the item at the place the stack would
383 // be popped to (i.e., we insert it above all the write-compatible items).
384 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
385 self.find_first_write_incompatible(granting_idx)
387 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
388 // Here, creating a reference actually counts as an access.
389 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
390 self.access(access, derived_from, global)?;
392 // We insert "as far up as possible": We know only compatible items are remaining
393 // on top of `derived_from`, and we want the new item at the top so that we
394 // get the strongest possible guarantees.
395 // This ensures U1 and F1.
399 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
400 if self.borrows[new_idx - 1] == new || self.borrows.get(new_idx) == Some(&new) {
401 // Optimization applies, done.
402 trace!("reborrow: avoiding adding redundant item {:?}", new);
404 trace!("reborrow: adding item {:?}", new);
405 self.borrows.insert(new_idx, new);
411 // # Stacked Borrows Core End
413 /// Map per-stack operations to higher-level per-location-range operations.
415 /// Creates new stack with initial tag.
416 fn new(size: Size, perm: Permission, tag: Tag, extra: MemoryExtra) -> Self {
417 let item = Item { perm, tag, protector: None };
418 let stack = Stack { borrows: vec![item] };
420 Stacks { stacks: RefCell::new(RangeMap::new(size, stack)), global: extra }
423 /// Call `f` on every stack in the range.
428 f: impl Fn(&mut Stack, &GlobalState) -> InterpResult<'tcx>,
429 ) -> InterpResult<'tcx> {
430 let global = self.global.borrow();
431 let mut stacks = self.stacks.borrow_mut();
432 for stack in stacks.iter_mut(ptr.offset, size) {
439 /// Glue code to connect with Miri Machine Hooks
441 pub fn new_allocation(
445 kind: MemoryKind<MiriMemoryKind>,
447 let (tag, perm) = match kind {
448 // New unique borrow. This tag is not accessible by the program,
449 // so it will only ever be used when using the local directly (i.e.,
450 // not through a pointer). That is, whenever we directly write to a local, this will pop
451 // everything else off the stack, invalidating all previous pointers,
452 // and in particular, *all* raw pointers.
453 MemoryKind::Stack => (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
454 // Static memory can be referenced by "global" pointers from `tcx`.
455 // Thus we call `static_base_ptr` such that the global pointers get the same tag
456 // as what we use here.
457 // The base pointer is not unique, so the base permission is `SharedReadWrite`.
458 MemoryKind::Machine(MiriMemoryKind::Static) =>
459 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
460 // Everything else we handle entirely untagged for now.
461 // FIXME: experiment with more precise tracking.
462 _ => (Tag::Untagged, Permission::SharedReadWrite),
464 (Stacks::new(size, perm, tag, extra), tag)
468 pub fn memory_read<'tcx>(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
469 trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
470 self.for_each(ptr, size, |stack, global| {
471 stack.access(AccessKind::Read, ptr.tag, global)?;
477 pub fn memory_written<'tcx>(&mut self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
478 trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
479 self.for_each(ptr, size, |stack, global| {
480 stack.access(AccessKind::Write, ptr.tag, global)?;
486 pub fn memory_deallocated<'tcx>(
490 ) -> InterpResult<'tcx> {
491 trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
492 self.for_each(ptr, size, |stack, global| stack.dealloc(ptr.tag, global))
496 /// Retagging/reborrowing. There is some policy in here, such as which permissions
497 /// to grant for which references, and when to add protectors.
498 impl<'mir, 'tcx> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
499 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
502 place: MPlaceTy<'tcx, Tag>,
507 ) -> InterpResult<'tcx> {
508 let this = self.eval_context_mut();
509 let protector = if protect { Some(this.frame().extra.call_id) } else { None };
510 let ptr = place.ptr.assert_ptr();
512 "reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
521 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
522 let extra = &this.memory.get_raw(ptr.alloc_id)?.extra;
523 let stacked_borrows =
524 extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
525 // Update the stacks.
526 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
527 // There could be existing unique pointers reborrowed from them that should remain valid!
528 let perm = match kind {
529 RefKind::Unique { two_phase: false } => Permission::Unique,
530 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
531 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
532 RefKind::Shared | RefKind::Raw { mutable: false } => {
533 // Shared references and *const are a whole different kind of game, the
534 // permission is not uniform across the entire range!
535 // We need a frozen-sensitive reborrow.
536 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
537 // We are only ever `SharedReadOnly` inside the frozen bits.
538 let perm = if frozen {
539 Permission::SharedReadOnly
541 Permission::SharedReadWrite
543 let item = Item { perm, tag: new_tag, protector };
544 stacked_borrows.for_each(cur_ptr, size, |stack, global| {
545 stack.grant(cur_ptr.tag, item, global)
550 let item = Item { perm, tag: new_tag, protector };
551 stacked_borrows.for_each(ptr, size, |stack, global| stack.grant(ptr.tag, item, global))
554 /// Retags an indidual pointer, returning the retagged version.
555 /// `mutbl` can be `None` to make this a raw pointer.
558 val: ImmTy<'tcx, Tag>,
561 ) -> InterpResult<'tcx, Immediate<Tag>> {
562 let this = self.eval_context_mut();
563 // We want a place for where the ptr *points to*, so we get one.
564 let place = this.ref_to_mplace(val)?;
566 .size_and_align_of_mplace(place)?
567 .map(|(size, _)| size)
568 .unwrap_or_else(|| place.layout.size);
569 // We can see dangling ptrs in here e.g. after a Box's `Unique` was
570 // updated using "self.0 = ..." (can happen in Box::from_raw); see miri#1050.
571 let place = this.mplace_access_checked(place)?;
572 if size == Size::ZERO {
573 // Nothing to do for ZSTs.
577 // Compute new borrow.
578 let new_tag = match kind {
579 // Give up tracking for raw pointers.
580 // FIXME: Experiment with more precise tracking. Blocked on `&raw`
581 // because `Rc::into_raw` currently creates intermediate references,
582 // breaking `Rc::from_raw`.
583 RefKind::Raw { .. } => Tag::Untagged,
584 // All other pointesr are properly tracked.
585 _ => Tag::Tagged(this.memory.extra.stacked_borrows.borrow_mut().new_ptr()),
589 this.reborrow(place, size, kind, new_tag, protect)?;
590 let new_place = place.replace_tag(new_tag);
592 // Return new pointer.
593 Ok(new_place.to_ref())
597 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
598 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
599 fn retag(&mut self, kind: RetagKind, place: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
600 let this = self.eval_context_mut();
601 // Determine mutability and whether to add a protector.
602 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
603 // making it useless.
604 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
606 // References are simple.
607 ty::Ref(_, _, Mutability::Mut) => Some((
608 RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
609 kind == RetagKind::FnEntry,
611 ty::Ref(_, _, Mutability::Not) =>
612 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
613 // Raw pointers need to be enabled.
614 ty::RawPtr(tym) if kind == RetagKind::Raw =>
615 Some((RefKind::Raw { mutable: tym.mutbl == Mutability::Mut }, false)),
616 // Boxes do not get a protector: protectors reflect that references outlive the call
617 // they were passed in to; that's just not the case for boxes.
618 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
623 // We only reborrow "bare" references/boxes.
624 // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
625 // but might also cost us optimization and analyses. We will have to experiment more with this.
626 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
628 let val = this.read_immediate(this.place_to_op(place)?)?;
629 let val = this.retag_reference(val, mutbl, protector)?;
630 this.write_immediate(val, place)?;