1 #![feature(rustc_private)]
3 #![allow(clippy::cast_lossless)]
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;
24 use std::collections::HashMap;
28 use rand::rngs::StdRng;
29 use rand::SeedableRng;
31 use rustc::ty::{self, TyCtxt, query::TyCtxtAt};
32 use rustc::ty::layout::{LayoutOf, Size, Align};
33 use rustc::hir::def_id::DefId;
35 pub use rustc_mir::interpret::*;
37 pub use rustc_mir::interpret::{self, AllocMap, PlaceTy};
39 use syntax::source_map::DUMMY_SP;
40 use syntax::symbol::sym;
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};
53 pub use crate::stacked_borrows::{Tag, Permission, Stack, Stacks, Item};
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"]
63 /// Configuration needed to spawn a Miri instance.
65 pub struct MiriConfig {
67 pub args: Vec<String>,
69 // The seed to use when non-determinism is required (e.g. getrandom())
74 pub fn create_ecx<'mir, 'tcx: 'mir>(
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),
85 let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
86 let main_mir = ecx.load_mir(main_instance.def)?;
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"
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(
100 ty::ParamEnv::reveal_all(),
103 ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
105 let start_mir = ecx.load_mir(start_instance.def)?;
107 if start_mir.arg_count != 3 {
108 return err!(AbiViolation(format!(
109 "'start' lang item should have three arguments, but has {}",
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());
118 // Push our stack frame.
119 ecx.push_stack_frame(
121 // There is no call site.
124 Some(ret_ptr.into()),
125 StackPopCleanup::None { cleanup: true },
128 let mut args = ecx.frame().body.args_iter();
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)?;
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`.
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()?);
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() {
155 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
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();
165 argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
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())?;
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`.
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()?);
184 // Store command line as UTF-16 for Windows `GetCommandLineW`.
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(),
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(
202 Scalar::from_uint(c, char_size).into(),
205 cur_ptr = cur_ptr.offset(char_size, tcx)?;
209 assert!(args.next().is_none(), "start lang item has more arguments than expected");
214 pub fn eval_main<'tcx>(
219 let mut ecx = match create_ecx(tcx, main_id, config) {
222 err.print_backtrace();
223 panic!("Miri initialziation error: {}", err.kind)
227 // Perform the main execution.
228 let res: InterpResult = (|| {
233 // Process the result.
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");
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),
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
259 block.terminator().source_info.span
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());
274 err.note(&frame_info.to_string());
279 ecx.tcx.sess.err(&msg);
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);
294 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
295 pub enum MiriMemoryKind {
296 /// `__rust_alloc` memory.
300 /// Part of env var emulation.
306 impl Into<MemoryKind<MiriMemoryKind>> for MiriMemoryKind {
308 fn into(self) -> MemoryKind<MiriMemoryKind> {
309 MemoryKind::Machine(self)
313 impl MayLeak for MiriMemoryKind {
315 fn may_leak(self) -> bool {
316 use self::MiriMemoryKind::*;
319 Env | Static => true,
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>>,
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>>,
337 pub(crate) last_error: u32,
340 pub(crate) tls: TlsData<'tcx>,
342 /// Whether to enforce the validity invariant.
343 pub(crate) validate: bool,
345 /// The random number generator to use if Miri
346 /// is running in non-deterministic mode
347 pub(crate) rng: Option<StdRng>
350 impl<'tcx> Evaluator<'tcx> {
351 fn new(validate: bool, seed: Option<u64>) -> Self {
353 env_vars: HashMap::default(),
358 tls: TlsData::default(),
360 rng: seed.map(|s| StdRng::seed_from_u64(s))
365 // FIXME: rustc issue <https://github.com/rust-lang/rust/issues/47131>.
367 type MiriEvalContext<'mir, 'tcx> = InterpretCx<'mir, 'tcx, Evaluator<'tcx>>;
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>;
374 impl<'mir, 'tcx> MiriEvalContextExt<'mir, 'tcx> for MiriEvalContext<'mir, 'tcx> {
376 fn eval_context_ref(&self) -> &MiriEvalContext<'mir, 'tcx> {
380 fn eval_context_mut(&mut self) -> &mut MiriEvalContext<'mir, 'tcx> {
385 impl<'mir, 'tcx> Machine<'mir, 'tcx> for Evaluator<'tcx> {
386 type MemoryKinds = MiriMemoryKind;
388 type FrameExtra = stacked_borrows::CallId;
389 type MemoryExtra = stacked_borrows::MemoryState;
390 type AllocExtra = stacked_borrows::Stacks;
391 type PointerTag = Tag;
393 type MemoryMap = MonoHashMap<AllocId, (MemoryKind<MiriMemoryKind>, Allocation<Tag, Self::AllocExtra>)>;
395 const STATIC_KIND: Option<MiriMemoryKind> = Some(MiriMemoryKind::Static);
398 fn enforce_validity(ecx: &InterpretCx<'mir, 'tcx, Self>) -> bool {
402 /// Returns `Ok()` when the function was handled; fail otherwise.
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)
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)
426 ecx: &rustc_mir::interpret::InterpretCx<'mir, 'tcx, Self>,
428 left: ImmTy<'tcx, Tag>,
429 right: ImmTy<'tcx, Tag>,
430 ) -> InterpResult<'tcx, (Scalar<Tag>, bool)> {
431 ecx.ptr_op(bin_op, left, right)
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(
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 },
454 let mut args = ecx.frame().body.args_iter();
455 let layout = ecx.layout_of(dest.layout.ty.builtin_deref(false).unwrap().ty)?;
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)?;
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)?;
468 // No more arguments.
470 args.next().is_none(),
471 "`exchange_malloc` lang item has more arguments than expected"
476 fn find_foreign_static(
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(),
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)
493 _ => return err!(Unimplemented(
494 format!("can't access foreign static: {}", link_name),
497 Ok(Cow::Owned(alloc))
501 fn before_terminator(_ecx: &mut InterpretCx<'mir, 'tcx, Self>) -> InterpResult<'tcx>
503 // We are not interested in detecting loops.
507 fn tag_allocation<'b>(
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(
517 Size::from_bytes(alloc.bytes.len() as u64),
518 Rc::clone(&memory.extra),
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.
525 let mut memory_extra = memory.extra.borrow_mut();
526 let alloc: Allocation<Tag, Self::AllocExtra> = Allocation {
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)))
535 undef_mask: alloc.undef_mask,
537 mutability: alloc.mutability,
540 (Cow::Owned(alloc), base_tag)
544 fn tag_static_base_pointer(
546 memory: &Memory<'mir, 'tcx, Self>,
547 ) -> Self::PointerTag {
548 memory.extra.borrow_mut().static_base_ptr(id)
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.
565 ecx.retag(kind, place)
571 ecx: &mut InterpretCx<'mir, 'tcx, Self>,
572 ) -> InterpResult<'tcx, stacked_borrows::CallId> {
573 Ok(ecx.memory().extra.borrow_mut().new_call())
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))