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