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,
28 /// If this is Some(), then this is a special 'catch unwind'
29 /// frame. When this frame is popped during unwinding a panic,
30 /// we stop unwinding, and use the `CatchUnwindData` to
31 /// store the panic payload and continue execution in the parent frame.
32 pub catch_panic: Option<CatchUnwindData<'tcx>>,
36 /// Extra memory kinds
37 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
38 pub enum MiriMemoryKind {
39 /// `__rust_alloc` memory.
43 /// Windows `HeapAlloc` memory.
45 /// Part of env var emulation.
51 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
53 fn into(self) -> MemoryKind<MiriMemoryKind> {
54 MemoryKind::Machine(self)
58 /// Extra per-allocation data
59 #[derive(Debug, Clone)]
60 pub struct AllocExtra {
61 /// Stacked Borrows state is only added if validation is enabled.
62 pub stacked_borrows: Option<stacked_borrows::AllocExtra>,
65 /// Extra global memory data
66 #[derive(Clone, Debug)]
67 pub struct MemoryExtra {
68 pub stacked_borrows: stacked_borrows::MemoryExtra,
69 pub intptrcast: intptrcast::MemoryExtra,
71 /// The random number generator used for resolving non-determinism.
72 pub(crate) rng: RefCell<StdRng>,
74 /// Whether to enforce the validity invariant.
75 pub(crate) validate: bool,
79 pub fn new(rng: StdRng, validate: bool) -> Self {
81 stacked_borrows: Default::default(),
82 intptrcast: Default::default(),
83 rng: RefCell::new(rng),
89 /// The machine itself.
90 pub struct Evaluator<'tcx> {
91 /// Environment variables set by `setenv`.
92 /// Miri does not expose env vars from the host to the emulated program.
93 pub(crate) env_vars: EnvVars,
95 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
96 /// These are *pointers* to argc/argv because macOS.
97 /// We also need the full command line as one string because of Windows.
98 pub(crate) argc: Option<Scalar<Tag>>,
99 pub(crate) argv: Option<Scalar<Tag>>,
100 pub(crate) cmd_line: Option<Scalar<Tag>>,
102 /// Last OS error location in memory. It is a 32-bit integer.
103 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
106 pub(crate) tls: TlsData<'tcx>,
108 /// If enabled, the `env_vars` field is populated with the host env vars during initialization
109 /// and random number generation is delegated to the host.
110 pub(crate) communicate: bool,
112 pub(crate) file_handler: FileHandler,
114 /// The temporary used for storing the argument of
115 /// the call to `miri_start_panic` (the panic payload) when unwinding.
116 pub(crate) panic_payload: Option<ImmTy<'tcx, Tag>>
119 impl<'tcx> Evaluator<'tcx> {
120 pub(crate) fn new(communicate: bool) -> Self {
122 // `env_vars` could be initialized properly here if `Memory` were available before
123 // calling this method.
124 env_vars: EnvVars::default(),
129 tls: TlsData::default(),
131 file_handler: Default::default(),
137 /// A rustc InterpCx for Miri.
138 pub type MiriEvalContext<'mir, 'tcx> = InterpCx<'mir, 'tcx, Evaluator<'tcx>>;
140 /// A little trait that's useful to be inherited by extension traits.
141 pub trait MiriEvalContextExt<'mir, 'tcx> {
142 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
143 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
145 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
147 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
151 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
156 /// Machine hook implementations.
157 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
158 type MemoryKinds = MiriMemoryKind;
160 type FrameExtra = FrameData<'tcx>;
161 type MemoryExtra = MemoryExtra;
162 type AllocExtra = AllocExtra;
163 type PointerTag = Tag;
164 type ExtraFnVal = Dlsym;
166 type MemoryMap = MonoHashMap<
169 MemoryKind<MiriMemoryKind>,
170 Allocation<Tag, Self::AllocExtra>,
174 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
176 const CHECK_ALIGN: bool = true;
179 fn enforce_validity(ecx: &InterpCx<'mir, 'tcx, Self>) -> bool {
180 ecx.memory.extra.validate
185 ecx: &mut InterpCx<'mir, 'tcx, Self>,
186 instance: ty::Instance<'tcx>,
187 args: &[OpTy<'tcx, Tag>],
188 dest: Option<PlaceTy<'tcx, Tag>>,
189 ret: Option<mir::BasicBlock>,
190 unwind: Option<mir::BasicBlock>,
191 ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
192 ecx.find_fn(instance, args, dest, ret, unwind)
197 ecx: &mut InterpCx<'mir, 'tcx, Self>,
199 args: &[OpTy<'tcx, Tag>],
200 dest: Option<PlaceTy<'tcx, Tag>>,
201 ret: Option<mir::BasicBlock>,
202 ) -> InterpResult<'tcx> {
203 ecx.call_dlsym(fn_val, args, dest, ret)
208 ecx: &mut rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
210 instance: ty::Instance<'tcx>,
211 args: &[OpTy<'tcx, Tag>],
212 dest: Option<PlaceTy<'tcx, Tag>>,
213 ret: Option<mir::BasicBlock>,
214 unwind: Option<mir::BasicBlock>,
215 ) -> InterpResult<'tcx> {
216 ecx.call_intrinsic(span, instance, args, dest, ret, unwind)
221 ecx: &rustc_mir::interpret::InterpCx<'mir, 'tcx, Self>,
223 left: ImmTy<'tcx, Tag>,
224 right: ImmTy<'tcx, Tag>,
225 ) -> InterpResult<'tcx, (Scalar<Tag>, bool, Ty<'tcx>)> {
226 ecx.binary_ptr_op(bin_op, left, right)
230 ecx: &mut InterpCx<'mir, 'tcx, Self>,
231 dest: PlaceTy<'tcx, Tag>,
232 ) -> InterpResult<'tcx> {
233 trace!("box_alloc for {:?}", dest.layout.ty);
234 // Call the `exchange_malloc` lang item.
235 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
236 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
237 let malloc_mir = ecx.load_mir(malloc.def, None)?;
238 ecx.push_stack_frame(
243 // Don't do anything when we are done. The `statement()` function will increment
244 // the old stack frame's stmt counter to the next statement, which means that when
245 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
246 StackPopCleanup::None { cleanup: true },
249 let mut args = ecx.frame().body.args_iter();
250 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
252 // First argument: `size`.
253 // (`0` is allowed here -- this is expected to be handled by the lang item).
254 let arg = ecx.local_place(args.next().unwrap())?;
255 let size = layout.size.bytes();
256 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
258 // Second argument: `align`.
259 let arg = ecx.local_place(args.next().unwrap())?;
260 let align = layout.align.abi.bytes();
261 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
263 // No more arguments.
264 args.next().expect_none("`exchange_malloc` lang item has more arguments than expected");
268 fn find_foreign_static(
271 ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
272 let attrs = tcx.get_attrs(def_id);
273 let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
274 Some(name) => name.as_str(),
275 None => tcx.item_name(def_id).as_str(),
278 let alloc = match &*link_name {
279 "__cxa_thread_atexit_impl" => {
280 // This should be all-zero, pointer-sized.
281 let size = tcx.data_layout.pointer_size;
282 let data = vec![0; size.bytes() as usize];
283 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
285 _ => throw_unsup_format!("can't access foreign static: {}", link_name),
287 Ok(Cow::Owned(alloc))
291 fn before_terminator(_ecx: &mut InterpCx<'mir, 'tcx, Self>) -> InterpResult<'tcx> {
292 // We are not interested in detecting loops.
296 fn tag_allocation<'b>(
297 memory_extra: &MemoryExtra,
299 alloc: Cow<'b, Allocation>,
300 kind: Option<MemoryKind<Self::MemoryKinds>>,
302 Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>,
305 let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
306 let alloc = alloc.into_owned();
307 let (stacks, base_tag) = if !memory_extra.validate {
308 (None, Tag::Untagged)
310 let (stacks, base_tag) = Stacks::new_allocation(
313 Rc::clone(&memory_extra.stacked_borrows),
316 (Some(stacks), base_tag)
318 let mut stacked_borrows = memory_extra.stacked_borrows.borrow_mut();
319 let alloc: Allocation<Tag, Self::AllocExtra> = alloc.with_tags_and_extra(
321 if !memory_extra.validate {
324 // Only statics may already contain pointers at this point
325 assert_eq!(kind, MiriMemoryKind::Static.into());
326 stacked_borrows.static_base_ptr(alloc)
330 stacked_borrows: stacks,
333 (Cow::Owned(alloc), base_tag)
337 fn tag_static_base_pointer(memory_extra: &MemoryExtra, id: AllocId) -> Self::PointerTag {
338 if !memory_extra.validate {
350 ecx: &mut InterpCx<'mir, 'tcx, Self>,
351 kind: mir::RetagKind,
352 place: PlaceTy<'tcx, Tag>,
353 ) -> InterpResult<'tcx> {
354 if !Self::enforce_validity(ecx) {
358 ecx.retag(kind, place)
364 ecx: &mut InterpCx<'mir, 'tcx, Self>,
365 ) -> InterpResult<'tcx, FrameData<'tcx>> {
367 call_id: ecx.memory.extra.stacked_borrows.borrow_mut().new_call(),
374 ecx: &mut InterpCx<'mir, 'tcx, Self>,
375 extra: FrameData<'tcx>,
377 ) -> InterpResult<'tcx, StackPopInfo> {
378 ecx.handle_stack_pop(extra, unwinding)
383 memory: &Memory<'mir, 'tcx, Self>,
385 ) -> InterpResult<'tcx, Pointer<Self::PointerTag>> {
386 intptrcast::GlobalState::int_to_ptr(int, memory)
391 memory: &Memory<'mir, 'tcx, Self>,
392 ptr: Pointer<Self::PointerTag>,
393 ) -> InterpResult<'tcx, u64> {
394 intptrcast::GlobalState::ptr_to_int(ptr, memory)
398 impl AllocationExtra<Tag> for AllocExtra {
400 fn memory_read<'tcx>(
401 alloc: &Allocation<Tag, AllocExtra>,
404 ) -> InterpResult<'tcx> {
405 if let Some(ref stacked_borrows) = alloc.extra.stacked_borrows {
406 stacked_borrows.memory_read(ptr, size)
413 fn memory_written<'tcx>(
414 alloc: &mut Allocation<Tag, AllocExtra>,
417 ) -> InterpResult<'tcx> {
418 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
419 stacked_borrows.memory_written(ptr, size)
426 fn memory_deallocated<'tcx>(
427 alloc: &mut Allocation<Tag, AllocExtra>,
430 ) -> InterpResult<'tcx> {
431 if let Some(ref mut stacked_borrows) = alloc.extra.stacked_borrows {
432 stacked_borrows.memory_deallocated(ptr, size)
439 impl MayLeak for MiriMemoryKind {
441 fn may_leak(self) -> bool {
442 use self::MiriMemoryKind::*;
444 Rust | C | WinHeap => false,
445 Env | Static => true,