1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
6 use std::collections::HashSet;
8 use std::num::NonZeroU64;
9 use std::time::Instant;
11 use rand::rngs::StdRng;
12 use rand::SeedableRng;
14 use rustc_ast::ast::Mutability;
15 use rustc_data_structures::fx::FxHashMap;
17 use rustc_data_structures::static_assert_size;
22 layout::{LayoutCx, LayoutError, LayoutOf, TyAndLayout},
23 Instance, TyCtxt, TypeAndMut,
26 use rustc_span::def_id::{CrateNum, DefId};
27 use rustc_span::symbol::{sym, Symbol};
28 use rustc_target::abi::Size;
29 use rustc_target::spec::abi::Abi;
33 // Some global facts about the emulated machine.
34 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
35 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
36 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
37 pub const NUM_CPUS: u64 = 1;
39 /// Extra data stored with each stack frame
40 pub struct FrameData<'tcx> {
41 /// Extra data for Stacked Borrows.
42 pub call_id: stacked_borrows::CallId,
44 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
45 /// called by `try`). When this frame is popped during unwinding a panic,
46 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
47 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
49 /// If `measureme` profiling is enabled, holds timing information
50 /// for the start of this frame. When we finish executing this frame,
51 /// we use this to register a completed event with `measureme`.
52 pub timing: Option<measureme::DetachedTiming>,
55 impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 // Omitting `timing`, it does not support `Debug`.
58 let FrameData { call_id, catch_unwind, timing: _ } = self;
59 f.debug_struct("FrameData")
60 .field("call_id", call_id)
61 .field("catch_unwind", catch_unwind)
66 /// Extra memory kinds
67 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
68 pub enum MiriMemoryKind {
69 /// `__rust_alloc` memory.
73 /// Windows `HeapAlloc` memory.
75 /// Memory for args, errno, and other parts of the machine-managed environment.
76 /// This memory may leak.
78 /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
79 /// because we clean it up and leak-check it.
81 /// Globals copied from `tcx`.
82 /// This memory may leak.
84 /// Memory for extern statics.
85 /// This memory may leak.
87 /// Memory for thread-local statics.
88 /// This memory may leak.
92 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
94 fn into(self) -> MemoryKind<MiriMemoryKind> {
95 MemoryKind::Machine(self)
99 impl MayLeak for MiriMemoryKind {
101 fn may_leak(self) -> bool {
102 use self::MiriMemoryKind::*;
104 Rust | C | WinHeap | Runtime => false,
105 Machine | Global | ExternStatic | Tls => true,
110 impl fmt::Display for MiriMemoryKind {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 use self::MiriMemoryKind::*;
114 Rust => write!(f, "Rust heap"),
115 C => write!(f, "C heap"),
116 WinHeap => write!(f, "Windows heap"),
117 Machine => write!(f, "machine-managed memory"),
118 Runtime => write!(f, "language runtime memory"),
119 Global => write!(f, "global (static or const)"),
120 ExternStatic => write!(f, "extern static"),
121 Tls => write!(f, "thread-local static"),
126 /// Pointer provenance (tag).
127 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
129 pub alloc_id: AllocId,
130 /// Stacked Borrows tag.
134 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
135 static_assert_size!(Pointer<Tag>, 24);
136 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
137 static_assert_size!(Pointer<Option<Tag>>, 24);
138 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
139 static_assert_size!(ScalarMaybeUninit<Tag>, 32);
141 impl Provenance for Tag {
142 /// We use absolute addresses in the `offset` of a `Pointer<Tag>`.
143 const OFFSET_IS_ADDR: bool = true;
145 /// We cannot err on partial overwrites, it happens too often in practice (due to unions).
146 const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = false;
148 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 let (tag, addr) = ptr.into_parts(); // address is absolute
150 write!(f, "0x{:x}", addr.bytes())?;
151 // Forward `alternate` flag to `alloc_id` printing.
153 write!(f, "[{:#?}]", tag.alloc_id)?;
155 write!(f, "[{:?}]", tag.alloc_id)?;
157 // Print Stacked Borrows tag.
158 write!(f, "{:?}", tag.sb)
161 fn get_alloc_id(self) -> AllocId {
166 /// Extra per-allocation data
167 #[derive(Debug, Clone)]
168 pub struct AllocExtra {
169 /// Stacked Borrows state is only added if it is enabled.
170 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
171 /// Data race detection via the use of a vector-clock,
172 /// this is only added if it is enabled.
173 pub data_race: Option<data_race::AllocExtra>,
176 /// Precomputed layouts of primitive types
177 pub struct PrimitiveLayouts<'tcx> {
178 pub unit: TyAndLayout<'tcx>,
179 pub i8: TyAndLayout<'tcx>,
180 pub i32: TyAndLayout<'tcx>,
181 pub isize: TyAndLayout<'tcx>,
182 pub u8: TyAndLayout<'tcx>,
183 pub u32: TyAndLayout<'tcx>,
184 pub usize: TyAndLayout<'tcx>,
185 pub bool: TyAndLayout<'tcx>,
186 pub mut_raw_ptr: TyAndLayout<'tcx>,
189 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
190 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
191 let tcx = layout_cx.tcx;
192 let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
194 unit: layout_cx.layout_of(tcx.mk_unit())?,
195 i8: layout_cx.layout_of(tcx.types.i8)?,
196 i32: layout_cx.layout_of(tcx.types.i32)?,
197 isize: layout_cx.layout_of(tcx.types.isize)?,
198 u8: layout_cx.layout_of(tcx.types.u8)?,
199 u32: layout_cx.layout_of(tcx.types.u32)?,
200 usize: layout_cx.layout_of(tcx.types.usize)?,
201 bool: layout_cx.layout_of(tcx.types.bool)?,
202 mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
207 /// The machine itself.
208 pub struct Evaluator<'mir, 'tcx> {
209 pub stacked_borrows: Option<stacked_borrows::GlobalState>,
210 pub data_race: Option<data_race::GlobalState>,
211 pub intptrcast: intptrcast::GlobalState,
213 /// Environment variables set by `setenv`.
214 /// Miri does not expose env vars from the host to the emulated program.
215 pub(crate) env_vars: EnvVars<'tcx>,
217 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
218 /// These are *pointers* to argc/argv because macOS.
219 /// We also need the full command line as one string because of Windows.
220 pub(crate) argc: Option<MemPlace<Tag>>,
221 pub(crate) argv: Option<MemPlace<Tag>>,
222 pub(crate) cmd_line: Option<MemPlace<Tag>>,
225 pub(crate) tls: TlsData<'tcx>,
227 /// What should Miri do when an op requires communicating with the host,
228 /// such as accessing host env vars, random number generation, and
229 /// file system access.
230 pub(crate) isolated_op: IsolatedOp,
232 /// Whether to enforce the validity invariant.
233 pub(crate) validate: bool,
235 /// Whether to enforce validity (e.g., initialization) of integers and floats.
236 pub(crate) enforce_number_validity: bool,
238 /// Whether to enforce [ABI](Abi) of function calls.
239 pub(crate) enforce_abi: bool,
241 pub(crate) file_handler: shims::posix::FileHandler,
242 pub(crate) dir_handler: shims::posix::DirHandler,
244 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
245 pub(crate) time_anchor: Instant,
247 /// The set of threads.
248 pub(crate) threads: ThreadManager<'mir, 'tcx>,
250 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
251 pub(crate) layouts: PrimitiveLayouts<'tcx>,
253 /// Allocations that are considered roots of static memory (that may leak).
254 pub(crate) static_roots: Vec<AllocId>,
256 /// The `measureme` profiler used to record timing information about
257 /// the emulated program.
258 profiler: Option<measureme::Profiler>,
259 /// Used with `profiler` to cache the `StringId`s for event names
260 /// uesd with `measureme`.
261 string_cache: FxHashMap<String, measureme::StringId>,
263 /// Cache of `Instance` exported under the given `Symbol` name.
264 /// `None` means no `Instance` exported under the given name is found.
265 pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
267 /// Whether to raise a panic in the context of the evaluated process when unsupported
268 /// functionality is encountered. If `false`, an error is propagated in the Miri application context
269 /// instead (default behavior)
270 pub(crate) panic_on_unsupported: bool,
272 /// Equivalent setting as RUST_BACKTRACE on encountering an error.
273 pub(crate) backtrace_style: BacktraceStyle,
275 /// Crates which are considered local for the purposes of error reporting.
276 pub(crate) local_crates: Vec<CrateNum>,
278 /// Mapping extern static names to their base pointer.
279 extern_statics: FxHashMap<Symbol, Pointer<Tag>>,
281 /// The random number generator used for resolving non-determinism.
282 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
283 pub(crate) rng: RefCell<StdRng>,
285 /// The allocation IDs to report when they are being allocated
286 /// (helps for debugging memory leaks and use after free bugs).
287 tracked_alloc_ids: HashSet<AllocId>,
289 /// Controls whether alignment of memory accesses is being checked.
290 pub(crate) check_alignment: AlignmentCheck,
292 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
293 pub(crate) cmpxchg_weak_failure_rate: f64,
296 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
297 pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
298 let local_crates = helpers::get_local_crates(&layout_cx.tcx);
300 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
301 let profiler = config.measureme_out.as_ref().map(|out| {
302 measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
304 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
305 let stacked_borrows = if config.stacked_borrows {
306 Some(RefCell::new(stacked_borrows::GlobalStateInner::new(
307 config.tracked_pointer_tags.clone(),
308 config.tracked_call_ids.clone(),
315 if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
319 intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config)),
320 // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
321 env_vars: EnvVars::default(),
325 tls: TlsData::default(),
326 isolated_op: config.isolated_op,
327 validate: config.validate,
328 enforce_number_validity: config.check_number_validity,
329 enforce_abi: config.check_abi,
330 file_handler: Default::default(),
331 dir_handler: Default::default(),
332 time_anchor: Instant::now(),
334 threads: ThreadManager::default(),
335 static_roots: Vec::new(),
337 string_cache: Default::default(),
338 exported_symbols_cache: FxHashMap::default(),
339 panic_on_unsupported: config.panic_on_unsupported,
340 backtrace_style: config.backtrace_style,
342 extern_statics: FxHashMap::default(),
343 rng: RefCell::new(rng),
344 tracked_alloc_ids: config.tracked_alloc_ids.clone(),
345 check_alignment: config.check_alignment,
346 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
350 pub(crate) fn late_init(
351 this: &mut MiriEvalContext<'mir, 'tcx>,
353 ) -> InterpResult<'tcx> {
354 EnvVars::init(this, config)?;
355 Evaluator::init_extern_statics(this)?;
359 fn add_extern_static(
360 this: &mut MiriEvalContext<'mir, 'tcx>,
362 ptr: Pointer<Option<Tag>>,
364 // This got just allocated, so there definitely is a pointer here.
365 let ptr = ptr.into_pointer_or_addr().unwrap();
366 this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
369 /// Sets up the "extern statics" for this machine.
370 fn init_extern_statics(this: &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx> {
371 match this.tcx.sess.target.os.as_ref() {
374 Self::add_extern_static(
377 this.machine.env_vars.environ.unwrap().ptr,
379 // A couple zero-initialized pointer-sized extern statics.
380 // Most of them are for weak symbols, which we all set to null (indicating that the
381 // symbol is not supported, and triggering fallback code which ends up calling a
382 // syscall that we do support).
383 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx"] {
384 let layout = this.machine.layouts.usize;
385 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
386 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
387 Self::add_extern_static(this, name, place.ptr);
392 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
393 let layout = this.machine.layouts.u8;
394 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
395 this.write_scalar(Scalar::from_u8(0), &place.into())?;
396 Self::add_extern_static(this, "_tls_used", place.ptr);
398 _ => {} // No "extern statics" supported on this target
403 pub(crate) fn communicate(&self) -> bool {
404 self.isolated_op == IsolatedOp::Allow
407 /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
408 pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
409 let def_id = frame.instance.def_id();
410 def_id.is_local() || self.local_crates.contains(&def_id.krate)
414 /// A rustc InterpCx for Miri.
415 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
417 /// A little trait that's useful to be inherited by extension traits.
418 pub trait MiriEvalContextExt<'mir, 'tcx> {
419 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
420 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
422 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
424 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
428 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
433 /// Machine hook implementations.
434 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
435 type MemoryKind = MiriMemoryKind;
436 type ExtraFnVal = Dlsym;
438 type FrameExtra = FrameData<'tcx>;
439 type AllocExtra = AllocExtra;
441 type PointerTag = Tag;
442 type TagExtra = SbTag;
445 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
447 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
449 const PANIC_ON_ALLOC_FAIL: bool = false;
452 fn enforce_alignment(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
453 ecx.machine.check_alignment != AlignmentCheck::None
457 fn force_int_for_alignment_check(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
458 ecx.machine.check_alignment == AlignmentCheck::Int
462 fn enforce_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
467 fn enforce_number_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
468 ecx.machine.enforce_number_validity
472 fn enforce_abi(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
473 ecx.machine.enforce_abi
477 fn find_mir_or_eval_fn(
478 ecx: &mut MiriEvalContext<'mir, 'tcx>,
479 instance: ty::Instance<'tcx>,
481 args: &[OpTy<'tcx, Tag>],
482 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
483 unwind: StackPopUnwind,
484 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
485 ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
490 ecx: &mut MiriEvalContext<'mir, 'tcx>,
493 args: &[OpTy<'tcx, Tag>],
494 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
495 _unwind: StackPopUnwind,
496 ) -> InterpResult<'tcx> {
497 ecx.call_dlsym(fn_val, abi, args, ret)
502 ecx: &mut MiriEvalContext<'mir, 'tcx>,
503 instance: ty::Instance<'tcx>,
504 args: &[OpTy<'tcx, Tag>],
505 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
506 unwind: StackPopUnwind,
507 ) -> InterpResult<'tcx> {
508 ecx.call_intrinsic(instance, args, ret, unwind)
513 ecx: &mut MiriEvalContext<'mir, 'tcx>,
514 msg: &mir::AssertMessage<'tcx>,
515 unwind: Option<mir::BasicBlock>,
516 ) -> InterpResult<'tcx> {
517 ecx.assert_panic(msg, unwind)
521 fn abort(_ecx: &mut MiriEvalContext<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
522 throw_machine_stop!(TerminationInfo::Abort(msg))
527 ecx: &MiriEvalContext<'mir, 'tcx>,
529 left: &ImmTy<'tcx, Tag>,
530 right: &ImmTy<'tcx, Tag>,
531 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
532 ecx.binary_ptr_op(bin_op, left, right)
535 fn thread_local_static_base_pointer(
536 ecx: &mut MiriEvalContext<'mir, 'tcx>,
538 ) -> InterpResult<'tcx, Pointer<Tag>> {
539 ecx.get_or_create_thread_local_alloc(def_id)
542 fn extern_static_base_pointer(
543 ecx: &MiriEvalContext<'mir, 'tcx>,
545 ) -> InterpResult<'tcx, Pointer<Tag>> {
546 let attrs = ecx.tcx.get_attrs(def_id);
547 let link_name = match ecx.tcx.sess.first_attr_value_str_by_name(attrs, sym::link_name) {
549 None => ecx.tcx.item_name(def_id),
551 if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
554 throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
558 fn init_allocation_extra<'b>(
559 ecx: &MiriEvalContext<'mir, 'tcx>,
561 alloc: Cow<'b, Allocation>,
562 kind: Option<MemoryKind<Self::MemoryKind>>,
563 ) -> Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>> {
564 if ecx.machine.tracked_alloc_ids.contains(&id) {
565 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
568 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
569 let alloc = alloc.into_owned();
570 let stacks = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
571 Some(Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind))
575 let race_alloc = if let Some(data_race) = &ecx.machine.data_race {
576 Some(data_race::AllocExtra::new_allocation(data_race, alloc.size(), kind))
580 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.convert_tag_add_extra(
582 AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
583 |ptr| Evaluator::tag_alloc_base_pointer(ecx, ptr),
588 fn tag_alloc_base_pointer(
589 ecx: &MiriEvalContext<'mir, 'tcx>,
590 ptr: Pointer<AllocId>,
592 let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
593 let sb_tag = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
594 stacked_borrows.borrow_mut().base_tag(ptr.provenance)
598 Pointer::new(Tag { alloc_id: ptr.provenance, sb: sb_tag }, Size::from_bytes(absolute_addr))
603 ecx: &MiriEvalContext<'mir, 'tcx>,
605 ) -> Pointer<Option<Self::PointerTag>> {
606 intptrcast::GlobalStateInner::ptr_from_addr(addr, ecx)
609 /// Convert a pointer with provenance into an allocation-offset pair,
610 /// or a `None` with an absolute address if that conversion is not possible.
612 ecx: &MiriEvalContext<'mir, 'tcx>,
613 ptr: Pointer<Self::PointerTag>,
614 ) -> (AllocId, Size, Self::TagExtra) {
615 let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
616 (ptr.provenance.alloc_id, rel, ptr.provenance.sb)
623 alloc_extra: &AllocExtra,
624 (alloc_id, tag): (AllocId, Self::TagExtra),
626 ) -> InterpResult<'tcx> {
627 if let Some(data_race) = &alloc_extra.data_race {
628 data_race.read(alloc_id, range, machine.data_race.as_ref().unwrap())?;
630 if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
631 stacked_borrows.memory_read(
635 machine.stacked_borrows.as_ref().unwrap(),
646 alloc_extra: &mut AllocExtra,
647 (alloc_id, tag): (AllocId, Self::TagExtra),
649 ) -> InterpResult<'tcx> {
650 if let Some(data_race) = &mut alloc_extra.data_race {
651 data_race.write(alloc_id, range, machine.data_race.as_mut().unwrap())?;
653 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
654 stacked_borrows.memory_written(
658 machine.stacked_borrows.as_mut().unwrap(),
666 fn memory_deallocated(
669 alloc_extra: &mut AllocExtra,
670 (alloc_id, tag): (AllocId, Self::TagExtra),
672 ) -> InterpResult<'tcx> {
673 if machine.tracked_alloc_ids.contains(&alloc_id) {
674 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
676 if let Some(data_race) = &mut alloc_extra.data_race {
677 data_race.deallocate(alloc_id, range, machine.data_race.as_mut().unwrap())?;
679 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
680 stacked_borrows.memory_deallocated(
684 machine.stacked_borrows.as_mut().unwrap(),
693 ecx: &mut InterpCx<'mir, 'tcx, Self>,
694 kind: mir::RetagKind,
695 place: &PlaceTy<'tcx, Tag>,
696 ) -> InterpResult<'tcx> {
697 if ecx.machine.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
702 ecx: &mut InterpCx<'mir, 'tcx, Self>,
703 frame: Frame<'mir, 'tcx, Tag>,
704 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
705 // Start recording our event before doing anything else
706 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
707 let fn_name = frame.instance.to_string();
708 let entry = ecx.machine.string_cache.entry(fn_name.clone());
709 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
711 Some(profiler.start_recording_interval_event_detached(
713 measureme::EventId::from_label(*name),
714 ecx.get_active_thread().to_u32(),
720 let stacked_borrows = ecx.machine.stacked_borrows.as_ref();
721 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
722 stacked_borrows.borrow_mut().new_call()
725 let extra = FrameData { call_id, catch_unwind: None, timing };
726 Ok(frame.with_extra(extra))
730 ecx: &'a InterpCx<'mir, 'tcx, Self>,
731 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
732 ecx.active_thread_stack()
736 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
737 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
738 ecx.active_thread_stack_mut()
742 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
743 if ecx.machine.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
748 ecx: &mut InterpCx<'mir, 'tcx, Self>,
749 mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
751 ) -> InterpResult<'tcx, StackPopJump> {
752 let timing = frame.extra.timing.take();
753 let res = ecx.handle_stack_pop(frame.extra, unwinding);
754 if let Some(profiler) = ecx.machine.profiler.as_ref() {
755 profiler.finish_recording_interval_event(timing.unwrap());