1use std::cell::RefCell;
2use std::num::NonZero;
3use std::{fmt, mem};
4
5use rustc_abi::Size;
6use rustc_data_structures::fx::{FxHashMap, FxHashSet};
7use rustc_middle::ty::Ty;
8use smallvec::SmallVec;
9
10use crate::*;
11pub mod stacked_borrows;
12pub mod tree_borrows;
13
14#[derive(Copy, Clone, Hash, PartialEq, Eq, Debug)]
16pub enum AccessKind {
17 Read,
18 Write,
19}
20
21impl fmt::Display for AccessKind {
22 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23 match self {
24 AccessKind::Read => write!(f, "read access"),
25 AccessKind::Write => write!(f, "write access"),
26 }
27 }
28}
29
30#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
32pub struct BorTag(NonZero<u64>);
33
34impl BorTag {
35 pub fn new(i: u64) -> Option<Self> {
36 NonZero::new(i).map(BorTag)
37 }
38
39 pub fn get(&self) -> u64 {
40 self.0.get()
41 }
42
43 pub fn inner(&self) -> NonZero<u64> {
44 self.0
45 }
46
47 pub fn succ(self) -> Option<Self> {
48 self.0.checked_add(1).map(Self)
49 }
50
51 pub fn one() -> Self {
53 Self::new(1).unwrap()
54 }
55}
56
57impl std::default::Default for BorTag {
58 fn default() -> Self {
60 Self::one()
61 }
62}
63
64impl fmt::Debug for BorTag {
65 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66 write!(f, "<{}>", self.0)
67 }
68}
69
70#[derive(Debug)]
72pub struct FrameState {
73 protected_tags: SmallVec<[(AllocId, BorTag); 2]>,
85}
86
87impl VisitProvenance for FrameState {
88 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
89 for (id, tag) in &self.protected_tags {
96 visit(Some(*id), Some(*tag));
97 }
98 }
99}
100
101#[derive(Debug)]
103pub struct GlobalStateInner {
104 borrow_tracker_method: BorrowTrackerMethod,
106 retag_mode: RetagMode,
108 next_ptr_tag: BorTag,
110 root_ptr_tags: FxHashMap<AllocId, BorTag>,
114 protected_tags: FxHashMap<BorTag, ProtectorKind>,
119 tracked_pointer_tags: FxHashSet<BorTag>,
121}
122
123impl VisitProvenance for GlobalStateInner {
124 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
125 }
129}
130
131pub type GlobalState = RefCell<GlobalStateInner>;
133
134#[derive(Copy, Clone, Debug, PartialEq, Eq)]
136pub enum ProtectorKind {
137 WeakProtector,
144
145 StrongProtector,
152}
153
154impl GlobalStateInner {
156 pub fn new(
157 borrow_tracker_method: BorrowTrackerMethod,
158 tracked_pointer_tags: FxHashSet<BorTag>,
159 ) -> Self {
160 GlobalStateInner {
161 borrow_tracker_method,
162 retag_mode: RetagMode::Default,
163 next_ptr_tag: BorTag::one(),
164 root_ptr_tags: FxHashMap::default(),
165 protected_tags: FxHashMap::default(),
166 tracked_pointer_tags,
167 }
168 }
169
170 fn new_ptr(&mut self) -> BorTag {
172 let id = self.next_ptr_tag;
173 self.next_ptr_tag = id.succ().unwrap();
174 id
175 }
176
177 pub fn new_frame(&mut self) -> FrameState {
178 FrameState { protected_tags: SmallVec::new() }
179 }
180
181 fn end_call(&mut self, frame: &machine::FrameExtra<'_>) {
182 for (_, tag) in &frame
183 .borrow_tracker
184 .as_ref()
185 .expect("we should have borrow tracking data")
186 .protected_tags
187 {
188 self.protected_tags.remove(tag);
189 }
190 }
191
192 pub fn root_ptr_tag(&mut self, id: AllocId, machine: &MiriMachine<'_>) -> BorTag {
193 self.root_ptr_tags.get(&id).copied().unwrap_or_else(|| {
194 let tag = self.new_ptr();
195 if self.tracked_pointer_tags.contains(&tag) {
196 machine.emit_diagnostic(NonHaltingDiagnostic::CreatedPointerTag(
197 tag.inner(),
198 None,
199 None,
200 ));
201 }
202 trace!("New allocation {:?} has rpot tag {:?}", id, tag);
203 self.root_ptr_tags.try_insert(id, tag).unwrap();
204 tag
205 })
206 }
207
208 pub fn remove_unreachable_allocs(&mut self, allocs: &LiveAllocs<'_, '_>) {
209 self.root_ptr_tags.retain(|id, _| allocs.is_live(*id));
210 }
211
212 pub fn borrow_tracker_method(&self) -> BorrowTrackerMethod {
213 self.borrow_tracker_method
214 }
215}
216
217#[derive(Debug, Copy, Clone, PartialEq, Eq)]
219pub enum BorrowTrackerMethod {
220 StackedBorrows,
222 TreeBorrows(TreeBorrowsParams),
224}
225
226#[derive(Debug, Copy, Clone, PartialEq, Eq)]
228pub struct TreeBorrowsParams {
229 pub precise_interior_mut: bool,
230 pub implicit_writes: bool,
232}
233
234impl BorrowTrackerMethod {
235 pub fn instantiate_global_state(self, config: &MiriConfig) -> GlobalState {
236 RefCell::new(GlobalStateInner::new(self, config.tracked_pointer_tags.clone()))
237 }
238
239 #[track_caller]
240 pub fn get_tree_borrows_params(self) -> TreeBorrowsParams {
241 match self {
242 BorrowTrackerMethod::TreeBorrows(params) => params,
243 _ => panic!("can only be called when `BorrowTrackerMethod` is `TreeBorrows`"),
244 }
245 }
246}
247
248impl GlobalStateInner {
249 pub fn new_allocation(
250 &mut self,
251 id: AllocId,
252 alloc_size: Size,
253 kind: MemoryKind,
254 machine: &MiriMachine<'_>,
255 ) -> AllocState {
256 let _trace = enter_trace_span!(borrow_tracker::new_allocation, ?id, ?alloc_size, ?kind);
257 match self.borrow_tracker_method {
258 BorrowTrackerMethod::StackedBorrows =>
259 AllocState::StackedBorrows(Box::new(RefCell::new(Stacks::new_allocation(
260 id, alloc_size, self, kind, machine,
261 )))),
262 BorrowTrackerMethod::TreeBorrows { .. } =>
263 AllocState::TreeBorrows(Box::new(RefCell::new(Tree::new_allocation(
264 id, alloc_size, self, kind, machine,
265 )))),
266 }
267 }
268}
269
270impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
271pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
272 fn retag_ptr_value(
273 &mut self,
274 val: &ImmTy<'tcx>,
275 ty: Ty<'tcx>,
276 ) -> InterpResult<'tcx, Option<ImmTy<'tcx>>> {
277 let _trace = enter_trace_span!(borrow_tracker::retag_ptr_value, ?ty);
278 let this = self.eval_context_mut();
279 let state = this.machine.borrow_tracker.as_mut().unwrap().get_mut();
280 let method = state.borrow_tracker_method;
281 let retag_mode = state.retag_mode;
282 info!("retag_ptr_value: type={ty}, mode={retag_mode:?}, val={:?}", **val);
283 match method {
284 BorrowTrackerMethod::StackedBorrows => this.sb_retag_ptr_value(val, ty, retag_mode),
285 BorrowTrackerMethod::TreeBorrows { .. } => this.tb_retag_ptr_value(val, ty, retag_mode),
286 }
287 }
288
289 fn with_retag_mode<T>(
290 &mut self,
291 mode: RetagMode,
292 f: impl FnOnce(&mut Self) -> InterpResult<'tcx, T>,
293 ) -> InterpResult<'tcx, T> {
294 let state = self.eval_context_mut().machine.borrow_tracker.as_mut().unwrap().get_mut();
296 let old_mode = mem::replace(&mut state.retag_mode, mode);
297
298 let ret = f(self);
299
300 let state = self.eval_context_mut().machine.borrow_tracker.as_mut().unwrap().get_mut();
302 state.retag_mode = old_mode;
303
304 ret
305 }
306
307 fn protect_place(&mut self, place: &MPlaceTy<'tcx>) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
308 let _trace = enter_trace_span!(borrow_tracker::protect_place, ?place);
309 let this = self.eval_context_mut();
310 let method = this.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method;
311 match method {
312 BorrowTrackerMethod::StackedBorrows => this.sb_protect_place(place),
313 BorrowTrackerMethod::TreeBorrows { .. } => this.tb_protect_place(place),
314 }
315 }
316
317 fn expose_tag(&self, alloc_id: AllocId, tag: BorTag) -> InterpResult<'tcx> {
318 let _trace =
319 enter_trace_span!(borrow_tracker::expose_tag, alloc_id = alloc_id.0, tag = tag.0);
320 let this = self.eval_context_ref();
321 let method = this.machine.borrow_tracker.as_ref().unwrap().borrow().borrow_tracker_method;
322 match method {
323 BorrowTrackerMethod::StackedBorrows => this.sb_expose_tag(alloc_id, tag),
324 BorrowTrackerMethod::TreeBorrows { .. } => this.tb_expose_tag(alloc_id, tag),
325 }
326 }
327
328 fn give_pointer_debug_name(
329 &mut self,
330 ptr: Pointer,
331 nth_parent: u8,
332 name: &str,
333 ) -> InterpResult<'tcx> {
334 let this = self.eval_context_mut();
335 let method = this.machine.borrow_tracker.as_mut().unwrap().get_mut().borrow_tracker_method;
336 match method {
337 BorrowTrackerMethod::StackedBorrows => {
338 this.tcx.tcx.dcx().warn("Stacked Borrows does not support named pointers; `miri_pointer_name` is a no-op");
339 interp_ok(())
340 }
341 BorrowTrackerMethod::TreeBorrows { .. } =>
342 this.tb_give_pointer_debug_name(ptr, nth_parent, name),
343 }
344 }
345
346 fn print_borrow_state(&mut self, alloc_id: AllocId, show_unnamed: bool) -> InterpResult<'tcx> {
347 let this = self.eval_context_mut();
348 let Some(borrow_tracker) = &mut this.machine.borrow_tracker else {
349 eprintln!("attempted to print borrow state, but no borrow state is being tracked");
350 return interp_ok(());
351 };
352 let method = borrow_tracker.get_mut().borrow_tracker_method;
353 match method {
354 BorrowTrackerMethod::StackedBorrows => this.print_stacks(alloc_id),
355 BorrowTrackerMethod::TreeBorrows { .. } => this.print_tree(alloc_id, show_unnamed),
356 }
357 }
358
359 fn on_stack_pop(
360 &self,
361 frame: &Frame<'tcx, Provenance, FrameExtra<'tcx>>,
362 ) -> InterpResult<'tcx> {
363 let _trace = enter_trace_span!(borrow_tracker::on_stack_pop);
364 let this = self.eval_context_ref();
365 let borrow_tracker = this.machine.borrow_tracker.as_ref().unwrap();
366 for (alloc_id, tag) in &frame
370 .extra
371 .borrow_tracker
372 .as_ref()
373 .expect("we should have borrow tracking data")
374 .protected_tags
375 {
376 let kind = this.get_alloc_info(*alloc_id).kind;
383 if matches!(kind, AllocKind::LiveData) {
384 let alloc_extra = this.get_alloc_extra(*alloc_id)?; let alloc_borrow_tracker = &alloc_extra.borrow_tracker.as_ref().unwrap();
386 alloc_borrow_tracker.release_protector(
387 &this.machine,
388 borrow_tracker,
389 *tag,
390 *alloc_id,
391 )?;
392 }
393 }
394 borrow_tracker.borrow_mut().end_call(&frame.extra);
395
396 interp_ok(())
397 }
398}
399
400#[derive(Debug, Clone)]
402pub enum AllocState {
403 StackedBorrows(Box<RefCell<stacked_borrows::AllocState>>),
405 TreeBorrows(Box<RefCell<tree_borrows::AllocState>>),
407}
408
409impl machine::AllocExtra<'_> {
410 #[track_caller]
411 pub fn borrow_tracker_sb(&self) -> &RefCell<stacked_borrows::AllocState> {
412 match self.borrow_tracker {
413 Some(AllocState::StackedBorrows(ref sb)) => sb,
414 _ => panic!("expected Stacked Borrows borrow tracking, got something else"),
415 }
416 }
417
418 #[track_caller]
419 pub fn borrow_tracker_sb_mut(&mut self) -> &mut RefCell<stacked_borrows::AllocState> {
420 match self.borrow_tracker {
421 Some(AllocState::StackedBorrows(ref mut sb)) => sb,
422 _ => panic!("expected Stacked Borrows borrow tracking, got something else"),
423 }
424 }
425
426 #[track_caller]
427 pub fn borrow_tracker_tb(&self) -> &RefCell<tree_borrows::AllocState> {
428 match self.borrow_tracker {
429 Some(AllocState::TreeBorrows(ref tb)) => tb,
430 _ => panic!("expected Tree Borrows borrow tracking, got something else"),
431 }
432 }
433}
434
435impl AllocState {
436 pub fn before_memory_read<'tcx>(
437 &self,
438 alloc_id: AllocId,
439 prov_extra: ProvenanceExtra,
440 range: AllocRange,
441 machine: &MiriMachine<'tcx>,
442 ) -> InterpResult<'tcx> {
443 let _trace = enter_trace_span!(borrow_tracker::before_memory_read, alloc_id = alloc_id.0);
444 match self {
445 AllocState::StackedBorrows(sb) =>
446 sb.borrow_mut().before_memory_read(alloc_id, prov_extra, range, machine),
447 AllocState::TreeBorrows(tb) =>
448 tb.borrow_mut().before_memory_access(
449 AccessKind::Read,
450 alloc_id,
451 prov_extra,
452 range,
453 machine,
454 ),
455 }
456 }
457
458 pub fn before_memory_write<'tcx>(
459 &mut self,
460 alloc_id: AllocId,
461 prov_extra: ProvenanceExtra,
462 range: AllocRange,
463 machine: &MiriMachine<'tcx>,
464 ) -> InterpResult<'tcx> {
465 let _trace = enter_trace_span!(borrow_tracker::before_memory_write, alloc_id = alloc_id.0);
466 match self {
467 AllocState::StackedBorrows(sb) =>
468 sb.get_mut().before_memory_write(alloc_id, prov_extra, range, machine),
469 AllocState::TreeBorrows(tb) =>
470 tb.get_mut().before_memory_access(
471 AccessKind::Write,
472 alloc_id,
473 prov_extra,
474 range,
475 machine,
476 ),
477 }
478 }
479
480 pub fn before_memory_deallocation<'tcx>(
481 &mut self,
482 alloc_id: AllocId,
483 prov_extra: ProvenanceExtra,
484 size: Size,
485 machine: &MiriMachine<'tcx>,
486 ) -> InterpResult<'tcx> {
487 let _trace =
488 enter_trace_span!(borrow_tracker::before_memory_deallocation, alloc_id = alloc_id.0);
489 match self {
490 AllocState::StackedBorrows(sb) =>
491 sb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine),
492 AllocState::TreeBorrows(tb) =>
493 tb.get_mut().before_memory_deallocation(alloc_id, prov_extra, size, machine),
494 }
495 }
496
497 pub fn remove_unreachable_tags(&self, tags: &FxHashSet<BorTag>) {
498 let _trace = enter_trace_span!(borrow_tracker::remove_unreachable_tags);
499 match self {
500 AllocState::StackedBorrows(sb) => sb.borrow_mut().remove_unreachable_tags(tags),
501 AllocState::TreeBorrows(tb) => tb.borrow_mut().remove_unreachable_tags(tags),
502 }
503 }
504
505 pub fn release_protector<'tcx>(
507 &self,
508 machine: &MiriMachine<'tcx>,
509 global: &GlobalState,
510 tag: BorTag,
511 alloc_id: AllocId, ) -> InterpResult<'tcx> {
513 let _trace = enter_trace_span!(
514 borrow_tracker::release_protector,
515 alloc_id = alloc_id.0,
516 tag = tag.0
517 );
518 match self {
519 AllocState::StackedBorrows(_sb) => interp_ok(()),
520 AllocState::TreeBorrows(tb) =>
521 tb.borrow_mut().release_protector(machine, global, tag, alloc_id),
522 }
523 }
524}
525
526impl VisitProvenance for AllocState {
527 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
528 let _trace = enter_trace_span!(borrow_tracker::visit_provenance);
529 match self {
530 AllocState::StackedBorrows(sb) => sb.visit_provenance(visit),
531 AllocState::TreeBorrows(tb) => tb.visit_provenance(visit),
532 }
533 }
534}