1 use std::cell::RefCell;
2 use std::collections::{HashMap, 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, AllocId, CheckInAllocMsg,
14 Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
17 pub type PtrId = NonZeroU64;
18 pub type CallId = NonZeroU64;
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.
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 {
95 /// Next unused pointer ID (tag).
97 /// Table storing the "base" tag for each allocation.
98 /// The base tag is the one used for the initial pointer.
99 /// We need this in a separate table to handle cyclic statics.
100 base_ptr_ids: HashMap<AllocId, Tag>,
101 /// Next unused call ID (for protectors).
102 next_call_id: CallId,
103 /// Those call IDs corresponding to functions that are still running.
104 active_calls: HashSet<CallId>,
106 /// Memory extra state gives us interior mutable access to the global state.
107 pub type MemoryState = Rc<RefCell<GlobalState>>;
109 /// Indicates which kind of access is being performed.
110 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
111 pub enum AccessKind {
116 impl fmt::Display for AccessKind {
117 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119 AccessKind::Read => write!(f, "read access"),
120 AccessKind::Write => write!(f, "write access"),
125 /// Indicates which kind of reference is being created.
126 /// Used by high-level `reborrow` to compute which permissions to grant to the
128 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
130 /// `&mut` and `Box`.
131 Unique { two_phase: bool },
132 /// `&` with or without interior mutability.
134 /// `*mut`/`*const` (raw pointers).
135 Raw { mutable: bool },
138 impl fmt::Display for RefKind {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141 RefKind::Unique { two_phase: false } => write!(f, "unique"),
142 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
143 RefKind::Shared => write!(f, "shared"),
144 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
145 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
150 /// Utilities for initialization and ID generation
151 impl Default for GlobalState {
152 fn default() -> Self {
154 next_ptr_id: NonZeroU64::new(1).unwrap(),
155 base_ptr_ids: HashMap::default(),
156 next_call_id: NonZeroU64::new(1).unwrap(),
157 active_calls: HashSet::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 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);
195 // # Stacked Borrows Core Begin
197 /// We need to make at least the following things true:
199 /// U1: After creating a `Uniq`, it is at the top.
200 /// U2: If the top is `Uniq`, accesses must be through that `Uniq` or remove it it.
201 /// U3: If an access happens with a `Uniq`, it requires the `Uniq` to be in the stack.
203 /// F1: After creating a `&`, the parts outside `UnsafeCell` have our `SharedReadOnly` on top.
204 /// F2: If a write access happens, it pops the `SharedReadOnly`. This has three pieces:
205 /// F2a: If a write happens granted by an item below our `SharedReadOnly`, the `SharedReadOnly`
207 /// F2b: No `SharedReadWrite` or `Unique` will ever be added on top of our `SharedReadOnly`.
208 /// F3: If an access happens with an `&` outside `UnsafeCell`,
209 /// it requires the `SharedReadOnly` to still be in the stack.
211 /// Core relation on `Permission` to define which accesses are allowed
213 /// This defines for a given permission, whether it permits the given kind of access.
214 fn grants(self, access: AccessKind) -> bool {
215 // Disabled grants nothing. Otherwise, all items grant read access, and except for SharedReadOnly they grant write access.
216 self != Permission::Disabled && (access == AccessKind::Read || self != Permission::SharedReadOnly)
220 /// Core per-location operations: access, dealloc, reborrow.
222 /// Find the item granting the given kind of access to the given tag, and return where
223 /// it is on the stack.
224 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
226 .enumerate() // we also need to know *where* in the stack
227 .rev() // search top-to-bottom
228 // Return permission of first item that grants access.
229 // We require a permission with the right tag, ensuring U3 and F3.
230 .find_map(|(idx, item)|
231 if tag == item.tag && item.perm.grants(access) {
239 /// Find the first write-incompatible item above the given one --
240 /// i.e, find the height to which the stack will be truncated when writing to `granting`.
241 fn find_first_write_incompaible(&self, granting: usize) -> usize {
242 let perm = self.borrows[granting].perm;
244 Permission::SharedReadOnly =>
245 bug!("Cannot use SharedReadOnly for writing"),
246 Permission::Disabled =>
247 bug!("Cannot use Disabled for anything"),
248 Permission::Unique =>
249 // On a write, everything above us is incompatible.
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) -> EvalResult<'tcx> {
270 if let Some(call) = item.protector {
271 if global.is_active(call) {
272 if let Some(tag) = tag {
273 return err!(MachineError(format!(
274 "not granting access to tag {:?} because incompatible item is protected: {:?}",
278 return err!(MachineError(format!(
279 "deallocating while item is protected: {:?}", item
287 /// Test if a memory `access` using pointer tagged `tag` is granted.
288 /// If yes, return the index of the item that granted it.
293 global: &GlobalState,
294 ) -> EvalResult<'tcx> {
295 // Two main steps: Find granting item, remove incompatible items above.
297 // Step 1: Find granting item.
298 let granting_idx = self.find_granting(access, tag)
299 .ok_or_else(|| InterpError::MachineError(format!(
300 "no item granting {} to tag {:?} found in borrow stack",
304 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
305 // items. Behavior differs for reads and writes.
306 if access == AccessKind::Write {
307 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
308 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
309 let first_incompatible_idx = self.find_first_write_incompaible(granting_idx);
310 for item in self.borrows.drain(first_incompatible_idx..).rev() {
311 trace!("access: popping item {:?}", item);
312 Stack::check_protector(&item, Some(tag), global)?;
315 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
316 // The reason this is not following the stack discipline (by removing the first Unique and
317 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
318 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
319 // `SharedReadWrite` for `raw`.
320 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
321 // reference and use that.
322 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
323 for idx in (granting_idx+1 .. self.borrows.len()).rev() {
324 let item = &mut self.borrows[idx];
325 if item.perm == Permission::Unique {
326 trace!("access: disabling item {:?}", item);
327 Stack::check_protector(item, Some(tag), global)?;
328 item.perm = Permission::Disabled;
337 /// Deallocate a location: Like a write access, but also there must be no
338 /// active protectors at all because we will remove all items.
342 global: &GlobalState,
343 ) -> EvalResult<'tcx> {
344 // Step 1: Find granting item.
345 self.find_granting(AccessKind::Write, tag)
346 .ok_or_else(|| InterpError::MachineError(format!(
347 "no item granting write access for deallocation to tag {:?} found in borrow stack",
351 // Step 2: Remove all items. Also checks for protectors.
352 for item in self.borrows.drain(..).rev() {
353 Stack::check_protector(&item, None, global)?;
359 /// Derived a new pointer from one with the given tag.
360 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
361 /// an access, and they add the new item directly on top of the one it is derived
362 /// from instead of all the way at the top of the stack.
367 global: &GlobalState,
368 ) -> EvalResult<'tcx> {
369 // Figure out which access `perm` corresponds to.
370 let access = if new.perm.grants(AccessKind::Write) {
375 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
376 // We use that to determine where to put the new item.
377 let granting_idx = self.find_granting(access, derived_from)
378 .ok_or_else(|| InterpError::MachineError(format!(
379 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack", new.perm, derived_from,
382 // Compute where to put the new item.
383 // Either way, we ensure that we insert the new item in a way such that between
384 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
385 let new_idx = if new.perm == Permission::SharedReadWrite {
386 assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
387 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
388 // access. Instead of popping the stack, we insert the item at the place the stack would
389 // be popped to (i.e., we insert it above all the write-compatible items).
390 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
391 self.find_first_write_incompaible(granting_idx)
393 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
394 // Here, creating a reference actually counts as an access.
395 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
396 self.access(access, derived_from, global)?;
398 // We insert "as far up as possible": We know only compatible items are remaining
399 // on top of `derived_from`, and we want the new item at the top so that we
400 // get the strongest possible guarantees.
401 // This ensures U1 and F1.
405 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
406 if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
407 // Optimization applies, done.
408 trace!("reborrow: avoiding adding redundant item {:?}", new);
410 trace!("reborrow: adding item {:?}", new);
411 self.borrows.insert(new_idx, new);
417 // # Stacked Borrows Core End
419 /// Map per-stack operations to higher-level per-location-range operations.
421 /// Creates new stack with initial tag.
428 let item = Item { perm, tag, protector: None };
433 stacks: RefCell::new(RangeMap::new(size, stack)),
438 /// Call `f` on every stack in the range.
443 f: impl Fn(&mut Stack, &GlobalState) -> EvalResult<'tcx>,
444 ) -> EvalResult<'tcx> {
445 let global = self.global.borrow();
446 let mut stacks = self.stacks.borrow_mut();
447 for stack in stacks.iter_mut(ptr.offset, size) {
454 /// Glue code to connect with Miri Machine Hooks
456 pub fn new_allocation(
460 kind: MemoryKind<MiriMemoryKind>,
462 let (tag, perm) = match kind {
464 // New unique borrow. This tag is not accessible by the program,
465 // so it will only ever be used when using the local directly (i.e.,
466 // not through a pointer). That is, whenever we directly write to a local, this will pop
467 // everything else off the stack, invalidating all previous pointers,
468 // and in particular, *all* raw pointers.
469 (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
470 MemoryKind::Machine(MiriMemoryKind::Static) =>
471 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
473 (Tag::Untagged, Permission::SharedReadWrite),
475 let stack = Stacks::new(size, perm, tag, extra);
480 impl AllocationExtra<Tag> for Stacks {
482 fn memory_read<'tcx>(
483 alloc: &Allocation<Tag, Stacks>,
486 ) -> EvalResult<'tcx> {
487 trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
488 alloc.extra.for_each(ptr, size, |stack, global| {
489 stack.access(AccessKind::Read, ptr.tag, global)?;
495 fn memory_written<'tcx>(
496 alloc: &mut Allocation<Tag, Stacks>,
499 ) -> EvalResult<'tcx> {
500 trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
501 alloc.extra.for_each(ptr, size, |stack, global| {
502 stack.access(AccessKind::Write, ptr.tag, global)?;
508 fn memory_deallocated<'tcx>(
509 alloc: &mut Allocation<Tag, Stacks>,
512 ) -> EvalResult<'tcx> {
513 trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
514 alloc.extra.for_each(ptr, size, |stack, global| {
515 stack.dealloc(ptr.tag, global)
520 /// Retagging/reborrowing. There is some policy in here, such as which permissions
521 /// to grant for which references, and when to add protectors.
522 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
523 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
526 place: MPlaceTy<'tcx, Tag>,
531 ) -> EvalResult<'tcx> {
532 let this = self.eval_context_mut();
533 let protector = if protect { Some(this.frame().extra) } else { None };
534 let ptr = place.ptr.to_ptr()?;
535 trace!("reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
536 kind, new_tag, ptr.tag, place.layout.ty, ptr.erase_tag(), size.bytes());
538 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
539 let alloc = this.memory().get(ptr.alloc_id)?;
540 alloc.check_bounds(this, ptr, size, CheckInAllocMsg::InboundsTest)?;
541 // Update the stacks.
542 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
543 // There could be existing unique pointers reborrowed from them that should remain valid!
544 let perm = match kind {
545 RefKind::Unique { two_phase: false } => Permission::Unique,
546 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
547 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
548 RefKind::Shared | RefKind::Raw { mutable: false } => {
549 // Shared references and *const are a whole different kind of game, the
550 // permission is not uniform across the entire range!
551 // We need a frozen-sensitive reborrow.
552 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
553 // We are only ever `SharedReadOnly` inside the frozen bits.
554 let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
555 let item = Item { perm, tag: new_tag, protector };
556 alloc.extra.for_each(cur_ptr, size, |stack, global| {
557 stack.grant(cur_ptr.tag, item, global)
562 let item = Item { perm, tag: new_tag, protector };
563 alloc.extra.for_each(ptr, size, |stack, global| {
564 stack.grant(ptr.tag, item, global)
568 /// Retags an indidual pointer, returning the retagged version.
569 /// `mutbl` can be `None` to make this a raw pointer.
572 val: ImmTy<'tcx, Tag>,
575 ) -> EvalResult<'tcx, Immediate<Tag>> {
576 let this = self.eval_context_mut();
577 // We want a place for where the ptr *points to*, so we get one.
578 let place = this.ref_to_mplace(val)?;
579 let size = this.size_and_align_of_mplace(place)?
580 .map(|(size, _)| size)
581 .unwrap_or_else(|| place.layout.size);
582 if size == Size::ZERO {
583 // Nothing to do for ZSTs.
587 // Compute new borrow.
588 let new_tag = match kind {
589 RefKind::Raw { .. } => Tag::Untagged,
590 _ => Tag::Tagged(this.memory().extra.borrow_mut().new_ptr()),
594 this.reborrow(place, size, kind, new_tag, protect)?;
595 let new_place = place.replace_tag(new_tag);
597 // Return new pointer.
598 Ok(new_place.to_ref())
602 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
603 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
607 place: PlaceTy<'tcx, Tag>
608 ) -> EvalResult<'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(_, _, MutMutable) =>
617 Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
618 ty::Ref(_, _, MutImmutable) =>
619 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
620 // Raw pointers need to be enabled.
621 ty::RawPtr(tym) if kind == RetagKind::Raw =>
622 Some((RefKind::Raw { mutable: tym.mutbl == MutMutable }, false)),
623 // Boxes do not get a protector: protectors reflect that references outlive the call
624 // they were passed in to; that's just not the case for boxes.
625 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
630 // We need a visitor to visit all references. However, that requires
631 // a `MemPlace`, so we have a fast path for reference types that
632 // avoids allocating.
633 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
635 let val = this.read_immediate(this.place_to_op(place)?)?;
636 let val = this.retag_reference(val, mutbl, protector)?;
637 this.write_immediate(val, place)?;
640 let place = this.force_allocation(place)?;
642 let mut visitor = RetagVisitor { ecx: this, kind };
643 visitor.visit_value(place)?;
645 // The actual visitor.
646 struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
647 ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
650 impl<'ecx, 'a, 'mir, 'tcx>
651 MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
653 RetagVisitor<'ecx, 'a, 'mir, 'tcx>
655 type V = MPlaceTy<'tcx, Tag>;
658 fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
662 // Primitives of reference type, that is the one thing we are interested in.
663 fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Tag>) -> EvalResult<'tcx>
665 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
666 // making it useless.
667 if let Some((mutbl, protector)) = qualify(place.layout.ty, self.kind) {
668 let val = self.ecx.read_immediate(place.into())?;
669 let val = self.ecx.retag_reference(
674 self.ecx.write_immediate(val, place.into())?;