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;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_middle::{mir, ty};
15 use rustc_target::abi::{LayoutOf, Size};
17 use rustc_span::symbol::{sym, Symbol};
21 // Some global facts about the emulated machine.
22 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
23 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
24 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
25 pub const NUM_CPUS: u64 = 1;
27 /// Extra data stored with each stack frame
29 pub struct FrameData<'tcx> {
30 /// Extra data for Stacked Borrows.
31 pub call_id: stacked_borrows::CallId,
33 /// If this is Some(), then this is a special "catch unwind" frame (the frame of `try_fn`
34 /// called by `try`). When this frame is popped during unwinding a panic,
35 /// we stop unwinding, use the `CatchUnwindData` to handle catching.
36 pub catch_unwind: Option<CatchUnwindData<'tcx>>,
39 /// Extra memory kinds
40 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
41 pub enum MiriMemoryKind {
42 /// `__rust_alloc` memory.
46 /// Windows `HeapAlloc` memory.
48 /// Memory for args, errno, extern statics and other parts of the machine-managed environment.
49 /// This memory may leak.
51 /// Memory for env vars. Separate from `Machine` because we clean it up and leak-check it.
53 /// Globals copied from `tcx`.
54 /// This memory may leak.
58 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
60 fn into(self) -> MemoryKind<MiriMemoryKind> {
61 MemoryKind::Machine(self)
65 /// Extra per-allocation data
66 #[derive(Debug, Clone)]
67 pub struct AllocExtra {
68 /// Stacked Borrows state is only added if it is enabled.
69 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
72 /// Extra global memory data
73 #[derive(Clone, Debug)]
74 pub struct MemoryExtra {
75 pub stacked_borrows: Option<stacked_borrows::MemoryExtra>,
76 pub intptrcast: intptrcast::MemoryExtra,
78 /// Mapping extern static names to their canonical allocation.
79 extern_statics: FxHashMap<Symbol, AllocId>,
81 /// The random number generator used for resolving non-determinism.
82 /// Needs to be queried by ptr_to_int, hence needs interior mutability.
83 pub(crate) rng: RefCell<StdRng>,
85 /// An allocation ID to report when it is being allocated
86 /// (helps for debugging memory leaks).
87 tracked_alloc_id: Option<AllocId>,
91 pub fn new(rng: StdRng, stacked_borrows: bool, tracked_pointer_tag: Option<PtrId>, tracked_alloc_id: Option<AllocId>) -> Self {
92 let stacked_borrows = if stacked_borrows {
93 Some(Rc::new(RefCell::new(stacked_borrows::GlobalState::new(tracked_pointer_tag))))
99 intptrcast: Default::default(),
100 extern_statics: FxHashMap::default(),
101 rng: RefCell::new(rng),
106 fn add_extern_static<'tcx, 'mir>(
107 this: &mut MiriEvalContext<'mir, 'tcx>,
111 let ptr = ptr.assert_ptr();
112 assert_eq!(ptr.offset, Size::ZERO);
116 .insert(Symbol::intern(name), ptr.alloc_id)
120 /// Sets up the "extern statics" for this machine.
121 pub fn init_extern_statics<'tcx, 'mir>(
122 this: &mut MiriEvalContext<'mir, 'tcx>,
123 ) -> InterpResult<'tcx> {
124 match this.tcx.sess.target.target.target_os.as_str() {
126 // "__cxa_thread_atexit_impl"
127 // This should be all-zero, pointer-sized.
128 let layout = this.layout_of(this.tcx.types.usize)?;
129 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
130 this.write_scalar(Scalar::from_machine_usize(0, this), place.into())?;
131 Self::add_extern_static(this, "__cxa_thread_atexit_impl", place.ptr);
133 Self::add_extern_static(this, "environ", this.machine.env_vars.environ.unwrap().ptr);
137 // This is some obscure hack that is part of the Windows TLS story. It's a `u8`.
138 let layout = this.layout_of(this.tcx.types.u8)?;
139 let place = this.allocate(layout, MiriMemoryKind::Machine.into());
140 this.write_scalar(Scalar::from_u8(0), place.into())?;
141 Self::add_extern_static(this, "_tls_used", place.ptr);
143 _ => {} // No "extern statics" supported on this target
149 /// The machine itself.
150 pub struct Evaluator<'tcx> {
151 /// Environment variables set by `setenv`.
152 /// Miri does not expose env vars from the host to the emulated program.
153 pub(crate) env_vars: EnvVars<'tcx>,
155 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
156 /// These are *pointers* to argc/argv because macOS.
157 /// We also need the full command line as one string because of Windows.
158 pub(crate) argc: Option<Scalar<Tag>>,
159 pub(crate) argv: Option<Scalar<Tag>>,
160 pub(crate) cmd_line: Option<Scalar<Tag>>,
162 /// Last OS error location in memory. It is a 32-bit integer.
163 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
166 pub(crate) tls: TlsData<'tcx>,
168 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
169 /// and random number generation is delegated to the host.
170 pub(crate) communicate: bool,
172 /// Whether to enforce the validity invariant.
173 pub(crate) validate: bool,
175 pub(crate) file_handler: FileHandler,
176 pub(crate) dir_handler: DirHandler,
178 /// The temporary used for storing the argument of
179 /// the call to `miri_start_panic` (the panic payload) when unwinding.
180 /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
181 pub(crate) panic_payload: Option<Scalar<Tag>>,
183 /// The "time anchor" for this machine's monotone clock (for `Instant` simulation).
184 pub(crate) time_anchor: Instant,
187 impl<'tcx> Evaluator<'tcx> {
188 pub(crate) fn new(communicate: bool, validate: bool) -> Self {
190 // `env_vars` could be initialized properly here if `Memory` were available before
191 // calling this method.
192 env_vars: EnvVars::default(),
197 tls: TlsData::default(),
200 file_handler: Default::default(),
201 dir_handler: Default::default(),
203 time_anchor: Instant::now(),
208 /// A rustc InterpCx for Miri.
209 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
211 /// A little trait that's useful to be inherited by extension traits.
212 pub trait MiriEvalContextExt<'mir, 'tcx> {
213 fn eval_context_ref<'a>(&'a self) -> &'a MiriEvalContext<'mir, 'tcx>;
214 fn eval_context_mut<'a>(&'a mut self) -> &'a mut MiriEvalContext<'mir, 'tcx>;
216 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
218 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
222 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
227 /// Machine hook implementations.
228 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
229 type MemoryKind = MiriMemoryKind;
231 type FrameExtra = FrameData<'tcx>;
232 type MemoryExtra = MemoryExtra;
233 type AllocExtra = AllocExtra;
234 type PointerTag = Tag;
235 type ExtraFnVal = Dlsym;
238 MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
240 const GLOBAL_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Global);
242 const CHECK_ALIGN: bool = true;
245 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
250 fn find_mir_or_eval_fn(
251 ecx: &mut InterpCx<'mir, 'tcx, Self>,
252 instance: ty::Instance<'tcx>,
253 args: &[OpTy<'tcx, Tag>],
254 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
255 unwind: Option<mir::BasicBlock>,
256 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
257 ecx.find_mir_or_eval_fn(instance, args, ret, unwind)
262 ecx: &mut InterpCx<'mir, 'tcx, Self>,
264 args: &[OpTy<'tcx, Tag>],
265 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
266 _unwind: Option<mir::BasicBlock>,
267 ) -> InterpResult<'tcx> {
268 ecx.call_dlsym(fn_val, args, ret)
273 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
274 instance: ty::Instance<'tcx>,
275 args: &[OpTy<'tcx, Tag>],
276 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
277 unwind: Option<mir::BasicBlock>,
278 ) -> InterpResult<'tcx> {
279 ecx.call_intrinsic(instance, args, ret, unwind)
284 ecx: &mut InterpCx<'mir, 'tcx, Self>,
285 msg: &mir::AssertMessage<'tcx>,
286 unwind: Option<mir::BasicBlock>,
287 ) -> InterpResult<'tcx> {
288 ecx.assert_panic(msg, unwind)
292 fn abort(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, !> {
293 throw_machine_stop!(TerminationInfo::Abort(None))
298 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
300 left: ImmTy<'tcx, Tag>,
301 right: ImmTy<'tcx, Tag>,
302 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, ty::Ty<'tcx>)> {
303 ecx.binary_ptr_op(bin_op, left, right)
307 ecx: &mut InterpCx<'mir, 'tcx, Self>,
308 dest: PlaceTy<'tcx, Tag>,
309 ) -> InterpResult<'tcx> {
310 trace!("box_alloc for {:?}", dest.layout.ty);
311 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
312 // First argument: `size`.
313 // (`0` is allowed here -- this is expected to be handled by the lang item).
314 let size = Scalar::from_machine_usize(layout.size.bytes(), ecx);
316 // Second argument: `align`.
317 let align = Scalar::from_machine_usize(layout.align.abi.bytes(), ecx);
319 // Call the `exchange_malloc` lang item.
320 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
321 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
324 &[size.into(), align.into()],
326 // Don't do anything when we are done. The `statement()` function will increment
327 // the old stack frame's stmt counter to the next statement, which means that when
328 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
329 StackPopCleanup::None { cleanup: true },
334 fn canonical_alloc_id(mem: &Memory<'mir, 'tcx, Self>, id: AllocId) -> AllocId {
336 // Figure out if this is an extern static, and if yes, which one.
337 let def_id = match tcx.alloc_map.lock().get(id) {
338 Some(GlobalAlloc::Static(def_id)) if tcx.is_foreign_item(def_id) => def_id,
340 // No need to canonicalize anything.
344 let attrs = tcx.get_attrs(def_id);
345 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
347 None => tcx.item_name(def_id),
349 // Check if we know this one.
350 if let Some(canonical_id) = mem.extra.extern_statics.get(&link_name) {
351 trace!("canonical_alloc_id: {:?} ({}) -> {:?}", id, link_name, canonical_id);
354 // Return original id; `Memory::get_static_alloc` will throw an error.
359 fn init_allocation_extra<'b>(
360 memory_extra: &MemoryExtra,
362 alloc: Cow<'b, Allocation>,
363 kind: Option<MemoryKind<Self::MemoryKind>>,
364 ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
365 if Some(id) == memory_extra.tracked_alloc_id {
366 register_diagnostic(NonHaltingDiagnostic::CreatedAlloc(id));
369 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
370 let alloc = alloc.into_owned();
371 let (stacks, base_tag) =
372 if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
373 let (stacks, base_tag) =
374 Stacks::new_allocation(id, alloc.size, Rc::clone(stacked_borrows), kind);
375 (Some(stacks), base_tag)
377 // No stacks, no tag.
378 (None, Tag::Untagged)
380 let mut stacked_borrows = memory_extra.stacked_borrows.as_ref().map(|sb| sb.borrow_mut());
381 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
383 if let Some(stacked_borrows) = stacked_borrows.as_mut() {
384 // Only globals may already contain pointers at this point
385 assert_eq!(kind, MiriMemoryKind::Global.into());
386 stacked_borrows.global_base_ptr(alloc)
391 AllocExtra { stacked_borrows: stacks },
393 (Cow::Owned(alloc), base_tag)
397 fn tag_global_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
398 if let Some(stacked_borrows) = memory_extra.stacked_borrows.as_ref() {
399 stacked_borrows.borrow_mut().global_base_ptr(id)
407 ecx: &mut InterpCx<'mir, 'tcx, Self>,
408 kind: mir::RetagKind,
409 place: PlaceTy<'tcx, Tag>,
410 ) -> InterpResult<'tcx> {
411 if ecx.memory.extra.stacked_borrows.is_none() {
415 ecx.retag(kind, place)
420 fn stack_push(ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx, FrameData<'tcx>> {
421 let stacked_borrows = ecx.memory.extra.stacked_borrows.as_ref();
422 let call_id = stacked_borrows.map_or(NonZeroU64::new(1).unwrap(), |stacked_borrows| {
423 stacked_borrows.borrow_mut().new_call()
425 Ok(FrameData { call_id, catch_unwind: None })
430 ecx: &mut InterpCx<'mir, 'tcx, Self>,
431 extra: FrameData<'tcx>,
433 ) -> InterpResult<'tcx, StackPopJump> {
434 ecx.handle_stack_pop(extra, unwinding)
439 memory: &Memory<'mir, 'tcx, Self>,
441 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
442 intptrcast::GlobalState::int_to_ptr(int, memory)
447 memory: &Memory<'mir, 'tcx, Self>,
448 ptr: Pointer<Self::PointerTag>,
449 ) -> InterpResult<'tcx, u64> {
450 intptrcast::GlobalState::ptr_to_int(ptr, memory)
454 impl AllocationExtra<Tag> for AllocExtra {
456 fn memory_read<'tcx>(
457 alloc: &Allocation<Tag, AllocExtra>,
460 ) -> InterpResult<'tcx> {
461 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
462 stacked_borrows.memory_read(ptr, size)
469 fn memory_written<'tcx>(
470 alloc: &mut Allocation<Tag, AllocExtra>,
473 ) -> InterpResult<'tcx> {
474 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
475 stacked_borrows.memory_written(ptr, size)
482 fn memory_deallocated<'tcx>(
483 alloc: &mut Allocation<Tag, AllocExtra>,
486 ) -> InterpResult<'tcx> {
487 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
488 stacked_borrows.memory_deallocated(ptr, size)
495 impl MayLeak for MiriMemoryKind {
497 fn may_leak(self) -> bool {
498 use self::MiriMemoryKind::*;
500 Rust | C | WinHeap | Env => false,
501 Machine | Global => true,