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