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