]> git.lizzy.rs Git - rust.git/blob - src/machine.rs
tweaks and feedback
[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 // #[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, "0x{: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
338 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
339     pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
340         let local_crates = helpers::get_local_crates(layout_cx.tcx);
341         let layouts =
342             PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
343         let profiler = config.measureme_out.as_ref().map(|out| {
344             measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
345         });
346         let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
347         let stacked_borrows = if config.stacked_borrows {
348             Some(RefCell::new(stacked_borrows::GlobalStateInner::new(
349                 config.tracked_pointer_tags.clone(),
350                 config.tracked_call_ids.clone(),
351                 config.tag_raw,
352             )))
353         } else {
354             None
355         };
356         let data_race =
357             if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
358         Evaluator {
359             stacked_borrows,
360             data_race,
361             intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config)),
362             // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
363             env_vars: EnvVars::default(),
364             argc: None,
365             argv: None,
366             cmd_line: None,
367             tls: TlsData::default(),
368             isolated_op: config.isolated_op,
369             validate: config.validate,
370             allow_uninit_numbers: config.allow_uninit_numbers,
371             allow_ptr_int_transmute: config.allow_ptr_int_transmute,
372             enforce_abi: config.check_abi,
373             file_handler: FileHandler::new(config.mute_stdout_stderr),
374             dir_handler: Default::default(),
375             time_anchor: Instant::now(),
376             layouts,
377             threads: ThreadManager::default(),
378             static_roots: Vec::new(),
379             profiler,
380             string_cache: Default::default(),
381             exported_symbols_cache: FxHashMap::default(),
382             panic_on_unsupported: config.panic_on_unsupported,
383             backtrace_style: config.backtrace_style,
384             local_crates,
385             extern_statics: FxHashMap::default(),
386             rng: RefCell::new(rng),
387             tracked_alloc_ids: config.tracked_alloc_ids.clone(),
388             check_alignment: config.check_alignment,
389             cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
390             mute_stdout_stderr: config.mute_stdout_stderr,
391             weak_memory: config.weak_memory_emulation,
392             preemption_rate: config.preemption_rate,
393         }
394     }
395
396     pub(crate) fn late_init(
397         this: &mut MiriEvalContext<'mir, 'tcx>,
398         config: &MiriConfig,
399     ) -> InterpResult<'tcx> {
400         EnvVars::init(this, config)?;
401         Evaluator::init_extern_statics(this)?;
402         Ok(())
403     }
404
405     fn add_extern_static(
406         this: &mut MiriEvalContext<'mir, 'tcx>,
407         name: &str,
408         ptr: Pointer<Option<Tag>>,
409     ) {
410         // This got just allocated, so there definitely is a pointer here.
411         let ptr = ptr.into_pointer_or_addr().unwrap();
412         this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
413     }
414
415     /// Sets up the "extern statics" for this machine.
416     fn init_extern_statics(this: &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx> {
417         match this.tcx.sess.target.os.as_ref() {
418             "linux" => {
419                 // "environ"
420                 Self::add_extern_static(
421                     this,
422                     "environ",
423                     this.machine.env_vars.environ.unwrap().ptr,
424                 );
425                 // A couple zero-initialized pointer-sized extern statics.
426                 // Most of them are for weak symbols, which we all set to null (indicating that the
427                 // symbol is not supported, and triggering fallback code which ends up calling a
428                 // syscall that we do support).
429                 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"]
430                 {
431                     let layout = this.machine.layouts.usize;
432                     let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
433                     this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
434                     Self::add_extern_static(this, name, place.ptr);
435                 }
436             }
437             "windows" => {
438                 // "_tls_used"
439                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
440                 let layout = this.machine.layouts.u8;
441                 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
442                 this.write_scalar(Scalar::from_u8(0), &place.into())?;
443                 Self::add_extern_static(this, "_tls_used", place.ptr);
444             }
445             _ => {} // No "extern statics" supported on this target
446         }
447         Ok(())
448     }
449
450     pub(crate) fn communicate(&self) -> bool {
451         self.isolated_op == IsolatedOp::Allow
452     }
453
454     /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
455     pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
456         let def_id = frame.instance.def_id();
457         def_id.is_local() || self.local_crates.contains(&def_id.krate)
458     }
459 }
460
461 /// A rustc InterpCx for Miri.
462 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
463
464 /// A little trait that's useful to be inherited by extension traits.
465 pub trait MiriEvalContextExt<'mir, 'tcx> {
466     fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
467     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
468 }
469 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
470     #[inline(always)]
471     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
472         self
473     }
474     #[inline(always)]
475     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
476         self
477     }
478 }
479
480 /// Machine hook implementations.
481 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
482     type MemoryKind = MiriMemoryKind;
483     type ExtraFnVal = Dlsym;
484
485     type FrameExtra = FrameData<'tcx>;
486     type AllocExtra = AllocExtra;
487
488     type PointerTag = Tag;
489     type TagExtra = SbTagExtra;
490
491     type MemoryMap =
492         MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
493
494     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
495
496     const PANIC_ON_ALLOC_FAIL: bool = false;
497
498     #[inline(always)]
499     fn enforce_alignment(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
500         ecx.machine.check_alignment != AlignmentCheck::None
501     }
502
503     #[inline(always)]
504     fn force_int_for_alignment_check(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
505         ecx.machine.check_alignment == AlignmentCheck::Int
506     }
507
508     #[inline(always)]
509     fn enforce_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
510         ecx.machine.validate
511     }
512
513     #[inline(always)]
514     fn enforce_number_init(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
515         !ecx.machine.allow_uninit_numbers
516     }
517
518     #[inline(always)]
519     fn enforce_number_no_provenance(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
520         !ecx.machine.allow_ptr_int_transmute
521     }
522
523     #[inline(always)]
524     fn enforce_abi(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
525         ecx.machine.enforce_abi
526     }
527
528     #[inline(always)]
529     fn find_mir_or_eval_fn(
530         ecx: &mut MiriEvalContext<'mir, 'tcx>,
531         instance: ty::Instance<'tcx>,
532         abi: Abi,
533         args: &[OpTy<'tcx, Tag>],
534         dest: &PlaceTy<'tcx, Tag>,
535         ret: Option<mir::BasicBlock>,
536         unwind: StackPopUnwind,
537     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
538         ecx.find_mir_or_eval_fn(instance, abi, args, dest, ret, unwind)
539     }
540
541     #[inline(always)]
542     fn call_extra_fn(
543         ecx: &mut MiriEvalContext<'mir, 'tcx>,
544         fn_val: Dlsym,
545         abi: Abi,
546         args: &[OpTy<'tcx, Tag>],
547         dest: &PlaceTy<'tcx, Tag>,
548         ret: Option<mir::BasicBlock>,
549         _unwind: StackPopUnwind,
550     ) -> InterpResult<'tcx> {
551         ecx.call_dlsym(fn_val, abi, args, dest, ret)
552     }
553
554     #[inline(always)]
555     fn call_intrinsic(
556         ecx: &mut MiriEvalContext<'mir, 'tcx>,
557         instance: ty::Instance<'tcx>,
558         args: &[OpTy<'tcx, Tag>],
559         dest: &PlaceTy<'tcx, Tag>,
560         ret: Option<mir::BasicBlock>,
561         unwind: StackPopUnwind,
562     ) -> InterpResult<'tcx> {
563         ecx.call_intrinsic(instance, args, dest, ret, unwind)
564     }
565
566     #[inline(always)]
567     fn assert_panic(
568         ecx: &mut MiriEvalContext<'mir, 'tcx>,
569         msg: &mir::AssertMessage<'tcx>,
570         unwind: Option<mir::BasicBlock>,
571     ) -> InterpResult<'tcx> {
572         ecx.assert_panic(msg, unwind)
573     }
574
575     #[inline(always)]
576     fn abort(_ecx: &mut MiriEvalContext<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
577         throw_machine_stop!(TerminationInfo::Abort(msg))
578     }
579
580     #[inline(always)]
581     fn binary_ptr_op(
582         ecx: &MiriEvalContext<'mir, 'tcx>,
583         bin_op: mir::BinOp,
584         left: &ImmTy<'tcx, Tag>,
585         right: &ImmTy<'tcx, Tag>,
586     ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
587         ecx.binary_ptr_op(bin_op, left, right)
588     }
589
590     fn thread_local_static_base_pointer(
591         ecx: &mut MiriEvalContext<'mir, 'tcx>,
592         def_id: DefId,
593     ) -> InterpResult<'tcx, Pointer<Tag>> {
594         ecx.get_or_create_thread_local_alloc(def_id)
595     }
596
597     fn extern_static_base_pointer(
598         ecx: &MiriEvalContext<'mir, 'tcx>,
599         def_id: DefId,
600     ) -> InterpResult<'tcx, Pointer<Tag>> {
601         let link_name = ecx.item_link_name(def_id);
602         if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
603             Ok(ptr)
604         } else {
605             throw_unsup_format!(
606                 "`extern` static `{}` from crate `{}` is not supported by Miri",
607                 ecx.tcx.def_path_str(def_id),
608                 ecx.tcx.crate_name(def_id.krate),
609             )
610         }
611     }
612
613     fn init_allocation_extra<'b>(
614         ecx: &MiriEvalContext<'mir, 'tcx>,
615         id: AllocId,
616         alloc: Cow<'b, Allocation>,
617         kind: Option<MemoryKind<Self::MemoryKind>>,
618     ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>> {
619         if ecx.machine.tracked_alloc_ids.contains(&id) {
620             register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
621         }
622
623         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
624         let alloc = alloc.into_owned();
625         let stacks = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
626             Some(Stacks::new_allocation(
627                 id,
628                 alloc.size(),
629                 stacked_borrows,
630                 kind,
631                 ecx.machine.current_span(),
632             ))
633         } else {
634             None
635         };
636         let race_alloc = if let Some(data_race) = &ecx.machine.data_race {
637             Some(data_race::AllocExtra::new_allocation(data_race, alloc.size(), kind))
638         } else {
639             None
640         };
641         let buffer_alloc = if ecx.machine.weak_memory {
642             Some(weak_memory::AllocExtra::new_allocation())
643         } else {
644             None
645         };
646         let alloc: Allocation<Tag, Self::AllocExtra> = alloc.convert_tag_add_extra(
647             &ecx.tcx,
648             AllocExtra {
649                 stacked_borrows: stacks.map(RefCell::new),
650                 data_race: race_alloc,
651                 weak_memory: buffer_alloc,
652             },
653             |ptr| ecx.global_base_pointer(ptr),
654         )?;
655         Ok(Cow::Owned(alloc))
656     }
657
658     fn tag_alloc_base_pointer(
659         ecx: &MiriEvalContext<'mir, 'tcx>,
660         ptr: Pointer<AllocId>,
661     ) -> Pointer<Tag> {
662         if cfg!(debug_assertions) {
663             // The machine promises to never call us on thread-local or extern statics.
664             let alloc_id = ptr.provenance;
665             match ecx.tcx.get_global_alloc(alloc_id) {
666                 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
667                     panic!("tag_alloc_base_pointer called on thread-local static")
668                 }
669                 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
670                     panic!("tag_alloc_base_pointer called on extern static")
671                 }
672                 _ => {}
673             }
674         }
675         let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
676         let sb_tag = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
677             stacked_borrows.borrow_mut().base_tag(ptr.provenance)
678         } else {
679             SbTag::Untagged
680         };
681         Pointer::new(
682             Tag::Concrete { alloc_id: ptr.provenance, sb: sb_tag },
683             Size::from_bytes(absolute_addr),
684         )
685     }
686
687     #[inline(always)]
688     fn ptr_from_addr_cast(
689         ecx: &MiriEvalContext<'mir, 'tcx>,
690         addr: u64,
691     ) -> InterpResult<'tcx, Pointer<Option<Self::PointerTag>>> {
692         Ok(intptrcast::GlobalStateInner::ptr_from_addr_cast(ecx, addr))
693     }
694
695     #[inline(always)]
696     fn ptr_from_addr_transmute(
697         ecx: &MiriEvalContext<'mir, 'tcx>,
698         addr: u64,
699     ) -> Pointer<Option<Self::PointerTag>> {
700         intptrcast::GlobalStateInner::ptr_from_addr_transmute(ecx, addr)
701     }
702
703     fn expose_ptr(
704         ecx: &mut InterpCx<'mir, 'tcx, Self>,
705         ptr: Pointer<Self::PointerTag>,
706     ) -> InterpResult<'tcx> {
707         match ptr.provenance {
708             Tag::Concrete { alloc_id, sb } => {
709                 intptrcast::GlobalStateInner::expose_ptr(ecx, alloc_id, sb);
710             }
711             Tag::Wildcard => {
712                 // No need to do anything for wildcard pointers as
713                 // their provenances have already been previously exposed.
714             }
715         }
716         Ok(())
717     }
718
719     /// Convert a pointer with provenance into an allocation-offset pair,
720     /// or a `None` with an absolute address if that conversion is not possible.
721     fn ptr_get_alloc(
722         ecx: &MiriEvalContext<'mir, 'tcx>,
723         ptr: Pointer<Self::PointerTag>,
724     ) -> Option<(AllocId, Size, Self::TagExtra)> {
725         let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
726
727         rel.map(|(alloc_id, size)| {
728             let sb = match ptr.provenance {
729                 Tag::Concrete { sb, .. } => SbTagExtra::Concrete(sb),
730                 Tag::Wildcard => SbTagExtra::Wildcard,
731             };
732             (alloc_id, size, sb)
733         })
734     }
735
736     #[inline(always)]
737     fn memory_read(
738         _tcx: TyCtxt<'tcx>,
739         machine: &Self,
740         alloc_extra: &AllocExtra,
741         (alloc_id, tag): (AllocId, Self::TagExtra),
742         range: AllocRange,
743     ) -> InterpResult<'tcx> {
744         if let Some(data_race) = &alloc_extra.data_race {
745             data_race.read(alloc_id, range, machine.data_race.as_ref().unwrap())?;
746         }
747         if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
748             stacked_borrows.borrow_mut().memory_read(
749                 alloc_id,
750                 tag,
751                 range,
752                 machine.stacked_borrows.as_ref().unwrap(),
753                 machine.current_span(),
754             )?;
755         }
756         if let Some(weak_memory) = &alloc_extra.weak_memory {
757             weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
758         }
759         Ok(())
760     }
761
762     #[inline(always)]
763     fn memory_written(
764         _tcx: TyCtxt<'tcx>,
765         machine: &mut Self,
766         alloc_extra: &mut AllocExtra,
767         (alloc_id, tag): (AllocId, Self::TagExtra),
768         range: AllocRange,
769     ) -> InterpResult<'tcx> {
770         if let Some(data_race) = &mut alloc_extra.data_race {
771             data_race.write(alloc_id, range, machine.data_race.as_mut().unwrap())?;
772         }
773         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
774             stacked_borrows.get_mut().memory_written(
775                 alloc_id,
776                 tag,
777                 range,
778                 machine.stacked_borrows.as_ref().unwrap(),
779                 machine.current_span(),
780             )?;
781         }
782         if let Some(weak_memory) = &alloc_extra.weak_memory {
783             weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
784         }
785         Ok(())
786     }
787
788     #[inline(always)]
789     fn memory_deallocated(
790         _tcx: TyCtxt<'tcx>,
791         machine: &mut Self,
792         alloc_extra: &mut AllocExtra,
793         (alloc_id, tag): (AllocId, Self::TagExtra),
794         range: AllocRange,
795     ) -> InterpResult<'tcx> {
796         if machine.tracked_alloc_ids.contains(&alloc_id) {
797             register_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
798         }
799         if let Some(data_race) = &mut alloc_extra.data_race {
800             data_race.deallocate(alloc_id, range, machine.data_race.as_mut().unwrap())?;
801         }
802         if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
803             stacked_borrows.get_mut().memory_deallocated(
804                 alloc_id,
805                 tag,
806                 range,
807                 machine.stacked_borrows.as_ref().unwrap(),
808             )
809         } else {
810             Ok(())
811         }
812     }
813
814     #[inline(always)]
815     fn retag(
816         ecx: &mut InterpCx<'mir, 'tcx, Self>,
817         kind: mir::RetagKind,
818         place: &PlaceTy<'tcx, Tag>,
819     ) -> InterpResult<'tcx> {
820         if ecx.machine.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
821     }
822
823     #[inline(always)]
824     fn init_frame_extra(
825         ecx: &mut InterpCx<'mir, 'tcx, Self>,
826         frame: Frame<'mir, 'tcx, Tag>,
827     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
828         // Start recording our event before doing anything else
829         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
830             let fn_name = frame.instance.to_string();
831             let entry = ecx.machine.string_cache.entry(fn_name.clone());
832             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
833
834             Some(profiler.start_recording_interval_event_detached(
835                 *name,
836                 measureme::EventId::from_label(*name),
837                 ecx.get_active_thread().to_u32(),
838             ))
839         } else {
840             None
841         };
842
843         let stacked_borrows = ecx.machine.stacked_borrows.as_ref();
844         let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
845             stacked_borrows.borrow_mut().new_call()
846         });
847
848         let extra = FrameData { call_id, catch_unwind: None, timing };
849         Ok(frame.with_extra(extra))
850     }
851
852     fn stack<'a>(
853         ecx: &'a InterpCx<'mir, 'tcx, Self>,
854     ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
855         ecx.active_thread_stack()
856     }
857
858     fn stack_mut<'a>(
859         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
860     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
861         ecx.active_thread_stack_mut()
862     }
863
864     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
865         ecx.maybe_preempt_active_thread();
866         Ok(())
867     }
868
869     #[inline(always)]
870     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
871         if ecx.machine.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
872     }
873
874     #[inline(always)]
875     fn after_stack_pop(
876         ecx: &mut InterpCx<'mir, 'tcx, Self>,
877         mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
878         unwinding: bool,
879     ) -> InterpResult<'tcx, StackPopJump> {
880         let timing = frame.extra.timing.take();
881         let res = ecx.handle_stack_pop(frame.extra, unwinding);
882         if let Some(profiler) = ecx.machine.profiler.as_ref() {
883             profiler.finish_recording_interval_event(timing.unwrap());
884         }
885         res
886     }
887 }