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;
14 use rustc_data_structures::fx::FxHashMap;
19 layout::{LayoutCx, LayoutError, TyAndLayout},
23 use rustc_span::symbol::{sym, Symbol};
24 use rustc_span::def_id::DefId;
25 use rustc_target::abi::{LayoutOf, Size};
29 // Some global facts about the emulated machine.
30 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
31 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
32 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
33 pub const NUM_CPUS: u64 = 1;
35 /// 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>>,
47 /// Extra memory kinds
48 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
49 pub enum MiriMemoryKind {
50 /// `__rust_alloc` memory.
54 /// Windows `HeapAlloc` memory.
56 /// Memory for args, errno, and other parts of the machine-managed environment.
57 /// This memory may leak.
59 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
61 /// Globals copied from `tcx`.
62 /// This memory may leak.
64 /// Memory for extern statics.
65 /// This memory may leak.
67 /// Memory for thread-local statics.
68 /// This memory may leak.
72 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
74 fn into(self) -> MemoryKind<MiriMemoryKind> {
75 MemoryKind::Machine(self)
79 impl MayLeak for MiriMemoryKind {
81 fn may_leak(self) -> bool {
82 use self::MiriMemoryKind::*;
84 Rust | C | WinHeap | Env => false,
85 Machine | Global | ExternStatic | Tls => true,
90 impl fmt::Display for MiriMemoryKind {
91 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92 use self::MiriMemoryKind::*;
94 Rust => write!(f, "Rust heap"),
95 C => write!(f, "C heap"),
96 WinHeap => write!(f, "Windows heap"),
97 Machine => write!(f, "machine-managed memory"),
98 Env => write!(f, "environment variable"),
99 Global => write!(f, "global (static or const)"),
100 ExternStatic => write!(f, "extern static"),
101 Tls => write!(f, "thread-local static"),
106 /// Extra per-allocation data
107 #[derive(Debug, Clone)]
108 pub struct AllocExtra {
109 /// Stacked Borrows state is only added if it is enabled.
110 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
113 /// Extra global memory data
114 #[derive(Clone, Debug)]
115 pub struct MemoryExtra {
116 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
117 pub intptrcast: intptrcast::MemoryExtra,
119 /// Mapping extern static names to their canonical allocation.
120 extern_statics: FxHashMap<Symbol, AllocId>,
122 /// The random number generator used for resolving non-determinism.
123 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
124 pub(crate) rng: RefCell<StdRng>,
126 /// An allocation ID to report when it is being allocated
127 /// (helps for debugging memory leaks and use after free bugs).
128 tracked_alloc_id: Option<AllocId>,
130 /// Controls whether alignment of memory accesses is being checked.
131 pub(crate) check_alignment: AlignmentCheck,
137 stacked_borrows: bool,
138 tracked_pointer_tag: Option<PtrId>,
139 tracked_call_id: Option<CallId>,
140 tracked_alloc_id: Option<AllocId>,
141 check_alignment: AlignmentCheck,
143 let stacked_borrows = if stacked_borrows {
144 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag, tracked_call_id))))
150 intptrcast: Default::default(),
151 extern_statics: FxHashMap::default(),
152 rng: RefCell::new(rng),
158 fn add_extern_static<'tcx, 'mir>(
159 this: &mut MiriEvalContext<'mir, 'tcx>,
163 let ptr = ptr.assert_ptr();
164 assert_eq!(ptr.offset, Size::ZERO);
168 .insert(Symbol::intern(name), ptr.alloc_id)
172 /// Sets up the "extern statics" for this machine.
173 pub fn init_extern_statics<'tcx, 'mir>(
174 this: &mut MiriEvalContext<'mir, 'tcx>,
175 ) -> InterpResult<'tcx> {
176 match this.tcx.sess.target.target.target_os.as_str() {
178 // "__cxa_thread_atexit_impl"
179 // This should be all-zero, pointer-sized.
180 let layout = this.machine.layouts.usize;
181 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
182 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
183 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
185 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
189 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
190 let layout = this.machine.layouts.u8;
191 let place = this.allocate(layout, MiriMemoryKind::ExternStatic.into());
192 this.write_scalar(Scalar::from_u8(0), place.into())?;
193 Self::add_extern_static(this, "_tls_used", place.ptr);
195 _ => {} // No "extern statics" supported on this target
201 /// Precomputed layouts of primitive types
202 pub struct PrimitiveLayouts<'tcx> {
203 pub unit: TyAndLayout<'tcx>,
204 pub i8: TyAndLayout<'tcx>,
205 pub i32: TyAndLayout<'tcx>,
206 pub isize: TyAndLayout<'tcx>,
207 pub u8: TyAndLayout<'tcx>,
208 pub u32: TyAndLayout<'tcx>,
209 pub usize: TyAndLayout<'tcx>,
212 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
213 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
215 unit: layout_cx.layout_of(layout_cx.tcx.mk_unit())?,
216 i8: layout_cx.layout_of(layout_cx.tcx.types.i8)?,
217 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
218 isize: layout_cx.layout_of(layout_cx.tcx.types.isize)?,
219 u8: layout_cx.layout_of(layout_cx.tcx.types.u8)?,
220 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
221 usize: layout_cx.layout_of(layout_cx.tcx.types.usize)?,
226 /// The machine itself.
227 pub struct Evaluator<'mir, 'tcx> {
228 /// Environment variables set by `setenv`.
229 /// Miri does not expose env vars from the host to the emulated program.
230 pub(crate) env_vars: EnvVars<'tcx>,
232 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
233 /// These are *pointers* to argc/argv because macOS.
234 /// We also need the full command line as one string because of Windows.
235 pub(crate) argc: Option<Scalar<Tag>>,
236 pub(crate) argv: Option<Scalar<Tag>>,
237 pub(crate) cmd_line: Option<Scalar<Tag>>,
239 /// Last OS error location in memory. It is a 32-bit integer.
240 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
243 pub(crate) tls: TlsData<'tcx>,
245 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
246 /// and random number generation is delegated to the host.
247 pub(crate) communicate: bool,
249 /// Whether to enforce the validity invariant.
250 pub(crate) validate: bool,
252 pub(crate) file_handler: shims::posix::FileHandler,
253 pub(crate) dir_handler: shims::posix::DirHandler,
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>,
264 /// Allocations that are considered roots of static memory (that may leak).
265 pub(crate) static_roots: Vec<AllocId>,
268 impl<'mir, 'tcx> Evaluator<'mir, 'tcx> {
272 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
274 let layouts = PrimitiveLayouts::new(layout_cx)
275 .expect("Couldn't get layouts of primitive types");
277 // `env_vars` could be initialized properly here if `Memory` were available before
278 // calling this method.
279 env_vars: EnvVars::default(),
284 tls: TlsData::default(),
287 file_handler: Default::default(),
288 dir_handler: Default::default(),
289 time_anchor: Instant::now(),
291 threads: ThreadManager::default(),
292 static_roots: Vec::new(),
297 /// A rustc InterpCx for Miri.
298 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>;
300 /// A little trait that's useful to be inherited by extension traits.
301 pub trait MiriEvalContextExt<'mir, 'tcx> {
302 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
303 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
305 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
307 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
311 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
316 /// Machine hook implementations.
317 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'mir, 'tcx> {
318 type MemoryKind = MiriMemoryKind;
320 type FrameExtra = FrameData<'tcx>;
321 type MemoryExtra = MemoryExtra;
322 type AllocExtra = AllocExtra;
323 type PointerTag = Tag;
324 type ExtraFnVal = Dlsym;
327 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
329 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
332 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
333 memory_extra.check_alignment != AlignmentCheck::None
337 fn force_int_for_alignment_check(memory_extra: &Self::MemoryExtra) -> bool {
338 memory_extra.check_alignment == AlignmentCheck::Int
342 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
347 fn find_mir_or_eval_fn(
348 ecx: &mut InterpCx<'mir, 'tcx, Self>,
349 instance: ty::Instance<'tcx>,
350 args: &[OpTy<'tcx, Tag>],
351 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
352 unwind: Option<mir::BasicBlock>,
353 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
354 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
359 ecx: &mut InterpCx<'mir, 'tcx, Self>,
361 args: &[OpTy<'tcx, Tag>],
362 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
363 _unwind: Option<mir::BasicBlock>,
364 ) -> InterpResult<'tcx> {
365 ecx.call_dlsym(fn_val, args, ret)
370 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
371 instance: ty::Instance<'tcx>,
372 args: &[OpTy<'tcx, Tag>],
373 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
374 unwind: Option<mir::BasicBlock>,
375 ) -> InterpResult<'tcx> {
376 ecx.call_intrinsic(instance, args, ret, unwind)
381 ecx: &mut InterpCx<'mir, 'tcx, Self>,
382 msg: &mir::AssertMessage<'tcx>,
383 unwind: Option<mir::BasicBlock>,
384 ) -> InterpResult<'tcx> {
385 ecx.assert_panic(msg, unwind)
389 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
390 throw_machine_stop!(TerminationInfo::Abort(None))
395 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
397 left: ImmTy<'tcx, Tag>,
398 right: ImmTy<'tcx, Tag>,
399 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
400 ecx.binary_ptr_op(bin_op, left, right)
404 ecx: &mut InterpCx<'mir, 'tcx, Self>,
405 dest: PlaceTy<'tcx, Tag>,
406 ) -> InterpResult<'tcx> {
407 trace!("box_alloc for {:?}", dest.layout.ty);
408 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
409 // First argument: `size`.
410 // (`0` is allowed here -- this is expected to be handled by the lang item).
411 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
413 // Second argument: `align`.
414 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
416 // Call the `exchange_malloc` lang item.
417 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
418 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
421 &[size.into(), align.into()],
423 // Don't do anything when we are done. The `statement()` function will increment
424 // the old stack frame's stmt counter to the next statement, which means that when
425 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
426 StackPopCleanup::None { cleanup: true },
431 fn thread_local_static_alloc_id(
432 ecx: &mut InterpCx<'mir, 'tcx, Self>,
434 ) -> InterpResult<'tcx, AllocId> {
435 ecx.get_or_create_thread_local_alloc_id(def_id)
438 fn extern_static_alloc_id(
439 memory: &Memory<'mir, 'tcx, Self>,
441 ) -> InterpResult<'tcx, AllocId> {
442 let attrs = memory.tcx.get_attrs(def_id);
443 let link_name = match memory.tcx.sess.first_attr_value_str_by_name(&attrs, sym::link_name) {
445 None => memory.tcx.item_name(def_id),
447 if let Some(&id) = memory.extra.extern_statics.get(&link_name) {
450 throw_unsup_format!("`extern` static {:?} is not supported by Miri", def_id)
454 fn init_allocation_extra<'b>(
455 memory_extra: &MemoryExtra,
457 alloc: Cow<'b, Allocation>,
458 kind: Option<MemoryKind<Self::MemoryKind>>,
459 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
460 if Some(id) == memory_extra.tracked_alloc_id {
461 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
464 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
465 let alloc = alloc.into_owned();
466 let (stacks, base_tag) =
467 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
468 let (stacks, base_tag) =
469 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
470 (Some(stacks), base_tag)
472 // No stacks, no tag.
473 (None, Tag::Untagged)
475 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
476 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
478 if let Some(stacked_borrows) = &mut stacked_borrows {
479 // Only globals may already contain pointers at this point
480 assert_eq!(kind, MiriMemoryKind::Global.into());
481 stacked_borrows.global_base_ptr(alloc)
486 AllocExtra { stacked_borrows: stacks },
488 (Cow::Owned(alloc), base_tag)
492 fn before_deallocation(
493 memory_extra: &mut Self::MemoryExtra,
495 ) -> InterpResult<'tcx> {
496 if Some(id) == memory_extra.tracked_alloc_id {
497 register_diagnostic(NonHaltingDiagnostic::FreedAlloc(id));
504 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
505 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
506 stacked_borrows.borrow_mut().global_base_ptr(id)
514 ecx: &mut InterpCx<'mir, 'tcx, Self>,
515 kind: mir::RetagKind,
516 place: PlaceTy<'tcx, Tag>,
517 ) -> InterpResult<'tcx> {
518 if ecx.memory.extra.stacked_borrows.is_some() {
519 ecx.retag(kind, place)
527 ecx: &mut InterpCx<'mir, 'tcx, Self>,
528 frame: Frame<'mir, 'tcx, Tag>,
529 ) -> InterpResult<'tcx, Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
530 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
531 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
532 stacked_borrows.borrow_mut().new_call()
534 let extra = FrameData { call_id, catch_unwind: None };
535 Ok(frame.with_extra(extra))
539 ecx: &'a InterpCx<'mir, 'tcx, Self>
540 ) -> &'a [Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>] {
541 ecx.active_thread_stack()
545 ecx: &'a mut InterpCx<'mir, 'tcx, Self>
546 ) -> &'a mut Vec<Frame<'mir, 'tcx, Self::PointerTag, Self::FrameExtra>> {
547 ecx.active_thread_stack_mut()
551 fn after_stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
552 if ecx.memory.extra.stacked_borrows.is_some() {
553 ecx.retag_return_place()
561 ecx: &mut InterpCx<'mir, 'tcx, Self>,
562 frame: Frame<'mir, 'tcx, Tag, FrameData<'tcx>>,
564 ) -> InterpResult<'tcx, StackPopJump> {
565 ecx.handle_stack_pop(frame.extra, unwinding)
570 memory: &Memory<'mir, 'tcx, Self>,
572 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
573 intptrcast::GlobalState::int_to_ptr(int, memory)
578 memory: &Memory<'mir, 'tcx, Self>,
579 ptr: Pointer<Self::PointerTag>,
580 ) -> InterpResult<'tcx, u64> {
581 intptrcast::GlobalState::ptr_to_int(ptr, memory)
585 impl AllocationExtra<Tag> for AllocExtra {
587 fn memory_read<'tcx>(
588 alloc: &Allocation<Tag, AllocExtra>,
591 ) -> InterpResult<'tcx> {
592 if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
593 stacked_borrows.memory_read(ptr, size)
600 fn memory_written<'tcx>(
601 alloc: &mut Allocation<Tag, AllocExtra>,
604 ) -> InterpResult<'tcx> {
605 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
606 stacked_borrows.memory_written(ptr, size)
613 fn memory_deallocated<'tcx>(
614 alloc: &mut Allocation<Tag, AllocExtra>,
617 ) -> InterpResult<'tcx> {
618 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
619 stacked_borrows.memory_deallocated(ptr, size)