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