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;
14 use rustc_data_structures::fx::FxHashMap;
19 layout::{LayoutCx, LayoutError, TyAndLayout},
23 use rustc_span::def_id::DefId;
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_target::abi::{LayoutOf, Size};
26 use rustc_target::spec::abi::Abi;
30 // Some global facts about the emulated machine.
31 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
32 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
33 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
34 pub const NUM_CPUS: u64 = 1;
36 /// Extra data stored with each stack frame
37 pub struct FrameData<'tcx> {
38 /// Extra data for Stacked Borrows.
39 pub call_id: stacked_borrows::CallId,
41 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
42 /// called by `try`). When this frame is popped during unwinding a panic,
43 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
44 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
46 /// If `measureme` profiling is enabled, holds timing information
47 /// for the start of this frame. When we finish executing this frame,
48 /// we use this to register a completed event with `measureme`.
49 pub timing: Option<measureme::DetachedTiming>,
52 impl<'tcx> std::fmt::Debug for FrameData<'tcx> {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("FrameData")
55 .field("call_id", &self.call_id)
56 .field("catch_unwind", &self.catch_unwind)
61 /// Extra memory kinds
62 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
63 pub enum MiriMemoryKind {
64 /// `__rust_alloc` memory.
68 /// Windows `HeapAlloc` memory.
70 /// Memory for args, errno, and other parts of the machine-managed environment.
71 /// This memory may leak.
73 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
75 /// Globals copied from `tcx`.
76 /// This memory may leak.
78 /// Memory for extern statics.
79 /// This memory may leak.
81 /// Memory for thread-local statics.
82 /// This memory may leak.
86 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
88 fn into(self) -> MemoryKind<MiriMemoryKind> {
89 MemoryKind::Machine(self)
93 impl MayLeak for MiriMemoryKind {
95 fn may_leak(self) -> bool {
96 use self::MiriMemoryKind::*;
98 Rust | C | WinHeap | Env => false,
99 Machine | Global | ExternStatic | Tls => true,
104 impl fmt::Display for MiriMemoryKind {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 use self::MiriMemoryKind::*;
108 Rust => write!(f, "Rust heap"),
109 C => write!(f, "C heap"),
110 WinHeap => write!(f, "Windows heap"),
111 Machine => write!(f, "machine-managed memory"),
112 Env => write!(f, "environment variable"),
113 Global => write!(f, "global (static or const)"),
114 ExternStatic => write!(f, "extern static"),
115 Tls => write!(f, "thread-local static"),
120 /// Extra per-allocation data
121 #[derive(Debug, Clone)]
122 pub struct AllocExtra {
123 /// Stacked Borrows state is only added if it is enabled.
124 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
125 /// Data race detection via the use of a vector-clock,
126 /// this is only added if it is enabled.
127 pub data_race: Option<data_race::AllocExtra>,
130 /// Extra global memory data
132 pub struct MemoryExtra {
133 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
134 pub data_race: Option<data_race::MemoryExtra>,
135 pub intptrcast: intptrcast::MemoryExtra,
137 /// Mapping extern static names to their canonical allocation.
138 extern_statics: FxHashMap<Symbol, AllocId>,
140 /// The random number generator used for resolving non-determinism.
141 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
142 pub(crate) rng: RefCell<StdRng>,
144 /// An allocation ID to report when it is being allocated
145 /// (helps for debugging memory leaks and use after free bugs).
146 tracked_alloc_id: Option<AllocId>,
148 /// Controls whether alignment of memory accesses is being checked.
149 pub(crate) check_alignment: AlignmentCheck,
151 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
152 pub(crate) cmpxchg_weak_failure_rate: f64,
156 pub fn new(config: &MiriConfig) -> Self {
157 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
158 let stacked_borrows = if config.stacked_borrows {
159 Some(RefCell::new(stacked_borrows::GlobalState::new(
160 config.tracked_pointer_tag,
161 config.tracked_call_id,
168 if config.data_race_detector { Some(data_race::GlobalState::new()) } else { None };
172 intptrcast: Default::default(),
173 extern_statics: FxHashMap::default(),
174 rng: RefCell::new(rng),
175 tracked_alloc_id: config.tracked_alloc_id,
176 check_alignment: config.check_alignment,
177 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
181 fn add_extern_static<'tcx, 'mir>(
182 this: &mut MiriEvalContext<'mir, 'tcx>,
186 let ptr = ptr.assert_ptr();
187 assert_eq!(ptr.offset, Size::ZERO);
188 this.memory.extra.extern_statics.try_insert(Symbol::intern(name), ptr.alloc_id).unwrap();
191 /// Sets up the "extern statics" for this machine.
192 pub fn init_extern_statics<'tcx, 'mir>(
193 this: &mut MiriEvalContext<'mir, 'tcx>,
194 ) -> InterpResult<'tcx> {
195 match this.tcx.sess.target.os.as_str() {
197 // "__cxa_thread_atexit_impl"
198 // This should be all-zero, pointer-sized.
199 let layout = this.machine.layouts.usize;
200 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
201 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
202 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
204 Self::add_extern_static(
207 this.machine.env_vars.environ.unwrap().ptr,
212 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
213 let layout = this.machine.layouts.u8;
214 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
215 this.write_scalar(Scalar::from_u8(0), &place.into())?;
216 Self::add_extern_static(this, "_tls_used", place.ptr);
218 _ => {} // No "extern statics" supported on this target
224 /// Precomputed layouts of primitive types
225 pub struct PrimitiveLayouts<'tcx> {
226 pub unit: TyAndLayout<'tcx>,
227 pub i8: TyAndLayout<'tcx>,
228 pub i32: TyAndLayout<'tcx>,
229 pub isize: TyAndLayout<'tcx>,
230 pub u8: TyAndLayout<'tcx>,
231 pub u32: TyAndLayout<'tcx>,
232 pub usize: TyAndLayout<'tcx>,
235 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
236 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
238 unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
239 i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
240 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
241 isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
242 u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
243 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
244 usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
249 /// The machine itself.
250 pub struct Evaluator<'mir, 'tcx> {
251 /// Environment variables set by `setenv`.
252 /// Miri does not expose env vars from the host to the emulated program.
253 pub(crate) env_vars: EnvVars<'tcx>,
255 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
256 /// These are *pointers* to argc/argv because macOS.
257 /// We also need the full command line as one string because of Windows.
258 pub(crate) argc: Option<Scalar<Tag>>,
259 pub(crate) argv: Option<Scalar<Tag>>,
260 pub(crate) cmd_line: Option<Scalar<Tag>>,
263 pub(crate) tls: TlsData<'tcx>,
265 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
266 /// and random number generation is delegated to the host.
267 pub(crate) communicate: bool,
269 /// Whether to enforce the validity invariant.
270 pub(crate) validate: bool,
272 pub(crate) file_handler: shims::posix::FileHandler,
273 pub(crate) dir_handler: shims::posix::DirHandler,
275 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
276 pub(crate) time_anchor: Instant,
278 /// The set of threads.
279 pub(crate) threads: ThreadManager<'mir, 'tcx>,
281 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
282 pub(crate) layouts: PrimitiveLayouts<'tcx>,
284 /// Allocations that are considered roots of static memory (that may leak).
285 pub(crate) static_roots: Vec<AllocId>,
287 /// The `measureme` profiler used to record timing information about
288 /// the emulated program.
289 profiler: Option<measureme::Profiler>,
290 /// Used with `profiler` to cache the `StringId`s for event names
291 /// uesd with `measureme`.
292 string_cache: FxHashMap<String, measureme::StringId>,
295 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
296 pub(crate) fn new(config: &MiriConfig, layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Self {
298 PrimitiveLayouts::new(layout_cx).expect("Couldn't get layouts of primitive types");
299 let profiler = config.measureme_out.as_ref().map(|out| {
300 measureme::Profiler::new(out).expect("Couldn't create `measureme` profiler")
303 // `env_vars` could be initialized properly here if `Memory` were available before
304 // calling this method.
305 env_vars: EnvVars::default(),
309 tls: TlsData::default(),
310 communicate: config.communicate,
311 validate: config.validate,
312 file_handler: Default::default(),
313 dir_handler: Default::default(),
314 time_anchor: Instant::now(),
316 threads: ThreadManager::default(),
317 static_roots: Vec::new(),
319 string_cache: Default::default(),
324 /// A rustc InterpCx for Miri.
325 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
327 /// A little trait that's useful to be inherited by extension traits.
328 pub trait MiriEvalContextExt<'mir, 'tcx> {
329 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
330 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
332 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
334 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
338 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
343 /// Machine hook implementations.
344 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
345 type MemoryKind = MiriMemoryKind;
347 type FrameExtra = FrameData<'tcx>;
348 type MemoryExtra = MemoryExtra;
349 type AllocExtra = AllocExtra;
350 type PointerTag = Tag;
351 type ExtraFnVal = Dlsym;
354 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
356 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
359 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
360 memory_extra.check_alignment != AlignmentCheck::None
364 fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
365 memory_extra.check_alignment == AlignmentCheck::Int
369 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
374 fn find_mir_or_eval_fn(
375 ecx: &mut InterpCx<'mir, 'tcx, Self>,
376 instance: ty::Instance<'tcx>,
378 args: &[OpTy<'tcx, Tag>],
379 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
380 unwind: StackPopUnwind,
381 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
382 ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
387 ecx: &mut InterpCx<'mir, 'tcx, Self>,
390 args: &[OpTy<'tcx, Tag>],
391 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
392 _unwind: StackPopUnwind,
393 ) -> InterpResult<'tcx> {
394 ecx.call_dlsym(fn_val, abi, args, ret)
399 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
400 instance: ty::Instance<'tcx>,
401 args: &[OpTy<'tcx, Tag>],
402 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
403 unwind: StackPopUnwind,
404 ) -> InterpResult<'tcx> {
405 ecx.call_intrinsic(instance, args, ret, unwind)
410 ecx: &mut InterpCx<'mir, 'tcx, Self>,
411 msg: &mir::AssertMessage<'tcx>,
412 unwind: Option<mir::BasicBlock>,
413 ) -> InterpResult<'tcx> {
414 ecx.assert_panic(msg, unwind)
418 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
419 throw_machine_stop!(TerminationInfo::Abort(msg))
424 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
426 left: &ImmTy<'tcx, Tag>,
427 right: &ImmTy<'tcx, Tag>,
428 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
429 ecx.binary_ptr_op(bin_op, left, right)
433 ecx: &mut InterpCx<'mir, 'tcx, Self>,
434 dest: &PlaceTy<'tcx, Tag>,
435 ) -> InterpResult<'tcx> {
436 trace!("box_alloc for {:?}", dest.layout.ty);
437 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
438 // First argument: `size`.
439 // (`0` is allowed here -- this is expected to be handled by the lang item).
440 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
442 // Second argument: `align`.
443 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
445 // Call the `exchange_malloc` lang item.
446 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
447 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
451 &[size.into(), align.into()],
453 // Don't do anything when we are done. The `statement()` function will increment
454 // the old stack frame's stmt counter to the next statement, which means that when
455 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
456 StackPopCleanup::None { cleanup: true },
461 fn thread_local_static_alloc_id(
462 ecx: &mut InterpCx<'mir, 'tcx, Self>,
464 ) -> InterpResult<'tcx, AllocId> {
465 ecx.get_or_create_thread_local_alloc_id(def_id)
468 fn extern_static_alloc_id(
469 memory: &Memory<'mir, 'tcx, Self>,
471 ) -> InterpResult<'tcx, AllocId> {
472 let attrs = memory.tcx.get_attrs(def_id);
473 let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
475 None => memory.tcx.item_name(def_id),
477 if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
480 throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
484 fn init_allocation_extra<'b>(
485 memory_extra: &MemoryExtra,
487 alloc: Cow<'b, Allocation>,
488 kind: Option<MemoryKind<Self::MemoryKind>>,
489 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
490 if Some(id) == memory_extra.tracked_alloc_id {
491 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
494 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
495 let alloc = alloc.into_owned();
496 let (stacks, base_tag) = if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
497 let (stacks, base_tag) =
498 Stacks::new_allocation(id, alloc.size(), stacked_borrows, kind);
499 (Some(stacks), base_tag)
501 // No stacks, no tag.
502 (None, Tag::Untagged)
504 let race_alloc = if let Some(data_race) = &memory_extra.data_race {
505 Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size(), kind))
509 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
510 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
512 if let Some(stacked_borrows) = &mut stacked_borrows {
513 // Only globals may already contain pointers at this point
514 assert_eq!(kind, MiriMemoryKind::Global.into());
515 stacked_borrows.global_base_ptr(alloc)
520 AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
522 (Cow::Owned(alloc), base_tag)
527 memory_extra: &Self::MemoryExtra,
528 alloc_extra: &AllocExtra,
531 ) -> InterpResult<'tcx> {
532 if let Some(data_race) = &alloc_extra.data_race {
533 data_race.read(ptr, size, memory_extra.data_race.as_ref().unwrap())?;
535 if let Some(stacked_borrows) = &alloc_extra.stacked_borrows {
536 stacked_borrows.memory_read(ptr, size, memory_extra.stacked_borrows.as_ref().unwrap())
544 memory_extra: &mut Self::MemoryExtra,
545 alloc_extra: &mut AllocExtra,
548 ) -> InterpResult<'tcx> {
549 if let Some(data_race) = &mut alloc_extra.data_race {
550 data_race.write(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
552 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
553 stacked_borrows.memory_written(
556 memory_extra.stacked_borrows.as_mut().unwrap(),
564 fn memory_deallocated(
565 memory_extra: &mut Self::MemoryExtra,
566 alloc_extra: &mut AllocExtra,
569 ) -> InterpResult<'tcx> {
570 if Some(ptr.alloc_id) == memory_extra.tracked_alloc_id {
571 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(ptr.alloc_id));
573 if let Some(data_race) = &mut alloc_extra.data_race {
574 data_race.deallocate(ptr, size, memory_extra.data_race.as_mut().unwrap())?;
576 if let Some(stacked_borrows) = &mut alloc_extra.stacked_borrows {
577 stacked_borrows.memory_deallocated(
580 memory_extra.stacked_borrows.as_mut().unwrap(),
587 fn after_static_mem_initialized(
588 ecx: &mut InterpCx<'mir, 'tcx, Self>,
589 ptr: Pointer<Self::PointerTag>,
591 ) -> InterpResult<'tcx> {
592 if ecx.memory.extra.data_race.is_some() {
593 ecx.reset_vector_clocks(ptr, size)?;
599 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
600 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
601 stacked_borrows.borrow_mut().global_base_ptr(id)
609 ecx: &mut InterpCx<'mir, 'tcx, Self>,
610 kind: mir::RetagKind,
611 place: &PlaceTy<'tcx, Tag>,
612 ) -> InterpResult<'tcx> {
613 if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag(kind, place) } else { Ok(()) }
618 ecx: &mut InterpCx<'mir, 'tcx, Self>,
619 frame: Frame<'mir, 'tcx, Tag>,
620 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
621 // Start recording our event before doing anything else
622 let timing = if let Some(profiler) = ecx.machine.profiler.as_ref() {
623 let fn_name = frame.instance.to_string();
624 let entry = ecx.machine.string_cache.entry(fn_name.clone());
625 let name = entry.or_insert_with(|| profiler.alloc_string(&*fn_name));
627 Some(profiler.start_recording_interval_event_detached(
629 measureme::EventId::from_label(*name),
630 ecx.get_active_thread().to_u32(),
636 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
637 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
638 stacked_borrows.borrow_mut().new_call()
641 let extra = FrameData { call_id, catch_unwind: None, timing };
642 Ok(frame.with_extra(extra))
646 ecx: &'a InterpCx<'mir, 'tcx, Self>,
647 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
648 ecx.active_thread_stack()
652 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
653 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
654 ecx.active_thread_stack_mut()
658 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
659 if ecx.memory.extra.stacked_borrows.is_some() { ecx.retag_return_place() } else { Ok(()) }
664 ecx: &mut InterpCx<'mir, 'tcx, Self>,
665 mut frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
667 ) -> InterpResult<'tcx, StackPopJump> {
668 let timing = frame.extra.timing.take();
669 let res = ecx.handle_stack_pop(frame.extra, unwinding);
670 if let Some(profiler) = ecx.machine.profiler.as_ref() {
671 profiler.finish_recording_interval_event(timing.unwrap());
678 memory: &Memory<'mir, 'tcx, Self>,
680 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
681 intptrcast::GlobalState::int_to_ptr(int, memory)
686 memory: &Memory<'mir, 'tcx, Self>,
687 ptr: Pointer<Self::PointerTag>,
688 ) -> InterpResult<'tcx, u64> {
689 intptrcast::GlobalState::ptr_to_int(ptr, memory)