1 #![feature(rustc_private)]
3 #![allow(clippy::cast_lossless)]
11 extern crate rustc_data_structures;
12 extern crate rustc_mir;
13 extern crate rustc_target;
24 use std::collections::HashMap;
27 use rand::rngs::StdRng;
28 use rand::SeedableRng;
30 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
31 use rustc::ty::layout::{LayoutOf, Size, Align};
32 use rustc::hir::{self, def_id::DefId};
34 pub use rustc_mir::interpret::*;
36 pub use rustc_mir::interpret::{self, AllocMap, PlaceTy};
38 use syntax::source_map::DUMMY_SP;
40 pub use crate::fn_call::EvalContextExt as MissingFnsEvalContextExt;
41 pub use crate::operator::EvalContextExt as OperatorEvalContextExt;
42 pub use crate::intrinsic::EvalContextExt as IntrinsicEvalContextExt;
43 pub use crate::tls::{EvalContextExt as TlsEvalContextExt, TlsData};
44 use crate::range_map::RangeMap;
45 #[allow(unused_imports)] // FIXME: rustc bug, issue <https://github.com/rust-lang/rust/issues/53682>.
46 pub use crate::helpers::{EvalContextExt as HelpersEvalContextExt};
47 use crate::mono_hash_map::MonoHashMap;
48 pub use crate::stacked_borrows::{EvalContextExt as StackedBorEvalContextExt};
51 pub use crate::stacked_borrows::{Borrow, Stack, Stacks, BorStackItem};
53 /// Insert rustc arguments at the beginning of the argument list that Miri wants to be
54 /// set per default, for maximal validation power.
55 pub fn miri_default_args() -> &'static [&'static str] {
56 // The flags here should be kept in sync with what bootstrap adds when `test-miri` is
57 // set, which happens in `bootstrap/bin/rustc.rs` in the rustc sources.
58 &["-Zalways-encode-mir", "-Zmir-emit-retag", "-Zmir-opt-level=0", "--cfg=miri"]
61 /// Configuration needed to spawn a Miri instance.
63 pub struct MiriConfig {
65 pub args: Vec<String>,
67 // The seed to use when non-determinism is required (e.g. getrandom())
72 pub fn create_ecx<'a, 'mir: 'a, 'tcx: 'mir>(
73 tcx: TyCtxt<'a, 'tcx, 'tcx>,
76 ) -> EvalResult<'tcx, InterpretCx<'a, 'mir, 'tcx, Evaluator<'tcx>>> {
77 let mut ecx = InterpretCx::new(
78 tcx.at(syntax::source_map::DUMMY_SP),
79 ty::ParamEnv::reveal_all(),
80 Evaluator::new(config.validate, config.seed),
83 let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
84 let main_mir = ecx.load_mir(main_instance.def)?;
86 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
87 return err!(Unimplemented(
88 "miri does not support main functions without `fn()` type signatures"
93 let start_id = tcx.lang_items().start_fn().unwrap();
94 let main_ret_ty = tcx.fn_sig(main_id).output();
95 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
96 let start_instance = ty::Instance::resolve(
98 ty::ParamEnv::reveal_all(),
101 ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
103 let start_mir = ecx.load_mir(start_instance.def)?;
105 if start_mir.arg_count != 3 {
106 return err!(AbiViolation(format!(
107 "'start' lang item should have three arguments, but has {}",
112 // Return value (in static memory so that it does not count as leak).
113 let ret = ecx.layout_of(start_mir.return_ty())?;
114 let ret_ptr = ecx.allocate(ret, MiriMemoryKind::MutStatic.into());
116 // Push our stack frame.
117 ecx.push_stack_frame(
119 // There is no call site.
122 Some(ret_ptr.into()),
123 StackPopCleanup::None { cleanup: true },
126 let mut args = ecx.frame().mir.args_iter();
128 // First argument: pointer to `main()`.
129 let main_ptr = ecx.memory_mut().create_fn_alloc(main_instance).with_default_tag();
130 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
131 ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
133 // Second argument (argc): `1`.
134 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
135 let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
136 ecx.write_scalar(argc, dest)?;
137 // Store argc for macOS's `_NSGetArgc`.
139 let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
140 ecx.write_scalar(argc, argc_place.into())?;
141 ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
144 // FIXME: extract main source file path.
145 // Third argument (`argv`): created from `config.args`.
146 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
147 // For Windows, construct a command string with all the aguments.
148 let mut cmd = String::new();
149 for arg in config.args.iter() {
153 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
155 // Don't forget `0` terminator.
156 cmd.push(std::char::from_u32(0).unwrap());
157 // Collect the pointers to the individual strings.
158 let mut argvs = Vec::<Pointer<Borrow>>::new();
159 for arg in config.args {
160 // Add `0` terminator.
161 let mut arg = arg.into_bytes();
163 argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice()).with_default_tag());
165 // Make an array with all these pointers, in the Miri memory.
166 let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
167 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
168 for (idx, arg) in argvs.into_iter().enumerate() {
169 let place = ecx.mplace_field(argvs_place, idx as u64)?;
170 ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
172 ecx.memory_mut().mark_immutable(argvs_place.to_ptr()?.alloc_id)?;
173 // Write a pointer to that place as the argument.
174 let argv = argvs_place.ptr;
175 ecx.write_scalar(argv, dest)?;
176 // Store `argv` for macOS `_NSGetArgv`.
178 let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
179 ecx.write_scalar(argv, argv_place.into())?;
180 ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
182 // Store command line as UTF-16 for Windows `GetCommandLineW`.
184 let tcx = &{ecx.tcx.tcx};
185 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
186 let cmd_ptr = ecx.memory_mut().allocate(
187 Size::from_bytes(cmd_utf16.len() as u64 * 2),
188 Align::from_bytes(2).unwrap(),
189 MiriMemoryKind::Env.into(),
190 ).with_default_tag();
191 ecx.machine.cmd_line = Some(cmd_ptr);
192 // Store the UTF-16 string.
193 let char_size = Size::from_bytes(2);
194 let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
195 let mut cur_ptr = cmd_ptr;
196 for &c in cmd_utf16.iter() {
197 cmd_alloc.write_scalar(
200 Scalar::from_uint(c, char_size).into(),
203 cur_ptr = cur_ptr.offset(char_size, tcx)?;
207 assert!(args.next().is_none(), "start lang item has more arguments than expected");
212 pub fn eval_main<'a, 'tcx: 'a>(
213 tcx: TyCtxt<'a, 'tcx, 'tcx>,
217 let mut ecx = create_ecx(tcx, main_id, config).expect("couldn't create ecx");
219 // Perform the main execution.
220 let res: EvalResult = (|| {
225 // Process the result.
228 let leaks = ecx.memory().leak_report();
229 // Disable the leak test on some platforms where we do not
230 // correctly implement TLS destructors.
231 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
232 let ignore_leaks = target_os == "windows" || target_os == "macos";
233 if !ignore_leaks && leaks != 0 {
234 tcx.sess.err("the evaluated program leaked memory");
239 if let Some(frame) = ecx.stack().last() {
240 let block = &frame.mir.basic_blocks()[frame.block];
241 let span = if frame.stmt < block.statements.len() {
242 block.statements[frame.stmt].source_info.span
244 block.terminator().source_info.span
247 let e = e.to_string();
248 let msg = format!("constant evaluation error: {}", e);
249 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
250 let frames = ecx.generate_stacktrace(None);
251 err.span_label(span, e);
252 // We iterate with indices because we need to look at the next frame (the caller).
253 for idx in 0..frames.len() {
254 let frame_info = &frames[idx];
255 let call_site_is_local = frames.get(idx+1).map_or(false,
256 |caller_info| caller_info.instance.def_id().is_local());
257 if call_site_is_local {
258 err.span_note(frame_info.call_site, &frame_info.to_string());
260 err.note(&frame_info.to_string());
265 ecx.tcx.sess.err(&e.to_string());
268 for (i, frame) in ecx.stack().iter().enumerate() {
269 trace!("-------------------");
270 trace!("Frame {}", i);
271 trace!(" return: {:#?}", frame.return_place);
272 for (i, local) in frame.locals.iter().enumerate() {
273 trace!(" local {}: {:?}", i, local.value);
280 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
281 pub enum MiriMemoryKind {
282 /// `__rust_alloc` memory.
286 /// Part of env var emulation.
292 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
294 fn into(self) -> MemoryKind<MiriMemoryKind> {
295 MemoryKind::Machine(self)
299 impl MayLeak for MiriMemoryKind {
301 fn may_leak(self) -> bool {
302 use self::MiriMemoryKind::*;
305 Env | MutStatic => true,
310 pub struct Evaluator<'tcx> {
311 /// Environment variables set by `setenv`.
312 /// Miri does not expose env vars from the host to the emulated program.
313 pub(crate) env_vars: HashMap<Vec<u8>, Pointer<Borrow>>,
315 /// Program arguments (`Option` because we can only initialize them after creating the ecx).
316 /// These are *pointers* to argc/argv because macOS.
317 /// We also need the full command line as one string because of Windows.
318 pub(crate) argc: Option<Pointer<Borrow>>,
319 pub(crate) argv: Option<Pointer<Borrow>>,
320 pub(crate) cmd_line: Option<Pointer<Borrow>>,
323 pub(crate) last_error: u32,
326 pub(crate) tls: TlsData<'tcx>,
328 /// Whether to enforce the validity invariant.
329 pub(crate) validate: bool,
331 /// Stacked Borrows state.
332 pub(crate) stacked_borrows: stacked_borrows::State,
334 /// The random number generator to use if Miri
335 /// is running in non-deterministic mode
336 pub(crate) rng: Option<StdRng>
339 impl<'tcx> Evaluator<'tcx> {
340 fn new(validate: bool, seed: Option<u64>) -> Self {
342 env_vars: HashMap::default(),
347 tls: TlsData::default(),
349 stacked_borrows: stacked_borrows::State::default(),
350 rng: seed.map(|s| StdRng::seed_from_u64(s))
355 // FIXME: rustc issue <https://github.com/rust-lang/rust/issues/47131>.
357 type MiriEvalContext<'a, 'mir, 'tcx> = InterpretCx<'a, 'mir, 'tcx, Evaluator<'tcx>>;
359 // A little trait that's useful to be inherited by extension traits.
360 pub trait MiriEvalContextExt<'a, 'mir, 'tcx> {
361 fn eval_context_ref(&self) -> &MiriEvalContext<'a, 'mir, 'tcx>;
362 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx>;
364 impl<'a, 'mir, 'tcx> MiriEvalContextExt<'a, 'mir, 'tcx> for MiriEvalContext<'a, 'mir, 'tcx> {
366 fn eval_context_ref(&self) -> &MiriEvalContext<'a, 'mir, 'tcx> {
370 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'a, 'mir, 'tcx> {
375 impl<'a, 'mir, 'tcx> Machine<'a, 'mir, 'tcx> for Evaluator<'tcx> {
376 type MemoryKinds = MiriMemoryKind;
378 type FrameExtra = stacked_borrows::CallId;
379 type MemoryExtra = stacked_borrows::MemoryState;
380 type AllocExtra = stacked_borrows::Stacks;
381 type PointerTag = Borrow;
383 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Borrow, Self::AllocExtra>)>;
385 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::MutStatic);
388 fn enforce_validity(ecx: &InterpretCx<'a, 'mir, 'tcx, Self>) -> bool {
392 /// Returns `Ok()` when the function was handled; fail otherwise.
395 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
396 instance: ty::Instance<'tcx>,
397 args: &[OpTy<'tcx, Borrow>],
398 dest: Option<PlaceTy<'tcx, Borrow>>,
399 ret: Option<mir::BasicBlock>,
400 ) -> EvalResult<'tcx, Option<&'mir mir::Mir<'tcx>>> {
401 ecx.find_fn(instance, args, dest, ret)
406 ecx: &mut rustc_mir::interpret::InterpretCx<'a, 'mir, 'tcx, Self>,
407 instance: ty::Instance<'tcx>,
408 args: &[OpTy<'tcx, Borrow>],
409 dest: PlaceTy<'tcx, Borrow>,
410 ) -> EvalResult<'tcx> {
411 ecx.call_intrinsic(instance, args, dest)
416 ecx: &rustc_mir::interpret::InterpretCx<'a, 'mir, 'tcx, Self>,
418 left: ImmTy<'tcx, Borrow>,
419 right: ImmTy<'tcx, Borrow>,
420 ) -> EvalResult<'tcx, (Scalar<Borrow>, bool)> {
421 ecx.ptr_op(bin_op, left, right)
425 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
426 dest: PlaceTy<'tcx, Borrow>,
427 ) -> EvalResult<'tcx> {
428 trace!("box_alloc for {:?}", dest.layout.ty);
429 // Call the `exchange_malloc` lang item.
430 let malloc = ecx.tcx.lang_items().exchange_malloc_fn().unwrap();
431 let malloc = ty::Instance::mono(ecx.tcx.tcx, malloc);
432 let malloc_mir = ecx.load_mir(malloc.def)?;
433 ecx.push_stack_frame(
438 // Don't do anything when we are done. The `statement()` function will increment
439 // the old stack frame's stmt counter to the next statement, which means that when
440 // `exchange_malloc` returns, we go on evaluating exactly where we want to be.
441 StackPopCleanup::None { cleanup: true },
444 let mut args = ecx.frame().mir.args_iter();
445 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
447 // First argument: `size`.
448 // (`0` is allowed here -- this is expected to be handled by the lang item).
449 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
450 let size = layout.size.bytes();
451 ecx.write_scalar(Scalar::from_uint(size, arg.layout.size), arg)?;
453 // Second argument: `align`.
454 let arg = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
455 let align = layout.align.abi.bytes();
456 ecx.write_scalar(Scalar::from_uint(align, arg.layout.size), arg)?;
458 // No more arguments.
460 args.next().is_none(),
461 "`exchange_malloc` lang item has more arguments than expected"
466 fn find_foreign_static(
468 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
469 memory_extra: &Self::MemoryExtra,
470 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<Borrow, Self::AllocExtra>>> {
471 let attrs = tcx.get_attrs(def_id);
472 let link_name = match attr::first_attr_value_str_by_name(&attrs, "link_name") {
473 Some(name) => name.as_str(),
474 None => tcx.item_name(def_id).as_str(),
477 let alloc = match link_name.get() {
478 "__cxa_thread_atexit_impl" => {
479 // This should be all-zero, pointer-sized.
480 let size = tcx.data_layout.pointer_size;
481 let data = vec![0; size.bytes() as usize];
482 let extra = AllocationExtra::memory_allocated(size, memory_extra);
483 Allocation::from_bytes(&data, tcx.data_layout.pointer_align.abi, extra)
485 _ => return err!(Unimplemented(
486 format!("can't access foreign static: {}", link_name),
489 Ok(Cow::Owned(alloc))
493 fn before_terminator(_ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>) -> EvalResult<'tcx>
495 // We are not interested in detecting loops.
499 fn adjust_static_allocation<'b>(
500 alloc: &'b Allocation,
501 memory_extra: &Self::MemoryExtra,
502 ) -> Cow<'b, Allocation<Borrow, Self::AllocExtra>> {
503 let extra = AllocationExtra::memory_allocated(
504 Size::from_bytes(alloc.bytes.len() as u64),
507 let alloc: Allocation<Borrow, Self::AllocExtra> = Allocation {
508 bytes: alloc.bytes.clone(),
509 relocations: Relocations::from_presorted(
510 alloc.relocations.iter()
511 .map(|&(offset, ((), alloc))| (offset, (Borrow::default(), alloc)))
514 undef_mask: alloc.undef_mask.clone(),
516 mutability: alloc.mutability,
523 ecx: &InterpretCx<'a, 'mir, 'tcx, Self>,
524 place: MPlaceTy<'tcx, Borrow>,
525 mutability: Option<hir::Mutability>,
526 ) -> EvalResult<'tcx, Scalar<Borrow>> {
527 let size = ecx.size_and_align_of_mplace(place)?.map(|(size, _)| size)
528 // For extern types, just cover what we can.
529 .unwrap_or_else(|| place.layout.size);
530 if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag ||
531 !Self::enforce_validity(ecx) || size == Size::ZERO
536 ecx.ptr_dereference(place, size, mutability.into())?;
537 // We never change the pointer.
543 fn tag_new_allocation(
544 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
546 kind: MemoryKind<Self::MemoryKinds>,
547 ) -> Pointer<Borrow> {
548 if !ecx.machine.validate {
550 ptr.with_default_tag()
552 let tag = ecx.tag_new_allocation(ptr.alloc_id, kind);
553 Pointer::new_with_tag(ptr.alloc_id, ptr.offset, tag)
559 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
560 kind: mir::RetagKind,
561 place: PlaceTy<'tcx, Borrow>,
562 ) -> EvalResult<'tcx> {
563 if !ecx.tcx.sess.opts.debugging_opts.mir_emit_retag || !Self::enforce_validity(ecx) {
564 // No tracking, or no retagging. The latter is possible because a dependency of ours
565 // might be called with different flags than we are, so there are `Retag`
566 // statements but we do not want to execute them.
567 // Also, honor the whitelist in `enforce_validity` because otherwise we might retag
568 // uninitialized data.
571 ecx.retag(kind, place)
577 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
578 ) -> EvalResult<'tcx, stacked_borrows::CallId> {
579 Ok(ecx.memory().extra.borrow_mut().new_call())
584 ecx: &mut InterpretCx<'a, 'mir, 'tcx, Self>,
585 extra: stacked_borrows::CallId,
586 ) -> EvalResult<'tcx> {
587 Ok(ecx.memory().extra.borrow_mut().end_call(extra))