1 use std::cell::RefCell;
2 use std::collections::HashSet;
5 use std::num::NonZeroU64;
7 use rustc::ty::{self, layout::Size};
8 use rustc::hir::{MutMutable, MutImmutable};
9 use rustc::mir::RetagKind;
12 EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
13 MemoryKind, MiriMemoryKind, RangeMap, Allocation, AllocationExtra,
14 Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
17 pub type PtrId = NonZeroU64;
18 pub type CallId = NonZeroU64;
20 /// Tracking pointer provenance
21 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
27 impl fmt::Display 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 /// Greants 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, Debug, 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::Display 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.
83 /// Extra per-allocation state.
84 #[derive(Clone, Debug)]
86 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
87 stacks: RefCell<RangeMap<Stack>>,
88 // Pointer to global state
92 /// Extra global state, available to the memory access hooks.
94 pub struct GlobalState {
97 active_calls: HashSet<CallId>,
99 pub type MemoryState = Rc<RefCell<GlobalState>>;
101 /// Indicates which kind of access is being performed.
102 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
103 pub enum AccessKind {
108 impl fmt::Display for AccessKind {
109 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111 AccessKind::Read => write!(f, "read"),
112 AccessKind::Write => write!(f, "write"),
117 /// Indicates which kind of reference is being created.
118 /// Used by high-level `reborrow` to compute which permissions to grant to the
120 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
122 /// `&mut` and `Box`.
123 Unique { two_phase: bool },
124 /// `&` with or without interior mutability.
126 /// `*mut`/`*const` (raw pointers).
127 Raw { mutable: bool },
130 impl fmt::Display for RefKind {
131 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
133 RefKind::Unique { two_phase: false } => write!(f, "unique"),
134 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
135 RefKind::Shared => write!(f, "shared"),
136 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
137 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
142 /// Utilities for initialization and ID generation
143 impl Default for GlobalState {
144 fn default() -> Self {
146 next_ptr_id: NonZeroU64::new(1).unwrap(),
147 next_call_id: NonZeroU64::new(1).unwrap(),
148 active_calls: HashSet::default(),
154 pub fn new_ptr(&mut self) -> PtrId {
155 let id = self.next_ptr_id;
156 self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
160 pub fn new_call(&mut self) -> CallId {
161 let id = self.next_call_id;
162 trace!("new_call: Assigning ID {}", id);
163 self.active_calls.insert(id);
164 self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
168 pub fn end_call(&mut self, id: CallId) {
169 assert!(self.active_calls.remove(&id));
172 fn is_active(&self, id: CallId) -> bool {
173 self.active_calls.contains(&id)
177 // # Stacked Borrows Core Begin
179 /// We need to make at least the following things true:
181 /// U1: After creating a `Uniq`, it is at the top.
182 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
183 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
185 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
186 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
187 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
189 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
190 /// F3: If an access happens with an `&` outside `UnsafeCell`,
191 /// it requires the `SharedReadOnly` to still be in the stack.
193 impl Default for Tag {
195 fn default() -> Tag {
201 /// Core relation on `Permission` to define which accesses are allowed
203 /// This defines for a given permission, whether it permits the given kind of access.
204 fn grants(self, access: AccessKind) -> bool {
205 // Disabled grants nother. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
206 self != Permission::Disabled && (access == AccessKind::Read || self != Permission::SharedReadOnly)
210 /// Core per-location operations: access, dealloc, reborrow.
212 /// Find the item granting the given kind of access to the given tag, and return where
213 /// it is on the stack.
214 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
216 .enumerate() // we also need to know *where* in the stack
217 .rev() // search top-to-bottom
218 // Return permission of first item that grants access.
219 // We require a permission with the right tag, ensuring U3 and F3.
220 .find_map(|(idx, item)|
221 if tag == item.tag && item.perm.grants(access) {
229 /// Find the first write-incompatible item above the given one --
230 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
231 fn find_first_write_incompaible(&self, granting: usize) -> usize {
232 let perm = self.borrows[granting].perm;
234 Permission::SharedReadOnly =>
235 bug!("Cannot use SharedReadOnly for writing"),
236 Permission::Disabled =>
237 bug!("Cannot use Disabled for anything"),
238 Permission::Unique =>
239 // On a write, everything above us is incompatible.
241 Permission::SharedReadWrite => {
242 // The SharedReadWrite *just* above us are compatible, to skip those.
243 let mut idx = granting + 1;
244 while let Some(item) = self.borrows.get(idx) {
245 if item.perm == Permission::SharedReadWrite {
249 // Found first incompatible!
258 /// Check if the given item is protected.
259 fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> EvalResult<'tcx> {
260 if let Some(call) = item.protector {
261 if global.is_active(call) {
262 if let Some(tag) = tag {
263 return err!(MachineError(format!(
264 "not granting access to tag {} because incompatible item is protected: {}",
268 return err!(MachineError(format!(
269 "deallocating while item is protected: {}", item
277 /// Test if a memory `access` using pointer tagged `tag` is granted.
278 /// If yes, return the index of the item that granted it.
283 global: &GlobalState,
284 ) -> EvalResult<'tcx> {
285 // Two main steps: Find granting item, remove incompatible items above.
287 // Step 1: Find granting item.
288 let granting_idx = self.find_granting(access, tag)
289 .ok_or_else(|| InterpError::MachineError(format!(
290 "no item granting {} access to tag {} found in borrow stack",
294 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
295 // items. Behavior differs for reads and writes.
296 if access == AccessKind::Write {
297 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
298 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
299 let first_incompatible_idx = self.find_first_write_incompaible(granting_idx);
300 while self.borrows.len() > first_incompatible_idx {
301 let item = self.borrows.pop().unwrap();
302 trace!("access: popping item {}", item);
303 Stack::check_protector(&item, Some(tag), global)?;
306 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
307 // The reason this is not following the stack discipline (by removing the first Unique and
308 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
309 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
310 // `SharedReadWrite` for `raw`.
311 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
312 // reference and use that.
313 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
314 for idx in (granting_idx+1 .. self.borrows.len()).rev() {
315 let item = &mut self.borrows[idx];
316 if item.perm == Permission::Unique {
317 trace!("access: disabling item {}", item);
318 Stack::check_protector(item, Some(tag), global)?;
319 item.perm = Permission::Disabled;
328 /// Deallocate a location: Like a write access, but also there must be no
329 /// active protectors at all because we will remove all items.
333 global: &GlobalState,
334 ) -> EvalResult<'tcx> {
335 // Step 1: Find granting item.
336 self.find_granting(AccessKind::Write, tag)
337 .ok_or_else(|| InterpError::MachineError(format!(
338 "no item granting write access for deallocation to tag {} found in borrow stack",
342 // Step 2: Remove all items. Also checks for protectors.
343 while self.borrows.len() > 0 {
344 let item = self.borrows.pop().unwrap();
345 Stack::check_protector(&item, None, global)?;
351 /// `reborrow` helper function: test that the stack invariants are still maintained.
352 fn test_invariants(&self) {
353 let mut saw_shared_read_only = false;
354 for item in self.borrows.iter() {
356 Permission::SharedReadOnly => {
357 saw_shared_read_only = true;
359 // Otherwise, if we saw one before, that's a bug.
360 perm if saw_shared_read_only => {
361 bug!("Found {:?} on top of a SharedReadOnly!", perm);
368 /// Derived a new pointer from one with the given tag.
369 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
370 /// an access, and they add the new item directly on top of the one it is derived
371 /// from instead of all the way at the top of the stack.
376 global: &GlobalState,
377 ) -> EvalResult<'tcx> {
378 // Figure out which access `perm` corresponds to.
379 let access = if new.perm.grants(AccessKind::Write) {
384 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
385 // We use that to determine where to put the new item.
386 let granting_idx = self.find_granting(access, derived_from)
387 .ok_or_else(|| InterpError::MachineError(format!(
388 "no item to reborrow for {:?} from tag {} found in borrow stack", new.perm, derived_from,
391 // Compute where to put the new item.
392 // Either way, we ensure that we insert the new item in a way such that between
393 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
394 let new_idx = if new.perm == Permission::SharedReadWrite {
395 assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
396 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
397 // access. Instead of popping the stack, we insert the item at the place the stack would
398 // be popped to (i.e., we insert it above all the write-compatible items).
399 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
400 self.find_first_write_incompaible(granting_idx)
402 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
403 // Here, creating a reference actually counts as an access.
404 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
405 self.access(access, derived_from, global)?;
407 // We insert "as far up as possible": We know only compatible items are remaining
408 // on top of `derived_from`, and we want the new item at the top so that we
409 // get the strongest possible guarantees.
410 // This ensures U1 and F1.
414 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
415 if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
416 // Optimization applies, done.
417 trace!("reborrow: avoiding adding redundant item {}", new);
419 trace!("reborrow: adding item {}", new);
420 self.borrows.insert(new_idx, new);
423 // Make sure that after all this, the stack's invariant is still maintained.
424 if cfg!(debug_assertions) {
425 self.test_invariants();
431 // # Stacked Borrows Core End
433 /// Map per-stack operations to higher-level per-location-range operations.
435 /// Creates new stack with initial tag.
441 let item = Item { perm: Permission::Unique, tag, protector: None };
446 stacks: RefCell::new(RangeMap::new(size, stack)),
451 /// Call `f` on every stack in the range.
456 f: impl Fn(&mut Stack, &GlobalState) -> EvalResult<'tcx>,
457 ) -> EvalResult<'tcx> {
458 let global = self.global.borrow();
459 let mut stacks = self.stacks.borrow_mut();
460 for stack in stacks.iter_mut(ptr.offset, size) {
467 /// Glue code to connect with Miri Machine Hooks
469 pub fn new_allocation(
472 kind: MemoryKind<MiriMemoryKind>,
474 let tag = match kind {
475 MemoryKind::Stack => {
476 // New unique borrow. This `Uniq` is not accessible by the program,
477 // so it will only ever be used when using the local directly (i.e.,
478 // not through a pointer). That is, whenever we directly use a local, this will pop
479 // everything else off the stack, invalidating all previous pointers,
480 // and in particular, *all* raw pointers. This subsumes the explicit
481 // `reset` which the blog post [1] says to perform when accessing a local.
483 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
484 Tag::Tagged(extra.borrow_mut().new_ptr())
490 let stack = Stacks::new(size, tag, Rc::clone(extra));
495 impl AllocationExtra<Tag> for Stacks {
497 fn memory_read<'tcx>(
498 alloc: &Allocation<Tag, Stacks>,
501 ) -> EvalResult<'tcx> {
502 trace!("read access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
503 alloc.extra.for_each(ptr, size, |stack, global| {
504 stack.access(AccessKind::Read, ptr.tag, global)?;
510 fn memory_written<'tcx>(
511 alloc: &mut Allocation<Tag, Stacks>,
514 ) -> EvalResult<'tcx> {
515 trace!("write access with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
516 alloc.extra.for_each(ptr, size, |stack, global| {
517 stack.access(AccessKind::Write, ptr.tag, global)?;
523 fn memory_deallocated<'tcx>(
524 alloc: &mut Allocation<Tag, Stacks>,
527 ) -> EvalResult<'tcx> {
528 trace!("deallocation with tag {}: {:?}, size {}", ptr.tag, ptr, size.bytes());
529 alloc.extra.for_each(ptr, size, |stack, global| {
530 stack.dealloc(ptr.tag, global)
535 /// Retagging/reborrowing. There is some policy in here, such as which permissions
536 /// to grant for which references, and when to add protectors.
537 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
538 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
541 place: MPlaceTy<'tcx, Tag>,
546 ) -> EvalResult<'tcx> {
547 let this = self.eval_context_mut();
548 let protector = if protect { Some(this.frame().extra) } else { None };
549 let ptr = place.ptr.to_ptr()?;
550 trace!("reborrow: {:?} reference {} derived from {} (pointee {}): {:?}, size {}",
551 kind, new_tag, ptr.tag, place.layout.ty, ptr, size.bytes());
553 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
554 let alloc = this.memory().get(ptr.alloc_id)?;
555 alloc.check_bounds(this, ptr, size)?;
556 // Update the stacks.
557 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
558 // There could be existing unique pointers reborrowed from them that should remain valid!
559 let perm = match kind {
560 RefKind::Unique { two_phase: false } => Permission::Unique,
561 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
562 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
563 RefKind::Shared | RefKind::Raw { mutable: false } => {
564 // Shared references and *const are a whole different kind of game, the
565 // permission is not uniform across the entire range!
566 // We need a frozen-sensitive reborrow.
567 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
568 // We are only ever `SharedReadOnly` inside the frozen bits.
569 let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
570 let item = Item { perm, tag: new_tag, protector };
571 alloc.extra.for_each(cur_ptr, size, |stack, global| {
572 stack.grant(cur_ptr.tag, item, global)
577 let item = Item { perm, tag: new_tag, protector };
578 alloc.extra.for_each(ptr, size, |stack, global| {
579 stack.grant(ptr.tag, item, global)
583 /// Retags an indidual pointer, returning the retagged version.
584 /// `mutbl` can be `None` to make this a raw pointer.
587 val: ImmTy<'tcx, Tag>,
590 ) -> EvalResult<'tcx, Immediate<Tag>> {
591 let this = self.eval_context_mut();
592 // We want a place for where the ptr *points to*, so we get one.
593 let place = this.ref_to_mplace(val)?;
594 let size = this.size_and_align_of_mplace(place)?
595 .map(|(size, _)| size)
596 .unwrap_or_else(|| place.layout.size);
597 if size == Size::ZERO {
598 // Nothing to do for ZSTs.
602 // Compute new borrow.
603 let new_tag = match kind {
604 RefKind::Raw { .. } => Tag::Untagged,
605 _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
609 this.reborrow(place, size, kind, new_tag, protect)?;
610 let new_place = place.replace_tag(new_tag);
612 // Return new pointer.
613 Ok(new_place.to_ref())
617 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
618 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
622 place: PlaceTy<'tcx, Tag>
623 ) -> EvalResult<'tcx> {
624 let this = self.eval_context_mut();
625 // Determine mutability and whether to add a protector.
626 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
627 // making it useless.
628 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
630 // References are simple.
631 ty::Ref(_, _, MutMutable) =>
632 Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
633 ty::Ref(_, _, MutImmutable) =>
634 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
635 // Raw pointers need to be enabled.
636 ty::RawPtr(tym) if kind == RetagKind::Raw =>
637 Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
638 // Boxes do not get a protector: protectors reflect that references outlive the call
639 // they were passed in to; that's just not the case for boxes.
640 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
645 // We need a visitor to visit all references. However, that requires
646 // a `MemPlace`, so we have a fast path for reference types that
647 // avoids allocating.
648 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
650 let val = this.read_immediate(this.place_to_op(place)?)?;
651 let val = this.retag_reference(val, mutbl, protector)?;
652 this.write_immediate(val, place)?;
655 let place = this.force_allocation(place)?;
657 let mut visitor = RetagVisitor { ecx: this, kind };
658 visitor.visit_value(place)?;
660 // The actual visitor.
661 struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
662 ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
665 impl<'ecx, 'a, 'mir, 'tcx>
666 MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
668 RetagVisitor<'ecx, 'a, 'mir, 'tcx>
670 type V = MPlaceTy<'tcx, Tag>;
673 fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
677 // Primitives of reference type, that is the one thing we are interested in.
678 fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
680 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
681 // making it useless.
682 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
683 let val = self.ecx.read_immediate(place.into())?;
684 let val = self.ecx.retag_reference(
689 self.ecx.write_immediate(val, place.into())?;