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;
12 InterpResult, InterpError, InterpCx, StackPopCleanup, struct_error,
13 Scalar, Tag, Pointer, FnVal,
14 MemoryExtra, MiriMemoryKind, Evaluator, TlsEvalContextExt, HelpersEvalContextExt,
18 /// Configuration needed to spawn a Miri instance.
20 pub struct MiriConfig {
21 /// Determine if validity checking and Stacked Borrows are enabled.
23 /// Determines if communication with the host environment is enabled.
24 pub communicate: bool,
25 pub args: Vec<String>,
26 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
27 pub seed: Option<u64>,
31 pub fn create_ecx<'mir, 'tcx: 'mir>(
35 ) -> InterpResult<'tcx, InterpCx<'mir, 'tcx, Evaluator<'tcx>>> {
36 let mut ecx = InterpCx::new(
37 tcx.at(syntax::source_map::DUMMY_SP),
38 ty::ParamEnv::reveal_all(),
39 Evaluator::new(config.communicate),
40 MemoryExtra::new(StdRng::seed_from_u64(config.seed.unwrap_or(0)), config.validate),
43 ShimsEnvVars::init(config.communicate, &mut ecx, &tcx);
45 let main_instance = ty::Instance::mono(ecx.tcx.tcx, main_id);
46 let main_mir = ecx.load_mir(main_instance.def)?;
48 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
50 "miri does not support main functions without `fn()` type signatures"
54 let start_id = tcx.lang_items().start_fn().unwrap();
55 let main_ret_ty = tcx.fn_sig(main_id).output();
56 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
57 let start_instance = ty::Instance::resolve(
59 ty::ParamEnv::reveal_all(),
62 ::std::iter::once(ty::subst::Kind::from(main_ret_ty)))
64 let start_mir = ecx.load_mir(start_instance.def)?;
66 if start_mir.arg_count != 3 {
68 "'start' lang item should have three arguments, but has {}",
73 // Return value (in static memory so that it does not count as leak).
74 let ret = ecx.layout_of(start_mir.return_ty())?;
75 let ret_ptr = ecx.allocate(ret, MiriMemoryKind::Static.into());
77 // Push our stack frame.
80 // There is no call site.
84 StackPopCleanup::None { cleanup: true },
87 let mut args = ecx.frame().body.args_iter();
89 // First argument: pointer to `main()`.
90 let main_ptr = ecx.memory_mut().create_fn_alloc(FnVal::Instance(main_instance));
91 let dest = ecx.local_place(args.next().unwrap())?;
92 ecx.write_scalar(Scalar::Ptr(main_ptr), dest)?;
94 // Second argument (argc): `1`.
95 let dest = ecx.local_place(args.next().unwrap())?;
96 let argc = Scalar::from_uint(config.args.len() as u128, dest.layout.size);
97 ecx.write_scalar(argc, dest)?;
98 // Store argc for macOS's `_NSGetArgc`.
100 let argc_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
101 ecx.write_scalar(argc, argc_place.into())?;
102 ecx.machine.argc = Some(argc_place.ptr.to_ptr()?);
105 // Third argument (`argv`): created from `config.args`.
106 let dest = ecx.local_place(args.next().unwrap())?;
107 // For Windows, construct a command string with all the aguments.
108 let mut cmd = String::new();
109 for arg in config.args.iter() {
113 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
115 // Don't forget `0` terminator.
116 cmd.push(std::char::from_u32(0).unwrap());
117 // Collect the pointers to the individual strings.
118 let mut argvs = Vec::<Pointer<Tag>>::new();
119 for arg in config.args {
120 // Add `0` terminator.
121 let mut arg = arg.into_bytes();
123 argvs.push(ecx.memory_mut().allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()));
125 // Make an array with all these pointers, in the Miri memory.
126 let argvs_layout = ecx.layout_of(ecx.tcx.mk_array(ecx.tcx.mk_imm_ptr(ecx.tcx.types.u8), argvs.len() as u64))?;
127 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
128 for (idx, arg) in argvs.into_iter().enumerate() {
129 let place = ecx.mplace_field(argvs_place, idx as u64)?;
130 ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
132 ecx.memory_mut().mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
133 // Write a pointer to that place as the argument.
134 let argv = argvs_place.ptr;
135 ecx.write_scalar(argv, dest)?;
136 // Store `argv` for macOS `_NSGetArgv`.
138 let argv_place = ecx.allocate(dest.layout, MiriMemoryKind::Env.into());
139 ecx.write_scalar(argv, argv_place.into())?;
140 ecx.machine.argv = Some(argv_place.ptr.to_ptr()?);
142 // Store command line as UTF-16 for Windows `GetCommandLineW`.
144 let tcx = &{ecx.tcx.tcx};
145 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
146 let cmd_ptr = ecx.memory_mut().allocate(
147 Size::from_bytes(cmd_utf16.len() as u64 * 2),
148 Align::from_bytes(2).unwrap(),
149 MiriMemoryKind::Env.into(),
151 ecx.machine.cmd_line = Some(cmd_ptr);
152 // Store the UTF-16 string.
153 let char_size = Size::from_bytes(2);
154 let cmd_alloc = ecx.memory_mut().get_mut(cmd_ptr.alloc_id)?;
155 let mut cur_ptr = cmd_ptr;
156 for &c in cmd_utf16.iter() {
157 cmd_alloc.write_scalar(
160 Scalar::from_uint(c, char_size).into(),
163 cur_ptr = cur_ptr.offset(char_size, tcx)?;
167 assert!(args.next().is_none(), "start lang item has more arguments than expected");
172 pub fn eval_main<'tcx>(
177 let mut ecx = match create_ecx(tcx, main_id, config) {
180 err.print_backtrace();
181 panic!("Miri initialziation error: {}", err.kind)
185 // Perform the main execution.
186 let res: InterpResult<'_> = (|| {
191 // Process the result.
194 let leaks = ecx.memory().leak_report();
195 // Disable the leak test on some platforms where we do not
196 // correctly implement TLS destructors.
197 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
198 let ignore_leaks = target_os == "windows" || target_os == "macos";
199 if !ignore_leaks && leaks != 0 {
200 tcx.sess.err("the evaluated program leaked memory");
204 // Special treatment for some error kinds
205 let msg = match e.kind {
206 InterpError::Exit(code) => std::process::exit(code),
207 err_unsup!(NoMirFor(..)) =>
208 format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
212 if let Some(frame) = ecx.stack().last() {
213 let block = &frame.body.basic_blocks()[frame.block];
214 let span = if frame.stmt < block.statements.len() {
215 block.statements[frame.stmt].source_info.span
217 block.terminator().source_info.span
220 let msg = format!("Miri evaluation error: {}", msg);
221 let mut err = struct_error(ecx.tcx.tcx.at(span), msg.as_str());
222 let frames = ecx.generate_stacktrace(None);
223 err.span_label(span, msg);
224 // We iterate with indices because we need to look at the next frame (the caller).
225 for idx in 0..frames.len() {
226 let frame_info = &frames[idx];
227 let call_site_is_local = frames.get(idx+1).map_or(false,
228 |caller_info| caller_info.instance.def_id().is_local());
229 if call_site_is_local {
230 err.span_note(frame_info.call_site, &frame_info.to_string());
232 err.note(&frame_info.to_string());
237 ecx.tcx.sess.err(&msg);
240 for (i, frame) in ecx.stack().iter().enumerate() {
241 trace!("-------------------");
242 trace!("Frame {}", i);
243 trace!(" return: {:?}", frame.return_place.map(|p| *p));
244 for (i, local) in frame.locals.iter().enumerate() {
245 trace!(" local {}: {:?}", i, local.value);