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