]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/machine.rs
Rollup merge of #107710 - ehuss:update-strip-ansi-escapes, r=Mark-Simulacrum
[rust.git] / src / tools / miri / 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::fmt;
7
8 use rand::rngs::StdRng;
9 use rand::SeedableRng;
10
11 use rustc_ast::ast::Mutability;
12 use rustc_const_eval::const_eval::CheckAlignment;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 #[allow(unused)]
15 use rustc_data_structures::static_assert_size;
16 use rustc_middle::{
17     mir,
18     ty::{
19         self,
20         layout::{LayoutCx, LayoutError, LayoutOf, TyAndLayout},
21         Instance, Ty, TyCtxt, TypeAndMut,
22     },
23 };
24 use rustc_span::def_id::{CrateNum, DefId};
25 use rustc_span::Symbol;
26 use rustc_target::abi::{Align, Size};
27 use rustc_target::spec::abi::Abi;
28
29 use crate::{
30     concurrency::{data_race, weak_memory},
31     shims::unix::FileHandler,
32     *,
33 };
34
35 /// The number of the available real-time signal with the lowest priority.
36 /// Dummy constant related to epoll, must be between 32 and 64.
37 pub const SIGRTMAX: i32 = 42;
38
39 /// Extra data stored with each stack frame
40 pub struct FrameExtra<'tcx> {
41     /// Extra data for Stacked Borrows.
42     pub borrow_tracker: Option<borrow_tracker::FrameState>,
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     /// Indicates whether a `Frame` is part of a workspace-local crate and is also not
55     /// `#[track_caller]`. We compute this once on creation and store the result, as an
56     /// optimization.
57     /// This is used by `MiriMachine::current_span` and `MiriMachine::caller_span`
58     pub is_user_relevant: bool,
59 }
60
61 impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> {
62     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63         // Omitting `timing`, it does not support `Debug`.
64         let FrameExtra { borrow_tracker, catch_unwind, timing: _, is_user_relevant: _ } = self;
65         f.debug_struct("FrameData")
66             .field("borrow_tracker", borrow_tracker)
67             .field("catch_unwind", catch_unwind)
68             .finish()
69     }
70 }
71
72 impl VisitTags for FrameExtra<'_> {
73     fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
74         let FrameExtra { catch_unwind, borrow_tracker, timing: _, is_user_relevant: _ } = self;
75
76         catch_unwind.visit_tags(visit);
77         borrow_tracker.visit_tags(visit);
78     }
79 }
80
81 /// Extra memory kinds
82 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
83 pub enum MiriMemoryKind {
84     /// `__rust_alloc` memory.
85     Rust,
86     /// `miri_alloc` memory.
87     Miri,
88     /// `malloc` memory.
89     C,
90     /// Windows `HeapAlloc` memory.
91     WinHeap,
92     /// Memory for args, errno, and other parts of the machine-managed environment.
93     /// This memory may leak.
94     Machine,
95     /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
96     /// because we clean it up and leak-check it.
97     Runtime,
98     /// Globals copied from `tcx`.
99     /// This memory may leak.
100     Global,
101     /// Memory for extern statics.
102     /// This memory may leak.
103     ExternStatic,
104     /// Memory for thread-local statics.
105     /// This memory may leak.
106     Tls,
107 }
108
109 impl From<MiriMemoryKind> for MemoryKind<MiriMemoryKind> {
110     #[inline(always)]
111     fn from(kind: MiriMemoryKind) -> MemoryKind<MiriMemoryKind> {
112         MemoryKind::Machine(kind)
113     }
114 }
115
116 impl MayLeak for MiriMemoryKind {
117     #[inline(always)]
118     fn may_leak(self) -> bool {
119         use self::MiriMemoryKind::*;
120         match self {
121             Rust | Miri | C | WinHeap | Runtime => false,
122             Machine | Global | ExternStatic | Tls => true,
123         }
124     }
125 }
126
127 impl fmt::Display for MiriMemoryKind {
128     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129         use self::MiriMemoryKind::*;
130         match self {
131             Rust => write!(f, "Rust heap"),
132             Miri => write!(f, "Miri bare-metal heap"),
133             C => write!(f, "C heap"),
134             WinHeap => write!(f, "Windows heap"),
135             Machine => write!(f, "machine-managed memory"),
136             Runtime => write!(f, "language runtime memory"),
137             Global => write!(f, "global (static or const)"),
138             ExternStatic => write!(f, "extern static"),
139             Tls => write!(f, "thread-local static"),
140         }
141     }
142 }
143
144 /// Pointer provenance.
145 #[derive(Clone, Copy)]
146 pub enum Provenance {
147     Concrete {
148         alloc_id: AllocId,
149         /// Stacked Borrows tag.
150         tag: BorTag,
151     },
152     Wildcard,
153 }
154
155 // This needs to be `Eq`+`Hash` because the `Machine` trait needs that because validity checking
156 // *might* be recursive and then it has to track which places have already been visited.
157 // However, comparing provenance is meaningless, since `Wildcard` might be any provenance -- and of
158 // course we don't actually do recursive checking.
159 // We could change `RefTracking` to strip provenance for its `seen` set but that type is generic so that is quite annoying.
160 // Instead owe add the required instances but make them panic.
161 impl PartialEq for Provenance {
162     fn eq(&self, _other: &Self) -> bool {
163         panic!("Provenance must not be compared")
164     }
165 }
166 impl Eq for Provenance {}
167 impl std::hash::Hash for Provenance {
168     fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
169         panic!("Provenance must not be hashed")
170     }
171 }
172
173 /// The "extra" information a pointer has over a regular AllocId.
174 #[derive(Copy, Clone, PartialEq)]
175 pub enum ProvenanceExtra {
176     Concrete(BorTag),
177     Wildcard,
178 }
179
180 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
181 static_assert_size!(Pointer<Provenance>, 24);
182 // FIXME: this would with in 24bytes but layout optimizations are not smart enough
183 // #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
184 //static_assert_size!(Pointer<Option<Provenance>>, 24);
185 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
186 static_assert_size!(Scalar<Provenance>, 32);
187
188 impl fmt::Debug for Provenance {
189     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190         match self {
191             Provenance::Concrete { alloc_id, tag } => {
192                 // Forward `alternate` flag to `alloc_id` printing.
193                 if f.alternate() {
194                     write!(f, "[{alloc_id:#?}]")?;
195                 } else {
196                     write!(f, "[{alloc_id:?}]")?;
197                 }
198                 // Print Stacked Borrows tag.
199                 write!(f, "{tag:?}")?;
200             }
201             Provenance::Wildcard => {
202                 write!(f, "[wildcard]")?;
203             }
204         }
205         Ok(())
206     }
207 }
208
209 impl interpret::Provenance for Provenance {
210     /// We use absolute addresses in the `offset` of a `Pointer<Provenance>`.
211     const OFFSET_IS_ADDR: bool = true;
212
213     fn get_alloc_id(self) -> Option<AllocId> {
214         match self {
215             Provenance::Concrete { alloc_id, .. } => Some(alloc_id),
216             Provenance::Wildcard => None,
217         }
218     }
219
220     fn join(left: Option<Self>, right: Option<Self>) -> Option<Self> {
221         match (left, right) {
222             // If both are the *same* concrete tag, that is the result.
223             (
224                 Some(Provenance::Concrete { alloc_id: left_alloc, tag: left_tag }),
225                 Some(Provenance::Concrete { alloc_id: right_alloc, tag: right_tag }),
226             ) if left_alloc == right_alloc && left_tag == right_tag => left,
227             // If one side is a wildcard, the best possible outcome is that it is equal to the other
228             // one, and we use that.
229             (Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o,
230             // Otherwise, fall back to `None`.
231             _ => None,
232         }
233     }
234 }
235
236 impl fmt::Debug for ProvenanceExtra {
237     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238         match self {
239             ProvenanceExtra::Concrete(pid) => write!(f, "{pid:?}"),
240             ProvenanceExtra::Wildcard => write!(f, "<wildcard>"),
241         }
242     }
243 }
244
245 impl ProvenanceExtra {
246     pub fn and_then<T>(self, f: impl FnOnce(BorTag) -> Option<T>) -> Option<T> {
247         match self {
248             ProvenanceExtra::Concrete(pid) => f(pid),
249             ProvenanceExtra::Wildcard => None,
250         }
251     }
252 }
253
254 /// Extra per-allocation data
255 #[derive(Debug, Clone)]
256 pub struct AllocExtra {
257     /// Global state of the borrow tracker, if enabled.
258     pub borrow_tracker: Option<borrow_tracker::AllocState>,
259     /// Data race detection via the use of a vector-clock,
260     ///  this is only added if it is enabled.
261     pub data_race: Option<data_race::AllocState>,
262     /// Weak memory emulation via the use of store buffers,
263     ///  this is only added if it is enabled.
264     pub weak_memory: Option<weak_memory::AllocState>,
265 }
266
267 impl VisitTags for AllocExtra {
268     fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
269         let AllocExtra { borrow_tracker, data_race, weak_memory } = self;
270
271         borrow_tracker.visit_tags(visit);
272         data_race.visit_tags(visit);
273         weak_memory.visit_tags(visit);
274     }
275 }
276
277 /// Precomputed layouts of primitive types
278 pub struct PrimitiveLayouts<'tcx> {
279     pub unit: TyAndLayout<'tcx>,
280     pub i8: TyAndLayout<'tcx>,
281     pub i16: TyAndLayout<'tcx>,
282     pub i32: TyAndLayout<'tcx>,
283     pub i64: TyAndLayout<'tcx>,
284     pub i128: TyAndLayout<'tcx>,
285     pub isize: TyAndLayout<'tcx>,
286     pub u8: TyAndLayout<'tcx>,
287     pub u16: TyAndLayout<'tcx>,
288     pub u32: TyAndLayout<'tcx>,
289     pub u64: TyAndLayout<'tcx>,
290     pub u128: TyAndLayout<'tcx>,
291     pub usize: TyAndLayout<'tcx>,
292     pub bool: TyAndLayout<'tcx>,
293     pub mut_raw_ptr: TyAndLayout<'tcx>,   // *mut ()
294     pub const_raw_ptr: TyAndLayout<'tcx>, // *const ()
295 }
296
297 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
298     fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
299         let tcx = layout_cx.tcx;
300         let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
301         let const_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Not });
302         Ok(Self {
303             unit: layout_cx.layout_of(tcx.mk_unit())?,
304             i8: layout_cx.layout_of(tcx.types.i8)?,
305             i16: layout_cx.layout_of(tcx.types.i16)?,
306             i32: layout_cx.layout_of(tcx.types.i32)?,
307             i64: layout_cx.layout_of(tcx.types.i64)?,
308             i128: layout_cx.layout_of(tcx.types.i128)?,
309             isize: layout_cx.layout_of(tcx.types.isize)?,
310             u8: layout_cx.layout_of(tcx.types.u8)?,
311             u16: layout_cx.layout_of(tcx.types.u16)?,
312             u32: layout_cx.layout_of(tcx.types.u32)?,
313             u64: layout_cx.layout_of(tcx.types.u64)?,
314             u128: layout_cx.layout_of(tcx.types.u128)?,
315             usize: layout_cx.layout_of(tcx.types.usize)?,
316             bool: layout_cx.layout_of(tcx.types.bool)?,
317             mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
318             const_raw_ptr: layout_cx.layout_of(const_raw_ptr)?,
319         })
320     }
321
322     pub fn uint(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
323         match size.bits() {
324             8 => Some(self.u8),
325             16 => Some(self.u16),
326             32 => Some(self.u32),
327             64 => Some(self.u64),
328             128 => Some(self.u128),
329             _ => None,
330         }
331     }
332
333     pub fn int(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
334         match size.bits() {
335             8 => Some(self.i8),
336             16 => Some(self.i16),
337             32 => Some(self.i32),
338             64 => Some(self.i64),
339             128 => Some(self.i128),
340             _ => None,
341         }
342     }
343 }
344
345 /// The machine itself.
346 ///
347 /// If you add anything here that stores machine values, remember to update
348 /// `visit_all_machine_values`!
349 pub struct MiriMachine<'mir, 'tcx> {
350     // We carry a copy of the global `TyCtxt` for convenience, so methods taking just `&Evaluator` have `tcx` access.
351     pub tcx: TyCtxt<'tcx>,
352
353     /// Global data for borrow tracking.
354     pub borrow_tracker: Option<borrow_tracker::GlobalState>,
355
356     /// Data race detector global data.
357     pub data_race: Option<data_race::GlobalState>,
358
359     /// Ptr-int-cast module global data.
360     pub intptrcast: intptrcast::GlobalState,
361
362     /// Environment variables set by `setenv`.
363     /// Miri does not expose env vars from the host to the emulated program.
364     pub(crate) env_vars: EnvVars<'tcx>,
365
366     /// Return place of the main function.
367     pub(crate) main_fn_ret_place: Option<MemPlace<Provenance>>,
368
369     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
370     /// These are *pointers* to argc/argv because macOS.
371     /// We also need the full command line as one string because of Windows.
372     pub(crate) argc: Option<MemPlace<Provenance>>,
373     pub(crate) argv: Option<MemPlace<Provenance>>,
374     pub(crate) cmd_line: Option<MemPlace<Provenance>>,
375
376     /// TLS state.
377     pub(crate) tls: TlsData<'tcx>,
378
379     /// What should Miri do when an op requires communicating with the host,
380     /// such as accessing host env vars, random number generation, and
381     /// file system access.
382     pub(crate) isolated_op: IsolatedOp,
383
384     /// Whether to enforce the validity invariant.
385     pub(crate) validate: bool,
386
387     /// Whether to enforce [ABI](Abi) of function calls.
388     pub(crate) enforce_abi: bool,
389
390     /// The table of file descriptors.
391     pub(crate) file_handler: shims::unix::FileHandler,
392     /// The table of directory descriptors.
393     pub(crate) dir_handler: shims::unix::DirHandler,
394
395     /// This machine's monotone clock.
396     pub(crate) clock: Clock,
397
398     /// The set of threads.
399     pub(crate) threads: ThreadManager<'mir, 'tcx>,
400
401     /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
402     pub(crate) layouts: PrimitiveLayouts<'tcx>,
403
404     /// Allocations that are considered roots of static memory (that may leak).
405     pub(crate) static_roots: Vec<AllocId>,
406
407     /// The `measureme` profiler used to record timing information about
408     /// the emulated program.
409     profiler: Option<measureme::Profiler>,
410     /// Used with `profiler` to cache the `StringId`s for event names
411     /// uesd with `measureme`.
412     string_cache: FxHashMap<String, measureme::StringId>,
413
414     /// Cache of `Instance` exported under the given `Symbol` name.
415     /// `None` means no `Instance` exported under the given name is found.
416     pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
417
418     /// Whether to raise a panic in the context of the evaluated process when unsupported
419     /// functionality is encountered. If `false`, an error is propagated in the Miri application context
420     /// instead (default behavior)
421     pub(crate) panic_on_unsupported: bool,
422
423     /// Equivalent setting as RUST_BACKTRACE on encountering an error.
424     pub(crate) backtrace_style: BacktraceStyle,
425
426     /// Crates which are considered local for the purposes of error reporting.
427     pub(crate) local_crates: Vec<CrateNum>,
428
429     /// Mapping extern static names to their base pointer.
430     extern_statics: FxHashMap<Symbol, Pointer<Provenance>>,
431
432     /// The random number generator used for resolving non-determinism.
433     /// Needs to be queried by ptr_to_int, hence needs interior mutability.
434     pub(crate) rng: RefCell<StdRng>,
435
436     /// The allocation IDs to report when they are being allocated
437     /// (helps for debugging memory leaks and use after free bugs).
438     tracked_alloc_ids: FxHashSet<AllocId>,
439
440     /// Controls whether alignment of memory accesses is being checked.
441     pub(crate) check_alignment: AlignmentCheck,
442
443     /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
444     pub(crate) cmpxchg_weak_failure_rate: f64,
445
446     /// Corresponds to -Zmiri-mute-stdout-stderr and doesn't write the output but acts as if it succeeded.
447     pub(crate) mute_stdout_stderr: bool,
448
449     /// Whether weak memory emulation is enabled
450     pub(crate) weak_memory: bool,
451
452     /// The probability of the active thread being preempted at the end of each basic block.
453     pub(crate) preemption_rate: f64,
454
455     /// If `Some`, we will report the current stack every N basic blocks.
456     pub(crate) report_progress: Option<u32>,
457     // The total number of blocks that have been executed.
458     pub(crate) basic_block_count: u64,
459
460     /// Handle of the optional shared object file for external functions.
461     #[cfg(target_os = "linux")]
462     pub external_so_lib: Option<(libloading::Library, std::path::PathBuf)>,
463     #[cfg(not(target_os = "linux"))]
464     pub external_so_lib: Option<!>,
465
466     /// Run a garbage collector for BorTags every N basic blocks.
467     pub(crate) gc_interval: u32,
468     /// The number of blocks that passed since the last BorTag GC pass.
469     pub(crate) since_gc: u32,
470     /// The number of CPUs to be reported by miri.
471     pub(crate) num_cpus: u32,
472     /// Determines Miri's page size and associated values
473     pub(crate) page_size: u64,
474     pub(crate) stack_addr: u64,
475     pub(crate) stack_size: u64,
476 }
477
478 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
479     pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
480         let local_crates = helpers::get_local_crates(layout_cx.tcx);
481         let layouts =
482             PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
483         let profiler = config.measureme_out.as_ref().map(|out| {
484             measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
485         });
486         let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
487         let borrow_tracker = config.borrow_tracker.map(|bt| bt.instanciate_global_state(config));
488         let data_race = config.data_race_detector.then(|| data_race::GlobalState::new(config));
489         let page_size = if let Some(page_size) = config.page_size {
490             page_size
491         } else {
492             let target = &layout_cx.tcx.sess.target;
493             match target.arch.as_ref() {
494                 "wasm32" | "wasm64" => 64 * 1024, // https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances
495                 "aarch64" =>
496                     if target.options.vendor.as_ref() == "apple" {
497                         // No "definitive" source, but see:
498                         // https://www.wwdcnotes.com/notes/wwdc20/10214/
499                         // https://github.com/ziglang/zig/issues/11308 etc.
500                         16 * 1024
501                     } else {
502                         4 * 1024
503                     },
504                 _ => 4 * 1024,
505             }
506         };
507         let stack_addr = page_size * 32;
508         let stack_size = page_size * 16;
509         MiriMachine {
510             tcx: layout_cx.tcx,
511             borrow_tracker,
512             data_race,
513             intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config, stack_addr)),
514             // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
515             env_vars: EnvVars::default(),
516             main_fn_ret_place: None,
517             argc: None,
518             argv: None,
519             cmd_line: None,
520             tls: TlsData::default(),
521             isolated_op: config.isolated_op,
522             validate: config.validate,
523             enforce_abi: config.check_abi,
524             file_handler: FileHandler::new(config.mute_stdout_stderr),
525             dir_handler: Default::default(),
526             layouts,
527             threads: ThreadManager::default(),
528             static_roots: Vec::new(),
529             profiler,
530             string_cache: Default::default(),
531             exported_symbols_cache: FxHashMap::default(),
532             panic_on_unsupported: config.panic_on_unsupported,
533             backtrace_style: config.backtrace_style,
534             local_crates,
535             extern_statics: FxHashMap::default(),
536             rng: RefCell::new(rng),
537             tracked_alloc_ids: config.tracked_alloc_ids.clone(),
538             check_alignment: config.check_alignment,
539             cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
540             mute_stdout_stderr: config.mute_stdout_stderr,
541             weak_memory: config.weak_memory_emulation,
542             preemption_rate: config.preemption_rate,
543             report_progress: config.report_progress,
544             basic_block_count: 0,
545             clock: Clock::new(config.isolated_op == IsolatedOp::Allow),
546             #[cfg(target_os = "linux")]
547             external_so_lib: config.external_so_file.as_ref().map(|lib_file_path| {
548                 let target_triple = layout_cx.tcx.sess.opts.target_triple.triple();
549                 // Check if host target == the session target.
550                 if env!("TARGET") != target_triple {
551                     panic!(
552                         "calling external C functions in linked .so file requires host and target to be the same: host={}, target={}",
553                         env!("TARGET"),
554                         target_triple,
555                     );
556                 }
557                 // Note: it is the user's responsibility to provide a correct SO file.
558                 // WATCH OUT: If an invalid/incorrect SO file is specified, this can cause
559                 // undefined behaviour in Miri itself!
560                 (
561                     unsafe {
562                         libloading::Library::new(lib_file_path)
563                             .expect("failed to read specified extern shared object file")
564                     },
565                     lib_file_path.clone(),
566                 )
567             }),
568             #[cfg(not(target_os = "linux"))]
569             external_so_lib: config.external_so_file.as_ref().map(|_| {
570                 panic!("loading external .so files is only supported on Linux")
571             }),
572             gc_interval: config.gc_interval,
573             since_gc: 0,
574             num_cpus: config.num_cpus,
575             page_size,
576             stack_addr,
577             stack_size,
578         }
579     }
580
581     pub(crate) fn late_init(
582         this: &mut MiriInterpCx<'mir, 'tcx>,
583         config: &MiriConfig,
584         on_main_stack_empty: StackEmptyCallback<'mir, 'tcx>,
585     ) -> InterpResult<'tcx> {
586         EnvVars::init(this, config)?;
587         MiriMachine::init_extern_statics(this)?;
588         ThreadManager::init(this, on_main_stack_empty);
589         Ok(())
590     }
591
592     fn add_extern_static(
593         this: &mut MiriInterpCx<'mir, 'tcx>,
594         name: &str,
595         ptr: Pointer<Option<Provenance>>,
596     ) {
597         // This got just allocated, so there definitely is a pointer here.
598         let ptr = ptr.into_pointer_or_addr().unwrap();
599         this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
600     }
601
602     fn alloc_extern_static(
603         this: &mut MiriInterpCx<'mir, 'tcx>,
604         name: &str,
605         val: ImmTy<'tcx, Provenance>,
606     ) -> InterpResult<'tcx> {
607         let place = this.allocate(val.layout, MiriMemoryKind::ExternStatic.into())?;
608         this.write_immediate(*val, &place.into())?;
609         Self::add_extern_static(this, name, place.ptr);
610         Ok(())
611     }
612
613     /// Sets up the "extern statics" for this machine.
614     fn init_extern_statics(this: &mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx> {
615         match this.tcx.sess.target.os.as_ref() {
616             "linux" => {
617                 // "environ"
618                 Self::add_extern_static(
619                     this,
620                     "environ",
621                     this.machine.env_vars.environ.unwrap().ptr,
622                 );
623                 // A couple zero-initialized pointer-sized extern statics.
624                 // Most of them are for weak symbols, which we all set to null (indicating that the
625                 // symbol is not supported, and triggering fallback code which ends up calling a
626                 // syscall that we do support).
627                 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"]
628                 {
629                     let val = ImmTy::from_int(0, this.machine.layouts.usize);
630                     Self::alloc_extern_static(this, name, val)?;
631                 }
632             }
633             "freebsd" => {
634                 // "environ"
635                 Self::add_extern_static(
636                     this,
637                     "environ",
638                     this.machine.env_vars.environ.unwrap().ptr,
639                 );
640             }
641             "android" => {
642                 // "signal"
643                 let layout = this.machine.layouts.const_raw_ptr;
644                 let dlsym = Dlsym::from_str("signal".as_bytes(), &this.tcx.sess.target.os)?
645                     .expect("`signal` must be an actual dlsym on android");
646                 let ptr = this.create_fn_alloc_ptr(FnVal::Other(dlsym));
647                 let val = ImmTy::from_scalar(Scalar::from_pointer(ptr, this), layout);
648                 Self::alloc_extern_static(this, "signal", val)?;
649                 // A couple zero-initialized pointer-sized extern statics.
650                 // Most of them are for weak symbols, which we all set to null (indicating that the
651                 // symbol is not supported, and triggering fallback code.)
652                 for name in &["bsd_signal"] {
653                     let val = ImmTy::from_int(0, this.machine.layouts.usize);
654                     Self::alloc_extern_static(this, name, val)?;
655                 }
656             }
657             "windows" => {
658                 // "_tls_used"
659                 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
660                 let val = ImmTy::from_int(0, this.machine.layouts.u8);
661                 Self::alloc_extern_static(this, "_tls_used", val)?;
662             }
663             _ => {} // No "extern statics" supported on this target
664         }
665         Ok(())
666     }
667
668     pub(crate) fn communicate(&self) -> bool {
669         self.isolated_op == IsolatedOp::Allow
670     }
671
672     /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
673     pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
674         let def_id = frame.instance.def_id();
675         def_id.is_local() || self.local_crates.contains(&def_id.krate)
676     }
677 }
678
679 impl VisitTags for MiriMachine<'_, '_> {
680     fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
681         #[rustfmt::skip]
682         let MiriMachine {
683             threads,
684             tls,
685             env_vars,
686             main_fn_ret_place,
687             argc,
688             argv,
689             cmd_line,
690             extern_statics,
691             dir_handler,
692             borrow_tracker,
693             data_race,
694             intptrcast,
695             file_handler,
696             tcx: _,
697             isolated_op: _,
698             validate: _,
699             enforce_abi: _,
700             clock: _,
701             layouts: _,
702             static_roots: _,
703             profiler: _,
704             string_cache: _,
705             exported_symbols_cache: _,
706             panic_on_unsupported: _,
707             backtrace_style: _,
708             local_crates: _,
709             rng: _,
710             tracked_alloc_ids: _,
711             check_alignment: _,
712             cmpxchg_weak_failure_rate: _,
713             mute_stdout_stderr: _,
714             weak_memory: _,
715             preemption_rate: _,
716             report_progress: _,
717             basic_block_count: _,
718             external_so_lib: _,
719             gc_interval: _,
720             since_gc: _,
721             num_cpus: _,
722             page_size: _,
723             stack_addr: _,
724             stack_size: _,
725         } = self;
726
727         threads.visit_tags(visit);
728         tls.visit_tags(visit);
729         env_vars.visit_tags(visit);
730         dir_handler.visit_tags(visit);
731         file_handler.visit_tags(visit);
732         data_race.visit_tags(visit);
733         borrow_tracker.visit_tags(visit);
734         intptrcast.visit_tags(visit);
735         main_fn_ret_place.visit_tags(visit);
736         argc.visit_tags(visit);
737         argv.visit_tags(visit);
738         cmd_line.visit_tags(visit);
739         for ptr in extern_statics.values() {
740             ptr.visit_tags(visit);
741         }
742     }
743 }
744
745 /// A rustc InterpCx for Miri.
746 pub type MiriInterpCx<'mir, 'tcx> = InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>;
747
748 /// A little trait that's useful to be inherited by extension traits.
749 pub trait MiriInterpCxExt<'mir, 'tcx> {
750     fn eval_context_ref<'a>(&'a self) -> &'a MiriInterpCx<'mir, 'tcx>;
751     fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriInterpCx<'mir, 'tcx>;
752 }
753 impl<'mir, 'tcx> MiriInterpCxExt<'mir, 'tcx> for MiriInterpCx<'mir, 'tcx> {
754     #[inline(always)]
755     fn eval_context_ref(&self) -> &MiriInterpCx<'mir, 'tcx> {
756         self
757     }
758     #[inline(always)]
759     fn eval_context_mut(&mut self) -> &mut MiriInterpCx<'mir, 'tcx> {
760         self
761     }
762 }
763
764 /// Machine hook implementations.
765 impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
766     type MemoryKind = MiriMemoryKind;
767     type ExtraFnVal = Dlsym;
768
769     type FrameExtra = FrameExtra<'tcx>;
770     type AllocExtra = AllocExtra;
771
772     type Provenance = Provenance;
773     type ProvenanceExtra = ProvenanceExtra;
774
775     type MemoryMap = MonoHashMap<
776         AllocId,
777         (MemoryKind<MiriMemoryKind>, Allocation<Provenance, Self::AllocExtra>),
778     >;
779
780     const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
781
782     const PANIC_ON_ALLOC_FAIL: bool = false;
783
784     #[inline(always)]
785     fn enforce_alignment(ecx: &MiriInterpCx<'mir, 'tcx>) -> CheckAlignment {
786         if ecx.machine.check_alignment == AlignmentCheck::None {
787             CheckAlignment::No
788         } else {
789             CheckAlignment::Error
790         }
791     }
792
793     #[inline(always)]
794     fn use_addr_for_alignment_check(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
795         ecx.machine.check_alignment == AlignmentCheck::Int
796     }
797
798     fn alignment_check_failed(
799         _ecx: &InterpCx<'mir, 'tcx, Self>,
800         has: Align,
801         required: Align,
802         _check: CheckAlignment,
803     ) -> InterpResult<'tcx, ()> {
804         throw_ub!(AlignmentCheckFailed { has, required })
805     }
806
807     #[inline(always)]
808     fn enforce_validity(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
809         ecx.machine.validate
810     }
811
812     #[inline(always)]
813     fn enforce_abi(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
814         ecx.machine.enforce_abi
815     }
816
817     #[inline(always)]
818     fn checked_binop_checks_overflow(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
819         ecx.tcx.sess.overflow_checks()
820     }
821
822     #[inline(always)]
823     fn find_mir_or_eval_fn(
824         ecx: &mut MiriInterpCx<'mir, 'tcx>,
825         instance: ty::Instance<'tcx>,
826         abi: Abi,
827         args: &[OpTy<'tcx, Provenance>],
828         dest: &PlaceTy<'tcx, Provenance>,
829         ret: Option<mir::BasicBlock>,
830         unwind: StackPopUnwind,
831     ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
832         ecx.find_mir_or_eval_fn(instance, abi, args, dest, ret, unwind)
833     }
834
835     #[inline(always)]
836     fn call_extra_fn(
837         ecx: &mut MiriInterpCx<'mir, 'tcx>,
838         fn_val: Dlsym,
839         abi: Abi,
840         args: &[OpTy<'tcx, Provenance>],
841         dest: &PlaceTy<'tcx, Provenance>,
842         ret: Option<mir::BasicBlock>,
843         _unwind: StackPopUnwind,
844     ) -> InterpResult<'tcx> {
845         ecx.call_dlsym(fn_val, abi, args, dest, ret)
846     }
847
848     #[inline(always)]
849     fn call_intrinsic(
850         ecx: &mut MiriInterpCx<'mir, 'tcx>,
851         instance: ty::Instance<'tcx>,
852         args: &[OpTy<'tcx, Provenance>],
853         dest: &PlaceTy<'tcx, Provenance>,
854         ret: Option<mir::BasicBlock>,
855         unwind: StackPopUnwind,
856     ) -> InterpResult<'tcx> {
857         ecx.call_intrinsic(instance, args, dest, ret, unwind)
858     }
859
860     #[inline(always)]
861     fn assert_panic(
862         ecx: &mut MiriInterpCx<'mir, 'tcx>,
863         msg: &mir::AssertMessage<'tcx>,
864         unwind: Option<mir::BasicBlock>,
865     ) -> InterpResult<'tcx> {
866         ecx.assert_panic(msg, unwind)
867     }
868
869     #[inline(always)]
870     fn abort(_ecx: &mut MiriInterpCx<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
871         throw_machine_stop!(TerminationInfo::Abort(msg))
872     }
873
874     #[inline(always)]
875     fn binary_ptr_op(
876         ecx: &MiriInterpCx<'mir, 'tcx>,
877         bin_op: mir::BinOp,
878         left: &ImmTy<'tcx, Provenance>,
879         right: &ImmTy<'tcx, Provenance>,
880     ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, Ty<'tcx>)> {
881         ecx.binary_ptr_op(bin_op, left, right)
882     }
883
884     fn thread_local_static_base_pointer(
885         ecx: &mut MiriInterpCx<'mir, 'tcx>,
886         def_id: DefId,
887     ) -> InterpResult<'tcx, Pointer<Provenance>> {
888         ecx.get_or_create_thread_local_alloc(def_id)
889     }
890
891     fn extern_static_base_pointer(
892         ecx: &MiriInterpCx<'mir, 'tcx>,
893         def_id: DefId,
894     ) -> InterpResult<'tcx, Pointer<Provenance>> {
895         let link_name = ecx.item_link_name(def_id);
896         if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
897             // Various parts of the engine rely on `get_alloc_info` for size and alignment
898             // information. That uses the type information of this static.
899             // Make sure it matches the Miri allocation for this.
900             let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
901                 panic!("extern_statics cannot contain wildcards")
902             };
903             let (shim_size, shim_align, _kind) = ecx.get_alloc_info(alloc_id);
904             let extern_decl_layout =
905                 ecx.tcx.layout_of(ty::ParamEnv::empty().and(ecx.tcx.type_of(def_id))).unwrap();
906             if extern_decl_layout.size != shim_size || extern_decl_layout.align.abi != shim_align {
907                 throw_unsup_format!(
908                     "`extern` static `{name}` from crate `{krate}` has been declared \
909                     with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
910                     but Miri emulates it via an extern static shim \
911                     with a size of {shim_size} bytes and alignment of {shim_align} bytes",
912                     name = ecx.tcx.def_path_str(def_id),
913                     krate = ecx.tcx.crate_name(def_id.krate),
914                     decl_size = extern_decl_layout.size.bytes(),
915                     decl_align = extern_decl_layout.align.abi.bytes(),
916                     shim_size = shim_size.bytes(),
917                     shim_align = shim_align.bytes(),
918                 )
919             }
920             Ok(ptr)
921         } else {
922             throw_unsup_format!(
923                 "`extern` static `{name}` from crate `{krate}` is not supported by Miri",
924                 name = ecx.tcx.def_path_str(def_id),
925                 krate = ecx.tcx.crate_name(def_id.krate),
926             )
927         }
928     }
929
930     fn adjust_allocation<'b>(
931         ecx: &MiriInterpCx<'mir, 'tcx>,
932         id: AllocId,
933         alloc: Cow<'b, Allocation>,
934         kind: Option<MemoryKind<Self::MemoryKind>>,
935     ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>> {
936         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
937         if ecx.machine.tracked_alloc_ids.contains(&id) {
938             ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(
939                 id,
940                 alloc.size(),
941                 alloc.align,
942                 kind,
943             ));
944         }
945
946         let alloc = alloc.into_owned();
947         let borrow_tracker = ecx
948             .machine
949             .borrow_tracker
950             .as_ref()
951             .map(|bt| bt.borrow_mut().new_allocation(id, alloc.size(), kind, &ecx.machine));
952
953         let race_alloc = ecx.machine.data_race.as_ref().map(|data_race| {
954             data_race::AllocState::new_allocation(
955                 data_race,
956                 &ecx.machine.threads,
957                 alloc.size(),
958                 kind,
959                 ecx.machine.current_span(),
960             )
961         });
962         let buffer_alloc = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation);
963         let alloc: Allocation<Provenance, Self::AllocExtra> = alloc.adjust_from_tcx(
964             &ecx.tcx,
965             AllocExtra { borrow_tracker, data_race: race_alloc, weak_memory: buffer_alloc },
966             |ptr| ecx.global_base_pointer(ptr),
967         )?;
968         Ok(Cow::Owned(alloc))
969     }
970
971     fn adjust_alloc_base_pointer(
972         ecx: &MiriInterpCx<'mir, 'tcx>,
973         ptr: Pointer<AllocId>,
974     ) -> InterpResult<'tcx, Pointer<Provenance>> {
975         if cfg!(debug_assertions) {
976             // The machine promises to never call us on thread-local or extern statics.
977             let alloc_id = ptr.provenance;
978             match ecx.tcx.try_get_global_alloc(alloc_id) {
979                 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
980                     panic!("adjust_alloc_base_pointer called on thread-local static")
981                 }
982                 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
983                     panic!("adjust_alloc_base_pointer called on extern static")
984                 }
985                 _ => {}
986             }
987         }
988         let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr)?;
989         let tag = if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
990             borrow_tracker.borrow_mut().base_ptr_tag(ptr.provenance, &ecx.machine)
991         } else {
992             // Value does not matter, SB is disabled
993             BorTag::default()
994         };
995         Ok(Pointer::new(
996             Provenance::Concrete { alloc_id: ptr.provenance, tag },
997             Size::from_bytes(absolute_addr),
998         ))
999     }
1000
1001     #[inline(always)]
1002     fn ptr_from_addr_cast(
1003         ecx: &MiriInterpCx<'mir, 'tcx>,
1004         addr: u64,
1005     ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>> {
1006         intptrcast::GlobalStateInner::ptr_from_addr_cast(ecx, addr)
1007     }
1008
1009     fn expose_ptr(
1010         ecx: &mut InterpCx<'mir, 'tcx, Self>,
1011         ptr: Pointer<Self::Provenance>,
1012     ) -> InterpResult<'tcx> {
1013         match ptr.provenance {
1014             Provenance::Concrete { alloc_id, tag } =>
1015                 intptrcast::GlobalStateInner::expose_ptr(ecx, alloc_id, tag),
1016             Provenance::Wildcard => {
1017                 // No need to do anything for wildcard pointers as
1018                 // their provenances have already been previously exposed.
1019                 Ok(())
1020             }
1021         }
1022     }
1023
1024     /// Convert a pointer with provenance into an allocation-offset pair,
1025     /// or a `None` with an absolute address if that conversion is not possible.
1026     fn ptr_get_alloc(
1027         ecx: &MiriInterpCx<'mir, 'tcx>,
1028         ptr: Pointer<Self::Provenance>,
1029     ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
1030         let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
1031
1032         rel.map(|(alloc_id, size)| {
1033             let tag = match ptr.provenance {
1034                 Provenance::Concrete { tag, .. } => ProvenanceExtra::Concrete(tag),
1035                 Provenance::Wildcard => ProvenanceExtra::Wildcard,
1036             };
1037             (alloc_id, size, tag)
1038         })
1039     }
1040
1041     #[inline(always)]
1042     fn before_memory_read(
1043         _tcx: TyCtxt<'tcx>,
1044         machine: &Self,
1045         alloc_extra: &AllocExtra,
1046         (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1047         range: AllocRange,
1048     ) -> InterpResult<'tcx> {
1049         if let Some(data_race) = &alloc_extra.data_race {
1050             data_race.read(alloc_id, range, machine)?;
1051         }
1052         if let Some(borrow_tracker) = &alloc_extra.borrow_tracker {
1053             borrow_tracker.before_memory_read(alloc_id, prov_extra, range, machine)?;
1054         }
1055         if let Some(weak_memory) = &alloc_extra.weak_memory {
1056             weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1057         }
1058         Ok(())
1059     }
1060
1061     #[inline(always)]
1062     fn before_memory_write(
1063         _tcx: TyCtxt<'tcx>,
1064         machine: &mut Self,
1065         alloc_extra: &mut AllocExtra,
1066         (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1067         range: AllocRange,
1068     ) -> InterpResult<'tcx> {
1069         if let Some(data_race) = &mut alloc_extra.data_race {
1070             data_race.write(alloc_id, range, machine)?;
1071         }
1072         if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1073             borrow_tracker.before_memory_write(alloc_id, prov_extra, range, machine)?;
1074         }
1075         if let Some(weak_memory) = &alloc_extra.weak_memory {
1076             weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1077         }
1078         Ok(())
1079     }
1080
1081     #[inline(always)]
1082     fn before_memory_deallocation(
1083         _tcx: TyCtxt<'tcx>,
1084         machine: &mut Self,
1085         alloc_extra: &mut AllocExtra,
1086         (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
1087         range: AllocRange,
1088     ) -> InterpResult<'tcx> {
1089         if machine.tracked_alloc_ids.contains(&alloc_id) {
1090             machine.emit_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
1091         }
1092         if let Some(data_race) = &mut alloc_extra.data_race {
1093             data_race.deallocate(alloc_id, range, machine)?;
1094         }
1095         if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1096             borrow_tracker.before_memory_deallocation(alloc_id, prove_extra, range, machine)?;
1097         }
1098         Ok(())
1099     }
1100
1101     #[inline(always)]
1102     fn retag_ptr_value(
1103         ecx: &mut InterpCx<'mir, 'tcx, Self>,
1104         kind: mir::RetagKind,
1105         val: &ImmTy<'tcx, Provenance>,
1106     ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> {
1107         if ecx.machine.borrow_tracker.is_some() {
1108             ecx.retag_ptr_value(kind, val)
1109         } else {
1110             Ok(val.clone())
1111         }
1112     }
1113
1114     #[inline(always)]
1115     fn retag_place_contents(
1116         ecx: &mut InterpCx<'mir, 'tcx, Self>,
1117         kind: mir::RetagKind,
1118         place: &PlaceTy<'tcx, Provenance>,
1119     ) -> InterpResult<'tcx> {
1120         if ecx.machine.borrow_tracker.is_some() {
1121             ecx.retag_place_contents(kind, place)?;
1122         }
1123         Ok(())
1124     }
1125
1126     #[inline(always)]
1127     fn init_frame_extra(
1128         ecx: &mut InterpCx<'mir, 'tcx, Self>,
1129         frame: Frame<'mir, 'tcx, Provenance>,
1130     ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>> {
1131         // Start recording our event before doing anything else
1132         let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
1133             let fn_name = frame.instance.to_string();
1134             let entry = ecx.machine.string_cache.entry(fn_name.clone());
1135             let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
1136
1137             Some(profiler.start_recording_interval_event_detached(
1138                 *name,
1139                 measureme::EventId::from_label(*name),
1140                 ecx.get_active_thread().to_u32(),
1141             ))
1142         } else {
1143             None
1144         };
1145
1146         let borrow_tracker = ecx.machine.borrow_tracker.as_ref();
1147
1148         let extra = FrameExtra {
1149             borrow_tracker: borrow_tracker.map(|bt| bt.borrow_mut().new_frame(&ecx.machine)),
1150             catch_unwind: None,
1151             timing,
1152             is_user_relevant: ecx.machine.is_user_relevant(&frame),
1153         };
1154
1155         Ok(frame.with_extra(extra))
1156     }
1157
1158     fn stack<'a>(
1159         ecx: &'a InterpCx<'mir, 'tcx, Self>,
1160     ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
1161         ecx.active_thread_stack()
1162     }
1163
1164     fn stack_mut<'a>(
1165         ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
1166     ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
1167         ecx.active_thread_stack_mut()
1168     }
1169
1170     fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1171         ecx.machine.basic_block_count += 1u64; // a u64 that is only incremented by 1 will "never" overflow
1172         ecx.machine.since_gc += 1;
1173         // Possibly report our progress.
1174         if let Some(report_progress) = ecx.machine.report_progress {
1175             if ecx.machine.basic_block_count % u64::from(report_progress) == 0 {
1176                 ecx.emit_diagnostic(NonHaltingDiagnostic::ProgressReport {
1177                     block_count: ecx.machine.basic_block_count,
1178                 });
1179             }
1180         }
1181
1182         // Search for BorTags to find all live pointers, then remove all other tags from borrow
1183         // stacks.
1184         // When debug assertions are enabled, run the GC as often as possible so that any cases
1185         // where it mistakenly removes an important tag become visible.
1186         if ecx.machine.gc_interval > 0 && ecx.machine.since_gc >= ecx.machine.gc_interval {
1187             ecx.machine.since_gc = 0;
1188             ecx.garbage_collect_tags()?;
1189         }
1190
1191         // These are our preemption points.
1192         ecx.maybe_preempt_active_thread();
1193
1194         // Make sure some time passes.
1195         ecx.machine.clock.tick();
1196
1197         Ok(())
1198     }
1199
1200     #[inline(always)]
1201     fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1202         if ecx.frame().extra.is_user_relevant {
1203             // We just pushed a local frame, so we know that the topmost local frame is the topmost
1204             // frame. If we push a non-local frame, there's no need to do anything.
1205             let stack_len = ecx.active_thread_stack().len();
1206             ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1);
1207         }
1208         if ecx.machine.borrow_tracker.is_some() {
1209             ecx.retag_return_place()?;
1210         }
1211         Ok(())
1212     }
1213
1214     #[inline(always)]
1215     fn after_stack_pop(
1216         ecx: &mut InterpCx<'mir, 'tcx, Self>,
1217         mut frame: Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>,
1218         unwinding: bool,
1219     ) -> InterpResult<'tcx, StackPopJump> {
1220         if frame.extra.is_user_relevant {
1221             // All that we store is whether or not the frame we just removed is local, so now we
1222             // have no idea where the next topmost local frame is. So we recompute it.
1223             // (If this ever becomes a bottleneck, we could have `push` store the previous
1224             // user-relevant frame and restore that here.)
1225             ecx.active_thread_mut().recompute_top_user_relevant_frame();
1226         }
1227         let timing = frame.extra.timing.take();
1228         if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
1229             borrow_tracker.borrow_mut().end_call(&frame.extra);
1230         }
1231         let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
1232         if let Some(profiler) = ecx.machine.profiler.as_ref() {
1233             profiler.finish_recording_interval_event(timing.unwrap());
1234         }
1235         res
1236     }
1237 }