]> git.lizzy.rs Git - rust.git/blob - src/lib.rs
9072f141f89d9d3759873c71791352741b03f83f
[rust.git] / src / lib.rs
1 #![feature(rustc_private)]
2
3 #![allow(clippy::cast_lossless)]
4
5 #[macro_use]
6 extern crate log;
7 // From rustc.
8 extern crate syntax;
9 extern crate rustc_apfloat;
10 #[macro_use] extern crate rustc;
11 extern crate rustc_data_structures;
12 extern crate rustc_mir;
13 extern crate rustc_target;
14
15 mod fn_call;
16 mod operator;
17 mod intrinsic;
18 mod helpers;
19 mod tls;
20 mod range_map;
21 mod mono_hash_map;
22 mod stacked_borrows;
23
24 use std::collections::HashMap;
25 use std::borrow::Cow;
26 use std::rc::Rc;
27
28 use rand::rngs::StdRng;
29 use rand::SeedableRng;
30
31 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
32 use rustc::ty::layout::{LayoutOf, Size, Align};
33 use rustc::hir::def_id::DefId;
34 use rustc::mir;
35 pub use rustc_mir::interpret::*;
36 // Resolve ambiguity.
37 pub use rustc_mir::interpret::{self, AllocMap, PlaceTy};
38 use syntax::attr;
39 use syntax::source_map::DUMMY_SP;
40 use syntax::symbol::sym;
41
42 pub use crate::fn_call::EvalContextExt as MissingFnsEvalContextExt;
43 pub use crate::operator::EvalContextExt as OperatorEvalContextExt;
44 pub use crate::intrinsic::EvalContextExt as IntrinsicEvalContextExt;
45 pub use crate::tls::{EvalContextExt as TlsEvalContextExt, TlsData};
46 use crate::range_map::RangeMap;
47 #[allow(unused_imports)] // FIXME: rustc bug, issue <https://github.com/rust-lang/rust/issues/53682>.
48 pub use crate::helpers::{EvalContextExt as HelpersEvalContextExt};
49 use crate::mono_hash_map::MonoHashMap;
50 pub use crate::stacked_borrows::{EvalContextExt as StackedBorEvalContextExt};
51
52 // Used by priroda.
53 pub use crate::stacked_borrows::{Tag, Permission, Stack, Stacks, Item};
54
55 /// Insert rustc arguments at the beginning of the argument list that Miri wants to be
56 /// set per default, for maximal validation power.
57 pub fn miri_default_args() -> &'static [&'static str] {
58     // The flags here should be kept in sync with what bootstrap adds when `test-miri` is
59     // set, which happens in `bootstrap/bin/rustc.rs` in the rustc sources.
60     &["-Zalways-encode-mir", "-Zmir-emit-retag", "-Zmir-opt-level=0", "--cfg=miri"]
61 }
62
63 /// Configuration needed to spawn a Miri instance.
64 #[derive(Clone)]
65 pub struct MiriConfig {
66     pub validate: bool,
67     pub args: Vec<String>,
68
69     // The seed to use when non-determinism is required (e.g. getrandom())
70     pub seed: Option<u64>
71 }
72
73 // Used by priroda.
74 pub fn create_ecx<'mir, 'tcx: 'mir>(
75     tcx: TyCtxt<'tcx>,
76     main_id: DefId,
77     config: MiriConfig,
78 ) -> InterpResult<'tcx, InterpretCx<'mir, 'tcx, Evaluator<'tcx>>> {
79     let mut ecx = InterpretCx::new(
80         tcx.at(syntax::source_map::DUMMY_SP),
81         ty::ParamEnv::reveal_all(),
82         Evaluator::new(config.validate, config.seed),
83     );
84
85     let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
86     let main_mir = ecx.load_mir(main_instance.def)?;
87
88     if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
89         return err!(Unimplemented(
90             "miri does not support main functions without `fn()` type signatures"
91                 .to_owned(),
92         ));
93     }
94
95     let start_id = tcx.lang_items().start_fn().unwrap();
96     let main_ret_ty = tcx.fn_sig(main_id).output();
97     let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
98     let start_instance = ty::Instance::resolve(
99         ecx.tcx.tcx,
100         ty::ParamEnv::reveal_all(),
101         start_id,
102         ecx.tcx.mk_substs(
103             ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
104         ).unwrap();
105     let start_mir = ecx.load_mir(start_instance.def)?;
106
107     if start_mir.arg_count != 3 {
108         return err!(AbiViolation(format!(
109             "'start' lang item should have three arguments, but has {}",
110             start_mir.arg_count
111         )));
112     }
113
114     // Return value (in static memory so that it does not count as leak).
115     let ret = ecx.layout_of(start_mir.return_ty())?;
116     let ret_ptr = ecx.allocate(ret, MiriMemoryKind::Static.into());
117
118     // Push our stack frame.
119     ecx.push_stack_frame(
120         start_instance,
121         // There is no call site.
122         DUMMY_SP,
123         start_mir,
124         Some(ret_ptr.into()),
125         StackPopCleanup::None { cleanup: true },
126     )?;
127
128     let mut args = ecx.frame().body.args_iter();
129
130     // First argument: pointer to `main()`.
131     let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance);
132     let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
133     ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
134
135     // Second argument (argc): `1`.
136     let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
137     let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
138     ecx.write_scalar(argc, dest)?;
139     // Store argc for macOS's `_NSGetArgc`.
140     {
141         let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
142         ecx.write_scalar(argc, argc_place.into())?;
143         ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
144     }
145
146     // FIXME: extract main source file path.
147     // Third argument (`argv`): created from `config.args`.
148     let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
149     // For Windows, construct a command string with all the aguments.
150     let mut cmd = String::new();
151     for arg in config.args.iter() {
152         if !cmd.is_empty() {
153             cmd.push(' ');
154         }
155         cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
156     }
157     // Don't forget `0` terminator.
158     cmd.push(std::char::from_u32(0).unwrap());
159     // Collect the pointers to the individual strings.
160     let mut argvs = Vec::<Pointer<Tag>>::new();
161     for arg in config.args {
162         // Add `0` terminator.
163         let mut arg = arg.into_bytes();
164         arg.push(0);
165         argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
166     }
167     // Make an array with all these pointers, in the Miri memory.
168     let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
169     let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
170     for (idx, arg) in argvs.into_iter().enumerate() {
171         let place = ecx.mplace_field(argvs_place, idx as u64)?;
172         ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
173     }
174     ecx.memory_mut().mark_immutable(argvs_place.to_ptr()?.alloc_id)?;
175     // Write a pointer to that place as the argument.
176     let argv = argvs_place.ptr;
177     ecx.write_scalar(argv, dest)?;
178     // Store `argv` for macOS `_NSGetArgv`.
179     {
180         let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
181         ecx.write_scalar(argv, argv_place.into())?;
182         ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
183     }
184     // Store command line as UTF-16 for Windows `GetCommandLineW`.
185     {
186         let tcx = &{ecx.tcx.tcx};
187         let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
188         let cmd_ptr = ecx.memory_mut().allocate(
189             Size::from_bytes(cmd_utf16.len() as u64 * 2),
190             Align::from_bytes(2).unwrap(),
191             MiriMemoryKind::Env.into(),
192         );
193         ecx.machine.cmd_line = Some(cmd_ptr);
194         // Store the UTF-16 string.
195         let char_size = Size::from_bytes(2);
196         let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
197         let mut cur_ptr = cmd_ptr;
198         for &c in cmd_utf16.iter() {
199             cmd_alloc.write_scalar(
200                 tcx,
201                 cur_ptr,
202                 Scalar::from_uint(c, char_size).into(),
203                 char_size,
204             )?;
205             cur_ptr = cur_ptr.offset(char_size, tcx)?;
206         }
207     }
208
209     assert!(args.next().is_none(), "start lang item has more arguments than expected");
210
211     Ok(ecx)
212 }
213
214 pub fn eval_main<'tcx>(
215     tcx: TyCtxt<'tcx>,
216     main_id: DefId,
217     config: MiriConfig,
218 ) {
219     let mut ecx = match create_ecx(tcx, main_id, config) {
220         Ok(ecx) => ecx,
221         Err(mut err) => {
222             err.print_backtrace();
223             panic!("Miri initialziation error: {}", err.kind)
224         }
225     };
226
227     // Perform the main execution.
228     let res: InterpResult = (|| {
229         ecx.run()?;
230         ecx.run_tls_dtors()
231     })();
232
233     // Process the result.
234     match res {
235         Ok(()) => {
236             let leaks = ecx.memory().leak_report();
237             // Disable the leak test on some platforms where we do not
238             // correctly implement TLS destructors.
239             let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
240             let ignore_leaks = target_os == "windows" || target_os == "macos";
241             if !ignore_leaks && leaks != 0 {
242                 tcx.sess.err("the evaluated program leaked memory");
243             }
244         }
245         Err(mut e) => {
246             // Special treatment for some error kinds
247             let msg = match e.kind {
248                 InterpError::Exit(code) => std::process::exit(code),
249                 InterpError::NoMirFor(..) =>
250                     format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
251                 _ => e.to_string()
252             };
253             e.print_backtrace();
254             if let Some(frame) = ecx.stack().last() {
255                 let block = &frame.body.basic_blocks()[frame.block];
256                 let span = if frame.stmt < block.statements.len() {
257                     block.statements[frame.stmt].source_info.span
258                 } else {
259                     block.terminator().source_info.span
260                 };
261
262                 let msg = format!("Miri evaluation error: {}", msg);
263                 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
264                 let frames = ecx.generate_stacktrace(None);
265                 err.span_label(span, msg);
266                 // We iterate with indices because we need to look at the next frame (the caller).
267                 for idx in 0..frames.len() {
268                     let frame_info = &frames[idx];
269                     let call_site_is_local = frames.get(idx+1).map_or(false,
270                         |caller_info| caller_info.instance.def_id().is_local());
271                     if call_site_is_local {
272                         err.span_note(frame_info.call_site, &frame_info.to_string());
273                     } else {
274                         err.note(&frame_info.to_string());
275                     }
276                 }
277                 err.emit();
278             } else {
279                 ecx.tcx.sess.err(&msg);
280             }
281
282             for (i, frame) in ecx.stack().iter().enumerate() {
283                 trace!("-------------------");
284                 trace!("Frame {}", i);
285                 trace!("    return: {:?}", frame.return_place.map(|p| *p));
286                 for (i, local) in frame.locals.iter().enumerate() {
287                     trace!("    local {}: {:?}", i, local.value);
288                 }
289             }
290         }
291     }
292 }
293
294 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
295 pub enum MiriMemoryKind {
296     /// `__rust_alloc` memory.
297     Rust,
298     /// `malloc` memory.
299     C,
300     /// Part of env var emulation.
301     Env,
302     /// Statics.
303     Static,
304 }
305
306 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
307     #[inline(always)]
308     fn into(self) -> MemoryKind<MiriMemoryKind> {
309         MemoryKind::Machine(self)
310     }
311 }
312
313 impl MayLeak for MiriMemoryKind {
314     #[inline(always)]
315     fn may_leak(self) -> bool {
316         use self::MiriMemoryKind::*;
317         match self {
318             Rust | C => false,
319             Env | Static => true,
320         }
321     }
322 }
323
324 pub struct Evaluator<'tcx> {
325     /// Environment variables set by `setenv`.
326     /// Miri does not expose env vars from the host to the emulated program.
327     pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Tag>>,
328
329     /// Program arguments (`Option` because we can only initialize them after creating the ecx).
330     /// These are *pointers* to argc/argv because macOS.
331     /// We also need the full command line as one string because of Windows.
332     pub(crate) argc: Option<Pointer<Tag>>,
333     pub(crate) argv: Option<Pointer<Tag>>,
334     pub(crate) cmd_line: Option<Pointer<Tag>>,
335
336     /// Last OS error.
337     pub(crate) last_error: u32,
338
339     /// TLS state.
340     pub(crate) tls: TlsData<'tcx>,
341
342     /// Whether to enforce the validity invariant.
343     pub(crate) validate: bool,
344
345     /// The random number generator to use if Miri
346     /// is running in non-deterministic mode
347     pub(crate) rng: Option<StdRng>
348 }
349
350 impl<'tcx> Evaluator<'tcx> {
351     fn new(validate: bool, seed: Option<u64>) -> Self {
352         Evaluator {
353             env_vars: HashMap::default(),
354             argc: None,
355             argv: None,
356             cmd_line: None,
357             last_error: 0,
358             tls: TlsData::default(),
359             validate,
360             rng: seed.map(|s| StdRng::seed_from_u64(s))
361         }
362     }
363 }
364
365 // FIXME: rustc issue <https://github.com/rust-lang/rust/issues/47131>.
366 #[allow(dead_code)]
367 type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
368
369 // A little trait that's useful to be inherited by extension traits.
370 pub trait MiriEvalContextExt<'mir, 'tcx> {
371     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx>;
372     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx>;
373 }
374 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
375     #[inline(always)]
376     fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
377         self
378     }
379     #[inline(always)]
380     fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
381         self
382     }
383 }
384
385 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
386     type MemoryKinds = MiriMemoryKind;
387
388     type FrameExtra = stacked_borrows::CallId;
389     type MemoryExtra = stacked_borrows::MemoryState;
390     type AllocExtra = stacked_borrows::Stacks;
391     type PointerTag = Tag;
392
393     type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
394
395     const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
396
397     #[inline(always)]
398     fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
399         ecx.machine.validate
400     }
401
402     /// Returns `Ok()` when the function was handled; fail otherwise.
403     #[inline(always)]
404     fn find_fn(
405         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
406         instance: ty::Instance<'tcx>,
407         args: &[OpTy<'tcx, Tag>],
408         dest: Option<PlaceTy<'tcx, Tag>>,
409         ret: Option<mir::BasicBlock>,
410     ) -> InterpResult<'tcx, Option<&'mir mir::Body<'tcx>>> {
411         ecx.find_fn(instance, args, dest, ret)
412     }
413
414     #[inline(always)]
415     fn call_intrinsic(
416         ecx: &mut rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
417         instance: ty::Instance<'tcx>,
418         args: &[OpTy<'tcx, Tag>],
419         dest: PlaceTy<'tcx, Tag>,
420     ) -> InterpResult<'tcx> {
421         ecx.call_intrinsic(instance, args, dest)
422     }
423
424     #[inline(always)]
425     fn ptr_op(
426         ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
427         bin_op: mir::BinOp,
428         left: ImmTy<'tcx, Tag>,
429         right: ImmTy<'tcx, Tag>,
430     ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
431         ecx.ptr_op(bin_op, left, right)
432     }
433
434     fn box_alloc(
435         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
436         dest: PlaceTy<'tcx, Tag>,
437     ) -> InterpResult<'tcx> {
438         trace!("box_alloc for {:?}", dest.layout.ty);
439         // Call the `exchange_malloc` lang item.
440         let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
441         let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
442         let malloc_mir = ecx.load_mir(malloc.def)?;
443         ecx.push_stack_frame(
444             malloc,
445             malloc_mir.span,
446             malloc_mir,
447             Some(dest),
448             // Don't do anything when we are done. The `statement()` function will increment
449             // the old stack frame's stmt counter to the next statement, which means that when
450             // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
451             StackPopCleanup::None { cleanup: true },
452         )?;
453
454         let mut args = ecx.frame().body.args_iter();
455         let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
456
457         // First argument: `size`.
458         // (`0` is allowed here -- this is expected to be handled by the lang item).
459         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
460         let size = layout.size.bytes();
461         ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
462
463         // Second argument: `align`.
464         let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
465         let align = layout.align.abi.bytes();
466         ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
467
468         // No more arguments.
469         assert!(
470             args.next().is_none(),
471             "`exchange_malloc` lang item has more arguments than expected"
472         );
473         Ok(())
474     }
475
476     fn find_foreign_static(
477         def_id: DefId,
478         tcx: TyCtxtAt<'tcx>,
479     ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> {
480         let attrs = tcx.get_attrs(def_id);
481         let link_name = match attr::first_attr_value_str_by_name(&attrs, sym::link_name) {
482             Some(name) => name.as_str(),
483             None => tcx.item_name(def_id).as_str(),
484         };
485
486         let alloc = match link_name.get() {
487             "__cxa_thread_atexit_impl" => {
488                 // This should be all-zero, pointer-sized.
489                 let size = tcx.data_layout.pointer_size;
490                 let data = vec![0; size.bytes() as usize];
491                 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi)
492             }
493             _ => return err!(Unimplemented(
494                     format!("can't access foreign static: {}", link_name),
495                 )),
496         };
497         Ok(Cow::Owned(alloc))
498     }
499
500     #[inline(always)]
501     fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
502     {
503         // We are not interested in detecting loops.
504         Ok(())
505     }
506
507     fn tag_allocation<'b>(
508         id: AllocId,
509         alloc: Cow<'b, Allocation>,
510         kind: Option<MemoryKind<Self::MemoryKinds>>,
511         memory: &Memory<'mir, 'tcx, Self>,
512     ) -> (Cow<'b, Allocation<Self::PointerTag, Self::AllocExtra>>, Self::PointerTag) {
513         let kind = kind.expect("we set our STATIC_KIND so this cannot be None");
514         let alloc = alloc.into_owned();
515         let (extra, base_tag) = Stacks::new_allocation(
516             id,
517             Size::from_bytes(alloc.bytes.len() as u64),
518             Rc::clone(&memory.extra),
519             kind,
520         );
521         if kind != MiriMemoryKind::Static.into() {
522             assert!(alloc.relocations.is_empty(), "Only statics can come initialized with inner pointers");
523             // Now we can rely on the inner pointers being static, too.
524         }
525         let mut memory_extra = memory.extra.borrow_mut();
526         let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
527             bytes: alloc.bytes,
528             relocations: Relocations::from_presorted(
529                 alloc.relocations.iter()
530                     // The allocations in the relocations (pointers stored *inside* this allocation)
531                     // all get the base pointer tag.
532                     .map(|&(offset, ((), alloc))| (offset, (memory_extra.static_base_ptr(alloc), alloc)))
533                     .collect()
534             ),
535             undef_mask: alloc.undef_mask,
536             align: alloc.align,
537             mutability: alloc.mutability,
538             extra,
539         };
540         (Cow::Owned(alloc), base_tag)
541     }
542
543     #[inline(always)]
544     fn tag_static_base_pointer(
545         id: AllocId,
546         memory: &Memory<'mir, 'tcx, Self>,
547     ) -> Self::PointerTag {
548         memory.extra.borrow_mut().static_base_ptr(id)
549     }
550
551     #[inline(always)]
552     fn retag(
553         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
554         kind: mir::RetagKind,
555         place: PlaceTy<'tcx, Tag>,
556     ) -> InterpResult<'tcx> {
557         if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
558             // No tracking, or no retagging. The latter is possible because a dependency of ours
559             // might be called with different flags than we are, so there are `Retag`
560             // statements but we do not want to execute them.
561             // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
562             // uninitialized data.
563              Ok(())
564         } else {
565             ecx.retag(kind, place)
566         }
567     }
568
569     #[inline(always)]
570     fn stack_push(
571         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
572     ) -> InterpResult<'tcx, stacked_borrows::CallId> {
573         Ok(ecx.memory().extra.borrow_mut().new_call())
574     }
575
576     #[inline(always)]
577     fn stack_pop(
578         ecx: &mut InterpretCx<'mir, 'tcx, Self>,
579         extra: stacked_borrows::CallId,
580     ) -> InterpResult<'tcx> {
581         Ok(ecx.memory().extra.borrow_mut().end_call(extra))
582     }
583 }