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;
20 layout::{LayoutCx, LayoutError, TyAndLayout},
24 use rustc_span::symbol::{sym, Symbol};
25 use rustc_target::abi::{LayoutOf, Size};
29 pub use crate::threads::{ThreadId, ThreadSet, ThreadLocalStorage};
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, extern statics 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.
68 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
70 fn into(self) -> MemoryKind<MiriMemoryKind> {
71 MemoryKind::Machine(self)
75 impl MayLeak for MiriMemoryKind {
77 fn may_leak(self) -> bool {
78 use self::MiriMemoryKind::*;
80 Rust | C | WinHeap | Env => false,
81 Machine | Global => true,
86 impl fmt::Display for MiriMemoryKind {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 use self::MiriMemoryKind::*;
90 Rust => write!(f, "Rust heap"),
91 C => write!(f, "C heap"),
92 WinHeap => write!(f, "Windows heap"),
93 Machine => write!(f, "machine-managed memory"),
94 Env => write!(f, "environment variable"),
95 Global => write!(f, "global"),
100 /// Extra per-allocation data
101 #[derive(Debug, Clone)]
102 pub struct AllocExtra {
103 /// Stacked Borrows state is only added if it is enabled.
104 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
107 /// Extra global memory data
108 #[derive(Clone, Debug)]
109 pub struct MemoryExtra {
110 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
111 pub intptrcast: intptrcast::MemoryExtra,
112 pub tls: ThreadLocalStorage,
114 /// Mapping extern static names to their canonical allocation.
115 extern_statics: FxHashMap<Symbol, AllocId>,
117 /// The random number generator used for resolving non-determinism.
118 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
119 pub(crate) rng: RefCell<StdRng>,
121 /// An allocation ID to report when it is being allocated
122 /// (helps for debugging memory leaks and use after free bugs).
123 tracked_alloc_id: Option<AllocId>,
125 /// Controls whether alignment of memory accesses is being checked.
126 check_alignment: bool,
132 stacked_borrows: bool,
133 tracked_pointer_tag: Option<PtrId>,
134 tracked_alloc_id: Option<AllocId>,
135 check_alignment: bool,
137 let stacked_borrows = if stacked_borrows {
138 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
144 intptrcast: Default::default(),
145 extern_statics: FxHashMap::default(),
146 rng: RefCell::new(rng),
149 tls: Default::default(),
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: ThreadSet<'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
335 ecx: &'a InterpCx<'mir, 'tcx, Self>
336 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
337 ecx.active_thread_stack()
341 ecx: &'a mut InterpCx<'mir, 'tcx, Self>
342 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
343 ecx.active_thread_stack_mut()
347 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
352 fn find_mir_or_eval_fn(
353 ecx: &mut InterpCx<'mir, 'tcx, Self>,
354 instance: ty::Instance<'tcx>,
355 args: &[OpTy<'tcx, Tag>],
356 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
357 unwind: Option<mir::BasicBlock>,
358 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
359 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
364 ecx: &mut InterpCx<'mir, 'tcx, Self>,
366 args: &[OpTy<'tcx, Tag>],
367 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
368 _unwind: Option<mir::BasicBlock>,
369 ) -> InterpResult<'tcx> {
370 ecx.call_dlsym(fn_val, args, ret)
375 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
376 instance: ty::Instance<'tcx>,
377 args: &[OpTy<'tcx, Tag>],
378 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
379 unwind: Option<mir::BasicBlock>,
380 ) -> InterpResult<'tcx> {
381 ecx.call_intrinsic(instance, args, ret, unwind)
386 ecx: &mut InterpCx<'mir, 'tcx, Self>,
387 msg: &mir::AssertMessage<'tcx>,
388 unwind: Option<mir::BasicBlock>,
389 ) -> InterpResult<'tcx> {
390 ecx.assert_panic(msg, unwind)
394 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
395 throw_machine_stop!(TerminationInfo::Abort(None))
400 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
402 left: ImmTy<'tcx, Tag>,
403 right: ImmTy<'tcx, Tag>,
404 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
405 ecx.binary_ptr_op(bin_op, left, right)
409 ecx: &mut InterpCx<'mir, 'tcx, Self>,
410 dest: PlaceTy<'tcx, Tag>,
411 ) -> InterpResult<'tcx> {
412 trace!("box_alloc for {:?}", dest.layout.ty);
413 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
414 // First argument: `size`.
415 // (`0` is allowed here -- this is expected to be handled by the lang item).
416 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
418 // Second argument: `align`.
419 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
421 // Call the `exchange_malloc` lang item.
422 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
423 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
426 &[size.into(), align.into()],
428 // Don't do anything when we are done. The `statement()` function will increment
429 // the old stack frame's stmt counter to the next statement, which means that when
430 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
431 StackPopCleanup::None { cleanup: true },
436 fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
438 let alloc = tcx.alloc_map.lock().get(id);
440 Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => {
441 // Figure out if this is an extern static, and if yes, which one.
442 let attrs = tcx.get_attrs(def_id);
443 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
445 None => tcx.item_name(def_id),
447 // Check if we know this one.
448 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
449 trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
452 // Return original id; `Memory::get_static_alloc` will throw an error.
456 Some(GlobalAlloc::Static(def_id)) if tcx.has_attr(def_id, sym::thread_local) => {
457 // We have a thread local, so we need to get a unique allocation id for it.
458 mem.extra.tls.get_or_register_allocation(*tcx, id)
461 // No need to canonicalize anything.
468 fn resolve_maybe_global_alloc(
469 tcx: ty::query::TyCtxtAt<'tcx>,
470 extra: &Self::MemoryExtra,
472 ) -> Option<mir::interpret::GlobalAlloc<'tcx>> {
473 extra.tls.resolve_allocation(*tcx, id)
476 fn init_allocation_extra<'b>(
477 memory_extra: &MemoryExtra,
479 alloc: Cow<'b, Allocation>,
480 kind: Option<MemoryKind<Self::MemoryKind>>,
481 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
482 if Some(id) == memory_extra.tracked_alloc_id {
483 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
486 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
487 let alloc = alloc.into_owned();
488 let (stacks, base_tag) =
489 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
490 let (stacks, base_tag) =
491 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
492 (Some(stacks), base_tag)
494 // No stacks, no tag.
495 (None, Tag::Untagged)
497 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
498 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
500 if let Some(stacked_borrows) = &mut stacked_borrows {
501 // Only globals may already contain pointers at this point
502 assert_eq!(kind, MiriMemoryKind::Global.into());
503 stacked_borrows.global_base_ptr(alloc)
508 AllocExtra { stacked_borrows: stacks },
510 (Cow::Owned(alloc), base_tag)
514 fn before_deallocation(
515 memory_extra: &mut Self::MemoryExtra,
517 ) -> InterpResult<'tcx> {
518 if Some(id) == memory_extra.tracked_alloc_id {
519 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
526 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
527 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
528 stacked_borrows.borrow_mut().global_base_ptr(id)
536 ecx: &mut InterpCx<'mir, 'tcx, Self>,
537 kind: mir::RetagKind,
538 place: PlaceTy<'tcx, Tag>,
539 ) -> InterpResult<'tcx> {
540 if ecx.memory.extra.stacked_borrows.is_some() {
541 ecx.retag(kind, place)
549 ecx: &mut InterpCx<'mir, 'tcx, Self>,
550 frame: Frame<'mir, 'tcx, Tag>,
551 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
552 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
553 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
554 stacked_borrows.borrow_mut().new_call()
556 let extra = FrameData { call_id, catch_unwind: None };
557 Ok(frame.with_extra(extra))
562 ecx: &'a InterpCx<'mir, 'tcx, Self>,
563 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
569 ecx: &'a mut InterpCx<'mir, 'tcx, Self>,
570 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
571 &mut ecx.machine.stack
575 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
576 if ecx.memory.extra.stacked_borrows.is_some() {
577 ecx.retag_return_place()
585 ecx: &mut InterpCx<'mir, 'tcx, Self>,
586 frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
588 ) -> InterpResult<'tcx, StackPopJump> {
589 ecx.handle_stack_pop(frame.extra, unwinding)
594 memory: &Memory<'mir, 'tcx, Self>,
596 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
597 intptrcast::GlobalState::int_to_ptr(int, memory)
602 memory: &Memory<'mir, 'tcx, Self>,
603 ptr: Pointer<Self::PointerTag>,
604 ) -> InterpResult<'tcx, u64> {
605 intptrcast::GlobalState::ptr_to_int(ptr, memory)
609 impl AllocationExtra<Tag> for AllocExtra {
611 fn memory_read<'tcx>(
612 alloc: &Allocation<Tag, AllocExtra>,
615 ) -> InterpResult<'tcx> {
616 if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
617 stacked_borrows.memory_read(ptr, size)
624 fn memory_written<'tcx>(
625 alloc: &mut Allocation<Tag, AllocExtra>,
628 ) -> InterpResult<'tcx> {
629 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
630 stacked_borrows.memory_written(ptr, size)
637 fn memory_deallocated<'tcx>(
638 alloc: &mut Allocation<Tag, AllocExtra>,
641 ) -> InterpResult<'tcx> {
642 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
643 stacked_borrows.memory_deallocated(ptr, size)