1 //! Main evaluator loop and setting up the initial stack frame.
3 use std::convert::TryFrom;
6 use rand::rngs::StdRng;
9 use rustc_hir::def_id::DefId;
10 use rustc_middle::ty::{self, layout::LayoutCx, TyCtxt};
11 use rustc_target::abi::LayoutOf;
15 /// Configuration needed to spawn a Miri instance.
17 pub struct MiriConfig {
18 /// Determine if validity checking is enabled.
20 /// Determines if Stacked Borrows is enabled.
21 pub stacked_borrows: bool,
22 /// Determines if alignment checking is enabled.
23 pub check_alignment: bool,
24 /// Determines if communication with the host environment is enabled.
25 pub communicate: bool,
26 /// Determines if memory leaks should be ignored.
27 pub ignore_leaks: bool,
28 /// Environment variables that should always be isolated from the host.
29 pub excluded_env_vars: Vec<String>,
30 /// Command-line arguments passed to the interpreted program.
31 pub args: Vec<String>,
32 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
33 pub seed: Option<u64>,
34 /// The stacked borrows pointer id to report about
35 pub tracked_pointer_tag: Option<PtrId>,
36 /// The stacked borrows call ID to report about
37 pub tracked_call_id: Option<CallId>,
38 /// The allocation id to report about.
39 pub tracked_alloc_id: Option<AllocId>,
42 impl Default for MiriConfig {
43 fn default() -> MiriConfig {
46 stacked_borrows: true,
47 check_alignment: true,
50 excluded_env_vars: vec![],
53 tracked_pointer_tag: None,
54 tracked_call_id: None,
55 tracked_alloc_id: None,
60 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
61 /// the location where the return value of the `start` lang item will be
63 /// Public because this is also used by `priroda`.
64 pub fn create_ecx<'mir, 'tcx: 'mir>(
68 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
69 let param_env = ty::ParamEnv::reveal_all();
70 let layout_cx = LayoutCx { tcx, param_env };
71 let mut ecx = InterpCx::new(
73 rustc_span::source_map::DUMMY_SP,
75 Evaluator::new(config.communicate, config.validate, layout_cx),
77 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
78 config.stacked_borrows,
79 config.tracked_pointer_tag,
80 config.tracked_call_id,
81 config.tracked_alloc_id,
82 config.check_alignment,
85 // Complete initialization.
86 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
87 MemoryExtra::init_extern_statics(&mut ecx)?;
89 // Setup first stack-frame
90 let main_instance = ty::Instance::mono(tcx, main_id);
91 let main_mir = ecx.load_mir(main_instance.def, None)?;
92 if main_mir.arg_count != 0 {
93 bug!("main function must not take any arguments");
96 let start_id = tcx.lang_items().start_fn().unwrap();
97 let main_ret_ty = tcx.fn_sig(main_id).output();
98 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
99 let start_instance = ty::Instance::resolve(
101 ty::ParamEnv::reveal_all(),
103 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
108 // First argument: pointer to `main()`.
109 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
110 // Second argument (argc): length of `config.args`.
111 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
112 // Third argument (`argv`): created from `config.args`.
114 // Put each argument in memory, collect pointers.
115 let mut argvs = Vec::<Scalar<Tag>>::new();
116 for arg in config.args.iter() {
117 // Make space for `0` terminator.
118 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
119 let arg_type = tcx.mk_array(tcx.types.u8, size);
120 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
121 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
122 argvs.push(arg_place.ptr);
124 // Make an array with all these pointers, in the Miri memory.
126 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
127 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
128 for (idx, arg) in argvs.into_iter().enumerate() {
129 let place = ecx.mplace_field(argvs_place, idx)?;
130 ecx.write_scalar(arg, place.into())?;
132 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
133 // A pointer to that place is the 3rd argument for main.
134 let argv = argvs_place.ptr;
135 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
138 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
139 ecx.write_scalar(argc, argc_place.into())?;
140 ecx.machine.argc = Some(argc_place.ptr);
142 let argv_place = ecx.allocate(
143 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
144 MiriMemoryKind::Machine.into(),
146 ecx.write_scalar(argv, argv_place.into())?;
147 ecx.machine.argv = Some(argv_place.ptr);
149 // Store command line as UTF-16 for Windows `GetCommandLineW`.
151 // Construct a command string with all the aguments.
152 let mut cmd = String::new();
153 for arg in config.args.iter() {
157 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
159 // Don't forget `0` terminator.
160 cmd.push(std::char::from_u32(0).unwrap());
162 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
163 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
164 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
165 ecx.machine.cmd_line = Some(cmd_place.ptr);
166 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
167 for (idx, &c) in cmd_utf16.iter().enumerate() {
168 let place = ecx.mplace_field(cmd_place, idx)?;
169 ecx.write_scalar(Scalar::from_u16(c), place.into())?;
175 // Return place (in static memory so that it does not count as leak).
176 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
177 // Call start function.
180 &[main_ptr.into(), argc.into(), argv.into()],
181 Some(ret_place.into()),
182 StackPopCleanup::None { cleanup: true },
185 // Set the last_error to 0
186 let errno_layout = ecx.machine.layouts.u32;
187 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Machine.into());
188 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
189 ecx.machine.last_error = Some(errno_place);
194 /// Evaluates the main function specified by `main_id`.
195 /// Returns `Some(return_code)` if program executed completed.
196 /// Returns `None` if an evaluation error occured.
197 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
198 // FIXME: on Windows, we ignore leaks (https://github.com/rust-lang/miri/issues/1302).
199 let ignore_leaks = config.ignore_leaks || tcx.sess.target.target.target_os == "windows";
201 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
204 err.print_backtrace();
205 panic!("Miri initialization error: {}", err.kind)
209 // Perform the main execution.
210 let res: InterpResult<'_, i64> = (|| {
213 match ecx.schedule()? {
214 SchedulingAction::ExecuteStep => {
215 let info = ecx.preprocess_diagnostics();
216 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
217 ecx.process_diagnostics(info);
219 SchedulingAction::ExecuteTimeoutCallback => {
220 assert!(ecx.machine.communicate,
221 "scheduler callbacks require disabled isolation, but the code \
222 that created the callback did not check it");
223 ecx.run_timeout_callback()?;
225 SchedulingAction::ExecuteDtors => {
226 // This will either enable the thread again (so we go back
227 // to `ExecuteStep`), or determine that this thread is done
229 ecx.schedule_next_tls_dtor_for_active_thread()?;
231 SchedulingAction::Stop => {
236 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
241 EnvVars::cleanup(&mut ecx).unwrap();
243 // Process the result.
247 let leaks = ecx.memory.leak_report();
249 tcx.sess.err("the evaluated program leaked memory");
250 // Ignore the provided return code - let the reported error
251 // determine the return code.
257 Err(e) => report_error(&ecx, e),