4 conservative_impl_trait,
15 extern crate rustc_mir;
16 extern crate rustc_data_structures;
20 extern crate lazy_static;
22 use rustc::ty::{self, TyCtxt};
23 use rustc::ty::layout::{TyLayout, LayoutOf};
24 use rustc::hir::def_id::DefId;
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>,
60 fn run_main<'a, 'mir: 'a, 'tcx: 'mir>(
61 ecx: &mut rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Evaluator<'tcx>>,
63 start_wrapper: Option<DefId>,
64 ) -> EvalResult<'tcx> {
65 let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
66 let main_mir = ecx.load_mir(main_instance.def)?;
67 let mut cleanup_ptr = None; // Pointer to be deallocated when we are done
69 if !main_mir.return_ty().is_nil() || main_mir.arg_count != 0 {
70 return err!(Unimplemented(
71 "miri does not support main functions without `fn()` type signatures"
76 if let Some(start_id) = start_wrapper {
77 let main_ret_ty = ecx.tcx.fn_sig(main_id).output();
78 let main_ret_ty = main_ret_ty.no_late_bound_regions().unwrap();
79 let start_instance = ty::Instance::resolve(
81 ty::ParamEnv::reveal_all(),
84 ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))).unwrap();
85 let start_mir = ecx.load_mir(start_instance.def)?;
87 if start_mir.arg_count != 3 {
88 return err!(AbiViolation(format!(
89 "'start' lang item should have three arguments, but has {}",
95 let size = ecx.tcx.data_layout.pointer_size.bytes();
96 let align = ecx.tcx.data_layout.pointer_align;
97 let ret_ptr = ecx.memory_mut().allocate(size, align, Some(MemoryKind::Stack))?;
98 cleanup_ptr = Some(ret_ptr);
100 // Push our stack frame
101 ecx.push_stack_frame(
105 Place::from_ptr(ret_ptr, align),
106 StackPopCleanup::None,
109 let mut args = ecx.frame().mir.args_iter();
111 // First argument: pointer to main()
112 let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance);
113 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
114 let main_ty = main_instance.ty(ecx.tcx.tcx);
115 let main_ptr_ty = ecx.tcx.mk_fn_ptr(main_ty.fn_sig(ecx.tcx.tcx));
118 value: Value::ByVal(PrimVal::Ptr(main_ptr)),
124 // Second argument (argc): 1
125 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
126 let ty = ecx.tcx.types.isize;
127 ecx.write_primval(dest, PrimVal::Bytes(1), ty)?;
129 // FIXME: extract main source file path
130 // Third argument (argv): &[b"foo"]
131 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
132 let ty = ecx.tcx.mk_imm_ptr(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8));
133 let foo = ecx.memory.allocate_cached(b"foo\0");
134 let ptr_size = ecx.memory.pointer_size();
135 let ptr_align = ecx.tcx.data_layout.pointer_align;
136 let foo_ptr = ecx.memory.allocate(ptr_size, ptr_align, None)?;
137 ecx.memory.write_primval(foo_ptr, ptr_align, PrimVal::Ptr(foo.into()), ptr_size, false)?;
138 ecx.memory.mark_static_initialized(foo_ptr.alloc_id, Mutability::Immutable)?;
139 ecx.write_ptr(dest, foo_ptr.into(), ty)?;
141 assert!(args.next().is_none(), "start lang item has more arguments than expected");
143 ecx.push_stack_frame(
148 StackPopCleanup::None,
152 let mut args = ecx.frame().mir.args_iter();
153 assert!(args.next().is_none(), "main function must not have arguments");
157 ecx.run_tls_dtors()?;
158 if let Some(cleanup_ptr) = cleanup_ptr {
159 ecx.memory_mut().deallocate(
168 let mut ecx = EvalContext::new(tcx.at(syntax::codemap::DUMMY_SP), ty::ParamEnv::reveal_all(), Default::default(), Default::default());
169 match run_main(&mut ecx, main_id, start_wrapper) {
171 let leaks = ecx.memory().leak_report();
173 tcx.sess.err("the evaluated program leaked memory");
177 ecx.report(&mut e, true, None);
183 pub struct Evaluator<'tcx> {
184 /// Environment variables set by `setenv`
185 /// Miri does not expose env vars from the host to the emulated program
186 pub(crate) env_vars: HashMap<Vec<u8>, MemoryPointer>,
188 /// Places that were suspended by the validation subsystem, and will be recovered later
189 pub(crate) suspended: HashMap<DynamicLifetime, Vec<ValidationQuery<'tcx>>>,
192 pub type TlsKey = usize;
194 #[derive(Copy, Clone, Debug)]
195 pub struct TlsEntry<'tcx> {
196 data: Pointer, // Will eventually become a map from thread IDs to `Pointer`s, if we ever support more than one thread.
197 dtor: Option<ty::Instance<'tcx>>,
201 pub struct MemoryData<'tcx> {
202 /// The Key to use for the next thread-local allocation.
203 next_thread_local: TlsKey,
205 /// pthreads-style thread-local storage.
206 thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
208 /// Memory regions that are locked by some function
210 /// Only mutable (static mut, heap, stack) allocations have an entry in this map.
211 /// The entry is created when allocating the memory and deleted after deallocation.
212 locks: HashMap<AllocId, RangeMap<LockInfo<'tcx>>>,
214 mut_statics: HashMap<GlobalId<'tcx>, AllocId>,
217 impl<'mir, 'tcx: 'mir> Machine<'mir, 'tcx> for Evaluator<'tcx> {
218 type MemoryData = MemoryData<'tcx>;
219 type MemoryKinds = memory::MemoryKind;
221 /// Returns Ok() when the function was handled, fail otherwise
223 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
224 instance: ty::Instance<'tcx>,
225 destination: Option<(Place, mir::BasicBlock)>,
226 args: &[ValTy<'tcx>],
228 sig: ty::FnSig<'tcx>,
229 ) -> EvalResult<'tcx, bool> {
230 ecx.eval_fn_call(instance, destination, args, span, sig)
233 fn call_intrinsic<'a>(
234 ecx: &mut rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Self>,
235 instance: ty::Instance<'tcx>,
236 args: &[ValTy<'tcx>],
238 dest_layout: TyLayout<'tcx>,
239 target: mir::BasicBlock,
240 ) -> EvalResult<'tcx> {
241 ecx.call_intrinsic(instance, args, dest, dest_layout, target)
245 ecx: &rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Self>,
248 left_ty: ty::Ty<'tcx>,
250 right_ty: ty::Ty<'tcx>,
251 ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
252 ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
255 fn mark_static_initialized<'a>(
256 _mem: &mut Memory<'a, 'mir, 'tcx, Self>,
258 _mutability: Mutability,
259 ) -> EvalResult<'tcx, bool> {
260 /*use memory::MemoryKind::*;
262 // FIXME: This could be allowed, but not for env vars set during miri execution
263 Env => err!(Unimplemented("statics can't refer to env vars".to_owned())),
264 _ => Ok(false), // TODO: What does the bool mean?
270 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
272 ) -> EvalResult<'tcx, AllocId> {
273 if let Some(alloc_id) = ecx.memory.data.get(&cid) {
276 let mir = ecx.load_mir(cid.instance.def)?;
277 let layout = ecx.layout_of(mir.return_ty().subst(tcx, cid.instance.substs))?;
278 let to_ptr = ecx.memory.allocate(
283 ecx.const_eval(cid)?;
287 .get_cached(cid.instance.def_id())
288 .expect("uncached static");
289 ecx.memory.copy(ptr, layout.align, to_ptr.into(), layout.align, layout.size.bytes(), true)?;
290 ecx.memory.mark_static_initialized(to_ptr.alloc_id, ::syntax::ast::Mutability::Mutable)?;
291 assert!(ecx.memory.data.insert(cid, to_ptr.alloc_id).is_none());
296 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
299 ) -> EvalResult<'tcx> {
300 let layout = ecx.layout_of(ty)?;
302 // Call the `exchange_malloc` lang item
303 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
304 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
305 let malloc_mir = ecx.load_mir(malloc.def)?;
306 ecx.push_stack_frame(
311 // Don't do anything when we are done. The statement() function will increment
312 // the old stack frame's stmt counter to the next statement, which means that when
313 // exchange_malloc returns, we go on evaluating exactly where we want to be.
314 StackPopCleanup::None,
317 let mut args = ecx.frame().mir.args_iter();
318 let usize = ecx.tcx.types.usize;
320 // First argument: size
321 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
324 value: Value::ByVal(PrimVal::Bytes(layout.size.bytes().into())),
330 // Second argument: align
331 let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
334 value: Value::ByVal(PrimVal::Bytes(layout.align.abi().into())),
341 assert!(args.next().is_none(), "exchange_malloc lang item has more arguments than expected");
345 fn global_item_with_linkage<'a>(
346 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
347 instance: ty::Instance<'tcx>,
348 mutability: Mutability,
349 ) -> EvalResult<'tcx> {
350 // FIXME: check that it's `#[linkage = "extern_weak"]`
351 trace!("Initializing an extern global with NULL");
352 let ptr_size = ecx.memory.pointer_size();
353 let ptr_align = ecx.tcx.data_layout.pointer_align;
354 let ptr = ecx.memory.allocate(
359 ecx.memory.write_ptr_sized_unsigned(ptr, ptr_align, PrimVal::Bytes(0))?;
360 ecx.memory.mark_static_initialized(ptr.alloc_id, mutability)?;
361 ecx.tcx.interpret_interner.cache(
369 mem: &Memory<'a, 'mir, 'tcx, Self>,
373 ) -> EvalResult<'tcx> {
374 mem.check_locks(ptr, size, access)
378 mem: &mut Memory<'a, 'mir, 'tcx, Self>,
381 mem.data.locks.insert(id, RangeMap::new());
385 mem: &mut Memory<'a, 'mir, 'tcx, Self>,
388 ) -> EvalResult<'tcx> {
391 .expect("allocation has no corresponding locks")
399 EvalErrorKind::DeallocatedLockedMemory {
402 alloc_id: AllocId(0),
411 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
412 reg: Option<::rustc::middle::region::Scope>,
413 ) -> EvalResult<'tcx> {
417 fn validation_op<'a>(
418 ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
419 op: ::rustc::mir::ValidationOp,
420 operand: &::rustc::mir::ValidationOperand<'tcx, ::rustc::mir::Place<'tcx>>,
421 ) -> EvalResult<'tcx> {
422 ecx.validation_op(op, operand)