4 conservative_impl_trait,
13 extern crate rustc_mir;
14 extern crate rustc_data_structures;
18 extern crate lazy_static;
20 use rustc::ty::{self, TyCtxt};
21 use rustc::ty::layout::{TyLayout, LayoutOf};
22 use rustc::hir::def_id::DefId;
23 use rustc::ty::subst::Substs;
27 use syntax::ast::Mutability;
28 use syntax::codemap::Span;
30 use std::collections::{HashMap, BTreeMap};
32 pub use rustc::mir::interpret::*;
33 pub use rustc_mir::interpret::*;
45 use fn_call::EvalContextExt as MissingFnsEvalContextExt;
46 use operator::EvalContextExt as OperatorEvalContextExt;
47 use intrinsic::EvalContextExt as IntrinsicEvalContextExt;
48 use tls::EvalContextExt as TlsEvalContextExt;
50 use locks::MemoryExt as LockMemoryExt;
51 use validation::EvalContextExt as ValidationEvalContextExt;
52 use range_map::RangeMap;
53 use validation::{ValidationQuery, AbsPlace};
55 pub fn eval_main<'a, 'tcx: 'a>(
56 tcx: TyCtxt<'a, 'tcx, 'tcx>,
58 start_wrapper: Option<DefId>,
59 limits: ResourceLimits,
61 fn run_main<'a, 'tcx: 'a>(
62 ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Evaluator<'tcx>>,
64 start_wrapper: Option<DefId>,
65 ) -> EvalResult<'tcx> {
66 let main_instance = ty::Instance::mono(ecx.tcx, main_id);
67 let main_mir = ecx.load_mir(main_instance.def)?;
68 let mut cleanup_ptr = None; // Pointer to be deallocated when we are done
70 if !main_mir.return_ty().is_nil() || main_mir.arg_count != 0 {
71 return err!(Unimplemented(
72 "miri does not support main functions without `fn()` type signatures"
77 if let Some(start_id) = start_wrapper {
78 let start_instance = ty::Instance::mono(ecx.tcx, start_id);
79 let start_mir = ecx.load_mir(start_instance.def)?;
81 if start_mir.arg_count != 3 {
82 return err!(AbiViolation(format!(
83 "'start' lang item should have three arguments, but has {}",
89 let size = ecx.tcx.data_layout.pointer_size.bytes();
90 let align = ecx.tcx.data_layout.pointer_align.abi();
91 let ret_ptr = ecx.memory_mut().allocate(size, align, Some(MemoryKind::Stack))?;
92 cleanup_ptr = Some(ret_ptr);
94 // Push our stack frame
99 Place::from_ptr(ret_ptr),
100 StackPopCleanup::None,
103 let mut args = ecx.frame().mir.args_iter();
105 // First argument: pointer to main()
106 let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance);
107 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
108 let main_ty = main_instance.ty(ecx.tcx);
109 let main_ptr_ty = ecx.tcx.mk_fn_ptr(main_ty.fn_sig(ecx.tcx));
112 value: Value::ByVal(PrimVal::Ptr(main_ptr)),
118 // Second argument (argc): 1
119 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
120 let ty = ecx.tcx.types.isize;
121 ecx.write_primval(dest, PrimVal::Bytes(1), ty)?;
123 // FIXME: extract main source file path
124 // Third argument (argv): &[b"foo"]
125 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
126 let ty = ecx.tcx.mk_imm_ptr(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8));
127 let foo = ecx.memory.allocate_cached(b"foo\0");
128 let ptr_size = ecx.memory.pointer_size();
129 let foo_ptr = ecx.memory.allocate(ptr_size * 1, ptr_size, None)?;
130 ecx.memory.write_primval(foo_ptr.into(), PrimVal::Ptr(foo.into()), ptr_size, false)?;
131 ecx.memory.mark_static_initalized(foo_ptr.alloc_id, Mutability::Immutable)?;
132 ecx.write_ptr(dest, foo_ptr.into(), ty)?;
134 assert!(args.next().is_none(), "start lang item has more arguments than expected");
136 ecx.push_stack_frame(
141 StackPopCleanup::None,
145 let mut args = ecx.frame().mir.args_iter();
146 assert!(args.next().is_none(), "main function must not have arguments");
150 ecx.run_tls_dtors()?;
151 if let Some(cleanup_ptr) = cleanup_ptr {
152 ecx.memory_mut().deallocate(
161 let mut ecx = EvalContext::new(tcx, ty::ParamEnv::empty(traits::Reveal::All), limits, Default::default(), Default::default(), Substs::empty());
162 match run_main(&mut ecx, main_id, start_wrapper) {
164 let leaks = ecx.memory().leak_report();
166 tcx.sess.err("the evaluated program leaked memory");
176 pub struct Evaluator<'tcx> {
177 /// Environment variables set by `setenv`
178 /// Miri does not expose env vars from the host to the emulated program
179 pub(crate) env_vars: HashMap<Vec<u8>, MemoryPointer>,
181 /// Places that were suspended by the validation subsystem, and will be recovered later
182 pub(crate) suspended: HashMap<DynamicLifetime, Vec<ValidationQuery<'tcx>>>,
185 pub type TlsKey = usize;
187 #[derive(Copy, Clone, Debug)]
188 pub struct TlsEntry<'tcx> {
189 data: Pointer, // Will eventually become a map from thread IDs to `Pointer`s, if we ever support more than one thread.
190 dtor: Option<ty::Instance<'tcx>>,
194 pub struct MemoryData<'tcx> {
195 /// The Key to use for the next thread-local allocation.
196 next_thread_local: TlsKey,
198 /// pthreads-style thread-local storage.
199 thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
201 /// Memory regions that are locked by some function
203 /// Only mutable (static mut, heap, stack) allocations have an entry in this map.
204 /// The entry is created when allocating the memory and deleted after deallocation.
205 locks: HashMap<u64, RangeMap<LockInfo<'tcx>>>,
208 impl<'tcx> Machine<'tcx> for Evaluator<'tcx> {
209 type MemoryData = MemoryData<'tcx>;
210 type MemoryKinds = memory::MemoryKind;
212 /// Returns Ok() when the function was handled, fail otherwise
214 ecx: &mut EvalContext<'a, 'tcx, Self>,
215 instance: ty::Instance<'tcx>,
216 destination: Option<(Place, mir::BasicBlock)>,
217 args: &[ValTy<'tcx>],
219 sig: ty::FnSig<'tcx>,
220 ) -> EvalResult<'tcx, bool> {
221 ecx.eval_fn_call(instance, destination, args, span, sig)
224 fn call_intrinsic<'a>(
225 ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
226 instance: ty::Instance<'tcx>,
227 args: &[ValTy<'tcx>],
229 dest_layout: TyLayout<'tcx>,
230 target: mir::BasicBlock,
231 ) -> EvalResult<'tcx> {
232 ecx.call_intrinsic(instance, args, dest, dest_layout, target)
236 ecx: &rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
239 left_ty: ty::Ty<'tcx>,
241 right_ty: ty::Ty<'tcx>,
242 ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
243 ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
246 fn mark_static_initialized(m: memory::MemoryKind) -> EvalResult<'tcx> {
247 use memory::MemoryKind::*;
249 // FIXME: This could be allowed, but not for env vars set during miri execution
250 Env => err!(Unimplemented("statics can't refer to env vars".to_owned())),
256 ecx: &mut EvalContext<'a, 'tcx, Self>,
259 ) -> EvalResult<'tcx> {
260 let layout = ecx.layout_of(ty)?;
262 // Call the `exchange_malloc` lang item
263 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
264 let malloc = ty::Instance::mono(ecx.tcx, malloc);
265 let malloc_mir = ecx.load_mir(malloc.def)?;
266 ecx.push_stack_frame(
271 // Don't do anything when we are done. The statement() function will increment
272 // the old stack frame's stmt counter to the next statement, which means that when
273 // exchange_malloc returns, we go on evaluating exactly where we want to be.
274 StackPopCleanup::None,
277 let mut args = ecx.frame().mir.args_iter();
278 let usize = ecx.tcx.types.usize;
280 // First argument: size
281 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
284 value: Value::ByVal(PrimVal::Bytes(layout.size.bytes().into())),
290 // Second argument: align
291 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
294 value: Value::ByVal(PrimVal::Bytes(layout.align.abi().into())),
301 assert!(args.next().is_none(), "exchange_malloc lang item has more arguments than expected");
305 fn global_item_with_linkage<'a>(
306 ecx: &mut EvalContext<'a, 'tcx, Self>,
307 instance: ty::Instance<'tcx>,
308 mutability: Mutability,
309 ) -> EvalResult<'tcx> {
310 // FIXME: check that it's `#[linkage = "extern_weak"]`
311 trace!("Initializing an extern global with NULL");
312 let ptr_size = ecx.memory.pointer_size();
313 let ptr = ecx.memory.allocate(
318 ecx.memory.write_ptr_sized_unsigned(ptr, PrimVal::Bytes(0))?;
319 ecx.memory.mark_static_initalized(ptr.alloc_id, mutability)?;
320 ecx.tcx.interpret_interner.borrow_mut().cache(
334 mem: &Memory<'a, 'tcx, Self>,
338 ) -> EvalResult<'tcx> {
339 mem.check_locks(ptr, size, access)
343 mem: &mut Memory<'a, 'tcx, Self>,
346 mem.data.locks.insert(id, RangeMap::new());
350 mem: &mut Memory<'a, 'tcx, Self>,
353 ) -> EvalResult<'tcx> {
356 .expect("allocation has no corresponding locks")
364 EvalErrorKind::DeallocatedLockedMemory {
367 alloc_id: AllocId(0),
376 ecx: &mut EvalContext<'a, 'tcx, Self>,
377 reg: Option<::rustc::middle::region::Scope>,
378 ) -> EvalResult<'tcx> {
382 fn validation_op<'a>(
383 ecx: &mut EvalContext<'a, 'tcx, Self>,
384 op: ::rustc::mir::ValidationOp,
385 operand: &::rustc::mir::ValidationOperand<'tcx, ::rustc::mir::Place<'tcx>>,
386 ) -> EvalResult<'tcx> {
387 ecx.validation_op(op, operand)