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};
8 use std::num::NonZeroU64;
10 use rustc::ty::{self, layout::Size};
11 use rustc::hir::Mutability::{Mutable, Immutable};
12 use rustc::mir::RetagKind;
15 InterpResult, HelpersEvalContextExt,
16 MemoryKind, MiriMemoryKind, RangeMap, AllocId, Pointer, Immediate, ImmTy, PlaceTy, MPlaceTy,
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.
86 /// Extra per-allocation state.
87 #[derive(Clone, Debug)]
89 // Even reading memory can have effects on the stack, so we need a `RefCell` here.
90 stacks: RefCell<RangeMap<Stack>>,
91 // Pointer to global state
95 /// Extra global state, available to the memory access hooks.
97 pub struct GlobalState {
98 /// Next unused pointer ID (tag).
100 /// Table storing the "base" tag for each allocation.
101 /// The base tag is the one used for the initial pointer.
102 /// We need this in a separate table to handle cyclic statics.
103 base_ptr_ids: HashMap<AllocId, Tag>,
104 /// Next unused call ID (for protectors).
105 next_call_id: CallId,
106 /// Those call IDs corresponding to functions that are still running.
107 active_calls: HashSet<CallId>,
109 /// Memory extra state gives us interior mutable access to the global state.
110 pub type MemoryExtra = Rc<RefCell<GlobalState>>;
112 /// Indicates which kind of access is being performed.
113 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
114 pub enum AccessKind {
119 impl fmt::Display for AccessKind {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 AccessKind::Read => write!(f, "read access"),
123 AccessKind::Write => write!(f, "write access"),
128 /// Indicates which kind of reference is being created.
129 /// Used by high-level `reborrow` to compute which permissions to grant to the
131 #[derive(Copy, Clone, Hash, PartialEq, Eq)]
133 /// `&mut` and `Box`.
134 Unique { two_phase: bool },
135 /// `&` with or without interior mutability.
137 /// `*mut`/`*const` (raw pointers).
138 Raw { mutable: bool },
141 impl fmt::Display for RefKind {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 RefKind::Unique { two_phase: false } => write!(f, "unique"),
145 RefKind::Unique { two_phase: true } => write!(f, "unique (two-phase)"),
146 RefKind::Shared => write!(f, "shared"),
147 RefKind::Raw { mutable: true } => write!(f, "raw (mutable)"),
148 RefKind::Raw { mutable: false } => write!(f, "raw (constant)"),
153 /// Utilities for initialization and ID generation
154 impl Default for GlobalState {
155 fn default() -> Self {
157 next_ptr_id: NonZeroU64::new(1).unwrap(),
158 base_ptr_ids: HashMap::default(),
159 next_call_id: NonZeroU64::new(1).unwrap(),
160 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 && (access == AccessKind::Read || self != Permission::SharedReadOnly)
223 /// Core per-location operations: access, dealloc, reborrow.
225 /// Find the item granting the given kind of access to the given tag, and return where
226 /// it is on the stack.
227 fn find_granting(&self, access: AccessKind, tag: Tag) -> Option<usize> {
229 .enumerate() // we also need to know *where* in the stack
230 .rev() // search top-to-bottom
231 // Return permission of first item that grants access.
232 // We require a permission with the right tag, ensuring U3 and F3.
233 .find_map(|(idx, item)|
234 if tag == item.tag && item.perm.grants(access) {
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 =>
248 bug!("Cannot use SharedReadOnly for writing"),
249 Permission::Disabled =>
250 bug!("Cannot use Disabled for anything"),
251 Permission::Unique =>
252 // On a write, everything above us is incompatible.
254 Permission::SharedReadWrite => {
255 // The SharedReadWrite *just* above us are compatible, to skip those.
256 let mut idx = granting + 1;
257 while let Some(item) = self.borrows.get(idx) {
258 if item.perm == Permission::SharedReadWrite {
262 // Found first incompatible!
271 /// Check if the given item is protected.
272 fn check_protector(item: &Item, tag: Option<Tag>, global: &GlobalState) -> InterpResult<'tcx> {
273 if let Some(call) = item.protector {
274 if global.is_active(call) {
275 if let Some(tag) = tag {
276 throw_ub!(UbExperimental(format!(
277 "not granting access to tag {:?} because incompatible item is protected: {:?}",
281 throw_ub!(UbExperimental(format!(
282 "deallocating while item is protected: {:?}", item
290 /// Test if a memory `access` using pointer tagged `tag` is granted.
291 /// If yes, return the index of the item that granted it.
296 global: &GlobalState,
297 ) -> InterpResult<'tcx> {
298 // Two main steps: Find granting item, remove incompatible items above.
300 // Step 1: Find granting item.
301 let granting_idx = self.find_granting(access, tag)
302 .ok_or_else(|| err_ub!(UbExperimental(format!(
303 "no item granting {} to tag {:?} found in borrow stack",
307 // Step 2: Remove incompatible items above them. Make sure we do not remove protected
308 // items. Behavior differs for reads and writes.
309 if access == AccessKind::Write {
310 // Remove everything above the write-compatible items, like a proper stack. This makes sure read-only and unique
311 // pointers become invalid on write accesses (ensures F2a, and ensures U2 for write accesses).
312 let first_incompatible_idx = self.find_first_write_incompatible(granting_idx);
313 for item in self.borrows.drain(first_incompatible_idx..).rev() {
314 trace!("access: popping item {:?}", item);
315 Stack::check_protector(&item, Some(tag), global)?;
318 // On a read, *disable* all `Unique` above the granting item. This ensures U2 for read accesses.
319 // The reason this is not following the stack discipline (by removing the first Unique and
320 // everything on top of it) is that in `let raw = &mut *x as *mut _; let _val = *x;`, the second statement
321 // would pop the `Unique` from the reborrow of the first statement, and subsequently also pop the
322 // `SharedReadWrite` for `raw`.
323 // This pattern occurs a lot in the standard library: create a raw pointer, then also create a shared
324 // reference and use that.
325 // We *disable* instead of removing `Unique` to avoid "connecting" two neighbouring blocks of SRWs.
326 for idx in (granting_idx+1 .. self.borrows.len()).rev() {
327 let item = &mut self.borrows[idx];
328 if item.perm == Permission::Unique {
329 trace!("access: disabling item {:?}", item);
330 Stack::check_protector(item, Some(tag), global)?;
331 item.perm = Permission::Disabled;
340 /// Deallocate a location: Like a write access, but also there must be no
341 /// active protectors at all because we will remove all items.
345 global: &GlobalState,
346 ) -> InterpResult<'tcx> {
347 // Step 1: Find granting item.
348 self.find_granting(AccessKind::Write, tag)
349 .ok_or_else(|| err_ub!(UbExperimental(format!(
350 "no item granting write access for deallocation to tag {:?} found in borrow stack",
354 // Step 2: Remove all items. Also checks for protectors.
355 for item in self.borrows.drain(..).rev() {
356 Stack::check_protector(&item, None, global)?;
362 /// Derived a new pointer from one with the given tag.
363 /// `weak` controls whether this operation is weak or strong: weak granting does not act as
364 /// an access, and they add the new item directly on top of the one it is derived
365 /// from instead of all the way at the top of the stack.
370 global: &GlobalState,
371 ) -> InterpResult<'tcx> {
372 // Figure out which access `perm` corresponds to.
373 let access = if new.perm.grants(AccessKind::Write) {
378 // Now we figure out which item grants our parent (`derived_from`) this kind of access.
379 // We use that to determine where to put the new item.
380 let granting_idx = self.find_granting(access, derived_from)
381 .ok_or_else(|| err_ub!(UbExperimental(format!(
382 "trying to reborrow for {:?}, but parent tag {:?} does not have an appropriate item in the borrow stack", new.perm, derived_from,
385 // Compute where to put the new item.
386 // Either way, we ensure that we insert the new item in a way such that between
387 // `derived_from` and the new one, there are only items *compatible with* `derived_from`.
388 let new_idx = if new.perm == Permission::SharedReadWrite {
389 assert!(access == AccessKind::Write, "this case only makes sense for stack-like accesses");
390 // SharedReadWrite can coexist with "existing loans", meaning they don't act like a write
391 // access. Instead of popping the stack, we insert the item at the place the stack would
392 // be popped to (i.e., we insert it above all the write-compatible items).
393 // This ensures F2b by adding the new item below any potentially existing `SharedReadOnly`.
394 self.find_first_write_incompatible(granting_idx)
396 // A "safe" reborrow for a pointer that actually expects some aliasing guarantees.
397 // Here, creating a reference actually counts as an access.
398 // This ensures F2b for `Unique`, by removing offending `SharedReadOnly`.
399 self.access(access, derived_from, global)?;
401 // We insert "as far up as possible": We know only compatible items are remaining
402 // on top of `derived_from`, and we want the new item at the top so that we
403 // get the strongest possible guarantees.
404 // This ensures U1 and F1.
408 // Put the new item there. As an optimization, deduplicate if it is equal to one of its new neighbors.
409 if self.borrows[new_idx-1] == new || self.borrows.get(new_idx) == Some(&new) {
410 // Optimization applies, done.
411 trace!("reborrow: avoiding adding redundant item {:?}", new);
413 trace!("reborrow: adding item {:?}", new);
414 self.borrows.insert(new_idx, new);
420 // # Stacked Borrows Core End
422 /// Map per-stack operations to higher-level per-location-range operations.
424 /// Creates new stack with initial tag.
431 let item = Item { perm, tag, protector: None };
437 stacks: RefCell::new(RangeMap::new(size, stack)),
442 /// Call `f` on every stack in the range.
447 f: impl Fn(&mut Stack, &GlobalState) -> InterpResult<'tcx>,
448 ) -> InterpResult<'tcx> {
449 let global = self.global.borrow();
450 let mut stacks = self.stacks.borrow_mut();
451 for stack in stacks.iter_mut(ptr.offset, size) {
458 /// Glue code to connect with Miri Machine Hooks
460 pub fn new_allocation(
464 kind: MemoryKind<MiriMemoryKind>,
466 let (tag, perm) = match kind {
468 // New unique borrow. This tag is not accessible by the program,
469 // so it will only ever be used when using the local directly (i.e.,
470 // not through a pointer). That is, whenever we directly write to a local, this will pop
471 // everything else off the stack, invalidating all previous pointers,
472 // and in particular, *all* raw pointers.
473 (Tag::Tagged(extra.borrow_mut().new_ptr()), Permission::Unique),
474 MemoryKind::Machine(MiriMemoryKind::Static) =>
475 (extra.borrow_mut().static_base_ptr(id), Permission::SharedReadWrite),
477 (Tag::Untagged, Permission::SharedReadWrite),
479 let stack = Stacks::new(size, perm, tag, extra);
484 pub fn memory_read<'tcx>(
488 ) -> InterpResult<'tcx> {
489 trace!("read access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
490 self.for_each(ptr, size, |stack, global| {
491 stack.access(AccessKind::Read, ptr.tag, global)?;
497 pub fn memory_written<'tcx>(
501 ) -> InterpResult<'tcx> {
502 trace!("write access with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
503 self.for_each(ptr, size, |stack, global| {
504 stack.access(AccessKind::Write, ptr.tag, global)?;
510 pub fn memory_deallocated<'tcx>(
514 ) -> InterpResult<'tcx> {
515 trace!("deallocation with tag {:?}: {:?}, size {}", ptr.tag, ptr.erase_tag(), size.bytes());
516 self.for_each(ptr, size, |stack, global| {
517 stack.dealloc(ptr.tag, global)
522 /// Retagging/reborrowing. There is some policy in here, such as which permissions
523 /// to grant for which references, and when to add protectors.
524 impl<'mir, 'tcx> EvalContextPrivExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
525 trait EvalContextPrivExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
528 place: MPlaceTy<'tcx, Tag>,
533 ) -> InterpResult<'tcx> {
534 let this = self.eval_context_mut();
535 let protector = if protect { Some(this.frame().extra) } else { None };
536 let ptr = this.memory.check_ptr_access(place.ptr, size, place.align)
537 .expect("validity checks should have excluded dangling/unaligned pointer")
538 .expect("we shouldn't get here for ZST");
539 trace!("reborrow: {} reference {:?} derived from {:?} (pointee {}): {:?}, size {}",
540 kind, new_tag, ptr.tag, place.layout.ty, ptr.erase_tag(), size.bytes());
542 // Get the allocation. It might not be mutable, so we cannot use `get_mut`.
543 let extra = &this.memory.get_raw(ptr.alloc_id)?.extra;
544 let stacked_borrows = extra.stacked_borrows.as_ref().expect("we should have Stacked Borrows data");
545 // Update the stacks.
546 // Make sure that raw pointers and mutable shared references are reborrowed "weak":
547 // There could be existing unique pointers reborrowed from them that should remain valid!
548 let perm = match kind {
549 RefKind::Unique { two_phase: false } => Permission::Unique,
550 RefKind::Unique { two_phase: true } => Permission::SharedReadWrite,
551 RefKind::Raw { mutable: true } => Permission::SharedReadWrite,
552 RefKind::Shared | RefKind::Raw { mutable: false } => {
553 // Shared references and *const are a whole different kind of game, the
554 // permission is not uniform across the entire range!
555 // We need a frozen-sensitive reborrow.
556 return this.visit_freeze_sensitive(place, size, |cur_ptr, size, frozen| {
557 // We are only ever `SharedReadOnly` inside the frozen bits.
558 let perm = if frozen { Permission::SharedReadOnly } else { Permission::SharedReadWrite };
559 let item = Item { perm, tag: new_tag, protector };
560 stacked_borrows.for_each(cur_ptr, size, |stack, global| {
561 stack.grant(cur_ptr.tag, item, global)
566 let item = Item { perm, tag: new_tag, protector };
567 stacked_borrows.for_each(ptr, size, |stack, global| {
568 stack.grant(ptr.tag, item, global)
572 /// Retags an indidual pointer, returning the retagged version.
573 /// `mutbl` can be `None` to make this a raw pointer.
576 val: ImmTy<'tcx, Tag>,
579 ) -> InterpResult<'tcx, Immediate<Tag>> {
580 let this = self.eval_context_mut();
581 // We want a place for where the ptr *points to*, so we get one.
582 let place = this.ref_to_mplace(val)?;
583 let size = this.size_and_align_of_mplace(place)?
584 .map(|(size, _)| size)
585 .unwrap_or_else(|| place.layout.size);
586 if size == Size::ZERO {
587 // Nothing to do for ZSTs.
590 let place = this.force_mplace_ptr(place)?;
592 // Compute new borrow.
593 let new_tag = match kind {
594 RefKind::Raw { .. } => Tag::Untagged,
595 _ => Tag::Tagged(this.memory.extra.stacked_borrows.borrow_mut().new_ptr()),
599 this.reborrow(place, size, kind, new_tag, protect)?;
600 let new_place = place.replace_tag(new_tag);
602 // Return new pointer.
603 Ok(new_place.to_ref())
607 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
608 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
612 place: PlaceTy<'tcx, Tag>
613 ) -> InterpResult<'tcx> {
614 let this = self.eval_context_mut();
615 // Determine mutability and whether to add a protector.
616 // Cannot use `builtin_deref` because that reports *immutable* for `Box`,
617 // making it useless.
618 fn qualify(ty: ty::Ty<'_>, kind: RetagKind) -> Option<(RefKind, bool)> {
620 // References are simple.
621 ty::Ref(_, _, Mutable) =>
622 Some((RefKind::Unique { two_phase: kind == RetagKind::TwoPhase}, kind == RetagKind::FnEntry)),
623 ty::Ref(_, _, Immutable) =>
624 Some((RefKind::Shared, kind == RetagKind::FnEntry)),
625 // Raw pointers need to be enabled.
626 ty::RawPtr(tym) if kind == RetagKind::Raw =>
627 Some((RefKind::Raw { mutable: tym.mutbl == Mutable }, false)),
628 // Boxes do not get a protector: protectors reflect that references outlive the call
629 // they were passed in to; that's just not the case for boxes.
630 ty::Adt(..) if ty.is_box() => Some((RefKind::Unique { two_phase: false }, false)),
635 // We only reborrow "bare" references/boxes.
636 // Not traversing into fields helps with <https://github.com/rust-lang/unsafe-code-guidelines/issues/125>,
637 // but might also cost us optimization and analyses. We will have to experiment more with this.
638 if let Some((mutbl, protector)) = qualify(place.layout.ty, kind) {
640 let val = this.read_immediate(this.place_to_op(place)?)?;
641 let val = this.retag_reference(val, mutbl, protector)?;
642 this.write_immediate(val, place)?;