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