Skip to main content

miri/
machine.rs

1//! Global machine state as well as implementation of the interpreter engine
2//! `Machine` trait.
3
4use std::borrow::Cow;
5use std::cell::{Cell, RefCell};
6use std::collections::BTreeMap;
7use std::path::Path;
8use std::rc::Rc;
9use std::{fmt, process};
10
11use rand::rngs::StdRng;
12use rand::{Rng, SeedableRng};
13use rustc_abi::{Align, ExternAbi, Size};
14use rustc_apfloat::{Float, FloatConvert};
15use rustc_ast::expand::allocator::{self, SpecialAllocatorMethod};
16use rustc_data_structures::either::Either;
17use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18#[allow(unused)]
19use rustc_data_structures::static_assert_size;
20use rustc_hir::attrs::InlineAttr;
21use rustc_log::tracing;
22use rustc_middle::middle::codegen_fn_attrs::TargetFeatureKind;
23use rustc_middle::mir;
24use rustc_middle::query::TyCtxtAt;
25use rustc_middle::ty::layout::{
26    HasTyCtxt, HasTypingEnv, LayoutCx, LayoutError, LayoutOf, TyAndLayout,
27};
28use rustc_middle::ty::{self, Instance, Ty, TyCtxt};
29use rustc_session::config::InliningThreshold;
30use rustc_span::def_id::{CrateNum, DefId};
31use rustc_span::{Span, SpanData, Symbol};
32use rustc_symbol_mangling::mangle_internal_symbol;
33use rustc_target::callconv::FnAbi;
34use rustc_target::spec::{Arch, Os};
35
36use crate::alloc_addresses::EvalContextExt;
37use crate::concurrency::cpu_affinity::{self, CpuAffinityMask};
38use crate::concurrency::data_race::{self, NaReadType, NaWriteType};
39use crate::concurrency::sync::SyncObj;
40use crate::concurrency::{
41    AllocDataRaceHandler, GenmcCtx, GenmcEvalContextExt as _, GlobalDataRaceHandler, weak_memory,
42};
43use crate::*;
44
45/// First real-time signal.
46/// `signal(7)` says this must be between 32 and 64 and specifies 34 or 35
47/// as typical values.
48pub const SIGRTMIN: i32 = 34;
49
50/// Last real-time signal.
51/// `signal(7)` says it must be between 32 and 64 and specifies
52/// `SIGRTMAX` - `SIGRTMIN` >= 8 (which is the value of `_POSIX_RTSIG_MAX`)
53pub const SIGRTMAX: i32 = 42;
54
55/// Each anonymous global (constant, vtable, function pointer, ...) has multiple addresses, but only
56/// this many. Since const allocations are never deallocated, choosing a new [`AllocId`] and thus
57/// base address for each evaluation would produce unbounded memory usage.
58const ADDRS_PER_ANON_GLOBAL: usize = 32;
59
60#[derive(Copy, Clone, Debug, PartialEq)]
61pub enum AlignmentCheck {
62    /// Do not check alignment.
63    None,
64    /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
65    Symbolic,
66    /// Check alignment on the actual physical integer address.
67    Int,
68}
69
70#[derive(Copy, Clone, Debug, PartialEq)]
71pub enum RejectOpWith {
72    /// Isolated op is rejected with an abort of the machine.
73    Abort,
74
75    /// If not Abort, miri returns an error for an isolated op.
76    /// Following options determine if user should be warned about such error.
77    /// Do not print warning about rejected isolated op.
78    NoWarning,
79
80    /// Print a warning about rejected isolated op, with backtrace.
81    Warning,
82
83    /// Print a warning about rejected isolated op, without backtrace.
84    WarningWithoutBacktrace,
85}
86
87#[derive(Copy, Clone, Debug, PartialEq)]
88pub enum IsolatedOp {
89    /// Reject an op requiring communication with the host. By
90    /// default, miri rejects the op with an abort. If not, it returns
91    /// an error code, and prints a warning about it. Warning levels
92    /// are controlled by `RejectOpWith` enum.
93    Reject(RejectOpWith),
94
95    /// Execute op requiring communication with the host, i.e. disable isolation.
96    Allow,
97}
98
99#[derive(Debug, Copy, Clone, PartialEq, Eq)]
100pub enum BacktraceStyle {
101    /// Prints a terser backtrace which ideally only contains relevant information.
102    Short,
103    /// Prints a backtrace with all possible information.
104    Full,
105    /// Prints only the frame that the error occurs in.
106    Off,
107}
108
109#[derive(Debug, Copy, Clone, PartialEq, Eq)]
110pub enum ValidationMode {
111    /// Do not perform any kind of validation.
112    No,
113    /// Validate the interior of the value, but not things behind references.
114    Shallow,
115    /// Fully recursively validate references.
116    Deep,
117}
118
119#[derive(Debug, Copy, Clone, PartialEq, Eq)]
120pub enum FloatRoundingErrorMode {
121    /// Apply a random error (the default).
122    Random,
123    /// Don't apply any error.
124    None,
125    /// Always apply the maximum error (with a random sign).
126    Max,
127}
128
129/// Extra data stored with each stack frame
130pub struct FrameExtra<'tcx> {
131    /// Extra data for the Borrow Tracker.
132    pub borrow_tracker: Option<borrow_tracker::FrameState>,
133
134    /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
135    /// called by `try`). When this frame is popped during unwinding a panic,
136    /// we stop unwinding, use the `CatchUnwindData` to handle catching.
137    pub catch_unwind: Option<CatchUnwindData<'tcx>>,
138
139    /// If `measureme` profiling is enabled, holds timing information
140    /// for the start of this frame. When we finish executing this frame,
141    /// we use this to register a completed event with `measureme`.
142    pub timing: Option<measureme::DetachedTiming>,
143
144    /// Indicates how user-relevant this frame is. `#[track_caller]` frames are never relevant.
145    /// Frames from user-relevant crates are maximally relevant; frames from other crates are less
146    /// relevant.
147    pub user_relevance: u8,
148
149    /// Data race detector per-frame data.
150    pub data_race: Option<data_race::FrameState>,
151}
152
153impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        // Omitting `timing`, it does not support `Debug`.
156        let FrameExtra { borrow_tracker, catch_unwind, timing: _, user_relevance, data_race } =
157            self;
158        f.debug_struct("FrameData")
159            .field("borrow_tracker", borrow_tracker)
160            .field("catch_unwind", catch_unwind)
161            .field("user_relevance", user_relevance)
162            .field("data_race", data_race)
163            .finish()
164    }
165}
166
167impl VisitProvenance for FrameExtra<'_> {
168    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
169        let FrameExtra { catch_unwind, borrow_tracker, timing: _, user_relevance: _, data_race: _ } =
170            self;
171
172        catch_unwind.visit_provenance(visit);
173        borrow_tracker.visit_provenance(visit);
174    }
175}
176
177/// Extra memory kinds
178#[derive(Debug, Copy, Clone, PartialEq, Eq)]
179pub enum MiriMemoryKind {
180    /// `__rust_alloc` memory.
181    Rust,
182    /// `miri_alloc` memory.
183    Miri,
184    /// `malloc` memory.
185    C,
186    /// Windows `HeapAlloc` memory.
187    WinHeap,
188    /// Windows "local" memory (to be freed with `LocalFree`)
189    WinLocal,
190    /// Memory for args, errno, env vars, and other parts of the machine-managed environment.
191    /// This memory may leak.
192    Machine,
193    /// Memory allocated by the runtime, e.g. for readdir. Separate from `Machine` because we clean
194    /// it up (or expect the user to invoke operations that clean it up) and leak-check it.
195    Runtime,
196    /// Globals copied from `tcx`.
197    /// This memory may leak.
198    Global,
199    /// Memory for extern statics.
200    /// This memory may leak.
201    ExternStatic,
202    /// Memory for thread-local statics.
203    /// This memory may leak.
204    Tls,
205    /// Memory mapped directly by the program
206    Mmap,
207}
208
209impl From<MiriMemoryKind> for MemoryKind {
210    #[inline(always)]
211    fn from(kind: MiriMemoryKind) -> MemoryKind {
212        MemoryKind::Machine(kind)
213    }
214}
215
216impl MayLeak for MiriMemoryKind {
217    #[inline(always)]
218    fn may_leak(self) -> bool {
219        use self::MiriMemoryKind::*;
220        match self {
221            Rust | Miri | C | WinHeap | WinLocal | Runtime => false,
222            Machine | Global | ExternStatic | Tls | Mmap => true,
223        }
224    }
225}
226
227impl MiriMemoryKind {
228    /// Whether we have a useful allocation span for an allocation of this kind.
229    fn should_save_allocation_span(self) -> bool {
230        use self::MiriMemoryKind::*;
231        match self {
232            // Heap allocations are fine since the `Allocation` is created immediately.
233            Rust | Miri | C | WinHeap | WinLocal | Mmap => true,
234            // Everything else is unclear, let's not show potentially confusing spans.
235            Machine | Global | ExternStatic | Tls | Runtime => false,
236        }
237    }
238}
239
240impl fmt::Display for MiriMemoryKind {
241    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
242        use self::MiriMemoryKind::*;
243        match self {
244            Rust => write!(f, "Rust heap"),
245            Miri => write!(f, "Miri bare-metal heap"),
246            C => write!(f, "C heap"),
247            WinHeap => write!(f, "Windows heap"),
248            WinLocal => write!(f, "Windows local memory"),
249            Machine => write!(f, "machine-managed memory"),
250            Runtime => write!(f, "language runtime memory"),
251            Global => write!(f, "global (static or const)"),
252            ExternStatic => write!(f, "extern static"),
253            Tls => write!(f, "thread-local static"),
254            Mmap => write!(f, "mmap"),
255        }
256    }
257}
258
259pub type MemoryKind = interpret::MemoryKind<MiriMemoryKind>;
260
261/// Pointer provenance.
262// This needs to be `Eq`+`Hash` because the `Machine` trait needs that because validity checking
263// *might* be recursive and then it has to track which places have already been visited.
264// These implementations are a bit questionable, and it means we may check the same place multiple
265// times with different provenance, but that is in general not wrong.
266#[derive(Clone, Copy, PartialEq, Eq, Hash)]
267pub enum Provenance {
268    /// For pointers with concrete provenance. we exactly know which allocation they are attached to
269    /// and what their borrow tag is.
270    Concrete {
271        alloc_id: AllocId,
272        /// Borrow Tracker tag.
273        tag: BorTag,
274    },
275    /// Pointers with wildcard provenance are created on int-to-ptr casts. According to the
276    /// specification, we should at that point angelically "guess" a provenance that will make all
277    /// future uses of this pointer work, if at all possible. Of course such a semantics cannot be
278    /// actually implemented in Miri. So instead, we approximate this, erroring on the side of
279    /// accepting too much code rather than rejecting correct code: a pointer with wildcard
280    /// provenance "acts like" any previously exposed pointer. Each time it is used, we check
281    /// whether *some* exposed pointer could have done what we want to do, and if the answer is yes
282    /// then we allow the access. This allows too much code in two ways:
283    /// - The same wildcard pointer can "take the role" of multiple different exposed pointers on
284    ///   subsequent memory accesses.
285    /// - In the aliasing model, we don't just have to know the borrow tag of the pointer used for
286    ///   the access, we also have to update the aliasing state -- and that update can be very
287    ///   different depending on which borrow tag we pick! Stacked Borrows has support for this by
288    ///   switching to a stack that is only approximately known, i.e. we over-approximate the effect
289    ///   of using *any* exposed pointer for this access, and only keep information about the borrow
290    ///   stack that would be true with all possible choices.
291    Wildcard,
292}
293
294/// The "extra" information a pointer has over a regular AllocId.
295#[derive(Copy, Clone, PartialEq)]
296pub enum ProvenanceExtra {
297    Concrete(BorTag),
298    Wildcard,
299}
300
301#[cfg(target_pointer_width = "64")]
302static_assert_size!(StrictPointer, 24);
303// Pointer does not fit as the layout algorithm isn't smart enough (but also, we tried using
304// pattern types to get a larger niche that makes this fit and it didn't improve performance).
305// #[cfg(target_pointer_width = "64")]
306//static_assert_size!(Pointer, 24);
307#[cfg(target_pointer_width = "64")]
308static_assert_size!(Scalar, 32);
309
310impl fmt::Debug for Provenance {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        match self {
313            Provenance::Concrete { alloc_id, tag } => {
314                // Forward `alternate` flag to `alloc_id` printing.
315                if f.alternate() {
316                    write!(f, "[{alloc_id:#?}]")?;
317                } else {
318                    write!(f, "[{alloc_id:?}]")?;
319                }
320                // Print Borrow Tracker tag.
321                write!(f, "{tag:?}")?;
322            }
323            Provenance::Wildcard => {
324                write!(f, "[wildcard]")?;
325            }
326        }
327        Ok(())
328    }
329}
330
331impl interpret::Provenance for Provenance {
332    /// We use absolute addresses in the `offset` of a `StrictPointer`.
333    const OFFSET_IS_ADDR: bool = true;
334
335    /// Miri implements wildcard provenance.
336    const WILDCARD: Option<Self> = Some(Provenance::Wildcard);
337
338    fn get_alloc_id(self) -> Option<AllocId> {
339        match self {
340            Provenance::Concrete { alloc_id, .. } => Some(alloc_id),
341            Provenance::Wildcard => None,
342        }
343    }
344
345    fn fmt(ptr: &interpret::Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
346        let (prov, addr) = ptr.into_raw_parts(); // offset is absolute address
347        write!(f, "{:#x}", addr.bytes())?;
348        if f.alternate() {
349            write!(f, "{prov:#?}")?;
350        } else {
351            write!(f, "{prov:?}")?;
352        }
353        Ok(())
354    }
355}
356
357impl fmt::Debug for ProvenanceExtra {
358    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
359        match self {
360            ProvenanceExtra::Concrete(pid) => write!(f, "{pid:?}"),
361            ProvenanceExtra::Wildcard => write!(f, "<wildcard>"),
362        }
363    }
364}
365
366impl ProvenanceExtra {
367    pub fn and_then<T>(self, f: impl FnOnce(BorTag) -> Option<T>) -> Option<T> {
368        match self {
369            ProvenanceExtra::Concrete(pid) => f(pid),
370            ProvenanceExtra::Wildcard => None,
371        }
372    }
373}
374
375/// Extra per-allocation data
376#[derive(Debug)]
377pub struct AllocExtra<'tcx> {
378    /// Global state of the borrow tracker, if enabled.
379    pub borrow_tracker: Option<borrow_tracker::AllocState>,
380    /// Extra state for data race detection.
381    ///
382    /// Invariant: The enum variant must match the enum variant in the `data_race` field on `MiriMachine`
383    pub data_race: AllocDataRaceHandler,
384    /// A backtrace to where this allocation was allocated.
385    /// As this is recorded for leak reports, it only exists
386    /// if this allocation is leakable. The backtrace is not
387    /// pruned yet; that should be done before printing it.
388    pub backtrace: Option<Vec<FrameInfo<'tcx>>>,
389    /// Synchronization objects like to attach extra data to particular addresses. We store that
390    /// inside the relevant allocation, to ensure that everything is removed when the allocation is
391    /// freed.
392    /// This maps offsets to synchronization-primitive-specific data.
393    pub sync_objs: BTreeMap<Size, Box<dyn SyncObj>>,
394}
395
396// We need a `Clone` impl because the machine passes `Allocation` through `Cow`...
397// but that should never end up actually cloning our `AllocExtra`.
398impl<'tcx> Clone for AllocExtra<'tcx> {
399    fn clone(&self) -> Self {
400        panic!("our allocations should never be cloned");
401    }
402}
403
404impl VisitProvenance for AllocExtra<'_> {
405    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
406        let AllocExtra { borrow_tracker, data_race, backtrace: _, sync_objs: _ } = self;
407
408        borrow_tracker.visit_provenance(visit);
409        data_race.visit_provenance(visit);
410    }
411}
412
413/// Precomputed layouts of primitive types
414pub struct PrimitiveLayouts<'tcx> {
415    pub unit: TyAndLayout<'tcx>,
416    pub i8: TyAndLayout<'tcx>,
417    pub i16: TyAndLayout<'tcx>,
418    pub i32: TyAndLayout<'tcx>,
419    pub i64: TyAndLayout<'tcx>,
420    pub i128: TyAndLayout<'tcx>,
421    pub isize: TyAndLayout<'tcx>,
422    pub u8: TyAndLayout<'tcx>,
423    pub u16: TyAndLayout<'tcx>,
424    pub u32: TyAndLayout<'tcx>,
425    pub u64: TyAndLayout<'tcx>,
426    pub u128: TyAndLayout<'tcx>,
427    pub usize: TyAndLayout<'tcx>,
428    pub bool: TyAndLayout<'tcx>,
429    pub mut_raw_ptr: TyAndLayout<'tcx>,   // *mut ()
430    pub const_raw_ptr: TyAndLayout<'tcx>, // *const ()
431}
432
433impl<'tcx> PrimitiveLayouts<'tcx> {
434    fn new(layout_cx: LayoutCx<'tcx>) -> Result<Self, &'tcx LayoutError<'tcx>> {
435        let tcx = layout_cx.tcx();
436        let mut_raw_ptr = Ty::new_mut_ptr(tcx, tcx.types.unit);
437        let const_raw_ptr = Ty::new_imm_ptr(tcx, tcx.types.unit);
438        Ok(Self {
439            unit: layout_cx.layout_of(tcx.types.unit)?,
440            i8: layout_cx.layout_of(tcx.types.i8)?,
441            i16: layout_cx.layout_of(tcx.types.i16)?,
442            i32: layout_cx.layout_of(tcx.types.i32)?,
443            i64: layout_cx.layout_of(tcx.types.i64)?,
444            i128: layout_cx.layout_of(tcx.types.i128)?,
445            isize: layout_cx.layout_of(tcx.types.isize)?,
446            u8: layout_cx.layout_of(tcx.types.u8)?,
447            u16: layout_cx.layout_of(tcx.types.u16)?,
448            u32: layout_cx.layout_of(tcx.types.u32)?,
449            u64: layout_cx.layout_of(tcx.types.u64)?,
450            u128: layout_cx.layout_of(tcx.types.u128)?,
451            usize: layout_cx.layout_of(tcx.types.usize)?,
452            bool: layout_cx.layout_of(tcx.types.bool)?,
453            mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
454            const_raw_ptr: layout_cx.layout_of(const_raw_ptr)?,
455        })
456    }
457
458    pub fn uint(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
459        match size.bits() {
460            8 => Some(self.u8),
461            16 => Some(self.u16),
462            32 => Some(self.u32),
463            64 => Some(self.u64),
464            128 => Some(self.u128),
465            _ => None,
466        }
467    }
468
469    pub fn int(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
470        match size.bits() {
471            8 => Some(self.i8),
472            16 => Some(self.i16),
473            32 => Some(self.i32),
474            64 => Some(self.i64),
475            128 => Some(self.i128),
476            _ => None,
477        }
478    }
479}
480
481/// The machine itself.
482///
483/// If you add anything here that stores machine values, remember to update
484/// `visit_all_machine_values`!
485pub struct MiriMachine<'tcx> {
486    // We carry a copy of the global `TyCtxt` for convenience, so methods taking just `&Evaluator` have `tcx` access.
487    pub tcx: TyCtxt<'tcx>,
488
489    /// Global data for borrow tracking.
490    pub borrow_tracker: Option<borrow_tracker::GlobalState>,
491
492    /// Depending on settings, this will be `None`,
493    /// global data for a data race detector,
494    /// or the context required for running in GenMC mode.
495    ///
496    /// Invariant: The enum variant must match the enum variant of `AllocDataRaceHandler` in the `data_race` field of all `AllocExtra`.
497    pub data_race: GlobalDataRaceHandler,
498
499    /// Ptr-int-cast module global data.
500    pub alloc_addresses: alloc_addresses::GlobalState,
501
502    /// Environment variables.
503    pub(crate) env_vars: EnvVars<'tcx>,
504
505    /// Return place of the main function.
506    pub(crate) main_fn_ret_place: Option<MPlaceTy<'tcx>>,
507
508    /// Program arguments (`Option` because we can only initialize them after creating the ecx).
509    /// These are *pointers* to argc/argv because macOS.
510    /// We also need the full command line as one string because of Windows.
511    pub(crate) argc: Option<Pointer>,
512    pub(crate) argv: Option<Pointer>,
513    pub(crate) cmd_line: Option<Pointer>,
514
515    /// TLS state.
516    pub(crate) tls: TlsData<'tcx>,
517
518    /// What should Miri do when an op requires communicating with the host,
519    /// such as accessing host env vars, random number generation, and
520    /// file system access.
521    pub(crate) isolated_op: IsolatedOp,
522
523    /// Whether to enforce the validity invariant.
524    pub(crate) validation: ValidationMode,
525
526    /// The table of file descriptors.
527    pub(crate) fds: shims::FdTable,
528    /// The table of directory descriptors.
529    pub(crate) dirs: shims::DirTable,
530
531    /// The list of all EpollEventInterest.
532    pub(crate) epoll_interests: shims::EpollInterestTable,
533
534    /// This machine's monotone clock.
535    pub(crate) monotonic_clock: MonotonicClock,
536
537    /// The set of threads.
538    pub(crate) threads: ThreadManager<'tcx>,
539
540    /// Stores which thread is eligible to run on which CPUs.
541    /// This has no effect at all, it is just tracked to produce the correct result
542    /// in `sched_getaffinity`
543    pub(crate) thread_cpu_affinity: FxHashMap<ThreadId, CpuAffinityMask>,
544
545    /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
546    pub(crate) layouts: PrimitiveLayouts<'tcx>,
547
548    /// Allocations that are considered roots of static memory (that may leak).
549    pub(crate) static_roots: Vec<AllocId>,
550
551    /// The `measureme` profiler used to record timing information about
552    /// the emulated program.
553    profiler: Option<measureme::Profiler>,
554    /// Used with `profiler` to cache the `StringId`s for event names
555    /// used with `measureme`.
556    string_cache: FxHashMap<String, measureme::StringId>,
557
558    /// Cache of `Instance` exported under the given `Symbol` name.
559    /// `None` means no `Instance` exported under the given name is found.
560    pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
561
562    /// Equivalent setting as RUST_BACKTRACE on encountering an error.
563    pub(crate) backtrace_style: BacktraceStyle,
564
565    /// Crates which are considered user-relevant for the purposes of error reporting.
566    pub(crate) user_relevant_crates: Vec<CrateNum>,
567
568    /// Mapping extern static names to their pointer.
569    extern_statics: FxHashMap<Symbol, StrictPointer>,
570
571    /// The random number generator used for resolving non-determinism.
572    /// Needs to be queried by ptr_to_int, hence needs interior mutability.
573    pub(crate) rng: RefCell<StdRng>,
574
575    /// The allocator used for the machine's `AllocBytes` in native-libs mode.
576    pub(crate) allocator: Option<Rc<RefCell<crate::alloc::isolated_alloc::IsolatedAlloc>>>,
577
578    /// The allocation IDs to report when they are being allocated
579    /// (helps for debugging memory leaks and use after free bugs).
580    pub(crate) tracked_alloc_ids: FxHashSet<AllocId>,
581    /// For the tracked alloc ids, also report read/write accesses.
582    track_alloc_accesses: bool,
583
584    /// Controls whether alignment of memory accesses is being checked.
585    pub(crate) check_alignment: AlignmentCheck,
586
587    /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
588    pub(crate) cmpxchg_weak_failure_rate: f64,
589
590    /// The probability of the active thread being preempted at the end of each basic block.
591    pub(crate) preemption_rate: f64,
592
593    /// If `Some`, we will report the current stack every N basic blocks.
594    pub(crate) report_progress: Option<u32>,
595    // The total number of blocks that have been executed.
596    pub(crate) basic_block_count: u64,
597
598    /// Handle of the optional shared object file for native functions.
599    #[cfg(all(unix, feature = "native-lib"))]
600    pub native_lib: Vec<(libloading::Library, std::path::PathBuf)>,
601    #[cfg(not(all(unix, feature = "native-lib")))]
602    pub native_lib: Vec<!>,
603    /// A memory location for exchanging the current `ecx` pointer with native code.
604    #[cfg(all(unix, feature = "native-lib"))]
605    pub native_lib_ecx_interchange: &'static Cell<usize>,
606
607    /// Run a garbage collector for BorTags every N basic blocks.
608    pub(crate) gc_interval: u32,
609    /// The number of blocks that passed since the last BorTag GC pass.
610    pub(crate) since_gc: u32,
611
612    /// The number of CPUs to be reported by miri.
613    pub(crate) num_cpus: u32,
614
615    /// Determines Miri's page size and associated values
616    pub(crate) page_size: u64,
617    pub(crate) stack_addr: u64,
618    pub(crate) stack_size: u64,
619
620    /// Whether to collect a backtrace when each allocation is created, just in case it leaks.
621    pub(crate) collect_leak_backtraces: bool,
622
623    /// The spans we will use to report where an allocation was created and deallocated in
624    /// diagnostics.
625    pub(crate) allocation_spans: RefCell<FxHashMap<AllocId, (Span, Option<Span>)>>,
626
627    /// For each allocation, an offset inside that allocation that was deemed aligned even for
628    /// symbolic alignment checks. This cannot be stored in `AllocExtra` since it needs to be
629    /// tracked for vtables and function allocations as well as regular allocations.
630    ///
631    /// Invariant: the promised alignment will never be less than the native alignment of the
632    /// allocation.
633    pub(crate) symbolic_alignment: RefCell<FxHashMap<AllocId, (Size, Align)>>,
634
635    /// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
636    union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
637
638    /// Caches the sanity-checks for various pthread primitives.
639    pub(crate) pthread_mutex_sanity: Cell<bool>,
640    pub(crate) pthread_rwlock_sanity: Cell<bool>,
641    pub(crate) pthread_condvar_sanity: Cell<bool>,
642
643    /// (Foreign) symbols that are synthesized as part of the allocator shim: the key indicates the
644    /// name of the symbol being synthesized; the value indicates whether this should invoke some
645    /// other symbol or whether this has special allocator semantics.
646    pub(crate) allocator_shim_symbols: FxHashMap<Symbol, Either<Symbol, SpecialAllocatorMethod>>,
647    /// Cache for `mangle_internal_symbol`.
648    pub(crate) mangle_internal_symbol_cache: FxHashMap<&'static str, String>,
649
650    /// Always prefer the intrinsic fallback body over the native Miri implementation.
651    pub force_intrinsic_fallback: bool,
652
653    /// Whether floating-point operations can behave non-deterministically.
654    pub float_nondet: bool,
655    /// Whether floating-point operations can have a non-deterministic rounding error.
656    pub float_rounding_error: FloatRoundingErrorMode,
657
658    /// Whether Miri artificially introduces short reads/writes on file descriptors.
659    pub short_fd_operations: bool,
660}
661
662impl<'tcx> MiriMachine<'tcx> {
663    /// Create a new MiriMachine.
664    ///
665    /// Invariant: `genmc_ctx.is_some() == config.genmc_config.is_some()`
666    pub(crate) fn new(
667        config: &MiriConfig,
668        layout_cx: LayoutCx<'tcx>,
669        genmc_ctx: Option<Rc<GenmcCtx>>,
670    ) -> Self {
671        let tcx = layout_cx.tcx();
672        let user_relevant_crates = Self::get_user_relevant_crates(tcx, config);
673        let layouts =
674            PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
675        let profiler = config.measureme_out.as_ref().map(|out| {
676            let crate_name =
677                tcx.sess.opts.crate_name.clone().unwrap_or_else(|| "unknown-crate".to_string());
678            let pid = process::id();
679            // We adopt the same naming scheme for the profiler output that rustc uses. In rustc,
680            // the PID is padded so that the nondeterministic value of the PID does not spread
681            // nondeterminism to the allocator. In Miri we are not aiming for such performance
682            // control, we just pad for consistency with rustc.
683            let filename = format!("{crate_name}-{pid:07}");
684            let path = Path::new(out).join(filename);
685            measureme::Profiler::new(path).expect("Couldn't create `measureme` profiler")
686        });
687        let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
688        let borrow_tracker = config.borrow_tracker.map(|bt| bt.instantiate_global_state(config));
689        let data_race = if config.genmc_config.is_some() {
690            // `genmc_ctx` persists across executions, so we don't create a new one here.
691            GlobalDataRaceHandler::Genmc(genmc_ctx.unwrap())
692        } else if config.data_race_detector {
693            GlobalDataRaceHandler::Vclocks(Box::new(data_race::GlobalState::new(config)))
694        } else {
695            GlobalDataRaceHandler::None
696        };
697        // Determine page size, stack address, and stack size.
698        // These values are mostly meaningless, but the stack address is also where we start
699        // allocating physical integer addresses for all allocations.
700        let page_size = if let Some(page_size) = config.page_size {
701            page_size
702        } else {
703            let target = &tcx.sess.target;
704            match target.arch {
705                Arch::Wasm32 | Arch::Wasm64 => 64 * 1024, // https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances
706                Arch::AArch64 => {
707                    if target.is_like_darwin {
708                        // No "definitive" source, but see:
709                        // https://www.wwdcnotes.com/notes/wwdc20/10214/
710                        // https://github.com/ziglang/zig/issues/11308 etc.
711                        16 * 1024
712                    } else {
713                        4 * 1024
714                    }
715                }
716                _ => 4 * 1024,
717            }
718        };
719        // On 16bit targets, 32 pages is more than the entire address space!
720        let stack_addr = if tcx.pointer_size().bits() < 32 { page_size } else { page_size * 32 };
721        let stack_size =
722            if tcx.pointer_size().bits() < 32 { page_size * 4 } else { page_size * 16 };
723        assert!(
724            usize::try_from(config.num_cpus).unwrap() <= cpu_affinity::MAX_CPUS,
725            "miri only supports up to {} CPUs, but {} were configured",
726            cpu_affinity::MAX_CPUS,
727            config.num_cpus
728        );
729        let threads = ThreadManager::new(config);
730        let mut thread_cpu_affinity = FxHashMap::default();
731        if matches!(&tcx.sess.target.os, Os::Linux | Os::FreeBsd | Os::Android) {
732            thread_cpu_affinity
733                .insert(threads.active_thread(), CpuAffinityMask::new(&layout_cx, config.num_cpus));
734        }
735        let alloc_addresses =
736            RefCell::new(alloc_addresses::GlobalStateInner::new(config, stack_addr, tcx));
737        MiriMachine {
738            tcx,
739            borrow_tracker,
740            data_race,
741            alloc_addresses,
742            // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
743            env_vars: EnvVars::default(),
744            main_fn_ret_place: None,
745            argc: None,
746            argv: None,
747            cmd_line: None,
748            tls: TlsData::default(),
749            isolated_op: config.isolated_op,
750            validation: config.validation,
751            fds: shims::FdTable::init(config.mute_stdout_stderr),
752            epoll_interests: shims::EpollInterestTable::new(),
753            dirs: Default::default(),
754            layouts,
755            threads,
756            thread_cpu_affinity,
757            static_roots: Vec::new(),
758            profiler,
759            string_cache: Default::default(),
760            exported_symbols_cache: FxHashMap::default(),
761            backtrace_style: config.backtrace_style,
762            user_relevant_crates,
763            extern_statics: FxHashMap::default(),
764            rng: RefCell::new(rng),
765            allocator: (!config.native_lib.is_empty())
766                .then(|| Rc::new(RefCell::new(crate::alloc::isolated_alloc::IsolatedAlloc::new()))),
767            tracked_alloc_ids: config.tracked_alloc_ids.clone(),
768            track_alloc_accesses: config.track_alloc_accesses,
769            check_alignment: config.check_alignment,
770            cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
771            preemption_rate: config.preemption_rate,
772            report_progress: config.report_progress,
773            basic_block_count: 0,
774            monotonic_clock: MonotonicClock::new(config.isolated_op == IsolatedOp::Allow),
775            #[cfg(all(unix, feature = "native-lib"))]
776            native_lib: config.native_lib.iter().map(|lib_file_path| {
777                let host_triple = rustc_session::config::host_tuple();
778                let target_triple = tcx.sess.opts.target_triple.tuple();
779                // Check if host target == the session target.
780                if host_triple != target_triple {
781                    panic!(
782                        "calling native C functions in linked .so file requires host and target to be the same: \
783                        host={host_triple}, target={target_triple}",
784                    );
785                }
786                // Note: it is the user's responsibility to provide a correct SO file.
787                // WATCH OUT: If an invalid/incorrect SO file is specified, this can cause
788                // undefined behaviour in Miri itself!
789                (
790                    unsafe {
791                        libloading::Library::new(lib_file_path)
792                            .expect("failed to read specified extern shared object file")
793                    },
794                    lib_file_path.clone(),
795                )
796            }).collect(),
797            #[cfg(all(unix, feature = "native-lib"))]
798            native_lib_ecx_interchange: Box::leak(Box::new(Cell::new(0))),
799            #[cfg(not(all(unix, feature = "native-lib")))]
800            native_lib: config.native_lib.iter().map(|_| {
801                panic!("calling functions from native libraries via FFI is not supported in this build of Miri")
802            }).collect(),
803            gc_interval: config.gc_interval,
804            since_gc: 0,
805            num_cpus: config.num_cpus,
806            page_size,
807            stack_addr,
808            stack_size,
809            collect_leak_backtraces: config.collect_leak_backtraces,
810            allocation_spans: RefCell::new(FxHashMap::default()),
811            symbolic_alignment: RefCell::new(FxHashMap::default()),
812            union_data_ranges: FxHashMap::default(),
813            pthread_mutex_sanity: Cell::new(false),
814            pthread_rwlock_sanity: Cell::new(false),
815            pthread_condvar_sanity: Cell::new(false),
816            allocator_shim_symbols: Self::allocator_shim_symbols(tcx),
817            mangle_internal_symbol_cache: Default::default(),
818            force_intrinsic_fallback: config.force_intrinsic_fallback,
819            float_nondet: config.float_nondet,
820            float_rounding_error: config.float_rounding_error,
821            short_fd_operations: config.short_fd_operations,
822        }
823    }
824
825    fn allocator_shim_symbols(
826        tcx: TyCtxt<'tcx>,
827    ) -> FxHashMap<Symbol, Either<Symbol, SpecialAllocatorMethod>> {
828        use rustc_codegen_ssa::base::allocator_shim_contents;
829
830        // codegen uses `allocator_kind_for_codegen` here, but that's only needed to deal with
831        // dylibs which we do not support.
832        let Some(kind) = tcx.allocator_kind(()) else {
833            return Default::default();
834        };
835        let methods = allocator_shim_contents(tcx, kind);
836        let mut symbols = FxHashMap::default();
837        for method in methods {
838            let from_name = Symbol::intern(&mangle_internal_symbol(
839                tcx,
840                &allocator::global_fn_name(method.name),
841            ));
842            let to = match method.special {
843                Some(special) => Either::Right(special),
844                None =>
845                    Either::Left(Symbol::intern(&mangle_internal_symbol(
846                        tcx,
847                        &allocator::default_fn_name(method.name),
848                    ))),
849            };
850            symbols.try_insert(from_name, to).unwrap();
851        }
852        symbols
853    }
854
855    /// Retrieve the list of user-relevant crates based on MIRI_LOCAL_CRATES as set by cargo-miri,
856    /// and extra crates set in the config.
857    fn get_user_relevant_crates(tcx: TyCtxt<'_>, config: &MiriConfig) -> Vec<CrateNum> {
858        // Convert the local crate names from the passed-in config into CrateNums so that they can
859        // be looked up quickly during execution
860        let local_crate_names = std::env::var("MIRI_LOCAL_CRATES")
861            .map(|crates| crates.split(',').map(|krate| krate.to_string()).collect::<Vec<_>>())
862            .unwrap_or_default();
863        let mut local_crates = Vec::new();
864        for &crate_num in tcx.crates(()) {
865            let name = tcx.crate_name(crate_num);
866            let name = name.as_str();
867            if local_crate_names
868                .iter()
869                .chain(&config.user_relevant_crates)
870                .any(|local_name| local_name == name)
871            {
872                local_crates.push(crate_num);
873            }
874        }
875        local_crates
876    }
877
878    pub(crate) fn late_init(
879        ecx: &mut MiriInterpCx<'tcx>,
880        config: &MiriConfig,
881        on_main_stack_empty: StackEmptyCallback<'tcx>,
882    ) -> InterpResult<'tcx> {
883        EnvVars::init(ecx, config)?;
884        MiriMachine::init_extern_statics(ecx)?;
885        ThreadManager::init(ecx, on_main_stack_empty);
886        interp_ok(())
887    }
888
889    pub(crate) fn add_extern_static(ecx: &mut MiriInterpCx<'tcx>, name: &str, ptr: Pointer) {
890        // This got just allocated, so there definitely is a pointer here.
891        let ptr = ptr.into_pointer_or_addr().unwrap();
892        ecx.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
893    }
894
895    pub(crate) fn communicate(&self) -> bool {
896        self.isolated_op == IsolatedOp::Allow
897    }
898
899    /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
900    pub(crate) fn is_local(&self, instance: ty::Instance<'tcx>) -> bool {
901        let def_id = instance.def_id();
902        def_id.is_local() || self.user_relevant_crates.contains(&def_id.krate)
903    }
904
905    /// Called when the interpreter is going to shut down abnormally, such as due to a Ctrl-C.
906    pub(crate) fn handle_abnormal_termination(&mut self) {
907        // All strings in the profile data are stored in a single string table which is not
908        // written to disk until the profiler is dropped. If the interpreter exits without dropping
909        // the profiler, it is not possible to interpret the profile data and all measureme tools
910        // will panic when given the file.
911        drop(self.profiler.take());
912    }
913
914    pub(crate) fn page_align(&self) -> Align {
915        Align::from_bytes(self.page_size).unwrap()
916    }
917
918    pub(crate) fn allocated_span(&self, alloc_id: AllocId) -> Option<SpanData> {
919        self.allocation_spans
920            .borrow()
921            .get(&alloc_id)
922            .map(|(allocated, _deallocated)| allocated.data())
923    }
924
925    pub(crate) fn deallocated_span(&self, alloc_id: AllocId) -> Option<SpanData> {
926        self.allocation_spans
927            .borrow()
928            .get(&alloc_id)
929            .and_then(|(_allocated, deallocated)| *deallocated)
930            .map(Span::data)
931    }
932
933    fn init_allocation(
934        ecx: &MiriInterpCx<'tcx>,
935        id: AllocId,
936        kind: MemoryKind,
937        size: Size,
938        align: Align,
939    ) -> InterpResult<'tcx, AllocExtra<'tcx>> {
940        if ecx.machine.tracked_alloc_ids.contains(&id) {
941            ecx.emit_diagnostic(NonHaltingDiagnostic::TrackingAlloc(id, size, align));
942        }
943
944        let borrow_tracker = ecx
945            .machine
946            .borrow_tracker
947            .as_ref()
948            .map(|bt| bt.borrow_mut().new_allocation(id, size, kind, &ecx.machine));
949
950        let data_race = match &ecx.machine.data_race {
951            GlobalDataRaceHandler::None => AllocDataRaceHandler::None,
952            GlobalDataRaceHandler::Vclocks(data_race) =>
953                AllocDataRaceHandler::Vclocks(
954                    data_race::AllocState::new_allocation(
955                        data_race,
956                        &ecx.machine.threads,
957                        size,
958                        kind,
959                        ecx.machine.current_user_relevant_span(),
960                    ),
961                    data_race.weak_memory.then(weak_memory::AllocState::new_allocation),
962                ),
963            GlobalDataRaceHandler::Genmc(_genmc_ctx) => {
964                // GenMC learns about new allocations directly from the alloc_addresses module,
965                // since it has to be able to control the address at which they are placed.
966                AllocDataRaceHandler::Genmc
967            }
968        };
969
970        // If an allocation is leaked, we want to report a backtrace to indicate where it was
971        // allocated. We don't need to record a backtrace for allocations which are allowed to
972        // leak.
973        let backtrace = if kind.may_leak() || !ecx.machine.collect_leak_backtraces {
974            None
975        } else {
976            Some(ecx.generate_stacktrace())
977        };
978
979        if matches!(kind, MemoryKind::Machine(kind) if kind.should_save_allocation_span()) {
980            ecx.machine
981                .allocation_spans
982                .borrow_mut()
983                .insert(id, (ecx.machine.current_user_relevant_span(), None));
984        }
985
986        interp_ok(AllocExtra {
987            borrow_tracker,
988            data_race,
989            backtrace,
990            sync_objs: BTreeMap::default(),
991        })
992    }
993}
994
995impl VisitProvenance for MiriMachine<'_> {
996    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
997        #[rustfmt::skip]
998        let MiriMachine {
999            threads,
1000            thread_cpu_affinity: _,
1001            tls,
1002            env_vars,
1003            main_fn_ret_place,
1004            argc,
1005            argv,
1006            cmd_line,
1007            extern_statics,
1008            dirs,
1009            borrow_tracker,
1010            data_race,
1011            alloc_addresses,
1012            fds,
1013            epoll_interests:_,
1014            tcx: _,
1015            isolated_op: _,
1016            validation: _,
1017            monotonic_clock: _,
1018            layouts: _,
1019            static_roots: _,
1020            profiler: _,
1021            string_cache: _,
1022            exported_symbols_cache: _,
1023            backtrace_style: _,
1024            user_relevant_crates: _,
1025            rng: _,
1026            allocator: _,
1027            tracked_alloc_ids: _,
1028            track_alloc_accesses: _,
1029            check_alignment: _,
1030            cmpxchg_weak_failure_rate: _,
1031            preemption_rate: _,
1032            report_progress: _,
1033            basic_block_count: _,
1034            native_lib: _,
1035            #[cfg(all(unix, feature = "native-lib"))]
1036            native_lib_ecx_interchange: _,
1037            gc_interval: _,
1038            since_gc: _,
1039            num_cpus: _,
1040            page_size: _,
1041            stack_addr: _,
1042            stack_size: _,
1043            collect_leak_backtraces: _,
1044            allocation_spans: _,
1045            symbolic_alignment: _,
1046            union_data_ranges: _,
1047            pthread_mutex_sanity: _,
1048            pthread_rwlock_sanity: _,
1049            pthread_condvar_sanity: _,
1050            allocator_shim_symbols: _,
1051            mangle_internal_symbol_cache: _,
1052            force_intrinsic_fallback: _,
1053            float_nondet: _,
1054            float_rounding_error: _,
1055            short_fd_operations: _,
1056        } = self;
1057
1058        threads.visit_provenance(visit);
1059        tls.visit_provenance(visit);
1060        env_vars.visit_provenance(visit);
1061        dirs.visit_provenance(visit);
1062        fds.visit_provenance(visit);
1063        data_race.visit_provenance(visit);
1064        borrow_tracker.visit_provenance(visit);
1065        alloc_addresses.visit_provenance(visit);
1066        main_fn_ret_place.visit_provenance(visit);
1067        argc.visit_provenance(visit);
1068        argv.visit_provenance(visit);
1069        cmd_line.visit_provenance(visit);
1070        for ptr in extern_statics.values() {
1071            ptr.visit_provenance(visit);
1072        }
1073    }
1074}
1075
1076/// A rustc InterpCx for Miri.
1077pub type MiriInterpCx<'tcx> = InterpCx<'tcx, MiriMachine<'tcx>>;
1078
1079/// A little trait that's useful to be inherited by extension traits.
1080pub trait MiriInterpCxExt<'tcx> {
1081    fn eval_context_ref<'a>(&'a self) -> &'a MiriInterpCx<'tcx>;
1082    fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriInterpCx<'tcx>;
1083}
1084impl<'tcx> MiriInterpCxExt<'tcx> for MiriInterpCx<'tcx> {
1085    #[inline(always)]
1086    fn eval_context_ref(&self) -> &MiriInterpCx<'tcx> {
1087        self
1088    }
1089    #[inline(always)]
1090    fn eval_context_mut(&mut self) -> &mut MiriInterpCx<'tcx> {
1091        self
1092    }
1093}
1094
1095/// Machine hook implementations.
1096impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
1097    type MemoryKind = MiriMemoryKind;
1098    type ExtraFnVal = DynSym;
1099
1100    type FrameExtra = FrameExtra<'tcx>;
1101    type AllocExtra = AllocExtra<'tcx>;
1102
1103    type Provenance = Provenance;
1104    type ProvenanceExtra = ProvenanceExtra;
1105    type Bytes = MiriAllocBytes;
1106
1107    type MemoryMap =
1108        MonoHashMap<AllocId, (MemoryKind, Allocation<Provenance, Self::AllocExtra, Self::Bytes>)>;
1109
1110    const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
1111
1112    const PANIC_ON_ALLOC_FAIL: bool = false;
1113
1114    #[inline(always)]
1115    fn enforce_alignment(ecx: &MiriInterpCx<'tcx>) -> bool {
1116        ecx.machine.check_alignment != AlignmentCheck::None
1117    }
1118
1119    #[inline(always)]
1120    fn alignment_check(
1121        ecx: &MiriInterpCx<'tcx>,
1122        alloc_id: AllocId,
1123        alloc_align: Align,
1124        alloc_kind: AllocKind,
1125        offset: Size,
1126        align: Align,
1127    ) -> Option<Misalignment> {
1128        if ecx.machine.check_alignment != AlignmentCheck::Symbolic {
1129            // Just use the built-in check.
1130            return None;
1131        }
1132        if alloc_kind != AllocKind::LiveData {
1133            // Can't have any extra info here.
1134            return None;
1135        }
1136        // Let's see which alignment we have been promised for this allocation.
1137        let (promised_offset, promised_align) = ecx
1138            .machine
1139            .symbolic_alignment
1140            .borrow()
1141            .get(&alloc_id)
1142            .copied()
1143            .unwrap_or((Size::ZERO, alloc_align));
1144        if promised_align < align {
1145            // Definitely not enough.
1146            Some(Misalignment { has: promised_align, required: align })
1147        } else {
1148            // What's the offset between us and the promised alignment?
1149            let distance = offset.bytes().wrapping_sub(promised_offset.bytes());
1150            // That must also be aligned.
1151            if distance.is_multiple_of(align.bytes()) {
1152                // All looking good!
1153                None
1154            } else {
1155                // The biggest power of two through which `distance` is divisible.
1156                let distance_pow2 = 1 << distance.trailing_zeros();
1157                Some(Misalignment {
1158                    has: Align::from_bytes(distance_pow2).unwrap(),
1159                    required: align,
1160                })
1161            }
1162        }
1163    }
1164
1165    #[inline(always)]
1166    fn enforce_validity(ecx: &MiriInterpCx<'tcx>, _layout: TyAndLayout<'tcx>) -> bool {
1167        ecx.machine.validation != ValidationMode::No
1168    }
1169    #[inline(always)]
1170    fn enforce_validity_recursively(
1171        ecx: &InterpCx<'tcx, Self>,
1172        _layout: TyAndLayout<'tcx>,
1173    ) -> bool {
1174        ecx.machine.validation == ValidationMode::Deep
1175    }
1176
1177    #[inline(always)]
1178    fn ignore_optional_overflow_checks(ecx: &MiriInterpCx<'tcx>) -> bool {
1179        !ecx.tcx.sess.overflow_checks()
1180    }
1181
1182    fn check_fn_target_features(
1183        ecx: &MiriInterpCx<'tcx>,
1184        instance: ty::Instance<'tcx>,
1185    ) -> InterpResult<'tcx> {
1186        let attrs = ecx.tcx.codegen_instance_attrs(instance.def);
1187        if attrs
1188            .target_features
1189            .iter()
1190            .any(|feature| !ecx.tcx.sess.target_features.contains(&feature.name))
1191        {
1192            let unavailable = attrs
1193                .target_features
1194                .iter()
1195                .filter(|&feature| {
1196                    feature.kind != TargetFeatureKind::Implied
1197                        && !ecx.tcx.sess.target_features.contains(&feature.name)
1198                })
1199                .fold(String::new(), |mut s, feature| {
1200                    if !s.is_empty() {
1201                        s.push_str(", ");
1202                    }
1203                    s.push_str(feature.name.as_str());
1204                    s
1205                });
1206            let msg = format!(
1207                "calling a function that requires unavailable target features: {unavailable}"
1208            );
1209            // On WASM, this is not UB, but instead gets rejected during validation of the module
1210            // (see #84988).
1211            if ecx.tcx.sess.target.is_like_wasm {
1212                throw_machine_stop!(TerminationInfo::Abort(msg));
1213            } else {
1214                throw_ub_format!("{msg}");
1215            }
1216        }
1217        interp_ok(())
1218    }
1219
1220    #[inline(always)]
1221    fn find_mir_or_eval_fn(
1222        ecx: &mut MiriInterpCx<'tcx>,
1223        instance: ty::Instance<'tcx>,
1224        abi: &FnAbi<'tcx, Ty<'tcx>>,
1225        args: &[FnArg<'tcx>],
1226        dest: &PlaceTy<'tcx>,
1227        ret: Option<mir::BasicBlock>,
1228        unwind: mir::UnwindAction,
1229    ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
1230        // For foreign items, try to see if we can emulate them.
1231        if ecx.tcx.is_foreign_item(instance.def_id()) {
1232            let _trace = enter_trace_span!("emulate_foreign_item");
1233            // An external function call that does not have a MIR body. We either find MIR elsewhere
1234            // or emulate its effect.
1235            // This will be Ok(None) if we're emulating the intrinsic entirely within Miri (no need
1236            // to run extra MIR), and Ok(Some(body)) if we found MIR to run for the
1237            // foreign function
1238            // Any needed call to `goto_block` will be performed by `emulate_foreign_item`.
1239            let args = MiriInterpCx::copy_fn_args(args); // FIXME: Should `InPlace` arguments be reset to uninit?
1240            let link_name = Symbol::intern(ecx.tcx.symbol_name(instance).name);
1241            return ecx.emulate_foreign_item(link_name, abi, &args, dest, ret, unwind);
1242        }
1243
1244        if ecx.machine.data_race.as_genmc_ref().is_some()
1245            && ecx.genmc_intercept_function(instance, args, dest)?
1246        {
1247            ecx.return_to_block(ret)?;
1248            return interp_ok(None);
1249        }
1250
1251        // Otherwise, load the MIR.
1252        let _trace = enter_trace_span!("load_mir");
1253        interp_ok(Some((ecx.load_mir(instance.def, None)?, instance)))
1254    }
1255
1256    #[inline(always)]
1257    fn call_extra_fn(
1258        ecx: &mut MiriInterpCx<'tcx>,
1259        fn_val: DynSym,
1260        abi: &FnAbi<'tcx, Ty<'tcx>>,
1261        args: &[FnArg<'tcx>],
1262        dest: &PlaceTy<'tcx>,
1263        ret: Option<mir::BasicBlock>,
1264        unwind: mir::UnwindAction,
1265    ) -> InterpResult<'tcx> {
1266        let args = MiriInterpCx::copy_fn_args(args); // FIXME: Should `InPlace` arguments be reset to uninit?
1267        ecx.emulate_dyn_sym(fn_val, abi, &args, dest, ret, unwind)
1268    }
1269
1270    #[inline(always)]
1271    fn call_intrinsic(
1272        ecx: &mut MiriInterpCx<'tcx>,
1273        instance: ty::Instance<'tcx>,
1274        args: &[OpTy<'tcx>],
1275        dest: &PlaceTy<'tcx>,
1276        ret: Option<mir::BasicBlock>,
1277        unwind: mir::UnwindAction,
1278    ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
1279        ecx.call_intrinsic(instance, args, dest, ret, unwind)
1280    }
1281
1282    #[inline(always)]
1283    fn assert_panic(
1284        ecx: &mut MiriInterpCx<'tcx>,
1285        msg: &mir::AssertMessage<'tcx>,
1286        unwind: mir::UnwindAction,
1287    ) -> InterpResult<'tcx> {
1288        ecx.assert_panic(msg, unwind)
1289    }
1290
1291    fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
1292        ecx.start_panic_nounwind(msg)
1293    }
1294
1295    fn unwind_terminate(
1296        ecx: &mut InterpCx<'tcx, Self>,
1297        reason: mir::UnwindTerminateReason,
1298    ) -> InterpResult<'tcx> {
1299        // Call the lang item.
1300        let panic = ecx.tcx.lang_items().get(reason.lang_item()).unwrap();
1301        let panic = ty::Instance::mono(ecx.tcx.tcx, panic);
1302        ecx.call_function(
1303            panic,
1304            ExternAbi::Rust,
1305            &[],
1306            None,
1307            ReturnContinuation::Goto { ret: None, unwind: mir::UnwindAction::Unreachable },
1308        )?;
1309        interp_ok(())
1310    }
1311
1312    #[inline(always)]
1313    fn binary_ptr_op(
1314        ecx: &MiriInterpCx<'tcx>,
1315        bin_op: mir::BinOp,
1316        left: &ImmTy<'tcx>,
1317        right: &ImmTy<'tcx>,
1318    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
1319        ecx.binary_ptr_op(bin_op, left, right)
1320    }
1321
1322    #[inline(always)]
1323    fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
1324        ecx: &InterpCx<'tcx, Self>,
1325        inputs: &[F1],
1326    ) -> F2 {
1327        ecx.generate_nan(inputs)
1328    }
1329
1330    #[inline(always)]
1331    fn apply_float_nondet(
1332        ecx: &mut InterpCx<'tcx, Self>,
1333        val: ImmTy<'tcx>,
1334    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
1335        crate::math::apply_random_float_error_to_imm(ecx, val, 4)
1336    }
1337
1338    #[inline(always)]
1339    fn equal_float_min_max<F: Float>(ecx: &MiriInterpCx<'tcx>, a: F, b: F) -> F {
1340        ecx.equal_float_min_max(a, b)
1341    }
1342
1343    #[inline(always)]
1344    fn float_fuse_mul_add(ecx: &InterpCx<'tcx, Self>) -> bool {
1345        ecx.machine.float_nondet && ecx.machine.rng.borrow_mut().random()
1346    }
1347
1348    #[inline(always)]
1349    fn runtime_checks(
1350        ecx: &InterpCx<'tcx, Self>,
1351        r: mir::RuntimeChecks,
1352    ) -> InterpResult<'tcx, bool> {
1353        interp_ok(r.value(ecx.tcx.sess))
1354    }
1355
1356    #[inline(always)]
1357    fn thread_local_static_pointer(
1358        ecx: &mut MiriInterpCx<'tcx>,
1359        def_id: DefId,
1360    ) -> InterpResult<'tcx, StrictPointer> {
1361        ecx.get_or_create_thread_local_alloc(def_id)
1362    }
1363
1364    fn extern_static_pointer(
1365        ecx: &MiriInterpCx<'tcx>,
1366        def_id: DefId,
1367    ) -> InterpResult<'tcx, StrictPointer> {
1368        let link_name = Symbol::intern(ecx.tcx.symbol_name(Instance::mono(*ecx.tcx, def_id)).name);
1369        if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
1370            // Various parts of the engine rely on `get_alloc_info` for size and alignment
1371            // information. That uses the type information of this static.
1372            // Make sure it matches the Miri allocation for this.
1373            let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
1374                panic!("extern_statics cannot contain wildcards")
1375            };
1376            let info = ecx.get_alloc_info(alloc_id);
1377            let def_ty = ecx.tcx.type_of(def_id).instantiate_identity();
1378            let extern_decl_layout =
1379                ecx.tcx.layout_of(ecx.typing_env().as_query_input(def_ty)).unwrap();
1380            if extern_decl_layout.size != info.size || extern_decl_layout.align.abi != info.align {
1381                throw_unsup_format!(
1382                    "extern static `{link_name}` has been declared as `{krate}::{name}` \
1383                    with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
1384                    but Miri emulates it via an extern static shim \
1385                    with a size of {shim_size} bytes and alignment of {shim_align} bytes",
1386                    name = ecx.tcx.def_path_str(def_id),
1387                    krate = ecx.tcx.crate_name(def_id.krate),
1388                    decl_size = extern_decl_layout.size.bytes(),
1389                    decl_align = extern_decl_layout.align.bytes(),
1390                    shim_size = info.size.bytes(),
1391                    shim_align = info.align.bytes(),
1392                )
1393            }
1394            interp_ok(ptr)
1395        } else {
1396            throw_unsup_format!("extern static `{link_name}` is not supported by Miri",)
1397        }
1398    }
1399
1400    fn init_local_allocation(
1401        ecx: &MiriInterpCx<'tcx>,
1402        id: AllocId,
1403        kind: MemoryKind,
1404        size: Size,
1405        align: Align,
1406    ) -> InterpResult<'tcx, Self::AllocExtra> {
1407        assert!(kind != MiriMemoryKind::Global.into());
1408        MiriMachine::init_allocation(ecx, id, kind, size, align)
1409    }
1410
1411    fn adjust_alloc_root_pointer(
1412        ecx: &MiriInterpCx<'tcx>,
1413        ptr: interpret::Pointer<CtfeProvenance>,
1414        kind: Option<MemoryKind>,
1415    ) -> InterpResult<'tcx, interpret::Pointer<Provenance>> {
1416        let kind = kind.expect("we set our GLOBAL_KIND so this cannot be None");
1417        let alloc_id = ptr.provenance.alloc_id();
1418        if cfg!(debug_assertions) {
1419            // The machine promises to never call us on thread-local or extern statics.
1420            match ecx.tcx.try_get_global_alloc(alloc_id) {
1421                Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
1422                    panic!("adjust_alloc_root_pointer called on thread-local static")
1423                }
1424                Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
1425                    panic!("adjust_alloc_root_pointer called on extern static")
1426                }
1427                _ => {}
1428            }
1429        }
1430        // FIXME: can we somehow preserve the immutability of `ptr`?
1431        let tag = if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
1432            borrow_tracker.borrow_mut().root_ptr_tag(alloc_id, &ecx.machine)
1433        } else {
1434            // Value does not matter, SB is disabled
1435            BorTag::default()
1436        };
1437        ecx.adjust_alloc_root_pointer(ptr, tag, kind)
1438    }
1439
1440    /// Called on `usize as ptr` casts.
1441    #[inline(always)]
1442    fn ptr_from_addr_cast(ecx: &MiriInterpCx<'tcx>, addr: u64) -> InterpResult<'tcx, Pointer> {
1443        ecx.ptr_from_addr_cast(addr)
1444    }
1445
1446    /// Called on `ptr as usize` casts.
1447    /// (Actually computing the resulting `usize` doesn't need machine help,
1448    /// that's just `Scalar::try_to_int`.)
1449    #[inline(always)]
1450    fn expose_provenance(
1451        ecx: &InterpCx<'tcx, Self>,
1452        provenance: Self::Provenance,
1453    ) -> InterpResult<'tcx> {
1454        ecx.expose_provenance(provenance)
1455    }
1456
1457    /// Convert a pointer with provenance into an allocation-offset pair and extra provenance info.
1458    /// `size` says how many bytes of memory are expected at that pointer. The *sign* of `size` can
1459    /// be used to disambiguate situations where a wildcard pointer sits right in between two
1460    /// allocations.
1461    ///
1462    /// If `ptr.provenance.get_alloc_id()` is `Some(p)`, the returned `AllocId` must be `p`.
1463    /// The resulting `AllocId` will just be used for that one step and the forgotten again
1464    /// (i.e., we'll never turn the data returned here back into a `Pointer` that might be
1465    /// stored in machine state).
1466    ///
1467    /// When this fails, that means the pointer does not point to a live allocation.
1468    fn ptr_get_alloc(
1469        ecx: &MiriInterpCx<'tcx>,
1470        ptr: StrictPointer,
1471        size: i64,
1472    ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
1473        let rel = ecx.ptr_get_alloc(ptr, size);
1474
1475        rel.map(|(alloc_id, size)| {
1476            let tag = match ptr.provenance {
1477                Provenance::Concrete { tag, .. } => ProvenanceExtra::Concrete(tag),
1478                Provenance::Wildcard => ProvenanceExtra::Wildcard,
1479            };
1480            (alloc_id, size, tag)
1481        })
1482    }
1483
1484    /// Called to adjust global allocations to the Provenance and AllocExtra of this machine.
1485    ///
1486    /// If `alloc` contains pointers, then they are all pointing to globals.
1487    ///
1488    /// This should avoid copying if no work has to be done! If this returns an owned
1489    /// allocation (because a copy had to be done to adjust things), machine memory will
1490    /// cache the result. (This relies on `AllocMap::get_or` being able to add the
1491    /// owned allocation to the map even when the map is shared.)
1492    fn adjust_global_allocation<'b>(
1493        ecx: &InterpCx<'tcx, Self>,
1494        id: AllocId,
1495        alloc: &'b Allocation,
1496    ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>
1497    {
1498        let alloc = alloc.adjust_from_tcx(
1499            &ecx.tcx,
1500            |bytes, align| ecx.get_global_alloc_bytes(id, bytes, align),
1501            |ptr| ecx.global_root_pointer(ptr),
1502        )?;
1503        let kind = MiriMemoryKind::Global.into();
1504        let extra = MiriMachine::init_allocation(ecx, id, kind, alloc.size(), alloc.align)?;
1505        interp_ok(Cow::Owned(alloc.with_extra(extra)))
1506    }
1507
1508    #[inline(always)]
1509    fn before_memory_read(
1510        _tcx: TyCtxtAt<'tcx>,
1511        machine: &Self,
1512        alloc_extra: &AllocExtra<'tcx>,
1513        ptr: Pointer,
1514        (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1515        range: AllocRange,
1516    ) -> InterpResult<'tcx> {
1517        if machine.track_alloc_accesses && machine.tracked_alloc_ids.contains(&alloc_id) {
1518            machine.emit_diagnostic(NonHaltingDiagnostic::AccessedAlloc(
1519                alloc_id,
1520                range,
1521                borrow_tracker::AccessKind::Read,
1522            ));
1523        }
1524        // The order of checks is deliberate, to prefer reporting a data race over a borrow tracker error.
1525        match &machine.data_race {
1526            GlobalDataRaceHandler::None => {}
1527            GlobalDataRaceHandler::Genmc(genmc_ctx) =>
1528                genmc_ctx.memory_load(machine, ptr.addr(), range.size)?,
1529            GlobalDataRaceHandler::Vclocks(_data_race) => {
1530                let _trace = enter_trace_span!(data_race::before_memory_read);
1531                let AllocDataRaceHandler::Vclocks(data_race, _weak_memory) = &alloc_extra.data_race
1532                else {
1533                    unreachable!();
1534                };
1535                data_race.read_non_atomic(alloc_id, range, NaReadType::Read, None, machine)?;
1536            }
1537        }
1538        if let Some(borrow_tracker) = &alloc_extra.borrow_tracker {
1539            borrow_tracker.before_memory_read(alloc_id, prov_extra, range, machine)?;
1540        }
1541        // Check if there are any sync objects that would like to prevent reading this memory.
1542        for (_offset, obj) in alloc_extra.sync_objs.range(range.start..range.end()) {
1543            obj.on_access(concurrency::sync::AccessKind::Read)?;
1544        }
1545
1546        interp_ok(())
1547    }
1548
1549    #[inline(always)]
1550    fn before_memory_write(
1551        _tcx: TyCtxtAt<'tcx>,
1552        machine: &mut Self,
1553        alloc_extra: &mut AllocExtra<'tcx>,
1554        ptr: Pointer,
1555        (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1556        range: AllocRange,
1557    ) -> InterpResult<'tcx> {
1558        if machine.track_alloc_accesses && machine.tracked_alloc_ids.contains(&alloc_id) {
1559            machine.emit_diagnostic(NonHaltingDiagnostic::AccessedAlloc(
1560                alloc_id,
1561                range,
1562                borrow_tracker::AccessKind::Write,
1563            ));
1564        }
1565        match &machine.data_race {
1566            GlobalDataRaceHandler::None => {}
1567            GlobalDataRaceHandler::Genmc(genmc_ctx) =>
1568                genmc_ctx.memory_store(machine, ptr.addr(), range.size)?,
1569            GlobalDataRaceHandler::Vclocks(_global_state) => {
1570                let _trace = enter_trace_span!(data_race::before_memory_write);
1571                let AllocDataRaceHandler::Vclocks(data_race, weak_memory) =
1572                    &mut alloc_extra.data_race
1573                else {
1574                    unreachable!()
1575                };
1576                data_race.write_non_atomic(alloc_id, range, NaWriteType::Write, None, machine)?;
1577                if let Some(weak_memory) = weak_memory {
1578                    weak_memory
1579                        .non_atomic_write(range, machine.data_race.as_vclocks_ref().unwrap());
1580                }
1581            }
1582        }
1583        if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1584            borrow_tracker.before_memory_write(alloc_id, prov_extra, range, machine)?;
1585        }
1586        // Delete sync objects that don't like writes.
1587        // Most of the time, we can just skip this.
1588        if !alloc_extra.sync_objs.is_empty() {
1589            let mut to_delete = vec![];
1590            for (offset, obj) in alloc_extra.sync_objs.range(range.start..range.end()) {
1591                obj.on_access(concurrency::sync::AccessKind::Write)?;
1592                if obj.delete_on_write() {
1593                    to_delete.push(*offset);
1594                }
1595            }
1596            for offset in to_delete {
1597                alloc_extra.sync_objs.remove(&offset);
1598            }
1599        }
1600        interp_ok(())
1601    }
1602
1603    #[inline(always)]
1604    fn before_memory_deallocation(
1605        _tcx: TyCtxtAt<'tcx>,
1606        machine: &mut Self,
1607        alloc_extra: &mut AllocExtra<'tcx>,
1608        ptr: Pointer,
1609        (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
1610        size: Size,
1611        align: Align,
1612        kind: MemoryKind,
1613    ) -> InterpResult<'tcx> {
1614        if machine.tracked_alloc_ids.contains(&alloc_id) {
1615            machine.emit_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
1616        }
1617        match &machine.data_race {
1618            GlobalDataRaceHandler::None => {}
1619            GlobalDataRaceHandler::Genmc(genmc_ctx) =>
1620                genmc_ctx.handle_dealloc(machine, alloc_id, ptr.addr(), kind)?,
1621            GlobalDataRaceHandler::Vclocks(_global_state) => {
1622                let _trace = enter_trace_span!(data_race::before_memory_deallocation);
1623                let data_race = alloc_extra.data_race.as_vclocks_mut().unwrap();
1624                data_race.write_non_atomic(
1625                    alloc_id,
1626                    alloc_range(Size::ZERO, size),
1627                    NaWriteType::Deallocate,
1628                    None,
1629                    machine,
1630                )?;
1631            }
1632        }
1633        if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1634            borrow_tracker.before_memory_deallocation(alloc_id, prove_extra, size, machine)?;
1635        }
1636        // Check if there are any sync objects that would like to prevent freeing this memory.
1637        for obj in alloc_extra.sync_objs.values() {
1638            obj.on_access(concurrency::sync::AccessKind::Dealloc)?;
1639        }
1640
1641        if let Some((_, deallocated_at)) = machine.allocation_spans.borrow_mut().get_mut(&alloc_id)
1642        {
1643            *deallocated_at = Some(machine.current_user_relevant_span());
1644        }
1645        machine.free_alloc_id(alloc_id, size, align, kind);
1646        interp_ok(())
1647    }
1648
1649    #[inline(always)]
1650    fn retag_ptr_value(
1651        ecx: &mut InterpCx<'tcx, Self>,
1652        kind: mir::RetagKind,
1653        val: &ImmTy<'tcx>,
1654    ) -> InterpResult<'tcx, ImmTy<'tcx>> {
1655        if ecx.machine.borrow_tracker.is_some() {
1656            ecx.retag_ptr_value(kind, val)
1657        } else {
1658            interp_ok(val.clone())
1659        }
1660    }
1661
1662    #[inline(always)]
1663    fn retag_place_contents(
1664        ecx: &mut InterpCx<'tcx, Self>,
1665        kind: mir::RetagKind,
1666        place: &PlaceTy<'tcx>,
1667    ) -> InterpResult<'tcx> {
1668        if ecx.machine.borrow_tracker.is_some() {
1669            ecx.retag_place_contents(kind, place)?;
1670        }
1671        interp_ok(())
1672    }
1673
1674    fn protect_in_place_function_argument(
1675        ecx: &mut InterpCx<'tcx, Self>,
1676        place: &MPlaceTy<'tcx>,
1677    ) -> InterpResult<'tcx> {
1678        // If we have a borrow tracker, we also have it set up protection so that all reads *and
1679        // writes* during this call are insta-UB.
1680        let protected_place = if ecx.machine.borrow_tracker.is_some() {
1681            ecx.protect_place(place)?
1682        } else {
1683            // No borrow tracker.
1684            place.clone()
1685        };
1686        // We do need to write `uninit` so that even after the call ends, the former contents of
1687        // this place cannot be observed any more. We do the write after retagging so that for
1688        // Tree Borrows, this is considered to activate the new tag.
1689        // Conveniently this also ensures that the place actually points to suitable memory.
1690        ecx.write_uninit(&protected_place)?;
1691        // Now we throw away the protected place, ensuring its tag is never used again.
1692        interp_ok(())
1693    }
1694
1695    #[inline(always)]
1696    fn init_frame(
1697        ecx: &mut InterpCx<'tcx, Self>,
1698        frame: Frame<'tcx, Provenance>,
1699    ) -> InterpResult<'tcx, Frame<'tcx, Provenance, FrameExtra<'tcx>>> {
1700        // Start recording our event before doing anything else
1701        let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
1702            let fn_name = frame.instance().to_string();
1703            let entry = ecx.machine.string_cache.entry(fn_name.clone());
1704            let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
1705
1706            Some(profiler.start_recording_interval_event_detached(
1707                *name,
1708                measureme::EventId::from_label(*name),
1709                ecx.active_thread().to_u32(),
1710            ))
1711        } else {
1712            None
1713        };
1714
1715        let borrow_tracker = ecx.machine.borrow_tracker.as_ref();
1716
1717        let extra = FrameExtra {
1718            borrow_tracker: borrow_tracker.map(|bt| bt.borrow_mut().new_frame()),
1719            catch_unwind: None,
1720            timing,
1721            user_relevance: ecx.machine.user_relevance(&frame),
1722            data_race: ecx
1723                .machine
1724                .data_race
1725                .as_vclocks_ref()
1726                .map(|_| data_race::FrameState::default()),
1727        };
1728
1729        interp_ok(frame.with_extra(extra))
1730    }
1731
1732    fn stack<'a>(
1733        ecx: &'a InterpCx<'tcx, Self>,
1734    ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
1735        ecx.active_thread_stack()
1736    }
1737
1738    fn stack_mut<'a>(
1739        ecx: &'a mut InterpCx<'tcx, Self>,
1740    ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
1741        ecx.active_thread_stack_mut()
1742    }
1743
1744    fn before_terminator(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1745        ecx.machine.basic_block_count += 1u64; // a u64 that is only incremented by 1 will "never" overflow
1746        ecx.machine.since_gc += 1;
1747        // Possibly report our progress. This will point at the terminator we are about to execute.
1748        if let Some(report_progress) = ecx.machine.report_progress {
1749            if ecx.machine.basic_block_count.is_multiple_of(u64::from(report_progress)) {
1750                ecx.emit_diagnostic(NonHaltingDiagnostic::ProgressReport {
1751                    block_count: ecx.machine.basic_block_count,
1752                });
1753            }
1754        }
1755
1756        // Search for BorTags to find all live pointers, then remove all other tags from borrow
1757        // stacks.
1758        // When debug assertions are enabled, run the GC as often as possible so that any cases
1759        // where it mistakenly removes an important tag become visible.
1760        if ecx.machine.gc_interval > 0 && ecx.machine.since_gc >= ecx.machine.gc_interval {
1761            ecx.machine.since_gc = 0;
1762            ecx.run_provenance_gc();
1763        }
1764
1765        // These are our preemption points.
1766        // (This will only take effect after the terminator has been executed.)
1767        ecx.maybe_preempt_active_thread();
1768
1769        // Make sure some time passes.
1770        ecx.machine.monotonic_clock.tick();
1771
1772        interp_ok(())
1773    }
1774
1775    #[inline(always)]
1776    fn after_stack_push(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1777        if ecx.frame().extra.user_relevance >= ecx.active_thread_ref().current_user_relevance() {
1778            // We just pushed a frame that's at least as relevant as the so-far most relevant frame.
1779            // That means we are now the most relevant frame.
1780            let stack_len = ecx.active_thread_stack().len();
1781            ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1);
1782        }
1783        interp_ok(())
1784    }
1785
1786    fn before_stack_pop(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1787        let frame = ecx.frame();
1788        // We want this *before* the return value copy, because the return place itself is protected
1789        // until we do `on_stack_pop` here, and we need to un-protect it to copy the return value.
1790        if ecx.machine.borrow_tracker.is_some() {
1791            ecx.on_stack_pop(frame)?;
1792        }
1793        if ecx
1794            .active_thread_ref()
1795            .top_user_relevant_frame()
1796            .expect("there should always be a most relevant frame for a non-empty stack")
1797            == ecx.frame_idx()
1798        {
1799            // We are popping the most relevant frame. We have no clue what the next relevant frame
1800            // below that is, so we recompute that.
1801            // (If this ever becomes a bottleneck, we could have `push` store the previous
1802            // user-relevant frame and restore that here.)
1803            // We have to skip the frame that is just being popped.
1804            ecx.active_thread_mut().recompute_top_user_relevant_frame(/* skip */ 1);
1805        }
1806        // tracing-tree can automatically annotate scope changes, but it gets very confused by our
1807        // concurrency and what it prints is just plain wrong. So we print our own information
1808        // instead. (Cc https://github.com/rust-lang/miri/issues/2266)
1809        info!("Leaving {}", ecx.frame().instance());
1810        interp_ok(())
1811    }
1812
1813    #[inline(always)]
1814    fn after_stack_pop(
1815        ecx: &mut InterpCx<'tcx, Self>,
1816        frame: Frame<'tcx, Provenance, FrameExtra<'tcx>>,
1817        unwinding: bool,
1818    ) -> InterpResult<'tcx, ReturnAction> {
1819        let res = {
1820            // Move `frame` into a sub-scope so we control when it will be dropped.
1821            let mut frame = frame;
1822            let timing = frame.extra.timing.take();
1823            let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
1824            if let Some(profiler) = ecx.machine.profiler.as_ref() {
1825                profiler.finish_recording_interval_event(timing.unwrap());
1826            }
1827            res
1828        };
1829        // Needs to be done after dropping frame to show up on the right nesting level.
1830        // (Cc https://github.com/rust-lang/miri/issues/2266)
1831        if !ecx.active_thread_stack().is_empty() {
1832            info!("Continuing in {}", ecx.frame().instance());
1833        }
1834        res
1835    }
1836
1837    fn after_local_read(
1838        ecx: &InterpCx<'tcx, Self>,
1839        frame: &Frame<'tcx, Provenance, FrameExtra<'tcx>>,
1840        local: mir::Local,
1841    ) -> InterpResult<'tcx> {
1842        if let Some(data_race) = &frame.extra.data_race {
1843            let _trace = enter_trace_span!(data_race::after_local_read);
1844            data_race.local_read(local, &ecx.machine);
1845        }
1846        interp_ok(())
1847    }
1848
1849    fn after_local_write(
1850        ecx: &mut InterpCx<'tcx, Self>,
1851        local: mir::Local,
1852        storage_live: bool,
1853    ) -> InterpResult<'tcx> {
1854        if let Some(data_race) = &ecx.frame().extra.data_race {
1855            let _trace = enter_trace_span!(data_race::after_local_write);
1856            data_race.local_write(local, storage_live, &ecx.machine);
1857        }
1858        interp_ok(())
1859    }
1860
1861    fn after_local_moved_to_memory(
1862        ecx: &mut InterpCx<'tcx, Self>,
1863        local: mir::Local,
1864        mplace: &MPlaceTy<'tcx>,
1865    ) -> InterpResult<'tcx> {
1866        let Some(Provenance::Concrete { alloc_id, .. }) = mplace.ptr().provenance else {
1867            panic!("after_local_allocated should only be called on fresh allocations");
1868        };
1869        // Record the span where this was allocated: the declaration of the local.
1870        let local_decl = &ecx.frame().body().local_decls[local];
1871        let span = local_decl.source_info.span;
1872        ecx.machine.allocation_spans.borrow_mut().insert(alloc_id, (span, None));
1873        // The data race system has to fix the clocks used for this write.
1874        let (alloc_info, machine) = ecx.get_alloc_extra_mut(alloc_id)?;
1875        if let Some(data_race) =
1876            &machine.threads.active_thread_stack().last().unwrap().extra.data_race
1877        {
1878            let _trace = enter_trace_span!(data_race::after_local_moved_to_memory);
1879            data_race.local_moved_to_memory(
1880                local,
1881                alloc_info.data_race.as_vclocks_mut().unwrap(),
1882                machine,
1883            );
1884        }
1885        interp_ok(())
1886    }
1887
1888    fn get_global_alloc_salt(
1889        ecx: &InterpCx<'tcx, Self>,
1890        instance: Option<ty::Instance<'tcx>>,
1891    ) -> usize {
1892        let unique = if let Some(instance) = instance {
1893            // Functions cannot be identified by pointers, as asm-equal functions can get
1894            // deduplicated by the linker (we set the "unnamed_addr" attribute for LLVM) and
1895            // functions can be duplicated across crates. We thus generate a new `AllocId` for every
1896            // mention of a function. This means that `main as fn() == main as fn()` is false, while
1897            // `let x = main as fn(); x == x` is true. However, as a quality-of-life feature it can
1898            // be useful to identify certain functions uniquely, e.g. for backtraces. So we identify
1899            // whether codegen will actually emit duplicate functions. It does that when they have
1900            // non-lifetime generics, or when they can be inlined. All other functions are given a
1901            // unique address. This is not a stable guarantee! The `inline` attribute is a hint and
1902            // cannot be relied upon for anything. But if we don't do this, the
1903            // `__rust_begin_short_backtrace`/`__rust_end_short_backtrace` logic breaks and panic
1904            // backtraces look terrible.
1905            let is_generic = instance
1906                .args
1907                .into_iter()
1908                .any(|arg| !matches!(arg.kind(), ty::GenericArgKind::Lifetime(_)));
1909            let can_be_inlined = matches!(
1910                ecx.tcx.sess.opts.unstable_opts.cross_crate_inline_threshold,
1911                InliningThreshold::Always
1912            ) || !matches!(
1913                ecx.tcx.codegen_instance_attrs(instance.def).inline,
1914                InlineAttr::Never
1915            );
1916            !is_generic && !can_be_inlined
1917        } else {
1918            // Non-functions are never unique.
1919            false
1920        };
1921        // Always use the same salt if the allocation is unique.
1922        if unique {
1923            CTFE_ALLOC_SALT
1924        } else {
1925            ecx.machine.rng.borrow_mut().random_range(0..ADDRS_PER_ANON_GLOBAL)
1926        }
1927    }
1928
1929    fn cached_union_data_range<'e>(
1930        ecx: &'e mut InterpCx<'tcx, Self>,
1931        ty: Ty<'tcx>,
1932        compute_range: impl FnOnce() -> RangeSet,
1933    ) -> Cow<'e, RangeSet> {
1934        Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
1935    }
1936
1937    fn get_default_alloc_params(&self) -> <Self::Bytes as AllocBytes>::AllocParams {
1938        use crate::alloc::MiriAllocParams;
1939
1940        match &self.allocator {
1941            Some(alloc) => MiriAllocParams::Isolated(alloc.clone()),
1942            None => MiriAllocParams::Global,
1943        }
1944    }
1945
1946    fn enter_trace_span(span: impl FnOnce() -> tracing::Span) -> impl EnteredTraceSpan {
1947        #[cfg(feature = "tracing")]
1948        {
1949            span().entered()
1950        }
1951        #[cfg(not(feature = "tracing"))]
1952        #[expect(clippy::unused_unit)]
1953        {
1954            let _ = span; // so we avoid the "unused variable" warning
1955            ()
1956        }
1957    }
1958}
1959
1960/// Trait for callbacks handling asynchronous machine operations.
1961pub trait MachineCallback<'tcx, T>: VisitProvenance {
1962    /// The function to be invoked when the callback is fired.
1963    fn call(
1964        self: Box<Self>,
1965        ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
1966        arg: T,
1967    ) -> InterpResult<'tcx>;
1968}
1969
1970/// Type alias for boxed machine callbacks with generic argument type.
1971pub type DynMachineCallback<'tcx, T> = Box<dyn MachineCallback<'tcx, T> + 'tcx>;
1972
1973/// Creates a `DynMachineCallback`:
1974///
1975/// ```rust
1976/// callback!(
1977///     @capture<'tcx> {
1978///         var1: Ty1,
1979///         var2: Ty2<'tcx>,
1980///     }
1981///     |this, arg: ArgTy| {
1982///         // Implement the callback here.
1983///         todo!()
1984///     }
1985/// )
1986/// ```
1987///
1988/// All the argument types must implement `VisitProvenance`.
1989#[macro_export]
1990macro_rules! callback {
1991    (@capture<$tcx:lifetime $(,)? $($lft:lifetime),*>
1992        { $($name:ident: $type:ty),* $(,)? }
1993     |$this:ident, $arg:ident: $arg_ty:ty| $body:expr $(,)?) => {{
1994        struct Callback<$tcx, $($lft),*> {
1995            $($name: $type,)*
1996            _phantom: std::marker::PhantomData<&$tcx ()>,
1997        }
1998
1999        impl<$tcx, $($lft),*> VisitProvenance for Callback<$tcx, $($lft),*> {
2000            fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
2001                $(
2002                    self.$name.visit_provenance(_visit);
2003                )*
2004            }
2005        }
2006
2007        impl<$tcx, $($lft),*> MachineCallback<$tcx, $arg_ty> for Callback<$tcx, $($lft),*> {
2008            fn call(
2009                self: Box<Self>,
2010                $this: &mut MiriInterpCx<$tcx>,
2011                $arg: $arg_ty
2012            ) -> InterpResult<$tcx> {
2013                #[allow(unused_variables)]
2014                let Callback { $($name,)* _phantom } = *self;
2015                $body
2016            }
2017        }
2018
2019        Box::new(Callback {
2020            $($name,)*
2021            _phantom: std::marker::PhantomData
2022        })
2023    }};
2024}