1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
8 use rand::rngs::StdRng;
11 use rustc_ast::ast::Mutability;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_data_structures::static_assert_size;
19 layout::{LayoutCx, LayoutError, LayoutOf, TyAndLayout},
20 Instance, Ty, TyCtxt, TypeAndMut,
23 use rustc_span::def_id::{CrateNum, DefId};
24 use rustc_span::Symbol;
25 use rustc_target::abi::Size;
26 use rustc_target::spec::abi::Abi;
29 concurrency::{data_race, weak_memory},
30 shims::unix::FileHandler,
34 /// Extra data stored with each stack frame
35 pub struct FrameExtra<'tcx> {
36 /// Extra data for Stacked Borrows.
37 pub borrow_tracker: Option<borrow_tracker::FrameState>,
39 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
40 /// called by `try`). When this frame is popped during unwinding a panic,
41 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
42 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
44 /// If `measureme` profiling is enabled, holds timing information
45 /// for the start of this frame. When we finish executing this frame,
46 /// we use this to register a completed event with `measureme`.
47 pub timing: Option<measureme::DetachedTiming>,
49 /// Indicates whether a `Frame` is part of a workspace-local crate and is also not
50 /// `#[track_caller]`. We compute this once on creation and store the result, as an
52 /// This is used by `MiriMachine::current_span` and `MiriMachine::caller_span`
53 pub is_user_relevant: bool,
56 impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 // Omitting `timing`, it does not support `Debug`.
59 let FrameExtra { borrow_tracker, catch_unwind, timing: _, is_user_relevant: _ } = self;
60 f.debug_struct("FrameData")
61 .field("borrow_tracker", borrow_tracker)
62 .field("catch_unwind", catch_unwind)
67 impl VisitTags for FrameExtra<'_> {
68 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
69 let FrameExtra { catch_unwind, borrow_tracker, timing: _, is_user_relevant: _ } = self;
71 catch_unwind.visit_tags(visit);
72 borrow_tracker.visit_tags(visit);
76 /// Extra memory kinds
77 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
78 pub enum MiriMemoryKind {
79 /// `__rust_alloc` memory.
81 /// `miri_alloc` memory.
85 /// Windows `HeapAlloc` memory.
87 /// Memory for args, errno, and other parts of the machine-managed environment.
88 /// This memory may leak.
90 /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
91 /// because we clean it up and leak-check it.
93 /// Globals copied from `tcx`.
94 /// This memory may leak.
96 /// Memory for extern statics.
97 /// This memory may leak.
99 /// Memory for thread-local statics.
100 /// This memory may leak.
104 impl From<MiriMemoryKind> for MemoryKind<MiriMemoryKind> {
106 fn from(kind: MiriMemoryKind) -> MemoryKind<MiriMemoryKind> {
107 MemoryKind::Machine(kind)
111 impl MayLeak for MiriMemoryKind {
113 fn may_leak(self) -> bool {
114 use self::MiriMemoryKind::*;
116 Rust | Miri | C | WinHeap | Runtime => false,
117 Machine | Global | ExternStatic | Tls => true,
122 impl fmt::Display for MiriMemoryKind {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 use self::MiriMemoryKind::*;
126 Rust => write!(f, "Rust heap"),
127 Miri => write!(f, "Miri bare-metal heap"),
128 C => write!(f, "C heap"),
129 WinHeap => write!(f, "Windows heap"),
130 Machine => write!(f, "machine-managed memory"),
131 Runtime => write!(f, "language runtime memory"),
132 Global => write!(f, "global (static or const)"),
133 ExternStatic => write!(f, "extern static"),
134 Tls => write!(f, "thread-local static"),
139 /// Pointer provenance.
140 #[derive(Clone, Copy)]
141 pub enum Provenance {
144 /// Stacked Borrows tag.
150 // This needs to be `Eq`+`Hash` because the `Machine` trait needs that because validity checking
151 // *might* be recursive and then it has to track which places have already been visited.
152 // However, comparing provenance is meaningless, since `Wildcard` might be any provenance -- and of
153 // course we don't actually do recursive checking.
154 // We could change `RefTracking` to strip provenance for its `seen` set but that type is generic so that is quite annoying.
155 // Instead owe add the required instances but make them panic.
156 impl PartialEq for Provenance {
157 fn eq(&self, _other: &Self) -> bool {
158 panic!("Provenance must not be compared")
161 impl Eq for Provenance {}
162 impl std::hash::Hash for Provenance {
163 fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
164 panic!("Provenance must not be hashed")
168 /// The "extra" information a pointer has over a regular AllocId.
169 #[derive(Copy, Clone, PartialEq)]
170 pub enum ProvenanceExtra {
175 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
176 static_assert_size!(Pointer<Provenance>, 24);
177 // FIXME: this would with in 24bytes but layout optimizations are not smart enough
178 // #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
179 //static_assert_size!(Pointer<Option<Provenance>>, 24);
180 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
181 static_assert_size!(Scalar<Provenance>, 32);
183 impl fmt::Debug for Provenance {
184 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 Provenance::Concrete { alloc_id, tag } => {
187 // Forward `alternate` flag to `alloc_id` printing.
189 write!(f, "[{alloc_id:#?}]")?;
191 write!(f, "[{alloc_id:?}]")?;
193 // Print Stacked Borrows tag.
194 write!(f, "{tag:?}")?;
196 Provenance::Wildcard => {
197 write!(f, "[wildcard]")?;
204 impl interpret::Provenance for Provenance {
205 /// We use absolute addresses in the `offset` of a `Pointer<Provenance>`.
206 const OFFSET_IS_ADDR: bool = true;
208 fn get_alloc_id(self) -> Option<AllocId> {
210 Provenance::Concrete { alloc_id, .. } => Some(alloc_id),
211 Provenance::Wildcard => None,
215 fn join(left: Option<Self>, right: Option<Self>) -> Option<Self> {
216 match (left, right) {
217 // If both are the *same* concrete tag, that is the result.
219 Some(Provenance::Concrete { alloc_id: left_alloc, tag: left_tag }),
220 Some(Provenance::Concrete { alloc_id: right_alloc, tag: right_tag }),
221 ) if left_alloc == right_alloc && left_tag == right_tag => left,
222 // If one side is a wildcard, the best possible outcome is that it is equal to the other
223 // one, and we use that.
224 (Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o,
225 // Otherwise, fall back to `None`.
231 impl fmt::Debug for ProvenanceExtra {
232 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 ProvenanceExtra::Concrete(pid) => write!(f, "{pid:?}"),
235 ProvenanceExtra::Wildcard => write!(f, "<wildcard>"),
240 impl ProvenanceExtra {
241 pub fn and_then<T>(self, f: impl FnOnce(BorTag) -> Option<T>) -> Option<T> {
243 ProvenanceExtra::Concrete(pid) => f(pid),
244 ProvenanceExtra::Wildcard => None,
249 /// Extra per-allocation data
250 #[derive(Debug, Clone)]
251 pub struct AllocExtra {
252 /// Global state of the borrow tracker, if enabled.
253 pub borrow_tracker: Option<borrow_tracker::AllocState>,
254 /// Data race detection via the use of a vector-clock,
255 /// this is only added if it is enabled.
256 pub data_race: Option<data_race::AllocState>,
257 /// Weak memory emulation via the use of store buffers,
258 /// this is only added if it is enabled.
259 pub weak_memory: Option<weak_memory::AllocState>,
262 impl VisitTags for AllocExtra {
263 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
264 let AllocExtra { borrow_tracker, data_race, weak_memory } = self;
266 borrow_tracker.visit_tags(visit);
267 data_race.visit_tags(visit);
268 weak_memory.visit_tags(visit);
272 /// Precomputed layouts of primitive types
273 pub struct PrimitiveLayouts<'tcx> {
274 pub unit: TyAndLayout<'tcx>,
275 pub i8: TyAndLayout<'tcx>,
276 pub i16: TyAndLayout<'tcx>,
277 pub i32: TyAndLayout<'tcx>,
278 pub i64: TyAndLayout<'tcx>,
279 pub i128: TyAndLayout<'tcx>,
280 pub isize: TyAndLayout<'tcx>,
281 pub u8: TyAndLayout<'tcx>,
282 pub u16: TyAndLayout<'tcx>,
283 pub u32: TyAndLayout<'tcx>,
284 pub u64: TyAndLayout<'tcx>,
285 pub u128: TyAndLayout<'tcx>,
286 pub usize: TyAndLayout<'tcx>,
287 pub bool: TyAndLayout<'tcx>,
288 pub mut_raw_ptr: TyAndLayout<'tcx>, // *mut ()
289 pub const_raw_ptr: TyAndLayout<'tcx>, // *const ()
292 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
293 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
294 let tcx = layout_cx.tcx;
295 let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
296 let const_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Not });
298 unit: layout_cx.layout_of(tcx.mk_unit())?,
299 i8: layout_cx.layout_of(tcx.types.i8)?,
300 i16: layout_cx.layout_of(tcx.types.i16)?,
301 i32: layout_cx.layout_of(tcx.types.i32)?,
302 i64: layout_cx.layout_of(tcx.types.i64)?,
303 i128: layout_cx.layout_of(tcx.types.i128)?,
304 isize: layout_cx.layout_of(tcx.types.isize)?,
305 u8: layout_cx.layout_of(tcx.types.u8)?,
306 u16: layout_cx.layout_of(tcx.types.u16)?,
307 u32: layout_cx.layout_of(tcx.types.u32)?,
308 u64: layout_cx.layout_of(tcx.types.u64)?,
309 u128: layout_cx.layout_of(tcx.types.u128)?,
310 usize: layout_cx.layout_of(tcx.types.usize)?,
311 bool: layout_cx.layout_of(tcx.types.bool)?,
312 mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
313 const_raw_ptr: layout_cx.layout_of(const_raw_ptr)?,
317 pub fn uint(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
320 16 => Some(self.u16),
321 32 => Some(self.u32),
322 64 => Some(self.u64),
323 128 => Some(self.u128),
328 pub fn int(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
331 16 => Some(self.i16),
332 32 => Some(self.i32),
333 64 => Some(self.i64),
334 128 => Some(self.i128),
340 /// The machine itself.
342 /// If you add anything here that stores machine values, remember to update
343 /// `visit_all_machine_values`!
344 pub struct MiriMachine<'mir, 'tcx> {
345 // We carry a copy of the global `TyCtxt` for convenience, so methods taking just `&Evaluator` have `tcx` access.
346 pub tcx: TyCtxt<'tcx>,
348 /// Global data for borrow tracking.
349 pub borrow_tracker: Option<borrow_tracker::GlobalState>,
351 /// Data race detector global data.
352 pub data_race: Option<data_race::GlobalState>,
354 /// Ptr-int-cast module global data.
355 pub intptrcast: intptrcast::GlobalState,
357 /// Environment variables set by `setenv`.
358 /// Miri does not expose env vars from the host to the emulated program.
359 pub(crate) env_vars: EnvVars<'tcx>,
361 /// Return place of the main function.
362 pub(crate) main_fn_ret_place: Option<MemPlace<Provenance>>,
364 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
365 /// These are *pointers* to argc/argv because macOS.
366 /// We also need the full command line as one string because of Windows.
367 pub(crate) argc: Option<MemPlace<Provenance>>,
368 pub(crate) argv: Option<MemPlace<Provenance>>,
369 pub(crate) cmd_line: Option<MemPlace<Provenance>>,
372 pub(crate) tls: TlsData<'tcx>,
374 /// What should Miri do when an op requires communicating with the host,
375 /// such as accessing host env vars, random number generation, and
376 /// file system access.
377 pub(crate) isolated_op: IsolatedOp,
379 /// Whether to enforce the validity invariant.
380 pub(crate) validate: bool,
382 /// Whether to enforce [ABI](Abi) of function calls.
383 pub(crate) enforce_abi: bool,
385 /// The table of file descriptors.
386 pub(crate) file_handler: shims::unix::FileHandler,
387 /// The table of directory descriptors.
388 pub(crate) dir_handler: shims::unix::DirHandler,
390 /// This machine's monotone clock.
391 pub(crate) clock: Clock,
393 /// The set of threads.
394 pub(crate) threads: ThreadManager<'mir, 'tcx>,
396 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
397 pub(crate) layouts: PrimitiveLayouts<'tcx>,
399 /// Allocations that are considered roots of static memory (that may leak).
400 pub(crate) static_roots: Vec<AllocId>,
402 /// The `measureme` profiler used to record timing information about
403 /// the emulated program.
404 profiler: Option<measureme::Profiler>,
405 /// Used with `profiler` to cache the `StringId`s for event names
406 /// uesd with `measureme`.
407 string_cache: FxHashMap<String, measureme::StringId>,
409 /// Cache of `Instance` exported under the given `Symbol` name.
410 /// `None` means no `Instance` exported under the given name is found.
411 pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
413 /// Whether to raise a panic in the context of the evaluated process when unsupported
414 /// functionality is encountered. If `false`, an error is propagated in the Miri application context
415 /// instead (default behavior)
416 pub(crate) panic_on_unsupported: bool,
418 /// Equivalent setting as RUST_BACKTRACE on encountering an error.
419 pub(crate) backtrace_style: BacktraceStyle,
421 /// Crates which are considered local for the purposes of error reporting.
422 pub(crate) local_crates: Vec<CrateNum>,
424 /// Mapping extern static names to their base pointer.
425 extern_statics: FxHashMap<Symbol, Pointer<Provenance>>,
427 /// The random number generator used for resolving non-determinism.
428 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
429 pub(crate) rng: RefCell<StdRng>,
431 /// The allocation IDs to report when they are being allocated
432 /// (helps for debugging memory leaks and use after free bugs).
433 tracked_alloc_ids: FxHashSet<AllocId>,
435 /// Controls whether alignment of memory accesses is being checked.
436 pub(crate) check_alignment: AlignmentCheck,
438 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
439 pub(crate) cmpxchg_weak_failure_rate: f64,
441 /// Corresponds to -Zmiri-mute-stdout-stderr and doesn't write the output but acts as if it succeeded.
442 pub(crate) mute_stdout_stderr: bool,
444 /// Whether weak memory emulation is enabled
445 pub(crate) weak_memory: bool,
447 /// The probability of the active thread being preempted at the end of each basic block.
448 pub(crate) preemption_rate: f64,
450 /// If `Some`, we will report the current stack every N basic blocks.
451 pub(crate) report_progress: Option<u32>,
452 // The total number of blocks that have been executed.
453 pub(crate) basic_block_count: u64,
455 /// Handle of the optional shared object file for external functions.
456 #[cfg(target_os = "linux")]
457 pub external_so_lib: Option<(libloading::Library, std::path::PathBuf)>,
458 #[cfg(not(target_os = "linux"))]
459 pub external_so_lib: Option<!>,
461 /// Run a garbage collector for BorTags every N basic blocks.
462 pub(crate) gc_interval: u32,
463 /// The number of blocks that passed since the last BorTag GC pass.
464 pub(crate) since_gc: u32,
465 /// The number of CPUs to be reported by miri.
466 pub(crate) num_cpus: u32,
467 /// Determines Miri's page size and associated values
468 pub(crate) page_size: u64,
469 pub(crate) stack_addr: u64,
470 pub(crate) stack_size: u64,
473 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
474 pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
475 let local_crates = helpers::get_local_crates(layout_cx.tcx);
477 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
478 let profiler = config.measureme_out.as_ref().map(|out| {
479 measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
481 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
482 let borrow_tracker = config.borrow_tracker.map(|bt| bt.instanciate_global_state(config));
483 let data_race = config.data_race_detector.then(|| data_race::GlobalState::new(config));
484 let page_size = if let Some(page_size) = config.page_size {
487 let target = &layout_cx.tcx.sess.target;
488 match target.arch.as_ref() {
489 "wasm32" | "wasm64" => 64 * 1024, // https://webassembly.github.io/spec/core/exec/runtime.html#memory-instances
491 if target.options.vendor.as_ref() == "apple" {
492 // No "definitive" source, but see:
493 // https://www.wwdcnotes.com/notes/wwdc20/10214/
494 // https://github.com/ziglang/zig/issues/11308 etc.
502 let stack_addr = page_size * 32;
503 let stack_size = page_size * 16;
508 intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config, stack_addr)),
509 // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
510 env_vars: EnvVars::default(),
511 main_fn_ret_place: None,
515 tls: TlsData::default(),
516 isolated_op: config.isolated_op,
517 validate: config.validate,
518 enforce_abi: config.check_abi,
519 file_handler: FileHandler::new(config.mute_stdout_stderr),
520 dir_handler: Default::default(),
522 threads: ThreadManager::default(),
523 static_roots: Vec::new(),
525 string_cache: Default::default(),
526 exported_symbols_cache: FxHashMap::default(),
527 panic_on_unsupported: config.panic_on_unsupported,
528 backtrace_style: config.backtrace_style,
530 extern_statics: FxHashMap::default(),
531 rng: RefCell::new(rng),
532 tracked_alloc_ids: config.tracked_alloc_ids.clone(),
533 check_alignment: config.check_alignment,
534 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
535 mute_stdout_stderr: config.mute_stdout_stderr,
536 weak_memory: config.weak_memory_emulation,
537 preemption_rate: config.preemption_rate,
538 report_progress: config.report_progress,
539 basic_block_count: 0,
540 clock: Clock::new(config.isolated_op == IsolatedOp::Allow),
541 #[cfg(target_os = "linux")]
542 external_so_lib: config.external_so_file.as_ref().map(|lib_file_path| {
543 let target_triple = layout_cx.tcx.sess.opts.target_triple.triple();
544 // Check if host target == the session target.
545 if env!("TARGET") != target_triple {
547 "calling external C functions in linked .so file requires host and target to be the same: host={}, target={}",
552 // Note: it is the user's responsibility to provide a correct SO file.
553 // WATCH OUT: If an invalid/incorrect SO file is specified, this can cause
554 // undefined behaviour in Miri itself!
557 libloading::Library::new(lib_file_path)
558 .expect("failed to read specified extern shared object file")
560 lib_file_path.clone(),
563 #[cfg(not(target_os = "linux"))]
564 external_so_lib: config.external_so_file.as_ref().map(|_| {
565 panic!("loading external .so files is only supported on Linux")
567 gc_interval: config.gc_interval,
569 num_cpus: config.num_cpus,
576 pub(crate) fn late_init(
577 this: &mut MiriInterpCx<'mir, 'tcx>,
579 on_main_stack_empty: StackEmptyCallback<'mir, 'tcx>,
580 ) -> InterpResult<'tcx> {
581 EnvVars::init(this, config)?;
582 MiriMachine::init_extern_statics(this)?;
583 ThreadManager::init(this, on_main_stack_empty);
587 fn add_extern_static(
588 this: &mut MiriInterpCx<'mir, 'tcx>,
590 ptr: Pointer<Option<Provenance>>,
592 // This got just allocated, so there definitely is a pointer here.
593 let ptr = ptr.into_pointer_or_addr().unwrap();
594 this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
597 fn alloc_extern_static(
598 this: &mut MiriInterpCx<'mir, 'tcx>,
600 val: ImmTy<'tcx, Provenance>,
601 ) -> InterpResult<'tcx> {
602 let place = this.allocate(val.layout, MiriMemoryKind::ExternStatic.into())?;
603 this.write_immediate(*val, &place.into())?;
604 Self::add_extern_static(this, name, place.ptr);
608 /// Sets up the "extern statics" for this machine.
609 fn init_extern_statics(this: &mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx> {
610 match this.tcx.sess.target.os.as_ref() {
613 Self::add_extern_static(
616 this.machine.env_vars.environ.unwrap().ptr,
618 // A couple zero-initialized pointer-sized extern statics.
619 // Most of them are for weak symbols, which we all set to null (indicating that the
620 // symbol is not supported, and triggering fallback code which ends up calling a
621 // syscall that we do support).
622 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"]
624 let val = ImmTy::from_int(0, this.machine.layouts.usize);
625 Self::alloc_extern_static(this, name, val)?;
630 Self::add_extern_static(
633 this.machine.env_vars.environ.unwrap().ptr,
638 let layout = this.machine.layouts.const_raw_ptr;
639 let dlsym = Dlsym::from_str("signal".as_bytes(), &this.tcx.sess.target.os)?
640 .expect("`signal` must be an actual dlsym on android");
641 let ptr = this.create_fn_alloc_ptr(FnVal::Other(dlsym));
642 let val = ImmTy::from_scalar(Scalar::from_pointer(ptr, this), layout);
643 Self::alloc_extern_static(this, "signal", val)?;
644 // A couple zero-initialized pointer-sized extern statics.
645 // Most of them are for weak symbols, which we all set to null (indicating that the
646 // symbol is not supported, and triggering fallback code.)
647 for name in &["bsd_signal"] {
648 let val = ImmTy::from_int(0, this.machine.layouts.usize);
649 Self::alloc_extern_static(this, name, val)?;
654 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
655 let val = ImmTy::from_int(0, this.machine.layouts.u8);
656 Self::alloc_extern_static(this, "_tls_used", val)?;
658 _ => {} // No "extern statics" supported on this target
663 pub(crate) fn communicate(&self) -> bool {
664 self.isolated_op == IsolatedOp::Allow
667 /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
668 pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
669 let def_id = frame.instance.def_id();
670 def_id.is_local() || self.local_crates.contains(&def_id.krate)
674 impl VisitTags for MiriMachine<'_, '_> {
675 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
700 exported_symbols_cache: _,
701 panic_on_unsupported: _,
705 tracked_alloc_ids: _,
707 cmpxchg_weak_failure_rate: _,
708 mute_stdout_stderr: _,
712 basic_block_count: _,
722 threads.visit_tags(visit);
723 tls.visit_tags(visit);
724 env_vars.visit_tags(visit);
725 dir_handler.visit_tags(visit);
726 file_handler.visit_tags(visit);
727 data_race.visit_tags(visit);
728 borrow_tracker.visit_tags(visit);
729 intptrcast.visit_tags(visit);
730 main_fn_ret_place.visit_tags(visit);
731 argc.visit_tags(visit);
732 argv.visit_tags(visit);
733 cmd_line.visit_tags(visit);
734 for ptr in extern_statics.values() {
735 ptr.visit_tags(visit);
740 /// A rustc InterpCx for Miri.
741 pub type MiriInterpCx<'mir, 'tcx> = InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>;
743 /// A little trait that's useful to be inherited by extension traits.
744 pub trait MiriInterpCxExt<'mir, 'tcx> {
745 fn eval_context_ref<'a>(&'a self) -> &'a MiriInterpCx<'mir, 'tcx>;
746 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriInterpCx<'mir, 'tcx>;
748 impl<'mir, 'tcx> MiriInterpCxExt<'mir, 'tcx> for MiriInterpCx<'mir, 'tcx> {
750 fn eval_context_ref(&self) -> &MiriInterpCx<'mir, 'tcx> {
754 fn eval_context_mut(&mut self) -> &mut MiriInterpCx<'mir, 'tcx> {
759 /// Machine hook implementations.
760 impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
761 type MemoryKind = MiriMemoryKind;
762 type ExtraFnVal = Dlsym;
764 type FrameExtra = FrameExtra<'tcx>;
765 type AllocExtra = AllocExtra;
767 type Provenance = Provenance;
768 type ProvenanceExtra = ProvenanceExtra;
770 type MemoryMap = MonoHashMap<
772 (MemoryKind<MiriMemoryKind>, Allocation<Provenance, Self::AllocExtra>),
775 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
777 const PANIC_ON_ALLOC_FAIL: bool = false;
780 fn enforce_alignment(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
781 ecx.machine.check_alignment != AlignmentCheck::None
785 fn use_addr_for_alignment_check(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
786 ecx.machine.check_alignment == AlignmentCheck::Int
790 fn enforce_validity(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
795 fn enforce_abi(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
796 ecx.machine.enforce_abi
800 fn checked_binop_checks_overflow(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
801 ecx.tcx.sess.overflow_checks()
805 fn find_mir_or_eval_fn(
806 ecx: &mut MiriInterpCx<'mir, 'tcx>,
807 instance: ty::Instance<'tcx>,
809 args: &[OpTy<'tcx, Provenance>],
810 dest: &PlaceTy<'tcx, Provenance>,
811 ret: Option<mir::BasicBlock>,
812 unwind: StackPopUnwind,
813 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
814 ecx.find_mir_or_eval_fn(instance, abi, args, dest, ret, unwind)
819 ecx: &mut MiriInterpCx<'mir, 'tcx>,
822 args: &[OpTy<'tcx, Provenance>],
823 dest: &PlaceTy<'tcx, Provenance>,
824 ret: Option<mir::BasicBlock>,
825 _unwind: StackPopUnwind,
826 ) -> InterpResult<'tcx> {
827 ecx.call_dlsym(fn_val, abi, args, dest, ret)
832 ecx: &mut MiriInterpCx<'mir, 'tcx>,
833 instance: ty::Instance<'tcx>,
834 args: &[OpTy<'tcx, Provenance>],
835 dest: &PlaceTy<'tcx, Provenance>,
836 ret: Option<mir::BasicBlock>,
837 unwind: StackPopUnwind,
838 ) -> InterpResult<'tcx> {
839 ecx.call_intrinsic(instance, args, dest, ret, unwind)
844 ecx: &mut MiriInterpCx<'mir, 'tcx>,
845 msg: &mir::AssertMessage<'tcx>,
846 unwind: Option<mir::BasicBlock>,
847 ) -> InterpResult<'tcx> {
848 ecx.assert_panic(msg, unwind)
852 fn abort(_ecx: &mut MiriInterpCx<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
853 throw_machine_stop!(TerminationInfo::Abort(msg))
858 ecx: &MiriInterpCx<'mir, 'tcx>,
860 left: &ImmTy<'tcx, Provenance>,
861 right: &ImmTy<'tcx, Provenance>,
862 ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, Ty<'tcx>)> {
863 ecx.binary_ptr_op(bin_op, left, right)
866 fn thread_local_static_base_pointer(
867 ecx: &mut MiriInterpCx<'mir, 'tcx>,
869 ) -> InterpResult<'tcx, Pointer<Provenance>> {
870 ecx.get_or_create_thread_local_alloc(def_id)
873 fn extern_static_base_pointer(
874 ecx: &MiriInterpCx<'mir, 'tcx>,
876 ) -> InterpResult<'tcx, Pointer<Provenance>> {
877 let link_name = ecx.item_link_name(def_id);
878 if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
879 // Various parts of the engine rely on `get_alloc_info` for size and alignment
880 // information. That uses the type information of this static.
881 // Make sure it matches the Miri allocation for this.
882 let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
883 panic!("extern_statics cannot contain wildcards")
885 let (shim_size, shim_align, _kind) = ecx.get_alloc_info(alloc_id);
886 let extern_decl_layout =
887 ecx.tcx.layout_of(ty::ParamEnv::empty().and(ecx.tcx.type_of(def_id))).unwrap();
888 if extern_decl_layout.size != shim_size || extern_decl_layout.align.abi != shim_align {
890 "`extern` static `{name}` from crate `{krate}` has been declared \
891 with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
892 but Miri emulates it via an extern static shim \
893 with a size of {shim_size} bytes and alignment of {shim_align} bytes",
894 name = ecx.tcx.def_path_str(def_id),
895 krate = ecx.tcx.crate_name(def_id.krate),
896 decl_size = extern_decl_layout.size.bytes(),
897 decl_align = extern_decl_layout.align.abi.bytes(),
898 shim_size = shim_size.bytes(),
899 shim_align = shim_align.bytes(),
905 "`extern` static `{name}` from crate `{krate}` is not supported by Miri",
906 name = ecx.tcx.def_path_str(def_id),
907 krate = ecx.tcx.crate_name(def_id.krate),
912 fn adjust_allocation<'b>(
913 ecx: &MiriInterpCx<'mir, 'tcx>,
915 alloc: Cow<'b, Allocation>,
916 kind: Option<MemoryKind<Self::MemoryKind>>,
917 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>> {
918 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
919 if ecx.machine.tracked_alloc_ids.contains(&id) {
920 ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(
928 let alloc = alloc.into_owned();
929 let borrow_tracker = ecx
933 .map(|bt| bt.borrow_mut().new_allocation(id, alloc.size(), kind, &ecx.machine));
935 let race_alloc = ecx.machine.data_race.as_ref().map(|data_race| {
936 data_race::AllocState::new_allocation(
938 &ecx.machine.threads,
943 let buffer_alloc = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation);
944 let alloc: Allocation<Provenance, Self::AllocExtra> = alloc.adjust_from_tcx(
946 AllocExtra { borrow_tracker, data_race: race_alloc, weak_memory: buffer_alloc },
947 |ptr| ecx.global_base_pointer(ptr),
949 Ok(Cow::Owned(alloc))
952 fn adjust_alloc_base_pointer(
953 ecx: &MiriInterpCx<'mir, 'tcx>,
954 ptr: Pointer<AllocId>,
955 ) -> Pointer<Provenance> {
956 if cfg!(debug_assertions) {
957 // The machine promises to never call us on thread-local or extern statics.
958 let alloc_id = ptr.provenance;
959 match ecx.tcx.try_get_global_alloc(alloc_id) {
960 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
961 panic!("adjust_alloc_base_pointer called on thread-local static")
963 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
964 panic!("adjust_alloc_base_pointer called on extern static")
969 let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
970 let tag = if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
971 borrow_tracker.borrow_mut().base_ptr_tag(ptr.provenance, &ecx.machine)
973 // Value does not matter, SB is disabled
977 Provenance::Concrete { alloc_id: ptr.provenance, tag },
978 Size::from_bytes(absolute_addr),
983 fn ptr_from_addr_cast(
984 ecx: &MiriInterpCx<'mir, 'tcx>,
986 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>> {
987 intptrcast::GlobalStateInner::ptr_from_addr_cast(ecx, addr)
991 ecx: &mut InterpCx<'mir, 'tcx, Self>,
992 ptr: Pointer<Self::Provenance>,
993 ) -> InterpResult<'tcx> {
994 match ptr.provenance {
995 Provenance::Concrete { alloc_id, tag } =>
996 intptrcast::GlobalStateInner::expose_ptr(ecx, alloc_id, tag),
997 Provenance::Wildcard => {
998 // No need to do anything for wildcard pointers as
999 // their provenances have already been previously exposed.
1005 /// Convert a pointer with provenance into an allocation-offset pair,
1006 /// or a `None` with an absolute address if that conversion is not possible.
1008 ecx: &MiriInterpCx<'mir, 'tcx>,
1009 ptr: Pointer<Self::Provenance>,
1010 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
1011 let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
1013 rel.map(|(alloc_id, size)| {
1014 let tag = match ptr.provenance {
1015 Provenance::Concrete { tag, .. } => ProvenanceExtra::Concrete(tag),
1016 Provenance::Wildcard => ProvenanceExtra::Wildcard,
1018 (alloc_id, size, tag)
1023 fn before_memory_read(
1026 alloc_extra: &AllocExtra,
1027 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1029 ) -> InterpResult<'tcx> {
1030 if let Some(data_race) = &alloc_extra.data_race {
1031 data_race.read(alloc_id, range, machine)?;
1033 if let Some(borrow_tracker) = &alloc_extra.borrow_tracker {
1034 borrow_tracker.before_memory_read(alloc_id, prov_extra, range, machine)?;
1036 if let Some(weak_memory) = &alloc_extra.weak_memory {
1037 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1043 fn before_memory_write(
1046 alloc_extra: &mut AllocExtra,
1047 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1049 ) -> InterpResult<'tcx> {
1050 if let Some(data_race) = &mut alloc_extra.data_race {
1051 data_race.write(alloc_id, range, machine)?;
1053 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1054 borrow_tracker.before_memory_write(alloc_id, prov_extra, range, machine)?;
1056 if let Some(weak_memory) = &alloc_extra.weak_memory {
1057 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1063 fn before_memory_deallocation(
1066 alloc_extra: &mut AllocExtra,
1067 (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
1069 ) -> InterpResult<'tcx> {
1070 if machine.tracked_alloc_ids.contains(&alloc_id) {
1071 machine.emit_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
1073 if let Some(data_race) = &mut alloc_extra.data_race {
1074 data_race.deallocate(alloc_id, range, machine)?;
1076 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1077 borrow_tracker.before_memory_deallocation(alloc_id, prove_extra, range, machine)?;
1084 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1085 kind: mir::RetagKind,
1086 val: &ImmTy<'tcx, Provenance>,
1087 ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> {
1088 if ecx.machine.borrow_tracker.is_some() {
1089 ecx.retag_ptr_value(kind, val)
1096 fn retag_place_contents(
1097 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1098 kind: mir::RetagKind,
1099 place: &PlaceTy<'tcx, Provenance>,
1100 ) -> InterpResult<'tcx> {
1101 if ecx.machine.borrow_tracker.is_some() {
1102 ecx.retag_place_contents(kind, place)?;
1108 fn init_frame_extra(
1109 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1110 frame: Frame<'mir, 'tcx, Provenance>,
1111 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>> {
1112 // Start recording our event before doing anything else
1113 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
1114 let fn_name = frame.instance.to_string();
1115 let entry = ecx.machine.string_cache.entry(fn_name.clone());
1116 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
1118 Some(profiler.start_recording_interval_event_detached(
1120 measureme::EventId::from_label(*name),
1121 ecx.get_active_thread().to_u32(),
1127 let borrow_tracker = ecx.machine.borrow_tracker.as_ref();
1129 let extra = FrameExtra {
1130 borrow_tracker: borrow_tracker.map(|bt| bt.borrow_mut().new_frame(&ecx.machine)),
1133 is_user_relevant: ecx.machine.is_user_relevant(&frame),
1136 Ok(frame.with_extra(extra))
1140 ecx: &'a InterpCx<'mir, 'tcx, Self>,
1141 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
1142 ecx.active_thread_stack()
1146 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
1147 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
1148 ecx.active_thread_stack_mut()
1151 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1152 ecx.machine.basic_block_count += 1u64; // a u64 that is only incremented by 1 will "never" overflow
1153 ecx.machine.since_gc += 1;
1154 // Possibly report our progress.
1155 if let Some(report_progress) = ecx.machine.report_progress {
1156 if ecx.machine.basic_block_count % u64::from(report_progress) == 0 {
1157 ecx.emit_diagnostic(NonHaltingDiagnostic::ProgressReport {
1158 block_count: ecx.machine.basic_block_count,
1163 // Search for BorTags to find all live pointers, then remove all other tags from borrow
1165 // When debug assertions are enabled, run the GC as often as possible so that any cases
1166 // where it mistakenly removes an important tag become visible.
1167 if ecx.machine.gc_interval > 0 && ecx.machine.since_gc >= ecx.machine.gc_interval {
1168 ecx.machine.since_gc = 0;
1169 ecx.garbage_collect_tags()?;
1172 // These are our preemption points.
1173 ecx.maybe_preempt_active_thread();
1175 // Make sure some time passes.
1176 ecx.machine.clock.tick();
1182 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1183 if ecx.frame().extra.is_user_relevant {
1184 // We just pushed a local frame, so we know that the topmost local frame is the topmost
1185 // frame. If we push a non-local frame, there's no need to do anything.
1186 let stack_len = ecx.active_thread_stack().len();
1187 ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1);
1189 if ecx.machine.borrow_tracker.is_some() {
1190 ecx.retag_return_place()?;
1197 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1198 mut frame: Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>,
1200 ) -> InterpResult<'tcx, StackPopJump> {
1201 if frame.extra.is_user_relevant {
1202 // All that we store is whether or not the frame we just removed is local, so now we
1203 // have no idea where the next topmost local frame is. So we recompute it.
1204 // (If this ever becomes a bottleneck, we could have `push` store the previous
1205 // user-relevant frame and restore that here.)
1206 ecx.active_thread_mut().recompute_top_user_relevant_frame();
1208 let timing = frame.extra.timing.take();
1209 if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
1210 borrow_tracker.borrow_mut().end_call(&frame.extra);
1212 let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
1213 if let Some(profiler) = ecx.machine.profiler.as_ref() {
1214 profiler.finish_recording_interval_event(timing.unwrap());