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