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 /// Details of premature program termination.
28 pub enum TerminationInfo {
33 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
34 /// the location where the return value of the `start` lang item will be
36 /// Public because this is also used by `priroda`.
37 pub fn create_ecx<'mir, 'tcx: 'mir>(
41 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
42 let mut ecx = InterpCx::new(
43 tcx.at(syntax::source_map::DUMMY_SP),
44 ty::ParamEnv::reveal_all(),
45 Evaluator::new(config.communicate),
46 MemoryExtra::new(StdRng::seed_from_u64(config.seed.unwrap_or(0)), config.validate),
48 // Complete initialization.
49 EnvVars::init(&mut ecx, config.excluded_env_vars);
51 // Setup first stack-frame
52 let main_instance = ty::Instance::mono(tcx, main_id);
53 let main_mir = ecx.load_mir(main_instance.def, None)?;
55 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
56 throw_unsup_format!("miri does not support main functions without `fn()` type signatures");
59 let start_id = tcx.lang_items().start_fn().unwrap();
60 let main_ret_ty = tcx.fn_sig(main_id).output();
61 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
62 let start_instance = ty::Instance::resolve(
64 ty::ParamEnv::reveal_all(),
66 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
70 // First argument: pointer to `main()`.
73 .create_fn_alloc(FnVal::Instance(main_instance));
74 // Second argument (argc): length of `config.args`.
75 let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
76 // Third argument (`argv`): created from `config.args`.
78 // For Windows, construct a command string with all the aguments (before we take apart `config.args`).
79 let mut cmd = String::new();
80 for arg in config.args.iter() {
84 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
86 // Don't forget `0` terminator.
87 cmd.push(std::char::from_u32(0).unwrap());
88 // Collect the pointers to the individual strings.
89 let mut argvs = Vec::<Pointer<Tag>>::new();
90 for arg in config.args {
91 // Add `0` terminator.
92 let mut arg = arg.into_bytes();
96 .allocate_static_bytes(arg.as_slice(), MiriMemoryKind::Static.into()),
99 // Make an array with all these pointers, in the Miri memory.
100 let argvs_layout = ecx.layout_of(
101 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64),
103 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
104 for (idx, arg) in argvs.into_iter().enumerate() {
105 let place = ecx.mplace_field(argvs_place, idx as u64)?;
106 ecx.write_scalar(Scalar::Ptr(arg), place.into())?;
109 .mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
110 // A pointer to that place is the argument.
111 let argv = argvs_place.ptr;
112 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
114 let argc_place = ecx.allocate(
115 ecx.layout_of(tcx.types.isize)?,
116 MiriMemoryKind::Env.into(),
118 ecx.write_scalar(argc, argc_place.into())?;
119 ecx.machine.argc = Some(argc_place.ptr);
121 let argv_place = ecx.allocate(
122 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
123 MiriMemoryKind::Env.into(),
125 ecx.write_scalar(argv, argv_place.into())?;
126 ecx.machine.argv = Some(argv_place.ptr);
128 // Store command line as UTF-16 for Windows `GetCommandLineW`.
130 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
131 let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
132 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
133 ecx.machine.cmd_line = Some(cmd_place.ptr);
134 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
135 let char_size = Size::from_bytes(2);
136 for (idx, &c) in cmd_utf16.iter().enumerate() {
137 let place = ecx.mplace_field(cmd_place, idx as u64)?;
138 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
144 // Return place (in static memory so that it does not count as leak).
145 let ret_place = ecx.allocate(
146 ecx.layout_of(tcx.types.isize)?,
147 MiriMemoryKind::Static.into(),
149 // Call start function.
152 &[main_ptr.into(), argc, argv],
153 Some(ret_place.into()),
154 StackPopCleanup::None { cleanup: true },
157 // Set the last_error to 0
158 let errno_layout = ecx.layout_of(tcx.types.u32)?;
159 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Static.into());
160 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
161 ecx.machine.last_error = Some(errno_place);
166 /// Evaluates the main function specified by `main_id`.
167 /// Returns `Some(return_code)` if program executed completed.
168 /// Returns `None` if an evaluation error occured.
169 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
170 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
173 err.print_backtrace();
174 panic!("Miri initialziation error: {}", err.kind)
178 // Perform the main execution.
179 let res: InterpResult<'_, i64> = (|| {
181 // Read the return code pointer *before* we run TLS destructors, to assert
182 // that it was written to by the time that `start` lang item returned.
183 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
184 ecx.run_tls_dtors()?;
188 // Process the result.
191 // Disable the leak test on some platforms where we do not
192 // correctly implement TLS destructors.
193 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
194 let ignore_leaks = target_os == "windows" || target_os == "macos";
196 let leaks = ecx.memory.leak_report();
198 tcx.sess.err("the evaluated program leaked memory");
199 // Ignore the provided return code - let the reported error
200 // determine the return code.
204 return Some(return_code)
207 // Special treatment for some error kinds
208 let msg = match e.kind {
209 InterpError::MachineStop(ref info) => {
210 let info = info.downcast_ref::<TerminationInfo>()
211 .expect("invalid MachineStop payload");
213 TerminationInfo::Exit(code) => return Some(*code),
214 TerminationInfo::Abort =>
215 format!("the evaluated program aborted execution")
218 err_unsup!(NoMirFor(..)) =>
219 format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
223 if let Some(frame) = ecx.stack().last() {
224 let block = &frame.body.basic_blocks()[frame.block.unwrap()];
225 let span = if frame.stmt < block.statements.len() {
226 block.statements[frame.stmt].source_info.span
228 block.terminator().source_info.span
231 let msg = format!("Miri evaluation error: {}", msg);
232 let mut err = ecx.tcx.sess.struct_span_err(span, msg.as_str());
233 let frames = ecx.generate_stacktrace(None);
234 err.span_label(span, msg);
235 // We iterate with indices because we need to look at the next frame (the caller).
236 for idx in 0..frames.len() {
237 let frame_info = &frames[idx];
238 let call_site_is_local = frames.get(idx + 1).map_or(false, |caller_info| {
239 caller_info.instance.def_id().is_local()
241 if call_site_is_local {
242 err.span_note(frame_info.call_site, &frame_info.to_string());
244 err.note(&frame_info.to_string());
249 ecx.tcx.sess.err(&msg);
252 for (i, frame) in ecx.stack().iter().enumerate() {
253 trace!("-------------------");
254 trace!("Frame {}", i);
255 trace!(" return: {:?}", frame.return_place.map(|p| *p));
256 for (i, local) in frame.locals.iter().enumerate() {
257 trace!(" local {}: {:?}", i, local.value);
260 // Let the reported error determine the return code.