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 /// Determines if memory leaks should be ignored.
22 pub ignore_leaks: bool,
23 /// Environment variables that should always be isolated from the host.
24 pub excluded_env_vars: Vec<String>,
25 /// Command-line arguments passed to the interpreted program.
26 pub args: Vec<String>,
27 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
28 pub seed: Option<u64>,
29 /// The stacked borrow id to report about
30 pub tracked_pointer_tag: Option<PtrId>,
33 /// Details of premature program termination.
34 pub enum TerminationInfo {
36 PoppedTrackedPointerTag(Item),
40 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
41 /// the location where the return value of the `start` lang item will be
43 /// Public because this is also used by `priroda`.
44 pub fn create_ecx<'mir, 'tcx: 'mir>(
48 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'tcx>>, MPlaceTy<'tcx, Tag>)> {
49 let mut ecx = InterpCx::new(
50 tcx.at(rustc_span::source_map::DUMMY_SP),
51 ty::ParamEnv::reveal_all(),
52 Evaluator::new(config.communicate),
54 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
56 config.tracked_pointer_tag,
59 // Complete initialization.
60 EnvVars::init(&mut ecx, config.excluded_env_vars);
62 // Setup first stack-frame
63 let main_instance = ty::Instance::mono(tcx, main_id);
64 let main_mir = ecx.load_mir(main_instance.def, None)?;
65 if main_mir.arg_count != 0 {
66 bug!("main function must not take any arguments");
69 let start_id = tcx.lang_items().start_fn().unwrap();
70 let main_ret_ty = tcx.fn_sig(main_id).output();
71 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
72 let start_instance = ty::Instance::resolve(
74 ty::ParamEnv::reveal_all(),
76 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
80 // First argument: pointer to `main()`.
81 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
82 // Second argument (argc): length of `config.args`.
83 let argc = Scalar::from_uint(config.args.len() as u128, ecx.pointer_size());
84 // Third argument (`argv`): created from `config.args`.
86 // Put each argument in memory, collect pointers.
87 let mut argvs = Vec::<Scalar<Tag>>::new();
88 for arg in config.args.iter() {
89 // Make space for `0` terminator.
90 let size = arg.len() as u64 + 1;
91 let arg_type = tcx.mk_array(tcx.types.u8, size);
92 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Env.into());
93 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
94 argvs.push(arg_place.ptr);
96 // Make an array with all these pointers, in the Miri memory.
98 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), argvs.len() as u64))?;
99 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Env.into());
100 for (idx, arg) in argvs.into_iter().enumerate() {
101 let place = ecx.mplace_field(argvs_place, idx as u64)?;
102 ecx.write_scalar(arg, place.into())?;
104 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
105 // A pointer to that place is the 3rd argument for main.
106 let argv = argvs_place.ptr;
107 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
110 ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
111 ecx.write_scalar(argc, argc_place.into())?;
112 ecx.machine.argc = Some(argc_place.ptr);
114 let argv_place = ecx.allocate(
115 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
116 MiriMemoryKind::Env.into(),
118 ecx.write_scalar(argv, argv_place.into())?;
119 ecx.machine.argv = Some(argv_place.ptr);
121 // Store command line as UTF-16 for Windows `GetCommandLineW`.
123 // Construct a command string with all the aguments.
124 let mut cmd = String::new();
125 for arg in config.args.iter() {
129 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
131 // Don't forget `0` terminator.
132 cmd.push(std::char::from_u32(0).unwrap());
134 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
135 let cmd_type = tcx.mk_array(tcx.types.u16, cmd_utf16.len() as u64);
136 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Env.into());
137 ecx.machine.cmd_line = Some(cmd_place.ptr);
138 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
139 let char_size = Size::from_bytes(2);
140 for (idx, &c) in cmd_utf16.iter().enumerate() {
141 let place = ecx.mplace_field(cmd_place, idx as u64)?;
142 ecx.write_scalar(Scalar::from_uint(c, char_size), place.into())?;
148 // Return place (in static memory so that it does not count as leak).
149 let ret_place = ecx.allocate(ecx.layout_of(tcx.types.isize)?, MiriMemoryKind::Env.into());
150 // Call start function.
153 &[main_ptr.into(), argc.into(), argv.into()],
154 Some(ret_place.into()),
155 StackPopCleanup::None { cleanup: true },
158 // Set the last_error to 0
159 let errno_layout = ecx.layout_of(tcx.types.u32)?;
160 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Env.into());
161 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
162 ecx.machine.last_error = Some(errno_place);
167 /// Evaluates the main function specified by `main_id`.
168 /// Returns `Some(return_code)` if program executed completed.
169 /// Returns `None` if an evaluation error occured.
170 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
171 // FIXME: We always ignore leaks on some platforms where we do not
172 // correctly implement TLS destructors.
173 let target_os = tcx.sess.target.target.target_os.to_lowercase();
174 let ignore_leaks = config.ignore_leaks || target_os == "windows" || target_os == "macos";
176 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
179 err.print_backtrace();
180 panic!("Miri initialziation error: {}", err.kind)
184 // Perform the main execution.
185 let res: InterpResult<'_, i64> = (|| {
187 // Read the return code pointer *before* we run TLS destructors, to assert
188 // that it was written to by the time that `start` lang item returned.
189 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
190 ecx.run_tls_dtors()?;
194 // Process the result.
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) => {
213 .downcast_ref::<TerminationInfo>()
214 .expect("invalid MachineStop payload");
216 TerminationInfo::Exit(code) => return Some(*code),
217 TerminationInfo::PoppedTrackedPointerTag(item) =>
218 format!("popped tracked tag for item {:?}", item),
219 TerminationInfo::Abort =>
220 format!("the evaluated program aborted execution"),
223 err_unsup!(NoMirFor(..)) => format!(
224 "{}. Did you set `MIRI_SYSROOT` to a Miri-enabled sysroot? You can prepare one with `cargo miri setup`.",
227 InterpError::InvalidProgram(_) =>
228 bug!("This error should be impossible in Miri: {}", e),
232 if let Some(frame) = ecx.stack().last() {
233 let span = frame.current_source_info().unwrap().span;
235 let msg = format!("Miri evaluation error: {}", msg);
236 let mut err = ecx.tcx.sess.struct_span_err(span, msg.as_str());
237 let frames = ecx.generate_stacktrace(None);
238 err.span_label(span, msg);
239 // We iterate with indices because we need to look at the next frame (the caller).
240 for idx in 0..frames.len() {
241 let frame_info = &frames[idx];
242 let call_site_is_local = frames
244 .map_or(false, |caller_info| caller_info.instance.def_id().is_local());
245 if call_site_is_local {
246 err.span_note(frame_info.call_site, &frame_info.to_string());
248 err.note(&frame_info.to_string());
253 ecx.tcx.sess.err(&msg);
256 for (i, frame) in ecx.stack().iter().enumerate() {
257 trace!("-------------------");
258 trace!("Frame {}", i);
259 trace!(" return: {:?}", frame.return_place.map(|p| *p));
260 for (i, local) in frame.locals.iter().enumerate() {
261 trace!(" local {}: {:?}", i, local.value);
264 // Let the reported error determine the return code.