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