]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
Make work after mir-alloc-oom
[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     const PANIC_ON_ALLOC_FAIL: bool = false;
381
382     #[inline(always)]
383     fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
384         memory_extra.check_alignment != AlignmentCheck::None
385     }
386
387     #[inline(always)]
388     fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
389         memory_extra.check_alignment == AlignmentCheck::Int
390     }
391
392     #[inline(always)]
393     fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
394         ecx.machine.validate
395     }
396
397     #[inline(always)]
398     fn enforce_abi(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
399         ecx.machine.enforce_abi
400     }
401
402     #[inline(always)]
403     fn find_mir_or_eval_fn(
404         ecx: &mut InterpCx<'mir, 'tcx, Self>,
405         instance: ty::Instance<'tcx>,
406         abi: Abi,
407         args: &[OpTy<'tcx, Tag>],
408         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
409         unwind: StackPopUnwind,
410     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
411         ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
412     }
413
414     #[inline(always)]
415     fn call_extra_fn(
416         ecx: &mut InterpCx<'mir, 'tcx, Self>,
417         fn_val: Dlsym,
418         abi: Abi,
419         args: &[OpTy<'tcx, Tag>],
420         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
421         _unwind: StackPopUnwind,
422     ) -> InterpResult<'tcx> {
423         ecx.call_dlsym(fn_val, abi, args, ret)
424     }
425
426     #[inline(always)]
427     fn call_intrinsic(
428         ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
429         instance: ty::Instance<'tcx>,
430         args: &[OpTy<'tcx, Tag>],
431         ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
432         unwind: StackPopUnwind,
433     ) -> InterpResult<'tcx> {
434         ecx.call_intrinsic(instance, args, ret, unwind)
435     }
436
437     #[inline(always)]
438     fn assert_panic(
439         ecx: &mut InterpCx<'mir, 'tcx, Self>,
440         msg: &mir::AssertMessage<'tcx>,
441         unwind: Option<mir::BasicBlock>,
442     ) -> InterpResult<'tcx> {
443         ecx.assert_panic(msg, unwind)
444     }
445
446     #[inline(always)]
447     fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
448         throw_machine_stop!(TerminationInfo::Abort(msg))
449     }
450
451     #[inline(always)]
452     fn binary_ptr_op(
453         ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
454         bin_op: mir::BinOp,
455         left: &ImmTy<'tcx, Tag>,
456         right: &ImmTy<'tcx, Tag>,
457     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
458         ecx.binary_ptr_op(bin_op, left, right)
459     }
460
461     fn box_alloc(
462         ecx: &mut InterpCx<'mir, 'tcx, Self>,
463         dest: &PlaceTy<'tcx, Tag>,
464     ) -> InterpResult<'tcx> {
465         trace!("box_alloc for {:?}", dest.layout.ty);
466         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
467         // First argument: `size`.
468         // (`0` is allowed here -- this is expected to be handled by the lang item).
469         let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
470
471         // Second argument: `align`.
472         let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
473
474         // Call the `exchange_malloc` lang item.
475         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
476         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
477         ecx.call_function(
478             malloc,
479             Abi::Rust,
480             &[size.into(), align.into()],
481             Some(dest),
482             // Don't do anything when we are done. The `statement()` function will increment
483             // the old stack frame's stmt counter to the next statement, which means that when
484             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
485             StackPopCleanup::None { cleanup: true },
486         )?;
487         Ok(())
488     }
489
490     fn thread_local_static_alloc_id(
491         ecx: &mut InterpCx<'mir, 'tcx, Self>,
492         def_id: DefId,
493     ) -> InterpResult<'tcx, AllocId> {
494         ecx.get_or_create_thread_local_alloc_id(def_id)
495     }
496
497     fn extern_static_alloc_id(
498         memory: &Memory<'mir, 'tcx, Self>,
499         def_id: DefId,
500     ) -> InterpResult<'tcx, AllocId> {
501         let attrs = memory.tcx.get_attrs(def_id);
502         let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
503             Some(name) => name,
504             None => memory.tcx.item_name(def_id),
505         };
506         if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
507             Ok(id)
508         } else {
509             throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
510         }
511     }
512
513     fn init_allocation_extra<'b>(
514         memory_extra: &MemoryExtra,
515         id: AllocId,
516         alloc: Cow<'b, Allocation>,
517         kind: Option<MemoryKind<Self::MemoryKind>>,
518     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
519         if Some(id) == memory_extra.tracked_alloc_id {
520             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
521         }
522
523         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
524         let alloc = alloc.into_owned();
525         let (stacks, base_tag) = if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
526             let (stacks, base_tag) =
527                 Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind);
528             (Some(stacks), base_tag)
529         } else {
530             // No stacks, no tag.
531             (None, Tag::Untagged)
532         };
533         let race_alloc = if let Some(data_race) = &memory_extra.data_race {
534             Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
535         } else {
536             None
537         };
538         let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
539         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
540             |alloc| {
541                 if let Some(stacked_borrows) = &mut stacked_borrows {
542                     // Only globals may already contain pointers at this point
543                     assert_eq!(kind, MiriMemoryKind::Global.into());
544                     stacked_borrows.global_base_ptr(alloc)
545                 } else {
546                     Tag::Untagged
547                 }
548             },
549             AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
550         );
551         (Cow::Owned(alloc), base_tag)
552     }
553
554     #[inline(always)]
555     fn memory_read(
556         memory_extra: &Self::MemoryExtra,
557         alloc_extra: &AllocExtra,
558         ptr: Pointer<Tag>,
559         size: Size,
560     ) -> InterpResult<'tcx> {
561         if let Some(data_race) = &alloc_extra.data_race {
562             data_race.read(ptr, size, memory_extra.data_race.as_ref().unwrap())?;
563         }
564         if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
565             stacked_borrows.memory_read(ptr, size, memory_extra.stacked_borrows.as_ref().unwrap())
566         } else {
567             Ok(())
568         }
569     }
570
571     #[inline(always)]
572     fn memory_written(
573         memory_extra: &mut Self::MemoryExtra,
574         alloc_extra: &mut AllocExtra,
575         ptr: Pointer<Tag>,
576         size: Size,
577     ) -> InterpResult<'tcx> {
578         if let Some(data_race) = &mut alloc_extra.data_race {
579             data_race.write(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
580         }
581         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
582             stacked_borrows.memory_written(
583                 ptr,
584                 size,
585                 memory_extra.stacked_borrows.as_mut().unwrap(),
586             )
587         } else {
588             Ok(())
589         }
590     }
591
592     #[inline(always)]
593     fn memory_deallocated(
594         memory_extra: &mut Self::MemoryExtra,
595         alloc_extra: &mut AllocExtra,
596         ptr: Pointer<Tag>,
597         size: Size,
598     ) -> InterpResult<'tcx> {
599         if Some(ptr.alloc_id) == memory_extra.tracked_alloc_id {
600             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(ptr.alloc_id));
601         }
602         if let Some(data_race) = &mut alloc_extra.data_race {
603             data_race.deallocate(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
604         }
605         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
606             stacked_borrows.memory_deallocated(
607                 ptr,
608                 size,
609                 memory_extra.stacked_borrows.as_mut().unwrap(),
610             )
611         } else {
612             Ok(())
613         }
614     }
615
616     fn after_static_mem_initialized(
617         ecx: &mut InterpCx<'mir, 'tcx, Self>,
618         ptr: Pointer<Self::PointerTag>,
619         size: Size,
620     ) -> InterpResult<'tcx> {
621         if ecx.memory.extra.data_race.is_some() {
622             ecx.reset_vector_clocks(ptr, size)?;
623         }
624         Ok(())
625     }
626
627     #[inline(always)]
628     fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
629         if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
630             stacked_borrows.borrow_mut().global_base_ptr(id)
631         } else {
632             Tag::Untagged
633         }
634     }
635
636     #[inline(always)]
637     fn retag(
638         ecx: &mut InterpCx<'mir, 'tcx, Self>,
639         kind: mir::RetagKind,
640         place: &PlaceTy<'tcx, Tag>,
641     ) -> InterpResult<'tcx> {
642         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
643     }
644
645     #[inline(always)]
646     fn init_frame_extra(
647         ecx: &mut InterpCx<'mir, 'tcx, Self>,
648         frame: Frame<'mir, 'tcx, Tag>,
649     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
650         // Start recording our event before doing anything else
651         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
652             let fn_name = frame.instance.to_string();
653             let entry = ecx.machine.string_cache.entry(fn_name.clone());
654             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
655
656             Some(profiler.start_recording_interval_event_detached(
657                 *name,
658                 measureme::EventId::from_label(*name),
659                 ecx.get_active_thread().to_u32(),
660             ))
661         } else {
662             None
663         };
664
665         let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
666         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
667             stacked_borrows.borrow_mut().new_call()
668         });
669
670         let extra = FrameData { call_id, catch_unwind: None, timing };
671         Ok(frame.with_extra(extra))
672     }
673
674     fn stack<'a>(
675         ecx: &'a InterpCx<'mir, 'tcx, Self>,
676     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
677         ecx.active_thread_stack()
678     }
679
680     fn stack_mut<'a>(
681         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
682     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
683         ecx.active_thread_stack_mut()
684     }
685
686     #[inline(always)]
687     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
688         if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
689     }
690
691     #[inline(always)]
692     fn after_stack_pop(
693         ecx: &mut InterpCx<'mir, 'tcx, Self>,
694         mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
695         unwinding: bool,
696     ) -> InterpResult<'tcx, StackPopJump> {
697         let timing = frame.extra.timing.take();
698         let res = ecx.handle_stack_pop(frame.extra, unwinding);
699         if let Some(profiler) = ecx.machine.profiler.as_ref() {
700             profiler.finish_recording_interval_event(timing.unwrap());
701         }
702         res
703     }
704
705     #[inline(always)]
706     fn int_to_ptr(
707         memory: &Memory<'mir, 'tcx, Self>,
708         int: u64,
709     ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
710         intptrcast::GlobalState::int_to_ptr(int, memory)
711     }
712
713     #[inline(always)]
714     fn ptr_to_int(
715         memory: &Memory<'mir, 'tcx, Self>,
716         ptr: Pointer<Self::PointerTag>,
717     ) -> InterpResult<'tcx, u64> {
718         intptrcast::GlobalState::ptr_to_int(ptr, memory)
719     }
720 }