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, Align};
26 use rustc_target::spec::abi::Abi;
27 use rustc_const_eval::const_eval::CheckAlignment;
30 concurrency::{data_race, weak_memory},
31 shims::unix::FileHandler,
35 // Some global facts about the emulated machine.
36 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
37 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
38 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
40 /// Extra data stored with each stack frame
41 pub struct FrameExtra<'tcx> {
42 /// Extra data for Stacked Borrows.
43 pub borrow_tracker: Option<borrow_tracker::FrameState>,
45 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
46 /// called by `try`). When this frame is popped during unwinding a panic,
47 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
48 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
50 /// If `measureme` profiling is enabled, holds timing information
51 /// for the start of this frame. When we finish executing this frame,
52 /// we use this to register a completed event with `measureme`.
53 pub timing: Option<measureme::DetachedTiming>,
55 /// Indicates whether a `Frame` is part of a workspace-local crate and is also not
56 /// `#[track_caller]`. We compute this once on creation and store the result, as an
58 /// This is used by `MiriMachine::current_span` and `MiriMachine::caller_span`
59 pub is_user_relevant: bool,
62 impl<'tcx> std::fmt::Debug for FrameExtra<'tcx> {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 // Omitting `timing`, it does not support `Debug`.
65 let FrameExtra { borrow_tracker, catch_unwind, timing: _, is_user_relevant: _ } = self;
66 f.debug_struct("FrameData")
67 .field("borrow_tracker", borrow_tracker)
68 .field("catch_unwind", catch_unwind)
73 impl VisitTags for FrameExtra<'_> {
74 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
75 let FrameExtra { catch_unwind, borrow_tracker, timing: _, is_user_relevant: _ } = self;
77 catch_unwind.visit_tags(visit);
78 borrow_tracker.visit_tags(visit);
82 /// Extra memory kinds
83 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
84 pub enum MiriMemoryKind {
85 /// `__rust_alloc` memory.
87 /// `miri_alloc` memory.
91 /// Windows `HeapAlloc` memory.
93 /// Memory for args, errno, and other parts of the machine-managed environment.
94 /// This memory may leak.
96 /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
97 /// because we clean it up and leak-check it.
99 /// Globals copied from `tcx`.
100 /// This memory may leak.
102 /// Memory for extern statics.
103 /// This memory may leak.
105 /// Memory for thread-local statics.
106 /// This memory may leak.
110 impl From<MiriMemoryKind> for MemoryKind<MiriMemoryKind> {
112 fn from(kind: MiriMemoryKind) -> MemoryKind<MiriMemoryKind> {
113 MemoryKind::Machine(kind)
117 impl MayLeak for MiriMemoryKind {
119 fn may_leak(self) -> bool {
120 use self::MiriMemoryKind::*;
122 Rust | Miri | C | WinHeap | Runtime => false,
123 Machine | Global | ExternStatic | Tls => true,
128 impl fmt::Display for MiriMemoryKind {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 use self::MiriMemoryKind::*;
132 Rust => write!(f, "Rust heap"),
133 Miri => write!(f, "Miri bare-metal heap"),
134 C => write!(f, "C heap"),
135 WinHeap => write!(f, "Windows heap"),
136 Machine => write!(f, "machine-managed memory"),
137 Runtime => write!(f, "language runtime memory"),
138 Global => write!(f, "global (static or const)"),
139 ExternStatic => write!(f, "extern static"),
140 Tls => write!(f, "thread-local static"),
145 /// Pointer provenance.
146 #[derive(Clone, Copy)]
147 pub enum Provenance {
150 /// Stacked Borrows tag.
156 // This needs to be `Eq`+`Hash` because the `Machine` trait needs that because validity checking
157 // *might* be recursive and then it has to track which places have already been visited.
158 // However, comparing provenance is meaningless, since `Wildcard` might be any provenance -- and of
159 // course we don't actually do recursive checking.
160 // We could change `RefTracking` to strip provenance for its `seen` set but that type is generic so that is quite annoying.
161 // Instead owe add the required instances but make them panic.
162 impl PartialEq for Provenance {
163 fn eq(&self, _other: &Self) -> bool {
164 panic!("Provenance must not be compared")
167 impl Eq for Provenance {}
168 impl std::hash::Hash for Provenance {
169 fn hash<H: std::hash::Hasher>(&self, _state: &mut H) {
170 panic!("Provenance must not be hashed")
174 /// The "extra" information a pointer has over a regular AllocId.
175 #[derive(Copy, Clone, PartialEq)]
176 pub enum ProvenanceExtra {
181 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
182 static_assert_size!(Pointer<Provenance>, 24);
183 // FIXME: this would with in 24bytes but layout optimizations are not smart enough
184 // #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
185 //static_assert_size!(Pointer<Option<Provenance>>, 24);
186 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
187 static_assert_size!(Scalar<Provenance>, 32);
189 impl fmt::Debug for Provenance {
190 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
192 Provenance::Concrete { alloc_id, tag } => {
193 // Forward `alternate` flag to `alloc_id` printing.
195 write!(f, "[{alloc_id:#?}]")?;
197 write!(f, "[{alloc_id:?}]")?;
199 // Print Stacked Borrows tag.
200 write!(f, "{tag:?}")?;
202 Provenance::Wildcard => {
203 write!(f, "[wildcard]")?;
210 impl interpret::Provenance for Provenance {
211 /// We use absolute addresses in the `offset` of a `Pointer<Provenance>`.
212 const OFFSET_IS_ADDR: bool = true;
214 fn get_alloc_id(self) -> Option<AllocId> {
216 Provenance::Concrete { alloc_id, .. } => Some(alloc_id),
217 Provenance::Wildcard => None,
221 fn join(left: Option<Self>, right: Option<Self>) -> Option<Self> {
222 match (left, right) {
223 // If both are the *same* concrete tag, that is the result.
225 Some(Provenance::Concrete { alloc_id: left_alloc, tag: left_tag }),
226 Some(Provenance::Concrete { alloc_id: right_alloc, tag: right_tag }),
227 ) if left_alloc == right_alloc && left_tag == right_tag => left,
228 // If one side is a wildcard, the best possible outcome is that it is equal to the other
229 // one, and we use that.
230 (Some(Provenance::Wildcard), o) | (o, Some(Provenance::Wildcard)) => o,
231 // Otherwise, fall back to `None`.
237 impl fmt::Debug for ProvenanceExtra {
238 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
240 ProvenanceExtra::Concrete(pid) => write!(f, "{pid:?}"),
241 ProvenanceExtra::Wildcard => write!(f, "<wildcard>"),
246 impl ProvenanceExtra {
247 pub fn and_then<T>(self, f: impl FnOnce(BorTag) -> Option<T>) -> Option<T> {
249 ProvenanceExtra::Concrete(pid) => f(pid),
250 ProvenanceExtra::Wildcard => None,
255 /// Extra per-allocation data
256 #[derive(Debug, Clone)]
257 pub struct AllocExtra {
258 /// Global state of the borrow tracker, if enabled.
259 pub borrow_tracker: Option<borrow_tracker::AllocState>,
260 /// Data race detection via the use of a vector-clock,
261 /// this is only added if it is enabled.
262 pub data_race: Option<data_race::AllocState>,
263 /// Weak memory emulation via the use of store buffers,
264 /// this is only added if it is enabled.
265 pub weak_memory: Option<weak_memory::AllocState>,
268 impl VisitTags for AllocExtra {
269 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
270 let AllocExtra { borrow_tracker, data_race, weak_memory } = self;
272 borrow_tracker.visit_tags(visit);
273 data_race.visit_tags(visit);
274 weak_memory.visit_tags(visit);
278 /// Precomputed layouts of primitive types
279 pub struct PrimitiveLayouts<'tcx> {
280 pub unit: TyAndLayout<'tcx>,
281 pub i8: TyAndLayout<'tcx>,
282 pub i16: TyAndLayout<'tcx>,
283 pub i32: TyAndLayout<'tcx>,
284 pub i64: TyAndLayout<'tcx>,
285 pub i128: TyAndLayout<'tcx>,
286 pub isize: TyAndLayout<'tcx>,
287 pub u8: TyAndLayout<'tcx>,
288 pub u16: TyAndLayout<'tcx>,
289 pub u32: TyAndLayout<'tcx>,
290 pub u64: TyAndLayout<'tcx>,
291 pub u128: TyAndLayout<'tcx>,
292 pub usize: TyAndLayout<'tcx>,
293 pub bool: TyAndLayout<'tcx>,
294 pub mut_raw_ptr: TyAndLayout<'tcx>, // *mut ()
295 pub const_raw_ptr: TyAndLayout<'tcx>, // *const ()
298 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
299 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
300 let tcx = layout_cx.tcx;
301 let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
302 let const_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Not });
304 unit: layout_cx.layout_of(tcx.mk_unit())?,
305 i8: layout_cx.layout_of(tcx.types.i8)?,
306 i16: layout_cx.layout_of(tcx.types.i16)?,
307 i32: layout_cx.layout_of(tcx.types.i32)?,
308 i64: layout_cx.layout_of(tcx.types.i64)?,
309 i128: layout_cx.layout_of(tcx.types.i128)?,
310 isize: layout_cx.layout_of(tcx.types.isize)?,
311 u8: layout_cx.layout_of(tcx.types.u8)?,
312 u16: layout_cx.layout_of(tcx.types.u16)?,
313 u32: layout_cx.layout_of(tcx.types.u32)?,
314 u64: layout_cx.layout_of(tcx.types.u64)?,
315 u128: layout_cx.layout_of(tcx.types.u128)?,
316 usize: layout_cx.layout_of(tcx.types.usize)?,
317 bool: layout_cx.layout_of(tcx.types.bool)?,
318 mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
319 const_raw_ptr: layout_cx.layout_of(const_raw_ptr)?,
323 pub fn uint(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
326 16 => Some(self.u16),
327 32 => Some(self.u32),
328 64 => Some(self.u64),
329 128 => Some(self.u128),
334 pub fn int(&self, size: Size) -> Option<TyAndLayout<'tcx>> {
337 16 => Some(self.i16),
338 32 => Some(self.i32),
339 64 => Some(self.i64),
340 128 => Some(self.i128),
346 /// The machine itself.
348 /// If you add anything here that stores machine values, remember to update
349 /// `visit_all_machine_values`!
350 pub struct MiriMachine<'mir, 'tcx> {
351 // We carry a copy of the global `TyCtxt` for convenience, so methods taking just `&Evaluator` have `tcx` access.
352 pub tcx: TyCtxt<'tcx>,
354 /// Global data for borrow tracking.
355 pub borrow_tracker: Option<borrow_tracker::GlobalState>,
357 /// Data race detector global data.
358 pub data_race: Option<data_race::GlobalState>,
360 /// Ptr-int-cast module global data.
361 pub intptrcast: intptrcast::GlobalState,
363 /// Environment variables set by `setenv`.
364 /// Miri does not expose env vars from the host to the emulated program.
365 pub(crate) env_vars: EnvVars<'tcx>,
367 /// Return place of the main function.
368 pub(crate) main_fn_ret_place: Option<MemPlace<Provenance>>,
370 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
371 /// These are *pointers* to argc/argv because macOS.
372 /// We also need the full command line as one string because of Windows.
373 pub(crate) argc: Option<MemPlace<Provenance>>,
374 pub(crate) argv: Option<MemPlace<Provenance>>,
375 pub(crate) cmd_line: Option<MemPlace<Provenance>>,
378 pub(crate) tls: TlsData<'tcx>,
380 /// What should Miri do when an op requires communicating with the host,
381 /// such as accessing host env vars, random number generation, and
382 /// file system access.
383 pub(crate) isolated_op: IsolatedOp,
385 /// Whether to enforce the validity invariant.
386 pub(crate) validate: bool,
388 /// Whether to enforce [ABI](Abi) of function calls.
389 pub(crate) enforce_abi: bool,
391 /// The table of file descriptors.
392 pub(crate) file_handler: shims::unix::FileHandler,
393 /// The table of directory descriptors.
394 pub(crate) dir_handler: shims::unix::DirHandler,
396 /// This machine's monotone clock.
397 pub(crate) clock: Clock,
399 /// The set of threads.
400 pub(crate) threads: ThreadManager<'mir, 'tcx>,
402 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
403 pub(crate) layouts: PrimitiveLayouts<'tcx>,
405 /// Allocations that are considered roots of static memory (that may leak).
406 pub(crate) static_roots: Vec<AllocId>,
408 /// The `measureme` profiler used to record timing information about
409 /// the emulated program.
410 profiler: Option<measureme::Profiler>,
411 /// Used with `profiler` to cache the `StringId`s for event names
412 /// uesd with `measureme`.
413 string_cache: FxHashMap<String, measureme::StringId>,
415 /// Cache of `Instance` exported under the given `Symbol` name.
416 /// `None` means no `Instance` exported under the given name is found.
417 pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
419 /// Whether to raise a panic in the context of the evaluated process when unsupported
420 /// functionality is encountered. If `false`, an error is propagated in the Miri application context
421 /// instead (default behavior)
422 pub(crate) panic_on_unsupported: bool,
424 /// Equivalent setting as RUST_BACKTRACE on encountering an error.
425 pub(crate) backtrace_style: BacktraceStyle,
427 /// Crates which are considered local for the purposes of error reporting.
428 pub(crate) local_crates: Vec<CrateNum>,
430 /// Mapping extern static names to their base pointer.
431 extern_statics: FxHashMap<Symbol, Pointer<Provenance>>,
433 /// The random number generator used for resolving non-determinism.
434 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
435 pub(crate) rng: RefCell<StdRng>,
437 /// The allocation IDs to report when they are being allocated
438 /// (helps for debugging memory leaks and use after free bugs).
439 tracked_alloc_ids: FxHashSet<AllocId>,
441 /// Controls whether alignment of memory accesses is being checked.
442 pub(crate) check_alignment: AlignmentCheck,
444 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
445 pub(crate) cmpxchg_weak_failure_rate: f64,
447 /// Corresponds to -Zmiri-mute-stdout-stderr and doesn't write the output but acts as if it succeeded.
448 pub(crate) mute_stdout_stderr: bool,
450 /// Whether weak memory emulation is enabled
451 pub(crate) weak_memory: bool,
453 /// The probability of the active thread being preempted at the end of each basic block.
454 pub(crate) preemption_rate: f64,
456 /// If `Some`, we will report the current stack every N basic blocks.
457 pub(crate) report_progress: Option<u32>,
458 // The total number of blocks that have been executed.
459 pub(crate) basic_block_count: u64,
461 /// Handle of the optional shared object file for external functions.
462 #[cfg(target_os = "linux")]
463 pub external_so_lib: Option<(libloading::Library, std::path::PathBuf)>,
464 #[cfg(not(target_os = "linux"))]
465 pub external_so_lib: Option<!>,
467 /// Run a garbage collector for BorTags every N basic blocks.
468 pub(crate) gc_interval: u32,
469 /// The number of blocks that passed since the last BorTag GC pass.
470 pub(crate) since_gc: u32,
471 /// The number of CPUs to be reported by miri.
472 pub(crate) num_cpus: u32,
475 impl<'mir, 'tcx> MiriMachine<'mir, 'tcx> {
476 pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
477 let local_crates = helpers::get_local_crates(layout_cx.tcx);
479 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
480 let profiler = config.measureme_out.as_ref().map(|out| {
481 measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
483 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
484 let borrow_tracker = config.borrow_tracker.map(|bt| bt.instanciate_global_state(config));
485 let data_race = config.data_race_detector.then(|| data_race::GlobalState::new(config));
490 intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config)),
491 // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
492 env_vars: EnvVars::default(),
493 main_fn_ret_place: None,
497 tls: TlsData::default(),
498 isolated_op: config.isolated_op,
499 validate: config.validate,
500 enforce_abi: config.check_abi,
501 file_handler: FileHandler::new(config.mute_stdout_stderr),
502 dir_handler: Default::default(),
504 threads: ThreadManager::default(),
505 static_roots: Vec::new(),
507 string_cache: Default::default(),
508 exported_symbols_cache: FxHashMap::default(),
509 panic_on_unsupported: config.panic_on_unsupported,
510 backtrace_style: config.backtrace_style,
512 extern_statics: FxHashMap::default(),
513 rng: RefCell::new(rng),
514 tracked_alloc_ids: config.tracked_alloc_ids.clone(),
515 check_alignment: config.check_alignment,
516 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
517 mute_stdout_stderr: config.mute_stdout_stderr,
518 weak_memory: config.weak_memory_emulation,
519 preemption_rate: config.preemption_rate,
520 report_progress: config.report_progress,
521 basic_block_count: 0,
522 clock: Clock::new(config.isolated_op == IsolatedOp::Allow),
523 #[cfg(target_os = "linux")]
524 external_so_lib: config.external_so_file.as_ref().map(|lib_file_path| {
525 let target_triple = layout_cx.tcx.sess.opts.target_triple.triple();
526 // Check if host target == the session target.
527 if env!("TARGET") != target_triple {
529 "calling external C functions in linked .so file requires host and target to be the same: host={}, target={}",
534 // Note: it is the user's responsibility to provide a correct SO file.
535 // WATCH OUT: If an invalid/incorrect SO file is specified, this can cause
536 // undefined behaviour in Miri itself!
539 libloading::Library::new(lib_file_path)
540 .expect("failed to read specified extern shared object file")
542 lib_file_path.clone(),
545 #[cfg(not(target_os = "linux"))]
546 external_so_lib: config.external_so_file.as_ref().map(|_| {
547 panic!("loading external .so files is only supported on Linux")
549 gc_interval: config.gc_interval,
551 num_cpus: config.num_cpus,
555 pub(crate) fn late_init(
556 this: &mut MiriInterpCx<'mir, 'tcx>,
558 on_main_stack_empty: StackEmptyCallback<'mir, 'tcx>,
559 ) -> InterpResult<'tcx> {
560 EnvVars::init(this, config)?;
561 MiriMachine::init_extern_statics(this)?;
562 ThreadManager::init(this, on_main_stack_empty);
566 fn add_extern_static(
567 this: &mut MiriInterpCx<'mir, 'tcx>,
569 ptr: Pointer<Option<Provenance>>,
571 // This got just allocated, so there definitely is a pointer here.
572 let ptr = ptr.into_pointer_or_addr().unwrap();
573 this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
576 fn alloc_extern_static(
577 this: &mut MiriInterpCx<'mir, 'tcx>,
579 val: ImmTy<'tcx, Provenance>,
580 ) -> InterpResult<'tcx> {
581 let place = this.allocate(val.layout, MiriMemoryKind::ExternStatic.into())?;
582 this.write_immediate(*val, &place.into())?;
583 Self::add_extern_static(this, name, place.ptr);
587 /// Sets up the "extern statics" for this machine.
588 fn init_extern_statics(this: &mut MiriInterpCx<'mir, 'tcx>) -> InterpResult<'tcx> {
589 match this.tcx.sess.target.os.as_ref() {
592 Self::add_extern_static(
595 this.machine.env_vars.environ.unwrap().ptr,
597 // A couple zero-initialized pointer-sized extern statics.
598 // Most of them are for weak symbols, which we all set to null (indicating that the
599 // symbol is not supported, and triggering fallback code which ends up calling a
600 // syscall that we do support).
601 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"]
603 let val = ImmTy::from_int(0, this.machine.layouts.usize);
604 Self::alloc_extern_static(this, name, val)?;
609 Self::add_extern_static(
612 this.machine.env_vars.environ.unwrap().ptr,
617 let layout = this.machine.layouts.const_raw_ptr;
618 let dlsym = Dlsym::from_str("signal".as_bytes(), &this.tcx.sess.target.os)?
619 .expect("`signal` must be an actual dlsym on android");
620 let ptr = this.create_fn_alloc_ptr(FnVal::Other(dlsym));
621 let val = ImmTy::from_scalar(Scalar::from_pointer(ptr, this), layout);
622 Self::alloc_extern_static(this, "signal", val)?;
623 // A couple zero-initialized pointer-sized extern statics.
624 // Most of them are for weak symbols, which we all set to null (indicating that the
625 // symbol is not supported, and triggering fallback code.)
626 for name in &["bsd_signal"] {
627 let val = ImmTy::from_int(0, this.machine.layouts.usize);
628 Self::alloc_extern_static(this, name, val)?;
633 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
634 let val = ImmTy::from_int(0, this.machine.layouts.u8);
635 Self::alloc_extern_static(this, "_tls_used", val)?;
637 _ => {} // No "extern statics" supported on this target
642 pub(crate) fn communicate(&self) -> bool {
643 self.isolated_op == IsolatedOp::Allow
646 /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
647 pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
648 let def_id = frame.instance.def_id();
649 def_id.is_local() || self.local_crates.contains(&def_id.krate)
653 impl VisitTags for MiriMachine<'_, '_> {
654 fn visit_tags(&self, visit: &mut dyn FnMut(BorTag)) {
679 exported_symbols_cache: _,
680 panic_on_unsupported: _,
684 tracked_alloc_ids: _,
686 cmpxchg_weak_failure_rate: _,
687 mute_stdout_stderr: _,
691 basic_block_count: _,
698 threads.visit_tags(visit);
699 tls.visit_tags(visit);
700 env_vars.visit_tags(visit);
701 dir_handler.visit_tags(visit);
702 file_handler.visit_tags(visit);
703 data_race.visit_tags(visit);
704 borrow_tracker.visit_tags(visit);
705 intptrcast.visit_tags(visit);
706 main_fn_ret_place.visit_tags(visit);
707 argc.visit_tags(visit);
708 argv.visit_tags(visit);
709 cmd_line.visit_tags(visit);
710 for ptr in extern_statics.values() {
711 ptr.visit_tags(visit);
716 /// A rustc InterpCx for Miri.
717 pub type MiriInterpCx<'mir, 'tcx> = InterpCx<'mir, 'tcx, MiriMachine<'mir, 'tcx>>;
719 /// A little trait that's useful to be inherited by extension traits.
720 pub trait MiriInterpCxExt<'mir, 'tcx> {
721 fn eval_context_ref<'a>(&'a self) -> &'a MiriInterpCx<'mir, 'tcx>;
722 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriInterpCx<'mir, 'tcx>;
724 impl<'mir, 'tcx> MiriInterpCxExt<'mir, 'tcx> for MiriInterpCx<'mir, 'tcx> {
726 fn eval_context_ref(&self) -> &MiriInterpCx<'mir, 'tcx> {
730 fn eval_context_mut(&mut self) -> &mut MiriInterpCx<'mir, 'tcx> {
735 /// Machine hook implementations.
736 impl<'mir, 'tcx> Machine<'mir, 'tcx> for MiriMachine<'mir, 'tcx> {
737 type MemoryKind = MiriMemoryKind;
738 type ExtraFnVal = Dlsym;
740 type FrameExtra = FrameExtra<'tcx>;
741 type AllocExtra = AllocExtra;
743 type Provenance = Provenance;
744 type ProvenanceExtra = ProvenanceExtra;
746 type MemoryMap = MonoHashMap<
748 (MemoryKind<MiriMemoryKind>, Allocation<Provenance, Self::AllocExtra>),
751 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
753 const PANIC_ON_ALLOC_FAIL: bool = false;
756 fn enforce_alignment(ecx: &MiriInterpCx<'mir, 'tcx>) -> CheckAlignment {
757 if ecx.machine.check_alignment == AlignmentCheck::None {
760 CheckAlignment::Error
765 fn use_addr_for_alignment_check(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
766 ecx.machine.check_alignment == AlignmentCheck::Int
769 fn alignment_check_failed(
770 _ecx: &InterpCx<'mir, 'tcx, Self>,
773 _check: CheckAlignment,
774 ) -> InterpResult<'tcx, ()> {
775 throw_ub!(AlignmentCheckFailed { has, required })
779 fn enforce_validity(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
784 fn enforce_abi(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
785 ecx.machine.enforce_abi
789 fn checked_binop_checks_overflow(ecx: &MiriInterpCx<'mir, 'tcx>) -> bool {
790 ecx.tcx.sess.overflow_checks()
794 fn find_mir_or_eval_fn(
795 ecx: &mut MiriInterpCx<'mir, 'tcx>,
796 instance: ty::Instance<'tcx>,
798 args: &[OpTy<'tcx, Provenance>],
799 dest: &PlaceTy<'tcx, Provenance>,
800 ret: Option<mir::BasicBlock>,
801 unwind: StackPopUnwind,
802 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
803 ecx.find_mir_or_eval_fn(instance, abi, args, dest, ret, unwind)
808 ecx: &mut MiriInterpCx<'mir, 'tcx>,
811 args: &[OpTy<'tcx, Provenance>],
812 dest: &PlaceTy<'tcx, Provenance>,
813 ret: Option<mir::BasicBlock>,
814 _unwind: StackPopUnwind,
815 ) -> InterpResult<'tcx> {
816 ecx.call_dlsym(fn_val, abi, args, dest, ret)
821 ecx: &mut MiriInterpCx<'mir, 'tcx>,
822 instance: ty::Instance<'tcx>,
823 args: &[OpTy<'tcx, Provenance>],
824 dest: &PlaceTy<'tcx, Provenance>,
825 ret: Option<mir::BasicBlock>,
826 unwind: StackPopUnwind,
827 ) -> InterpResult<'tcx> {
828 ecx.call_intrinsic(instance, args, dest, ret, unwind)
833 ecx: &mut MiriInterpCx<'mir, 'tcx>,
834 msg: &mir::AssertMessage<'tcx>,
835 unwind: Option<mir::BasicBlock>,
836 ) -> InterpResult<'tcx> {
837 ecx.assert_panic(msg, unwind)
841 fn abort(_ecx: &mut MiriInterpCx<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
842 throw_machine_stop!(TerminationInfo::Abort(msg))
847 ecx: &MiriInterpCx<'mir, 'tcx>,
849 left: &ImmTy<'tcx, Provenance>,
850 right: &ImmTy<'tcx, Provenance>,
851 ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, Ty<'tcx>)> {
852 ecx.binary_ptr_op(bin_op, left, right)
855 fn thread_local_static_base_pointer(
856 ecx: &mut MiriInterpCx<'mir, 'tcx>,
858 ) -> InterpResult<'tcx, Pointer<Provenance>> {
859 ecx.get_or_create_thread_local_alloc(def_id)
862 fn extern_static_base_pointer(
863 ecx: &MiriInterpCx<'mir, 'tcx>,
865 ) -> InterpResult<'tcx, Pointer<Provenance>> {
866 let link_name = ecx.item_link_name(def_id);
867 if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
868 // Various parts of the engine rely on `get_alloc_info` for size and alignment
869 // information. That uses the type information of this static.
870 // Make sure it matches the Miri allocation for this.
871 let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
872 panic!("extern_statics cannot contain wildcards")
874 let (shim_size, shim_align, _kind) = ecx.get_alloc_info(alloc_id);
875 let extern_decl_layout =
876 ecx.tcx.layout_of(ty::ParamEnv::empty().and(ecx.tcx.type_of(def_id))).unwrap();
877 if extern_decl_layout.size != shim_size || extern_decl_layout.align.abi != shim_align {
879 "`extern` static `{name}` from crate `{krate}` has been declared \
880 with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
881 but Miri emulates it via an extern static shim \
882 with a size of {shim_size} bytes and alignment of {shim_align} bytes",
883 name = ecx.tcx.def_path_str(def_id),
884 krate = ecx.tcx.crate_name(def_id.krate),
885 decl_size = extern_decl_layout.size.bytes(),
886 decl_align = extern_decl_layout.align.abi.bytes(),
887 shim_size = shim_size.bytes(),
888 shim_align = shim_align.bytes(),
894 "`extern` static `{name}` from crate `{krate}` is not supported by Miri",
895 name = ecx.tcx.def_path_str(def_id),
896 krate = ecx.tcx.crate_name(def_id.krate),
901 fn adjust_allocation<'b>(
902 ecx: &MiriInterpCx<'mir, 'tcx>,
904 alloc: Cow<'b, Allocation>,
905 kind: Option<MemoryKind<Self::MemoryKind>>,
906 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>> {
907 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
908 if ecx.machine.tracked_alloc_ids.contains(&id) {
909 ecx.emit_diagnostic(NonHaltingDiagnostic::CreatedAlloc(
917 let alloc = alloc.into_owned();
918 let borrow_tracker = ecx
922 .map(|bt| bt.borrow_mut().new_allocation(id, alloc.size(), kind, &ecx.machine));
924 let race_alloc = ecx.machine.data_race.as_ref().map(|data_race| {
925 data_race::AllocState::new_allocation(
927 &ecx.machine.threads,
932 let buffer_alloc = ecx.machine.weak_memory.then(weak_memory::AllocState::new_allocation);
933 let alloc: Allocation<Provenance, Self::AllocExtra> = alloc.adjust_from_tcx(
935 AllocExtra { borrow_tracker, data_race: race_alloc, weak_memory: buffer_alloc },
936 |ptr| ecx.global_base_pointer(ptr),
938 Ok(Cow::Owned(alloc))
941 fn adjust_alloc_base_pointer(
942 ecx: &MiriInterpCx<'mir, 'tcx>,
943 ptr: Pointer<AllocId>,
944 ) -> Pointer<Provenance> {
945 if cfg!(debug_assertions) {
946 // The machine promises to never call us on thread-local or extern statics.
947 let alloc_id = ptr.provenance;
948 match ecx.tcx.try_get_global_alloc(alloc_id) {
949 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
950 panic!("adjust_alloc_base_pointer called on thread-local static")
952 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
953 panic!("adjust_alloc_base_pointer called on extern static")
958 let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
959 let tag = if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
960 borrow_tracker.borrow_mut().base_ptr_tag(ptr.provenance, &ecx.machine)
962 // Value does not matter, SB is disabled
966 Provenance::Concrete { alloc_id: ptr.provenance, tag },
967 Size::from_bytes(absolute_addr),
972 fn ptr_from_addr_cast(
973 ecx: &MiriInterpCx<'mir, 'tcx>,
975 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>> {
976 intptrcast::GlobalStateInner::ptr_from_addr_cast(ecx, addr)
980 ecx: &mut InterpCx<'mir, 'tcx, Self>,
981 ptr: Pointer<Self::Provenance>,
982 ) -> InterpResult<'tcx> {
983 match ptr.provenance {
984 Provenance::Concrete { alloc_id, tag } => {
985 intptrcast::GlobalStateInner::expose_ptr(ecx, alloc_id, tag)
987 Provenance::Wildcard => {
988 // No need to do anything for wildcard pointers as
989 // their provenances have already been previously exposed.
995 /// Convert a pointer with provenance into an allocation-offset pair,
996 /// or a `None` with an absolute address if that conversion is not possible.
998 ecx: &MiriInterpCx<'mir, 'tcx>,
999 ptr: Pointer<Self::Provenance>,
1000 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
1001 let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
1003 rel.map(|(alloc_id, size)| {
1004 let tag = match ptr.provenance {
1005 Provenance::Concrete { tag, .. } => ProvenanceExtra::Concrete(tag),
1006 Provenance::Wildcard => ProvenanceExtra::Wildcard,
1008 (alloc_id, size, tag)
1013 fn before_memory_read(
1016 alloc_extra: &AllocExtra,
1017 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1019 ) -> InterpResult<'tcx> {
1020 if let Some(data_race) = &alloc_extra.data_race {
1021 data_race.read(alloc_id, range, machine)?;
1023 if let Some(borrow_tracker) = &alloc_extra.borrow_tracker {
1024 borrow_tracker.before_memory_read(alloc_id, prov_extra, range, machine)?;
1026 if let Some(weak_memory) = &alloc_extra.weak_memory {
1027 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1033 fn before_memory_write(
1036 alloc_extra: &mut AllocExtra,
1037 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
1039 ) -> InterpResult<'tcx> {
1040 if let Some(data_race) = &mut alloc_extra.data_race {
1041 data_race.write(alloc_id, range, machine)?;
1043 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1044 borrow_tracker.before_memory_write(alloc_id, prov_extra, range, machine)?;
1046 if let Some(weak_memory) = &alloc_extra.weak_memory {
1047 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
1053 fn before_memory_deallocation(
1056 alloc_extra: &mut AllocExtra,
1057 (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
1059 ) -> InterpResult<'tcx> {
1060 if machine.tracked_alloc_ids.contains(&alloc_id) {
1061 machine.emit_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
1063 if let Some(data_race) = &mut alloc_extra.data_race {
1064 data_race.deallocate(alloc_id, range, machine)?;
1066 if let Some(borrow_tracker) = &mut alloc_extra.borrow_tracker {
1067 borrow_tracker.before_memory_deallocation(alloc_id, prove_extra, range, machine)?;
1074 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1075 kind: mir::RetagKind,
1076 val: &ImmTy<'tcx, Provenance>,
1077 ) -> InterpResult<'tcx, ImmTy<'tcx, Provenance>> {
1078 if ecx.machine.borrow_tracker.is_some() {
1079 ecx.retag_ptr_value(kind, val)
1086 fn retag_place_contents(
1087 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1088 kind: mir::RetagKind,
1089 place: &PlaceTy<'tcx, Provenance>,
1090 ) -> InterpResult<'tcx> {
1091 if ecx.machine.borrow_tracker.is_some() {
1092 ecx.retag_place_contents(kind, place)?;
1098 fn init_frame_extra(
1099 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1100 frame: Frame<'mir, 'tcx, Provenance>,
1101 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>> {
1102 // Start recording our event before doing anything else
1103 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
1104 let fn_name = frame.instance.to_string();
1105 let entry = ecx.machine.string_cache.entry(fn_name.clone());
1106 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
1108 Some(profiler.start_recording_interval_event_detached(
1110 measureme::EventId::from_label(*name),
1111 ecx.get_active_thread().to_u32(),
1117 let borrow_tracker = ecx.machine.borrow_tracker.as_ref();
1119 let extra = FrameExtra {
1120 borrow_tracker: borrow_tracker.map(|bt| bt.borrow_mut().new_frame(&ecx.machine)),
1123 is_user_relevant: ecx.machine.is_user_relevant(&frame),
1126 Ok(frame.with_extra(extra))
1130 ecx: &'a InterpCx<'mir, 'tcx, Self>,
1131 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
1132 ecx.active_thread_stack()
1136 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
1137 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
1138 ecx.active_thread_stack_mut()
1141 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1142 ecx.machine.basic_block_count += 1u64; // a u64 that is only incremented by 1 will "never" overflow
1143 ecx.machine.since_gc += 1;
1144 // Possibly report our progress.
1145 if let Some(report_progress) = ecx.machine.report_progress {
1146 if ecx.machine.basic_block_count % u64::from(report_progress) == 0 {
1147 ecx.emit_diagnostic(NonHaltingDiagnostic::ProgressReport {
1148 block_count: ecx.machine.basic_block_count,
1153 // Search for BorTags to find all live pointers, then remove all other tags from borrow
1155 // When debug assertions are enabled, run the GC as often as possible so that any cases
1156 // where it mistakenly removes an important tag become visible.
1157 if ecx.machine.gc_interval > 0 && ecx.machine.since_gc >= ecx.machine.gc_interval {
1158 ecx.machine.since_gc = 0;
1159 ecx.garbage_collect_tags()?;
1162 // These are our preemption points.
1163 ecx.maybe_preempt_active_thread();
1165 // Make sure some time passes.
1166 ecx.machine.clock.tick();
1172 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
1173 if ecx.frame().extra.is_user_relevant {
1174 // We just pushed a local frame, so we know that the topmost local frame is the topmost
1175 // frame. If we push a non-local frame, there's no need to do anything.
1176 let stack_len = ecx.active_thread_stack().len();
1177 ecx.active_thread_mut().set_top_user_relevant_frame(stack_len - 1);
1179 if ecx.machine.borrow_tracker.is_some() {
1180 ecx.retag_return_place()?;
1187 ecx: &mut InterpCx<'mir, 'tcx, Self>,
1188 mut frame: Frame<'mir, 'tcx, Provenance, FrameExtra<'tcx>>,
1190 ) -> InterpResult<'tcx, StackPopJump> {
1191 if frame.extra.is_user_relevant {
1192 // All that we store is whether or not the frame we just removed is local, so now we
1193 // have no idea where the next topmost local frame is. So we recompute it.
1194 // (If this ever becomes a bottleneck, we could have `push` store the previous
1195 // user-relevant frame and restore that here.)
1196 ecx.active_thread_mut().recompute_top_user_relevant_frame();
1198 let timing = frame.extra.timing.take();
1199 if let Some(borrow_tracker) = &ecx.machine.borrow_tracker {
1200 borrow_tracker.borrow_mut().end_call(&frame.extra);
1202 let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
1203 if let Some(profiler) = ecx.machine.profiler.as_ref() {
1204 profiler.finish_recording_interval_event(timing.unwrap());