]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Auto merge of #1851 - RalfJung:provenance-overhaul, r=RalfJung
[rust.git] / src / machine.rs
1 //! Global machine state as well as implementation of the interpreter engine
2 //! `Machine` trait.
3
4 use std::borrow::Cow;
5 use std::cell::RefCell;
6 use std::fmt;
7 use std::num::NonZeroU64;
8 use std::time::Instant;
9
10 use log::trace;
11 use rand::rngs::StdRng;
12 use rand::SeedableRng;
13
14 use rustc_data_structures::fx::FxHashMap;
15 use rustc_middle::{
16     mir,
17     ty::{
18         self,
19         layout::{LayoutCx, LayoutError, TyAndLayout},
20         Instance, TyCtxt,
21     },
22 };
23 use rustc_span::def_id::DefId;
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_target::abi::{LayoutOf, Size};
26 use rustc_target::spec::abi::Abi;
27
28 use crate::*;
29
30 // Some global facts about the emulated machine.
31 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
32 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
33 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
34 pub const NUM_CPUS: u64 = 1;
35
36 /// Extra data stored with each stack frame
37 pub struct FrameData<'tcx> {
38     /// Extra data for Stacked Borrows.
39     pub call_id: stacked_borrows::CallId,
40
41     /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
42     /// called by `try`). When this frame is popped during unwinding a panic,
43     /// we stop unwinding, use the `CatchUnwindData` to handle catching.
44     pub catch_unwind: Option<CatchUnwindData<'tcx>>,
45
46     /// If `measureme` profiling is enabled, holds timing information
47     /// for the start of this frame. When we finish executing this frame,
48     /// we use this to register a completed event with `measureme`.
49     pub timing: Option<measureme::DetachedTiming>,
50 }
51
52 impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
53     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54         // Omitting `timing`, it does not support `Debug`.
55         let FrameData { call_id, catch_unwind, timing: _ } = self;
56         f.debug_struct("FrameData")
57             .field("call_id", call_id)
58             .field("catch_unwind", catch_unwind)
59             .finish()
60     }
61 }
62
63 /// Extra memory kinds
64 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
65 pub enum MiriMemoryKind {
66     /// `__rust_alloc` memory.
67     Rust,
68     /// `malloc` memory.
69     C,
70     /// Windows `HeapAlloc` memory.
71     WinHeap,
72     /// Memory for args, errno, and other parts of the machine-managed environment.
73     /// This memory may leak.
74     Machine,
75     /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
76     Env,
77     /// Globals copied from `tcx`.
78     /// This memory may leak.
79     Global,
80     /// Memory for extern statics.
81     /// This memory may leak.
82     ExternStatic,
83     /// Memory for thread-local statics.
84     /// This memory may leak.
85     Tls,
86 }
87
88 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
89     #[inline(always)]
90     fn into(self) -> MemoryKind<MiriMemoryKind> {
91         MemoryKind::Machine(self)
92     }
93 }
94
95 impl MayLeak for MiriMemoryKind {
96     #[inline(always)]
97     fn may_leak(self) -> bool {
98         use self::MiriMemoryKind::*;
99         match self {
100             Rust | C | WinHeap | Env => false,
101             Machine | Global | ExternStatic | Tls => true,
102         }
103     }
104 }
105
106 impl fmt::Display for MiriMemoryKind {
107     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108         use self::MiriMemoryKind::*;
109         match self {
110             Rust => write!(f, "Rust heap"),
111             C => write!(f, "C heap"),
112             WinHeap => write!(f, "Windows heap"),
113             Machine => write!(f, "machine-managed memory"),
114             Env => write!(f, "environment variable"),
115             Global => write!(f, "global (static or const)"),
116             ExternStatic => write!(f, "extern static"),
117             Tls => write!(f, "thread-local static"),
118         }
119     }
120 }
121
122 /// Pointer provenance (tag).
123 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
124 pub struct Tag {
125     pub alloc_id: AllocId,
126     // Stacked Borrows tag.
127     pub sb: SbTag,
128 }
129
130 impl Provenance for Tag {
131     const OFFSET_IS_ADDR: bool = true;
132
133     fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134         let (tag, addr) = ptr.into_parts(); // address is absolute
135         write!(f, "0x{:x}", addr.bytes())?;
136         // Forward `alternate` flag to `alloc_id` printing.
137         if f.alternate() {
138             write!(f, "[{:#?}]", tag.alloc_id)?;
139         } else {
140             write!(f, "[{:?}]", tag.alloc_id)?;
141         }
142         // Print Stacked Borrows tag.
143         write!(f, "{:?}", tag.sb)
144     }
145
146     fn get_alloc_id(self) -> AllocId {
147         self.alloc_id
148     }
149 }
150
151 /// Extra per-allocation data
152 #[derive(Debug, Clone)]
153 pub struct AllocExtra {
154     /// Stacked Borrows state is only added if it is enabled.
155     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
156     /// Data race detection via the use of a vector-clock,
157     ///  this is only added if it is enabled.
158     pub data_race: Option<data_race::AllocExtra>,
159 }
160
161 /// Extra global memory data
162 #[derive(Debug)]
163 pub struct MemoryExtra {
164     pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
165     pub data_race: Option<data_race::MemoryExtra>,
166     pub intptrcast: intptrcast::MemoryExtra,
167
168     /// Mapping extern static names to their base pointer.
169     extern_statics: FxHashMap<Symbol, Pointer<Tag>>,
170
171     /// The random number generator used for resolving non-determinism.
172     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
173     pub(crate) rng: RefCell<StdRng>,
174
175     /// An allocation ID to report when it is being allocated
176     /// (helps for debugging memory leaks and use after free bugs).
177     tracked_alloc_id: Option<AllocId>,
178
179     /// Controls whether alignment of memory accesses is being checked.
180     pub(crate) check_alignment: AlignmentCheck,
181
182     /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
183     pub(crate) cmpxchg_weak_failure_rate: f64,
184 }
185
186 impl MemoryExtra {
187     pub fn new(config: &MiriConfig) -> Self {
188         let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
189         let stacked_borrows = if config.stacked_borrows {
190             Some(RefCell::new(stacked_borrows::GlobalState::new(
191                 config.tracked_pointer_tag,
192                 config.tracked_call_id,
193                 config.track_raw,
194             )))
195         } else {
196             None
197         };
198         let data_race =
199             if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
200         MemoryExtra {
201             stacked_borrows,
202             data_race,
203             intptrcast: Default::default(),
204             extern_statics: FxHashMap::default(),
205             rng: RefCell::new(rng),
206             tracked_alloc_id: config.tracked_alloc_id,
207             check_alignment: config.check_alignment,
208             cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
209         }
210     }
211
212     fn add_extern_static<'tcx, 'mir>(
213         this: &mut MiriEvalContext<'mir, 'tcx>,
214         name: &str,
215         ptr: Pointer<Option<Tag>>,
216     ) {
217         let ptr = ptr.into_pointer_or_addr().unwrap();
218         this.memory.extra.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
219     }
220
221     /// Sets up the "extern statics" for this machine.
222     pub fn init_extern_statics<'tcx, 'mir>(
223         this: &mut MiriEvalContext<'mir, 'tcx>,
224     ) -> InterpResult<'tcx> {
225         match this.tcx.sess.target.os.as_str() {
226             "linux" => {
227                 // "__cxa_thread_atexit_impl"
228                 // This should be all-zero, pointer-sized.
229                 let layout = this.machine.layouts.usize;
230                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
231                 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
232                 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
233                 // "environ"
234                 Self::add_extern_static(
235                     this,
236                     "environ",
237                     this.machine.env_vars.environ.unwrap().ptr,
238                 );
239             }
240             "windows" => {
241                 // "_tls_used"
242                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
243                 let layout = this.machine.layouts.u8;
244                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
245                 this.write_scalar(Scalar::from_u8(0), &place.into())?;
246                 Self::add_extern_static(this, "_tls_used", place.ptr);
247             }
248             _ => {} // No "extern statics" supported on this target
249         }
250         Ok(())
251     }
252 }
253
254 /// Precomputed layouts of primitive types
255 pub struct PrimitiveLayouts<'tcx> {
256     pub unit: TyAndLayout<'tcx>,
257     pub i8: TyAndLayout<'tcx>,
258     pub i32: TyAndLayout<'tcx>,
259     pub isize: TyAndLayout<'tcx>,
260     pub u8: TyAndLayout<'tcx>,
261     pub u32: TyAndLayout<'tcx>,
262     pub usize: TyAndLayout<'tcx>,
263 }
264
265 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
266     fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
267         Ok(Self {
268             unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
269             i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
270             i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
271             isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
272             u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
273             u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
274             usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
275         })
276     }
277 }
278
279 /// The machine itself.
280 pub struct Evaluator<'mir, 'tcx> {
281     /// Environment variables set by `setenv`.
282     /// Miri does not expose env vars from the host to the emulated program.
283     pub(crate) env_vars: EnvVars<'tcx>,
284
285     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
286     /// These are *pointers* to argc/argv because macOS.
287     /// We also need the full command line as one string because of Windows.
288     pub(crate) argc: Option<MemPlace<Tag>>,
289     pub(crate) argv: Option<MemPlace<Tag>>,
290     pub(crate) cmd_line: Option<MemPlace<Tag>>,
291
292     /// TLS state.
293     pub(crate) tls: TlsData<'tcx>,
294
295     /// What should Miri do when an op requires communicating with the host,
296     /// such as accessing host env vars, random number generation, and
297     /// file system access.
298     pub(crate) isolated_op: IsolatedOp,
299
300     /// Whether to enforce the validity invariant.
301     pub(crate) validate: bool,
302
303     /// Whether to enforce [ABI](Abi) of function calls.
304     pub(crate) enforce_abi: bool,
305
306     pub(crate) file_handler: shims::posix::FileHandler,
307     pub(crate) dir_handler: shims::posix::DirHandler,
308
309     /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
310     pub(crate) time_anchor: Instant,
311
312     /// The set of threads.
313     pub(crate) threads: ThreadManager<'mir, 'tcx>,
314
315     /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
316     pub(crate) layouts: PrimitiveLayouts<'tcx>,
317
318     /// Allocations that are considered roots of static memory (that may leak).
319     pub(crate) static_roots: Vec<AllocId>,
320
321     /// The `measureme` profiler used to record timing information about
322     /// the emulated program.
323     profiler: Option<measureme::Profiler>,
324     /// Used with `profiler` to cache the `StringId`s for event names
325     /// uesd with `measureme`.
326     string_cache: FxHashMap<String, measureme::StringId>,
327
328     /// Cache of `Instance` exported under the given `Symbol` name.
329     /// `None` means no `Instance` exported under the given name is found.
330     pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
331
332     /// Whether to raise a panic in the context of the evaluated process when unsupported
333     /// functionality is encountered. If `false`, an error is propagated in the Miri application context
334     /// instead (default behavior)
335     pub(crate) panic_on_unsupported: bool,
336 }
337
338 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
339     pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
340         let layouts =
341             PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
342         let profiler = config.measureme_out.as_ref().map(|out| {
343             measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
344         });
345         Evaluator {
346             // `env_vars` could be initialized properly here if `Memory` were available before
347             // calling this method.
348             env_vars: EnvVars::default(),
349             argc: None,
350             argv: None,
351             cmd_line: None,
352             tls: TlsData::default(),
353             isolated_op: config.isolated_op,
354             validate: config.validate,
355             enforce_abi: config.check_abi,
356             file_handler: Default::default(),
357             dir_handler: Default::default(),
358             time_anchor: Instant::now(),
359             layouts,
360             threads: ThreadManager::default(),
361             static_roots: Vec::new(),
362             profiler,
363             string_cache: Default::default(),
364             exported_symbols_cache: FxHashMap::default(),
365             panic_on_unsupported: config.panic_on_unsupported,
366         }
367     }
368
369     pub(crate) fn communicate(&self) -> bool {
370         self.isolated_op == IsolatedOp::Allow
371     }
372 }
373
374 /// A rustc InterpCx for Miri.
375 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
376
377 /// A little trait that's useful to be inherited by extension traits.
378 pub trait MiriEvalContextExt<'mir, 'tcx> {
379     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
380     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
381 }
382 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
383     #[inline(always)]
384     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
385         self
386     }
387     #[inline(always)]
388     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
389         self
390     }
391 }
392
393 /// Machine hook implementations.
394 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
395     type MemoryKind = MiriMemoryKind;
396
397     type FrameExtra = FrameData<'tcx>;
398     type MemoryExtra = MemoryExtra;
399     type AllocExtra = AllocExtra;
400     type PointerTag = Tag;
401     type ExtraFnVal = Dlsym;
402
403     type MemoryMap =
404         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
405
406     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
407
408     const PANIC_ON_ALLOC_FAIL: bool = false;
409
410     #[inline(always)]
411     fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
412         memory_extra.check_alignment != AlignmentCheck::None
413     }
414
415     #[inline(always)]
416     fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
417         memory_extra.check_alignment == AlignmentCheck::Int
418     }
419
420     #[inline(always)]
421     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
422         ecx.machine.validate
423     }
424
425     #[inline(always)]
426     fn enforce_abi(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
427         ecx.machine.enforce_abi
428     }
429
430     #[inline(always)]
431     fn find_mir_or_eval_fn(
432         ecx: &mut InterpCx<'mir, 'tcx, Self>,
433         instance: ty::Instance<'tcx>,
434         abi: Abi,
435         args: &[OpTy<'tcx, Tag>],
436         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
437         unwind: StackPopUnwind,
438     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
439         ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
440     }
441
442     #[inline(always)]
443     fn call_extra_fn(
444         ecx: &mut InterpCx<'mir, 'tcx, Self>,
445         fn_val: Dlsym,
446         abi: Abi,
447         args: &[OpTy<'tcx, Tag>],
448         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
449         _unwind: StackPopUnwind,
450     ) -> InterpResult<'tcx> {
451         ecx.call_dlsym(fn_val, abi, args, ret)
452     }
453
454     #[inline(always)]
455     fn call_intrinsic(
456         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
457         instance: ty::Instance<'tcx>,
458         args: &[OpTy<'tcx, Tag>],
459         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
460         unwind: StackPopUnwind,
461     ) -> InterpResult<'tcx> {
462         ecx.call_intrinsic(instance, args, ret, unwind)
463     }
464
465     #[inline(always)]
466     fn assert_panic(
467         ecx: &mut InterpCx<'mir, 'tcx, Self>,
468         msg: &mir::AssertMessage<'tcx>,
469         unwind: Option<mir::BasicBlock>,
470     ) -> InterpResult<'tcx> {
471         ecx.assert_panic(msg, unwind)
472     }
473
474     #[inline(always)]
475     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
476         throw_machine_stop!(TerminationInfo::Abort(msg))
477     }
478
479     #[inline(always)]
480     fn binary_ptr_op(
481         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
482         bin_op: mir::BinOp,
483         left: &ImmTy<'tcx, Tag>,
484         right: &ImmTy<'tcx, Tag>,
485     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
486         ecx.binary_ptr_op(bin_op, left, right)
487     }
488
489     fn box_alloc(
490         ecx: &mut InterpCx<'mir, 'tcx, Self>,
491         dest: &PlaceTy<'tcx, Tag>,
492     ) -> InterpResult<'tcx> {
493         trace!("box_alloc for {:?}", dest.layout.ty);
494         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
495         // First argument: `size`.
496         // (`0` is allowed here -- this is expected to be handled by the lang item).
497         let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
498
499         // Second argument: `align`.
500         let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
501
502         // Call the `exchange_malloc` lang item.
503         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
504         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
505         ecx.call_function(
506             malloc,
507             Abi::Rust,
508             &[size.into(), align.into()],
509             Some(dest),
510             // Don't do anything when we are done. The `statement()` function will increment
511             // the old stack frame's stmt counter to the next statement, which means that when
512             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
513             StackPopCleanup::None { cleanup: true },
514         )?;
515         Ok(())
516     }
517
518     fn thread_local_static_base_pointer(
519         ecx: &mut InterpCx<'mir, 'tcx, Self>,
520         def_id: DefId,
521     ) -> InterpResult<'tcx, Pointer<Tag>> {
522         ecx.get_or_create_thread_local_alloc(def_id)
523     }
524
525     fn extern_static_base_pointer(
526         memory: &Memory<'mir, 'tcx, Self>,
527         def_id: DefId,
528     ) -> InterpResult<'tcx, Pointer<Tag>> {
529         let attrs = memory.tcx.get_attrs(def_id);
530         let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
531             Some(name) => name,
532             None => memory.tcx.item_name(def_id),
533         };
534         if let Some(&ptr) = memory.extra.extern_statics.get(&link_name) {
535             Ok(ptr)
536         } else {
537             throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
538         }
539     }
540
541     fn init_allocation_extra<'b>(
542         mem: &Memory<'mir, 'tcx, Self>,
543         id: AllocId,
544         alloc: Cow<'b, Allocation>,
545         kind: Option<MemoryKind<Self::MemoryKind>>,
546     ) -> Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>> {
547         if Some(id) == mem.extra.tracked_alloc_id {
548             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
549         }
550
551         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
552         let alloc = alloc.into_owned();
553         let stacks = if let Some(stacked_borrows) = &mem.extra.stacked_borrows {
554             Some(Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind))
555         } else {
556             None
557         };
558         let race_alloc = if let Some(data_race) = &mem.extra.data_race {
559             Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
560         } else {
561             None
562         };
563         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.convert_tag_add_extra(
564             &mem.tcx,
565             AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
566             |ptr| Evaluator::tag_alloc_base_pointer(mem, ptr),
567         );
568         Cow::Owned(alloc)
569     }
570
571     fn tag_alloc_base_pointer(
572         mem: &Memory<'mir, 'tcx, Self>,
573         ptr: Pointer<AllocId>,
574     ) -> Pointer<Tag> {
575         let absolute_addr = intptrcast::GlobalState::rel_ptr_to_addr(&mem, ptr);
576         let sb_tag = if let Some(stacked_borrows) = &mem.extra.stacked_borrows {
577             stacked_borrows.borrow_mut().base_tag(ptr.provenance)
578         } else {
579             SbTag::Untagged
580         };
581         Pointer::new(Tag { alloc_id: ptr.provenance, sb: sb_tag }, Size::from_bytes(absolute_addr))
582     }
583
584     #[inline(always)]
585     fn ptr_from_addr(
586         mem: &Memory<'mir, 'tcx, Self>,
587         addr: u64,
588     ) -> Pointer<Option<Self::PointerTag>> {
589         intptrcast::GlobalState::ptr_from_addr(addr, mem)
590     }
591
592     /// Convert a pointer with provenance into an allocation-offset pair,
593     /// or a `None` with an absolute address if that conversion is not possible.
594     fn ptr_get_alloc(
595         mem: &Memory<'mir, 'tcx, Self>,
596         ptr: Pointer<Self::PointerTag>,
597     ) -> (AllocId, Size) {
598         let rel = intptrcast::GlobalState::abs_ptr_to_rel(mem, ptr);
599         (ptr.provenance.alloc_id, rel)
600     }
601
602     #[inline(always)]
603     fn memory_read(
604         memory_extra: &Self::MemoryExtra,
605         alloc_extra: &AllocExtra,
606         tag: Tag,
607         range: AllocRange,
608     ) -> InterpResult<'tcx> {
609         if let Some(data_race) = &alloc_extra.data_race {
610             data_race.read(tag.alloc_id, range, memory_extra.data_race.as_ref().unwrap())?;
611         }
612         if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
613             stacked_borrows.memory_read(
614                 tag.alloc_id,
615                 tag.sb,
616                 range,
617                 memory_extra.stacked_borrows.as_ref().unwrap(),
618             )
619         } else {
620             Ok(())
621         }
622     }
623
624     #[inline(always)]
625     fn memory_written(
626         memory_extra: &mut Self::MemoryExtra,
627         alloc_extra: &mut AllocExtra,
628         tag: Tag,
629         range: AllocRange,
630     ) -> InterpResult<'tcx> {
631         if let Some(data_race) = &mut alloc_extra.data_race {
632             data_race.write(tag.alloc_id, range, memory_extra.data_race.as_mut().unwrap())?;
633         }
634         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
635             stacked_borrows.memory_written(
636                 tag.alloc_id,
637                 tag.sb,
638                 range,
639                 memory_extra.stacked_borrows.as_mut().unwrap(),
640             )
641         } else {
642             Ok(())
643         }
644     }
645
646     #[inline(always)]
647     fn memory_deallocated(
648         memory_extra: &mut Self::MemoryExtra,
649         alloc_extra: &mut AllocExtra,
650         tag: Tag,
651         range: AllocRange,
652     ) -> InterpResult<'tcx> {
653         if Some(tag.alloc_id) == memory_extra.tracked_alloc_id {
654             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(tag.alloc_id));
655         }
656         if let Some(data_race) = &mut alloc_extra.data_race {
657             data_race.deallocate(tag.alloc_id, range, memory_extra.data_race.as_mut().unwrap())?;
658         }
659         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
660             stacked_borrows.memory_deallocated(
661                 tag.alloc_id,
662                 tag.sb,
663                 range,
664                 memory_extra.stacked_borrows.as_mut().unwrap(),
665             )
666         } else {
667             Ok(())
668         }
669     }
670
671     #[inline(always)]
672     fn retag(
673         ecx: &mut InterpCx<'mir, 'tcx, Self>,
674         kind: mir::RetagKind,
675         place: &PlaceTy<'tcx, Tag>,
676     ) -> InterpResult<'tcx> {
677         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
678     }
679
680     #[inline(always)]
681     fn init_frame_extra(
682         ecx: &mut InterpCx<'mir, 'tcx, Self>,
683         frame: Frame<'mir, 'tcx, Tag>,
684     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
685         // Start recording our event before doing anything else
686         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
687             let fn_name = frame.instance.to_string();
688             let entry = ecx.machine.string_cache.entry(fn_name.clone());
689             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
690
691             Some(profiler.start_recording_interval_event_detached(
692                 *name,
693                 measureme::EventId::from_label(*name),
694                 ecx.get_active_thread().to_u32(),
695             ))
696         } else {
697             None
698         };
699
700         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
701         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
702             stacked_borrows.borrow_mut().new_call()
703         });
704
705         let extra = FrameData { call_id, catch_unwind: None, timing };
706         Ok(frame.with_extra(extra))
707     }
708
709     fn stack<'a>(
710         ecx: &'a InterpCx<'mir, 'tcx, Self>,
711     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
712         ecx.active_thread_stack()
713     }
714
715     fn stack_mut<'a>(
716         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
717     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
718         ecx.active_thread_stack_mut()
719     }
720
721     #[inline(always)]
722     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
723         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
724     }
725
726     #[inline(always)]
727     fn after_stack_pop(
728         ecx: &mut InterpCx<'mir, 'tcx, Self>,
729         mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
730         unwinding: bool,
731     ) -> InterpResult<'tcx, StackPopJump> {
732         let timing = frame.extra.timing.take();
733         let res = ecx.handle_stack_pop(frame.extra, unwinding);
734         if let Some(profiler) = ecx.machine.profiler.as_ref() {
735             profiler.finish_recording_interval_event(timing.unwrap());
736         }
737         res
738     }
739 }