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