miri/borrow_tracker/tree_borrows/tree.rs
1//! In this file we handle the "Tree" part of Tree Borrows, i.e. all tree
2//! traversal functions, optimizations to trim branches, and keeping track of
3//! the relative position of the access to each node being updated. This of course
4//! also includes the definition of the tree structure.
5//!
6//! Functions here manipulate permissions but are oblivious to them: as
7//! the internals of `Permission` are private, the update process is a black
8//! box. All we need to know here are
9//! - the fact that updates depend only on the old state, the status of protectors,
10//! and the relative position of the access;
11//! - idempotency properties asserted in `perms.rs` (for optimizations)
12
13use std::{fmt, mem};
14
15use rustc_abi::Size;
16use rustc_data_structures::fx::FxHashSet;
17use rustc_span::Span;
18use smallvec::SmallVec;
19
20use crate::borrow_tracker::tree_borrows::Permission;
21use crate::borrow_tracker::tree_borrows::diagnostics::{
22 self, NodeDebugInfo, TbError, TransitionError,
23};
24use crate::borrow_tracker::tree_borrows::foreign_access_skipping::IdempotentForeignAccess;
25use crate::borrow_tracker::tree_borrows::perms::PermTransition;
26use crate::borrow_tracker::tree_borrows::unimap::{UniEntry, UniIndex, UniKeyMap, UniValMap};
27use crate::borrow_tracker::{GlobalState, ProtectorKind};
28use crate::*;
29
30mod tests;
31
32/// Data for a single *location*.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub(super) struct LocationState {
35 /// A location is initialized when it is child-accessed for the first time (and the initial
36 /// retag initializes the location for the range covered by the type), and it then stays
37 /// initialized forever.
38 /// For initialized locations, "permission" is the current permission. However, for
39 /// uninitialized locations, we still need to track the "future initial permission": this will
40 /// start out to be `default_initial_perm`, but foreign accesses need to be taken into account.
41 /// Crucially however, while transitions to `Disabled` would usually be UB if this location is
42 /// protected, that is *not* the case for uninitialized locations. Instead we just have a latent
43 /// "future initial permission" of `Disabled`, causing UB only if an access is ever actually
44 /// performed.
45 /// Note that the tree root is also always initialized, as if the allocation was a write access.
46 initialized: bool,
47 /// This pointer's current permission / future initial permission.
48 permission: Permission,
49 /// See `foreign_access_skipping.rs`.
50 /// Stores an idempotent foreign access for this location and its children.
51 /// For correctness, this must not be too strong, and the recorded idempotent foreign access
52 /// of all children must be at least as strong as this. For performance, it should be as strong as possible.
53 idempotent_foreign_access: IdempotentForeignAccess,
54}
55
56impl LocationState {
57 /// Constructs a new initial state. It has neither been accessed, nor been subjected
58 /// to any foreign access yet.
59 /// The permission is not allowed to be `Active`.
60 /// `sifa` is the (strongest) idempotent foreign access, see `foreign_access_skipping.rs`
61 fn new_uninit(permission: Permission, sifa: IdempotentForeignAccess) -> Self {
62 assert!(permission.is_initial() || permission.is_disabled());
63 Self { permission, initialized: false, idempotent_foreign_access: sifa }
64 }
65
66 /// Constructs a new initial state. It has not yet been subjected
67 /// to any foreign access. However, it is already marked as having been accessed.
68 /// `sifa` is the (strongest) idempotent foreign access, see `foreign_access_skipping.rs`
69 fn new_init(permission: Permission, sifa: IdempotentForeignAccess) -> Self {
70 Self { permission, initialized: true, idempotent_foreign_access: sifa }
71 }
72
73 /// Check if the location has been initialized, i.e. if it has
74 /// ever been accessed through a child pointer.
75 pub fn is_initialized(&self) -> bool {
76 self.initialized
77 }
78
79 /// Check if the state can exist as the initial permission of a pointer.
80 ///
81 /// Do not confuse with `is_initialized`, the two are almost orthogonal
82 /// as apart from `Active` which is not initial and must be initialized,
83 /// any other permission can have an arbitrary combination of being
84 /// initial/initialized.
85 /// FIXME: when the corresponding `assert` in `tree_borrows/mod.rs` finally
86 /// passes and can be uncommented, remove this `#[allow(dead_code)]`.
87 #[cfg_attr(not(test), allow(dead_code))]
88 pub fn is_initial(&self) -> bool {
89 self.permission.is_initial()
90 }
91
92 pub fn permission(&self) -> Permission {
93 self.permission
94 }
95
96 /// Apply the effect of an access to one location, including
97 /// - applying `Permission::perform_access` to the inner `Permission`,
98 /// - emitting protector UB if the location is initialized,
99 /// - updating the initialized status (child accesses produce initialized locations).
100 fn perform_access(
101 &mut self,
102 access_kind: AccessKind,
103 rel_pos: AccessRelatedness,
104 protected: bool,
105 ) -> Result<PermTransition, TransitionError> {
106 let old_perm = self.permission;
107 let transition = Permission::perform_access(access_kind, rel_pos, old_perm, protected)
108 .ok_or(TransitionError::ChildAccessForbidden(old_perm))?;
109 self.initialized |= !rel_pos.is_foreign();
110 self.permission = transition.applied(old_perm).unwrap();
111 // Why do only initialized locations cause protector errors?
112 // Consider two mutable references `x`, `y` into disjoint parts of
113 // the same allocation. A priori, these may actually both be used to
114 // access the entire allocation, as long as only reads occur. However,
115 // a write to `y` needs to somehow record that `x` can no longer be used
116 // on that location at all. For these uninitialized locations (i.e., locations
117 // that haven't been accessed with `x` yet), we track the "future initial state":
118 // it defaults to whatever the initial state of the tag is,
119 // but the access to `y` moves that "future initial state" of `x` to `Disabled`.
120 // However, usually a `Reserved -> Disabled` transition would be UB due to the protector!
121 // So clearly protectors shouldn't fire for such "future initial state" transitions.
122 //
123 // See the test `two_mut_protected_same_alloc` in `tests/pass/tree_borrows/tree-borrows.rs`
124 // for an example of safe code that would be UB if we forgot to check `self.initialized`.
125 if protected && self.initialized && transition.produces_disabled() {
126 return Err(TransitionError::ProtectedDisabled(old_perm));
127 }
128 Ok(transition)
129 }
130
131 /// Like `perform_access`, but ignores the concrete error cause and also uses state-passing
132 /// rather than a mutable reference. As such, it returns `Some(x)` if the transition succeeded,
133 /// or `None` if there was an error.
134 #[cfg(test)]
135 fn perform_access_no_fluff(
136 mut self,
137 access_kind: AccessKind,
138 rel_pos: AccessRelatedness,
139 protected: bool,
140 ) -> Option<Self> {
141 match self.perform_access(access_kind, rel_pos, protected) {
142 Ok(_) => Some(self),
143 Err(_) => None,
144 }
145 }
146
147 /// Tree traversal optimizations. See `foreign_access_skipping.rs`.
148 /// This checks if such a foreign access can be skipped.
149 fn skip_if_known_noop(
150 &self,
151 access_kind: AccessKind,
152 rel_pos: AccessRelatedness,
153 ) -> ContinueTraversal {
154 if rel_pos.is_foreign() {
155 let happening_now = IdempotentForeignAccess::from_foreign(access_kind);
156 let mut new_access_noop =
157 self.idempotent_foreign_access.can_skip_foreign_access(happening_now);
158 if self.permission.is_disabled() {
159 // A foreign access to a `Disabled` tag will have almost no observable effect.
160 // It's a theorem that `Disabled` node have no protected initialized children,
161 // and so this foreign access will never trigger any protector.
162 // (Intuition: You're either protected initialized, and thus can't become Disabled
163 // or you're already Disabled protected, but not initialized, and then can't
164 // become initialized since that requires a child access, which Disabled blocks.)
165 // Further, the children will never be able to read or write again, since they
166 // have a `Disabled` parent. So this only affects diagnostics, such that the
167 // blocking write will still be identified directly, just at a different tag.
168 new_access_noop = true;
169 }
170 if self.permission.is_frozen() && access_kind == AccessKind::Read {
171 // A foreign read to a `Frozen` tag will have almost no observable effect.
172 // It's a theorem that `Frozen` nodes have no active children, so all children
173 // already survive foreign reads. Foreign reads in general have almost no
174 // effect, the only further thing they could do is make protected `Reserved`
175 // nodes become conflicted, i.e. make them reject child writes for the further
176 // duration of their protector. But such a child write is already rejected
177 // because this node is frozen. So this only affects diagnostics, but the
178 // blocking read will still be identified directly, just at a different tag.
179 new_access_noop = true;
180 }
181 if new_access_noop {
182 // Abort traversal if the new access is indeed guaranteed
183 // to be noop.
184 // No need to update `self.idempotent_foreign_access`,
185 // the type of the current streak among nonempty read-only
186 // or nonempty with at least one write has not changed.
187 ContinueTraversal::SkipSelfAndChildren
188 } else {
189 // Otherwise propagate this time, and also record the
190 // access that just occurred so that we can skip the propagation
191 // next time.
192 ContinueTraversal::Recurse
193 }
194 } else {
195 // A child access occurred, this breaks the streak of foreign
196 // accesses in a row and the sequence since the previous child access
197 // is now empty.
198 ContinueTraversal::Recurse
199 }
200 }
201
202 /// Records a new access, so that future access can potentially be skipped
203 /// by `skip_if_known_noop`. This must be called on child accesses, and otherwise
204 /// shoud be called on foreign accesses for increased performance. It should not be called
205 /// when `skip_if_known_noop` indicated skipping, since it then is a no-op.
206 /// See `foreign_access_skipping.rs`
207 fn record_new_access(&mut self, access_kind: AccessKind, rel_pos: AccessRelatedness) {
208 debug_assert!(matches!(
209 self.skip_if_known_noop(access_kind, rel_pos),
210 ContinueTraversal::Recurse
211 ));
212 self.idempotent_foreign_access
213 .record_new(IdempotentForeignAccess::from_acc_and_rel(access_kind, rel_pos));
214 }
215}
216
217impl fmt::Display for LocationState {
218 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219 write!(f, "{}", self.permission)?;
220 if !self.initialized {
221 write!(f, "?")?;
222 }
223 Ok(())
224 }
225}
226
227/// Tree structure with both parents and children since we want to be
228/// able to traverse the tree efficiently in both directions.
229#[derive(Clone, Debug)]
230pub struct Tree {
231 /// Mapping from tags to keys. The key obtained can then be used in
232 /// any of the `UniValMap` relative to this allocation, i.e. both the
233 /// `nodes` and `rperms` of the same `Tree`.
234 /// The parent-child relationship in `Node` is encoded in terms of these same
235 /// keys, so traversing the entire tree needs exactly one access to
236 /// `tag_mapping`.
237 pub(super) tag_mapping: UniKeyMap<BorTag>,
238 /// All nodes of this tree.
239 pub(super) nodes: UniValMap<Node>,
240 /// Maps a tag and a location to a perm, with possible lazy
241 /// initialization.
242 ///
243 /// NOTE: not all tags registered in `nodes` are necessarily in all
244 /// ranges of `rperms`, because `rperms` is in part lazily initialized.
245 /// Just because `nodes.get(key)` is `Some(_)` does not mean you can safely
246 /// `unwrap` any `perm.get(key)`.
247 ///
248 /// We do uphold the fact that `keys(perms)` is a subset of `keys(nodes)`
249 pub(super) rperms: RangeMap<UniValMap<LocationState>>,
250 /// The index of the root node.
251 pub(super) root: UniIndex,
252}
253
254/// A node in the borrow tree. Each node is uniquely identified by a tag via
255/// the `nodes` map of `Tree`.
256#[derive(Clone, Debug)]
257pub(super) struct Node {
258 /// The tag of this node.
259 pub tag: BorTag,
260 /// All tags except the root have a parent tag.
261 pub parent: Option<UniIndex>,
262 /// If the pointer was reborrowed, it has children.
263 // FIXME: bench to compare this to FxHashSet and to other SmallVec sizes
264 pub children: SmallVec<[UniIndex; 4]>,
265 /// Either `Reserved`, `Frozen`, or `Disabled`, it is the permission this tag will
266 /// lazily be initialized to on the first access.
267 /// It is only ever `Disabled` for a tree root, since the root is initialized to `Active` by
268 /// its own separate mechanism.
269 default_initial_perm: Permission,
270 /// The default initial (strongest) idempotent foreign access.
271 /// This participates in the invariant for `LocationState::idempotent_foreign_access`
272 /// in cases where there is no location state yet. See `foreign_access_skipping.rs`,
273 /// and `LocationState::idempotent_foreign_access` for more information
274 default_initial_idempotent_foreign_access: IdempotentForeignAccess,
275 /// Some extra information useful only for debugging purposes
276 pub debug_info: NodeDebugInfo,
277}
278
279/// Data given to the transition function
280struct NodeAppArgs<'node> {
281 /// Node on which the transition is currently being applied
282 node: &'node mut Node,
283 /// Mutable access to its permissions
284 perm: UniEntry<'node, LocationState>,
285 /// Relative position of the access
286 rel_pos: AccessRelatedness,
287}
288/// Data given to the error handler
289struct ErrHandlerArgs<'node, InErr> {
290 /// Kind of error that occurred
291 error_kind: InErr,
292 /// Tag that triggered the error (not the tag that was accessed,
293 /// rather the parent tag that had insufficient permissions or the
294 /// non-parent tag that had a protector).
295 conflicting_info: &'node NodeDebugInfo,
296 /// Information about the tag that was accessed just before the
297 /// error was triggered.
298 accessed_info: &'node NodeDebugInfo,
299}
300/// Internal contents of `Tree` with the minimum of mutable access for
301/// the purposes of the tree traversal functions: the permissions (`perms`) can be
302/// updated but not the tree structure (`tag_mapping` and `nodes`)
303struct TreeVisitor<'tree> {
304 tag_mapping: &'tree UniKeyMap<BorTag>,
305 nodes: &'tree mut UniValMap<Node>,
306 perms: &'tree mut UniValMap<LocationState>,
307}
308
309/// Whether to continue exploring the children recursively or not.
310enum ContinueTraversal {
311 Recurse,
312 SkipSelfAndChildren,
313}
314
315#[derive(Clone, Copy)]
316pub enum ChildrenVisitMode {
317 VisitChildrenOfAccessed,
318 SkipChildrenOfAccessed,
319}
320
321enum RecursionState {
322 BeforeChildren,
323 AfterChildren,
324}
325
326/// Stack of nodes left to explore in a tree traversal.
327/// See the docs of `traverse_this_parents_children_other` for details on the
328/// traversal order.
329struct TreeVisitorStack<NodeContinue, NodeApp, ErrHandler> {
330 /// Identifier of the original access.
331 initial: UniIndex,
332 /// Function describing whether to continue at a tag.
333 /// This is only invoked for foreign accesses.
334 f_continue: NodeContinue,
335 /// Function to apply to each tag.
336 f_propagate: NodeApp,
337 /// Handler to add the required context to diagnostics.
338 err_builder: ErrHandler,
339 /// Mutable state of the visit: the tags left to handle.
340 /// Every tag pushed should eventually be handled,
341 /// and the precise order is relevant for diagnostics.
342 /// Since the traversal is piecewise bottom-up, we need to
343 /// remember whether we're here initially, or after visiting all children.
344 /// The last element indicates this.
345 /// This is just an artifact of how you hand-roll recursion,
346 /// it does not have a deeper meaning otherwise.
347 stack: Vec<(UniIndex, AccessRelatedness, RecursionState)>,
348}
349
350impl<NodeContinue, NodeApp, InnErr, OutErr, ErrHandler>
351 TreeVisitorStack<NodeContinue, NodeApp, ErrHandler>
352where
353 NodeContinue: Fn(&NodeAppArgs<'_>) -> ContinueTraversal,
354 NodeApp: Fn(NodeAppArgs<'_>) -> Result<(), InnErr>,
355 ErrHandler: Fn(ErrHandlerArgs<'_, InnErr>) -> OutErr,
356{
357 fn should_continue_at(
358 &self,
359 this: &mut TreeVisitor<'_>,
360 idx: UniIndex,
361 rel_pos: AccessRelatedness,
362 ) -> ContinueTraversal {
363 let node = this.nodes.get_mut(idx).unwrap();
364 let args = NodeAppArgs { node, perm: this.perms.entry(idx), rel_pos };
365 (self.f_continue)(&args)
366 }
367
368 fn propagate_at(
369 &mut self,
370 this: &mut TreeVisitor<'_>,
371 idx: UniIndex,
372 rel_pos: AccessRelatedness,
373 ) -> Result<(), OutErr> {
374 let node = this.nodes.get_mut(idx).unwrap();
375 (self.f_propagate)(NodeAppArgs { node, perm: this.perms.entry(idx), rel_pos }).map_err(
376 |error_kind| {
377 (self.err_builder)(ErrHandlerArgs {
378 error_kind,
379 conflicting_info: &this.nodes.get(idx).unwrap().debug_info,
380 accessed_info: &this.nodes.get(self.initial).unwrap().debug_info,
381 })
382 },
383 )
384 }
385
386 fn go_upwards_from_accessed(
387 &mut self,
388 this: &mut TreeVisitor<'_>,
389 accessed_node: UniIndex,
390 visit_children: ChildrenVisitMode,
391 ) -> Result<(), OutErr> {
392 // We want to visit the accessed node's children first.
393 // However, we will below walk up our parents and push their children (our cousins)
394 // onto the stack. To ensure correct iteration order, this method thus finishes
395 // by reversing the stack. This only works if the stack is empty initially.
396 assert!(self.stack.is_empty());
397 // First, handle accessed node. A bunch of things need to
398 // be handled differently here compared to the further parents
399 // of `accesssed_node`.
400 {
401 self.propagate_at(this, accessed_node, AccessRelatedness::This)?;
402 if matches!(visit_children, ChildrenVisitMode::VisitChildrenOfAccessed) {
403 let accessed_node = this.nodes.get(accessed_node).unwrap();
404 // We `rev()` here because we reverse the entire stack later.
405 for &child in accessed_node.children.iter().rev() {
406 self.stack.push((
407 child,
408 AccessRelatedness::AncestorAccess,
409 RecursionState::BeforeChildren,
410 ));
411 }
412 }
413 }
414 // Then, handle the accessed node's parents. Here, we need to
415 // make sure we only mark the "cousin" subtrees for later visitation,
416 // not the subtree that contains the accessed node.
417 let mut last_node = accessed_node;
418 while let Some(current) = this.nodes.get(last_node).unwrap().parent {
419 self.propagate_at(this, current, AccessRelatedness::StrictChildAccess)?;
420 let node = this.nodes.get(current).unwrap();
421 // We `rev()` here because we reverse the entire stack later.
422 for &child in node.children.iter().rev() {
423 if last_node == child {
424 continue;
425 }
426 self.stack.push((
427 child,
428 AccessRelatedness::CousinAccess,
429 RecursionState::BeforeChildren,
430 ));
431 }
432 last_node = current;
433 }
434 // Reverse the stack, as discussed above.
435 self.stack.reverse();
436 Ok(())
437 }
438
439 fn finish_foreign_accesses(&mut self, this: &mut TreeVisitor<'_>) -> Result<(), OutErr> {
440 while let Some((idx, rel_pos, step)) = self.stack.last_mut() {
441 let idx = *idx;
442 let rel_pos = *rel_pos;
443 match *step {
444 // How to do bottom-up traversal, 101: Before you handle a node, you handle all children.
445 // For this, you must first find the children, which is what this code here does.
446 RecursionState::BeforeChildren => {
447 // Next time we come back will be when all the children are handled.
448 *step = RecursionState::AfterChildren;
449 // Now push the children, except if we are told to skip this subtree.
450 let handle_children = self.should_continue_at(this, idx, rel_pos);
451 match handle_children {
452 ContinueTraversal::Recurse => {
453 let node = this.nodes.get(idx).unwrap();
454 for &child in node.children.iter() {
455 self.stack.push((child, rel_pos, RecursionState::BeforeChildren));
456 }
457 }
458 ContinueTraversal::SkipSelfAndChildren => {
459 // skip self
460 self.stack.pop();
461 continue;
462 }
463 }
464 }
465 // All the children are handled, let's actually visit this node
466 RecursionState::AfterChildren => {
467 self.stack.pop();
468 self.propagate_at(this, idx, rel_pos)?;
469 }
470 }
471 }
472 Ok(())
473 }
474
475 fn new(
476 initial: UniIndex,
477 f_continue: NodeContinue,
478 f_propagate: NodeApp,
479 err_builder: ErrHandler,
480 ) -> Self {
481 Self { initial, f_continue, f_propagate, err_builder, stack: Vec::new() }
482 }
483}
484
485impl<'tree> TreeVisitor<'tree> {
486 /// Applies `f_propagate` to every vertex of the tree in a piecewise bottom-up way: First, visit
487 /// all ancestors of `start` (starting with `start` itself), then children of `start`, then the rest,
488 /// going bottom-up in each of these two "pieces" / sections.
489 /// This ensures that errors are triggered in the following order
490 /// - first invalid accesses with insufficient permissions, closest to the accessed node first,
491 /// - then protector violations, bottom-up, starting with the children of the accessed node, and then
492 /// going upwards and outwards.
493 ///
494 /// The following graphic visualizes it, with numbers indicating visitation order and `start` being
495 /// the node that is visited first ("1"):
496 ///
497 /// ```text
498 /// 3
499 /// /|
500 /// / |
501 /// 9 2
502 /// | |\
503 /// | | \
504 /// 8 1 7
505 /// / \
506 /// 4 6
507 /// |
508 /// 5
509 /// ```
510 ///
511 /// `f_propagate` should follow the following format: for a given `Node` it updates its
512 /// `Permission` depending on the position relative to `start` (given by an
513 /// `AccessRelatedness`).
514 /// `f_continue` is called earlier on foreign nodes, and describes whether to even start
515 /// visiting the subtree at that node. If it e.g. returns `SkipSelfAndChildren` on node 6
516 /// above, then nodes 5 _and_ 6 would not be visited by `f_propagate`. It is not used for
517 /// notes having a child access (nodes 1, 2, 3).
518 ///
519 /// Finally, remember that the iteration order is not relevant for UB, it only affects
520 /// diagnostics. It also affects tree traversal optimizations built on top of this, so
521 /// those need to be reviewed carefully as well whenever this changes.
522 fn traverse_this_parents_children_other<InnErr, OutErr>(
523 mut self,
524 start: BorTag,
525 f_continue: impl Fn(&NodeAppArgs<'_>) -> ContinueTraversal,
526 f_propagate: impl Fn(NodeAppArgs<'_>) -> Result<(), InnErr>,
527 err_builder: impl Fn(ErrHandlerArgs<'_, InnErr>) -> OutErr,
528 ) -> Result<(), OutErr> {
529 let start_idx = self.tag_mapping.get(&start).unwrap();
530 let mut stack = TreeVisitorStack::new(start_idx, f_continue, f_propagate, err_builder);
531 // Visits the accessed node itself, and all its parents, i.e. all nodes
532 // undergoing a child access. Also pushes the children and the other
533 // cousin nodes (i.e. all nodes undergoing a foreign access) to the stack
534 // to be processed later.
535 stack.go_upwards_from_accessed(
536 &mut self,
537 start_idx,
538 ChildrenVisitMode::VisitChildrenOfAccessed,
539 )?;
540 // Now visit all the foreign nodes we remembered earlier.
541 // For this we go bottom-up, but also allow f_continue to skip entire
542 // subtrees from being visited if it would be a NOP.
543 stack.finish_foreign_accesses(&mut self)
544 }
545
546 /// Like `traverse_this_parents_children_other`, but skips the children of `start`.
547 fn traverse_nonchildren<InnErr, OutErr>(
548 mut self,
549 start: BorTag,
550 f_continue: impl Fn(&NodeAppArgs<'_>) -> ContinueTraversal,
551 f_propagate: impl Fn(NodeAppArgs<'_>) -> Result<(), InnErr>,
552 err_builder: impl Fn(ErrHandlerArgs<'_, InnErr>) -> OutErr,
553 ) -> Result<(), OutErr> {
554 let start_idx = self.tag_mapping.get(&start).unwrap();
555 let mut stack = TreeVisitorStack::new(start_idx, f_continue, f_propagate, err_builder);
556 // Visits the accessed node itself, and all its parents, i.e. all nodes
557 // undergoing a child access. Also pushes the other cousin nodes to the
558 // stack, but not the children of the accessed node.
559 stack.go_upwards_from_accessed(
560 &mut self,
561 start_idx,
562 ChildrenVisitMode::SkipChildrenOfAccessed,
563 )?;
564 // Now visit all the foreign nodes we remembered earlier.
565 // For this we go bottom-up, but also allow f_continue to skip entire
566 // subtrees from being visited if it would be a NOP.
567 stack.finish_foreign_accesses(&mut self)
568 }
569}
570
571impl Tree {
572 /// Create a new tree, with only a root pointer.
573 pub fn new(root_tag: BorTag, size: Size, span: Span) -> Self {
574 // The root has `Disabled` as the default permission,
575 // so that any access out of bounds is invalid.
576 let root_default_perm = Permission::new_disabled();
577 let mut tag_mapping = UniKeyMap::default();
578 let root_idx = tag_mapping.insert(root_tag);
579 let nodes = {
580 let mut nodes = UniValMap::<Node>::default();
581 let mut debug_info = NodeDebugInfo::new(root_tag, root_default_perm, span);
582 // name the root so that all allocations contain one named pointer
583 debug_info.add_name("root of the allocation");
584 nodes.insert(
585 root_idx,
586 Node {
587 tag: root_tag,
588 parent: None,
589 children: SmallVec::default(),
590 default_initial_perm: root_default_perm,
591 // The root may never be skipped, all accesses will be local.
592 default_initial_idempotent_foreign_access: IdempotentForeignAccess::None,
593 debug_info,
594 },
595 );
596 nodes
597 };
598 let rperms = {
599 let mut perms = UniValMap::default();
600 // We manually set it to `Active` on all in-bounds positions.
601 // We also ensure that it is initialized, so that no `Active` but
602 // not yet initialized nodes exist. Essentially, we pretend there
603 // was a write that initialized these to `Active`.
604 perms.insert(
605 root_idx,
606 LocationState::new_init(Permission::new_active(), IdempotentForeignAccess::None),
607 );
608 RangeMap::new(size, perms)
609 };
610 Self { root: root_idx, nodes, rperms, tag_mapping }
611 }
612}
613
614impl<'tcx> Tree {
615 /// Insert a new tag in the tree
616 pub fn new_child(
617 &mut self,
618 parent_tag: BorTag,
619 new_tag: BorTag,
620 default_initial_perm: Permission,
621 reborrow_range: AllocRange,
622 span: Span,
623 prot: bool,
624 ) -> InterpResult<'tcx> {
625 assert!(!self.tag_mapping.contains_key(&new_tag));
626 let idx = self.tag_mapping.insert(new_tag);
627 let parent_idx = self.tag_mapping.get(&parent_tag).unwrap();
628 let strongest_idempotent = default_initial_perm.strongest_idempotent_foreign_access(prot);
629 // Create the node
630 self.nodes.insert(
631 idx,
632 Node {
633 tag: new_tag,
634 parent: Some(parent_idx),
635 children: SmallVec::default(),
636 default_initial_perm,
637 default_initial_idempotent_foreign_access: strongest_idempotent,
638 debug_info: NodeDebugInfo::new(new_tag, default_initial_perm, span),
639 },
640 );
641 // Register new_tag as a child of parent_tag
642 self.nodes.get_mut(parent_idx).unwrap().children.push(idx);
643 // Initialize perms
644 let perm = LocationState::new_init(default_initial_perm, strongest_idempotent);
645 for (_perms_range, perms) in self.rperms.iter_mut(reborrow_range.start, reborrow_range.size)
646 {
647 perms.insert(idx, perm);
648 }
649
650 // Inserting the new perms might have broken the SIFA invariant (see `foreign_access_skipping.rs`).
651 // We now weaken the recorded SIFA for our parents, until the invariant is restored.
652 // We could weaken them all to `LocalAccess`, but it is more efficient to compute the SIFA
653 // for the new permission statically, and use that.
654 self.update_last_accessed_after_retag(parent_idx, strongest_idempotent);
655
656 interp_ok(())
657 }
658
659 /// Restores the SIFA "children are stronger" invariant after a retag.
660 /// See `foreign_access_skipping` and `new_child`.
661 fn update_last_accessed_after_retag(
662 &mut self,
663 mut current: UniIndex,
664 strongest_allowed: IdempotentForeignAccess,
665 ) {
666 // We walk the tree upwards, until the invariant is restored
667 loop {
668 let current_node = self.nodes.get_mut(current).unwrap();
669 // Call `ensure_no_stronger_than` on all SIFAs for this node: the per-location SIFA, as well
670 // as the default SIFA for not-yet-initialized locations.
671 // Record whether we did any change; if not, the invariant is restored and we can stop the traversal.
672 let mut any_change = false;
673 for (_, map) in self.rperms.iter_mut_all() {
674 // Check if this node has a state for this location (or range of locations).
675 if let Some(perm) = map.get_mut(current) {
676 // Update the per-location SIFA, recording if it changed.
677 any_change |=
678 perm.idempotent_foreign_access.ensure_no_stronger_than(strongest_allowed);
679 }
680 }
681 // Now update `default_initial_idempotent_foreign_access`, which stores the default SIFA for not-yet-initialized locations.
682 any_change |= current_node
683 .default_initial_idempotent_foreign_access
684 .ensure_no_stronger_than(strongest_allowed);
685
686 if any_change {
687 let Some(next) = self.nodes.get(current).unwrap().parent else {
688 // We have arrived at the root.
689 break;
690 };
691 current = next;
692 continue;
693 } else {
694 break;
695 }
696 }
697 }
698
699 /// Deallocation requires
700 /// - a pointer that permits write accesses
701 /// - the absence of Strong Protectors anywhere in the allocation
702 pub fn dealloc(
703 &mut self,
704 tag: BorTag,
705 access_range: AllocRange,
706 global: &GlobalState,
707 alloc_id: AllocId, // diagnostics
708 span: Span, // diagnostics
709 ) -> InterpResult<'tcx> {
710 self.perform_access(
711 tag,
712 Some((access_range, AccessKind::Write, diagnostics::AccessCause::Dealloc)),
713 global,
714 alloc_id,
715 span,
716 )?;
717 for (perms_range, perms) in self.rperms.iter_mut(access_range.start, access_range.size) {
718 TreeVisitor { nodes: &mut self.nodes, tag_mapping: &self.tag_mapping, perms }
719 .traverse_this_parents_children_other(
720 tag,
721 // visit all children, skipping none
722 |_| ContinueTraversal::Recurse,
723 |args: NodeAppArgs<'_>| -> Result<(), TransitionError> {
724 let NodeAppArgs { node, perm, .. } = args;
725 let perm =
726 perm.get().copied().unwrap_or_else(|| node.default_location_state());
727 if global.borrow().protected_tags.get(&node.tag)
728 == Some(&ProtectorKind::StrongProtector)
729 // Don't check for protector if it is a Cell (see `unsafe_cell_deallocate` in `interior_mutability.rs`).
730 // Related to https://github.com/rust-lang/rust/issues/55005.
731 && !perm.permission().is_cell()
732 {
733 Err(TransitionError::ProtectedDealloc)
734 } else {
735 Ok(())
736 }
737 },
738 |args: ErrHandlerArgs<'_, TransitionError>| -> InterpErrorKind<'tcx> {
739 let ErrHandlerArgs { error_kind, conflicting_info, accessed_info } = args;
740 TbError {
741 conflicting_info,
742 access_cause: diagnostics::AccessCause::Dealloc,
743 alloc_id,
744 error_offset: perms_range.start,
745 error_kind,
746 accessed_info,
747 }
748 .build()
749 },
750 )?;
751 }
752 interp_ok(())
753 }
754
755 /// Map the per-node and per-location `LocationState::perform_access`
756 /// to each location of the first component of `access_range_and_kind`,
757 /// on every tag of the allocation.
758 ///
759 /// If `access_range_and_kind` is `None`, this is interpreted as the special
760 /// access that is applied on protector release:
761 /// - the access will be applied only to initialized locations of the allocation,
762 /// - it will not be visible to children,
763 /// - it will be recorded as a `FnExit` diagnostic access
764 /// - and it will be a read except if the location is `Active`, i.e. has been written to,
765 /// in which case it will be a write.
766 ///
767 /// `LocationState::perform_access` will take care of raising transition
768 /// errors and updating the `initialized` status of each location,
769 /// this traversal adds to that:
770 /// - inserting into the map locations that do not exist yet,
771 /// - trimming the traversal,
772 /// - recording the history.
773 pub fn perform_access(
774 &mut self,
775 tag: BorTag,
776 access_range_and_kind: Option<(AllocRange, AccessKind, diagnostics::AccessCause)>,
777 global: &GlobalState,
778 alloc_id: AllocId, // diagnostics
779 span: Span, // diagnostics
780 ) -> InterpResult<'tcx> {
781 use std::ops::Range;
782 // Performs the per-node work:
783 // - insert the permission if it does not exist
784 // - perform the access
785 // - record the transition
786 // to which some optimizations are added:
787 // - skip the traversal of the children in some cases
788 // - do not record noop transitions
789 //
790 // `perms_range` is only for diagnostics (it is the range of
791 // the `RangeMap` on which we are currently working).
792 let node_skipper = |access_kind: AccessKind, args: &NodeAppArgs<'_>| -> ContinueTraversal {
793 let NodeAppArgs { node, perm, rel_pos } = args;
794
795 let old_state = perm.get().copied().unwrap_or_else(|| node.default_location_state());
796 old_state.skip_if_known_noop(access_kind, *rel_pos)
797 };
798 let node_app = |perms_range: Range<u64>,
799 access_kind: AccessKind,
800 access_cause: diagnostics::AccessCause,
801 args: NodeAppArgs<'_>|
802 -> Result<(), TransitionError> {
803 let NodeAppArgs { node, mut perm, rel_pos } = args;
804
805 let old_state = perm.or_insert(node.default_location_state());
806
807 // Call this function now, which ensures it is only called when
808 // `skip_if_known_noop` returns `Recurse`, due to the contract of
809 // `traverse_this_parents_children_other`.
810 old_state.record_new_access(access_kind, rel_pos);
811
812 let protected = global.borrow().protected_tags.contains_key(&node.tag);
813 let transition = old_state.perform_access(access_kind, rel_pos, protected)?;
814 // Record the event as part of the history
815 if !transition.is_noop() {
816 node.debug_info.history.push(diagnostics::Event {
817 transition,
818 is_foreign: rel_pos.is_foreign(),
819 access_cause,
820 access_range: access_range_and_kind.map(|x| x.0),
821 transition_range: perms_range,
822 span,
823 });
824 }
825 Ok(())
826 };
827
828 // Error handler in case `node_app` goes wrong.
829 // Wraps the faulty transition in more context for diagnostics.
830 let err_handler = |perms_range: Range<u64>,
831 access_cause: diagnostics::AccessCause,
832 args: ErrHandlerArgs<'_, TransitionError>|
833 -> InterpErrorKind<'tcx> {
834 let ErrHandlerArgs { error_kind, conflicting_info, accessed_info } = args;
835 TbError {
836 conflicting_info,
837 access_cause,
838 alloc_id,
839 error_offset: perms_range.start,
840 error_kind,
841 accessed_info,
842 }
843 .build()
844 };
845
846 if let Some((access_range, access_kind, access_cause)) = access_range_and_kind {
847 // Default branch: this is a "normal" access through a known range.
848 // We iterate over affected locations and traverse the tree for each of them.
849 for (perms_range, perms) in self.rperms.iter_mut(access_range.start, access_range.size)
850 {
851 TreeVisitor { nodes: &mut self.nodes, tag_mapping: &self.tag_mapping, perms }
852 .traverse_this_parents_children_other(
853 tag,
854 |args| node_skipper(access_kind, args),
855 |args| node_app(perms_range.clone(), access_kind, access_cause, args),
856 |args| err_handler(perms_range.clone(), access_cause, args),
857 )?;
858 }
859 } else {
860 // This is a special access through the entire allocation.
861 // It actually only affects `initialized` locations, so we need
862 // to filter on those before initiating the traversal.
863 //
864 // In addition this implicit access should not be visible to children,
865 // thus the use of `traverse_nonchildren`.
866 // See the test case `returned_mut_is_usable` from
867 // `tests/pass/tree_borrows/tree-borrows.rs` for an example of
868 // why this is important.
869 for (perms_range, perms) in self.rperms.iter_mut_all() {
870 let idx = self.tag_mapping.get(&tag).unwrap();
871 // Only visit initialized permissions
872 if let Some(p) = perms.get(idx)
873 && let Some(access_kind) = p.permission.protector_end_access()
874 && p.initialized
875 {
876 let access_cause = diagnostics::AccessCause::FnExit(access_kind);
877 TreeVisitor { nodes: &mut self.nodes, tag_mapping: &self.tag_mapping, perms }
878 .traverse_nonchildren(
879 tag,
880 |args| node_skipper(access_kind, args),
881 |args| node_app(perms_range.clone(), access_kind, access_cause, args),
882 |args| err_handler(perms_range.clone(), access_cause, args),
883 )?;
884 }
885 }
886 }
887 interp_ok(())
888 }
889}
890
891/// Integration with the BorTag garbage collector
892impl Tree {
893 pub fn remove_unreachable_tags(&mut self, live_tags: &FxHashSet<BorTag>) {
894 self.remove_useless_children(self.root, live_tags);
895 // Right after the GC runs is a good moment to check if we can
896 // merge some adjacent ranges that were made equal by the removal of some
897 // tags (this does not necessarily mean that they have identical internal representations,
898 // see the `PartialEq` impl for `UniValMap`)
899 self.rperms.merge_adjacent_thorough();
900 }
901
902 /// Checks if a node is useless and should be GC'ed.
903 /// A node is useless if it has no children and also the tag is no longer live.
904 fn is_useless(&self, idx: UniIndex, live: &FxHashSet<BorTag>) -> bool {
905 let node = self.nodes.get(idx).unwrap();
906 node.children.is_empty() && !live.contains(&node.tag)
907 }
908
909 /// Checks whether a node can be replaced by its only child.
910 /// If so, returns the index of said only child.
911 /// If not, returns none.
912 fn can_be_replaced_by_single_child(
913 &self,
914 idx: UniIndex,
915 live: &FxHashSet<BorTag>,
916 ) -> Option<UniIndex> {
917 let node = self.nodes.get(idx).unwrap();
918
919 let [child_idx] = node.children[..] else { return None };
920
921 // We never want to replace the root node, as it is also kept in `root_ptr_tags`.
922 if live.contains(&node.tag) || node.parent.is_none() {
923 return None;
924 }
925 // Since protected nodes are never GC'd (see `borrow_tracker::FrameExtra::visit_provenance`),
926 // we know that `node` is not protected because otherwise `live` would
927 // have contained `node.tag`.
928 let child = self.nodes.get(child_idx).unwrap();
929 // Check that for that one child, `can_be_replaced_by_child` holds for the permission
930 // on all locations.
931 for (_, data) in self.rperms.iter_all() {
932 let parent_perm =
933 data.get(idx).map(|x| x.permission).unwrap_or_else(|| node.default_initial_perm);
934 let child_perm = data
935 .get(child_idx)
936 .map(|x| x.permission)
937 .unwrap_or_else(|| child.default_initial_perm);
938 if !parent_perm.can_be_replaced_by_child(child_perm) {
939 return None;
940 }
941 }
942
943 Some(child_idx)
944 }
945
946 /// Properly removes a node.
947 /// The node to be removed should not otherwise be usable. It also
948 /// should have no children, but this is not checked, so that nodes
949 /// whose children were rotated somewhere else can be deleted without
950 /// having to first modify them to clear that array.
951 fn remove_useless_node(&mut self, this: UniIndex) {
952 // Due to the API of UniMap we must make sure to call
953 // `UniValMap::remove` for the key of this node on *all* maps that used it
954 // (which are `self.nodes` and every range of `self.rperms`)
955 // before we can safely apply `UniKeyMap::remove` to truly remove
956 // this tag from the `tag_mapping`.
957 let node = self.nodes.remove(this).unwrap();
958 for (_perms_range, perms) in self.rperms.iter_mut_all() {
959 perms.remove(this);
960 }
961 self.tag_mapping.remove(&node.tag);
962 }
963
964 /// Traverses the entire tree looking for useless tags.
965 /// Removes from the tree all useless child nodes of root.
966 /// It will not delete the root itself.
967 ///
968 /// NOTE: This leaves in the middle of the tree tags that are unreachable but have
969 /// reachable children. There is a potential for compacting the tree by reassigning
970 /// children of dead tags to the nearest live parent, but it must be done with care
971 /// not to remove UB.
972 ///
973 /// Example: Consider the tree `root - parent - child`, with `parent: Frozen` and
974 /// `child: Reserved`. This tree can exist. If we blindly delete `parent` and reassign
975 /// `child` to be a direct child of `root` then Writes to `child` are now permitted
976 /// whereas they were not when `parent` was still there.
977 fn remove_useless_children(&mut self, root: UniIndex, live: &FxHashSet<BorTag>) {
978 // To avoid stack overflows, we roll our own stack.
979 // Each element in the stack consists of the current tag, and the number of the
980 // next child to be processed.
981
982 // The other functions are written using the `TreeVisitorStack`, but that does not work here
983 // since we need to 1) do a post-traversal and 2) remove nodes from the tree.
984 // Since we do a post-traversal (by deleting nodes only after handling all children),
985 // we also need to be a bit smarter than "pop node, push all children."
986 let mut stack = vec![(root, 0)];
987 while let Some((tag, nth_child)) = stack.last_mut() {
988 let node = self.nodes.get(*tag).unwrap();
989 if *nth_child < node.children.len() {
990 // Visit the child by pushing it to the stack.
991 // Also increase `nth_child` so that when we come back to the `tag` node, we
992 // look at the next child.
993 let next_child = node.children[*nth_child];
994 *nth_child += 1;
995 stack.push((next_child, 0));
996 continue;
997 } else {
998 // We have processed all children of `node`, so now it is time to process `node` itself.
999 // First, get the current children of `node`. To appease the borrow checker,
1000 // we have to temporarily move the list out of the node, and then put the
1001 // list of remaining children back in.
1002 let mut children_of_node =
1003 mem::take(&mut self.nodes.get_mut(*tag).unwrap().children);
1004 // Remove all useless children.
1005 children_of_node.retain_mut(|idx| {
1006 if self.is_useless(*idx, live) {
1007 // Delete `idx` node everywhere else.
1008 self.remove_useless_node(*idx);
1009 // And delete it from children_of_node.
1010 false
1011 } else {
1012 if let Some(nextchild) = self.can_be_replaced_by_single_child(*idx, live) {
1013 // `nextchild` is our grandchild, and will become our direct child.
1014 // Delete the in-between node, `idx`.
1015 self.remove_useless_node(*idx);
1016 // Set the new child's parent.
1017 self.nodes.get_mut(nextchild).unwrap().parent = Some(*tag);
1018 // Save the new child in children_of_node.
1019 *idx = nextchild;
1020 }
1021 // retain it
1022 true
1023 }
1024 });
1025 // Put back the now-filtered vector.
1026 self.nodes.get_mut(*tag).unwrap().children = children_of_node;
1027
1028 // We are done, the parent can continue.
1029 stack.pop();
1030 continue;
1031 }
1032 }
1033 }
1034}
1035
1036impl Node {
1037 pub fn default_location_state(&self) -> LocationState {
1038 LocationState::new_uninit(
1039 self.default_initial_perm,
1040 self.default_initial_idempotent_foreign_access,
1041 )
1042 }
1043}
1044
1045impl VisitProvenance for Tree {
1046 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
1047 // To ensure that the root never gets removed, we visit it
1048 // (the `root` node of `Tree` is not an `Option<_>`)
1049 visit(None, Some(self.nodes.get(self.root).unwrap().tag))
1050 }
1051}
1052
1053/// Relative position of the access
1054#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1055pub enum AccessRelatedness {
1056 /// The accessed pointer is the current one
1057 This,
1058 /// The accessed pointer is a (transitive) child of the current one.
1059 // Current pointer is excluded (unlike in some other places of this module
1060 // where "child" is inclusive).
1061 StrictChildAccess,
1062 /// The accessed pointer is a (transitive) parent of the current one.
1063 // Current pointer is excluded.
1064 AncestorAccess,
1065 /// The accessed pointer is neither of the above.
1066 // It's a cousin/uncle/etc., something in a side branch.
1067 CousinAccess,
1068}
1069
1070impl AccessRelatedness {
1071 /// Check that access is either Ancestor or Distant, i.e. not
1072 /// a transitive child (initial pointer included).
1073 pub fn is_foreign(self) -> bool {
1074 matches!(self, AccessRelatedness::AncestorAccess | AccessRelatedness::CousinAccess)
1075 }
1076
1077 /// Given the AccessRelatedness for the parent node, compute the AccessRelatedness
1078 /// for the child node. This function assumes that we propagate away from the initial
1079 /// access.
1080 pub fn for_child(self) -> Self {
1081 use AccessRelatedness::*;
1082 match self {
1083 AncestorAccess | This => AncestorAccess,
1084 StrictChildAccess | CousinAccess => CousinAccess,
1085 }
1086 }
1087}