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