]> git.lizzy.rs Git - rust.git/blob - miri/lib.rs
d4c211e1fd959f46f26fee220c3d5f4483a2eae4
[rust.git] / miri / lib.rs
1 #![feature(
2     i128_type,
3     rustc_private,
4     conservative_impl_trait,
5     catch_expr,
6 )]
7
8 // From rustc.
9 #[macro_use]
10 extern crate log;
11 #[macro_use]
12 extern crate rustc;
13 extern crate rustc_mir;
14 extern crate rustc_data_structures;
15 extern crate syntax;
16 extern crate regex;
17 #[macro_use]
18 extern crate lazy_static;
19
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;
24 use rustc::mir;
25 use rustc::traits;
26
27 use syntax::ast::Mutability;
28 use syntax::codemap::Span;
29
30 use std::collections::{HashMap, BTreeMap};
31
32 pub use rustc::mir::interpret::*;
33 pub use rustc_mir::interpret::*;
34
35 mod fn_call;
36 mod operator;
37 mod intrinsic;
38 mod helpers;
39 mod memory;
40 mod tls;
41 mod locks;
42 mod range_map;
43 mod validation;
44
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;
49 use locks::LockInfo;
50 use locks::MemoryExt as LockMemoryExt;
51 use validation::EvalContextExt as ValidationEvalContextExt;
52 use range_map::RangeMap;
53 use validation::{ValidationQuery, AbsPlace};
54
55 pub fn eval_main<'a, 'tcx: 'a>(
56     tcx: TyCtxt<'a, 'tcx, 'tcx>,
57     main_id: DefId,
58     start_wrapper: Option<DefId>,
59     limits: ResourceLimits,
60 ) {
61     fn run_main<'a, 'tcx: 'a>(
62         ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Evaluator<'tcx>>,
63         main_id: DefId,
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
69
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"
73                     .to_owned(),
74             ));
75         }
76
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)?;
80
81             if start_mir.arg_count != 3 {
82                 return err!(AbiViolation(format!(
83                     "'start' lang item should have three arguments, but has {}",
84                     start_mir.arg_count
85                 )));
86             }
87
88             // Return value
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);
93
94             // Push our stack frame
95             ecx.push_stack_frame(
96                 start_instance,
97                 start_mir.span,
98                 start_mir,
99                 Place::from_ptr(ret_ptr),
100                 StackPopCleanup::None,
101             )?;
102
103             let mut args = ecx.frame().mir.args_iter();
104
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));
110             ecx.write_value(
111                 ValTy {
112                     value: Value::ByVal(PrimVal::Ptr(main_ptr)),
113                     ty: main_ptr_ty,
114                 },
115                 dest,
116             )?;
117
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)?;
122
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)?;
133
134             assert!(args.next().is_none(), "start lang item has more arguments than expected");
135         } else {
136             ecx.push_stack_frame(
137                 main_instance,
138                 main_mir.span,
139                 main_mir,
140                 Place::undef(),
141                 StackPopCleanup::None,
142             )?;
143
144             // No arguments
145             let mut args = ecx.frame().mir.args_iter();
146             assert!(args.next().is_none(), "main function must not have arguments");
147         }
148
149         while ecx.step()? {}
150         ecx.run_tls_dtors()?;
151         if let Some(cleanup_ptr) = cleanup_ptr {
152             ecx.memory_mut().deallocate(
153                 cleanup_ptr,
154                 None,
155                 MemoryKind::Stack,
156             )?;
157         }
158         Ok(())
159     }
160
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) {
163         Ok(()) => {
164             let leaks = ecx.memory().leak_report();
165             if leaks != 0 {
166                 tcx.sess.err("the evaluated program leaked memory");
167             }
168         }
169         Err(mut e) => {
170             ecx.report(&mut e);
171         }
172     }
173 }
174
175 #[derive(Default)]
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>,
180
181     /// Places that were suspended by the validation subsystem, and will be recovered later
182     pub(crate) suspended: HashMap<DynamicLifetime, Vec<ValidationQuery<'tcx>>>,
183 }
184
185 pub type TlsKey = usize;
186
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>>,
191 }
192
193 #[derive(Default)]
194 pub struct MemoryData<'tcx> {
195     /// The Key to use for the next thread-local allocation.
196     next_thread_local: TlsKey,
197
198     /// pthreads-style thread-local storage.
199     thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
200
201     /// Memory regions that are locked by some function
202     ///
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>>>,
206 }
207
208 impl<'tcx> Machine<'tcx> for Evaluator<'tcx> {
209     type MemoryData = MemoryData<'tcx>;
210     type MemoryKinds = memory::MemoryKind;
211
212     /// Returns Ok() when the function was handled, fail otherwise
213     fn eval_fn_call<'a>(
214         ecx: &mut EvalContext<'a, 'tcx, Self>,
215         instance: ty::Instance<'tcx>,
216         destination: Option<(Place, mir::BasicBlock)>,
217         args: &[ValTy<'tcx>],
218         span: Span,
219         sig: ty::FnSig<'tcx>,
220     ) -> EvalResult<'tcx, bool> {
221         ecx.eval_fn_call(instance, destination, args, span, sig)
222     }
223
224     fn call_intrinsic<'a>(
225         ecx: &mut rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
226         instance: ty::Instance<'tcx>,
227         args: &[ValTy<'tcx>],
228         dest: Place,
229         dest_layout: TyLayout<'tcx>,
230         target: mir::BasicBlock,
231     ) -> EvalResult<'tcx> {
232         ecx.call_intrinsic(instance, args, dest, dest_layout, target)
233     }
234
235     fn try_ptr_op<'a>(
236         ecx: &rustc_mir::interpret::EvalContext<'a, 'tcx, Self>,
237         bin_op: mir::BinOp,
238         left: PrimVal,
239         left_ty: ty::Ty<'tcx>,
240         right: PrimVal,
241         right_ty: ty::Ty<'tcx>,
242     ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
243         ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
244     }
245
246     fn mark_static_initialized(m: memory::MemoryKind) -> EvalResult<'tcx> {
247         use memory::MemoryKind::*;
248         match m {
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())),
251             _ => Ok(()),
252         }
253     }
254
255     fn box_alloc<'a>(
256         ecx: &mut EvalContext<'a, 'tcx, Self>,
257         ty: ty::Ty<'tcx>,
258         dest: Place,
259     ) -> EvalResult<'tcx> {
260         let layout = ecx.layout_of(ty)?;
261
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(
267             malloc,
268             malloc_mir.span,
269             malloc_mir,
270             dest,
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,
275         )?;
276
277         let mut args = ecx.frame().mir.args_iter();
278         let usize = ecx.tcx.types.usize;
279
280         // First argument: size
281         let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
282         ecx.write_value(
283             ValTy {
284                 value: Value::ByVal(PrimVal::Bytes(layout.size.bytes().into())),
285                 ty: usize,
286             },
287             dest,
288         )?;
289
290         // Second argument: align
291         let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
292         ecx.write_value(
293             ValTy {
294                 value: Value::ByVal(PrimVal::Bytes(layout.align.abi().into())),
295                 ty: usize,
296             },
297             dest,
298         )?;
299
300         // No more arguments
301         assert!(args.next().is_none(), "exchange_malloc lang item has more arguments than expected");
302         Ok(())
303     }
304
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(
314             ptr_size,
315             ptr_size,
316             None,
317         )?;
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(
321             GlobalId {
322                 instance,
323                 promoted: None,
324             },
325             PtrAndAlign {
326                 ptr: ptr.into(),
327                 aligned: true,
328             },
329         );
330         Ok(())
331     }
332
333     fn check_locks<'a>(
334         mem: &Memory<'a, 'tcx, Self>,
335         ptr: MemoryPointer,
336         size: u64,
337         access: AccessKind,
338     ) -> EvalResult<'tcx> {
339         mem.check_locks(ptr, size, access)
340     }
341
342     fn add_lock<'a>(
343         mem: &mut Memory<'a, 'tcx, Self>,
344         id: u64,
345     ) {
346         mem.data.locks.insert(id, RangeMap::new());
347     }
348
349     fn free_lock<'a>(
350         mem: &mut Memory<'a, 'tcx, Self>,
351         id: u64,
352         len: u64,
353     ) -> EvalResult<'tcx> {
354         mem.data.locks
355             .remove(&id)
356             .expect("allocation has no corresponding locks")
357             .check(
358                 Some(mem.cur_frame),
359                 0,
360                 len,
361                 AccessKind::Read,
362             )
363             .map_err(|lock| {
364                 EvalErrorKind::DeallocatedLockedMemory {
365                     //ptr, FIXME
366                     ptr: MemoryPointer {
367                         alloc_id: AllocId(0),
368                         offset: 0,
369                     },
370                     lock: lock.active,
371                 }.into()
372             })
373     }
374
375     fn end_region<'a>(
376         ecx: &mut EvalContext<'a, 'tcx, Self>,
377         reg: Option<::rustc::middle::region::Scope>,
378     ) -> EvalResult<'tcx> {
379         ecx.end_region(reg)
380     }
381
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)
388     }
389 }