1use 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
35pub const SIGRTMIN: i32 = 34;
39
40pub const SIGRTMAX: i32 = 42;
44
45const ADDRS_PER_ANON_GLOBAL: usize = 32;
49
50pub struct FrameExtra<'tcx> {
52 pub borrow_tracker: Option<borrow_tracker::FrameState>,
54
55 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
59
60 pub timing: Option<measureme::DetachedTiming>,
64
65 pub is_user_relevant: bool,
70
71 salt: usize,
76
77 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 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#[derive(Debug, Copy, Clone, PartialEq, Eq)]
120pub enum MiriMemoryKind {
121 Rust,
123 Miri,
125 C,
127 WinHeap,
129 WinLocal,
131 Machine,
134 Runtime,
137 Global,
140 ExternStatic,
143 Tls,
146 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 fn should_save_allocation_span(self) -> bool {
171 use self::MiriMemoryKind::*;
172 match self {
173 Rust | Miri | C | WinHeap | WinLocal | Mmap => true,
175 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#[derive(Clone, Copy, PartialEq, Eq, Hash)]
208pub enum Provenance {
209 Concrete {
212 alloc_id: AllocId,
213 tag: BorTag,
215 },
216 Wildcard,
233}
234
235#[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#[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 if f.alternate() {
256 write!(f, "[{alloc_id:#?}]")?;
257 } else {
258 write!(f, "[{alloc_id:?}]")?;
259 }
260 write!(f, "{tag:?}")?;
262 }
263 Provenance::Wildcard => {
264 write!(f, "[wildcard]")?;
265 }
266 }
267 Ok(())
268 }
269}
270
271impl interpret::Provenance for Provenance {
272 const OFFSET_IS_ADDR: bool = true;
274
275 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(); 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 (
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 (Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o,
306 _ => 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#[derive(Debug)]
332pub struct AllocExtra<'tcx> {
333 pub borrow_tracker: Option<borrow_tracker::AllocState>,
335 pub data_race: Option<data_race::AllocState>,
338 pub weak_memory: Option<weak_memory::AllocState>,
341 pub backtrace: Option<Vec<FrameInfo<'tcx>>>,
346 pub sync: FxHashMap<Size, Box<dyn Any>>,
351}
352
353impl<'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
371pub 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>, pub const_raw_ptr: TyAndLayout<'tcx>, }
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
439pub struct MiriMachine<'tcx> {
444 pub tcx: TyCtxt<'tcx>,
446
447 pub borrow_tracker: Option<borrow_tracker::GlobalState>,
449
450 pub data_race: Option<data_race::GlobalState>,
452
453 pub alloc_addresses: alloc_addresses::GlobalState,
455
456 pub(crate) env_vars: EnvVars<'tcx>,
458
459 pub(crate) main_fn_ret_place: Option<MPlaceTy<'tcx>>,
461
462 pub(crate) argc: Option<Pointer>,
466 pub(crate) argv: Option<Pointer>,
467 pub(crate) cmd_line: Option<Pointer>,
468
469 pub(crate) tls: TlsData<'tcx>,
471
472 pub(crate) isolated_op: IsolatedOp,
476
477 pub(crate) validation: ValidationMode,
479
480 pub(crate) fds: shims::FdTable,
482 pub(crate) dirs: shims::DirTable,
484
485 pub(crate) epoll_interests: shims::EpollInterestTable,
487
488 pub(crate) clock: Clock,
490
491 pub(crate) threads: ThreadManager<'tcx>,
493
494 pub(crate) thread_cpu_affinity: FxHashMap<ThreadId, CpuAffinityMask>,
498
499 pub(crate) sync: SynchronizationObjects,
501
502 pub(crate) layouts: PrimitiveLayouts<'tcx>,
504
505 pub(crate) static_roots: Vec<AllocId>,
507
508 profiler: Option<measureme::Profiler>,
511 string_cache: FxHashMap<String, measureme::StringId>,
514
515 pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
518
519 pub(crate) backtrace_style: BacktraceStyle,
521
522 pub(crate) local_crates: Vec<CrateNum>,
524
525 extern_statics: FxHashMap<Symbol, StrictPointer>,
527
528 pub(crate) rng: RefCell<StdRng>,
531
532 tracked_alloc_ids: FxHashSet<AllocId>,
535 track_alloc_accesses: bool,
537
538 pub(crate) check_alignment: AlignmentCheck,
540
541 pub(crate) cmpxchg_weak_failure_rate: f64,
543
544 pub(crate) mute_stdout_stderr: bool,
546
547 pub(crate) weak_memory: bool,
549
550 pub(crate) preemption_rate: f64,
552
553 pub(crate) report_progress: Option<u32>,
555 pub(crate) basic_block_count: u64,
557
558 #[cfg(unix)]
560 pub native_lib: Option<(libloading::Library, std::path::PathBuf)>,
561 #[cfg(not(unix))]
562 pub native_lib: Option<!>,
563
564 pub(crate) gc_interval: u32,
566 pub(crate) since_gc: u32,
568
569 pub(crate) num_cpus: u32,
571
572 pub(crate) page_size: u64,
574 pub(crate) stack_addr: u64,
575 pub(crate) stack_size: u64,
576
577 pub(crate) collect_leak_backtraces: bool,
579
580 pub(crate) allocation_spans: RefCell<FxHashMap<AllocId, (Span, Option<Span>)>>,
583
584 const_cache: RefCell<FxHashMap<(mir::Const<'tcx>, usize), OpTy<'tcx>>>,
588
589 pub(crate) symbolic_alignment: RefCell<FxHashMap<AllocId, (Size, Align)>>,
596
597 union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
599
600 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 pub(crate) sb_extern_type_warned: Cell<bool>,
607 #[cfg(unix)]
609 pub(crate) native_call_mem_warned: Cell<bool>,
610 pub(crate) reject_in_isolation_warned: RefCell<FxHashSet<String>>,
612 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 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 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, "aarch64" => {
647 if target.options.vendor.as_ref() == "apple" {
648 16 * 1024
652 } else {
653 4 * 1024
654 }
655 }
656 _ => 4 * 1024,
657 }
658 };
659 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: 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 target_triple = tcx.sess.opts.target_triple.tuple();
717 if env!("TARGET") != target_triple {
719 panic!(
720 "calling external C functions in linked .so file requires host and target to be the same: host={}, target={}",
721 env!("TARGET"),
722 target_triple,
723 );
724 }
725 (
729 unsafe {
730 libloading::Library::new(lib_file_path)
731 .expect("failed to read specified extern shared object file")
732 },
733 lib_file_path.clone(),
734 )
735 }),
736 #[cfg(not(unix))]
737 native_lib: config.native_lib.as_ref().map(|_| {
738 panic!("calling functions from native libraries via FFI is only supported on Unix")
739 }),
740 gc_interval: config.gc_interval,
741 since_gc: 0,
742 num_cpus: config.num_cpus,
743 page_size,
744 stack_addr,
745 stack_size,
746 collect_leak_backtraces: config.collect_leak_backtraces,
747 allocation_spans: RefCell::new(FxHashMap::default()),
748 const_cache: RefCell::new(FxHashMap::default()),
749 symbolic_alignment: RefCell::new(FxHashMap::default()),
750 union_data_ranges: FxHashMap::default(),
751 pthread_mutex_sanity: Cell::new(false),
752 pthread_rwlock_sanity: Cell::new(false),
753 pthread_condvar_sanity: Cell::new(false),
754 sb_extern_type_warned: Cell::new(false),
755 #[cfg(unix)]
756 native_call_mem_warned: Cell::new(false),
757 reject_in_isolation_warned: Default::default(),
758 int2ptr_warned: Default::default(),
759 }
760 }
761
762 pub(crate) fn late_init(
763 ecx: &mut MiriInterpCx<'tcx>,
764 config: &MiriConfig,
765 on_main_stack_empty: StackEmptyCallback<'tcx>,
766 ) -> InterpResult<'tcx> {
767 EnvVars::init(ecx, config)?;
768 MiriMachine::init_extern_statics(ecx)?;
769 ThreadManager::init(ecx, on_main_stack_empty);
770 interp_ok(())
771 }
772
773 pub(crate) fn add_extern_static(ecx: &mut MiriInterpCx<'tcx>, name: &str, ptr: Pointer) {
774 let ptr = ptr.into_pointer_or_addr().unwrap();
776 ecx.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
777 }
778
779 pub(crate) fn communicate(&self) -> bool {
780 self.isolated_op == IsolatedOp::Allow
781 }
782
783 pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
785 let def_id = frame.instance.def_id();
786 def_id.is_local() || self.local_crates.contains(&def_id.krate)
787 }
788
789 pub(crate) fn handle_abnormal_termination(&mut self) {
791 drop(self.profiler.take());
796 }
797
798 pub(crate) fn page_align(&self) -> Align {
799 Align::from_bytes(self.page_size).unwrap()
800 }
801
802 pub(crate) fn allocated_span(&self, alloc_id: AllocId) -> Option<SpanData> {
803 self.allocation_spans
804 .borrow()
805 .get(&alloc_id)
806 .map(|(allocated, _deallocated)| allocated.data())
807 }
808
809 pub(crate) fn deallocated_span(&self, alloc_id: AllocId) -> Option<SpanData> {
810 self.allocation_spans
811 .borrow()
812 .get(&alloc_id)
813 .and_then(|(_allocated, deallocated)| *deallocated)
814 .map(Span::data)
815 }
816}
817
818impl VisitProvenance for MiriMachine<'_> {
819 fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
820 #[rustfmt::skip]
821 let MiriMachine {
822 threads,
823 thread_cpu_affinity: _,
824 sync: _,
825 tls,
826 env_vars,
827 main_fn_ret_place,
828 argc,
829 argv,
830 cmd_line,
831 extern_statics,
832 dirs,
833 borrow_tracker,
834 data_race,
835 alloc_addresses,
836 fds,
837 epoll_interests:_,
838 tcx: _,
839 isolated_op: _,
840 validation: _,
841 clock: _,
842 layouts: _,
843 static_roots: _,
844 profiler: _,
845 string_cache: _,
846 exported_symbols_cache: _,
847 backtrace_style: _,
848 local_crates: _,
849 rng: _,
850 tracked_alloc_ids: _,
851 track_alloc_accesses: _,
852 check_alignment: _,
853 cmpxchg_weak_failure_rate: _,
854 mute_stdout_stderr: _,
855 weak_memory: _,
856 preemption_rate: _,
857 report_progress: _,
858 basic_block_count: _,
859 native_lib: _,
860 gc_interval: _,
861 since_gc: _,
862 num_cpus: _,
863 page_size: _,
864 stack_addr: _,
865 stack_size: _,
866 collect_leak_backtraces: _,
867 allocation_spans: _,
868 const_cache: _,
869 symbolic_alignment: _,
870 union_data_ranges: _,
871 pthread_mutex_sanity: _,
872 pthread_rwlock_sanity: _,
873 pthread_condvar_sanity: _,
874 sb_extern_type_warned: _,
875 #[cfg(unix)]
876 native_call_mem_warned: _,
877 reject_in_isolation_warned: _,
878 int2ptr_warned: _,
879 } = self;
880
881 threads.visit_provenance(visit);
882 tls.visit_provenance(visit);
883 env_vars.visit_provenance(visit);
884 dirs.visit_provenance(visit);
885 fds.visit_provenance(visit);
886 data_race.visit_provenance(visit);
887 borrow_tracker.visit_provenance(visit);
888 alloc_addresses.visit_provenance(visit);
889 main_fn_ret_place.visit_provenance(visit);
890 argc.visit_provenance(visit);
891 argv.visit_provenance(visit);
892 cmd_line.visit_provenance(visit);
893 for ptr in extern_statics.values() {
894 ptr.visit_provenance(visit);
895 }
896 }
897}
898
899pub type MiriInterpCx<'tcx> = InterpCx<'tcx, MiriMachine<'tcx>>;
901
902pub trait MiriInterpCxExt<'tcx> {
904 fn eval_context_ref<'a>(&'a self) -> &'a MiriInterpCx<'tcx>;
905 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriInterpCx<'tcx>;
906}
907impl<'tcx> MiriInterpCxExt<'tcx> for MiriInterpCx<'tcx> {
908 #[inline(always)]
909 fn eval_context_ref(&self) -> &MiriInterpCx<'tcx> {
910 self
911 }
912 #[inline(always)]
913 fn eval_context_mut(&mut self) -> &mut MiriInterpCx<'tcx> {
914 self
915 }
916}
917
918impl<'tcx> Machine<'tcx> for MiriMachine<'tcx> {
920 type MemoryKind = MiriMemoryKind;
921 type ExtraFnVal = DynSym;
922
923 type FrameExtra = FrameExtra<'tcx>;
924 type AllocExtra = AllocExtra<'tcx>;
925
926 type Provenance = Provenance;
927 type ProvenanceExtra = ProvenanceExtra;
928 type Bytes = MiriAllocBytes;
929
930 type MemoryMap =
931 MonoHashMap<AllocId, (MemoryKind, Allocation<Provenance, Self::AllocExtra, Self::Bytes>)>;
932
933 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
934
935 const PANIC_ON_ALLOC_FAIL: bool = false;
936
937 #[inline(always)]
938 fn enforce_alignment(ecx: &MiriInterpCx<'tcx>) -> bool {
939 ecx.machine.check_alignment != AlignmentCheck::None
940 }
941
942 #[inline(always)]
943 fn alignment_check(
944 ecx: &MiriInterpCx<'tcx>,
945 alloc_id: AllocId,
946 alloc_align: Align,
947 alloc_kind: AllocKind,
948 offset: Size,
949 align: Align,
950 ) -> Option<Misalignment> {
951 if ecx.machine.check_alignment != AlignmentCheck::Symbolic {
952 return None;
954 }
955 if alloc_kind != AllocKind::LiveData {
956 return None;
958 }
959 let (promised_offset, promised_align) = ecx
961 .machine
962 .symbolic_alignment
963 .borrow()
964 .get(&alloc_id)
965 .copied()
966 .unwrap_or((Size::ZERO, alloc_align));
967 if promised_align < align {
968 Some(Misalignment { has: promised_align, required: align })
970 } else {
971 let distance = offset.bytes().wrapping_sub(promised_offset.bytes());
973 if distance % align.bytes() == 0 {
975 None
977 } else {
978 let distance_pow2 = 1 << distance.trailing_zeros();
980 Some(Misalignment {
981 has: Align::from_bytes(distance_pow2).unwrap(),
982 required: align,
983 })
984 }
985 }
986 }
987
988 #[inline(always)]
989 fn enforce_validity(ecx: &MiriInterpCx<'tcx>, _layout: TyAndLayout<'tcx>) -> bool {
990 ecx.machine.validation != ValidationMode::No
991 }
992 #[inline(always)]
993 fn enforce_validity_recursively(
994 ecx: &InterpCx<'tcx, Self>,
995 _layout: TyAndLayout<'tcx>,
996 ) -> bool {
997 ecx.machine.validation == ValidationMode::Deep
998 }
999
1000 #[inline(always)]
1001 fn ignore_optional_overflow_checks(ecx: &MiriInterpCx<'tcx>) -> bool {
1002 !ecx.tcx.sess.overflow_checks()
1003 }
1004
1005 fn check_fn_target_features(
1006 ecx: &MiriInterpCx<'tcx>,
1007 instance: ty::Instance<'tcx>,
1008 ) -> InterpResult<'tcx> {
1009 let attrs = ecx.tcx.codegen_fn_attrs(instance.def_id());
1010 if attrs
1011 .target_features
1012 .iter()
1013 .any(|feature| !ecx.tcx.sess.target_features.contains(&feature.name))
1014 {
1015 let unavailable = attrs
1016 .target_features
1017 .iter()
1018 .filter(|&feature| {
1019 !feature.implied && !ecx.tcx.sess.target_features.contains(&feature.name)
1020 })
1021 .fold(String::new(), |mut s, feature| {
1022 if !s.is_empty() {
1023 s.push_str(", ");
1024 }
1025 s.push_str(feature.name.as_str());
1026 s
1027 });
1028 let msg = format!(
1029 "calling a function that requires unavailable target features: {unavailable}"
1030 );
1031 if ecx.tcx.sess.target.is_like_wasm {
1034 throw_machine_stop!(TerminationInfo::Abort(msg));
1035 } else {
1036 throw_ub_format!("{msg}");
1037 }
1038 }
1039 interp_ok(())
1040 }
1041
1042 #[inline(always)]
1043 fn find_mir_or_eval_fn(
1044 ecx: &mut MiriInterpCx<'tcx>,
1045 instance: ty::Instance<'tcx>,
1046 abi: &FnAbi<'tcx, Ty<'tcx>>,
1047 args: &[FnArg<'tcx, Provenance>],
1048 dest: &MPlaceTy<'tcx>,
1049 ret: Option<mir::BasicBlock>,
1050 unwind: mir::UnwindAction,
1051 ) -> InterpResult<'tcx, Option<(&'tcx mir::Body<'tcx>, ty::Instance<'tcx>)>> {
1052 if ecx.tcx.is_foreign_item(instance.def_id()) {
1054 let args = ecx.copy_fn_args(args); let link_name = Symbol::intern(ecx.tcx.symbol_name(instance).name);
1062 return ecx.emulate_foreign_item(link_name, abi, &args, dest, ret, unwind);
1063 }
1064
1065 interp_ok(Some((ecx.load_mir(instance.def, None)?, instance)))
1067 }
1068
1069 #[inline(always)]
1070 fn call_extra_fn(
1071 ecx: &mut MiriInterpCx<'tcx>,
1072 fn_val: DynSym,
1073 abi: &FnAbi<'tcx, Ty<'tcx>>,
1074 args: &[FnArg<'tcx, Provenance>],
1075 dest: &MPlaceTy<'tcx>,
1076 ret: Option<mir::BasicBlock>,
1077 unwind: mir::UnwindAction,
1078 ) -> InterpResult<'tcx> {
1079 let args = ecx.copy_fn_args(args); ecx.emulate_dyn_sym(fn_val, abi, &args, dest, ret, unwind)
1081 }
1082
1083 #[inline(always)]
1084 fn call_intrinsic(
1085 ecx: &mut MiriInterpCx<'tcx>,
1086 instance: ty::Instance<'tcx>,
1087 args: &[OpTy<'tcx>],
1088 dest: &MPlaceTy<'tcx>,
1089 ret: Option<mir::BasicBlock>,
1090 unwind: mir::UnwindAction,
1091 ) -> InterpResult<'tcx, Option<ty::Instance<'tcx>>> {
1092 ecx.call_intrinsic(instance, args, dest, ret, unwind)
1093 }
1094
1095 #[inline(always)]
1096 fn assert_panic(
1097 ecx: &mut MiriInterpCx<'tcx>,
1098 msg: &mir::AssertMessage<'tcx>,
1099 unwind: mir::UnwindAction,
1100 ) -> InterpResult<'tcx> {
1101 ecx.assert_panic(msg, unwind)
1102 }
1103
1104 fn panic_nounwind(ecx: &mut InterpCx<'tcx, Self>, msg: &str) -> InterpResult<'tcx> {
1105 ecx.start_panic_nounwind(msg)
1106 }
1107
1108 fn unwind_terminate(
1109 ecx: &mut InterpCx<'tcx, Self>,
1110 reason: mir::UnwindTerminateReason,
1111 ) -> InterpResult<'tcx> {
1112 let panic = ecx.tcx.lang_items().get(reason.lang_item()).unwrap();
1114 let panic = ty::Instance::mono(ecx.tcx.tcx, panic);
1115 ecx.call_function(
1116 panic,
1117 ExternAbi::Rust,
1118 &[],
1119 None,
1120 StackPopCleanup::Goto { ret: None, unwind: mir::UnwindAction::Unreachable },
1121 )?;
1122 interp_ok(())
1123 }
1124
1125 #[inline(always)]
1126 fn binary_ptr_op(
1127 ecx: &MiriInterpCx<'tcx>,
1128 bin_op: mir::BinOp,
1129 left: &ImmTy<'tcx>,
1130 right: &ImmTy<'tcx>,
1131 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
1132 ecx.binary_ptr_op(bin_op, left, right)
1133 }
1134
1135 #[inline(always)]
1136 fn generate_nan<F1: Float + FloatConvert<F2>, F2: Float>(
1137 ecx: &InterpCx<'tcx, Self>,
1138 inputs: &[F1],
1139 ) -> F2 {
1140 ecx.generate_nan(inputs)
1141 }
1142
1143 #[inline(always)]
1144 fn equal_float_min_max<F: Float>(ecx: &MiriInterpCx<'tcx>, a: F, b: F) -> F {
1145 ecx.equal_float_min_max(a, b)
1146 }
1147
1148 #[inline(always)]
1149 fn ub_checks(ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool> {
1150 interp_ok(ecx.tcx.sess.ub_checks())
1151 }
1152
1153 #[inline(always)]
1154 fn contract_checks(ecx: &InterpCx<'tcx, Self>) -> InterpResult<'tcx, bool> {
1155 interp_ok(ecx.tcx.sess.contract_checks())
1156 }
1157
1158 #[inline(always)]
1159 fn thread_local_static_pointer(
1160 ecx: &mut MiriInterpCx<'tcx>,
1161 def_id: DefId,
1162 ) -> InterpResult<'tcx, StrictPointer> {
1163 ecx.get_or_create_thread_local_alloc(def_id)
1164 }
1165
1166 fn extern_static_pointer(
1167 ecx: &MiriInterpCx<'tcx>,
1168 def_id: DefId,
1169 ) -> InterpResult<'tcx, StrictPointer> {
1170 let link_name = Symbol::intern(ecx.tcx.symbol_name(Instance::mono(*ecx.tcx, def_id)).name);
1171 if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
1172 let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
1176 panic!("extern_statics cannot contain wildcards")
1177 };
1178 let info = ecx.get_alloc_info(alloc_id);
1179 let def_ty = ecx.tcx.type_of(def_id).instantiate_identity();
1180 let extern_decl_layout =
1181 ecx.tcx.layout_of(ecx.typing_env().as_query_input(def_ty)).unwrap();
1182 if extern_decl_layout.size != info.size || extern_decl_layout.align.abi != info.align {
1183 throw_unsup_format!(
1184 "extern static `{link_name}` has been declared as `{krate}::{name}` \
1185 with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
1186 but Miri emulates it via an extern static shim \
1187 with a size of {shim_size} bytes and alignment of {shim_align} bytes",
1188 name = ecx.tcx.def_path_str(def_id),
1189 krate = ecx.tcx.crate_name(def_id.krate),
1190 decl_size = extern_decl_layout.size.bytes(),
1191 decl_align = extern_decl_layout.align.abi.bytes(),
1192 shim_size = info.size.bytes(),
1193 shim_align = info.align.bytes(),
1194 )
1195 }
1196 interp_ok(ptr)
1197 } else {
1198 throw_unsup_format!("extern static `{link_name}` is not supported by Miri",)
1199 }
1200 }
1201
1202 fn init_alloc_extra(
1203 ecx: &MiriInterpCx<'tcx>,
1204 id: AllocId,
1205 kind: MemoryKind,
1206 size: Size,
1207 align: Align,
1208 ) -> InterpResult<'tcx, Self::AllocExtra> {
1209 if ecx.machine.tracked_alloc_ids.contains(&id) {
1210 ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id, size, align, kind));
1211 }
1212
1213 let borrow_tracker = ecx
1214 .machine
1215 .borrow_tracker
1216 .as_ref()
1217 .map(|bt| bt.borrow_mut().new_allocation(id, size, kind, &ecx.machine));
1218
1219 let data_race = ecx.machine.data_race.as_ref().map(|data_race| {
1220 data_race::AllocState::new_allocation(
1221 data_race,
1222 &ecx.machine.threads,
1223 size,
1224 kind,
1225 ecx.machine.current_span(),
1226 )
1227 });
1228 let weak_memory = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation);
1229
1230 let backtrace = if kind.may_leak() || !ecx.machine.collect_leak_backtraces {
1234 None
1235 } else {
1236 Some(ecx.generate_stacktrace())
1237 };
1238
1239 if matches!(kind, MemoryKind::Machine(kind) if kind.should_save_allocation_span()) {
1240 ecx.machine
1241 .allocation_spans
1242 .borrow_mut()
1243 .insert(id, (ecx.machine.current_span(), None));
1244 }
1245
1246 interp_ok(AllocExtra {
1247 borrow_tracker,
1248 data_race,
1249 weak_memory,
1250 backtrace,
1251 sync: FxHashMap::default(),
1252 })
1253 }
1254
1255 fn adjust_alloc_root_pointer(
1256 ecx: &MiriInterpCx<'tcx>,
1257 ptr: interpret::Pointer<CtfeProvenance>,
1258 kind: Option<MemoryKind>,
1259 ) -> InterpResult<'tcx, interpret::Pointer<Provenance>> {
1260 let kind = kind.expect("we set our GLOBAL_KIND so this cannot be None");
1261 let alloc_id = ptr.provenance.alloc_id();
1262 if cfg!(debug_assertions) {
1263 match ecx.tcx.try_get_global_alloc(alloc_id) {
1265 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
1266 panic!("adjust_alloc_root_pointer called on thread-local static")
1267 }
1268 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
1269 panic!("adjust_alloc_root_pointer called on extern static")
1270 }
1271 _ => {}
1272 }
1273 }
1274 let tag = if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
1276 borrow_tracker.borrow_mut().root_ptr_tag(alloc_id, &ecx.machine)
1277 } else {
1278 BorTag::default()
1280 };
1281 ecx.adjust_alloc_root_pointer(ptr, tag, kind)
1282 }
1283
1284 #[inline(always)]
1286 fn ptr_from_addr_cast(ecx: &MiriInterpCx<'tcx>, addr: u64) -> InterpResult<'tcx, Pointer> {
1287 ecx.ptr_from_addr_cast(addr)
1288 }
1289
1290 fn expose_provenance(
1294 ecx: &InterpCx<'tcx, Self>,
1295 provenance: Self::Provenance,
1296 ) -> InterpResult<'tcx> {
1297 match provenance {
1298 Provenance::Concrete { alloc_id, tag } => ecx.expose_ptr(alloc_id, tag),
1299 Provenance::Wildcard => {
1300 interp_ok(())
1303 }
1304 }
1305 }
1306
1307 fn ptr_get_alloc(
1319 ecx: &MiriInterpCx<'tcx>,
1320 ptr: StrictPointer,
1321 size: i64,
1322 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
1323 let rel = ecx.ptr_get_alloc(ptr, size);
1324
1325 rel.map(|(alloc_id, size)| {
1326 let tag = match ptr.provenance {
1327 Provenance::Concrete { tag, .. } => ProvenanceExtra::Concrete(tag),
1328 Provenance::Wildcard => ProvenanceExtra::Wildcard,
1329 };
1330 (alloc_id, size, tag)
1331 })
1332 }
1333
1334 fn adjust_global_allocation<'b>(
1343 ecx: &InterpCx<'tcx, Self>,
1344 id: AllocId,
1345 alloc: &'b Allocation,
1346 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra, Self::Bytes>>>
1347 {
1348 let kind = Self::GLOBAL_KIND.unwrap().into();
1349 let alloc = alloc.adjust_from_tcx(
1350 &ecx.tcx,
1351 |bytes, align| ecx.get_global_alloc_bytes(id, kind, bytes, align),
1352 |ptr| ecx.global_root_pointer(ptr),
1353 )?;
1354 let extra = Self::init_alloc_extra(ecx, id, kind, alloc.size(), alloc.align)?;
1355 interp_ok(Cow::Owned(alloc.with_extra(extra)))
1356 }
1357
1358 #[inline(always)]
1359 fn before_memory_read(
1360 _tcx: TyCtxtAt<'tcx>,
1361 machine: &Self,
1362 alloc_extra: &AllocExtra<'tcx>,
1363 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1364 range: AllocRange,
1365 ) -> InterpResult<'tcx> {
1366 if machine.track_alloc_accesses && machine.tracked_alloc_ids.contains(&alloc_id) {
1367 machine
1368 .emit_diagnostic(NonHaltingDiagnostic::AccessedAlloc(alloc_id, AccessKind::Read));
1369 }
1370 if let Some(data_race) = &alloc_extra.data_race {
1371 data_race.read(alloc_id, range, NaReadType::Read, None, machine)?;
1372 }
1373 if let Some(borrow_tracker) = &alloc_extra.borrow_tracker {
1374 borrow_tracker.before_memory_read(alloc_id, prov_extra, range, machine)?;
1375 }
1376 if let Some(weak_memory) = &alloc_extra.weak_memory {
1377 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1378 }
1379 interp_ok(())
1380 }
1381
1382 #[inline(always)]
1383 fn before_memory_write(
1384 _tcx: TyCtxtAt<'tcx>,
1385 machine: &mut Self,
1386 alloc_extra: &mut AllocExtra<'tcx>,
1387 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1388 range: AllocRange,
1389 ) -> InterpResult<'tcx> {
1390 if machine.track_alloc_accesses && machine.tracked_alloc_ids.contains(&alloc_id) {
1391 machine
1392 .emit_diagnostic(NonHaltingDiagnostic::AccessedAlloc(alloc_id, AccessKind::Write));
1393 }
1394 if let Some(data_race) = &mut alloc_extra.data_race {
1395 data_race.write(alloc_id, range, NaWriteType::Write, None, machine)?;
1396 }
1397 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1398 borrow_tracker.before_memory_write(alloc_id, prov_extra, range, machine)?;
1399 }
1400 if let Some(weak_memory) = &alloc_extra.weak_memory {
1401 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1402 }
1403 interp_ok(())
1404 }
1405
1406 #[inline(always)]
1407 fn before_memory_deallocation(
1408 _tcx: TyCtxtAt<'tcx>,
1409 machine: &mut Self,
1410 alloc_extra: &mut AllocExtra<'tcx>,
1411 (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
1412 size: Size,
1413 align: Align,
1414 kind: MemoryKind,
1415 ) -> InterpResult<'tcx> {
1416 if machine.tracked_alloc_ids.contains(&alloc_id) {
1417 machine.emit_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
1418 }
1419 if let Some(data_race) = &mut alloc_extra.data_race {
1420 data_race.write(
1421 alloc_id,
1422 alloc_range(Size::ZERO, size),
1423 NaWriteType::Deallocate,
1424 None,
1425 machine,
1426 )?;
1427 }
1428 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1429 borrow_tracker.before_memory_deallocation(alloc_id, prove_extra, size, machine)?;
1430 }
1431 if let Some((_, deallocated_at)) = machine.allocation_spans.borrow_mut().get_mut(&alloc_id)
1432 {
1433 *deallocated_at = Some(machine.current_span());
1434 }
1435 machine.free_alloc_id(alloc_id, size, align, kind);
1436 interp_ok(())
1437 }
1438
1439 #[inline(always)]
1440 fn retag_ptr_value(
1441 ecx: &mut InterpCx<'tcx, Self>,
1442 kind: mir::RetagKind,
1443 val: &ImmTy<'tcx>,
1444 ) -> InterpResult<'tcx, ImmTy<'tcx>> {
1445 if ecx.machine.borrow_tracker.is_some() {
1446 ecx.retag_ptr_value(kind, val)
1447 } else {
1448 interp_ok(val.clone())
1449 }
1450 }
1451
1452 #[inline(always)]
1453 fn retag_place_contents(
1454 ecx: &mut InterpCx<'tcx, Self>,
1455 kind: mir::RetagKind,
1456 place: &PlaceTy<'tcx>,
1457 ) -> InterpResult<'tcx> {
1458 if ecx.machine.borrow_tracker.is_some() {
1459 ecx.retag_place_contents(kind, place)?;
1460 }
1461 interp_ok(())
1462 }
1463
1464 fn protect_in_place_function_argument(
1465 ecx: &mut InterpCx<'tcx, Self>,
1466 place: &MPlaceTy<'tcx>,
1467 ) -> InterpResult<'tcx> {
1468 let protected_place = if ecx.machine.borrow_tracker.is_some() {
1471 ecx.protect_place(place)?
1472 } else {
1473 place.clone()
1475 };
1476 ecx.write_uninit(&protected_place)?;
1481 interp_ok(())
1483 }
1484
1485 #[inline(always)]
1486 fn init_frame(
1487 ecx: &mut InterpCx<'tcx, Self>,
1488 frame: Frame<'tcx, Provenance>,
1489 ) -> InterpResult<'tcx, Frame<'tcx, Provenance, FrameExtra<'tcx>>> {
1490 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
1492 let fn_name = frame.instance().to_string();
1493 let entry = ecx.machine.string_cache.entry(fn_name.clone());
1494 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
1495
1496 Some(profiler.start_recording_interval_event_detached(
1497 *name,
1498 measureme::EventId::from_label(*name),
1499 ecx.active_thread().to_u32(),
1500 ))
1501 } else {
1502 None
1503 };
1504
1505 let borrow_tracker = ecx.machine.borrow_tracker.as_ref();
1506
1507 let extra = FrameExtra {
1508 borrow_tracker: borrow_tracker.map(|bt| bt.borrow_mut().new_frame()),
1509 catch_unwind: None,
1510 timing,
1511 is_user_relevant: ecx.machine.is_user_relevant(&frame),
1512 salt: ecx.machine.rng.borrow_mut().random_range(0..ADDRS_PER_ANON_GLOBAL),
1513 data_race: ecx.machine.data_race.as_ref().map(|_| data_race::FrameState::default()),
1514 };
1515
1516 interp_ok(frame.with_extra(extra))
1517 }
1518
1519 fn stack<'a>(
1520 ecx: &'a InterpCx<'tcx, Self>,
1521 ) -> &'a [Frame<'tcx, Self::Provenance, Self::FrameExtra>] {
1522 ecx.active_thread_stack()
1523 }
1524
1525 fn stack_mut<'a>(
1526 ecx: &'a mut InterpCx<'tcx, Self>,
1527 ) -> &'a mut Vec<Frame<'tcx, Self::Provenance, Self::FrameExtra>> {
1528 ecx.active_thread_stack_mut()
1529 }
1530
1531 fn before_terminator(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1532 ecx.machine.basic_block_count += 1u64; ecx.machine.since_gc += 1;
1534 if let Some(report_progress) = ecx.machine.report_progress {
1536 if ecx.machine.basic_block_count % u64::from(report_progress) == 0 {
1537 ecx.emit_diagnostic(NonHaltingDiagnostic::ProgressReport {
1538 block_count: ecx.machine.basic_block_count,
1539 });
1540 }
1541 }
1542
1543 if ecx.machine.gc_interval > 0 && ecx.machine.since_gc >= ecx.machine.gc_interval {
1548 ecx.machine.since_gc = 0;
1549 ecx.run_provenance_gc();
1550 }
1551
1552 ecx.maybe_preempt_active_thread();
1554
1555 ecx.machine.clock.tick();
1557
1558 interp_ok(())
1559 }
1560
1561 #[inline(always)]
1562 fn after_stack_push(ecx: &mut InterpCx<'tcx, Self>) -> InterpResult<'tcx> {
1563 if ecx.frame().extra.is_user_relevant {
1564 let stack_len = ecx.active_thread_stack().len();
1567 ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1);
1568 }
1569 interp_ok(())
1570 }
1571
1572 fn before_stack_pop(
1573 ecx: &InterpCx<'tcx, Self>,
1574 frame: &Frame<'tcx, Self::Provenance, Self::FrameExtra>,
1575 ) -> InterpResult<'tcx> {
1576 if ecx.machine.borrow_tracker.is_some() {
1579 ecx.on_stack_pop(frame)?;
1580 }
1581 info!("Leaving {}", ecx.frame().instance());
1585 interp_ok(())
1586 }
1587
1588 #[inline(always)]
1589 fn after_stack_pop(
1590 ecx: &mut InterpCx<'tcx, Self>,
1591 frame: Frame<'tcx, Provenance, FrameExtra<'tcx>>,
1592 unwinding: bool,
1593 ) -> InterpResult<'tcx, ReturnAction> {
1594 if frame.extra.is_user_relevant {
1595 ecx.active_thread_mut().recompute_top_user_relevant_frame();
1600 }
1601 let res = {
1602 let mut frame = frame;
1604 let timing = frame.extra.timing.take();
1605 let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
1606 if let Some(profiler) = ecx.machine.profiler.as_ref() {
1607 profiler.finish_recording_interval_event(timing.unwrap());
1608 }
1609 res
1610 };
1611 if !ecx.active_thread_stack().is_empty() {
1614 info!("Continuing in {}", ecx.frame().instance());
1615 }
1616 res
1617 }
1618
1619 fn after_local_read(
1620 ecx: &InterpCx<'tcx, Self>,
1621 frame: &Frame<'tcx, Provenance, FrameExtra<'tcx>>,
1622 local: mir::Local,
1623 ) -> InterpResult<'tcx> {
1624 if let Some(data_race) = &frame.extra.data_race {
1625 data_race.local_read(local, &ecx.machine);
1626 }
1627 interp_ok(())
1628 }
1629
1630 fn after_local_write(
1631 ecx: &mut InterpCx<'tcx, Self>,
1632 local: mir::Local,
1633 storage_live: bool,
1634 ) -> InterpResult<'tcx> {
1635 if let Some(data_race) = &ecx.frame().extra.data_race {
1636 data_race.local_write(local, storage_live, &ecx.machine);
1637 }
1638 interp_ok(())
1639 }
1640
1641 fn after_local_moved_to_memory(
1642 ecx: &mut InterpCx<'tcx, Self>,
1643 local: mir::Local,
1644 mplace: &MPlaceTy<'tcx>,
1645 ) -> InterpResult<'tcx> {
1646 let Some(Provenance::Concrete { alloc_id, .. }) = mplace.ptr().provenance else {
1647 panic!("after_local_allocated should only be called on fresh allocations");
1648 };
1649 let local_decl = &ecx.frame().body().local_decls[local];
1651 let span = local_decl.source_info.span;
1652 ecx.machine.allocation_spans.borrow_mut().insert(alloc_id, (span, None));
1653 let (alloc_info, machine) = ecx.get_alloc_extra_mut(alloc_id)?;
1655 if let Some(data_race) =
1656 &machine.threads.active_thread_stack().last().unwrap().extra.data_race
1657 {
1658 data_race.local_moved_to_memory(local, alloc_info.data_race.as_mut().unwrap(), machine);
1659 }
1660 interp_ok(())
1661 }
1662
1663 fn eval_mir_constant<F>(
1664 ecx: &InterpCx<'tcx, Self>,
1665 val: mir::Const<'tcx>,
1666 span: Span,
1667 layout: Option<TyAndLayout<'tcx>>,
1668 eval: F,
1669 ) -> InterpResult<'tcx, OpTy<'tcx>>
1670 where
1671 F: Fn(
1672 &InterpCx<'tcx, Self>,
1673 mir::Const<'tcx>,
1674 Span,
1675 Option<TyAndLayout<'tcx>>,
1676 ) -> InterpResult<'tcx, OpTy<'tcx>>,
1677 {
1678 let frame = ecx.active_thread_stack().last().unwrap();
1679 let mut cache = ecx.machine.const_cache.borrow_mut();
1680 match cache.entry((val, frame.extra.salt)) {
1681 Entry::Vacant(ve) => {
1682 let op = eval(ecx, val, span, layout)?;
1683 ve.insert(op.clone());
1684 interp_ok(op)
1685 }
1686 Entry::Occupied(oe) => interp_ok(oe.get().clone()),
1687 }
1688 }
1689
1690 fn get_global_alloc_salt(
1691 ecx: &InterpCx<'tcx, Self>,
1692 instance: Option<ty::Instance<'tcx>>,
1693 ) -> usize {
1694 let unique = if let Some(instance) = instance {
1695 let is_generic = instance
1708 .args
1709 .into_iter()
1710 .any(|kind| !matches!(kind.unpack(), ty::GenericArgKind::Lifetime(_)));
1711 let can_be_inlined = matches!(
1712 ecx.tcx.sess.opts.unstable_opts.cross_crate_inline_threshold,
1713 InliningThreshold::Always
1714 ) || !matches!(
1715 ecx.tcx.codegen_fn_attrs(instance.def_id()).inline,
1716 InlineAttr::Never
1717 );
1718 !is_generic && !can_be_inlined
1719 } else {
1720 false
1722 };
1723 if unique {
1725 CTFE_ALLOC_SALT
1726 } else {
1727 ecx.machine.rng.borrow_mut().random_range(0..ADDRS_PER_ANON_GLOBAL)
1728 }
1729 }
1730
1731 fn cached_union_data_range<'e>(
1732 ecx: &'e mut InterpCx<'tcx, Self>,
1733 ty: Ty<'tcx>,
1734 compute_range: impl FnOnce() -> RangeSet,
1735 ) -> Cow<'e, RangeSet> {
1736 Cow::Borrowed(ecx.machine.union_data_ranges.entry(ty).or_insert_with(compute_range))
1737 }
1738}
1739
1740pub trait MachineCallback<'tcx, T>: VisitProvenance {
1742 fn call(
1744 self: Box<Self>,
1745 ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
1746 arg: T,
1747 ) -> InterpResult<'tcx>;
1748}
1749
1750pub type DynMachineCallback<'tcx, T> = Box<dyn MachineCallback<'tcx, T> + 'tcx>;
1752
1753#[macro_export]
1770macro_rules! callback {
1771 (@capture<$tcx:lifetime $(,)? $($lft:lifetime),*>
1772 { $($name:ident: $type:ty),* $(,)? }
1773 |$this:ident, $arg:ident: $arg_ty:ty| $body:expr $(,)?) => {{
1774 struct Callback<$tcx, $($lft),*> {
1775 $($name: $type,)*
1776 _phantom: std::marker::PhantomData<&$tcx ()>,
1777 }
1778
1779 impl<$tcx, $($lft),*> VisitProvenance for Callback<$tcx, $($lft),*> {
1780 fn visit_provenance(&self, _visit: &mut VisitWith<'_>) {
1781 $(
1782 self.$name.visit_provenance(_visit);
1783 )*
1784 }
1785 }
1786
1787 impl<$tcx, $($lft),*> MachineCallback<$tcx, $arg_ty> for Callback<$tcx, $($lft),*> {
1788 fn call(
1789 self: Box<Self>,
1790 $this: &mut MiriInterpCx<$tcx>,
1791 $arg: $arg_ty
1792 ) -> InterpResult<$tcx> {
1793 #[allow(unused_variables)]
1794 let Callback { $($name,)* _phantom } = *self;
1795 $body
1796 }
1797 }
1798
1799 Box::new(Callback {
1800 $($name,)*
1801 _phantom: std::marker::PhantomData
1802 })
1803 }};
1804}