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