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