1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
6 use std::collections::HashSet;
8 use std::time::Instant;
10 use rand::rngs::StdRng;
11 use rand::SeedableRng;
13 use rustc_ast::ast::Mutability;
14 use rustc_data_structures::fx::FxHashMap;
16 use rustc_data_structures::static_assert_size;
21 layout::{LayoutCx, LayoutError, LayoutOf, TyAndLayout},
22 Instance, TyCtxt, TypeAndMut,
25 use rustc_span::def_id::{CrateNum, DefId};
26 use rustc_span::Symbol;
27 use rustc_target::abi::Size;
28 use rustc_target::spec::abi::Abi;
31 concurrency::{data_race, weak_memory},
32 shims::unix::FileHandler,
36 // Some global facts about the emulated machine.
37 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
38 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
39 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
40 pub const NUM_CPUS: u64 = 1;
42 /// Extra data stored with each stack frame
43 pub struct FrameData<'tcx> {
44 /// Extra data for Stacked Borrows.
45 pub stacked_borrows: Option<stacked_borrows::FrameExtra>,
47 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
48 /// called by `try`). When this frame is popped during unwinding a panic,
49 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
50 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
52 /// If `measureme` profiling is enabled, holds timing information
53 /// for the start of this frame. When we finish executing this frame,
54 /// we use this to register a completed event with `measureme`.
55 pub timing: Option<measureme::DetachedTiming>,
58 impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 // Omitting `timing`, it does not support `Debug`.
61 let FrameData { stacked_borrows, catch_unwind, timing: _ } = self;
62 f.debug_struct("FrameData")
63 .field("stacked_borrows", stacked_borrows)
64 .field("catch_unwind", catch_unwind)
69 /// Extra memory kinds
70 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
71 pub enum MiriMemoryKind {
72 /// `__rust_alloc` memory.
76 /// Windows `HeapAlloc` memory.
78 /// Memory for args, errno, and other parts of the machine-managed environment.
79 /// This memory may leak.
81 /// Memory allocated by the runtime (e.g. env vars). Separate from `Machine`
82 /// because we clean it up and leak-check it.
84 /// Globals copied from `tcx`.
85 /// This memory may leak.
87 /// Memory for extern statics.
88 /// This memory may leak.
90 /// Memory for thread-local statics.
91 /// This memory may leak.
95 impl From<MiriMemoryKind> for MemoryKind<MiriMemoryKind> {
97 fn from(kind: MiriMemoryKind) -> MemoryKind<MiriMemoryKind> {
98 MemoryKind::Machine(kind)
102 impl MayLeak for MiriMemoryKind {
104 fn may_leak(self) -> bool {
105 use self::MiriMemoryKind::*;
107 Rust | C | WinHeap | Runtime => false,
108 Machine | Global | ExternStatic | Tls => true,
113 impl fmt::Display for MiriMemoryKind {
114 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115 use self::MiriMemoryKind::*;
117 Rust => write!(f, "Rust heap"),
118 C => write!(f, "C heap"),
119 WinHeap => write!(f, "Windows heap"),
120 Machine => write!(f, "machine-managed memory"),
121 Runtime => write!(f, "language runtime memory"),
122 Global => write!(f, "global (static or const)"),
123 ExternStatic => write!(f, "extern static"),
124 Tls => write!(f, "thread-local static"),
129 /// Pointer provenance.
130 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
131 pub enum Provenance {
134 /// Stacked Borrows tag.
140 /// The "extra" information a pointer has over a regular AllocId.
141 #[derive(Copy, Clone)]
142 pub enum ProvenanceExtra {
147 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
148 static_assert_size!(Pointer<Provenance>, 24);
149 // FIXME: this would with in 24bytes but layout optimizations are not smart enough
150 // #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
151 //static_assert_size!(Pointer<Option<Provenance>>, 24);
152 #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]
153 static_assert_size!(ScalarMaybeUninit<Provenance>, 32);
155 impl interpret::Provenance for Provenance {
156 /// We use absolute addresses in the `offset` of a `Pointer<Provenance>`.
157 const OFFSET_IS_ADDR: bool = true;
159 /// We cannot err on partial overwrites, it happens too often in practice (due to unions).
160 const ERR_ON_PARTIAL_PTR_OVERWRITE: bool = false;
162 fn fmt(ptr: &Pointer<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 let (prov, addr) = ptr.into_parts(); // address is absolute
164 write!(f, "{:#x}", addr.bytes())?;
167 Provenance::Concrete { alloc_id, sb } => {
168 // Forward `alternate` flag to `alloc_id` printing.
170 write!(f, "[{:#?}]", alloc_id)?;
172 write!(f, "[{:?}]", alloc_id)?;
174 // Print Stacked Borrows tag.
175 write!(f, "{:?}", sb)?;
177 Provenance::Wildcard => {
178 write!(f, "[wildcard]")?;
185 fn get_alloc_id(self) -> Option<AllocId> {
187 Provenance::Concrete { alloc_id, .. } => Some(alloc_id),
188 Provenance::Wildcard => None,
193 impl fmt::Debug for ProvenanceExtra {
194 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196 ProvenanceExtra::Concrete(pid) => write!(f, "{pid:?}"),
197 ProvenanceExtra::Wildcard => write!(f, "<wildcard>"),
202 impl ProvenanceExtra {
203 pub fn and_then<T>(self, f: impl FnOnce(SbTag) -> Option<T>) -> Option<T> {
205 ProvenanceExtra::Concrete(pid) => f(pid),
206 ProvenanceExtra::Wildcard => None,
211 /// Extra per-allocation data
212 #[derive(Debug, Clone)]
213 pub struct AllocExtra {
214 /// Stacked Borrows state is only added if it is enabled.
215 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
216 /// Data race detection via the use of a vector-clock,
217 /// this is only added if it is enabled.
218 pub data_race: Option<data_race::AllocExtra>,
219 /// Weak memory emulation via the use of store buffers,
220 /// this is only added if it is enabled.
221 pub weak_memory: Option<weak_memory::AllocExtra>,
224 /// Precomputed layouts of primitive types
225 pub struct PrimitiveLayouts<'tcx> {
226 pub unit: TyAndLayout<'tcx>,
227 pub i8: TyAndLayout<'tcx>,
228 pub i16: TyAndLayout<'tcx>,
229 pub i32: TyAndLayout<'tcx>,
230 pub isize: TyAndLayout<'tcx>,
231 pub u8: TyAndLayout<'tcx>,
232 pub u16: TyAndLayout<'tcx>,
233 pub u32: TyAndLayout<'tcx>,
234 pub usize: TyAndLayout<'tcx>,
235 pub bool: TyAndLayout<'tcx>,
236 pub mut_raw_ptr: TyAndLayout<'tcx>,
239 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
240 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
241 let tcx = layout_cx.tcx;
242 let mut_raw_ptr = tcx.mk_ptr(TypeAndMut { ty: tcx.types.unit, mutbl: Mutability::Mut });
244 unit: layout_cx.layout_of(tcx.mk_unit())?,
245 i8: layout_cx.layout_of(tcx.types.i8)?,
246 i16: layout_cx.layout_of(tcx.types.i16)?,
247 i32: layout_cx.layout_of(tcx.types.i32)?,
248 isize: layout_cx.layout_of(tcx.types.isize)?,
249 u8: layout_cx.layout_of(tcx.types.u8)?,
250 u16: layout_cx.layout_of(tcx.types.u16)?,
251 u32: layout_cx.layout_of(tcx.types.u32)?,
252 usize: layout_cx.layout_of(tcx.types.usize)?,
253 bool: layout_cx.layout_of(tcx.types.bool)?,
254 mut_raw_ptr: layout_cx.layout_of(mut_raw_ptr)?,
259 /// The machine itself.
260 pub struct Evaluator<'mir, 'tcx> {
261 pub stacked_borrows: Option<stacked_borrows::GlobalState>,
262 pub data_race: Option<data_race::GlobalState>,
263 pub intptrcast: intptrcast::GlobalState,
265 /// Environment variables set by `setenv`.
266 /// Miri does not expose env vars from the host to the emulated program.
267 pub(crate) env_vars: EnvVars<'tcx>,
269 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
270 /// These are *pointers* to argc/argv because macOS.
271 /// We also need the full command line as one string because of Windows.
272 pub(crate) argc: Option<MemPlace<Provenance>>,
273 pub(crate) argv: Option<MemPlace<Provenance>>,
274 pub(crate) cmd_line: Option<MemPlace<Provenance>>,
277 pub(crate) tls: TlsData<'tcx>,
279 /// What should Miri do when an op requires communicating with the host,
280 /// such as accessing host env vars, random number generation, and
281 /// file system access.
282 pub(crate) isolated_op: IsolatedOp,
284 /// Whether to enforce the validity invariant.
285 pub(crate) validate: bool,
287 /// Whether to enforce [ABI](Abi) of function calls.
288 pub(crate) enforce_abi: bool,
290 /// The table of file descriptors.
291 pub(crate) file_handler: shims::unix::FileHandler,
292 /// The table of directory descriptors.
293 pub(crate) dir_handler: shims::unix::DirHandler,
295 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
296 pub(crate) time_anchor: Instant,
298 /// The set of threads.
299 pub(crate) threads: ThreadManager<'mir, 'tcx>,
301 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
302 pub(crate) layouts: PrimitiveLayouts<'tcx>,
304 /// Allocations that are considered roots of static memory (that may leak).
305 pub(crate) static_roots: Vec<AllocId>,
307 /// The `measureme` profiler used to record timing information about
308 /// the emulated program.
309 profiler: Option<measureme::Profiler>,
310 /// Used with `profiler` to cache the `StringId`s for event names
311 /// uesd with `measureme`.
312 string_cache: FxHashMap<String, measureme::StringId>,
314 /// Cache of `Instance` exported under the given `Symbol` name.
315 /// `None` means no `Instance` exported under the given name is found.
316 pub(crate) exported_symbols_cache: FxHashMap<Symbol, Option<Instance<'tcx>>>,
318 /// Whether to raise a panic in the context of the evaluated process when unsupported
319 /// functionality is encountered. If `false`, an error is propagated in the Miri application context
320 /// instead (default behavior)
321 pub(crate) panic_on_unsupported: bool,
323 /// Equivalent setting as RUST_BACKTRACE on encountering an error.
324 pub(crate) backtrace_style: BacktraceStyle,
326 /// Crates which are considered local for the purposes of error reporting.
327 pub(crate) local_crates: Vec<CrateNum>,
329 /// Mapping extern static names to their base pointer.
330 extern_statics: FxHashMap<Symbol, Pointer<Provenance>>,
332 /// The random number generator used for resolving non-determinism.
333 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
334 pub(crate) rng: RefCell<StdRng>,
336 /// The allocation IDs to report when they are being allocated
337 /// (helps for debugging memory leaks and use after free bugs).
338 tracked_alloc_ids: HashSet<AllocId>,
340 /// Controls whether alignment of memory accesses is being checked.
341 pub(crate) check_alignment: AlignmentCheck,
343 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
344 pub(crate) cmpxchg_weak_failure_rate: f64,
346 /// Corresponds to -Zmiri-mute-stdout-stderr and doesn't write the output but acts as if it succeeded.
347 pub(crate) mute_stdout_stderr: bool,
349 /// Whether weak memory emulation is enabled
350 pub(crate) weak_memory: bool,
352 /// The probability of the active thread being preempted at the end of each basic block.
353 pub(crate) preemption_rate: f64,
355 /// If `Some`, we will report the current stack every N basic blocks.
356 pub(crate) report_progress: Option<u32>,
357 /// The number of blocks that passed since the last progress report.
358 pub(crate) since_progress_report: u32,
361 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
362 pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
363 let local_crates = helpers::get_local_crates(layout_cx.tcx);
365 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
366 let profiler = config.measureme_out.as_ref().map(|out| {
367 measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
369 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
370 let stacked_borrows = config.stacked_borrows.then(|| {
371 RefCell::new(stacked_borrows::GlobalStateInner::new(
372 config.tracked_pointer_tags.clone(),
373 config.tracked_call_ids.clone(),
377 let data_race = config.data_race_detector.then(|| data_race::GlobalState::new(config));
381 intptrcast: RefCell::new(intptrcast::GlobalStateInner::new(config)),
382 // `env_vars` depends on a full interpreter so we cannot properly initialize it yet.
383 env_vars: EnvVars::default(),
387 tls: TlsData::default(),
388 isolated_op: config.isolated_op,
389 validate: config.validate,
390 enforce_abi: config.check_abi,
391 file_handler: FileHandler::new(config.mute_stdout_stderr),
392 dir_handler: Default::default(),
393 time_anchor: Instant::now(),
395 threads: ThreadManager::default(),
396 static_roots: Vec::new(),
398 string_cache: Default::default(),
399 exported_symbols_cache: FxHashMap::default(),
400 panic_on_unsupported: config.panic_on_unsupported,
401 backtrace_style: config.backtrace_style,
403 extern_statics: FxHashMap::default(),
404 rng: RefCell::new(rng),
405 tracked_alloc_ids: config.tracked_alloc_ids.clone(),
406 check_alignment: config.check_alignment,
407 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
408 mute_stdout_stderr: config.mute_stdout_stderr,
409 weak_memory: config.weak_memory_emulation,
410 preemption_rate: config.preemption_rate,
411 report_progress: config.report_progress,
412 since_progress_report: 0,
416 pub(crate) fn late_init(
417 this: &mut MiriEvalContext<'mir, 'tcx>,
419 ) -> InterpResult<'tcx> {
420 EnvVars::init(this, config)?;
421 Evaluator::init_extern_statics(this)?;
425 fn add_extern_static(
426 this: &mut MiriEvalContext<'mir, 'tcx>,
428 ptr: Pointer<Option<Provenance>>,
430 // This got just allocated, so there definitely is a pointer here.
431 let ptr = ptr.into_pointer_or_addr().unwrap();
432 this.machine.extern_statics.try_insert(Symbol::intern(name), ptr).unwrap();
435 /// Sets up the "extern statics" for this machine.
436 fn init_extern_statics(this: &mut MiriEvalContext<'mir, 'tcx>) -> InterpResult<'tcx> {
437 match this.tcx.sess.target.os.as_ref() {
440 Self::add_extern_static(
443 this.machine.env_vars.environ.unwrap().ptr,
445 // A couple zero-initialized pointer-sized extern statics.
446 // Most of them are for weak symbols, which we all set to null (indicating that the
447 // symbol is not supported, and triggering fallback code which ends up calling a
448 // syscall that we do support).
449 for name in &["__cxa_thread_atexit_impl", "getrandom", "statx", "__clock_gettime64"]
451 let layout = this.machine.layouts.usize;
452 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
453 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
454 Self::add_extern_static(this, name, place.ptr);
459 Self::add_extern_static(
462 this.machine.env_vars.environ.unwrap().ptr,
467 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
468 let layout = this.machine.layouts.u8;
469 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
470 this.write_scalar(Scalar::from_u8(0), &place.into())?;
471 Self::add_extern_static(this, "_tls_used", place.ptr);
473 _ => {} // No "extern statics" supported on this target
478 pub(crate) fn communicate(&self) -> bool {
479 self.isolated_op == IsolatedOp::Allow
482 /// Check whether the stack frame that this `FrameInfo` refers to is part of a local crate.
483 pub(crate) fn is_local(&self, frame: &FrameInfo<'_>) -> bool {
484 let def_id = frame.instance.def_id();
485 def_id.is_local() || self.local_crates.contains(&def_id.krate)
489 /// A rustc InterpCx for Miri.
490 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
492 /// A little trait that's useful to be inherited by extension traits.
493 pub trait MiriEvalContextExt<'mir, 'tcx> {
494 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
495 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
497 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
499 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
503 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
508 /// Machine hook implementations.
509 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
510 type MemoryKind = MiriMemoryKind;
511 type ExtraFnVal = Dlsym;
513 type FrameExtra = FrameData<'tcx>;
514 type AllocExtra = AllocExtra;
516 type Provenance = Provenance;
517 type ProvenanceExtra = ProvenanceExtra;
519 type MemoryMap = MonoHashMap<
521 (MemoryKind<MiriMemoryKind>, Allocation<Provenance, Self::AllocExtra>),
524 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
526 const PANIC_ON_ALLOC_FAIL: bool = false;
529 fn enforce_alignment(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
530 ecx.machine.check_alignment != AlignmentCheck::None
534 fn force_int_for_alignment_check(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
535 ecx.machine.check_alignment == AlignmentCheck::Int
539 fn enforce_validity(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
544 fn enforce_number_init(_ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
549 fn enforce_abi(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
550 ecx.machine.enforce_abi
554 fn checked_binop_checks_overflow(ecx: &MiriEvalContext<'mir, 'tcx>) -> bool {
555 ecx.tcx.sess.overflow_checks()
559 fn find_mir_or_eval_fn(
560 ecx: &mut MiriEvalContext<'mir, 'tcx>,
561 instance: ty::Instance<'tcx>,
563 args: &[OpTy<'tcx, Provenance>],
564 dest: &PlaceTy<'tcx, Provenance>,
565 ret: Option<mir::BasicBlock>,
566 unwind: StackPopUnwind,
567 ) -> InterpResult<'tcx, Option<(&'mir mir::Body<'tcx>, ty::Instance<'tcx>)>> {
568 ecx.find_mir_or_eval_fn(instance, abi, args, dest, ret, unwind)
573 ecx: &mut MiriEvalContext<'mir, 'tcx>,
576 args: &[OpTy<'tcx, Provenance>],
577 dest: &PlaceTy<'tcx, Provenance>,
578 ret: Option<mir::BasicBlock>,
579 _unwind: StackPopUnwind,
580 ) -> InterpResult<'tcx> {
581 ecx.call_dlsym(fn_val, abi, args, dest, ret)
586 ecx: &mut MiriEvalContext<'mir, 'tcx>,
587 instance: ty::Instance<'tcx>,
588 args: &[OpTy<'tcx, Provenance>],
589 dest: &PlaceTy<'tcx, Provenance>,
590 ret: Option<mir::BasicBlock>,
591 unwind: StackPopUnwind,
592 ) -> InterpResult<'tcx> {
593 ecx.call_intrinsic(instance, args, dest, ret, unwind)
598 ecx: &mut MiriEvalContext<'mir, 'tcx>,
599 msg: &mir::AssertMessage<'tcx>,
600 unwind: Option<mir::BasicBlock>,
601 ) -> InterpResult<'tcx> {
602 ecx.assert_panic(msg, unwind)
606 fn abort(_ecx: &mut MiriEvalContext<'mir, 'tcx>, msg: String) -> InterpResult<'tcx, !> {
607 throw_machine_stop!(TerminationInfo::Abort(msg))
612 ecx: &MiriEvalContext<'mir, 'tcx>,
614 left: &ImmTy<'tcx, Provenance>,
615 right: &ImmTy<'tcx, Provenance>,
616 ) -> InterpResult<'tcx, (Scalar<Provenance>, bool, ty::Ty<'tcx>)> {
617 ecx.binary_ptr_op(bin_op, left, right)
620 fn thread_local_static_base_pointer(
621 ecx: &mut MiriEvalContext<'mir, 'tcx>,
623 ) -> InterpResult<'tcx, Pointer<Provenance>> {
624 ecx.get_or_create_thread_local_alloc(def_id)
627 fn extern_static_base_pointer(
628 ecx: &MiriEvalContext<'mir, 'tcx>,
630 ) -> InterpResult<'tcx, Pointer<Provenance>> {
631 let link_name = ecx.item_link_name(def_id);
632 if let Some(&ptr) = ecx.machine.extern_statics.get(&link_name) {
633 // Various parts of the engine rely on `get_alloc_info` for size and alignment
634 // information. That uses the type information of this static.
635 // Make sure it matches the Miri allocation for this.
636 let Provenance::Concrete { alloc_id, .. } = ptr.provenance else {
637 panic!("extern_statics cannot contain wildcards")
639 let (shim_size, shim_align, _kind) = ecx.get_alloc_info(alloc_id);
640 let extern_decl_layout =
641 ecx.tcx.layout_of(ty::ParamEnv::empty().and(ecx.tcx.type_of(def_id))).unwrap();
642 if extern_decl_layout.size != shim_size || extern_decl_layout.align.abi != shim_align {
644 "`extern` static `{name}` from crate `{krate}` has been declared \
645 with a size of {decl_size} bytes and alignment of {decl_align} bytes, \
646 but Miri emulates it via an extern static shim \
647 with a size of {shim_size} bytes and alignment of {shim_align} bytes",
648 name = ecx.tcx.def_path_str(def_id),
649 krate = ecx.tcx.crate_name(def_id.krate),
650 decl_size = extern_decl_layout.size.bytes(),
651 decl_align = extern_decl_layout.align.abi.bytes(),
652 shim_size = shim_size.bytes(),
653 shim_align = shim_align.bytes(),
659 "`extern` static `{name}` from crate `{krate}` is not supported by Miri",
660 name = ecx.tcx.def_path_str(def_id),
661 krate = ecx.tcx.crate_name(def_id.krate),
666 fn adjust_allocation<'b>(
667 ecx: &MiriEvalContext<'mir, 'tcx>,
669 alloc: Cow<'b, Allocation>,
670 kind: Option<MemoryKind<Self::MemoryKind>>,
671 ) -> InterpResult<'tcx, Cow<'b, Allocation<Self::Provenance, Self::AllocExtra>>> {
672 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
673 if ecx.machine.tracked_alloc_ids.contains(&id) {
674 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(
682 let alloc = alloc.into_owned();
683 let stacks = ecx.machine.stacked_borrows.as_ref().map(|stacked_borrows| {
684 Stacks::new_allocation(
689 ecx.machine.current_span(),
692 let race_alloc = ecx.machine.data_race.as_ref().map(|data_race| {
693 data_race::AllocExtra::new_allocation(
695 &ecx.machine.threads,
700 let buffer_alloc = ecx.machine.weak_memory.then(weak_memory::AllocExtra::new_allocation);
701 let alloc: Allocation<Provenance, Self::AllocExtra> = alloc.adjust_from_tcx(
704 stacked_borrows: stacks.map(RefCell::new),
705 data_race: race_alloc,
706 weak_memory: buffer_alloc,
708 |ptr| ecx.global_base_pointer(ptr),
710 Ok(Cow::Owned(alloc))
713 fn adjust_alloc_base_pointer(
714 ecx: &MiriEvalContext<'mir, 'tcx>,
715 ptr: Pointer<AllocId>,
716 ) -> Pointer<Provenance> {
717 if cfg!(debug_assertions) {
718 // The machine promises to never call us on thread-local or extern statics.
719 let alloc_id = ptr.provenance;
720 match ecx.tcx.try_get_global_alloc(alloc_id) {
721 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_thread_local_static(def_id) => {
722 panic!("adjust_alloc_base_pointer called on thread-local static")
724 Some(GlobalAlloc::Static(def_id)) if ecx.tcx.is_foreign_item(def_id) => {
725 panic!("adjust_alloc_base_pointer called on extern static")
730 let absolute_addr = intptrcast::GlobalStateInner::rel_ptr_to_addr(ecx, ptr);
731 let sb_tag = if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
732 stacked_borrows.borrow_mut().base_ptr_tag(ptr.provenance)
734 // Value does not matter, SB is disabled
738 Provenance::Concrete { alloc_id: ptr.provenance, sb: sb_tag },
739 Size::from_bytes(absolute_addr),
744 fn ptr_from_addr_cast(
745 ecx: &MiriEvalContext<'mir, 'tcx>,
747 ) -> InterpResult<'tcx, Pointer<Option<Self::Provenance>>> {
748 intptrcast::GlobalStateInner::ptr_from_addr_cast(ecx, addr)
752 ecx: &mut InterpCx<'mir, 'tcx, Self>,
753 ptr: Pointer<Self::Provenance>,
754 ) -> InterpResult<'tcx> {
755 match ptr.provenance {
756 Provenance::Concrete { alloc_id, sb } =>
757 intptrcast::GlobalStateInner::expose_ptr(ecx, alloc_id, sb),
758 Provenance::Wildcard => {
759 // No need to do anything for wildcard pointers as
760 // their provenances have already been previously exposed.
766 /// Convert a pointer with provenance into an allocation-offset pair,
767 /// or a `None` with an absolute address if that conversion is not possible.
769 ecx: &MiriEvalContext<'mir, 'tcx>,
770 ptr: Pointer<Self::Provenance>,
771 ) -> Option<(AllocId, Size, Self::ProvenanceExtra)> {
772 let rel = intptrcast::GlobalStateInner::abs_ptr_to_rel(ecx, ptr);
774 rel.map(|(alloc_id, size)| {
775 let sb = match ptr.provenance {
776 Provenance::Concrete { sb, .. } => ProvenanceExtra::Concrete(sb),
777 Provenance::Wildcard => ProvenanceExtra::Wildcard,
787 alloc_extra: &AllocExtra,
788 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
790 ) -> InterpResult<'tcx> {
791 if let Some(data_race) = &alloc_extra.data_race {
795 machine.data_race.as_ref().unwrap(),
799 if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
800 stacked_borrows.borrow_mut().memory_read(
804 machine.stacked_borrows.as_ref().unwrap(),
805 machine.current_span(),
809 if let Some(weak_memory) = &alloc_extra.weak_memory {
810 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
819 alloc_extra: &mut AllocExtra,
820 (alloc_id, prov_extra): (AllocId, Self::ProvenanceExtra),
822 ) -> InterpResult<'tcx> {
823 if let Some(data_race) = &mut alloc_extra.data_race {
827 machine.data_race.as_mut().unwrap(),
831 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
832 stacked_borrows.get_mut().memory_written(
836 machine.stacked_borrows.as_ref().unwrap(),
837 machine.current_span(),
841 if let Some(weak_memory) = &alloc_extra.weak_memory {
842 weak_memory.memory_accessed(range, machine.data_race.as_ref().unwrap());
848 fn memory_deallocated(
851 alloc_extra: &mut AllocExtra,
852 (alloc_id, prove_extra): (AllocId, Self::ProvenanceExtra),
854 ) -> InterpResult<'tcx> {
855 if machine.tracked_alloc_ids.contains(&alloc_id) {
856 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(alloc_id));
858 if let Some(data_race) = &mut alloc_extra.data_race {
859 data_race.deallocate(
862 machine.data_race.as_mut().unwrap(),
866 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
867 stacked_borrows.get_mut().memory_deallocated(
871 machine.stacked_borrows.as_ref().unwrap(),
881 ecx: &mut InterpCx<'mir, 'tcx, Self>,
882 kind: mir::RetagKind,
883 place: &PlaceTy<'tcx, Provenance>,
884 ) -> InterpResult<'tcx> {
885 if ecx.machine.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
890 ecx: &mut InterpCx<'mir, 'tcx, Self>,
891 frame: Frame<'mir, 'tcx, Provenance>,
892 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Provenance, FrameData<'tcx>>> {
893 // Start recording our event before doing anything else
894 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
895 let fn_name = frame.instance.to_string();
896 let entry = ecx.machine.string_cache.entry(fn_name.clone());
897 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
899 Some(profiler.start_recording_interval_event_detached(
901 measureme::EventId::from_label(*name),
902 ecx.get_active_thread().to_u32(),
908 let stacked_borrows = ecx.machine.stacked_borrows.as_ref();
910 let extra = FrameData {
911 stacked_borrows: stacked_borrows.map(|sb| sb.borrow_mut().new_frame()),
915 Ok(frame.with_extra(extra))
919 ecx: &'a InterpCx<'mir, 'tcx, Self>,
920 ) -> &'a [Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>] {
921 ecx.active_thread_stack()
925 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
926 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::Provenance, Self::FrameExtra>> {
927 ecx.active_thread_stack_mut()
930 fn before_terminator(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
931 // Possibly report our progress.
932 if let Some(report_progress) = ecx.machine.report_progress {
933 if ecx.machine.since_progress_report >= report_progress {
934 register_diagnostic(NonHaltingDiagnostic::ProgressReport);
935 ecx.machine.since_progress_report = 0;
937 // Cannot overflow, since it is strictly less than `report_progress`.
938 ecx.machine.since_progress_report += 1;
940 // These are our preemption points.
941 ecx.maybe_preempt_active_thread();
946 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
947 if ecx.machine.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
952 ecx: &mut InterpCx<'mir, 'tcx, Self>,
953 mut frame: Frame<'mir, 'tcx, Provenance, FrameData<'tcx>>,
955 ) -> InterpResult<'tcx, StackPopJump> {
956 let timing = frame.extra.timing.take();
957 if let Some(stacked_borrows) = &ecx.machine.stacked_borrows {
958 stacked_borrows.borrow_mut().end_call(&frame.extra);
960 let res = ecx.handle_stack_pop_unwind(frame.extra, unwinding);
961 if let Some(profiler) = ecx.machine.profiler.as_ref() {
962 profiler.finish_recording_interval_event(timing.unwrap());