1 use std::cell::RefCell;
2 use std::collections::HashSet;
5 use rustc::ty::{self, layout::Size};
6 use rustc::hir::{Mutability, MutMutable, MutImmutable};
7 use rustc::mir::RetagKind;
10 EvalResult, InterpError, MiriEvalContext, HelpersEvalContextExt, Evaluator, MutValueVisitor,
11 MemoryKind, MiriMemoryKind, RangeMap, AllocId, Allocation, AllocationExtra,
12 Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
15 pub type Timestamp = u64;
16 pub type CallId = u64;
18 /// Information about which kind of borrow was used to create the reference this is tagged with.
19 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
21 /// A unique (mutable) reference.
23 /// An aliasing reference. This is also used by raw pointers, which do not track details
24 /// of how or when they were created, hence the timestamp is optional.
25 /// `Shr(Some(_))` does *not* mean that the destination of this reference is frozen;
26 /// that depends on the type! Only those parts outside of an `UnsafeCell` are actually
28 Alias(Option<Timestamp>),
33 pub fn is_aliasing(self) -> bool {
35 Borrow::Alias(_) => true,
41 pub fn is_unique(self) -> bool {
43 Borrow::Uniq(_) => true,
49 impl Default for Borrow {
50 fn default() -> Self {
55 /// An item in the per-location borrow stack.
56 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
57 pub enum BorStackItem {
58 /// Indicates the unique reference that may mutate.
60 /// Indicates that the location has been mutably shared. Used for raw pointers as
61 /// well as for unfrozen shared references.
63 /// A barrier, tracking the function it belongs to by its index on the call stack.
67 /// Extra per-location state.
68 #[derive(Clone, Debug, PartialEq, Eq)]
70 /// Used as the stack; never empty.
71 borrows: Vec<BorStackItem>,
72 /// A virtual frozen "item" on top of the stack.
73 frozen_since: Option<Timestamp>,
78 pub fn is_frozen(&self) -> bool {
79 self.frozen_since.is_some()
83 /// Indicates which kind of reference is being used.
84 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
88 /// `&` without interior mutability.
90 /// `*` (raw pointer) or `&` to `UnsafeCell`.
94 /// Indicates which kind of access is being performed.
95 #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
102 /// Extra global state in the memory, available to the memory access hooks.
104 pub struct BarrierTracking {
106 active_calls: HashSet<CallId>,
108 pub type MemoryState = Rc<RefCell<BarrierTracking>>;
110 impl Default for BarrierTracking {
111 fn default() -> Self {
114 active_calls: HashSet::default(),
119 impl BarrierTracking {
120 pub fn new_call(&mut self) -> CallId {
121 let id = self.next_id;
122 trace!("new_call: Assigning ID {}", id);
123 self.active_calls.insert(id);
128 pub fn end_call(&mut self, id: CallId) {
129 assert!(self.active_calls.remove(&id));
132 fn is_active(&self, id: CallId) -> bool {
133 self.active_calls.contains(&id)
137 /// Extra global machine state.
138 #[derive(Clone, Debug)]
143 impl Default for State {
144 fn default() -> Self {
150 fn increment_clock(&mut self) -> Timestamp {
151 let val = self.clock;
152 self.clock = val + 1;
157 /// Extra per-allocation state.
158 #[derive(Clone, Debug)]
160 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
161 stacks: RefCell<RangeMap<Stack>>,
162 barrier_tracking: MemoryState,
165 /// Core per-location operations: deref, access, create.
166 /// We need to make at least the following things true:
168 /// U1: After creating a `Uniq`, it is at the top (and unfrozen).
169 /// U2: If the top is `Uniq` (and unfrozen), accesses must be through that `Uniq` or pop it.
170 /// U3: If an access (deref sufficient?) happens with a `Uniq`, it requires the `Uniq` to be in the stack.
172 /// F1: After creating a `&`, the parts outside `UnsafeCell` are frozen.
173 /// F2: If a write access happens, it unfreezes.
174 /// F3: If an access (well, a deref) happens with an `&` outside `UnsafeCell`,
175 /// it requires the location to still be frozen.
177 /// Deref `bor`: check if the location is frozen and the tag in the stack.
178 /// This dos *not* constitute an access! "Deref" refers to the `*` operator
179 /// in Rust, and includs cases like `&*x` or `(*x).foo` where no or only part
180 /// of the memory actually gets accessed. Also we cannot know if we are
181 /// going to read or write.
182 /// Returns the index of the item we matched, `None` if it was the frozen one.
183 /// `kind` indicates which kind of reference is being dereferenced.
188 ) -> Result<Option<usize>, String> {
189 // Exclude unique ref with frozen tag.
190 if let (RefKind::Unique, Borrow::Alias(Some(_))) = (kind, bor) {
191 return Err(format!("encountered mutable reference with frozen tag ({:?})", bor));
193 // Checks related to freezing.
195 Borrow::Alias(Some(bor_t)) if kind == RefKind::Frozen => {
196 // We need the location to be frozen. This ensures F3.
197 let frozen = self.frozen_since.map_or(false, |itm_t| itm_t <= bor_t);
198 return if frozen { Ok(None) } else {
199 Err(format!("location is not frozen long enough"))
202 Borrow::Alias(_) if self.frozen_since.is_some() => {
203 // Shared deref to frozen location; looking good.
206 // Not sufficient; go on looking.
209 // If we got here, we have to look for our item in the stack.
210 for (idx, &itm) in self.borrows.iter().enumerate().rev() {
212 (BorStackItem::Uniq(itm_t), Borrow::Uniq(bor_t)) if itm_t == bor_t => {
213 // Found matching unique item. This satisfies U3.
216 (BorStackItem::Raw, Borrow::Alias(_)) => {
217 // Found matching aliasing/raw item.
220 // Go on looking. We ignore barriers! When an `&mut` and an `&` alias,
221 // dereferencing the `&` is still possible (to reborrow), but doing
226 // If we got here, we did not find our item. We have to error to satisfy U3.
227 Err(format!("Borrow being dereferenced ({:?}) does not exist on the borrow stack", bor))
230 /// Performs an actual memory access using `bor`. We do not know any types here
231 /// or whether things should be frozen, but we *do* know if this is reading
237 barrier_tracking: &BarrierTracking,
238 ) -> EvalResult<'tcx> {
239 // Check if we can match the frozen "item".
240 // Not possible on writes!
241 if self.is_frozen() {
242 if kind == AccessKind::Read {
243 // When we are frozen, we just accept all reads. No harm in this.
244 // The deref already checked that `Uniq` items are in the stack, and that
245 // the location is frozen if it should be.
248 trace!("access: unfreezing");
250 // Unfreeze on writes. This ensures F2.
251 self.frozen_since = None;
252 // Pop the stack until we have something matching.
253 while let Some(&itm) = self.borrows.last() {
255 (BorStackItem::FnBarrier(call), _) if barrier_tracking.is_active(call) => {
256 return err!(MachineError(format!(
257 "stopping looking for borrow being accessed ({:?}) because of barrier ({})",
261 (BorStackItem::Uniq(itm_t), Borrow::Uniq(bor_t)) if itm_t == bor_t => {
262 // Found matching unique item. Continue after the match.
264 (BorStackItem::Raw, _) if kind == AccessKind::Read => {
265 // When reading, everything can use a raw item!
266 // We do not want to do this when writing: Writing to an `&mut`
267 // should reaffirm its exclusivity (i.e., make sure it is
268 // on top of the stack). Continue after the match.
270 (BorStackItem::Raw, Borrow::Alias(_)) => {
271 // Found matching raw item. Continue after the match.
274 // Pop this, go on. This ensures U2.
275 let itm = self.borrows.pop().unwrap();
276 trace!("access: Popping {:?}", itm);
280 // If we got here, we found a matching item. Congratulations!
281 // However, we are not done yet: If this access is deallocating, we must make sure
282 // there are no active barriers remaining on the stack.
283 if kind == AccessKind::Dealloc {
284 for &itm in self.borrows.iter().rev() {
286 BorStackItem::FnBarrier(call) if barrier_tracking.is_active(call) => {
287 return err!(MachineError(format!(
288 "deallocating with active barrier ({})", call
298 // If we got here, we did not find our item.
299 err!(MachineError(format!(
300 "borrow being accessed ({:?}) does not exist on the borrow stack",
305 /// Initiate `bor`; mostly this means pushing.
306 /// This operation cannot fail; it is up to the caller to ensure that the precondition
307 /// is met: We cannot push `Uniq` onto frozen stacks.
308 /// `kind` indicates which kind of reference is being created.
309 fn create(&mut self, bor: Borrow, kind: RefKind) {
310 // When creating a frozen reference, freeze. This ensures F1.
311 // We also do *not* push anything else to the stack, making sure that no nother kind
312 // of access (like writing through raw pointers) is permitted.
313 if kind == RefKind::Frozen {
314 let bor_t = match bor {
315 Borrow::Alias(Some(t)) => t,
316 _ => bug!("Creating illegal borrow {:?} for frozen ref", bor),
318 // It is possible that we already are frozen (e.g., if we just pushed a barrier,
319 // the redundancy check would not have kicked in).
320 match self.frozen_since {
321 Some(loc_t) => assert!(
323 "trying to freeze location for longer than it was already frozen"
326 trace!("create: Freezing");
327 self.frozen_since = Some(bor_t);
333 self.frozen_since.is_none(),
334 "trying to create non-frozen reference to frozen location"
337 // Push new item to the stack.
338 let itm = match bor {
339 Borrow::Uniq(t) => BorStackItem::Uniq(t),
340 Borrow::Alias(_) => BorStackItem::Raw,
342 if *self.borrows.last().unwrap() == itm {
343 // This is just an optimization, no functional change: Avoid stacking
344 // multiple `Shr` on top of each other.
345 assert!(bor.is_aliasing());
346 trace!("create: sharing a shared location is a NOP");
349 trace!("create: pushing {:?}", itm);
350 self.borrows.push(itm);
355 fn barrier(&mut self, call: CallId) {
356 let itm = BorStackItem::FnBarrier(call);
357 if *self.borrows.last().unwrap() == itm {
358 // This is just an optimization, no functional change: Avoid stacking
359 // multiple identical barriers on top of each other.
360 // This can happen when a function receives several shared references
362 trace!("barrier: avoiding redundant extra barrier");
364 trace!("barrier: pushing barrier for call {}", call);
365 self.borrows.push(itm);
370 /// Higher-level per-location operations: deref, access, reborrow.
372 /// Checks that this stack is fine with being dereferenced.
375 ptr: Pointer<Borrow>,
378 ) -> EvalResult<'tcx> {
379 trace!("deref for tag {:?} as {:?}: {:?}, size {}",
380 ptr.tag, kind, ptr, size.bytes());
381 let stacks = self.stacks.borrow();
382 for stack in stacks.iter(ptr.offset, size) {
383 stack.deref(ptr.tag, kind).map_err(InterpError::MachineError)?;
388 /// `ptr` got used, reflect that in the stack.
391 ptr: Pointer<Borrow>,
394 ) -> EvalResult<'tcx> {
395 trace!("{:?} access of tag {:?}: {:?}, size {}", kind, ptr.tag, ptr, size.bytes());
396 // Even reads can have a side-effect, by invalidating other references.
397 // This is fundamentally necessary since `&mut` asserts that there
398 // are no accesses through other references, not even reads.
399 let barrier_tracking = self.barrier_tracking.borrow();
400 let mut stacks = self.stacks.borrow_mut();
401 for stack in stacks.iter_mut(ptr.offset, size) {
402 stack.access(ptr.tag, kind, &*barrier_tracking)?;
407 /// Reborrow the given pointer to the new tag for the given kind of reference.
408 /// This works on `&self` because we might encounter references to constant memory.
411 ptr: Pointer<Borrow>,
413 mut barrier: Option<CallId>,
416 ) -> EvalResult<'tcx> {
417 assert_eq!(new_bor.is_unique(), new_kind == RefKind::Unique);
419 "reborrow for tag {:?} to {:?} as {:?}: {:?}, size {}",
420 ptr.tag, new_bor, new_kind, ptr, size.bytes(),
422 if new_kind == RefKind::Raw {
423 // No barrier for raw, including `&UnsafeCell`. They can rightfully alias with `&mut`.
424 // FIXME: This means that the `dereferencable` attribute on non-frozen shared references
425 // is incorrect! They are dereferencable when the function is called, but might become
426 // non-dereferencable during the course of execution.
427 // Also see [1], [2].
429 // [1]: <https://internals.rust-lang.org/t/
430 // is-it-possible-to-be-memory-safe-with-deallocated-self/8457/8>,
431 // [2]: <https://lists.llvm.org/pipermail/llvm-dev/2018-July/124555.html>
434 let barrier_tracking = self.barrier_tracking.borrow();
435 let mut stacks = self.stacks.borrow_mut();
436 for stack in stacks.iter_mut(ptr.offset, size) {
437 // Access source `ptr`, create new ref.
438 let ptr_idx = stack.deref(ptr.tag, new_kind).map_err(InterpError::MachineError)?;
439 // If we can deref the new tag already, and if that tag lives higher on
440 // the stack than the one we come from, just use that.
441 // That is, we check if `new_bor` *already* is "derived from" `ptr.tag`.
442 // This also checks frozenness, if required.
443 let bor_redundant = barrier.is_none() &&
444 match (ptr_idx, stack.deref(new_bor, new_kind)) {
445 // If the new borrow works with the frozen item, or else if it lives
446 // above the old one in the stack, our job here is done.
447 (_, Ok(None)) => true,
448 (Some(ptr_idx), Ok(Some(new_idx))) if new_idx >= ptr_idx => true,
449 // Otherwise, we need to create a new borrow.
453 assert!(new_bor.is_aliasing(), "a unique reborrow can never be redundant");
454 trace!("reborrow is redundant");
457 // We need to do some actual work.
458 let access_kind = if new_kind == RefKind::Unique {
463 stack.access(ptr.tag, access_kind, &*barrier_tracking)?;
464 if let Some(call) = barrier {
467 stack.create(new_bor, new_kind);
474 impl AllocationExtra<Borrow, MemoryState> for Stacks {
476 fn memory_allocated<'tcx>(size: Size, extra: &MemoryState) -> Self {
478 borrows: vec![BorStackItem::Raw],
482 stacks: RefCell::new(RangeMap::new(size, stack)),
483 barrier_tracking: Rc::clone(extra),
488 fn memory_read<'tcx>(
489 alloc: &Allocation<Borrow, Stacks>,
490 ptr: Pointer<Borrow>,
492 ) -> EvalResult<'tcx> {
493 alloc.extra.access(ptr, size, AccessKind::Read)
497 fn memory_written<'tcx>(
498 alloc: &mut Allocation<Borrow, Stacks>,
499 ptr: Pointer<Borrow>,
501 ) -> EvalResult<'tcx> {
502 alloc.extra.access(ptr, size, AccessKind::Write)
506 fn memory_deallocated<'tcx>(
507 alloc: &mut Allocation<Borrow, Stacks>,
508 ptr: Pointer<Borrow>,
510 ) -> EvalResult<'tcx> {
511 alloc.extra.access(ptr, size, AccessKind::Dealloc)
516 /// Pushes the first item to the stacks.
517 pub(crate) fn first_item(
522 for stack in self.stacks.get_mut().iter_mut(Size::ZERO, size) {
523 assert!(stack.borrows.len() == 1);
524 assert_eq!(stack.borrows.pop().unwrap(), BorStackItem::Raw);
525 stack.borrows.push(itm);
530 impl<'a, 'mir, 'tcx> EvalContextPrivExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
531 trait EvalContextPrivExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
534 place: MPlaceTy<'tcx, Borrow>,
538 ) -> EvalResult<'tcx> {
539 let this = self.eval_context_mut();
540 let ptr = place.ptr.to_ptr()?;
541 let barrier = if fn_barrier { Some(this.frame().extra) } else { None };
542 trace!("reborrow: creating new reference for {:?} (pointee {}): {:?}",
543 ptr, place.layout.ty, new_bor);
545 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
546 let alloc = this.memory().get(ptr.alloc_id)?;
547 alloc.check_bounds(this, ptr, size)?;
548 // Update the stacks.
549 if let Borrow::Alias(Some(_)) = new_bor {
550 // Reference that cares about freezing. We need a frozen-sensitive reborrow.
551 this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
552 let kind = if frozen { RefKind::Frozen } else { RefKind::Raw };
553 alloc.extra.reborrow(cur_ptr, size, barrier, new_bor, kind)
556 // Just treat this as one big chunk.
557 let kind = if new_bor.is_unique() { RefKind::Unique } else { RefKind::Raw };
558 alloc.extra.reborrow(ptr, size, barrier, new_bor, kind)?;
563 /// Retags an indidual pointer, returning the retagged version.
564 /// `mutbl` can be `None` to make this a raw pointer.
567 val: ImmTy<'tcx, Borrow>,
568 mutbl: Option<Mutability>,
571 ) -> EvalResult<'tcx, Immediate<Borrow>> {
572 let this = self.eval_context_mut();
573 // We want a place for where the ptr *points to*, so we get one.
574 let place = this.ref_to_mplace(val)?;
575 let size = this.size_and_align_of_mplace(place)?
576 .map(|(size, _)| size)
577 .unwrap_or_else(|| place.layout.size);
578 if size == Size::ZERO {
579 // Nothing to do for ZSTs.
583 // Compute new borrow.
584 let time = this.machine.stacked_borrows.increment_clock();
585 let new_bor = match mutbl {
586 Some(MutMutable) => Borrow::Uniq(time),
587 Some(MutImmutable) => Borrow::Alias(Some(time)),
588 None => Borrow::default(),
592 this.reborrow(place, size, fn_barrier, new_bor)?;
593 let new_place = place.with_tag(new_bor);
594 // Handle two-phase borrows.
596 assert!(mutbl == Some(MutMutable), "two-phase shared borrows make no sense");
597 // We immediately share it, to allow read accesses
598 let two_phase_time = this.machine.stacked_borrows.increment_clock();
599 let two_phase_bor = Borrow::Alias(Some(two_phase_time));
600 this.reborrow(new_place, size, false /* fn_barrier */, two_phase_bor)?;
603 // Return new pointer.
604 Ok(new_place.to_ref())
608 impl<'a, 'mir, 'tcx> EvalContextExt<'a, 'mir, 'tcx> for crate::MiriEvalContext<'a, 'mir, 'tcx> {}
609 pub trait EvalContextExt<'a, 'mir, 'tcx: 'a+'mir>: crate::MiriEvalContextExt<'a, 'mir, 'tcx> {
610 fn tag_new_allocation(
613 kind: MemoryKind<MiriMemoryKind>,
615 let this = self.eval_context_mut();
616 let time = match kind {
617 MemoryKind::Stack => {
618 // New unique borrow. This `Uniq` is not accessible by the program,
619 // so it will only ever be used when using the local directly (i.e.,
620 // not through a pointer). That is, whenever we directly use a local, this will pop
621 // everything else off the stack, invalidating all previous pointers,
622 // and in particular, *all* raw pointers. This subsumes the explicit
623 // `reset` which the blog post [1] says to perform when accessing a local.
625 // [1]: <https://www.ralfj.de/blog/2018/08/07/stacked-borrows.html>
626 this.machine.stacked_borrows.increment_clock()
629 // Nothing to do for everything else.
630 return Borrow::default()
633 // Make this the active borrow for this allocation.
637 .expect("this is a new allocation; it must still exist");
638 let size = Size::from_bytes(alloc.bytes.len() as u64);
639 alloc.extra.first_item(BorStackItem::Uniq(time), size);
643 /// Called for value-to-place conversion. `mutability` is `None` for raw pointers.
645 /// Note that this does *not* mean that all this memory will actually get accessed/referenced!
646 /// We could be in the middle of `&(*var).1`.
649 place: MPlaceTy<'tcx, Borrow>,
651 mutability: Option<Mutability>,
652 ) -> EvalResult<'tcx> {
653 let this = self.eval_context_ref();
655 "ptr_dereference: Accessing {} reference for {:?} (pointee {})",
656 if let Some(mutability) = mutability {
657 format!("{:?}", mutability)
661 place.ptr, place.layout.ty
663 let ptr = place.ptr.to_ptr()?;
664 if mutability.is_none() {
665 // No further checks on raw derefs -- only the access itself will be checked.
669 // Get the allocation
670 let alloc = this.memory().get(ptr.alloc_id)?;
671 alloc.check_bounds(this, ptr, size)?;
672 // If we got here, we do some checking, *but* we leave the tag unchanged.
673 if let Borrow::Alias(Some(_)) = ptr.tag {
674 assert_eq!(mutability, Some(MutImmutable));
675 // We need a frozen-sensitive check.
676 this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
677 let kind = if frozen { RefKind::Frozen } else { RefKind::Raw };
678 alloc.extra.deref(cur_ptr, size, kind)
681 // Just treat this as one big chunk.
682 let kind = if mutability == Some(MutMutable) { RefKind::Unique } else { RefKind::Raw };
683 alloc.extra.deref(ptr, size, kind)?;
693 place: PlaceTy<'tcx, Borrow>
694 ) -> EvalResult<'tcx> {
695 let this = self.eval_context_mut();
696 // Determine mutability and whether to add a barrier.
697 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
698 // making it useless.
699 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(Option<Mutability>, bool)> {
701 // References are simple.
702 ty::Ref(_, _, mutbl) => Some((Some(mutbl), kind == RetagKind::FnEntry)),
703 // Raw pointers need to be enabled.
704 ty::RawPtr(..) if kind == RetagKind::Raw => Some((None, false)),
705 // Boxes do not get a barrier: barriers reflect that references outlive the call
706 // they were passed in to; that's just not the case for boxes.
707 ty::Adt(..) if ty.is_box() => Some((Some(MutMutable), false)),
712 // We need a visitor to visit all references. However, that requires
713 // a `MemPlace`, so we have a fast path for reference types that
714 // avoids allocating.
715 if let Some((mutbl, barrier)) = qualify(place.layout.ty, kind) {
717 let val = this.read_immediate(this.place_to_op(place)?)?;
718 let val = this.retag_reference(val, mutbl, barrier, kind == RetagKind::TwoPhase)?;
719 this.write_immediate(val, place)?;
722 let place = this.force_allocation(place)?;
724 let mut visitor = RetagVisitor { ecx: this, kind };
725 visitor.visit_value(place)?;
727 // The actual visitor.
728 struct RetagVisitor<'ecx, 'a, 'mir, 'tcx> {
729 ecx: &'ecx mut MiriEvalContext<'a, 'mir, 'tcx>,
732 impl<'ecx, 'a, 'mir, 'tcx>
733 MutValueVisitor<'a, 'mir, 'tcx, Evaluator<'tcx>>
735 RetagVisitor<'ecx, 'a, 'mir, 'tcx>
737 type V = MPlaceTy<'tcx, Borrow>;
740 fn ecx(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
744 // Primitives of reference type, that is the one thing we are interested in.
745 fn visit_primitive(&mut self, place: MPlaceTy<'tcx, Borrow>) -> EvalResult<'tcx>
747 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
748 // making it useless.
749 if let Some((mutbl, barrier)) = qualify(place.layout.ty, self.kind) {
750 let val = self.ecx.read_immediate(place.into())?;
751 let val = self.ecx.retag_reference(
755 self.kind == RetagKind::TwoPhase
757 self.ecx.write_immediate(val, place.into())?;