1 //! Global machine state as well as implementation of the interpreter engine
5 use std::cell::RefCell;
8 use rand::rngs::StdRng;
10 use rustc::hir::def_id::DefId;
11 use rustc::ty::{self, layout::{Size, LayoutOf}, Ty, TyCtxt};
13 use syntax::{attr, source_map::Span, symbol::sym};
17 // Some global facts about the emulated machine.
18 pub const PAGE_SIZE: u64 = 4 * 1024; // FIXME: adjust to target architecture
19 pub const STACK_ADDR: u64 = 32 * PAGE_SIZE; // not really about the "stack", but where we start assigning integer addresses to allocations
20 pub const STACK_SIZE: u64 = 16 * PAGE_SIZE; // whatever
21 pub const NUM_CPUS: u64 = 1;
23 /// Extra data stored with each stack frame
25 pub struct FrameData<'tcx> {
26 /// Extra data for Stacked Borrows.
27 pub call_id: stacked_borrows::CallId,
29 /// If this is Some(), then this is a special "catch unwind" frame (the frame of the closure
30 /// called by `__rustc_maybe_catch_panic`). When this frame is popped during unwinding a panic,
31 /// we stop unwinding, use the `CatchUnwindData` to
32 /// store the panic payload, and continue execution in the parent frame.
33 pub catch_panic: Option<CatchUnwindData<'tcx>>,
37 /// Extra memory kinds
38 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
39 pub enum MiriMemoryKind {
40 /// `__rust_alloc` memory.
44 /// Windows `HeapAlloc` memory.
46 /// Part of env var emulation.
52 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
54 fn into(self) -> MemoryKind<MiriMemoryKind> {
55 MemoryKind::Machine(self)
59 /// Extra per-allocation data
60 #[derive(Debug, Clone)]
61 pub struct AllocExtra {
62 /// Stacked Borrows state is only added if validation is enabled.
63 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
66 /// Extra global memory data
67 #[derive(Clone, Debug)]
68 pub struct MemoryExtra {
69 pub stacked_borrows: stacked_borrows::MemoryExtra,
70 pub intptrcast: intptrcast::MemoryExtra,
72 /// The random number generator used for resolving non-determinism.
73 pub(crate) rng: RefCell<StdRng>,
75 /// Whether to enforce the validity invariant.
76 pub(crate) validate: bool,
80 pub fn new(rng: StdRng, validate: bool) -> Self {
82 stacked_borrows: Default::default(),
83 intptrcast: Default::default(),
84 rng: RefCell::new(rng),
90 /// The machine itself.
91 pub struct Evaluator<'tcx> {
92 /// Environment variables set by `setenv`.
93 /// Miri does not expose env vars from the host to the emulated program.
94 pub(crate) env_vars: EnvVars,
96 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
97 /// These are *pointers* to argc/argv because macOS.
98 /// We also need the full command line as one string because of Windows.
99 pub(crate) argc: Option<Scalar<Tag>>,
100 pub(crate) argv: Option<Scalar<Tag>>,
101 pub(crate) cmd_line: Option<Scalar<Tag>>,
103 /// Last OS error location in memory. It is a 32-bit integer.
104 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
107 pub(crate) tls: TlsData<'tcx>,
109 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
110 /// and random number generation is delegated to the host.
111 pub(crate) communicate: bool,
113 pub(crate) file_handler: FileHandler,
115 /// The temporary used for storing the argument of
116 /// the call to `miri_start_panic` (the panic payload) when unwinding.
117 pub(crate) panic_payload: Option<ImmTy<'tcx, Tag>>
120 impl<'tcx> Evaluator<'tcx> {
121 pub(crate) fn new(communicate: bool) -> Self {
123 // `env_vars` could be initialized properly here if `Memory` were available before
124 // calling this method.
125 env_vars: EnvVars::default(),
130 tls: TlsData::default(),
132 file_handler: Default::default(),
138 /// A rustc InterpCx for Miri.
139 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
141 /// A little trait that's useful to be inherited by extension traits.
142 pub trait MiriEvalContextExt<'mir, 'tcx> {
143 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
144 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
146 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
148 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
152 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
157 /// Machine hook implementations.
158 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
159 type MemoryKinds = MiriMemoryKind;
161 type FrameExtra = FrameData<'tcx>;
162 type MemoryExtra = MemoryExtra;
163 type AllocExtra = AllocExtra;
164 type PointerTag = Tag;
165 type ExtraFnVal = Dlsym;
167 type MemoryMap = MonoHashMap<
170 MemoryKind<MiriMemoryKind>,
171 Allocation<Tag, Self::AllocExtra>,
175 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
177 const CHECK_ALIGN: bool = true;
180 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
181 ecx.memory.extra.validate
186 ecx: &mut InterpCx<'mir, 'tcx, Self>,
187 instance: ty::Instance<'tcx>,
188 args: &[OpTy<'tcx, Tag>],
189 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
190 unwind: Option<mir::BasicBlock>,
191 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
192 ecx.find_fn(instance, args, ret, unwind)
197 ecx: &mut InterpCx<'mir, 'tcx, Self>,
199 args: &[OpTy<'tcx, Tag>],
200 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
201 _unwind: Option<mir::BasicBlock>,
202 ) -> InterpResult<'tcx> {
203 ecx.call_dlsym(fn_val, args, ret)
208 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
210 instance: ty::Instance<'tcx>,
211 args: &[OpTy<'tcx, Tag>],
212 ret: Option<(PlaceTy<'tcx, Tag>, mir::BasicBlock)>,
213 unwind: Option<mir::BasicBlock>,
214 ) -> InterpResult<'tcx> {
215 ecx.call_intrinsic(span, instance, args, ret, unwind)
220 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
222 left: ImmTy<'tcx, Tag>,
223 right: ImmTy<'tcx, Tag>,
224 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
225 ecx.binary_ptr_op(bin_op, left, right)
229 ecx: &mut InterpCx<'mir, 'tcx, Self>,
230 dest: PlaceTy<'tcx, Tag>,
231 ) -> InterpResult<'tcx> {
232 trace!("box_alloc for {:?}", dest.layout.ty);
233 // Call the `exchange_malloc` lang item.
234 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
235 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
236 let malloc_mir = ecx.load_mir(malloc.def, None)?;
237 ecx.push_stack_frame(
242 // Don't do anything when we are done. The `statement()` function will increment
243 // the old stack frame's stmt counter to the next statement, which means that when
244 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
245 StackPopCleanup::None { cleanup: true },
248 let mut args = ecx.frame().body.args_iter();
249 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
251 // First argument: `size`.
252 // (`0` is allowed here -- this is expected to be handled by the lang item).
253 let arg = ecx.local_place(args.next().unwrap())?;
254 let size = layout.size.bytes();
255 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
257 // Second argument: `align`.
258 let arg = ecx.local_place(args.next().unwrap())?;
259 let align = layout.align.abi.bytes();
260 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
262 // No more arguments.
263 args.next().expect_none("`exchange_malloc` lang item has more arguments than expected");
267 fn find_foreign_static(
270 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
271 let attrs = tcx.get_attrs(def_id);
272 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
273 Some(name) => name.as_str(),
274 None => tcx.item_name(def_id).as_str(),
277 let alloc = match &*link_name {
278 "__cxa_thread_atexit_impl" => {
279 // This should be all-zero, pointer-sized.
280 let size = tcx.data_layout.pointer_size;
281 let data = vec![0; size.bytes() as usize];
282 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
284 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
286 Ok(Cow::Owned(alloc))
290 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
291 // We are not interested in detecting loops.
295 fn tag_allocation<'b>(
296 memory_extra: &MemoryExtra,
298 alloc: Cow<'b, Allocation>,
299 kind: Option<MemoryKind<Self::MemoryKinds>>,
301 Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>,
304 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
305 let alloc = alloc.into_owned();
306 let (stacks, base_tag) = if !memory_extra.validate {
307 (None, Tag::Untagged)
309 let (stacks, base_tag) = Stacks::new_allocation(
312 Rc::clone(&memory_extra.stacked_borrows),
315 (Some(stacks), base_tag)
317 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
318 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
320 if !memory_extra.validate {
323 // Only statics may already contain pointers at this point
324 assert_eq!(kind, MiriMemoryKind::Static.into());
325 stacked_borrows.static_base_ptr(alloc)
329 stacked_borrows: stacks,
332 (Cow::Owned(alloc), base_tag)
336 fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
337 if !memory_extra.validate {
349 ecx: &mut InterpCx<'mir, 'tcx, Self>,
350 kind: mir::RetagKind,
351 place: PlaceTy<'tcx, Tag>,
352 ) -> InterpResult<'tcx> {
353 if !Self::enforce_validity(ecx) {
357 ecx.retag(kind, place)
363 ecx: &mut InterpCx<'mir, 'tcx, Self>,
364 ) -> InterpResult<'tcx, FrameData<'tcx>> {
366 call_id: ecx.memory.extra.stacked_borrows.borrow_mut().new_call(),
373 ecx: &mut InterpCx<'mir, 'tcx, Self>,
374 extra: FrameData<'tcx>,
376 ) -> InterpResult<'tcx, StackPopInfo> {
377 ecx.handle_stack_pop(extra, unwinding)
382 memory: &Memory<'mir, 'tcx, Self>,
384 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
385 intptrcast::GlobalState::int_to_ptr(int, memory)
390 memory: &Memory<'mir, 'tcx, Self>,
391 ptr: Pointer<Self::PointerTag>,
392 ) -> InterpResult<'tcx, u64> {
393 intptrcast::GlobalState::ptr_to_int(ptr, memory)
397 impl AllocationExtra<Tag> for AllocExtra {
399 fn memory_read<'tcx>(
400 alloc: &Allocation<Tag, AllocExtra>,
403 ) -> InterpResult<'tcx> {
404 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
405 stacked_borrows.memory_read(ptr, size)
412 fn memory_written<'tcx>(
413 alloc: &mut Allocation<Tag, AllocExtra>,
416 ) -> InterpResult<'tcx> {
417 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
418 stacked_borrows.memory_written(ptr, size)
425 fn memory_deallocated<'tcx>(
426 alloc: &mut Allocation<Tag, AllocExtra>,
429 ) -> InterpResult<'tcx> {
430 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
431 stacked_borrows.memory_deallocated(ptr, size)
438 impl MayLeak for MiriMemoryKind {
440 fn may_leak(self) -> bool {
441 use self::MiriMemoryKind::*;
443 Rust | C | WinHeap => false,
444 Env | Static => true,