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