1 //! Main evaluator loop and setting up the initial stack frame.
5 use rand::rngs::StdRng;
8 use rustc::hir::def_id::DefId;
9 use rustc::ty::layout::{LayoutOf, Size};
10 use rustc::ty::{self, TyCtxt};
14 /// Configuration needed to spawn a Miri instance.
16 pub struct MiriConfig {
17 /// Determine if validity checking and Stacked Borrows are enabled.
19 /// Determines if communication with the host environment is enabled.
20 pub communicate: bool,
21 /// Environment variables that should always be isolated from the host.
22 pub excluded_env_vars: Vec<String>,
23 /// Command-line arguments passed to the interpreted program.
24 pub args: Vec<String>,
25 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
26 pub seed: Option<u64>,
29 /// Details of premature program termination.
30 pub enum TerminationInfo {
35 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
36 /// the location where the return value of the `start` lang item will be
38 /// Public because this is also used by `priroda`.
39 pub fn create_ecx<'mir, 'tcx: 'mir>(
43 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
44 let mut ecx = InterpCx::new(
45 tcx.at(syntax::source_map::DUMMY_SP),
46 ty::ParamEnv::reveal_all(),
47 Evaluator::new(config.communicate),
48 MemoryExtra::new(StdRng::seed_from_u64(config.seed.unwrap_or(0)), config.validate),
50 // Complete initialization.
51 EnvVars::init(&mut ecx, config.excluded_env_vars);
53 // Setup first stack-frame
54 let main_instance = ty::Instance::mono(tcx, main_id);
55 let main_mir = ecx.load_mir(main_instance.def, None)?;
57 if !main_mir.return_ty().is_unit() || main_mir.arg_count != 0 {
58 throw_unsup_format!("miri does not support main functions without `fn()` type signatures");
61 let start_id = tcx.lang_items().start_fn().unwrap();
62 let main_ret_ty = tcx.fn_sig(main_id).output();
63 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
64 let start_instance = ty::Instance::resolve(
66 ty::ParamEnv::reveal_all(),
68 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
72 // First argument: pointer to `main()`.
75 .create_fn_alloc(FnVal::Instance(main_instance));
76 // Second argument (argc): length of `config.args`.
77 let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
78 // Third argument (`argv`): created from `config.args`.
80 // Put each argument in memory, collect pointers.
81 let mut argvs = Vec::<Scalar<Tag>>::new();
82 for arg in config.args.iter() {
83 // Make space for `0` terminator.
84 let size = arg.len() as u64 + 1;
85 let arg_type = tcx.mk_array(tcx.types.u8, size);
86 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Env.into());
87 ecx.write_os_str_to_c_string(OsStr::new(arg), arg_place.ptr, size)?;
88 argvs.push(arg_place.ptr);
90 // Make an array with all these pointers, in the Miri memory.
91 let argvs_layout = ecx.layout_of(
92 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64),
94 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
95 for (idx, arg) in argvs.into_iter().enumerate() {
96 let place = ecx.mplace_field(argvs_place, idx as u64)?;
97 ecx.write_scalar(arg, place.into())?;
100 .mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
101 // A pointer to that place is the 3rd argument for main.
102 let argv = argvs_place.ptr;
103 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
105 let argc_place = ecx.allocate(
106 ecx.layout_of(tcx.types.isize)?,
107 MiriMemoryKind::Env.into(),
109 ecx.write_scalar(argc, argc_place.into())?;
110 ecx.machine.argc = Some(argc_place.ptr);
112 let argv_place = ecx.allocate(
113 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
114 MiriMemoryKind::Env.into(),
116 ecx.write_scalar(argv, argv_place.into())?;
117 ecx.machine.argv = Some(argv_place.ptr);
119 // Store command line as UTF-16 for Windows `GetCommandLineW`.
121 // Construct a command string with all the aguments.
122 let mut cmd = String::new();
123 for arg in config.args.iter() {
127 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
129 // Don't forget `0` terminator.
130 cmd.push(std::char::from_u32(0).unwrap());
132 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
133 let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
134 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
135 ecx.machine.cmd_line = Some(cmd_place.ptr);
136 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
137 let char_size = Size::from_bytes(2);
138 for (idx, &c) in cmd_utf16.iter().enumerate() {
139 let place = ecx.mplace_field(cmd_place, idx as u64)?;
140 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
146 // Return place (in static memory so that it does not count as leak).
147 let ret_place = ecx.allocate(
148 ecx.layout_of(tcx.types.isize)?,
149 MiriMemoryKind::Env.into(),
151 // Call start function.
154 &[main_ptr.into(), argc.into(), argv.into()],
155 Some(ret_place.into()),
156 StackPopCleanup::None { cleanup: true },
159 // Set the last_error to 0
160 let errno_layout = ecx.layout_of(tcx.types.u32)?;
161 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Env.into());
162 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
163 ecx.machine.last_error = Some(errno_place);
168 /// Evaluates the main function specified by `main_id`.
169 /// Returns `Some(return_code)` if program executed completed.
170 /// Returns `None` if an evaluation error occured.
171 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
172 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
175 err.print_backtrace();
176 panic!("Miri initialziation error: {}", err.kind)
180 // Perform the main execution.
181 let res: InterpResult<'_, i64> = (|| {
183 // Read the return code pointer *before* we run TLS destructors, to assert
184 // that it was written to by the time that `start` lang item returned.
185 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
186 ecx.run_tls_dtors()?;
190 // Process the result.
193 // Disable the leak test on some platforms where we do not
194 // correctly implement TLS destructors.
195 let target_os = ecx.tcx.tcx.sess.target.target.target_os.to_lowercase();
196 let ignore_leaks = target_os == "windows" || target_os == "macos";
198 let leaks = ecx.memory.leak_report();
200 tcx.sess.err("the evaluated program leaked memory");
201 // Ignore the provided return code - let the reported error
202 // determine the return code.
206 return Some(return_code)
209 // Special treatment for some error kinds
210 let msg = match e.kind {
211 InterpError::MachineStop(ref info) => {
212 let info = info.downcast_ref::<TerminationInfo>()
213 .expect("invalid MachineStop payload");
215 TerminationInfo::Exit(code) => return Some(*code),
216 TerminationInfo::Abort =>
217 format!("the evaluated program aborted execution")
220 err_unsup!(NoMirFor(..)) =>
221 format!("{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.", e),
222 InterpError::InvalidProgram(_) =>
223 bug!("This error should be impossible in Miri: {}", e),
227 if let Some(frame) = ecx.stack().last() {
228 let span = frame.current_source_info().unwrap().span;
230 let msg = format!("Miri evaluation error: {}", msg);
231 let mut err = ecx.tcx.sess.struct_span_err(span, msg.as_str());
232 let frames = ecx.generate_stacktrace(None);
233 err.span_label(span, msg);
234 // We iterate with indices because we need to look at the next frame (the caller).
235 for idx in 0..frames.len() {
236 let frame_info = &frames[idx];
237 let call_site_is_local = frames.get(idx + 1).map_or(false, |caller_info| {
238 caller_info.instance.def_id().is_local()
240 if call_site_is_local {
241 err.span_note(frame_info.call_site, &frame_info.to_string());
243 err.note(&frame_info.to_string());
248 ecx.tcx.sess.err(&msg);
251 for (i, frame) in ecx.stack().iter().enumerate() {
252 trace!("-------------------");
253 trace!("Frame {}", i);
254 trace!(" return: {:?}", frame.return_place.map(|p| *p));
255 for (i, local) in frame.locals.iter().enumerate() {
256 trace!(" local {}: {:?}", i, local.value);
259 // Let the reported error determine the return code.