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