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 // 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, extern statics 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.
66 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
68 fn into(self) -> MemoryKind<MiriMemoryKind> {
69 MemoryKind::Machine(self)
73 impl MayLeak for MiriMemoryKind {
75 fn may_leak(self) -> bool {
76 use self::MiriMemoryKind::*;
78 Rust | C | WinHeap | Env => false,
79 Machine | Global => true,
84 impl fmt::Display for MiriMemoryKind {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 use self::MiriMemoryKind::*;
88 Rust => write!(f, "Rust heap"),
89 C => write!(f, "C heap"),
90 WinHeap => write!(f, "Windows heap"),
91 Machine => write!(f, "machine-managed memory"),
92 Env => write!(f, "environment variable"),
93 Global => write!(f, "global"),
98 /// Extra per-allocation data
99 #[derive(Debug, Clone)]
100 pub struct AllocExtra {
101 /// Stacked Borrows state is only added if it is enabled.
102 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
105 /// Extra global memory data
106 #[derive(Clone, Debug)]
107 pub struct MemoryExtra {
108 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
109 pub intptrcast: intptrcast::MemoryExtra,
111 /// Mapping extern static names to their canonical allocation.
112 extern_statics: FxHashMap<Symbol, AllocId>,
114 /// The random number generator used for resolving non-determinism.
115 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
116 pub(crate) rng: RefCell<StdRng>,
118 /// An allocation ID to report when it is being allocated
119 /// (helps for debugging memory leaks).
120 tracked_alloc_id: Option<AllocId>,
122 /// Controls whether alignment of memory accesses is being checked.
123 check_alignment: bool,
129 stacked_borrows: bool,
130 tracked_pointer_tag: Option<PtrId>,
131 tracked_alloc_id: Option<AllocId>,
132 check_alignment: bool,
134 let stacked_borrows = if stacked_borrows {
135 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
141 intptrcast: Default::default(),
142 extern_statics: FxHashMap::default(),
143 rng: RefCell::new(rng),
149 fn add_extern_static<'tcx, 'mir>(
150 this: &mut MiriEvalContext<'mir, 'tcx>,
154 let ptr = ptr.assert_ptr();
155 assert_eq!(ptr.offset, Size::ZERO);
159 .insert(Symbol::intern(name), ptr.alloc_id)
163 /// Sets up the "extern statics" for this machine.
164 pub fn init_extern_statics<'tcx, 'mir>(
165 this: &mut MiriEvalContext<'mir, 'tcx>,
166 ) -> InterpResult<'tcx> {
167 match this.tcx.sess.target.target.target_os.as_str() {
169 // "__cxa_thread_atexit_impl"
170 // This should be all-zero, pointer-sized.
171 let layout = this.layout_of(this.tcx.types.usize)?;
172 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
173 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
174 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
176 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
180 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
181 let layout = this.layout_of(this.tcx.types.u8)?;
182 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
183 this.write_scalar(Scalar::from_u8(0), place.into())?;
184 Self::add_extern_static(this, "_tls_used", place.ptr);
186 _ => {} // No "extern statics" supported on this target
192 /// Precomputed layouts of primitive types
193 pub(crate) struct PrimitiveLayouts<'tcx> {
194 pub(crate) i32: TyAndLayout<'tcx>,
195 pub(crate) u32: TyAndLayout<'tcx>,
198 impl<'mir, 'tcx: 'mir> PrimitiveLayouts<'tcx> {
199 fn new(layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>) -> Result<Self, LayoutError<'tcx>> {
201 i32: layout_cx.layout_of(layout_cx.tcx.types.i32)?,
202 u32: layout_cx.layout_of(layout_cx.tcx.types.u32)?,
207 /// The machine itself.
208 pub struct Evaluator<'tcx> {
209 /// Environment variables set by `setenv`.
210 /// Miri does not expose env vars from the host to the emulated program.
211 pub(crate) env_vars: EnvVars<'tcx>,
213 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
214 /// These are *pointers* to argc/argv because macOS.
215 /// We also need the full command line as one string because of Windows.
216 pub(crate) argc: Option<Scalar<Tag>>,
217 pub(crate) argv: Option<Scalar<Tag>>,
218 pub(crate) cmd_line: Option<Scalar<Tag>>,
220 /// Last OS error location in memory. It is a 32-bit integer.
221 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
224 pub(crate) tls: TlsData<'tcx>,
226 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
227 /// and random number generation is delegated to the host.
228 pub(crate) communicate: bool,
230 /// Whether to enforce the validity invariant.
231 pub(crate) validate: bool,
233 pub(crate) file_handler: FileHandler,
234 pub(crate) dir_handler: DirHandler,
236 /// The temporary used for storing the argument of
237 /// the call to `miri_start_panic` (the panic payload) when unwinding.
238 /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
239 pub(crate) panic_payload: Option<Scalar<Tag>>,
241 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
242 pub(crate) time_anchor: Instant,
244 /// Precomputed `TyLayout`s for primitive data types that are commonly used inside Miri.
245 /// FIXME: Search through the rest of the codebase for more layout_of() calls that
246 /// could be stored here.
247 pub(crate) layouts: PrimitiveLayouts<'tcx>,
250 impl<'tcx> Evaluator<'tcx> {
254 layout_cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
256 let layouts = PrimitiveLayouts::new(layout_cx)
257 .expect("Couldn't get layouts of primitive types");
259 // `env_vars` could be initialized properly here if `Memory` were available before
260 // calling this method.
261 env_vars: EnvVars::default(),
266 tls: TlsData::default(),
269 file_handler: Default::default(),
270 dir_handler: Default::default(),
272 time_anchor: Instant::now(),
278 /// A rustc InterpCx for Miri.
279 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
281 /// A little trait that's useful to be inherited by extension traits.
282 pub trait MiriEvalContextExt<'mir, 'tcx> {
283 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
284 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
286 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
288 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
292 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
297 /// Machine hook implementations.
298 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
299 type MemoryKind = MiriMemoryKind;
301 type FrameExtra = FrameData<'tcx>;
302 type MemoryExtra = MemoryExtra;
303 type AllocExtra = AllocExtra;
304 type PointerTag = Tag;
305 type ExtraFnVal = Dlsym;
308 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
310 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
313 fn enforce_alignment(memory_extra: &MemoryExtra) -> bool {
314 memory_extra.check_alignment
318 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
323 fn find_mir_or_eval_fn(
324 ecx: &mut InterpCx<'mir, 'tcx, Self>,
325 instance: ty::Instance<'tcx>,
326 args: &[OpTy<'tcx, Tag>],
327 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
328 unwind: Option<mir::BasicBlock>,
329 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
330 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
335 ecx: &mut InterpCx<'mir, 'tcx, Self>,
337 args: &[OpTy<'tcx, Tag>],
338 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
339 _unwind: Option<mir::BasicBlock>,
340 ) -> InterpResult<'tcx> {
341 ecx.call_dlsym(fn_val, args, ret)
346 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
347 instance: ty::Instance<'tcx>,
348 args: &[OpTy<'tcx, Tag>],
349 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
350 unwind: Option<mir::BasicBlock>,
351 ) -> InterpResult<'tcx> {
352 ecx.call_intrinsic(instance, args, ret, unwind)
357 ecx: &mut InterpCx<'mir, 'tcx, Self>,
358 msg: &mir::AssertMessage<'tcx>,
359 unwind: Option<mir::BasicBlock>,
360 ) -> InterpResult<'tcx> {
361 ecx.assert_panic(msg, unwind)
365 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
366 throw_machine_stop!(TerminationInfo::Abort(None))
371 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
373 left: ImmTy<'tcx, Tag>,
374 right: ImmTy<'tcx, Tag>,
375 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
376 ecx.binary_ptr_op(bin_op, left, right)
380 ecx: &mut InterpCx<'mir, 'tcx, Self>,
381 dest: PlaceTy<'tcx, Tag>,
382 ) -> InterpResult<'tcx> {
383 trace!("box_alloc for {:?}", dest.layout.ty);
384 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
385 // First argument: `size`.
386 // (`0` is allowed here -- this is expected to be handled by the lang item).
387 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
389 // Second argument: `align`.
390 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
392 // Call the `exchange_malloc` lang item.
393 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
394 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
397 &[size.into(), align.into()],
399 // Don't do anything when we are done. The `statement()` function will increment
400 // the old stack frame's stmt counter to the next statement, which means that when
401 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
402 StackPopCleanup::None { cleanup: true },
407 fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
409 // Figure out if this is an extern static, and if yes, which one.
410 let def_id = match tcx.alloc_map.lock().get(id) {
411 Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
413 // No need to canonicalize anything.
417 let attrs = tcx.get_attrs(def_id);
418 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
420 None => tcx.item_name(def_id),
422 // Check if we know this one.
423 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
424 trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
427 // Return original id; `Memory::get_static_alloc` will throw an error.
432 fn init_allocation_extra<'b>(
433 memory_extra: &MemoryExtra,
435 alloc: Cow<'b, Allocation>,
436 kind: Option<MemoryKind<Self::MemoryKind>>,
437 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
438 if Some(id) == memory_extra.tracked_alloc_id {
439 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
442 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
443 let alloc = alloc.into_owned();
444 let (stacks, base_tag) =
445 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
446 let (stacks, base_tag) =
447 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
448 (Some(stacks), base_tag)
450 // No stacks, no tag.
451 (None, Tag::Untagged)
453 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
454 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
456 if let Some(stacked_borrows) = &mut stacked_borrows {
457 // Only globals may already contain pointers at this point
458 assert_eq!(kind, MiriMemoryKind::Global.into());
459 stacked_borrows.global_base_ptr(alloc)
464 AllocExtra { stacked_borrows: stacks },
466 (Cow::Owned(alloc), base_tag)
470 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
471 if let Some(stacked_borrows) = &memory_extra.stacked_borrows {
472 stacked_borrows.borrow_mut().global_base_ptr(id)
480 ecx: &mut InterpCx<'mir, 'tcx, Self>,
481 kind: mir::RetagKind,
482 place: PlaceTy<'tcx, Tag>,
483 ) -> InterpResult<'tcx> {
484 if ecx.memory.extra.stacked_borrows.is_none() {
488 ecx.retag(kind, place)
493 fn stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, FrameData<'tcx>> {
494 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
495 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
496 stacked_borrows.borrow_mut().new_call()
498 Ok(FrameData { call_id, catch_unwind: None })
503 ecx: &mut InterpCx<'mir, 'tcx, Self>,
504 extra: FrameData<'tcx>,
506 ) -> InterpResult<'tcx, StackPopJump> {
507 ecx.handle_stack_pop(extra, unwinding)
512 memory: &Memory<'mir, 'tcx, Self>,
514 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
515 intptrcast::GlobalState::int_to_ptr(int, memory)
520 memory: &Memory<'mir, 'tcx, Self>,
521 ptr: Pointer<Self::PointerTag>,
522 ) -> InterpResult<'tcx, u64> {
523 intptrcast::GlobalState::ptr_to_int(ptr, memory)
527 impl AllocationExtra<Tag> for AllocExtra {
529 fn memory_read<'tcx>(
530 alloc: &Allocation<Tag, AllocExtra>,
533 ) -> InterpResult<'tcx> {
534 if let Some(stacked_borrows) = &alloc.extra.stacked_borrows {
535 stacked_borrows.memory_read(ptr, size)
542 fn memory_written<'tcx>(
543 alloc: &mut Allocation<Tag, AllocExtra>,
546 ) -> InterpResult<'tcx> {
547 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
548 stacked_borrows.memory_written(ptr, size)
555 fn memory_deallocated<'tcx>(
556 alloc: &mut Allocation<Tag, AllocExtra>,
559 ) -> InterpResult<'tcx> {
560 if let Some(stacked_borrows) = &mut alloc.extra.stacked_borrows {
561 stacked_borrows.memory_deallocated(ptr, size)