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 #[derive(Copy, Clone, Debug, PartialEq)]
26 pub enum RejectOpWith {
27 /// Isolated op is rejected with an abort of the machine.
30 /// If not Abort, miri returns an error for an isolated op.
31 /// Following options determine if user should be warned about such error.
32 /// Do not print warning about rejected isolated op.
35 /// Print a warning about rejected isolated op, with backtrace.
38 /// Print a warning about rejected isolated op, without backtrace.
39 WarningWithoutBacktrace,
42 #[derive(Copy, Clone, Debug, PartialEq)]
44 /// Reject an op requiring communication with the host. By
45 /// default, miri rejects the op with an abort. If not, it returns
46 /// an error code, and prints a warning about it. Warning levels
47 /// are controlled by `RejectOpWith` enum.
50 /// Execute op requiring communication with the host, i.e. disable isolation.
54 /// Configuration needed to spawn a Miri instance.
56 pub struct MiriConfig {
57 /// Determine if validity checking is enabled.
59 /// Determines if Stacked Borrows is enabled.
60 pub stacked_borrows: bool,
61 /// Controls alignment checking.
62 pub check_alignment: AlignmentCheck,
63 /// Controls function [ABI](Abi) checking.
65 /// Action for an op requiring communication with the host.
66 pub isolated_op: IsolatedOp,
67 /// Determines if memory leaks should be ignored.
68 pub ignore_leaks: bool,
69 /// Environment variables that should always be isolated from the host.
70 pub excluded_env_vars: Vec<String>,
71 /// Command-line arguments passed to the interpreted program.
72 pub args: Vec<String>,
73 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
74 pub seed: Option<u64>,
75 /// The stacked borrows pointer id to report about
76 pub tracked_pointer_tag: Option<PtrId>,
77 /// The stacked borrows call ID to report about
78 pub tracked_call_id: Option<CallId>,
79 /// The allocation id to report about.
80 pub tracked_alloc_id: Option<AllocId>,
81 /// Whether to track raw pointers in stacked borrows.
83 /// Determine if data race detection should be enabled
84 pub data_race_detector: bool,
85 /// Rate of spurious failures for compare_exchange_weak atomic operations,
86 /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
87 pub cmpxchg_weak_failure_rate: f64,
88 /// If `Some`, enable the `measureme` profiler, writing results to a file
89 /// with the specified prefix.
90 pub measureme_out: Option<String>,
91 /// Panic when unsupported functionality is encountered
92 pub panic_on_unsupported: bool,
95 impl Default for MiriConfig {
96 fn default() -> MiriConfig {
99 stacked_borrows: true,
100 check_alignment: AlignmentCheck::Int,
102 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
104 excluded_env_vars: vec![],
107 tracked_pointer_tag: None,
108 tracked_call_id: None,
109 tracked_alloc_id: None,
111 data_race_detector: true,
112 cmpxchg_weak_failure_rate: 0.8,
114 panic_on_unsupported: false,
119 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
120 /// the location where the return value of the `start` lang item will be
122 /// Public because this is also used by `priroda`.
123 pub fn create_ecx<'mir, 'tcx: 'mir>(
127 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
128 let param_env = ty::ParamEnv::reveal_all();
129 let layout_cx = LayoutCx { tcx, param_env };
130 let mut ecx = InterpCx::new(
132 rustc_span::source_map::DUMMY_SP,
134 Evaluator::new(&config, layout_cx),
135 MemoryExtra::new(&config),
137 // Complete initialization.
138 EnvVars::init(&mut ecx, config.excluded_env_vars)?;
139 MemoryExtra::init_extern_statics(&mut ecx)?;
141 // Setup first stack-frame
142 let main_instance = ty::Instance::mono(tcx, main_id);
143 let main_mir = ecx.load_mir(main_instance.def, None)?;
144 if main_mir.arg_count != 0 {
145 bug!("main function must not take any arguments");
148 let start_id = tcx.lang_items().start_fn().unwrap();
149 let main_ret_ty = tcx.fn_sig(main_id).output();
150 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
151 let start_instance = ty::Instance::resolve(
153 ty::ParamEnv::reveal_all(),
155 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
160 // First argument: pointer to `main()`.
161 let main_ptr = ecx.memory.create_fn_alloc(FnVal::Instance(main_instance));
162 // Second argument (argc): length of `config.args`.
163 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
164 // Third argument (`argv`): created from `config.args`.
166 // Put each argument in memory, collect pointers.
167 let mut argvs = Vec::<Immediate<Tag>>::new();
168 for arg in config.args.iter() {
169 // Make space for `0` terminator.
170 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
171 let arg_type = tcx.mk_array(tcx.types.u8, size);
173 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
174 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
175 ecx.mark_immutable(&*arg_place);
176 argvs.push(arg_place.to_ref(&ecx));
178 // Make an array with all these pointers, in the Miri memory.
179 let argvs_layout = ecx.layout_of(
180 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
182 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
183 for (idx, arg) in argvs.into_iter().enumerate() {
184 let place = ecx.mplace_field(&argvs_place, idx)?;
185 ecx.write_immediate(arg, &place.into())?;
187 ecx.mark_immutable(&*argvs_place);
188 // A pointer to that place is the 3rd argument for main.
189 let argv = argvs_place.to_ref(&ecx);
190 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
193 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
194 ecx.write_scalar(argc, &argc_place.into())?;
195 ecx.mark_immutable(&*argc_place);
196 ecx.machine.argc = Some(*argc_place);
198 let argv_place = ecx.allocate(
199 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
200 MiriMemoryKind::Machine.into(),
202 ecx.write_immediate(argv, &argv_place.into())?;
203 ecx.mark_immutable(&*argv_place);
204 ecx.machine.argv = Some(*argv_place);
206 // Store command line as UTF-16 for Windows `GetCommandLineW`.
208 // Construct a command string with all the aguments.
209 let mut cmd = String::new();
210 for arg in config.args.iter() {
214 cmd.push_str(&*shell_escape::windows::escape(arg.as_str().into()));
216 // Don't forget `0` terminator.
217 cmd.push(std::char::from_u32(0).unwrap());
219 let cmd_utf16: Vec<u16> = cmd.encode_utf16().collect();
220 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
222 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
223 ecx.machine.cmd_line = Some(*cmd_place);
224 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
225 for (idx, &c) in cmd_utf16.iter().enumerate() {
226 let place = ecx.mplace_field(&cmd_place, idx)?;
227 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
229 ecx.mark_immutable(&*cmd_place);
234 // Return place (in static memory so that it does not count as leak).
235 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
236 // Call start function.
240 &[Scalar::from_pointer(main_ptr, &ecx).into(), argc.into(), argv],
241 Some(&ret_place.into()),
242 StackPopCleanup::None { cleanup: true },
248 /// Evaluates the main function specified by `main_id`.
249 /// Returns `Some(return_code)` if program executed completed.
250 /// Returns `None` if an evaluation error occured.
251 pub fn eval_main<'tcx>(tcx: TyCtxt<'tcx>, main_id: DefId, config: MiriConfig) -> Option<i64> {
252 // Copy setting before we move `config`.
253 let ignore_leaks = config.ignore_leaks;
255 let (mut ecx, ret_place) = match create_ecx(tcx, main_id, config) {
258 err.print_backtrace();
259 panic!("Miri initialization error: {}", err.kind())
263 // Perform the main execution.
264 let res: InterpResult<'_, i64> = (|| {
267 let info = ecx.preprocess_diagnostics();
268 match ecx.schedule()? {
269 SchedulingAction::ExecuteStep => {
270 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
272 SchedulingAction::ExecuteTimeoutCallback => {
274 ecx.machine.communicate(),
275 "scheduler callbacks require disabled isolation, but the code \
276 that created the callback did not check it"
278 ecx.run_timeout_callback()?;
280 SchedulingAction::ExecuteDtors => {
281 // This will either enable the thread again (so we go back
282 // to `ExecuteStep`), or determine that this thread is done
284 ecx.schedule_next_tls_dtor_for_active_thread()?;
286 SchedulingAction::Stop => {
290 ecx.process_diagnostics(info);
292 let return_code = ecx.read_scalar(&ret_place.into())?.to_machine_isize(&ecx)?;
297 EnvVars::cleanup(&mut ecx).unwrap();
299 // Process the result.
303 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
304 let leaks = ecx.memory.leak_report(&ecx.machine.static_roots);
306 tcx.sess.err("the evaluated program leaked memory");
307 // Ignore the provided return code - let the reported error
308 // determine the return code.
314 Err(e) => report_error(&ecx, e),