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