1use std::ffi::{OsStr, OsString};
4use std::panic::{self, AssertUnwindSafe};
5use std::path::PathBuf;
6use std::rc::Rc;
7use std::task::Poll;
8use std::{iter, thread};
9
10use rustc_abi::ExternAbi;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12use rustc_hir::def::Namespace;
13use rustc_hir::def_id::DefId;
14use rustc_middle::ty::layout::{LayoutCx, LayoutOf};
15use rustc_middle::ty::{self, Ty, TyCtxt};
16use rustc_session::config::EntryFnType;
17
18use crate::concurrency::GenmcCtx;
19use crate::concurrency::thread::TlsAllocAction;
20use crate::diagnostics::report_leaks;
21use crate::shims::tls;
22use crate::*;
23
24#[derive(Copy, Clone, Debug)]
25pub enum MiriEntryFnType {
26 MiriStart,
27 Rustc(EntryFnType),
28}
29
30const MAIN_THREAD_YIELDS_AT_SHUTDOWN: u32 = 256;
34
35#[derive(Copy, Clone, Debug, PartialEq)]
36pub enum AlignmentCheck {
37 None,
39 Symbolic,
41 Int,
43}
44
45#[derive(Copy, Clone, Debug, PartialEq)]
46pub enum RejectOpWith {
47 Abort,
49
50 NoWarning,
54
55 Warning,
57
58 WarningWithoutBacktrace,
60}
61
62#[derive(Copy, Clone, Debug, PartialEq)]
63pub enum IsolatedOp {
64 Reject(RejectOpWith),
69
70 Allow,
72}
73
74#[derive(Debug, Copy, Clone, PartialEq, Eq)]
75pub enum BacktraceStyle {
76 Short,
78 Full,
80 Off,
82}
83
84#[derive(Debug, Copy, Clone, PartialEq, Eq)]
85pub enum ValidationMode {
86 No,
88 Shallow,
90 Deep,
92}
93
94#[derive(Clone)]
96pub struct MiriConfig {
97 pub env: Vec<(OsString, OsString)>,
100 pub validation: ValidationMode,
102 pub borrow_tracker: Option<BorrowTrackerMethod>,
104 pub check_alignment: AlignmentCheck,
106 pub isolated_op: IsolatedOp,
108 pub ignore_leaks: bool,
110 pub forwarded_env_vars: Vec<String>,
112 pub set_env_vars: FxHashMap<String, String>,
114 pub args: Vec<String>,
116 pub seed: Option<u64>,
118 pub tracked_pointer_tags: FxHashSet<BorTag>,
120 pub tracked_alloc_ids: FxHashSet<AllocId>,
122 pub track_alloc_accesses: bool,
124 pub data_race_detector: bool,
126 pub weak_memory_emulation: bool,
128 pub genmc_mode: bool,
130 pub track_outdated_loads: bool,
132 pub cmpxchg_weak_failure_rate: f64,
135 pub measureme_out: Option<String>,
138 pub backtrace_style: BacktraceStyle,
140 pub provenance_mode: ProvenanceMode,
142 pub mute_stdout_stderr: bool,
145 pub preemption_rate: f64,
147 pub report_progress: Option<u32>,
149 pub retag_fields: RetagFields,
151 pub native_lib: Option<PathBuf>,
154 pub gc_interval: u32,
156 pub num_cpus: u32,
158 pub page_size: Option<u64>,
160 pub collect_leak_backtraces: bool,
162 pub address_reuse_rate: f64,
164 pub address_reuse_cross_thread_rate: f64,
166 pub fixed_scheduling: bool,
168}
169
170impl Default for MiriConfig {
171 fn default() -> MiriConfig {
172 MiriConfig {
173 env: vec![],
174 validation: ValidationMode::Shallow,
175 borrow_tracker: Some(BorrowTrackerMethod::StackedBorrows),
176 check_alignment: AlignmentCheck::Int,
177 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
178 ignore_leaks: false,
179 forwarded_env_vars: vec![],
180 set_env_vars: FxHashMap::default(),
181 args: vec![],
182 seed: None,
183 tracked_pointer_tags: FxHashSet::default(),
184 tracked_alloc_ids: FxHashSet::default(),
185 track_alloc_accesses: false,
186 data_race_detector: true,
187 weak_memory_emulation: true,
188 genmc_mode: false,
189 track_outdated_loads: false,
190 cmpxchg_weak_failure_rate: 0.8, measureme_out: None,
192 backtrace_style: BacktraceStyle::Short,
193 provenance_mode: ProvenanceMode::Default,
194 mute_stdout_stderr: false,
195 preemption_rate: 0.01, report_progress: None,
197 retag_fields: RetagFields::Yes,
198 native_lib: None,
199 gc_interval: 10_000,
200 num_cpus: 1,
201 page_size: None,
202 collect_leak_backtraces: true,
203 address_reuse_rate: 0.5,
204 address_reuse_cross_thread_rate: 0.1,
205 fixed_scheduling: false,
206 }
207 }
208}
209
210#[derive(Default, Debug)]
212enum MainThreadState<'tcx> {
213 #[default]
214 Running,
215 TlsDtors(tls::TlsDtorsState<'tcx>),
216 Yield {
217 remaining: u32,
218 },
219 Done,
220}
221
222impl<'tcx> MainThreadState<'tcx> {
223 fn on_main_stack_empty(
224 &mut self,
225 this: &mut MiriInterpCx<'tcx>,
226 ) -> InterpResult<'tcx, Poll<()>> {
227 use MainThreadState::*;
228 match self {
229 Running => {
230 *self = TlsDtors(Default::default());
231 }
232 TlsDtors(state) =>
233 match state.on_stack_empty(this)? {
234 Poll::Pending => {} Poll::Ready(()) => {
236 if this.machine.data_race.as_genmc_ref().is_some() {
237 *self = Done;
240 } else {
241 if this.machine.preemption_rate > 0.0 {
244 *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN };
247 } else {
248 *self = Done;
251 }
252 }
253 }
254 },
255 Yield { remaining } =>
256 match remaining.checked_sub(1) {
257 None => *self = Done,
258 Some(new_remaining) => {
259 *remaining = new_remaining;
260 this.yield_active_thread();
261 }
262 },
263 Done => {
264 let ret_place = this.machine.main_fn_ret_place.clone().unwrap();
266 let exit_code = this.read_target_isize(&ret_place)?;
267 let exit_code = i32::try_from(exit_code).unwrap_or(if exit_code >= 0 {
270 i32::MAX
271 } else {
272 i32::MIN
273 });
274 this.terminate_active_thread(TlsAllocAction::Leak)?;
277
278 if this.have_all_terminated() {
281 this.allow_data_races_all_threads_done();
285 EnvVars::cleanup(this).expect("error during env var cleanup");
286 }
287
288 throw_machine_stop!(TerminationInfo::Exit { code: exit_code, leak_check: true });
290 }
291 }
292 interp_ok(Poll::Pending)
293 }
294}
295
296pub fn create_ecx<'tcx>(
299 tcx: TyCtxt<'tcx>,
300 entry_id: DefId,
301 entry_type: MiriEntryFnType,
302 config: &MiriConfig,
303 genmc_ctx: Option<Rc<GenmcCtx>>,
304) -> InterpResult<'tcx, InterpCx<'tcx, MiriMachine<'tcx>>> {
305 let typing_env = ty::TypingEnv::fully_monomorphized();
306 let layout_cx = LayoutCx::new(tcx, typing_env);
307 let mut ecx = InterpCx::new(
308 tcx,
309 rustc_span::DUMMY_SP,
310 typing_env,
311 MiriMachine::new(config, layout_cx, genmc_ctx),
312 );
313
314 MiriMachine::late_init(&mut ecx, config, {
316 let mut state = MainThreadState::default();
317 Box::new(move |m| state.on_main_stack_empty(m))
319 })?;
320
321 let sentinel =
323 helpers::try_resolve_path(tcx, &["core", "ascii", "escape_default"], Namespace::ValueNS);
324 if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
325 tcx.dcx().fatal(
326 "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
327 Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
328 );
329 }
330
331 let entry_instance = ty::Instance::mono(tcx, entry_id);
333
334 let argc =
338 ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
339 let argv = {
341 let mut argvs = Vec::<Immediate<Provenance>>::with_capacity(config.args.len());
343 for arg in config.args.iter() {
344 let size = u64::try_from(arg.len()).unwrap().strict_add(1);
346 let arg_type = Ty::new_array(tcx, tcx.types.u8, size);
347 let arg_place =
348 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
349 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr(), size)?;
350 ecx.mark_immutable(&arg_place);
351 argvs.push(arg_place.to_ref(&ecx));
352 }
353 let argvs_layout = ecx.layout_of(Ty::new_array(
355 tcx,
356 Ty::new_imm_ptr(tcx, tcx.types.u8),
357 u64::try_from(argvs.len()).unwrap(),
358 ))?;
359 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
360 for (idx, arg) in argvs.into_iter().enumerate() {
361 let place = ecx.project_field(&argvs_place, idx)?;
362 ecx.write_immediate(arg, &place)?;
363 }
364 ecx.mark_immutable(&argvs_place);
365 {
367 let argc_place =
368 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
369 ecx.write_immediate(*argc, &argc_place)?;
370 ecx.mark_immutable(&argc_place);
371 ecx.machine.argc = Some(argc_place.ptr());
372
373 let argv_place = ecx.allocate(
374 ecx.layout_of(Ty::new_imm_ptr(tcx, tcx.types.unit))?,
375 MiriMemoryKind::Machine.into(),
376 )?;
377 ecx.write_pointer(argvs_place.ptr(), &argv_place)?;
378 ecx.mark_immutable(&argv_place);
379 ecx.machine.argv = Some(argv_place.ptr());
380 }
381 {
383 let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
385
386 let cmd_type =
387 Ty::new_array(tcx, tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
388 let cmd_place =
389 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
390 ecx.machine.cmd_line = Some(cmd_place.ptr());
391 for (idx, &c) in cmd_utf16.iter().enumerate() {
393 let place = ecx.project_field(&cmd_place, idx)?;
394 ecx.write_scalar(Scalar::from_u16(c), &place)?;
395 }
396 ecx.mark_immutable(&cmd_place);
397 }
398 ecx.mplace_to_ref(&argvs_place)?
399 };
400
401 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
403 ecx.machine.main_fn_ret_place = Some(ret_place.clone());
404 match entry_type {
407 MiriEntryFnType::Rustc(EntryFnType::Main { .. }) => {
408 let start_id = tcx.lang_items().start_fn().unwrap_or_else(|| {
409 tcx.dcx().fatal("could not find start lang item");
410 });
411 let main_ret_ty = tcx.fn_sig(entry_id).no_bound_vars().unwrap().output();
412 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
413 let start_instance = ty::Instance::try_resolve(
414 tcx,
415 typing_env,
416 start_id,
417 tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]),
418 )
419 .unwrap()
420 .unwrap();
421
422 let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance));
423
424 let sigpipe = rustc_session::config::sigpipe::DEFAULT;
427
428 ecx.call_function(
429 start_instance,
430 ExternAbi::Rust,
431 &[
432 ImmTy::from_scalar(
433 Scalar::from_pointer(main_ptr, &ecx),
434 ecx.machine.layouts.const_raw_ptr,
436 ),
437 argc,
438 argv,
439 ImmTy::from_uint(sigpipe, ecx.machine.layouts.u8),
440 ],
441 Some(&ret_place),
442 StackPopCleanup::Root { cleanup: true },
443 )?;
444 }
445 MiriEntryFnType::MiriStart => {
446 ecx.call_function(
447 entry_instance,
448 ExternAbi::Rust,
449 &[argc, argv],
450 Some(&ret_place),
451 StackPopCleanup::Root { cleanup: true },
452 )?;
453 }
454 }
455
456 interp_ok(ecx)
457}
458
459pub fn eval_entry<'tcx>(
463 tcx: TyCtxt<'tcx>,
464 entry_id: DefId,
465 entry_type: MiriEntryFnType,
466 config: &MiriConfig,
467 genmc_ctx: Option<Rc<GenmcCtx>>,
468) -> Option<i32> {
469 let ignore_leaks = config.ignore_leaks;
471
472 if let Some(genmc_ctx) = &genmc_ctx {
473 genmc_ctx.handle_execution_start();
474 }
475
476 let mut ecx = match create_ecx(tcx, entry_id, entry_type, config, genmc_ctx).report_err() {
477 Ok(v) => v,
478 Err(err) => {
479 let (kind, backtrace) = err.into_parts();
480 backtrace.print_backtrace();
481 panic!("Miri initialization error: {kind:?}")
482 }
483 };
484
485 let res: thread::Result<InterpResult<'_, !>> =
487 panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
488 let res = res.unwrap_or_else(|panic_payload| {
489 ecx.handle_ice();
490 panic::resume_unwind(panic_payload)
491 });
492 let Err(err) = res.report_err();
495
496 let (return_code, leak_check) = report_error(&ecx, err)?;
498
499 if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref()
501 && let Err(error) = genmc_ctx.handle_execution_end(&ecx)
502 {
503 tcx.dcx().err(format!("GenMC returned an error: \"{error}\""));
505 return None;
506 }
507
508 if leak_check && !ignore_leaks {
512 if !ecx.have_all_terminated() {
514 tcx.dcx().err("the main thread terminated without waiting for all remaining threads");
515 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
516 return None;
517 }
518 info!("Additional static roots: {:?}", ecx.machine.static_roots);
520 let leaks = ecx.take_leaked_allocations(|ecx| &ecx.machine.static_roots);
521 if !leaks.is_empty() {
522 report_leaks(&ecx, leaks);
523 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
524 return None;
527 }
528 }
529 Some(return_code)
530}
531
532fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
543where
544 I: Iterator<Item = T>,
545 T: AsRef<str>,
546{
547 let mut cmd = {
549 let arg0 = if let Some(arg0) = args.next() {
550 arg0
551 } else {
552 return vec![0];
553 };
554 let arg0 = arg0.as_ref();
555 if arg0.contains('"') {
556 panic!("argv[0] cannot contain a doublequote (\") character");
557 } else {
558 let mut s = String::new();
560 s.push('"');
561 s.push_str(arg0);
562 s.push('"');
563 s
564 }
565 };
566
567 for arg in args {
569 let arg = arg.as_ref();
570 cmd.push(' ');
571 if arg.is_empty() {
572 cmd.push_str("\"\"");
573 } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
574 cmd.push_str(arg);
576 } else {
577 cmd.push('"');
584 let mut chars = arg.chars().peekable();
585 loop {
586 let mut nslashes = 0;
587 while let Some(&'\\') = chars.peek() {
588 chars.next();
589 nslashes += 1;
590 }
591
592 match chars.next() {
593 Some('"') => {
594 cmd.extend(iter::repeat_n('\\', nslashes * 2 + 1));
595 cmd.push('"');
596 }
597 Some(c) => {
598 cmd.extend(iter::repeat_n('\\', nslashes));
599 cmd.push(c);
600 }
601 None => {
602 cmd.extend(iter::repeat_n('\\', nslashes * 2));
603 break;
604 }
605 }
606 }
607 cmd.push('"');
608 }
609 }
610
611 if cmd.contains('\0') {
612 panic!("interior null in command line arguments");
613 }
614 cmd.encode_utf16().chain(iter::once(0)).collect()
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620 #[test]
621 #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
622 fn windows_argv0_panic_on_quote() {
623 args_to_utf16_command_string(["\""].iter());
624 }
625 #[test]
626 fn windows_argv0_no_escape() {
627 let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
629 [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
630 ));
631 assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
632 }
633}