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;
15 use rustc_data_structures::fx::FxHashMap;
17 middle::codegen_fn_attrs::CodegenFnAttrFlags,
22 layout::{LayoutCx, LayoutError, TyAndLayout},
26 use rustc_span::symbol::{sym, Symbol};
27 use rustc_target::abi::{LayoutOf, Size};
31 pub use crate::threads::{ThreadId, ThreadManager, ThreadState};
33 // Some global facts about the emulated machine.
34 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
35 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
36 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
37 pub const NUM_CPUS: u64 = 1;
39 /// Extra data stored with each stack frame
41 pub struct FrameData<'tcx> {
42 /// Extra data for Stacked Borrows.
43 pub call_id: stacked_borrows::CallId,
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>>,
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, extern statics 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.
70 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
72 fn into(self) -> MemoryKind<MiriMemoryKind> {
73 MemoryKind::Machine(self)
77 impl MayLeak for MiriMemoryKind {
79 fn may_leak(self) -> bool {
80 use self::MiriMemoryKind::*;
82 Rust | C | WinHeap | Env => false,
83 Machine | Global => true,
88 impl fmt::Display for MiriMemoryKind {
89 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90 use self::MiriMemoryKind::*;
92 Rust => write!(f, "Rust heap"),
93 C => write!(f, "C heap"),
94 WinHeap => write!(f, "Windows heap"),
95 Machine => write!(f, "machine-managed memory"),
96 Env => write!(f, "environment variable"),
97 Global => write!(f, "global"),
102 /// Extra per-allocation data
103 #[derive(Debug, Clone)]
104 pub struct AllocExtra {
105 /// Stacked Borrows state is only added if it is enabled.
106 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
109 /// Extra global memory data
110 #[derive(Clone, Debug)]
111 pub struct MemoryExtra {
112 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
113 pub intptrcast: intptrcast::MemoryExtra,
115 /// Mapping extern static names to their canonical allocation.
116 extern_statics: FxHashMap<Symbol, AllocId>,
118 /// The random number generator used for resolving non-determinism.
119 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
120 pub(crate) rng: RefCell<StdRng>,
122 /// An allocation ID to report when it is being allocated
123 /// (helps for debugging memory leaks and use after free bugs).
124 tracked_alloc_id: Option<AllocId>,
126 /// Controls whether alignment of memory accesses is being checked.
127 check_alignment: bool,
133 stacked_borrows: bool,
134 tracked_pointer_tag: Option<PtrId>,
135 tracked_alloc_id: Option<AllocId>,
136 check_alignment: bool,
138 let stacked_borrows = if stacked_borrows {
139 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
145 intptrcast: Default::default(),
146 extern_statics: FxHashMap::default(),
147 rng: RefCell::new(rng),
153 fn add_extern_static<'tcx, 'mir>(
154 this: &mut MiriEvalContext<'mir, 'tcx>,
158 let ptr = ptr.assert_ptr();
159 assert_eq!(ptr.offset, Size::ZERO);
163 .insert(Symbol::intern(name), ptr.alloc_id)
167 /// Sets up the "extern statics" for this machine.
168 pub fn init_extern_statics<'tcx, 'mir>(
169 this: &mut MiriEvalContext<'mir, 'tcx>,
170 ) -> InterpResult<'tcx> {
171 match this.tcx.sess.target.target.target_os.as_str() {
173 // "__cxa_thread_atexit_impl"
174 // This should be all-zero, pointer-sized.
175 let layout = this.machine.layouts.usize;
176 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
177 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
178 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
180 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
184 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
185 let layout = this.machine.layouts.u8;
186 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
187 this.write_scalar(Scalar::from_u8(0), place.into())?;
188 Self::add_extern_static(this, "_tls_used", place.ptr);
190 _ => {} // No "extern statics" supported on this target
196 /// Precomputed layouts of primitive types
197 pub struct PrimitiveLayouts<'tcx> {
198 pub unit: TyAndLayout<'tcx>,
199 pub i8: TyAndLayout<'tcx>,
200 pub i32: TyAndLayout<'tcx>,
201 pub isize: TyAndLayout<'tcx>,
202 pub u8: TyAndLayout<'tcx>,
203 pub u32: TyAndLayout<'tcx>,
204 pub usize: TyAndLayout<'tcx>,
207 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
208 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
210 unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
211 i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
212 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
213 isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
214 u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
215 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
216 usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
221 /// The machine itself.
222 pub struct Evaluator<'mir, 'tcx> {
223 /// Environment variables set by `setenv`.
224 /// Miri does not expose env vars from the host to the emulated program.
225 pub(crate) env_vars: EnvVars<'tcx>,
227 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
228 /// These are *pointers* to argc/argv because macOS.
229 /// We also need the full command line as one string because of Windows.
230 pub(crate) argc: Option<Scalar<Tag>>,
231 pub(crate) argv: Option<Scalar<Tag>>,
232 pub(crate) cmd_line: Option<Scalar<Tag>>,
234 /// Last OS error location in memory. It is a 32-bit integer.
235 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
238 pub(crate) tls: TlsData<'tcx>,
240 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
241 /// and random number generation is delegated to the host.
242 pub(crate) communicate: bool,
244 /// Whether to enforce the validity invariant.
245 pub(crate) validate: bool,
247 pub(crate) file_handler: FileHandler,
248 pub(crate) dir_handler: DirHandler,
250 /// The temporary used for storing the argument of
251 /// the call to `miri_start_panic` (the panic payload) when unwinding.
252 /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
253 pub(crate) panic_payload: Option<Scalar<Tag>>,
255 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
256 pub(crate) time_anchor: Instant,
258 /// The set of threads.
259 pub(crate) threads: ThreadManager<'mir, 'tcx>,
261 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
262 pub(crate) layouts: PrimitiveLayouts<'tcx>,
265 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
269 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
271 let layouts = PrimitiveLayouts::new(layout_cx)
272 .expect("Couldn't get layouts of primitive types");
274 // `env_vars` could be initialized properly here if `Memory` were available before
275 // calling this method.
276 env_vars: EnvVars::default(),
281 tls: TlsData::default(),
284 file_handler: Default::default(),
285 dir_handler: Default::default(),
287 time_anchor: Instant::now(),
289 threads: Default::default(),
294 /// A rustc InterpCx for Miri.
295 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
297 /// A little trait that's useful to be inherited by extension traits.
298 pub trait MiriEvalContextExt<'mir, 'tcx> {
299 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
300 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
302 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
304 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
308 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
313 /// Machine hook implementations.
314 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
315 type MemoryKind = MiriMemoryKind;
317 type FrameExtra = FrameData<'tcx>;
318 type MemoryExtra = MemoryExtra;
319 type AllocExtra = AllocExtra;
320 type PointerTag = Tag;
321 type ExtraFnVal = Dlsym;
324 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
326 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
329 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
330 memory_extra.check_alignment
334 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
339 fn find_mir_or_eval_fn(
340 ecx: &mut InterpCx<'mir, 'tcx, Self>,
341 instance: ty::Instance<'tcx>,
342 args: &[OpTy<'tcx, Tag>],
343 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
344 unwind: Option<mir::BasicBlock>,
345 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
346 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
351 ecx: &mut InterpCx<'mir, 'tcx, Self>,
353 args: &[OpTy<'tcx, Tag>],
354 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
355 _unwind: Option<mir::BasicBlock>,
356 ) -> InterpResult<'tcx> {
357 ecx.call_dlsym(fn_val, args, ret)
362 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
363 instance: ty::Instance<'tcx>,
364 args: &[OpTy<'tcx, Tag>],
365 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
366 unwind: Option<mir::BasicBlock>,
367 ) -> InterpResult<'tcx> {
368 ecx.call_intrinsic(instance, args, ret, unwind)
373 ecx: &mut InterpCx<'mir, 'tcx, Self>,
374 msg: &mir::AssertMessage<'tcx>,
375 unwind: Option<mir::BasicBlock>,
376 ) -> InterpResult<'tcx> {
377 ecx.assert_panic(msg, unwind)
381 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
382 throw_machine_stop!(TerminationInfo::Abort(None))
387 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
389 left: ImmTy<'tcx, Tag>,
390 right: ImmTy<'tcx, Tag>,
391 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
392 ecx.binary_ptr_op(bin_op, left, right)
396 ecx: &mut InterpCx<'mir, 'tcx, Self>,
397 dest: PlaceTy<'tcx, Tag>,
398 ) -> InterpResult<'tcx> {
399 trace!("box_alloc for {:?}", dest.layout.ty);
400 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
401 // First argument: `size`.
402 // (`0` is allowed here -- this is expected to be handled by the lang item).
403 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
405 // Second argument: `align`.
406 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
408 // Call the `exchange_malloc` lang item.
409 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
410 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
413 &[size.into(), align.into()],
415 // Don't do anything when we are done. The `statement()` function will increment
416 // the old stack frame's stmt counter to the next statement, which means that when
417 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
418 StackPopCleanup::None { cleanup: true },
423 fn eval_maybe_thread_local_static_const(
424 ecx: &InterpCx<'mir, 'tcx, Self>,
425 mut val: mir::interpret::ConstValue<'tcx>,
426 ) -> InterpResult<'tcx, mir::interpret::ConstValue<'tcx>> {
428 mir::interpret::ConstValue::Scalar(Scalar::Ptr(ptr)) => {
429 let alloc_id = ptr.alloc_id;
430 let alloc = ecx.tcx.alloc_map.lock().get(alloc_id);
432 Some(GlobalAlloc::Static(def_id))
435 .codegen_fn_attrs(def_id)
437 .contains(CodegenFnAttrFlags::THREAD_LOCAL) =>
439 // We have a thread-local static.
440 let new_alloc_id = if let Some(new_alloc_id) =
441 ecx.get_thread_local_alloc_id(alloc_id)
445 if ecx.tcx.is_foreign_item(def_id) {
447 "Foreign thread-local statics are not supported."
450 let instance = Instance::mono(ecx.tcx.tcx, def_id);
451 let gid = GlobalId { instance, promoted: None };
454 .const_eval_raw(ty::ParamEnv::reveal_all().and(gid))
456 // no need to report anything, the const_eval call takes care of that
458 assert!(ecx.tcx.is_static(def_id));
460 ErrorHandled::Reported => err_inval!(ReferencedConstant),
461 ErrorHandled::TooGeneric => err_inval!(TooGeneric),
464 let id = raw_const.alloc_id;
465 let mut alloc_map = ecx.tcx.alloc_map.lock();
466 let allocation = alloc_map.unwrap_memory(id);
467 let new_alloc_id = alloc_map.create_memory_alloc(allocation);
468 ecx.set_thread_local_alloc_id(alloc_id, new_alloc_id);
471 ptr.alloc_id = new_alloc_id;
481 fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
483 // Figure out if this is an extern static, and if yes, which one.
484 let def_id = match tcx.alloc_map.lock().get(id) {
485 Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
487 // No need to canonicalize anything.
491 let attrs = tcx.get_attrs(def_id);
492 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
494 None => tcx.item_name(def_id),
496 // Check if we know this one.
497 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
498 trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
501 // Return original id; `Memory::get_static_alloc` will throw an error.
506 fn init_allocation_extra<'b>(
507 memory_extra: &MemoryExtra,
509 alloc: Cow<'b, Allocation>,
510 kind: Option<MemoryKind<Self::MemoryKind>>,
511 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
512 if Some(id) == memory_extra.tracked_alloc_id {
513 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
516 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
517 let alloc = alloc.into_owned();
518 let (stacks, base_tag) =
519 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
520 let (stacks, base_tag) =
521 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
522 (Some(stacks), base_tag)
524 // No stacks, no tag.
525 (None, Tag::Untagged)
527 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
528 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
530 if let Some(stacked_borrows) = &mut stacked_borrows {
531 // Only globals may already contain pointers at this point
532 assert_eq!(kind, MiriMemoryKind::Global.into());
533 stacked_borrows.global_base_ptr(alloc)
538 AllocExtra { stacked_borrows: stacks },
540 (Cow::Owned(alloc), base_tag)
544 fn before_deallocation(
545 memory_extra: &mut Self::MemoryExtra,
547 ) -> InterpResult<'tcx> {
548 if Some(id) == memory_extra.tracked_alloc_id {
549 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
556 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
557 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
558 stacked_borrows.borrow_mut().global_base_ptr(id)
566 ecx: &mut InterpCx<'mir, 'tcx, Self>,
567 kind: mir::RetagKind,
568 place: PlaceTy<'tcx, Tag>,
569 ) -> InterpResult<'tcx> {
570 if ecx.memory.extra.stacked_borrows.is_some() {
571 ecx.retag(kind, place)
579 ecx: &mut InterpCx<'mir, 'tcx, Self>,
580 frame: Frame<'mir, 'tcx, Tag>,
581 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
582 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
583 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
584 stacked_borrows.borrow_mut().new_call()
586 let extra = FrameData { call_id, catch_unwind: None };
587 Ok(frame.with_extra(extra))
591 ecx: &'a InterpCx<'mir, 'tcx, Self>
592 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
593 ecx.active_thread_stack()
597 ecx: &'a mut InterpCx<'mir, 'tcx, Self>
598 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
599 ecx.active_thread_stack_mut()
604 ecx: &'a InterpCx<'mir, 'tcx, Self>,
605 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
611 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
612 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
613 &mut ecx.machine.stack
617 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
618 if ecx.memory.extra.stacked_borrows.is_some() {
619 ecx.retag_return_place()
627 ecx: &mut InterpCx<'mir, 'tcx, Self>,
628 frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
630 ) -> InterpResult<'tcx, StackPopJump> {
631 ecx.handle_stack_pop(frame.extra, unwinding)
636 memory: &Memory<'mir, 'tcx, Self>,
638 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
639 intptrcast::GlobalState::int_to_ptr(int, memory)
644 memory: &Memory<'mir, 'tcx, Self>,
645 ptr: Pointer<Self::PointerTag>,
646 ) -> InterpResult<'tcx, u64> {
647 intptrcast::GlobalState::ptr_to_int(ptr, memory)
651 impl AllocationExtra<Tag> for AllocExtra {
653 fn memory_read<'tcx>(
654 alloc: &Allocation<Tag, AllocExtra>,
657 ) -> InterpResult<'tcx> {
658 if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
659 stacked_borrows.memory_read(ptr, size)
666 fn memory_written<'tcx>(
667 alloc: &mut Allocation<Tag, AllocExtra>,
670 ) -> InterpResult<'tcx> {
671 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
672 stacked_borrows.memory_written(ptr, size)
679 fn memory_deallocated<'tcx>(
680 alloc: &mut Allocation<Tag, AllocExtra>,
683 ) -> InterpResult<'tcx> {
684 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
685 stacked_borrows.memory_deallocated(ptr, size)