1 //! Main evaluator loop and setting up the initial stack frame.
8 use rustc_hir::def_id::DefId;
9 use rustc_middle::ty::{
11 layout::{LayoutCx, LayoutOf},
14 use rustc_target::spec::abi::Abi;
16 use rustc_session::config::EntryFnType;
18 use std::collections::HashSet;
22 #[derive(Copy, Clone, Debug, PartialEq)]
23 pub enum AlignmentCheck {
24 /// Do not check alignment.
26 /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
28 /// Check alignment on the actual physical integer address.
32 #[derive(Copy, Clone, Debug, PartialEq)]
33 pub enum RejectOpWith {
34 /// Isolated op is rejected with an abort of the machine.
37 /// If not Abort, miri returns an error for an isolated op.
38 /// Following options determine if user should be warned about such error.
39 /// Do not print warning about rejected isolated op.
42 /// Print a warning about rejected isolated op, with backtrace.
45 /// Print a warning about rejected isolated op, without backtrace.
46 WarningWithoutBacktrace,
49 #[derive(Copy, Clone, Debug, PartialEq)]
51 /// Reject an op requiring communication with the host. By
52 /// default, miri rejects the op with an abort. If not, it returns
53 /// an error code, and prints a warning about it. Warning levels
54 /// are controlled by `RejectOpWith` enum.
57 /// Execute op requiring communication with the host, i.e. disable isolation.
61 #[derive(Copy, Clone, PartialEq, Eq)]
62 pub enum BacktraceStyle {
63 /// Prints a terser backtrace which ideally only contains relevant information.
65 /// Prints a backtrace with all possible information.
67 /// Prints only the frame that the error occurs in.
71 /// Configuration needed to spawn a Miri instance.
73 pub struct MiriConfig {
74 /// Determine if validity checking is enabled.
76 /// Determines if Stacked Borrows is enabled.
77 pub stacked_borrows: bool,
78 /// Controls alignment checking.
79 pub check_alignment: AlignmentCheck,
80 /// Controls integer and float validity initialization checking.
81 pub allow_uninit_numbers: bool,
82 /// Controls how we treat ptr2int and int2ptr transmutes.
83 pub allow_ptr_int_transmute: bool,
84 /// Controls function [ABI](Abi) checking.
86 /// Action for an op requiring communication with the host.
87 pub isolated_op: IsolatedOp,
88 /// Determines if memory leaks should be ignored.
89 pub ignore_leaks: bool,
90 /// Environment variables that should always be isolated from the host.
91 pub excluded_env_vars: Vec<String>,
92 /// Environment variables that should always be forwarded from the host.
93 pub forwarded_env_vars: Vec<String>,
94 /// Command-line arguments passed to the interpreted program.
95 pub args: Vec<String>,
96 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
97 pub seed: Option<u64>,
98 /// The stacked borrows pointer ids to report about
99 pub tracked_pointer_tags: HashSet<PtrId>,
100 /// The stacked borrows call IDs to report about
101 pub tracked_call_ids: HashSet<CallId>,
102 /// The allocation ids to report about.
103 pub tracked_alloc_ids: HashSet<AllocId>,
104 /// Determine if data race detection should be enabled
105 pub data_race_detector: bool,
106 /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled
107 pub weak_memory_emulation: bool,
108 /// Rate of spurious failures for compare_exchange_weak atomic operations,
109 /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
110 pub cmpxchg_weak_failure_rate: f64,
111 /// If `Some`, enable the `measureme` profiler, writing results to a file
112 /// with the specified prefix.
113 pub measureme_out: Option<String>,
114 /// Panic when unsupported functionality is encountered.
115 pub panic_on_unsupported: bool,
116 /// Which style to use for printing backtraces.
117 pub backtrace_style: BacktraceStyle,
118 /// Which provenance to use for int2ptr casts
119 pub provenance_mode: ProvenanceMode,
120 /// Whether to ignore any output by the program. This is helpful when debugging miri
121 /// as its messages don't get intermingled with the program messages.
122 pub mute_stdout_stderr: bool,
123 /// The probability of the active thread being preempted at the end of each basic block.
124 pub preemption_rate: f64,
125 /// Report the current instruction being executed every N basic blocks.
126 pub report_progress: Option<u32>,
129 impl Default for MiriConfig {
130 fn default() -> MiriConfig {
133 stacked_borrows: true,
134 check_alignment: AlignmentCheck::Int,
135 allow_uninit_numbers: false,
136 allow_ptr_int_transmute: false,
138 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
140 excluded_env_vars: vec![],
141 forwarded_env_vars: vec![],
144 tracked_pointer_tags: HashSet::default(),
145 tracked_call_ids: HashSet::default(),
146 tracked_alloc_ids: HashSet::default(),
147 data_race_detector: true,
148 weak_memory_emulation: true,
149 cmpxchg_weak_failure_rate: 0.8, // 80%
151 panic_on_unsupported: false,
152 backtrace_style: BacktraceStyle::Short,
153 provenance_mode: ProvenanceMode::Default,
154 mute_stdout_stderr: false,
155 preemption_rate: 0.01, // 1%
156 report_progress: None,
161 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
162 /// the location where the return value of the `start` function will be
164 /// Public because this is also used by `priroda`.
165 pub fn create_ecx<'mir, 'tcx: 'mir>(
168 entry_type: EntryFnType,
170 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
171 let param_env = ty::ParamEnv::reveal_all();
172 let layout_cx = LayoutCx { tcx, param_env };
173 let mut ecx = InterpCx::new(
175 rustc_span::source_map::DUMMY_SP,
177 Evaluator::new(config, layout_cx),
180 // Capture the current interpreter stack state (which should be empty) so that we can emit
181 // allocation-tracking and tag-tracking diagnostics for allocations which are part of the
182 // early runtime setup.
183 let info = ecx.preprocess_diagnostics();
185 // Some parts of initialization require a full `InterpCx`.
186 Evaluator::late_init(&mut ecx, config)?;
188 // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore.
189 let sentinel = ecx.try_resolve_path(&["core", "ascii", "escape_default"]);
190 if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
192 "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
193 Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
197 // Setup first stack frame.
198 let entry_instance = ty::Instance::mono(tcx, entry_id);
200 // First argument is constructed later, because it's skipped if the entry function uses #[start].
202 // Second argument (argc): length of `config.args`.
203 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
204 // Third argument (`argv`): created from `config.args`.
206 // Put each argument in memory, collect pointers.
207 let mut argvs = Vec::<Immediate<Tag>>::new();
208 for arg in config.args.iter() {
209 // Make space for `0` terminator.
210 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
211 let arg_type = tcx.mk_array(tcx.types.u8, size);
213 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
214 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
215 ecx.mark_immutable(&*arg_place);
216 argvs.push(arg_place.to_ref(&ecx));
218 // Make an array with all these pointers, in the Miri memory.
219 let argvs_layout = ecx.layout_of(
220 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
222 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
223 for (idx, arg) in argvs.into_iter().enumerate() {
224 let place = ecx.mplace_field(&argvs_place, idx)?;
225 ecx.write_immediate(arg, &place.into())?;
227 ecx.mark_immutable(&*argvs_place);
228 // A pointer to that place is the 3rd argument for main.
229 let argv = argvs_place.to_ref(&ecx);
230 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
233 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
234 ecx.write_scalar(argc, &argc_place.into())?;
235 ecx.mark_immutable(&*argc_place);
236 ecx.machine.argc = Some(*argc_place);
238 let argv_place = ecx.allocate(
239 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
240 MiriMemoryKind::Machine.into(),
242 ecx.write_immediate(argv, &argv_place.into())?;
243 ecx.mark_immutable(&*argv_place);
244 ecx.machine.argv = Some(*argv_place);
246 // Store command line as UTF-16 for Windows `GetCommandLineW`.
248 // Construct a command string with all the aguments.
249 let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
251 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
253 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
254 ecx.machine.cmd_line = Some(*cmd_place);
255 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
256 for (idx, &c) in cmd_utf16.iter().enumerate() {
257 let place = ecx.mplace_field(&cmd_place, idx)?;
258 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
260 ecx.mark_immutable(&*cmd_place);
265 // Return place (in static memory so that it does not count as leak).
266 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
267 // Call start function.
270 EntryFnType::Main => {
271 let start_id = tcx.lang_items().start_fn().unwrap();
272 let main_ret_ty = tcx.fn_sig(entry_id).output();
273 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
274 let start_instance = ty::Instance::resolve(
276 ty::ParamEnv::reveal_all(),
278 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
283 let main_ptr = ecx.create_fn_alloc_ptr(FnVal::Instance(entry_instance));
288 &[Scalar::from_pointer(main_ptr, &ecx).into(), argc.into(), argv],
290 StackPopCleanup::Root { cleanup: true },
293 EntryFnType::Start => {
297 &[argc.into(), argv],
299 StackPopCleanup::Root { cleanup: true },
304 // Emit any diagnostics related to the setup process for the runtime, so that when the
305 // interpreter loop starts there are no unprocessed diagnostics.
306 ecx.process_diagnostics(info);
311 /// Evaluates the entry function specified by `entry_id`.
312 /// Returns `Some(return_code)` if program executed completed.
313 /// Returns `None` if an evaluation error occured.
314 pub fn eval_entry<'tcx>(
317 entry_type: EntryFnType,
320 // Copy setting before we move `config`.
321 let ignore_leaks = config.ignore_leaks;
323 let (mut ecx, ret_place) = match create_ecx(tcx, entry_id, entry_type, &config) {
326 err.print_backtrace();
327 panic!("Miri initialization error: {}", err.kind())
331 // Perform the main execution.
332 let res: InterpResult<'_, i64> = (|| {
335 let info = ecx.preprocess_diagnostics();
336 match ecx.schedule()? {
337 SchedulingAction::ExecuteStep => {
338 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
340 SchedulingAction::ExecuteTimeoutCallback => {
342 ecx.machine.communicate(),
343 "scheduler callbacks require disabled isolation, but the code \
344 that created the callback did not check it"
346 ecx.run_timeout_callback()?;
348 SchedulingAction::ExecuteDtors => {
349 // This will either enable the thread again (so we go back
350 // to `ExecuteStep`), or determine that this thread is done
352 ecx.schedule_next_tls_dtor_for_active_thread()?;
354 SchedulingAction::Stop => {
358 ecx.process_diagnostics(info);
360 let return_code = ecx.read_scalar(&ret_place.into())?.to_machine_isize(&ecx)?;
365 // Execution of the program has halted so any memory access we do here
366 // cannot produce a real data race. If we do not do something to disable
367 // data race detection here, some uncommon combination of errors will
368 // cause a data race to be detected:
369 // https://github.com/rust-lang/miri/issues/2020
370 ecx.allow_data_races_mut(|ecx| EnvVars::cleanup(ecx).unwrap());
372 // Process the result.
376 // Check for thread leaks.
377 if !ecx.have_all_terminated() {
379 "the main thread terminated without waiting for all remaining threads",
381 tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
384 // Check for memory leaks.
385 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
386 let leaks = ecx.leak_report(&ecx.machine.static_roots);
388 tcx.sess.err("the evaluated program leaked memory");
389 tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
390 // Ignore the provided return code - let the reported error
391 // determine the return code.
397 Err(e) => report_error(&ecx, e),
401 /// Turns an array of arguments into a Windows command line string.
403 /// The string will be UTF-16 encoded and NUL terminated.
405 /// Panics if the zeroth argument contains the `"` character because doublequotes
406 /// in `argv[0]` cannot be encoded using the standard command line parsing rules.
409 /// * [Parsing C++ command-line arguments](https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments)
410 /// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
411 fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
413 I: Iterator<Item = T>,
416 // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
418 let arg0 = if let Some(arg0) = args.next() {
423 let arg0 = arg0.as_ref();
424 if arg0.contains('"') {
425 panic!("argv[0] cannot contain a doublequote (\") character");
427 // Always surround argv[0] with quotes.
428 let mut s = String::new();
436 // Build the other arguments.
438 let arg = arg.as_ref();
441 cmd.push_str("\"\"");
442 } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
443 // No quote, tab, or space -- no escaping required.
446 // Spaces and tabs are escaped by surrounding them in quotes.
447 // Quotes are themselves escaped by using backslashes when in a
449 // Backslashes only need to be escaped when one or more are directly
450 // followed by a quote. Otherwise they are taken literally.
453 let mut chars = arg.chars().peekable();
455 let mut nslashes = 0;
456 while let Some(&'\\') = chars.peek() {
463 cmd.extend(iter::repeat('\\').take(nslashes * 2 + 1));
467 cmd.extend(iter::repeat('\\').take(nslashes));
471 cmd.extend(iter::repeat('\\').take(nslashes * 2));
480 if cmd.contains('\0') {
481 panic!("interior null in command line arguments");
483 cmd.encode_utf16().chain(iter::once(0)).collect()
490 #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
491 fn windows_argv0_panic_on_quote() {
492 args_to_utf16_command_string(["\""].iter());
495 fn windows_argv0_no_escape() {
496 // Ensure that a trailing backslash in argv[0] is not escaped.
497 let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
498 [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
500 assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);