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;
11 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_target::abi::{LayoutOf, Size};
28 // Some global facts about the emulated machine.
29 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
30 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
31 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
32 pub const NUM_CPUS: u64 = 1;
34 /// Extra data stored with each stack frame
36 pub struct FrameData<'tcx> {
37 /// Extra data for Stacked Borrows.
38 pub call_id: stacked_borrows::CallId,
40 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
41 /// called by `try`). When this frame is popped during unwinding a panic,
42 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
43 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
46 /// Extra memory kinds
47 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
48 pub enum MiriMemoryKind {
49 /// `__rust_alloc` memory.
53 /// Windows `HeapAlloc` memory.
55 /// Memory for args, errno, extern statics and other parts of the machine-managed environment.
56 /// This memory may leak.
58 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
60 /// Globals copied from `tcx`.
61 /// This memory may leak.
65 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
67 fn into(self) -> MemoryKind<MiriMemoryKind> {
68 MemoryKind::Machine(self)
72 /// Extra per-allocation data
73 #[derive(Debug, Clone)]
74 pub struct AllocExtra {
75 /// Stacked Borrows state is only added if it is enabled.
76 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
79 /// Extra global memory data
80 #[derive(Clone, Debug)]
81 pub struct MemoryExtra {
82 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
83 pub intptrcast: intptrcast::MemoryExtra,
85 /// Mapping extern static names to their canonical allocation.
86 extern_statics: FxHashMap<Symbol, AllocId>,
88 /// The random number generator used for resolving non-determinism.
89 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
90 pub(crate) rng: RefCell<StdRng>,
92 /// An allocation ID to report when it is being allocated
93 /// (helps for debugging memory leaks).
94 tracked_alloc_id: Option<AllocId>,
98 pub fn new(rng: StdRng, stacked_borrows: bool, tracked_pointer_tag: Option<PtrId>, tracked_alloc_id: Option<AllocId>) -> Self {
99 let stacked_borrows = if stacked_borrows {
100 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
106 intptrcast: Default::default(),
107 extern_statics: FxHashMap::default(),
108 rng: RefCell::new(rng),
113 fn add_extern_static<'tcx, 'mir>(
114 this: &mut MiriEvalContext<'mir, 'tcx>,
118 let ptr = ptr.assert_ptr();
119 assert_eq!(ptr.offset, Size::ZERO);
123 .insert(Symbol::intern(name), ptr.alloc_id)
127 /// Sets up the "extern statics" for this machine.
128 pub fn init_extern_statics<'tcx, 'mir>(
129 this: &mut MiriEvalContext<'mir, 'tcx>,
130 ) -> InterpResult<'tcx> {
131 match this.tcx.sess.target.target.target_os.as_str() {
133 // "__cxa_thread_atexit_impl"
134 // This should be all-zero, pointer-sized.
135 let layout = this.layout_of(this.tcx.types.usize)?;
136 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
137 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
138 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
140 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
144 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
145 let layout = this.layout_of(this.tcx.types.u8)?;
146 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
147 this.write_scalar(Scalar::from_u8(0), place.into())?;
148 Self::add_extern_static(this, "_tls_used", place.ptr);
150 _ => {} // No "extern statics" supported on this target
156 /// Precomputed layouts of primitive types
157 pub(crate) struct PrimitiveLayouts<'tcx> {
158 pub(crate) i32: TyAndLayout<'tcx>,
159 pub(crate) u32: TyAndLayout<'tcx>,
162 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
163 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
165 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
166 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
171 /// The machine itself.
172 pub struct Evaluator<'tcx> {
173 /// Environment variables set by `setenv`.
174 /// Miri does not expose env vars from the host to the emulated program.
175 pub(crate) env_vars: EnvVars<'tcx>,
177 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
178 /// These are *pointers* to argc/argv because macOS.
179 /// We also need the full command line as one string because of Windows.
180 pub(crate) argc: Option<Scalar<Tag>>,
181 pub(crate) argv: Option<Scalar<Tag>>,
182 pub(crate) cmd_line: Option<Scalar<Tag>>,
184 /// Last OS error location in memory. It is a 32-bit integer.
185 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
188 pub(crate) tls: TlsData<'tcx>,
190 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
191 /// and random number generation is delegated to the host.
192 pub(crate) communicate: bool,
194 /// Whether to enforce the validity invariant.
195 pub(crate) validate: bool,
197 pub(crate) file_handler: FileHandler,
198 pub(crate) dir_handler: DirHandler,
200 /// The temporary used for storing the argument of
201 /// the call to `miri_start_panic` (the panic payload) when unwinding.
202 /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
203 pub(crate) panic_payload: Option<Scalar<Tag>>,
205 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
206 pub(crate) time_anchor: Instant,
208 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
209 /// FIXME: Search through the rest of the codebase for more layout_of() calls that
210 /// could be stored here.
211 pub(crate) layouts: PrimitiveLayouts<'tcx>,
214 impl<'tcx> Evaluator<'tcx> {
218 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
220 let layouts = PrimitiveLayouts::new(layout_cx)
221 .expect("Couldn't get layouts of primitive types");
223 // `env_vars` could be initialized properly here if `Memory` were available before
224 // calling this method.
225 env_vars: EnvVars::default(),
230 tls: TlsData::default(),
233 file_handler: Default::default(),
234 dir_handler: Default::default(),
236 time_anchor: Instant::now(),
242 /// A rustc InterpCx for Miri.
243 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
245 /// A little trait that's useful to be inherited by extension traits.
246 pub trait MiriEvalContextExt<'mir, 'tcx> {
247 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
248 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
250 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
252 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
256 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
261 /// Machine hook implementations.
262 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
263 type MemoryKind = MiriMemoryKind;
265 type FrameExtra = FrameData<'tcx>;
266 type MemoryExtra = MemoryExtra;
267 type AllocExtra = AllocExtra;
268 type PointerTag = Tag;
269 type ExtraFnVal = Dlsym;
272 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
274 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
276 const CHECK_ALIGN: bool = true;
279 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
284 fn find_mir_or_eval_fn(
285 ecx: &mut InterpCx<'mir, 'tcx, Self>,
286 instance: ty::Instance<'tcx>,
287 args: &[OpTy<'tcx, Tag>],
288 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
289 unwind: Option<mir::BasicBlock>,
290 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
291 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
296 ecx: &mut InterpCx<'mir, 'tcx, Self>,
298 args: &[OpTy<'tcx, Tag>],
299 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
300 _unwind: Option<mir::BasicBlock>,
301 ) -> InterpResult<'tcx> {
302 ecx.call_dlsym(fn_val, args, ret)
307 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
308 instance: ty::Instance<'tcx>,
309 args: &[OpTy<'tcx, Tag>],
310 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
311 unwind: Option<mir::BasicBlock>,
312 ) -> InterpResult<'tcx> {
313 ecx.call_intrinsic(instance, args, ret, unwind)
318 ecx: &mut InterpCx<'mir, 'tcx, Self>,
319 msg: &mir::AssertMessage<'tcx>,
320 unwind: Option<mir::BasicBlock>,
321 ) -> InterpResult<'tcx> {
322 ecx.assert_panic(msg, unwind)
326 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
327 throw_machine_stop!(TerminationInfo::Abort(None))
332 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
334 left: ImmTy<'tcx, Tag>,
335 right: ImmTy<'tcx, Tag>,
336 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
337 ecx.binary_ptr_op(bin_op, left, right)
341 ecx: &mut InterpCx<'mir, 'tcx, Self>,
342 dest: PlaceTy<'tcx, Tag>,
343 ) -> InterpResult<'tcx> {
344 trace!("box_alloc for {:?}", dest.layout.ty);
345 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
346 // First argument: `size`.
347 // (`0` is allowed here -- this is expected to be handled by the lang item).
348 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
350 // Second argument: `align`.
351 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
353 // Call the `exchange_malloc` lang item.
354 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
355 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
358 &[size.into(), align.into()],
360 // Don't do anything when we are done. The `statement()` function will increment
361 // the old stack frame's stmt counter to the next statement, which means that when
362 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
363 StackPopCleanup::None { cleanup: true },
368 fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
370 // Figure out if this is an extern static, and if yes, which one.
371 let def_id = match tcx.alloc_map.lock().get(id) {
372 Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
374 // No need to canonicalize anything.
378 let attrs = tcx.get_attrs(def_id);
379 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
381 None => tcx.item_name(def_id),
383 // Check if we know this one.
384 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
385 trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
388 // Return original id; `Memory::get_static_alloc` will throw an error.
393 fn init_allocation_extra<'b>(
394 memory_extra: &MemoryExtra,
396 alloc: Cow<'b, Allocation>,
397 kind: Option<MemoryKind<Self::MemoryKind>>,
398 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
399 if Some(id) == memory_extra.tracked_alloc_id {
400 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
403 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
404 let alloc = alloc.into_owned();
405 let (stacks, base_tag) =
406 if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
407 let (stacks, base_tag) =
408 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
409 (Some(stacks), base_tag)
411 // No stacks, no tag.
412 (None, Tag::Untagged)
414 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
415 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
417 if let Some(stacked_borrows) = stacked_borrows.as_mut() {
418 // Only globals may already contain pointers at this point
419 assert_eq!(kind, MiriMemoryKind::Global.into());
420 stacked_borrows.global_base_ptr(alloc)
425 AllocExtra { stacked_borrows: stacks },
427 (Cow::Owned(alloc), base_tag)
431 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
432 if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
433 stacked_borrows.borrow_mut().global_base_ptr(id)
441 ecx: &mut InterpCx<'mir, 'tcx, Self>,
442 kind: mir::RetagKind,
443 place: PlaceTy<'tcx, Tag>,
444 ) -> InterpResult<'tcx> {
445 if ecx.memory.extra.stacked_borrows.is_none() {
449 ecx.retag(kind, place)
454 fn stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, FrameData<'tcx>> {
455 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
456 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
457 stacked_borrows.borrow_mut().new_call()
459 Ok(FrameData { call_id, catch_unwind: None })
464 ecx: &mut InterpCx<'mir, 'tcx, Self>,
465 extra: FrameData<'tcx>,
467 ) -> InterpResult<'tcx, StackPopJump> {
468 ecx.handle_stack_pop(extra, unwinding)
473 memory: &Memory<'mir, 'tcx, Self>,
475 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
476 intptrcast::GlobalState::int_to_ptr(int, memory)
481 memory: &Memory<'mir, 'tcx, Self>,
482 ptr: Pointer<Self::PointerTag>,
483 ) -> InterpResult<'tcx, u64> {
484 intptrcast::GlobalState::ptr_to_int(ptr, memory)
488 impl AllocationExtra<Tag> for AllocExtra {
490 fn memory_read<'tcx>(
491 alloc: &Allocation<Tag, AllocExtra>,
494 ) -> InterpResult<'tcx> {
495 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
496 stacked_borrows.memory_read(ptr, size)
503 fn memory_written<'tcx>(
504 alloc: &mut Allocation<Tag, AllocExtra>,
507 ) -> InterpResult<'tcx> {
508 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
509 stacked_borrows.memory_written(ptr, size)
516 fn memory_deallocated<'tcx>(
517 alloc: &mut Allocation<Tag, AllocExtra>,
520 ) -> InterpResult<'tcx> {
521 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
522 stacked_borrows.memory_deallocated(ptr, size)
529 impl MayLeak for MiriMemoryKind {
531 fn may_leak(self) -> bool {
532 use self::MiriMemoryKind::*;
534 Rust | C | WinHeap | Env => false,
535 Machine | Global => true,