]> git.lizzy.rs Git - rust.git/blob - miri/lib.rs
bd17ab6f2cbf98c912616df0b9265c6536f00c42
[rust.git] / miri / lib.rs
1 #![feature(
2     i128_type,
3     rustc_private,
4 )]
5
6 // From rustc.
7 #[macro_use]
8 extern crate log;
9 extern crate log_settings;
10 #[macro_use]
11 extern crate rustc;
12 extern crate rustc_const_math;
13 extern crate rustc_data_structures;
14 extern crate syntax;
15
16 use rustc::ty::{self, TyCtxt};
17 use rustc::hir::def_id::DefId;
18 use rustc::mir;
19
20 use syntax::codemap::Span;
21
22 use std::collections::{
23     HashMap,
24     BTreeMap,
25 };
26
27 extern crate rustc_miri;
28 pub use rustc_miri::interpret::*;
29
30 mod fn_call;
31 mod operator;
32
33 use fn_call::EvalContextExt as MissingFnsEvalContextExt;
34 use operator::EvalContextExt as OperatorEvalContextExt;
35
36 pub fn eval_main<'a, 'tcx: 'a>(
37     tcx: TyCtxt<'a, 'tcx, 'tcx>,
38     main_id: DefId,
39     start_wrapper: Option<DefId>,
40     limits: ResourceLimits,
41 ) {
42     fn run_main<'a, 'tcx: 'a>(
43         ecx: &mut rustc_miri::interpret::EvalContext<'a, 'tcx, Evaluator>,
44         main_id: DefId,
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
50
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()));
53         }
54
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)?;
58
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)));
61             }
62
63             // Return value
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);
68
69             // Push our stack frame
70             ecx.push_stack_frame(
71                 start_instance,
72                 start_mir.span,
73                 start_mir,
74                 Lvalue::from_ptr(ret_ptr),
75                 StackPopCleanup::None,
76             )?;
77
78             let mut args = ecx.frame().mir.args_iter();
79
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)?;
86
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)?;
91
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)?;
96         } else {
97             ecx.push_stack_frame(
98                 main_instance,
99                 main_mir.span,
100                 main_mir,
101                 Lvalue::undef(),
102                 StackPopCleanup::None,
103             )?;
104         }
105
106         while ecx.step()? {}
107         ecx.finish()?;
108         if let Some(cleanup_ptr) = cleanup_ptr {
109             ecx.memory_mut().deallocate(cleanup_ptr, None, Kind::Stack)?;
110         }
111         Ok(())
112     }
113
114     let mut ecx = EvalContext::new(tcx, limits, Default::default(), Default::default());
115     match run_main(&mut ecx, main_id, start_wrapper) {
116         Ok(()) => {
117             let leaks = ecx.memory().leak_report();
118             if leaks != 0 {
119                 tcx.sess.err("the evaluated program leaked memory");
120             }
121         }
122         Err(e) => {
123             ecx.report(&e);
124         }
125     }
126 }
127
128 struct Evaluator;
129 #[derive(Default)]
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>,
134 }
135
136 pub type TlsKey = usize;
137
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>>,
142 }
143
144 #[derive(Default)]
145 struct MemoryData<'tcx> {
146     /// The Key to use for the next thread-local allocation.
147     next_thread_local: TlsKey,
148
149     /// pthreads-style thread-local storage.
150     thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
151 }
152
153 trait EvalContextExt<'tcx> {
154     fn finish(&mut self) -> EvalResult<'tcx>;
155 }
156
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(
166                 instance,
167                 mir.span,
168                 mir,
169                 Lvalue::undef(),
170                 StackPopCleanup::None,
171             )?;
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)?;
176
177             // step until out of stackframes
178             while self.step()? {}
179
180             dtor = match self.memory.fetch_tls_dtor(Some(key))? {
181                 dtor @ Some(_) => dtor,
182                 None => self.memory.fetch_tls_dtor(None)?,
183             };
184         }
185         Ok(())
186     }
187 }
188
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)>>;
195 }
196
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);
203         return new_key;
204     }
205
206     fn delete_tls_key(&mut self, key: TlsKey) -> EvalResult<'tcx> {
207         return match self.data.thread_local.remove(&key) {
208             Some(_) => {
209                 trace!("TLS key {} removed", key);
210                 Ok(())
211             },
212             None => Err(EvalError::TlsOutOfBounds)
213         }
214     }
215
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);
220                 Ok(data)
221             },
222             None => Err(EvalError::TlsOutOfBounds)
223         }
224     }
225
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);
230                 *data = new_data;
231                 Ok(())
232             },
233             None => Err(EvalError::TlsOutOfBounds)
234         }
235     }
236     
237     /// Returns a dtor, its argument and its index, if one is supposed to run
238     ///
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.
246     ///
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),
259             None => Unbounded,
260         };
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();
266                     return Ok(ret);
267                 }
268             }
269         }
270         return Ok(None);
271     }
272 }
273
274 impl<'tcx> Machine<'tcx> for Evaluator {
275     type Data = EvaluatorData;
276     type MemoryData = MemoryData<'tcx>;
277
278     /// Returns Ok() when the function was handled, fail otherwise
279     fn eval_fn_call<'a>(
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>],
284         span: Span,
285         sig: ty::FnSig<'tcx>,
286     ) -> EvalResult<'tcx, bool> {
287         ecx.eval_fn_call(instance, destination, arg_operands, span, sig)
288     }
289
290     fn ptr_op<'a>(
291         ecx: &rustc_miri::interpret::EvalContext<'a, 'tcx, Self>,
292         bin_op: mir::BinOp,
293         left: PrimVal,
294         left_ty: ty::Ty<'tcx>,
295         right: PrimVal,
296         right_ty: ty::Ty<'tcx>,
297     ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
298         ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
299     }
300 }