1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
7 use std::num::NonZeroU64;
8 use std::time::Instant;
11 use rand::rngs::StdRng;
12 use rand::SeedableRng;
13 use std::collections::hash_map::Entry;
14 use measureme::{Profiler, StringId, EventId, DetachedTiming};
16 use rustc_data_structures::fx::FxHashMap;
21 layout::{LayoutCx, LayoutError, TyAndLayout},
25 use rustc_span::def_id::DefId;
26 use rustc_span::symbol::{sym, Symbol};
27 use rustc_target::abi::{LayoutOf, Size};
28 use rustc_target::spec::abi::Abi;
32 // Some global facts about the emulated machine.
33 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
34 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
35 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
36 pub const NUM_CPUS: u64 = 1;
38 /// Extra data stored with each stack frame
39 pub struct FrameData<'tcx> {
40 /// Extra data for Stacked Borrows.
41 pub call_id: stacked_borrows::CallId,
43 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
44 /// called by `try`). When this frame is popped during unwinding a panic,
45 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
46 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
48 pub timing: Option<DetachedTiming>,
51 /// Extra memory kinds
52 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
53 pub enum MiriMemoryKind {
54 /// `__rust_alloc` memory.
58 /// Windows `HeapAlloc` memory.
60 /// Memory for args, errno, and other parts of the machine-managed environment.
61 /// This memory may leak.
63 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
65 /// Globals copied from `tcx`.
66 /// This memory may leak.
68 /// Memory for extern statics.
69 /// This memory may leak.
71 /// Memory for thread-local statics.
72 /// This memory may leak.
76 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
78 fn into(self) -> MemoryKind<MiriMemoryKind> {
79 MemoryKind::Machine(self)
83 impl MayLeak for MiriMemoryKind {
85 fn may_leak(self) -> bool {
86 use self::MiriMemoryKind::*;
88 Rust | C | WinHeap | Env => false,
89 Machine | Global | ExternStatic | Tls => true,
94 impl fmt::Display for MiriMemoryKind {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 use self::MiriMemoryKind::*;
98 Rust => write!(f, "Rust heap"),
99 C => write!(f, "C heap"),
100 WinHeap => write!(f, "Windows heap"),
101 Machine => write!(f, "machine-managed memory"),
102 Env => write!(f, "environment variable"),
103 Global => write!(f, "global (static or const)"),
104 ExternStatic => write!(f, "extern static"),
105 Tls => write!(f, "thread-local static"),
110 /// Extra per-allocation data
111 #[derive(Debug, Clone)]
112 pub struct AllocExtra {
113 /// Stacked Borrows state is only added if it is enabled.
114 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
115 /// Data race detection via the use of a vector-clock,
116 /// this is only added if it is enabled.
117 pub data_race: Option<data_race::AllocExtra>,
120 /// Extra global memory data
122 pub struct MemoryExtra {
123 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
124 pub data_race: Option<data_race::MemoryExtra>,
125 pub intptrcast: intptrcast::MemoryExtra,
127 /// Mapping extern static names to their canonical allocation.
128 extern_statics: FxHashMap<Symbol, AllocId>,
130 /// The random number generator used for resolving non-determinism.
131 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
132 pub(crate) rng: RefCell<StdRng>,
134 /// An allocation ID to report when it is being allocated
135 /// (helps for debugging memory leaks and use after free bugs).
136 tracked_alloc_id: Option<AllocId>,
138 /// Controls whether alignment of memory accesses is being checked.
139 pub(crate) check_alignment: AlignmentCheck,
141 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
142 pub(crate) cmpxchg_weak_failure_rate: f64,
146 pub fn new(config: &MiriConfig) -> Self {
147 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
148 let stacked_borrows = if config.stacked_borrows {
149 Some(RefCell::new(stacked_borrows::GlobalState::new(
150 config.tracked_pointer_tag,
151 config.tracked_call_id,
158 if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
162 intptrcast: Default::default(),
163 extern_statics: FxHashMap::default(),
164 rng: RefCell::new(rng),
165 tracked_alloc_id: config.tracked_alloc_id,
166 check_alignment: config.check_alignment,
167 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
171 fn add_extern_static<'tcx, 'mir>(
172 this: &mut MiriEvalContext<'mir, 'tcx>,
176 let ptr = ptr.assert_ptr();
177 assert_eq!(ptr.offset, Size::ZERO);
178 this.memory.extra.extern_statics.try_insert(Symbol::intern(name), ptr.alloc_id).unwrap();
181 /// Sets up the "extern statics" for this machine.
182 pub fn init_extern_statics<'tcx, 'mir>(
183 this: &mut MiriEvalContext<'mir, 'tcx>,
184 ) -> InterpResult<'tcx> {
185 match this.tcx.sess.target.os.as_str() {
187 // "__cxa_thread_atexit_impl"
188 // This should be all-zero, pointer-sized.
189 let layout = this.machine.layouts.usize;
190 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
191 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
192 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
194 Self::add_extern_static(
197 this.machine.env_vars.environ.unwrap().ptr,
202 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
203 let layout = this.machine.layouts.u8;
204 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
205 this.write_scalar(Scalar::from_u8(0), &place.into())?;
206 Self::add_extern_static(this, "_tls_used", place.ptr);
208 _ => {} // No "extern statics" supported on this target
214 /// Precomputed layouts of primitive types
215 pub struct PrimitiveLayouts<'tcx> {
216 pub unit: TyAndLayout<'tcx>,
217 pub i8: TyAndLayout<'tcx>,
218 pub i32: TyAndLayout<'tcx>,
219 pub isize: TyAndLayout<'tcx>,
220 pub u8: TyAndLayout<'tcx>,
221 pub u32: TyAndLayout<'tcx>,
222 pub usize: TyAndLayout<'tcx>,
225 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
226 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
228 unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
229 i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
230 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
231 isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
232 u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
233 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
234 usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
239 /// The machine itself.
240 pub struct Evaluator<'mir, 'tcx> {
241 /// Environment variables set by `setenv`.
242 /// Miri does not expose env vars from the host to the emulated program.
243 pub(crate) env_vars: EnvVars<'tcx>,
245 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
246 /// These are *pointers* to argc/argv because macOS.
247 /// We also need the full command line as one string because of Windows.
248 pub(crate) argc: Option<Scalar<Tag>>,
249 pub(crate) argv: Option<Scalar<Tag>>,
250 pub(crate) cmd_line: Option<Scalar<Tag>>,
253 pub(crate) tls: TlsData<'tcx>,
255 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
256 /// and random number generation is delegated to the host.
257 pub(crate) communicate: bool,
259 /// Whether to enforce the validity invariant.
260 pub(crate) validate: bool,
262 pub(crate) file_handler: shims::posix::FileHandler,
263 pub(crate) dir_handler: shims::posix::DirHandler,
265 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
266 pub(crate) time_anchor: Instant,
268 /// The set of threads.
269 pub(crate) threads: ThreadManager<'mir, 'tcx>,
271 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
272 pub(crate) layouts: PrimitiveLayouts<'tcx>,
274 /// Allocations that are considered roots of static memory (that may leak).
275 pub(crate) static_roots: Vec<AllocId>,
277 profiler: Option<Profiler>,
278 string_cache: FxHashMap<String, StringId>,
281 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
284 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
287 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
288 let profiler = config.measureme_out.as_ref().map(|out| {
289 Profiler::new(out).expect("Couldn't create `measureme` profiler")
292 // `env_vars` could be initialized properly here if `Memory` were available before
293 // calling this method.
294 env_vars: EnvVars::default(),
298 tls: TlsData::default(),
299 communicate: config.communicate,
300 validate: config.validate,
301 file_handler: Default::default(),
302 dir_handler: Default::default(),
303 time_anchor: Instant::now(),
305 threads: ThreadManager::default(),
306 static_roots: Vec::new(),
308 string_cache: Default::default(),
313 /// A rustc InterpCx for Miri.
314 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
316 /// A little trait that's useful to be inherited by extension traits.
317 pub trait MiriEvalContextExt<'mir, 'tcx> {
318 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
319 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
321 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
323 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
327 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
332 /// Machine hook implementations.
333 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
334 type MemoryKind = MiriMemoryKind;
336 type FrameExtra = FrameData<'tcx>;
337 type MemoryExtra = MemoryExtra;
338 type AllocExtra = AllocExtra;
339 type PointerTag = Tag;
340 type ExtraFnVal = Dlsym;
343 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
345 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
348 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
349 memory_extra.check_alignment != AlignmentCheck::None
353 fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
354 memory_extra.check_alignment == AlignmentCheck::Int
358 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
363 fn find_mir_or_eval_fn(
364 ecx: &mut InterpCx<'mir, 'tcx, Self>,
365 instance: ty::Instance<'tcx>,
367 args: &[OpTy<'tcx, Tag>],
368 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
369 unwind: StackPopUnwind,
370 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
371 ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
376 ecx: &mut InterpCx<'mir, 'tcx, Self>,
379 args: &[OpTy<'tcx, Tag>],
380 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
381 _unwind: StackPopUnwind,
382 ) -> InterpResult<'tcx> {
383 ecx.call_dlsym(fn_val, abi, args, ret)
388 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
389 instance: ty::Instance<'tcx>,
390 args: &[OpTy<'tcx, Tag>],
391 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
392 unwind: StackPopUnwind,
393 ) -> InterpResult<'tcx> {
394 ecx.call_intrinsic(instance, args, ret, unwind)
399 ecx: &mut InterpCx<'mir, 'tcx, Self>,
400 msg: &mir::AssertMessage<'tcx>,
401 unwind: Option<mir::BasicBlock>,
402 ) -> InterpResult<'tcx> {
403 ecx.assert_panic(msg, unwind)
407 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
408 throw_machine_stop!(TerminationInfo::Abort(msg))
413 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
415 left: &ImmTy<'tcx, Tag>,
416 right: &ImmTy<'tcx, Tag>,
417 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
418 ecx.binary_ptr_op(bin_op, left, right)
422 ecx: &mut InterpCx<'mir, 'tcx, Self>,
423 dest: &PlaceTy<'tcx, Tag>,
424 ) -> InterpResult<'tcx> {
425 trace!("box_alloc for {:?}", dest.layout.ty);
426 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
427 // First argument: `size`.
428 // (`0` is allowed here -- this is expected to be handled by the lang item).
429 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
431 // Second argument: `align`.
432 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
434 // Call the `exchange_malloc` lang item.
435 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
436 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
440 &[size.into(), align.into()],
442 // Don't do anything when we are done. The `statement()` function will increment
443 // the old stack frame's stmt counter to the next statement, which means that when
444 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
445 StackPopCleanup::None { cleanup: true },
450 fn thread_local_static_alloc_id(
451 ecx: &mut InterpCx<'mir, 'tcx, Self>,
453 ) -> InterpResult<'tcx, AllocId> {
454 ecx.get_or_create_thread_local_alloc_id(def_id)
457 fn extern_static_alloc_id(
458 memory: &Memory<'mir, 'tcx, Self>,
460 ) -> InterpResult<'tcx, AllocId> {
461 let attrs = memory.tcx.get_attrs(def_id);
462 let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
464 None => memory.tcx.item_name(def_id),
466 if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
469 throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
473 fn init_allocation_extra<'b>(
474 memory_extra: &MemoryExtra,
476 alloc: Cow<'b, Allocation>,
477 kind: Option<MemoryKind<Self::MemoryKind>>,
478 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
479 if Some(id) == memory_extra.tracked_alloc_id {
480 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
483 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
484 let alloc = alloc.into_owned();
485 let (stacks, base_tag) = if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
486 let (stacks, base_tag) =
487 Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind);
488 (Some(stacks), base_tag)
490 // No stacks, no tag.
491 (None, Tag::Untagged)
493 let race_alloc = if let Some(data_race) = &memory_extra.data_race {
494 Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
498 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
499 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
501 if let Some(stacked_borrows) = &mut stacked_borrows {
502 // Only globals may already contain pointers at this point
503 assert_eq!(kind, MiriMemoryKind::Global.into());
504 stacked_borrows.global_base_ptr(alloc)
509 AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
511 (Cow::Owned(alloc), base_tag)
516 memory_extra: &Self::MemoryExtra,
517 alloc_extra: &AllocExtra,
520 ) -> InterpResult<'tcx> {
521 if let Some(data_race) = &alloc_extra.data_race {
522 data_race.read(ptr, size, memory_extra.data_race.as_ref().unwrap())?;
524 if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
525 stacked_borrows.memory_read(ptr, size, memory_extra.stacked_borrows.as_ref().unwrap())
533 memory_extra: &mut Self::MemoryExtra,
534 alloc_extra: &mut AllocExtra,
537 ) -> InterpResult<'tcx> {
538 if let Some(data_race) = &mut alloc_extra.data_race {
539 data_race.write(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
541 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
542 stacked_borrows.memory_written(
545 memory_extra.stacked_borrows.as_mut().unwrap(),
553 fn memory_deallocated(
554 memory_extra: &mut Self::MemoryExtra,
555 alloc_extra: &mut AllocExtra,
558 ) -> InterpResult<'tcx> {
559 if Some(ptr.alloc_id) == memory_extra.tracked_alloc_id {
560 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(ptr.alloc_id));
562 if let Some(data_race) = &mut alloc_extra.data_race {
563 data_race.deallocate(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
565 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
566 stacked_borrows.memory_deallocated(
569 memory_extra.stacked_borrows.as_mut().unwrap(),
576 fn after_static_mem_initialized(
577 ecx: &mut InterpCx<'mir, 'tcx, Self>,
578 ptr: Pointer<Self::PointerTag>,
580 ) -> InterpResult<'tcx> {
581 if ecx.memory.extra.data_race.is_some() {
582 ecx.reset_vector_clocks(ptr, size)?;
588 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
589 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
590 stacked_borrows.borrow_mut().global_base_ptr(id)
598 ecx: &mut InterpCx<'mir, 'tcx, Self>,
599 kind: mir::RetagKind,
600 place: &PlaceTy<'tcx, Tag>,
601 ) -> InterpResult<'tcx> {
602 if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
607 ecx: &mut InterpCx<'mir, 'tcx, Self>,
608 frame: Frame<'mir, 'tcx, Tag>,
609 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
610 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
611 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
612 stacked_borrows.borrow_mut().new_call()
614 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
615 let fn_name = frame.instance.to_string();
616 let entry = ecx.machine.string_cache.entry(fn_name.clone());
617 let name = match entry {
618 Entry::Occupied(e) => *e.get(),
619 Entry::Vacant(e) => {
620 *e.insert(profiler.alloc_string(&*fn_name))
624 Some(profiler.start_recording_interval_event_detached(
626 EventId::from_label(name),
633 let extra = FrameData { call_id, catch_unwind: None, timing };
634 Ok(frame.with_extra(extra))
638 ecx: &'a InterpCx<'mir, 'tcx, Self>,
639 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
640 ecx.active_thread_stack()
644 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
645 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
646 ecx.active_thread_stack_mut()
650 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
651 if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
656 ecx: &mut InterpCx<'mir, 'tcx, Self>,
657 mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
659 ) -> InterpResult<'tcx, StackPopJump> {
660 let timing = frame.extra.timing.take();
661 let res = ecx.handle_stack_pop(frame.extra, unwinding);
662 if let Some(profiler) = ecx.machine.profiler.as_ref() {
663 profiler.finish_recording_interval_event(timing.unwrap());
670 memory: &Memory<'mir, 'tcx, Self>,
672 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
673 intptrcast::GlobalState::int_to_ptr(int, memory)
678 memory: &Memory<'mir, 'tcx, Self>,
679 ptr: Pointer<Self::PointerTag>,
680 ) -> InterpResult<'tcx, u64> {
681 intptrcast::GlobalState::ptr_to_int(ptr, memory)