1 //! Main evaluator loop and setting up the initial stack frame.
3 use rand::rngs::StdRng;
6 use syntax::source_map::DUMMY_SP;
7 use rustc::ty::{self, TyCtxt};
8 use rustc::ty::layout::{LayoutOf, Size, Align};
9 use rustc::hir::def_id::DefId;
13 InterpResult, InterpError, InterpCx, StackPopCleanup, struct_error,
14 Scalar, Tag, Pointer, FnVal,
15 MemoryExtra, MiriMemoryKind, Evaluator, TlsEvalContextExt,
18 /// Configuration needed to spawn a Miri instance.
20 pub struct MiriConfig {
22 pub args: Vec<String>,
24 // The seed to use when non-determinism is required (e.g. getrandom())
29 pub fn create_ecx<'mir, 'tcx: 'mir>(
33 ) -> InterpResult<'tcx, InterpCx<'mir, 'tcx, Evaluator<'tcx>>> {
35 // FIXME(https://github.com/rust-lang/miri/pull/803): no validation on Windows.
36 let target_os = tcx.sess.target.target.target_os.to_lowercase();
37 let validate = if target_os == "windows" {
43 let mut ecx = InterpCx::new(
44 tcx.at(syntax::source_map::DUMMY_SP),
45 ty::ParamEnv::reveal_all(),
47 MemoryExtra::new(config.seed.map(StdRng::seed_from_u64), validate),
50 let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
51 let main_mir = ecx.load_mir(main_instance.def)?;
53 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
54 return err!(Unimplemented(
55 "miri does not support main functions without `fn()` type signatures"
60 let start_id = tcx.lang_items().start_fn().unwrap();
61 let main_ret_ty = tcx.fn_sig(main_id).output();
62 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
63 let start_instance = ty::Instance::resolve(
65 ty::ParamEnv::reveal_all(),
68 ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
70 let start_mir = ecx.load_mir(start_instance.def)?;
72 if start_mir.arg_count != 3 {
73 return err!(AbiViolation(format!(
74 "'start' lang item should have three arguments, but has {}",
79 // Return value (in static memory so that it does not count as leak).
80 let ret = ecx.layout_of(start_mir.return_ty())?;
81 let ret_ptr = ecx.allocate(ret, MiriMemoryKind::Static.into());
83 // Push our stack frame.
86 // There is no call site.
90 StackPopCleanup::None { cleanup: true },
93 let mut args = ecx.frame().body.args_iter();
95 // First argument: pointer to `main()`.
96 let main_ptr = ecx.memory_mut().create_fn_alloc(FnVal::Instance(main_instance));
97 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
98 ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
100 // Second argument (argc): `1`.
101 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
102 let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
103 ecx.write_scalar(argc, dest)?;
104 // Store argc for macOS's `_NSGetArgc`.
106 let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
107 ecx.write_scalar(argc, argc_place.into())?;
108 ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
111 // FIXME: extract main source file path.
112 // Third argument (`argv`): created from `config.args`.
113 let dest = ecx.eval_place(&mir::Place::Base(mir::PlaceBase::Local(args.next().unwrap())))?;
114 // For Windows, construct a command string with all the aguments.
115 let mut cmd = String::new();
116 for arg in config.args.iter() {
120 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
122 // Don't forget `0` terminator.
123 cmd.push(std::char::from_u32(0).unwrap());
124 // Collect the pointers to the individual strings.
125 let mut argvs = Vec::<Pointer<Tag>>::new();
126 for arg in config.args {
127 // Add `0` terminator.
128 let mut arg = arg.into_bytes();
130 argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
132 // Make an array with all these pointers, in the Miri memory.
133 let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
134 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
135 for (idx, arg) in argvs.into_iter().enumerate() {
136 let place = ecx.mplace_field(argvs_place, idx as u64)?;
137 ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
139 ecx.memory_mut().mark_immutable(argvs_place.to_ptr()?.alloc_id)?;
140 // Write a pointer to that place as the argument.
141 let argv = argvs_place.ptr;
142 ecx.write_scalar(argv, dest)?;
143 // Store `argv` for macOS `_NSGetArgv`.
145 let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
146 ecx.write_scalar(argv, argv_place.into())?;
147 ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
149 // Store command line as UTF-16 for Windows `GetCommandLineW`.
151 let tcx = &{ecx.tcx.tcx};
152 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
153 let cmd_ptr = ecx.memory_mut().allocate(
154 Size::from_bytes(cmd_utf16.len() as u64 * 2),
155 Align::from_bytes(2).unwrap(),
156 MiriMemoryKind::Env.into(),
158 ecx.machine.cmd_line = Some(cmd_ptr);
159 // Store the UTF-16 string.
160 let char_size = Size::from_bytes(2);
161 let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
162 let mut cur_ptr = cmd_ptr;
163 for &c in cmd_utf16.iter() {
164 cmd_alloc.write_scalar(
167 Scalar::from_uint(c, char_size).into(),
170 cur_ptr = cur_ptr.offset(char_size, tcx)?;
174 assert!(args.next().is_none(), "start lang item has more arguments than expected");
179 pub fn eval_main<'tcx>(
184 let mut ecx = match create_ecx(tcx, main_id, config) {
187 err.print_backtrace();
188 panic!("Miri initialziation error: {}", err.kind)
192 // Perform the main execution.
193 let res: InterpResult = (|| {
198 // Process the result.
201 let leaks = ecx.memory().leak_report();
202 // Disable the leak test on some platforms where we do not
203 // correctly implement TLS destructors.
204 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
205 let ignore_leaks = target_os == "windows" || target_os == "macos";
206 if !ignore_leaks && leaks != 0 {
207 tcx.sess.err("the evaluated program leaked memory");
211 // Special treatment for some error kinds
212 let msg = match e.kind {
213 InterpError::Exit(code) => std::process::exit(code),
214 InterpError::NoMirFor(..) =>
215 format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
219 if let Some(frame) = ecx.stack().last() {
220 let block = &frame.body.basic_blocks()[frame.block];
221 let span = if frame.stmt < block.statements.len() {
222 block.statements[frame.stmt].source_info.span
224 block.terminator().source_info.span
227 let msg = format!("Miri evaluation error: {}", msg);
228 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
229 let frames = ecx.generate_stacktrace(None);
230 err.span_label(span, msg);
231 // We iterate with indices because we need to look at the next frame (the caller).
232 for idx in 0..frames.len() {
233 let frame_info = &frames[idx];
234 let call_site_is_local = frames.get(idx+1).map_or(false,
235 |caller_info| caller_info.instance.def_id().is_local());
236 if call_site_is_local {
237 err.span_note(frame_info.call_site, &frame_info.to_string());
239 err.note(&frame_info.to_string());
244 ecx.tcx.sess.err(&msg);
247 for (i, frame) in ecx.stack().iter().enumerate() {
248 trace!("-------------------");
249 trace!("Frame {}", i);
250 trace!(" return: {:?}", frame.return_place.map(|p| *p));
251 for (i, local) in frame.locals.iter().enumerate() {
252 trace!(" local {}: {:?}", i, local.value);