1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
6 use std::num::NonZeroU64;
8 use std::time::Instant;
12 use rand::rngs::StdRng;
13 use rand::SeedableRng;
15 use rustc_data_structures::fx::FxHashMap;
20 layout::{LayoutCx, LayoutError, TyAndLayout},
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_span::def_id::DefId;
26 use rustc_target::abi::{LayoutOf, Size};
27 use rustc_target::spec::abi::Abi;
31 // Some global facts about the emulated machine.
32 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
33 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
34 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
35 pub const NUM_CPUS: u64 = 1;
37 /// 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>>,
49 /// Extra memory kinds
50 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
51 pub enum MiriMemoryKind {
52 /// `__rust_alloc` memory.
56 /// Windows `HeapAlloc` memory.
58 /// Memory for args, errno, and other parts of the machine-managed environment.
59 /// This memory may leak.
61 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
63 /// Globals copied from `tcx`.
64 /// This memory may leak.
66 /// Memory for extern statics.
67 /// This memory may leak.
69 /// Memory for thread-local statics.
70 /// This memory may leak.
74 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
76 fn into(self) -> MemoryKind<MiriMemoryKind> {
77 MemoryKind::Machine(self)
81 impl MayLeak for MiriMemoryKind {
83 fn may_leak(self) -> bool {
84 use self::MiriMemoryKind::*;
86 Rust | C | WinHeap | Env => false,
87 Machine | Global | ExternStatic | Tls => true,
92 impl fmt::Display for MiriMemoryKind {
93 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94 use self::MiriMemoryKind::*;
96 Rust => write!(f, "Rust heap"),
97 C => write!(f, "C heap"),
98 WinHeap => write!(f, "Windows heap"),
99 Machine => write!(f, "machine-managed memory"),
100 Env => write!(f, "environment variable"),
101 Global => write!(f, "global (static or const)"),
102 ExternStatic => write!(f, "extern static"),
103 Tls => write!(f, "thread-local static"),
108 /// Extra per-allocation data
109 #[derive(Debug, Clone)]
110 pub struct AllocExtra {
111 /// Stacked Borrows state is only added if it is enabled.
112 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
113 /// Data race detection via the use of a vector-clock,
114 /// this is only added if it is enabled.
115 pub data_race: Option<data_race::AllocExtra>,
118 /// Extra global memory data
119 #[derive(Clone, Debug)]
120 pub struct MemoryExtra {
121 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
122 pub data_race: Option<data_race::MemoryExtra>,
123 pub intptrcast: intptrcast::MemoryExtra,
125 /// Mapping extern static names to their canonical allocation.
126 extern_statics: FxHashMap<Symbol, AllocId>,
128 /// The random number generator used for resolving non-determinism.
129 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
130 pub(crate) rng: RefCell<StdRng>,
132 /// An allocation ID to report when it is being allocated
133 /// (helps for debugging memory leaks and use after free bugs).
134 tracked_alloc_id: Option<AllocId>,
136 /// Controls whether alignment of memory accesses is being checked.
137 pub(crate) check_alignment: AlignmentCheck,
139 /// Failure rate of compare_exchange_weak, between 0.0 and 1.0
140 pub(crate) cmpxchg_weak_failure_rate: f64,
144 pub fn new(config: &MiriConfig) -> Self {
145 let rng = StdRng::seed_from_u64(config.seed.unwrap_or(0));
146 let stacked_borrows = if config.stacked_borrows {
147 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(
148 config.tracked_pointer_tag,
149 config.tracked_call_id,
155 let data_race = if config.data_race_detector {
156 Some(Rc::new(data_race::GlobalState::new()))
163 intptrcast: Default::default(),
164 extern_statics: FxHashMap::default(),
165 rng: RefCell::new(rng),
166 tracked_alloc_id: config.tracked_alloc_id,
167 check_alignment: config.check_alignment,
168 cmpxchg_weak_failure_rate: config.cmpxchg_weak_failure_rate,
172 fn add_extern_static<'tcx, 'mir>(
173 this: &mut MiriEvalContext<'mir, 'tcx>,
177 let ptr = ptr.assert_ptr();
178 assert_eq!(ptr.offset, Size::ZERO);
182 .try_insert(Symbol::intern(name), ptr.alloc_id)
186 /// Sets up the "extern statics" for this machine.
187 pub fn init_extern_statics<'tcx, 'mir>(
188 this: &mut MiriEvalContext<'mir, 'tcx>,
189 ) -> InterpResult<'tcx> {
190 match this.tcx.sess.target.os.as_str() {
192 // "__cxa_thread_atexit_impl"
193 // This should be all-zero, pointer-sized.
194 let layout = this.machine.layouts.usize;
195 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
196 this.write_scalar(Scalar::from_machine_usize(0, this), &place.into())?;
197 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
199 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
203 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
204 let layout = this.machine.layouts.u8;
205 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
206 this.write_scalar(Scalar::from_u8(0), &place.into())?;
207 Self::add_extern_static(this, "_tls_used", place.ptr);
209 _ => {} // No "extern statics" supported on this target
215 /// Precomputed layouts of primitive types
216 pub struct PrimitiveLayouts<'tcx> {
217 pub unit: TyAndLayout<'tcx>,
218 pub i8: TyAndLayout<'tcx>,
219 pub i32: TyAndLayout<'tcx>,
220 pub isize: TyAndLayout<'tcx>,
221 pub u8: TyAndLayout<'tcx>,
222 pub u32: TyAndLayout<'tcx>,
223 pub usize: TyAndLayout<'tcx>,
226 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
227 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
229 unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
230 i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
231 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
232 isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
233 u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
234 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
235 usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
240 /// The machine itself.
241 pub struct Evaluator<'mir, 'tcx> {
242 /// Environment variables set by `setenv`.
243 /// Miri does not expose env vars from the host to the emulated program.
244 pub(crate) env_vars: EnvVars<'tcx>,
246 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
247 /// These are *pointers* to argc/argv because macOS.
248 /// We also need the full command line as one string because of Windows.
249 pub(crate) argc: Option<Scalar<Tag>>,
250 pub(crate) argv: Option<Scalar<Tag>>,
251 pub(crate) cmd_line: Option<Scalar<Tag>>,
254 pub(crate) tls: TlsData<'tcx>,
256 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
257 /// and random number generation is delegated to the host.
258 pub(crate) communicate: bool,
260 /// Whether to enforce the validity invariant.
261 pub(crate) validate: bool,
263 pub(crate) file_handler: shims::posix::FileHandler,
264 pub(crate) dir_handler: shims::posix::DirHandler,
266 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
267 pub(crate) time_anchor: Instant,
269 /// The set of threads.
270 pub(crate) threads: ThreadManager<'mir, 'tcx>,
272 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
273 pub(crate) layouts: PrimitiveLayouts<'tcx>,
275 /// Allocations that are considered roots of static memory (that may leak).
276 pub(crate) static_roots: Vec<AllocId>,
279 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
283 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
285 let layouts = PrimitiveLayouts::new(layout_cx)
286 .expect("Couldn't get layouts of primitive types");
288 // `env_vars` could be initialized properly here if `Memory` were available before
289 // calling this method.
290 env_vars: EnvVars::default(),
294 tls: TlsData::default(),
297 file_handler: Default::default(),
298 dir_handler: Default::default(),
299 time_anchor: Instant::now(),
301 threads: ThreadManager::default(),
302 static_roots: Vec::new(),
307 /// A rustc InterpCx for Miri.
308 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
310 /// A little trait that's useful to be inherited by extension traits.
311 pub trait MiriEvalContextExt<'mir, 'tcx> {
312 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
313 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
315 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
317 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
321 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
326 /// Machine hook implementations.
327 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
328 type MemoryKind = MiriMemoryKind;
330 type FrameExtra = FrameData<'tcx>;
331 type MemoryExtra = MemoryExtra;
332 type AllocExtra = AllocExtra;
333 type PointerTag = Tag;
334 type ExtraFnVal = Dlsym;
337 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
339 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
342 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
343 memory_extra.check_alignment != AlignmentCheck::None
347 fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
348 memory_extra.check_alignment == AlignmentCheck::Int
352 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
357 fn find_mir_or_eval_fn(
358 ecx: &mut InterpCx<'mir, 'tcx, Self>,
359 instance: ty::Instance<'tcx>,
361 args: &[OpTy<'tcx, Tag>],
362 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
363 unwind: Option<mir::BasicBlock>,
364 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
365 ecx.find_mir_or_eval_fn(instance, abi, args, ret, unwind)
370 ecx: &mut InterpCx<'mir, 'tcx, Self>,
373 args: &[OpTy<'tcx, Tag>],
374 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
375 _unwind: Option<mir::BasicBlock>,
376 ) -> InterpResult<'tcx> {
377 ecx.call_dlsym(fn_val, abi, args, ret)
382 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
383 instance: ty::Instance<'tcx>,
384 args: &[OpTy<'tcx, Tag>],
385 ret: Option<(&PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
386 unwind: Option<mir::BasicBlock>,
387 ) -> InterpResult<'tcx> {
388 ecx.call_intrinsic(instance, args, ret, unwind)
393 ecx: &mut InterpCx<'mir, 'tcx, Self>,
394 msg: &mir::AssertMessage<'tcx>,
395 unwind: Option<mir::BasicBlock>,
396 ) -> InterpResult<'tcx> {
397 ecx.assert_panic(msg, unwind)
401 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>, msg: String) -> InterpResult<'tcx, !> {
402 throw_machine_stop!(TerminationInfo::Abort(msg))
407 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
409 left: &ImmTy<'tcx, Tag>,
410 right: &ImmTy<'tcx, Tag>,
411 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
412 ecx.binary_ptr_op(bin_op, left, right)
416 ecx: &mut InterpCx<'mir, 'tcx, Self>,
417 dest: &PlaceTy<'tcx, Tag>,
418 ) -> InterpResult<'tcx> {
419 trace!("box_alloc for {:?}", dest.layout.ty);
420 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
421 // First argument: `size`.
422 // (`0` is allowed here -- this is expected to be handled by the lang item).
423 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
425 // Second argument: `align`.
426 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
428 // Call the `exchange_malloc` lang item.
429 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
430 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
433 &[size.into(), align.into()],
435 // Don't do anything when we are done. The `statement()` function will increment
436 // the old stack frame's stmt counter to the next statement, which means that when
437 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
438 StackPopCleanup::None { cleanup: true },
443 fn thread_local_static_alloc_id(
444 ecx: &mut InterpCx<'mir, 'tcx, Self>,
446 ) -> InterpResult<'tcx, AllocId> {
447 ecx.get_or_create_thread_local_alloc_id(def_id)
450 fn extern_static_alloc_id(
451 memory: &Memory<'mir, 'tcx, Self>,
453 ) -> InterpResult<'tcx, AllocId> {
454 let attrs = memory.tcx.get_attrs(def_id);
455 let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
457 None => memory.tcx.item_name(def_id),
459 if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
462 throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
466 fn init_allocation_extra<'b>(
467 memory_extra: &MemoryExtra,
469 alloc: Cow<'b, Allocation>,
470 kind: Option<MemoryKind<Self::MemoryKind>>,
471 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
472 if Some(id) == memory_extra.tracked_alloc_id {
473 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
476 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
477 let alloc = alloc.into_owned();
478 let (stacks, base_tag) =
479 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
480 let (stacks, base_tag) =
481 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
482 (Some(stacks), base_tag)
484 // No stacks, no tag.
485 (None, Tag::Untagged)
487 let race_alloc = if let Some(data_race) = &memory_extra.data_race {
488 Some(data_race::AllocExtra::new_allocation(&data_race, alloc.size, kind))
492 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
493 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
495 if let Some(stacked_borrows) = &mut stacked_borrows {
496 // Only globals may already contain pointers at this point
497 assert_eq!(kind, MiriMemoryKind::Global.into());
498 stacked_borrows.global_base_ptr(alloc)
503 AllocExtra { stacked_borrows: stacks, data_race: race_alloc },
505 (Cow::Owned(alloc), base_tag)
509 fn before_deallocation(
510 memory_extra: &mut Self::MemoryExtra,
512 ) -> InterpResult<'tcx> {
513 if Some(id) == memory_extra.tracked_alloc_id {
514 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
521 fn after_static_mem_initialized(
522 ecx: &mut InterpCx<'mir, 'tcx, Self>,
523 ptr: Pointer<Self::PointerTag>,
525 ) -> InterpResult<'tcx> {
526 if ecx.memory.extra.data_race.is_some() {
527 ecx.reset_vector_clocks(ptr, size)?;
533 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
534 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
535 stacked_borrows.borrow_mut().global_base_ptr(id)
543 ecx: &mut InterpCx<'mir, 'tcx, Self>,
544 kind: mir::RetagKind,
545 place: &PlaceTy<'tcx, Tag>,
546 ) -> InterpResult<'tcx> {
547 if ecx.memory.extra.stacked_borrows.is_some() {
548 ecx.retag(kind, place)
556 ecx: &mut InterpCx<'mir, 'tcx, Self>,
557 frame: Frame<'mir, 'tcx, Tag>,
558 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
559 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
560 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
561 stacked_borrows.borrow_mut().new_call()
563 let extra = FrameData { call_id, catch_unwind: None };
564 Ok(frame.with_extra(extra))
568 ecx: &'a InterpCx<'mir, 'tcx, Self>
569 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
570 ecx.active_thread_stack()
574 ecx: &'a mut InterpCx<'mir, 'tcx, Self>
575 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
576 ecx.active_thread_stack_mut()
580 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
581 if ecx.memory.extra.stacked_borrows.is_some() {
582 ecx.retag_return_place()
590 ecx: &mut InterpCx<'mir, 'tcx, Self>,
591 frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
593 ) -> InterpResult<'tcx, StackPopJump> {
594 ecx.handle_stack_pop(frame.extra, unwinding)
599 memory: &Memory<'mir, 'tcx, Self>,
601 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
602 intptrcast::GlobalState::int_to_ptr(int, memory)
607 memory: &Memory<'mir, 'tcx, Self>,
608 ptr: Pointer<Self::PointerTag>,
609 ) -> InterpResult<'tcx, u64> {
610 intptrcast::GlobalState::ptr_to_int(ptr, memory)
614 impl AllocationExtra<Tag> for AllocExtra {
616 fn memory_read<'tcx>(
617 alloc: &Allocation<Tag, AllocExtra>,
620 ) -> InterpResult<'tcx> {
621 if let Some(data_race) = &alloc.extra.data_race {
622 data_race.read(ptr, size)?;
624 if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
625 stacked_borrows.memory_read(ptr, size)
632 fn memory_written<'tcx>(
633 alloc: &mut Allocation<Tag, AllocExtra>,
636 ) -> InterpResult<'tcx> {
637 if let Some(data_race) = &mut alloc.extra.data_race {
638 data_race.write(ptr, size)?;
640 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
641 stacked_borrows.memory_written(ptr, size)
648 fn memory_deallocated<'tcx>(
649 alloc: &mut Allocation<Tag, AllocExtra>,
652 ) -> InterpResult<'tcx> {
653 if let Some(data_race) = &mut alloc.extra.data_race {
654 data_race.deallocate(ptr, size)?;
656 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
657 stacked_borrows.memory_deallocated(ptr, size)