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 function [ABI](Abi) checking.
82 /// Action for an op requiring communication with the host.
83 pub isolated_op: IsolatedOp,
84 /// Determines if memory leaks should be ignored.
85 pub ignore_leaks: bool,
86 /// Environment variables that should always be isolated from the host.
87 pub excluded_env_vars: Vec<String>,
88 /// Environment variables that should always be forwarded from the host.
89 pub forwarded_env_vars: Vec<String>,
90 /// Command-line arguments passed to the interpreted program.
91 pub args: Vec<String>,
92 /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
93 pub seed: Option<u64>,
94 /// The stacked borrows pointer ids to report about
95 pub tracked_pointer_tags: HashSet<SbTag>,
96 /// The stacked borrows call IDs to report about
97 pub tracked_call_ids: HashSet<CallId>,
98 /// The allocation ids to report about.
99 pub tracked_alloc_ids: HashSet<AllocId>,
100 /// Determine if data race detection should be enabled
101 pub data_race_detector: bool,
102 /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled
103 pub weak_memory_emulation: bool,
104 /// Rate of spurious failures for compare_exchange_weak atomic operations,
105 /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
106 pub cmpxchg_weak_failure_rate: f64,
107 /// If `Some`, enable the `measureme` profiler, writing results to a file
108 /// with the specified prefix.
109 pub measureme_out: Option<String>,
110 /// Panic when unsupported functionality is encountered.
111 pub panic_on_unsupported: bool,
112 /// Which style to use for printing backtraces.
113 pub backtrace_style: BacktraceStyle,
114 /// Which provenance to use for int2ptr casts
115 pub provenance_mode: ProvenanceMode,
116 /// Whether to ignore any output by the program. This is helpful when debugging miri
117 /// as its messages don't get intermingled with the program messages.
118 pub mute_stdout_stderr: bool,
119 /// The probability of the active thread being preempted at the end of each basic block.
120 pub preemption_rate: f64,
121 /// Report the current instruction being executed every N basic blocks.
122 pub report_progress: Option<u32>,
123 /// Whether Stacked Borrows retagging should recurse into fields of datatypes.
124 pub retag_fields: bool,
127 impl Default for MiriConfig {
128 fn default() -> MiriConfig {
131 stacked_borrows: true,
132 check_alignment: AlignmentCheck::Int,
134 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
136 excluded_env_vars: vec![],
137 forwarded_env_vars: vec![],
140 tracked_pointer_tags: HashSet::default(),
141 tracked_call_ids: HashSet::default(),
142 tracked_alloc_ids: HashSet::default(),
143 data_race_detector: true,
144 weak_memory_emulation: true,
145 cmpxchg_weak_failure_rate: 0.8, // 80%
147 panic_on_unsupported: false,
148 backtrace_style: BacktraceStyle::Short,
149 provenance_mode: ProvenanceMode::Default,
150 mute_stdout_stderr: false,
151 preemption_rate: 0.01, // 1%
152 report_progress: None,
158 /// Returns a freshly created `InterpCx`, along with an `MPlaceTy` representing
159 /// the location where the return value of the `start` function will be
161 /// Public because this is also used by `priroda`.
162 pub fn create_ecx<'mir, 'tcx: 'mir>(
165 entry_type: EntryFnType,
167 ) -> InterpResult<'tcx, (InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>, MPlaceTy<'tcx, Tag>)> {
168 let param_env = ty::ParamEnv::reveal_all();
169 let layout_cx = LayoutCx { tcx, param_env };
170 let mut ecx = InterpCx::new(
172 rustc_span::source_map::DUMMY_SP,
174 Evaluator::new(config, layout_cx),
177 // Capture the current interpreter stack state (which should be empty) so that we can emit
178 // allocation-tracking and tag-tracking diagnostics for allocations which are part of the
179 // early runtime setup.
180 let info = ecx.preprocess_diagnostics();
182 // Some parts of initialization require a full `InterpCx`.
183 Evaluator::late_init(&mut ecx, config)?;
185 // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore.
186 let sentinel = ecx.try_resolve_path(&["core", "ascii", "escape_default"]);
187 if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
189 "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
190 Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
194 // Setup first stack frame.
195 let entry_instance = ty::Instance::mono(tcx, entry_id);
197 // First argument is constructed later, because it's skipped if the entry function uses #[start].
199 // Second argument (argc): length of `config.args`.
200 let argc = Scalar::from_machine_usize(u64::try_from(config.args.len()).unwrap(), &ecx);
201 // Third argument (`argv`): created from `config.args`.
203 // Put each argument in memory, collect pointers.
204 let mut argvs = Vec::<Immediate<Tag>>::new();
205 for arg in config.args.iter() {
206 // Make space for `0` terminator.
207 let size = u64::try_from(arg.len()).unwrap().checked_add(1).unwrap();
208 let arg_type = tcx.mk_array(tcx.types.u8, size);
210 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
211 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr, size)?;
212 ecx.mark_immutable(&arg_place);
213 argvs.push(arg_place.to_ref(&ecx));
215 // Make an array with all these pointers, in the Miri memory.
216 let argvs_layout = ecx.layout_of(
217 tcx.mk_array(tcx.mk_imm_ptr(tcx.types.u8), u64::try_from(argvs.len()).unwrap()),
219 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
220 for (idx, arg) in argvs.into_iter().enumerate() {
221 let place = ecx.mplace_field(&argvs_place, idx)?;
222 ecx.write_immediate(arg, &place.into())?;
224 ecx.mark_immutable(&argvs_place);
225 // A pointer to that place is the 3rd argument for main.
226 let argv = argvs_place.to_ref(&ecx);
227 // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
230 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
231 ecx.write_scalar(argc, &argc_place.into())?;
232 ecx.mark_immutable(&argc_place);
233 ecx.machine.argc = Some(*argc_place);
235 let argv_place = ecx.allocate(
236 ecx.layout_of(tcx.mk_imm_ptr(tcx.types.unit))?,
237 MiriMemoryKind::Machine.into(),
239 ecx.write_immediate(argv, &argv_place.into())?;
240 ecx.mark_immutable(&argv_place);
241 ecx.machine.argv = Some(*argv_place);
243 // Store command line as UTF-16 for Windows `GetCommandLineW`.
245 // Construct a command string with all the aguments.
246 let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
248 let cmd_type = tcx.mk_array(tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
250 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
251 ecx.machine.cmd_line = Some(*cmd_place);
252 // Store the UTF-16 string. We just allocated so we know the bounds are fine.
253 for (idx, &c) in cmd_utf16.iter().enumerate() {
254 let place = ecx.mplace_field(&cmd_place, idx)?;
255 ecx.write_scalar(Scalar::from_u16(c), &place.into())?;
257 ecx.mark_immutable(&cmd_place);
262 // Return place (in static memory so that it does not count as leak).
263 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
264 // Call start function.
267 EntryFnType::Main => {
268 let start_id = tcx.lang_items().start_fn().unwrap();
269 let main_ret_ty = tcx.fn_sig(entry_id).output();
270 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
271 let start_instance = ty::Instance::resolve(
273 ty::ParamEnv::reveal_all(),
275 tcx.mk_substs(::std::iter::once(ty::subst::GenericArg::from(main_ret_ty))),
280 let main_ptr = ecx.create_fn_alloc_ptr(FnVal::Instance(entry_instance));
285 &[Scalar::from_pointer(main_ptr, &ecx).into(), argc.into(), argv],
286 Some(&ret_place.into()),
287 StackPopCleanup::Root { cleanup: true },
290 EntryFnType::Start => {
294 &[argc.into(), argv],
295 Some(&ret_place.into()),
296 StackPopCleanup::Root { cleanup: true },
301 // Emit any diagnostics related to the setup process for the runtime, so that when the
302 // interpreter loop starts there are no unprocessed diagnostics.
303 ecx.process_diagnostics(info);
308 /// Evaluates the entry function specified by `entry_id`.
309 /// Returns `Some(return_code)` if program executed completed.
310 /// Returns `None` if an evaluation error occured.
311 pub fn eval_entry<'tcx>(
314 entry_type: EntryFnType,
317 // Copy setting before we move `config`.
318 let ignore_leaks = config.ignore_leaks;
320 let (mut ecx, ret_place) = match create_ecx(tcx, entry_id, entry_type, &config) {
323 err.print_backtrace();
324 panic!("Miri initialization error: {}", err.kind())
328 // Perform the main execution.
329 let res: InterpResult<'_, i64> = (|| {
332 let info = ecx.preprocess_diagnostics();
333 match ecx.schedule()? {
334 SchedulingAction::ExecuteStep => {
335 assert!(ecx.step()?, "a terminated thread was scheduled for execution");
337 SchedulingAction::ExecuteTimeoutCallback => {
339 ecx.machine.communicate(),
340 "scheduler callbacks require disabled isolation, but the code \
341 that created the callback did not check it"
343 ecx.run_timeout_callback()?;
345 SchedulingAction::ExecuteDtors => {
346 // This will either enable the thread again (so we go back
347 // to `ExecuteStep`), or determine that this thread is done
349 ecx.schedule_next_tls_dtor_for_active_thread()?;
351 SchedulingAction::Stop => {
355 ecx.process_diagnostics(info);
357 let return_code = ecx.read_scalar(&ret_place.into())?.to_machine_isize(&ecx)?;
362 // Execution of the program has halted so any memory access we do here
363 // cannot produce a real data race. If we do not do something to disable
364 // data race detection here, some uncommon combination of errors will
365 // cause a data race to be detected:
366 // https://github.com/rust-lang/miri/issues/2020
367 ecx.allow_data_races_mut(|ecx| EnvVars::cleanup(ecx).unwrap());
369 // Process the result.
373 // Check for thread leaks.
374 if !ecx.have_all_terminated() {
376 "the main thread terminated without waiting for all remaining threads",
378 tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
381 // Check for memory leaks.
382 info!("Additonal static roots: {:?}", ecx.machine.static_roots);
383 let leaks = ecx.leak_report(&ecx.machine.static_roots);
385 tcx.sess.err("the evaluated program leaked memory");
386 tcx.sess.note_without_error("pass `-Zmiri-ignore-leaks` to disable this check");
387 // Ignore the provided return code - let the reported error
388 // determine the return code.
394 Err(e) => report_error(&ecx, e),
398 /// Turns an array of arguments into a Windows command line string.
400 /// The string will be UTF-16 encoded and NUL terminated.
402 /// Panics if the zeroth argument contains the `"` character because doublequotes
403 /// in `argv[0]` cannot be encoded using the standard command line parsing rules.
406 /// * [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)
407 /// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
408 fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
410 I: Iterator<Item = T>,
413 // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
415 let arg0 = if let Some(arg0) = args.next() {
420 let arg0 = arg0.as_ref();
421 if arg0.contains('"') {
422 panic!("argv[0] cannot contain a doublequote (\") character");
424 // Always surround argv[0] with quotes.
425 let mut s = String::new();
433 // Build the other arguments.
435 let arg = arg.as_ref();
438 cmd.push_str("\"\"");
439 } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
440 // No quote, tab, or space -- no escaping required.
443 // Spaces and tabs are escaped by surrounding them in quotes.
444 // Quotes are themselves escaped by using backslashes when in a
446 // Backslashes only need to be escaped when one or more are directly
447 // followed by a quote. Otherwise they are taken literally.
450 let mut chars = arg.chars().peekable();
452 let mut nslashes = 0;
453 while let Some(&'\\') = chars.peek() {
460 cmd.extend(iter::repeat('\\').take(nslashes * 2 + 1));
464 cmd.extend(iter::repeat('\\').take(nslashes));
468 cmd.extend(iter::repeat('\\').take(nslashes * 2));
477 if cmd.contains('\0') {
478 panic!("interior null in command line arguments");
480 cmd.encode_utf16().chain(iter::once(0)).collect()
487 #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
488 fn windows_argv0_panic_on_quote() {
489 args_to_utf16_command_string(["\""].iter());
492 fn windows_argv0_no_escape() {
493 // Ensure that a trailing backslash in argv[0] is not escaped.
494 let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
495 [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
497 assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);