]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Auto merge of #1841 - RalfJung:debug, 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 /// Extra per-allocation data
123 #[derive(Debug, Clone)]
124 pub struct AllocExtra {
125     /// Stacked Borrows state is only added if it is enabled.
126     pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
127     /// Data race detection via the use of a vector-clock,
128     ///  this is only added if it is enabled.
129     pub data_race: Option<data_race::AllocExtra>,
130 }
131
132 /// Extra global memory data
133 #[derive(Debug)]
134 pub struct MemoryExtra {
135     pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
136     pub data_race: Option<data_race::MemoryExtra>,
137     pub intptrcast: intptrcast::MemoryExtra,
138
139     /// Mapping extern static names to their canonical allocation.
140     extern_statics: FxHashMap<Symbol, AllocId>,
141
142     /// The random number generator used for resolving non-determinism.
143     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
144     pub(crate) rng: RefCell<StdRng>,
145
146     /// An allocation ID to report when it is being allocated
147     /// (helps for debugging memory leaks and use after free bugs).
148     tracked_alloc_id: Option<AllocId>,
149
150     /// Controls whether alignment of memory accesses is being checked.
151     pub(crate) check_alignment: AlignmentCheck,
152
153     /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
154     pub(crate) cmpxchg_weak_failure_rate: f64,
155 }
156
157 impl MemoryExtra {
158     pub fn new(config: &MiriConfig) -> Self {
159         let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
160         let stacked_borrows = if config.stacked_borrows {
161             Some(RefCell::new(stacked_borrows::GlobalState::new(
162                 config.tracked_pointer_tag,
163                 config.tracked_call_id,
164                 config.track_raw,
165             )))
166         } else {
167             None
168         };
169         let data_race =
170             if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
171         MemoryExtra {
172             stacked_borrows,
173             data_race,
174             intptrcast: Default::default(),
175             extern_statics: FxHashMap::default(),
176             rng: RefCell::new(rng),
177             tracked_alloc_id: config.tracked_alloc_id,
178             check_alignment: config.check_alignment,
179             cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
180         }
181     }
182
183     fn add_extern_static<'tcx, 'mir>(
184         this: &mut MiriEvalContext<'mir, 'tcx>,
185         name: &str,
186         ptr: Scalar<Tag>,
187     ) {
188         let ptr = ptr.assert_ptr();
189         assert_eq!(ptr.offset, Size::ZERO);
190         this.memory.extra.extern_statics.try_insert(Symbol::intern(name), ptr.alloc_id).unwrap();
191     }
192
193     /// Sets up the "extern statics" for this machine.
194     pub fn init_extern_statics<'tcx, 'mir>(
195         this: &mut MiriEvalContext<'mir, 'tcx>,
196     ) -> InterpResult<'tcx> {
197         match this.tcx.sess.target.os.as_str() {
198             "linux" => {
199                 // "__cxa_thread_atexit_impl"
200                 // This should be all-zero, pointer-sized.
201                 let layout = this.machine.layouts.usize;
202                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
203                 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
204                 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
205                 // "environ"
206                 Self::add_extern_static(
207                     this,
208                     "environ",
209                     this.machine.env_vars.environ.unwrap().ptr,
210                 );
211             }
212             "windows" => {
213                 // "_tls_used"
214                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
215                 let layout = this.machine.layouts.u8;
216                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
217                 this.write_scalar(Scalar::from_u8(0), &place.into())?;
218                 Self::add_extern_static(this, "_tls_used", place.ptr);
219             }
220             _ => {} // No "extern statics" supported on this target
221         }
222         Ok(())
223     }
224 }
225
226 /// Precomputed layouts of primitive types
227 pub struct PrimitiveLayouts<'tcx> {
228     pub unit: TyAndLayout<'tcx>,
229     pub i8: TyAndLayout<'tcx>,
230     pub i32: TyAndLayout<'tcx>,
231     pub isize: TyAndLayout<'tcx>,
232     pub u8: TyAndLayout<'tcx>,
233     pub u32: TyAndLayout<'tcx>,
234     pub usize: TyAndLayout<'tcx>,
235 }
236
237 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
238     fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
239         Ok(Self {
240             unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
241             i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
242             i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
243             isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
244             u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
245             u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
246             usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
247         })
248     }
249 }
250
251 /// The machine itself.
252 pub struct Evaluator<'mir, 'tcx> {
253     /// Environment variables set by `setenv`.
254     /// Miri does not expose env vars from the host to the emulated program.
255     pub(crate) env_vars: EnvVars<'tcx>,
256
257     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
258     /// These are *pointers* to argc/argv because macOS.
259     /// We also need the full command line as one string because of Windows.
260     pub(crate) argc: Option<Scalar<Tag>>,
261     pub(crate) argv: Option<Scalar<Tag>>,
262     pub(crate) cmd_line: Option<Scalar<Tag>>,
263
264     /// TLS state.
265     pub(crate) tls: TlsData<'tcx>,
266
267     /// What should Miri do when an op requires communicating with the host,
268     /// such as accessing host env vars, random number generation, and
269     /// file system access.
270     pub(crate) isolated_op: IsolatedOp,
271
272     /// Whether to enforce the validity invariant.
273     pub(crate) validate: bool,
274
275     /// Whether to enforce [ABI](Abi) of function calls.
276     pub(crate) enforce_abi: bool,
277
278     pub(crate) file_handler: shims::posix::FileHandler,
279     pub(crate) dir_handler: shims::posix::DirHandler,
280
281     /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
282     pub(crate) time_anchor: Instant,
283
284     /// The set of threads.
285     pub(crate) threads: ThreadManager<'mir, 'tcx>,
286
287     /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
288     pub(crate) layouts: PrimitiveLayouts<'tcx>,
289
290     /// Allocations that are considered roots of static memory (that may leak).
291     pub(crate) static_roots: Vec<AllocId>,
292
293     /// The `measureme` profiler used to record timing information about
294     /// the emulated program.
295     profiler: Option<measureme::Profiler>,
296     /// Used with `profiler` to cache the `StringId`s for event names
297     /// uesd with `measureme`.
298     string_cache: FxHashMap<String, measureme::StringId>,
299
300     /// Cache of `Instance` exported under the given `Symbol` name.
301     /// `None` means no `Instance` exported under the given name is found.
302     pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
303
304     /// Whether to raise a panic in the context of the evaluated process when unsupported
305     /// functionality is encountered. If `false`, an error is propagated in the Miri application context
306     /// instead (default behavior)
307     pub(crate) panic_on_unsupported: bool,
308 }
309
310 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
311     pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
312         let layouts =
313             PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
314         let profiler = config.measureme_out.as_ref().map(|out| {
315             measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
316         });
317         Evaluator {
318             // `env_vars` could be initialized properly here if `Memory` were available before
319             // calling this method.
320             env_vars: EnvVars::default(),
321             argc: None,
322             argv: None,
323             cmd_line: None,
324             tls: TlsData::default(),
325             isolated_op: config.isolated_op,
326             validate: config.validate,
327             enforce_abi: config.check_abi,
328             file_handler: Default::default(),
329             dir_handler: Default::default(),
330             time_anchor: Instant::now(),
331             layouts,
332             threads: ThreadManager::default(),
333             static_roots: Vec::new(),
334             profiler,
335             string_cache: Default::default(),
336             exported_symbols_cache: FxHashMap::default(),
337             panic_on_unsupported: config.panic_on_unsupported,
338         }
339     }
340
341     pub(crate) fn communicate(&self) -> bool {
342         self.isolated_op == IsolatedOp::Allow
343     }
344 }
345
346 /// A rustc InterpCx for Miri.
347 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
348
349 /// A little trait that's useful to be inherited by extension traits.
350 pub trait MiriEvalContextExt<'mir, 'tcx> {
351     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
352     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
353 }
354 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
355     #[inline(always)]
356     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
357         self
358     }
359     #[inline(always)]
360     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
361         self
362     }
363 }
364
365 /// Machine hook implementations.
366 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
367     type MemoryKind = MiriMemoryKind;
368
369     type FrameExtra = FrameData<'tcx>;
370     type MemoryExtra = MemoryExtra;
371     type AllocExtra = AllocExtra;
372     type PointerTag = Tag;
373     type ExtraFnVal = Dlsym;
374
375     type MemoryMap =
376         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
377
378     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
379
380     #[inline(always)]
381     fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
382         memory_extra.check_alignment != AlignmentCheck::None
383     }
384
385     #[inline(always)]
386     fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
387         memory_extra.check_alignment == AlignmentCheck::Int
388     }
389
390     #[inline(always)]
391     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
392         ecx.machine.validate
393     }
394
395     #[inline(always)]
396     fn enforce_abi(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
397         ecx.machine.enforce_abi
398     }
399
400     #[inline(always)]
401     fn find_mir_or_eval_fn(
402         ecx: &mut InterpCx<'mir, 'tcx, Self>,
403         instance: ty::Instance<'tcx>,
404         abi: Abi,
405         args: &[OpTy<'tcx, Tag>],
406         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
407         unwind: StackPopUnwind,
408     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
409         ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
410     }
411
412     #[inline(always)]
413     fn call_extra_fn(
414         ecx: &mut InterpCx<'mir, 'tcx, Self>,
415         fn_val: Dlsym,
416         abi: Abi,
417         args: &[OpTy<'tcx, Tag>],
418         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
419         _unwind: StackPopUnwind,
420     ) -> InterpResult<'tcx> {
421         ecx.call_dlsym(fn_val, abi, args, ret)
422     }
423
424     #[inline(always)]
425     fn call_intrinsic(
426         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
427         instance: ty::Instance<'tcx>,
428         args: &[OpTy<'tcx, Tag>],
429         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
430         unwind: StackPopUnwind,
431     ) -> InterpResult<'tcx> {
432         ecx.call_intrinsic(instance, args, ret, unwind)
433     }
434
435     #[inline(always)]
436     fn assert_panic(
437         ecx: &mut InterpCx<'mir, 'tcx, Self>,
438         msg: &mir::AssertMessage<'tcx>,
439         unwind: Option<mir::BasicBlock>,
440     ) -> InterpResult<'tcx> {
441         ecx.assert_panic(msg, unwind)
442     }
443
444     #[inline(always)]
445     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
446         throw_machine_stop!(TerminationInfo::Abort(msg))
447     }
448
449     #[inline(always)]
450     fn binary_ptr_op(
451         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
452         bin_op: mir::BinOp,
453         left: &ImmTy<'tcx, Tag>,
454         right: &ImmTy<'tcx, Tag>,
455     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
456         ecx.binary_ptr_op(bin_op, left, right)
457     }
458
459     fn box_alloc(
460         ecx: &mut InterpCx<'mir, 'tcx, Self>,
461         dest: &PlaceTy<'tcx, Tag>,
462     ) -> InterpResult<'tcx> {
463         trace!("box_alloc for {:?}", dest.layout.ty);
464         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
465         // First argument: `size`.
466         // (`0` is allowed here -- this is expected to be handled by the lang item).
467         let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
468
469         // Second argument: `align`.
470         let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
471
472         // Call the `exchange_malloc` lang item.
473         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
474         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
475         ecx.call_function(
476             malloc,
477             Abi::Rust,
478             &[size.into(), align.into()],
479             Some(dest),
480             // Don't do anything when we are done. The `statement()` function will increment
481             // the old stack frame's stmt counter to the next statement, which means that when
482             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
483             StackPopCleanup::None { cleanup: true },
484         )?;
485         Ok(())
486     }
487
488     fn thread_local_static_alloc_id(
489         ecx: &mut InterpCx<'mir, 'tcx, Self>,
490         def_id: DefId,
491     ) -> InterpResult<'tcx, AllocId> {
492         ecx.get_or_create_thread_local_alloc_id(def_id)
493     }
494
495     fn extern_static_alloc_id(
496         memory: &Memory<'mir, 'tcx, Self>,
497         def_id: DefId,
498     ) -> InterpResult<'tcx, AllocId> {
499         let attrs = memory.tcx.get_attrs(def_id);
500         let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
501             Some(name) => name,
502             None => memory.tcx.item_name(def_id),
503         };
504         if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
505             Ok(id)
506         } else {
507             throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
508         }
509     }
510
511     fn init_allocation_extra<'b>(
512         memory_extra: &MemoryExtra,
513         id: AllocId,
514         alloc: Cow<'b, Allocation>,
515         kind: Option<MemoryKind<Self::MemoryKind>>,
516     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
517         if Some(id) == memory_extra.tracked_alloc_id {
518             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
519         }
520
521         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
522         let alloc = alloc.into_owned();
523         let (stacks, base_tag) = if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
524             let (stacks, base_tag) =
525                 Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind);
526             (Some(stacks), base_tag)
527         } else {
528             // No stacks, no tag.
529             (None, Tag::Untagged)
530         };
531         let race_alloc = if let Some(data_race) = &memory_extra.data_race {
532             Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
533         } else {
534             None
535         };
536         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
537         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
538             |alloc| {
539                 if let Some(stacked_borrows) = &mut stacked_borrows {
540                     // Only globals may already contain pointers at this point
541                     assert_eq!(kind, MiriMemoryKind::Global.into());
542                     stacked_borrows.global_base_ptr(alloc)
543                 } else {
544                     Tag::Untagged
545                 }
546             },
547             AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
548         );
549         (Cow::Owned(alloc), base_tag)
550     }
551
552     #[inline(always)]
553     fn memory_read(
554         memory_extra: &Self::MemoryExtra,
555         alloc_extra: &AllocExtra,
556         ptr: Pointer<Tag>,
557         size: Size,
558     ) -> InterpResult<'tcx> {
559         if let Some(data_race) = &alloc_extra.data_race {
560             data_race.read(ptr, size, memory_extra.data_race.as_ref().unwrap())?;
561         }
562         if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
563             stacked_borrows.memory_read(ptr, size, memory_extra.stacked_borrows.as_ref().unwrap())
564         } else {
565             Ok(())
566         }
567     }
568
569     #[inline(always)]
570     fn memory_written(
571         memory_extra: &mut Self::MemoryExtra,
572         alloc_extra: &mut AllocExtra,
573         ptr: Pointer<Tag>,
574         size: Size,
575     ) -> InterpResult<'tcx> {
576         if let Some(data_race) = &mut alloc_extra.data_race {
577             data_race.write(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
578         }
579         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
580             stacked_borrows.memory_written(
581                 ptr,
582                 size,
583                 memory_extra.stacked_borrows.as_mut().unwrap(),
584             )
585         } else {
586             Ok(())
587         }
588     }
589
590     #[inline(always)]
591     fn memory_deallocated(
592         memory_extra: &mut Self::MemoryExtra,
593         alloc_extra: &mut AllocExtra,
594         ptr: Pointer<Tag>,
595         size: Size,
596     ) -> InterpResult<'tcx> {
597         if Some(ptr.alloc_id) == memory_extra.tracked_alloc_id {
598             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(ptr.alloc_id));
599         }
600         if let Some(data_race) = &mut alloc_extra.data_race {
601             data_race.deallocate(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
602         }
603         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
604             stacked_borrows.memory_deallocated(
605                 ptr,
606                 size,
607                 memory_extra.stacked_borrows.as_mut().unwrap(),
608             )
609         } else {
610             Ok(())
611         }
612     }
613
614     fn after_static_mem_initialized(
615         ecx: &mut InterpCx<'mir, 'tcx, Self>,
616         ptr: Pointer<Self::PointerTag>,
617         size: Size,
618     ) -> InterpResult<'tcx> {
619         if ecx.memory.extra.data_race.is_some() {
620             ecx.reset_vector_clocks(ptr, size)?;
621         }
622         Ok(())
623     }
624
625     #[inline(always)]
626     fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
627         if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
628             stacked_borrows.borrow_mut().global_base_ptr(id)
629         } else {
630             Tag::Untagged
631         }
632     }
633
634     #[inline(always)]
635     fn retag(
636         ecx: &mut InterpCx<'mir, 'tcx, Self>,
637         kind: mir::RetagKind,
638         place: &PlaceTy<'tcx, Tag>,
639     ) -> InterpResult<'tcx> {
640         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
641     }
642
643     #[inline(always)]
644     fn init_frame_extra(
645         ecx: &mut InterpCx<'mir, 'tcx, Self>,
646         frame: Frame<'mir, 'tcx, Tag>,
647     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
648         // Start recording our event before doing anything else
649         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
650             let fn_name = frame.instance.to_string();
651             let entry = ecx.machine.string_cache.entry(fn_name.clone());
652             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
653
654             Some(profiler.start_recording_interval_event_detached(
655                 *name,
656                 measureme::EventId::from_label(*name),
657                 ecx.get_active_thread().to_u32(),
658             ))
659         } else {
660             None
661         };
662
663         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
664         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
665             stacked_borrows.borrow_mut().new_call()
666         });
667
668         let extra = FrameData { call_id, catch_unwind: None, timing };
669         Ok(frame.with_extra(extra))
670     }
671
672     fn stack<'a>(
673         ecx: &'a InterpCx<'mir, 'tcx, Self>,
674     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
675         ecx.active_thread_stack()
676     }
677
678     fn stack_mut<'a>(
679         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
680     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
681         ecx.active_thread_stack_mut()
682     }
683
684     #[inline(always)]
685     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
686         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
687     }
688
689     #[inline(always)]
690     fn after_stack_pop(
691         ecx: &mut InterpCx<'mir, 'tcx, Self>,
692         mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
693         unwinding: bool,
694     ) -> InterpResult<'tcx, StackPopJump> {
695         let timing = frame.extra.timing.take();
696         let res = ecx.handle_stack_pop(frame.extra, unwinding);
697         if let Some(profiler) = ecx.machine.profiler.as_ref() {
698             profiler.finish_recording_interval_event(timing.unwrap());
699         }
700         res
701     }
702
703     #[inline(always)]
704     fn int_to_ptr(
705         memory: &Memory<'mir, 'tcx, Self>,
706         int: u64,
707     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
708         intptrcast::GlobalState::int_to_ptr(int, memory)
709     }
710
711     #[inline(always)]
712     fn ptr_to_int(
713         memory: &Memory<'mir, 'tcx, Self>,
714         ptr: Pointer<Self::PointerTag>,
715     ) -> InterpResult<'tcx, u64> {
716         intptrcast::GlobalState::ptr_to_int(ptr, memory)
717     }
718 }