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