miri/
machine.rs

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