1 //! Main evaluator loop and setting up the initial stack frame.
3 use std::convert::TryFrom;
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::{self, layout::LayoutCx, TyCtxt};
10 use rustc_target::abi::LayoutOf;
11 use rustc_target::spec::abi::Abi;
15 #[derive(Copy, Clone, Debug, PartialEq)]
16 pub enum AlignmentCheck {
17 /// Do not check alignment.
19 /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
21 /// Check alignment on the actual physical integer address.
25 /// Configuration needed to spawn a Miri instance.
27 pub struct MiriConfig {
28 /// Determine if validity checking is enabled.
30 /// Determines if Stacked Borrows is enabled.
31 pub stacked_borrows: bool,
32 /// Controls alignment checking.
33 pub check_alignment: AlignmentCheck,
34 /// Controls function [ABI](Abi) checking.
36 /// Determines if communication with the host environment is enabled.
37 pub communicate: bool,
38 /// Determines if memory leaks should be ignored.
39 pub ignore_leaks: bool,
40 /// Environment variables that should always be isolated from the host.
41 pub excluded_env_vars: Vec<String>,
42 /// Command-line arguments passed to the interpreted program.
43 pub args: Vec<String>,
44 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
45 pub seed: Option<u64>,
46 /// The stacked borrows pointer id to report about
47 pub tracked_pointer_tag: Option<PtrId>,
48 /// The stacked borrows call ID to report about
49 pub tracked_call_id: Option<CallId>,
50 /// The allocation id to report about.
51 pub tracked_alloc_id: Option<AllocId>,
52 /// Whether to track raw pointers in stacked borrows.
54 /// Determine if data race detection should be enabled
55 pub data_race_detector: bool,
56 /// Rate of spurious failures for compare_exchange_weak atomic operations,
57 /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
58 pub cmpxchg_weak_failure_rate: f64,
59 /// If `Some`, enable the `measureme` profiler, writing results to a file
60 /// with the specified prefix.
61 pub measureme_out: Option<String>,
64 impl Default for MiriConfig {
65 fn default() -> MiriConfig {
68 stacked_borrows: true,
69 check_alignment: AlignmentCheck::Int,
73 excluded_env_vars: vec![],
76 tracked_pointer_tag: None,
77 tracked_call_id: None,
78 tracked_alloc_id: None,
80 data_race_detector: true,
81 cmpxchg_weak_failure_rate: 0.8,
87 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
88 /// the location where the return value of the `start` lang item will be
90 /// Public because this is also used by `priroda`.
91 pub fn create_ecx<'mir, 'tcx: 'mir>(
95 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
96 let param_env = ty::ParamEnv::reveal_all();
97 let layout_cx = LayoutCx { tcx, param_env };
98 let mut ecx = InterpCx::new(
100 rustc_span::source_map::DUMMY_SP,
102 Evaluator::new(&config, layout_cx),
103 MemoryExtra::new(&config),
105 // Complete initialization.
106 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
107 MemoryExtra::init_extern_statics(&mut ecx)?;
109 // Setup first stack-frame
110 let main_instance = ty::Instance::mono(tcx, main_id);
111 let main_mir = ecx.load_mir(main_instance.def, None)?;
112 if main_mir.arg_count != 0 {
113 bug!("main function must not take any arguments");
116 let start_id = tcx.lang_items().start_fn().unwrap();
117 let main_ret_ty = tcx.fn_sig(main_id).output();
118 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
119 let start_instance = ty::Instance::resolve(
121 ty::ParamEnv::reveal_all(),
123 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
128 // First argument: pointer to `main()`.
129 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
130 // Second argument (argc): length of `config.args`.
131 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
132 // Third argument (`argv`): created from `config.args`.
134 // Put each argument in memory, collect pointers.
135 let mut argvs = Vec::<Scalar<Tag>>::new();
136 for arg in config.args.iter() {
137 // Make space for `0` terminator.
138 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
139 let arg_type = tcx.mk_array(tcx.types.u8, size);
140 let arg_place = ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into());
141 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
142 argvs.push(arg_place.ptr);
144 // Make an array with all these pointers, in the Miri memory.
145 let argvs_layout = ecx.layout_of(
146 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
148 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into());
149 for (idx, arg) in argvs.into_iter().enumerate() {
150 let place = ecx.mplace_field(&argvs_place, idx)?;
151 ecx.write_scalar(arg, &place.into())?;
153 ecx.memory.mark_immutable(argvs_place.ptr.assert_ptr().alloc_id)?;
154 // A pointer to that place is the 3rd argument for main.
155 let argv = argvs_place.ptr;
156 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
159 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
160 ecx.write_scalar(argc, &argc_place.into())?;
161 ecx.machine.argc = Some(argc_place.ptr);
163 let argv_place = ecx.allocate(
164 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
165 MiriMemoryKind::Machine.into(),
167 ecx.write_scalar(argv, &argv_place.into())?;
168 ecx.machine.argv = Some(argv_place.ptr);
170 // Store command line as UTF-16 for Windows `GetCommandLineW`.
172 // Construct a command string with all the aguments.
173 let mut cmd = String::new();
174 for arg in config.args.iter() {
178 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
180 // Don't forget `0` terminator.
181 cmd.push(std::char::from_u32(0).unwrap());
183 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
184 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
185 let cmd_place = ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into());
186 ecx.machine.cmd_line = Some(cmd_place.ptr);
187 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
188 for (idx, &c) in cmd_utf16.iter().enumerate() {
189 let place = ecx.mplace_field(&cmd_place, idx)?;
190 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
196 // Return place (in static memory so that it does not count as leak).
197 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into());
198 // Call start function.
202 &[main_ptr.into(), argc.into(), argv.into()],
203 Some(&ret_place.into()),
204 StackPopCleanup::None { cleanup: true },
210 /// Evaluates the main function specified by `main_id`.
211 /// Returns `Some(return_code)` if program executed completed.
212 /// Returns `None` if an evaluation error occured.
213 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
214 // Copy setting before we move `config`.
215 let ignore_leaks = config.ignore_leaks;
217 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
220 err.print_backtrace();
221 panic!("Miri initialization error: {}", err.kind())
225 // Perform the main execution.
226 let res: InterpResult<'_, i64> = (|| {
229 let info = ecx.preprocess_diagnostics();
230 match ecx.schedule()? {
231 SchedulingAction::ExecuteStep => {
232 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
234 SchedulingAction::ExecuteTimeoutCallback => {
236 ecx.machine.communicate,
237 "scheduler callbacks require disabled isolation, but the code \
238 that created the callback did not check it"
240 ecx.run_timeout_callback()?;
242 SchedulingAction::ExecuteDtors => {
243 // This will either enable the thread again (so we go back
244 // to `ExecuteStep`), or determine that this thread is done
246 ecx.schedule_next_tls_dtor_for_active_thread()?;
248 SchedulingAction::Stop => {
252 ecx.process_diagnostics(info);
255 ecx.read_scalar(&ret_place.into())?.check_init()?.to_machine_isize(&ecx)?;
260 EnvVars::cleanup(&mut ecx).unwrap();
262 // Process the result.
266 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
267 let leaks = ecx.memory.leak_report(&ecx.machine.static_roots);
269 tcx.sess.err("the evaluated program leaked memory");
270 // Ignore the provided return code - let the reported error
271 // determine the return code.
277 Err(e) => report_error(&ecx, e),