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 borrow id to report about
35 pub tracked_pointer_tag: Option<PtrId>,
36 /// The allocation id to report about.
37 pub tracked_alloc_id: Option<AllocId>,
40 impl Default for MiriConfig {
41 fn default() -> MiriConfig {
44 stacked_borrows: true,
45 check_alignment: true,
48 excluded_env_vars: vec![],
51 tracked_pointer_tag: None,
52 tracked_alloc_id: None,
57 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
58 /// the location where the return value of the `start` lang item will be
60 /// Public because this is also used by `priroda`.
61 pub fn create_ecx<'mir, 'tcx: 'mir>(
65 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
66 let tcx_at = tcx.at(rustc_span::source_map::DUMMY_SP);
67 let param_env = ty::ParamEnv::reveal_all();
68 let layout_cx = LayoutCx { tcx, param_env };
69 let mut ecx = InterpCx::new(
72 Evaluator::new(config.communicate, config.validate, layout_cx),
74 StdRng::seed_from_u64(config.seed.unwrap_or(0)),
75 config.stacked_borrows,
76 config.tracked_pointer_tag,
77 config.tracked_alloc_id,
78 config.check_alignment,
81 // Complete initialization.
82 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
83 MemoryExtra::init_extern_statics(&mut ecx)?;
85 // Setup first stack-frame
86 let main_instance = ty::Instance::mono(tcx, main_id);
87 let main_mir = ecx.load_mir(main_instance.def, None)?;
88 if main_mir.arg_count != 0 {
89 bug!("main function must not take any arguments");
92 let start_id = tcx.lang_items().start_fn().unwrap();
93 let main_ret_ty = tcx.fn_sig(main_id).output();
94 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
95 let start_instance = ty::Instance::resolve(
97 ty::ParamEnv::reveal_all(),
99 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
104 // First argument: pointer to `main()`.
105 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
106 // Second argument (argc): length of `config.args`.
107 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
108 // Third argument (`argv`): created from `config.args`.
110 // Put each argument in memory, collect pointers.
111 let mut argvs = Vec::<Scalar<Tag>>::new();
112 for arg in config.args.iter() {
113 // Make space for `0` terminator.
114 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
115 let arg_type = tcx.mk_array(tcx.types.u8, size);
116 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
117 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
118 argvs.push(arg_place.ptr);
120 // Make an array with all these pointers, in the Miri memory.
122 ecx.layout_of(tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()))?;
123 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
124 for (idx, arg) in argvs.into_iter().enumerate() {
125 let place = ecx.mplace_field(argvs_place, idx)?;
126 ecx.write_scalar(arg, place.into())?;
128 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
129 // A pointer to that place is the 3rd argument for main.
130 let argv = argvs_place.ptr;
131 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
134 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
135 ecx.write_scalar(argc, argc_place.into())?;
136 ecx.machine.argc = Some(argc_place.ptr);
138 let argv_place = ecx.allocate(
139 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
140 MiriMemoryKind::Machine.into(),
142 ecx.write_scalar(argv, argv_place.into())?;
143 ecx.machine.argv = Some(argv_place.ptr);
145 // Store command line as UTF-16 for Windows `GetCommandLineW`.
147 // Construct a command string with all the aguments.
148 let mut cmd = String::new();
149 for arg in config.args.iter() {
153 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
155 // Don't forget `0` terminator.
156 cmd.push(std::char::from_u32(0).unwrap());
158 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
159 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
160 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
161 ecx.machine.cmd_line = Some(cmd_place.ptr);
162 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
163 for (idx, &c) in cmd_utf16.iter().enumerate() {
164 let place = ecx.mplace_field(cmd_place, idx)?;
165 ecx.write_scalar(Scalar::from_u16(c), place.into())?;
171 // Return place (in static memory so that it does not count as leak).
172 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
173 // Call start function.
176 &[main_ptr.into(), argc.into(), argv.into()],
177 Some(ret_place.into()),
178 StackPopCleanup::None { cleanup: true },
181 // Set the last_error to 0
182 let errno_layout = ecx.machine.layouts.u32;
183 let errno_place = ecx.allocate(errno_layout, MiriMemoryKind::Machine.into());
184 ecx.write_scalar(Scalar::from_u32(0), errno_place.into())?;
185 ecx.machine.last_error = Some(errno_place);
190 /// Evaluates the main function specified by `main_id`.
191 /// Returns `Some(return_code)` if program executed completed.
192 /// Returns `None` if an evaluation error occured.
193 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
194 // FIXME: on Windows, we ignore leaks (https://github.com/rust-lang/miri/issues/1302).
195 let ignore_leaks = config.ignore_leaks || tcx.sess.target.target.target_os == "windows";
197 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
200 err.print_backtrace();
201 panic!("Miri initialization error: {}", err.kind)
205 // Perform the main execution.
206 let res: InterpResult<'_, i64> = (|| {
209 match ecx.schedule()? {
210 SchedulingAction::ExecuteStep => {
211 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
213 SchedulingAction::ExecuteTimeoutCallback => {
214 assert!(ecx.machine.communicate,
215 "scheduler callbacks require disabled isolation, but the code \
216 that created the callback did not check it");
217 ecx.run_timeout_callback()?;
219 SchedulingAction::ExecuteDtors => {
220 // This will either enable the thread again (so we go back
221 // to `ExecuteStep`), or determine that this thread is done
223 ecx.schedule_next_tls_dtor_for_active_thread()?;
225 SchedulingAction::Stop => {
229 ecx.process_diagnostics();
231 let return_code = ecx.read_scalar(ret_place.into())?.not_undef()?.to_machine_isize(&ecx)?;
236 EnvVars::cleanup(&mut ecx).unwrap();
238 // Process the result.
242 let leaks = ecx.memory.leak_report();
244 tcx.sess.err("the evaluated program leaked memory");
245 // Ignore the provided return code - let the reported error
246 // determine the return code.
252 Err(e) => report_error(&ecx, e),