use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_middle::mir::RetagKind;
use rustc_middle::ty;
-use rustc_target::abi::Size;
+use rustc_target::abi::{Align, LayoutOf, Size};
use rustc_hir::Mutability;
use crate::*;
next_call_id: CallId,
/// Those call IDs corresponding to functions that are still running.
active_calls: FxHashSet<CallId>,
- /// The id to trace in this execution run
+ /// The pointer id to trace
tracked_pointer_tag: Option<PtrId>,
+ /// The call id to trace
+ tracked_call_id: Option<CallId>,
+ /// Whether to track raw pointers.
+ track_raw: bool,
}
/// Memory extra state gives us interior mutable access to the global state.
pub type MemoryExtra = Rc<RefCell<GlobalState>>;
/// Utilities for initialization and ID generation
impl GlobalState {
- pub fn new(tracked_pointer_tag: Option<PtrId>) -> Self {
+ pub fn new(tracked_pointer_tag: Option<PtrId>, tracked_call_id: Option<CallId>, track_raw: bool) -> Self {
GlobalState {
next_ptr_id: NonZeroU64::new(1).unwrap(),
base_ptr_ids: FxHashMap::default(),
next_call_id: NonZeroU64::new(1).unwrap(),
active_calls: FxHashSet::default(),
tracked_pointer_tag,
+ tracked_call_id,
+ track_raw,
}
}
fn new_ptr(&mut self) -> PtrId {
let id = self.next_ptr_id;
+ if Some(id) == self.tracked_pointer_tag {
+ register_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(id));
+ }
self.next_ptr_id = NonZeroU64::new(id.get() + 1).unwrap();
id
}
pub fn new_call(&mut self) -> CallId {
let id = self.next_call_id;
trace!("new_call: Assigning ID {}", id);
+ if Some(id) == self.tracked_call_id {
+ register_diagnostic(NonHaltingDiagnostic::CreatedCallId(id));
+ }
assert!(self.active_calls.insert(id));
self.next_call_id = NonZeroU64::new(id.get() + 1).unwrap();
id
fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
if let Tag::Tagged(id) = item.tag {
if Some(id) == global.tracked_pointer_tag {
- register_diagnostic(NonHaltingDiagnostic::PoppedTrackedPointerTag(item.clone()));
+ register_diagnostic(NonHaltingDiagnostic::PoppedPointerTag(item.clone()));
}
}
if let Some(call) = item.protector {
/// Test if a memory `access` using pointer tagged `tag` is granted.
/// If yes, return the index of the item that granted it.
- fn access(&mut self, access: AccessKind, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
+ fn access(&mut self, access: AccessKind, ptr: Pointer<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
// Two main steps: Find granting item, remove incompatible items above.
// Step 1: Find granting item.
- let granting_idx = self.find_granting(access, tag).ok_or_else(|| {
+ let granting_idx = self.find_granting(access, ptr.tag).ok_or_else(|| {
err_sb_ub(format!(
- "no item granting {} to tag {:?} found in borrow stack.",
- access, tag
+ "no item granting {} to tag {:?} at {} found in borrow stack.",
+ access, ptr.tag, ptr.erase_tag(),
))
})?;
let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
for item in self.borrows.drain(first_incompatible_idx..).rev() {
trace!("access: popping item {:?}", item);
- Stack::check_protector(&item, Some(tag), global)?;
+ Stack::check_protector(&item, Some(ptr.tag), global)?;
}
} else {
// On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
let item = &mut self.borrows[idx];
if item.perm == Permission::Unique {
trace!("access: disabling item {:?}", item);
- Stack::check_protector(item, Some(tag), global)?;
+ Stack::check_protector(item, Some(ptr.tag), global)?;
item.perm = Permission::Disabled;
}
}
/// Deallocate a location: Like a write access, but also there must be no
/// active protectors at all because we will remove all items.
- fn dealloc(&mut self, tag: Tag, global: &GlobalState) -> InterpResult<'tcx> {
+ fn dealloc(&mut self, ptr: Pointer<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
// Step 1: Find granting item.
- self.find_granting(AccessKind::Write, tag).ok_or_else(|| {
+ self.find_granting(AccessKind::Write, ptr.tag).ok_or_else(|| {
err_sb_ub(format!(
- "no item granting write access for deallocation to tag {:?} found in borrow stack",
- tag,
+ "no item granting write access for deallocation to tag {:?} at {} found in borrow stack",
+ ptr.tag, ptr.erase_tag(),
))
})?;
Ok(())
}
- /// Derived a new pointer from one with the given tag.
+ /// Derive a new pointer from one with the given tag.
/// `weak` controls whether this operation is weak or strong: weak granting does not act as
/// an access, and they add the new item directly on top of the one it is derived
/// from instead of all the way at the top of the stack.
- fn grant(&mut self, derived_from: Tag, new: Item, global: &GlobalState) -> InterpResult<'tcx> {
+ fn grant(&mut self, derived_from: Pointer<Tag>, new: Item, global: &GlobalState) -> InterpResult<'tcx> {
// Figure out which access `perm` corresponds to.
let access =
if new.perm.grants(AccessKind::Write) { AccessKind::Write } else { AccessKind::Read };
// Now we figure out which item grants our parent (`derived_from`) this kind of access.
// We use that to determine where to put the new item.
- let granting_idx = self.find_granting(access, derived_from)
+ let granting_idx = self.find_granting(access, derived_from.tag)
.ok_or_else(|| err_sb_ub(format!(
- "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack",
- new.perm, derived_from,
+ "trying to reborrow for {:?} at {}, but parent tag {:?} does not have an appropriate item in the borrow stack",
+ new.perm, derived_from.erase_tag(), derived_from.tag,
)))?;
// Compute where to put the new item.
&self,
ptr: Pointer<Tag>,
size: Size,
- f: impl Fn(&mut Stack, &GlobalState) -> InterpResult<'tcx>,
+ f: impl Fn(Pointer<Tag>, &mut Stack, &GlobalState) -> InterpResult<'tcx>,
) -> InterpResult<'tcx> {
let global = self.global.borrow();
let mut stacks = self.stacks.borrow_mut();
- for stack in stacks.iter_mut(ptr.offset, size) {
- f(stack, &*global)?;
+ for (offset, stack) in stacks.iter_mut(ptr.offset, size) {
+ let mut cur_ptr = ptr;
+ cur_ptr.offset = offset;
+ f(cur_ptr, stack, &*global)?;
}
Ok(())
}
// everything else off the stack, invalidating all previous pointers,
// and in particular, *all* raw pointers.
MemoryKind::Stack => (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
- // Global memory can be referenced by global pointers from `tcx`.
+ // `Global` memory can be referenced by global pointers from `tcx`.
// Thus we call `global_base_ptr` such that the global pointers get the same tag
// as what we use here.
- // `Machine` is used for extern statics, and thus must also be listed here.
+ // `ExternStatic` is used for extern statics, and thus must also be listed here.
// `Env` we list because we can get away with precise tracking there.
// The base pointer is not unique, so the base permission is `SharedReadWrite`.
- MemoryKind::Machine(MiriMemoryKind::Global | MiriMemoryKind::Machine | MiriMemoryKind::Env) =>
+ MemoryKind::Machine(MiriMemoryKind::Global | MiriMemoryKind::ExternStatic | MiriMemoryKind::Tls | MiriMemoryKind::Env) =>
(extra.borrow_mut().global_base_ptr(id), Permission::SharedReadWrite),
- // Everything else we handle entirely untagged for now.
- // FIXME: experiment with more precise tracking.
- _ => (Tag::Untagged, Permission::SharedReadWrite),
+ // Everything else we handle like raw pointers for now.
+ _ => {
+ let mut extra = extra.borrow_mut();
+ let tag = if extra.track_raw { Tag::Tagged(extra.new_ptr()) } else { Tag::Untagged };
+ (tag, Permission::SharedReadWrite)
+ }
};
(Stacks::new(size, perm, tag, extra), tag)
}
#[inline(always)]
pub fn memory_read<'tcx>(&self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
- self.for_each(ptr, size, |stack, global| {
- stack.access(AccessKind::Read, ptr.tag, global)?;
- Ok(())
- })
+ self.for_each(ptr, size, |ptr, stack, global| stack.access(AccessKind::Read, ptr, global))
}
#[inline(always)]
pub fn memory_written<'tcx>(&mut self, ptr: Pointer<Tag>, size: Size) -> InterpResult<'tcx> {
trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
- self.for_each(ptr, size, |stack, global| {
- stack.access(AccessKind::Write, ptr.tag, global)?;
- Ok(())
- })
+ self.for_each(ptr, size, |ptr, stack, global| stack.access(AccessKind::Write, ptr, global))
}
#[inline(always)]
size: Size,
) -> InterpResult<'tcx> {
trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
- self.for_each(ptr, size, |stack, global| stack.dealloc(ptr.tag, global))
+ self.for_each(ptr, size, |ptr, stack, global| stack.dealloc(ptr, global))
}
}
/// Retagging/reborrowing. There is some policy in here, such as which permissions
/// to grant for which references, and when to add protectors.
-impl<'mir, 'tcx> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
+impl<'mir, 'tcx: 'mir> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
fn reborrow(
&mut self,
- place: MPlaceTy<'tcx, Tag>,
+ place: &MPlaceTy<'tcx, Tag>,
size: Size,
kind: RefKind,
new_tag: Tag,
Permission::SharedReadWrite
};
let item = Item { perm, tag: new_tag, protector };
- stacked_borrows.for_each(cur_ptr, size, |stack, global| {
- stack.grant(cur_ptr.tag, item, global)
+ stacked_borrows.for_each(cur_ptr, size, |cur_ptr, stack, global| {
+ stack.grant(cur_ptr, item, global)
})
});
}
};
let item = Item { perm, tag: new_tag, protector };
- stacked_borrows.for_each(ptr, size, |stack, global| stack.grant(ptr.tag, item, global))
+ stacked_borrows.for_each(ptr, size, |ptr, stack, global| stack.grant(ptr, item, global))
}
/// Retags an indidual pointer, returning the retagged version.
/// `mutbl` can be `None` to make this a raw pointer.
fn retag_reference(
&mut self,
- val: ImmTy<'tcx, Tag>,
+ val: &ImmTy<'tcx, Tag>,
kind: RefKind,
protect: bool,
- ) -> InterpResult<'tcx, Immediate<Tag>> {
+ ) -> InterpResult<'tcx, ImmTy<'tcx, Tag>> {
let this = self.eval_context_mut();
// We want a place for where the ptr *points to*, so we get one.
let place = this.ref_to_mplace(val)?;
let size = this
- .size_and_align_of_mplace(place)?
- .map(|(size, _)| size)
- .unwrap_or_else(|| place.layout.size);
+ .size_and_align_of_mplace(&place)?
+ .map(|(size, _)| size);
+ // FIXME: If we cannot determine the size (because the unsized tail is an `extern type`),
+ // bail out -- we cannot reasonably figure out which memory range to reborrow.
+ // See https://github.com/rust-lang/unsafe-code-guidelines/issues/276.
+ let size = match size {
+ Some(size) => size,
+ None => return Ok(*val),
+ };
+ // `reborrow` relies on getting a `Pointer` and everything being in-bounds,
+ // so let's ensure that. However, we do not care about alignment.
// We can see dangling ptrs in here e.g. after a Box's `Unique` was
- // updated using "self.0 = ..." (can happen in Box::from_raw); see miri#1050.
- let place = this.mplace_access_checked(place)?;
- if size == Size::ZERO {
- // Nothing to do for ZSTs.
+ // updated using "self.0 = ..." (can happen in Box::from_raw) so we cannot ICE; see miri#1050.
+ let place = this.mplace_access_checked(place, Some(Align::from_bytes(1).unwrap()))?;
+ // Nothing to do for ZSTs. We use `is_bits` here because we *do* need to retag even ZSTs
+ // when there actually is a tag (to avoid inheriting a tag that would let us access more
+ // than 0 bytes).
+ if size == Size::ZERO && place.ptr.is_bits() {
return Ok(*val);
}
// Compute new borrow.
- let new_tag = match kind {
- // Give up tracking for raw pointers.
- // FIXME: Experiment with more precise tracking. Blocked on `&raw`
- // because `Rc::into_raw` currently creates intermediate references,
- // breaking `Rc::from_raw`.
- RefKind::Raw { .. } => Tag::Untagged,
- // All other pointesr are properly tracked.
- _ => Tag::Tagged(
- this.memory.extra.stacked_borrows.as_ref().unwrap().borrow_mut().new_ptr(),
- ),
+ let new_tag = {
+ let mut mem_extra = this.memory.extra.stacked_borrows.as_ref().unwrap().borrow_mut();
+ match kind {
+ // Give up tracking for raw pointers.
+ RefKind::Raw { .. } if !mem_extra.track_raw => Tag::Untagged,
+ // All other pointers are properly tracked.
+ _ => Tag::Tagged(mem_extra.new_ptr()),
+ }
};
// Reborrow.
- this.reborrow(place, size, kind, new_tag, protect)?;
+ this.reborrow(&place, size, kind, new_tag, protect)?;
let new_place = place.replace_tag(new_tag);
// Return new pointer.
- Ok(new_place.to_ref())
+ Ok(ImmTy::from_immediate(new_place.to_ref(), val.layout))
}
}
-impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
+impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
- fn retag(&mut self, kind: RetagKind, place: PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
+ fn retag(&mut self, kind: RetagKind, place: &PlaceTy<'tcx, Tag>) -> InterpResult<'tcx> {
let this = self.eval_context_mut();
// Determine mutability and whether to add a protector.
// Cannot use `builtin_deref` because that reports *immutable* for `Box`,
// making it useless.
fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
- match ty.kind {
+ match ty.kind() {
// References are simple.
ty::Ref(_, _, Mutability::Mut) => Some((
RefKind::Unique { two_phase: kind == RetagKind::TwoPhase },
// but might also cost us optimization and analyses. We will have to experiment more with this.
if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
// Fast path.
- let val = this.read_immediate(this.place_to_op(place)?)?;
- let val = this.retag_reference(val, mutbl, protector)?;
- this.write_immediate(val, place)?;
+ let val = this.read_immediate(&this.place_to_op(place)?)?;
+ let val = this.retag_reference(&val, mutbl, protector)?;
+ this.write_immediate(*val, place)?;
+ }
+
+ Ok(())
+ }
+
+ /// After a stack frame got pushed, retag the return place so that we are sure
+ /// it does not alias with anything.
+ ///
+ /// This is a HACK because there is nothing in MIR that would make the retag
+ /// explicit. Also see https://github.com/rust-lang/rust/issues/71117.
+ fn retag_return_place(&mut self) -> InterpResult<'tcx> {
+ let this = self.eval_context_mut();
+ let return_place = if let Some(return_place) = this.frame_mut().return_place {
+ return_place
+ } else {
+ // No return place, nothing to do.
+ return Ok(());
+ };
+ if return_place.layout.is_zst() {
+ // There may not be any memory here, nothing to do.
+ return Ok(());
}
+ // We need this to be in-memory to use tagged pointers.
+ let return_place = this.force_allocation(&return_place)?;
+
+ // We have to turn the place into a pointer to use the existing code.
+ // (The pointer type does not matter, so we use a raw pointer.)
+ let ptr_layout = this.layout_of(this.tcx.mk_mut_ptr(return_place.layout.ty))?;
+ let val = ImmTy::from_immediate(return_place.to_ref(), ptr_layout);
+ // Reborrow it.
+ let val = this.retag_reference(&val, RefKind::Unique { two_phase: false }, /*protector*/ true)?;
+ // And use reborrowed pointer for return place.
+ let return_place = this.ref_to_mplace(&val)?;
+ this.frame_mut().return_place = Some(return_place.into());
Ok(())
}