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