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