9 extern crate log_settings;
12 extern crate rustc_const_math;
13 extern crate rustc_data_structures;
16 use rustc::ty::{self, TyCtxt};
17 use rustc::hir::def_id::DefId;
20 use syntax::codemap::Span;
22 use std::collections::{
27 extern crate rustc_miri;
28 pub use rustc_miri::interpret::*;
33 use fn_call::EvalContextExt as MissingFnsEvalContextExt;
34 use operator::EvalContextExt as OperatorEvalContextExt;
36 pub fn eval_main<'a, 'tcx: 'a>(
37 tcx: TyCtxt<'a, 'tcx, 'tcx>,
39 start_wrapper: Option<DefId>,
40 limits: ResourceLimits,
42 fn run_main<'a, 'tcx: 'a>(
43 ecx: &mut rustc_miri::interpret::EvalContext<'a, 'tcx, Evaluator>,
45 start_wrapper: Option<DefId>,
46 ) -> EvalResult<'tcx> {
47 let main_instance = ty::Instance::mono(ecx.tcx, main_id);
48 let main_mir = ecx.load_mir(main_instance.def)?;
49 let mut cleanup_ptr = None; // Pointer to be deallocated when we are done
51 if !main_mir.return_ty.is_nil() || main_mir.arg_count != 0 {
52 return Err(EvalError::Unimplemented("miri does not support main functions without `fn()` type signatures".to_owned()));
55 if let Some(start_id) = start_wrapper {
56 let start_instance = ty::Instance::mono(ecx.tcx, start_id);
57 let start_mir = ecx.load_mir(start_instance.def)?;
59 if start_mir.arg_count != 3 {
60 return Err(EvalError::AbiViolation(format!("'start' lang item should have three arguments, but has {}", start_mir.arg_count)));
64 let size = ecx.tcx.data_layout.pointer_size.bytes();
65 let align = ecx.tcx.data_layout.pointer_align.abi();
66 let ret_ptr = ecx.memory_mut().allocate(size, align, Kind::Stack)?;
67 cleanup_ptr = Some(ret_ptr);
69 // Push our stack frame
74 Lvalue::from_ptr(ret_ptr),
75 StackPopCleanup::None,
78 let mut args = ecx.frame().mir.args_iter();
80 // First argument: pointer to main()
81 let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance);
82 let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
83 let main_ty = main_instance.def.def_ty(ecx.tcx);
84 let main_ptr_ty = ecx.tcx.mk_fn_ptr(main_ty.fn_sig(ecx.tcx));
85 ecx.write_value(Value::ByVal(PrimVal::Ptr(main_ptr)), dest, main_ptr_ty)?;
87 // Second argument (argc): 0
88 let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
89 let ty = ecx.tcx.types.isize;
90 ecx.write_null(dest, ty)?;
92 // Third argument (argv): 0
93 let dest = ecx.eval_lvalue(&mir::Lvalue::Local(args.next().unwrap()))?;
94 let ty = ecx.tcx.mk_imm_ptr(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8));
95 ecx.write_null(dest, ty)?;
102 StackPopCleanup::None,
108 if let Some(cleanup_ptr) = cleanup_ptr {
109 ecx.memory_mut().deallocate(cleanup_ptr, None, Kind::Stack)?;
114 let mut ecx = EvalContext::new(tcx, limits, Default::default(), Default::default());
115 match run_main(&mut ecx, main_id, start_wrapper) {
117 let leaks = ecx.memory().leak_report();
119 tcx.sess.err("the evaluated program leaked memory");
130 struct EvaluatorData {
131 /// Environment variables set by `setenv`
132 /// Miri does not expose env vars from the host to the emulated program
133 pub(crate) env_vars: HashMap<Vec<u8>, MemoryPointer>,
136 pub type TlsKey = usize;
138 #[derive(Copy, Clone, Debug)]
139 pub struct TlsEntry<'tcx> {
140 data: Pointer, // Will eventually become a map from thread IDs to `Pointer`s, if we ever support more than one thread.
141 dtor: Option<ty::Instance<'tcx>>,
145 struct MemoryData<'tcx> {
146 /// The Key to use for the next thread-local allocation.
147 next_thread_local: TlsKey,
149 /// pthreads-style thread-local storage.
150 thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
153 trait EvalContextExt<'tcx> {
154 fn finish(&mut self) -> EvalResult<'tcx>;
157 impl<'a, 'tcx> EvalContextExt<'tcx> for EvalContext<'a, 'tcx, Evaluator> {
158 fn finish(&mut self) -> EvalResult<'tcx> {
159 let mut dtor = self.memory.fetch_tls_dtor(None)?;
160 // FIXME: replace loop by some structure that works with stepping
161 while let Some((instance, ptr, key)) = dtor {
162 trace!("Running TLS dtor {:?} on {:?}", instance, ptr);
163 // TODO: Potentially, this has to support all the other possible instances? See eval_fn_call in terminator/mod.rs
164 let mir = self.load_mir(instance.def)?;
165 self.push_stack_frame(
170 StackPopCleanup::None,
172 let arg_local = self.frame().mir.args_iter().next().ok_or(EvalError::AbiViolation("TLS dtor does not take enough arguments.".to_owned()))?;
173 let dest = self.eval_lvalue(&mir::Lvalue::Local(arg_local))?;
174 let ty = self.tcx.mk_mut_ptr(self.tcx.types.u8);
175 self.write_ptr(dest, ptr, ty)?;
177 // step until out of stackframes
178 while self.step()? {}
180 dtor = match self.memory.fetch_tls_dtor(Some(key))? {
181 dtor @ Some(_) => dtor,
182 None => self.memory.fetch_tls_dtor(None)?,
189 trait MemoryExt<'tcx> {
190 fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>) -> TlsKey;
191 fn delete_tls_key(&mut self, key: TlsKey) -> EvalResult<'tcx>;
192 fn load_tls(&mut self, key: TlsKey) -> EvalResult<'tcx, Pointer>;
193 fn store_tls(&mut self, key: TlsKey, new_data: Pointer) -> EvalResult<'tcx>;
194 fn fetch_tls_dtor(&mut self, key: Option<TlsKey>) -> EvalResult<'tcx, Option<(ty::Instance<'tcx>, Pointer, TlsKey)>>;
197 impl<'a, 'tcx: 'a> MemoryExt<'tcx> for Memory<'a, 'tcx, Evaluator> {
198 fn create_tls_key(&mut self, dtor: Option<ty::Instance<'tcx>>) -> TlsKey {
199 let new_key = self.data.next_thread_local;
200 self.data.next_thread_local += 1;
201 self.data.thread_local.insert(new_key, TlsEntry { data: Pointer::null(), dtor });
202 trace!("New TLS key allocated: {} with dtor {:?}", new_key, dtor);
206 fn delete_tls_key(&mut self, key: TlsKey) -> EvalResult<'tcx> {
207 return match self.data.thread_local.remove(&key) {
209 trace!("TLS key {} removed", key);
212 None => Err(EvalError::TlsOutOfBounds)
216 fn load_tls(&mut self, key: TlsKey) -> EvalResult<'tcx, Pointer> {
217 return match self.data.thread_local.get(&key) {
218 Some(&TlsEntry { data, .. }) => {
219 trace!("TLS key {} loaded: {:?}", key, data);
222 None => Err(EvalError::TlsOutOfBounds)
226 fn store_tls(&mut self, key: TlsKey, new_data: Pointer) -> EvalResult<'tcx> {
227 return match self.data.thread_local.get_mut(&key) {
228 Some(&mut TlsEntry { ref mut data, .. }) => {
229 trace!("TLS key {} stored: {:?}", key, new_data);
233 None => Err(EvalError::TlsOutOfBounds)
237 /// Returns a dtor, its argument and its index, if one is supposed to run
239 /// An optional destructor function may be associated with each key value.
240 /// At thread exit, if a key value has a non-NULL destructor pointer,
241 /// and the thread has a non-NULL value associated with that key,
242 /// the value of the key is set to NULL, and then the function pointed
243 /// to is called with the previously associated value as its sole argument.
244 /// The order of destructor calls is unspecified if more than one destructor
245 /// exists for a thread when it exits.
247 /// If, after all the destructors have been called for all non-NULL values
248 /// with associated destructors, there are still some non-NULL values with
249 /// associated destructors, then the process is repeated.
250 /// If, after at least {PTHREAD_DESTRUCTOR_ITERATIONS} iterations of destructor
251 /// calls for outstanding non-NULL values, there are still some non-NULL values
252 /// with associated destructors, implementations may stop calling destructors,
253 /// or they may continue calling destructors until no non-NULL values with
254 /// associated destructors exist, even though this might result in an infinite loop.
255 fn fetch_tls_dtor(&mut self, key: Option<TlsKey>) -> EvalResult<'tcx, Option<(ty::Instance<'tcx>, Pointer, TlsKey)>> {
256 use std::collections::Bound::*;
257 let start = match key {
258 Some(key) => Excluded(key),
261 for (&key, &mut TlsEntry { ref mut data, dtor }) in self.data.thread_local.range_mut((start, Unbounded)) {
262 if !data.is_null()? {
263 if let Some(dtor) = dtor {
264 let ret = Some((dtor, *data, key));
265 *data = Pointer::null();
274 impl<'tcx> Machine<'tcx> for Evaluator {
275 type Data = EvaluatorData;
276 type MemoryData = MemoryData<'tcx>;
278 /// Returns Ok() when the function was handled, fail otherwise
280 ecx: &mut EvalContext<'a, 'tcx, Self>,
281 instance: ty::Instance<'tcx>,
282 destination: Option<(Lvalue<'tcx>, mir::BasicBlock)>,
283 arg_operands: &[mir::Operand<'tcx>],
285 sig: ty::FnSig<'tcx>,
286 ) -> EvalResult<'tcx, bool> {
287 ecx.eval_fn_call(instance, destination, arg_operands, span, sig)
291 ecx: &rustc_miri::interpret::EvalContext<'a, 'tcx, Self>,
294 left_ty: ty::Ty<'tcx>,
296 right_ty: ty::Ty<'tcx>,
297 ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
298 ecx.ptr_op(bin_op, left, left_ty, right, right_ty)