1 //! Main evaluator loop and setting up the initial stack frame.
3 use rand::rngs::StdRng;
6 use rustc::hir::def_id::DefId;
7 use rustc::ty::layout::{LayoutOf, Size};
8 use rustc::ty::{self, TyCtxt};
12 /// Configuration needed to spawn a Miri instance.
14 pub struct MiriConfig {
15 /// Determine if validity checking and Stacked Borrows are enabled.
17 /// Determines if communication with the host environment is enabled.
18 pub communicate: bool,
19 /// Environment variables that should always be isolated from the host.
20 pub excluded_env_vars: Vec<String>,
21 /// Command-line arguments passed to the interpreted program.
22 pub args: Vec<String>,
23 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
24 pub seed: Option<u64>,
27 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
28 /// the location where the return value of the `start` lang item will be
30 /// Public because this is also used by `priroda`.
31 pub fn create_ecx<'mir, 'tcx: 'mir>(
35 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
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),
42 // Complete initialization.
43 EnvVars::init(&mut ecx, config.excluded_env_vars);
45 // Setup first stack-frame
46 let main_instance = ty::Instance::mono(tcx, main_id);
47 let main_mir = ecx.load_mir(main_instance.def, None)?;
49 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
50 throw_unsup_format!("miri does not support main functions without `fn()` type signatures");
53 let start_id = tcx.lang_items().start_fn().unwrap();
54 let main_ret_ty = tcx.fn_sig(main_id).output();
55 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
56 let start_instance = ty::Instance::resolve(
58 ty::ParamEnv::reveal_all(),
60 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
64 // First argument: pointer to `main()`.
67 .create_fn_alloc(FnVal::Instance(main_instance));
68 // Second argument (argc): length of `config.args`.
69 let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
70 // Third argument (`argv`): created from `config.args`.
72 // For Windows, construct a command string with all the aguments (before we take apart `config.args`).
73 let mut cmd = String::new();
74 for arg in config.args.iter() {
78 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
80 // Don't forget `0` terminator.
81 cmd.push(std::char::from_u32(0).unwrap());
82 // Collect the pointers to the individual strings.
83 let mut argvs = Vec::<Pointer<Tag>>::new();
84 for arg in config.args {
85 // Add `0` terminator.
86 let mut arg = arg.into_bytes();
90 .allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()),
93 // Make an array with all these pointers, in the Miri memory.
94 let argvs_layout = ecx.layout_of(
95 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64),
97 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
98 for (idx, arg) in argvs.into_iter().enumerate() {
99 let place = ecx.mplace_field(argvs_place, idx as u64)?;
100 ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
103 .mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
104 // A pointer to that place is the argument.
105 let argv = argvs_place.ptr;
106 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
108 let argc_place = ecx.allocate(
109 ecx.layout_of(tcx.types.isize)?,
110 MiriMemoryKind::Env.into(),
112 ecx.write_scalar(argc, argc_place.into())?;
113 ecx.machine.argc = Some(argc_place.ptr);
115 let argv_place = ecx.allocate(
116 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
117 MiriMemoryKind::Env.into(),
119 ecx.write_scalar(argv, argv_place.into())?;
120 ecx.machine.argv = Some(argv_place.ptr);
122 // Store command line as UTF-16 for Windows `GetCommandLineW`.
124 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
125 let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
126 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
127 ecx.machine.cmd_line = Some(cmd_place.ptr);
128 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
129 let char_size = Size::from_bytes(2);
130 for (idx, &c) in cmd_utf16.iter().enumerate() {
131 let place = ecx.mplace_field(cmd_place, idx as u64)?;
132 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
138 // Return place (in static memory so that it does not count as leak).
139 let ret_place = ecx.allocate(
140 ecx.layout_of(tcx.types.isize)?,
141 MiriMemoryKind::Static.into(),
143 // Call start function.
146 &[main_ptr.into(), argc, argv],
147 Some(ret_place.into()),
148 StackPopCleanup::None { cleanup: true },
151 // Set the last_error to 0
152 let errno_layout = ecx.layout_of(tcx.types.u32)?;
153 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Static.into());
154 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
155 ecx.machine.last_error = Some(errno_place);
160 /// Evaluates the main function specified by `main_id`.
161 /// Returns `Some(return_code)` if program executed completed.
162 /// Returns `None` if an evaluation error occured.
163 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
164 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
167 err.print_backtrace();
168 panic!("Miri initialziation error: {}", err.kind)
172 // Perform the main execution.
173 let res: InterpResult<'_, i64> = (|| {
175 // Read the return code pointer *before* we run TLS destructors, to assert
176 // that it was written to by the time that `start` lang item returned.
177 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
178 ecx.run_tls_dtors()?;
182 // Process the result.
185 // Disable the leak test on some platforms where we do not
186 // correctly implement TLS destructors.
187 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
188 let ignore_leaks = target_os == "windows" || target_os == "macos";
190 let leaks = ecx.memory.leak_report();
192 tcx.sess.err("the evaluated program leaked memory");
193 // Ignore the provided return code - let the reported error
194 // determine the return code.
198 return Some(return_code)
201 // Special treatment for some error kinds
202 let msg = match e.kind {
203 InterpError::Exit(code) => return Some(code.into()),
204 err_unsup!(NoMirFor(..)) =>
205 format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
209 if let Some(frame) = ecx.stack().last() {
210 let block = &frame.body.basic_blocks()[frame.block.unwrap()];
211 let span = if frame.stmt < block.statements.len() {
212 block.statements[frame.stmt].source_info.span
214 block.terminator().source_info.span
217 let msg = format!("Miri evaluation error: {}", msg);
218 let mut err = ecx.tcx.sess.struct_span_err(span, msg.as_str());
219 let frames = ecx.generate_stacktrace(None);
220 err.span_label(span, msg);
221 // We iterate with indices because we need to look at the next frame (the caller).
222 for idx in 0..frames.len() {
223 let frame_info = &frames[idx];
224 let call_site_is_local = frames.get(idx + 1).map_or(false, |caller_info| {
225 caller_info.instance.def_id().is_local()
227 if call_site_is_local {
228 err.span_note(frame_info.call_site, &frame_info.to_string());
230 err.note(&frame_info.to_string());
235 ecx.tcx.sess.err(&msg);
238 for (i, frame) in ecx.stack().iter().enumerate() {
239 trace!("-------------------");
240 trace!("Frame {}", i);
241 trace!(" return: {:?}", frame.return_place.map(|p| *p));
242 for (i, local) in frame.locals.iter().enumerate() {
243 trace!(" local {}: {:?}", i, local.value);
246 // Let the reported error determine the return code.