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