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