]> git.lizzy.rs Git - rust.git/blob - miri/lib.rs
fb79780c3820a6ed589689e6b1d544148cf07412
[rust.git] / miri / lib.rs
1 #![feature(
2     i128_type,
3     rustc_private,
4     conservative_impl_trait,
5     catch_expr,
6     inclusive_range_fields
7 )]
8
9 #[macro_use]
10 extern crate log;
11
12 // From rustc.
13 #[macro_use]
14 extern crate rustc;
15 extern crate rustc_mir;
16 extern crate rustc_data_structures;
17 extern crate syntax;
18 extern crate regex;
19 #[macro_use]
20 extern crate lazy_static;
21
22 use rustc::ty::{self, TyCtxt};
23 use rustc::ty::layout::{TyLayout, LayoutOf};
24 use rustc::hir::def_id::DefId;
25 use rustc::mir;
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 ) {
60     fn run_main<'a, 'mir: 'a, 'tcx: 'mir>(
61         ecx: &mut rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Evaluator<'tcx>>,
62         main_id: DefId,
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
68
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"
72                     .to_owned(),
73             ));
74         }
75
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(
80                 ecx.tcx.tcx,
81                 ty::ParamEnv::reveal_all(),
82                 start_id,
83                 ecx.tcx.mk_substs(
84                     ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))).unwrap();
85             let start_mir = ecx.load_mir(start_instance.def)?;
86
87             if start_mir.arg_count != 3 {
88                 return err!(AbiViolation(format!(
89                     "'start' lang item should have three arguments, but has {}",
90                     start_mir.arg_count
91                 )));
92             }
93
94             // Return value
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);
99
100             // Push our stack frame
101             ecx.push_stack_frame(
102                 start_instance,
103                 start_mir.span,
104                 start_mir,
105                 Place::from_ptr(ret_ptr, align),
106                 StackPopCleanup::None,
107             )?;
108
109             let mut args = ecx.frame().mir.args_iter();
110
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));
116             ecx.write_value(
117                 ValTy {
118                     value: Value::ByVal(PrimVal::Ptr(main_ptr)),
119                     ty: main_ptr_ty,
120                 },
121                 dest,
122             )?;
123
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)?;
128
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)?;
140
141             assert!(args.next().is_none(), "start lang item has more arguments than expected");
142         } else {
143             ecx.push_stack_frame(
144                 main_instance,
145                 main_mir.span,
146                 main_mir,
147                 Place::undef(),
148                 StackPopCleanup::None,
149             )?;
150
151             // No arguments
152             let mut args = ecx.frame().mir.args_iter();
153             assert!(args.next().is_none(), "main function must not have arguments");
154         }
155
156         while ecx.step()? {}
157         ecx.run_tls_dtors()?;
158         if let Some(cleanup_ptr) = cleanup_ptr {
159             ecx.memory_mut().deallocate(
160                 cleanup_ptr,
161                 None,
162                 MemoryKind::Stack,
163             )?;
164         }
165         Ok(())
166     }
167
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) {
170         Ok(()) => {
171             let leaks = ecx.memory().leak_report();
172             if leaks != 0 {
173                 tcx.sess.err("the evaluated program leaked memory");
174             }
175         }
176         Err(mut e) => {
177             ecx.report(&mut e, true, None);
178         }
179     }
180 }
181
182 #[derive(Default)]
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>,
187
188     /// Places that were suspended by the validation subsystem, and will be recovered later
189     pub(crate) suspended: HashMap<DynamicLifetime, Vec<ValidationQuery<'tcx>>>,
190 }
191
192 pub type TlsKey = usize;
193
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>>,
198 }
199
200 #[derive(Default)]
201 pub struct MemoryData<'tcx> {
202     /// The Key to use for the next thread-local allocation.
203     next_thread_local: TlsKey,
204
205     /// pthreads-style thread-local storage.
206     thread_local: BTreeMap<TlsKey, TlsEntry<'tcx>>,
207
208     /// Memory regions that are locked by some function
209     ///
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>>>,
213
214     mut_statics: HashMap<GlobalId<'tcx>, AllocId>,
215 }
216
217 impl<'mir, 'tcx: 'mir> Machine<'mir, 'tcx> for Evaluator<'tcx> {
218     type MemoryData = MemoryData<'tcx>;
219     type MemoryKinds = memory::MemoryKind;
220
221     /// Returns Ok() when the function was handled, fail otherwise
222     fn eval_fn_call<'a>(
223         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
224         instance: ty::Instance<'tcx>,
225         destination: Option<(Place, mir::BasicBlock)>,
226         args: &[ValTy<'tcx>],
227         span: Span,
228         sig: ty::FnSig<'tcx>,
229     ) -> EvalResult<'tcx, bool> {
230         ecx.eval_fn_call(instance, destination, args, span, sig)
231     }
232
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>],
237         dest: Place,
238         dest_layout: TyLayout<'tcx>,
239         target: mir::BasicBlock,
240     ) -> EvalResult<'tcx> {
241         ecx.call_intrinsic(instance, args, dest, dest_layout, target)
242     }
243
244     fn try_ptr_op<'a>(
245         ecx: &rustc_mir::interpret::EvalContext<'a, 'mir, 'tcx, Self>,
246         bin_op: mir::BinOp,
247         left: PrimVal,
248         left_ty: ty::Ty<'tcx>,
249         right: PrimVal,
250         right_ty: ty::Ty<'tcx>,
251     ) -> EvalResult<'tcx, Option<(PrimVal, bool)>> {
252         ecx.ptr_op(bin_op, left, left_ty, right, right_ty)
253     }
254
255     fn mark_static_initialized<'a>(
256         _mem: &mut Memory<'a, 'mir, 'tcx, Self>,
257         _id: AllocId,
258         _mutability: Mutability,
259     ) -> EvalResult<'tcx, bool> {
260         /*use memory::MemoryKind::*;
261         match m {
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?
265         }*/
266         Ok(false)
267     }
268
269     fn init_static<'a>(
270         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
271         cid: GlobalId<'tcx>,
272     ) -> EvalResult<'tcx, AllocId> {
273         if let Some(alloc_id) = ecx.memory.data.get(&cid) {
274             return Ok(alloc_id);
275         }
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(
279             layout.size.bytes(),
280             layout.align,
281             None,
282         )?;
283         ecx.const_eval(cid)?;
284         let ptr = ecx
285             .tcx
286             .interpret_interner
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());
292         Ok(to_ptr.alloc_id)
293     }
294
295     fn box_alloc<'a>(
296         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
297         ty: ty::Ty<'tcx>,
298         dest: Place,
299     ) -> EvalResult<'tcx> {
300         let layout = ecx.layout_of(ty)?;
301
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(
307             malloc,
308             malloc_mir.span,
309             malloc_mir,
310             dest,
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,
315         )?;
316
317         let mut args = ecx.frame().mir.args_iter();
318         let usize = ecx.tcx.types.usize;
319
320         // First argument: size
321         let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
322         ecx.write_value(
323             ValTy {
324                 value: Value::ByVal(PrimVal::Bytes(layout.size.bytes().into())),
325                 ty: usize,
326             },
327             dest,
328         )?;
329
330         // Second argument: align
331         let dest = ecx.eval_place(&mir::Place::Local(args.next().unwrap()))?;
332         ecx.write_value(
333             ValTy {
334                 value: Value::ByVal(PrimVal::Bytes(layout.align.abi().into())),
335                 ty: usize,
336             },
337             dest,
338         )?;
339
340         // No more arguments
341         assert!(args.next().is_none(), "exchange_malloc lang item has more arguments than expected");
342         Ok(())
343     }
344
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(
355             ptr_size,
356             ptr_align,
357             None,
358         )?;
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(
362             instance.def_id(),
363             ptr.alloc_id,
364         );
365         Ok(())
366     }
367
368     fn check_locks<'a>(
369         mem: &Memory<'a, 'mir, 'tcx, Self>,
370         ptr: MemoryPointer,
371         size: u64,
372         access: AccessKind,
373     ) -> EvalResult<'tcx> {
374         mem.check_locks(ptr, size, access)
375     }
376
377     fn add_lock<'a>(
378         mem: &mut Memory<'a, 'mir, 'tcx, Self>,
379         id: AllocId,
380     ) {
381         mem.data.locks.insert(id, RangeMap::new());
382     }
383
384     fn free_lock<'a>(
385         mem: &mut Memory<'a, 'mir, 'tcx, Self>,
386         id: AllocId,
387         len: u64,
388     ) -> EvalResult<'tcx> {
389         mem.data.locks
390             .remove(&id)
391             .expect("allocation has no corresponding locks")
392             .check(
393                 Some(mem.cur_frame),
394                 0,
395                 len,
396                 AccessKind::Read,
397             )
398             .map_err(|lock| {
399                 EvalErrorKind::DeallocatedLockedMemory {
400                     //ptr, FIXME
401                     ptr: MemoryPointer {
402                         alloc_id: AllocId(0),
403                         offset: 0,
404                     },
405                     lock: lock.active,
406                 }.into()
407             })
408     }
409
410     fn end_region<'a>(
411         ecx: &mut EvalContext<'a, 'mir, 'tcx, Self>,
412         reg: Option<::rustc::middle::region::Scope>,
413     ) -> EvalResult<'tcx> {
414         ecx.end_region(reg)
415     }
416
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)
423     }
424 }