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::{HasTyCtxt, HasTypingEnv, LayoutCx};
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::{global_ctor, 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: Vec<PathBuf>,
153 pub native_lib_enable_tracing: bool,
155 pub gc_interval: u32,
157 pub num_cpus: u32,
159 pub page_size: Option<u64>,
161 pub collect_leak_backtraces: bool,
163 pub address_reuse_rate: f64,
165 pub address_reuse_cross_thread_rate: f64,
167 pub fixed_scheduling: bool,
169 pub force_intrinsic_fallback: bool,
171 pub float_nondet: bool,
173}
174
175impl Default for MiriConfig {
176 fn default() -> MiriConfig {
177 MiriConfig {
178 env: vec![],
179 validation: ValidationMode::Shallow,
180 borrow_tracker: Some(BorrowTrackerMethod::StackedBorrows),
181 check_alignment: AlignmentCheck::Int,
182 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
183 ignore_leaks: false,
184 forwarded_env_vars: vec![],
185 set_env_vars: FxHashMap::default(),
186 args: vec![],
187 seed: None,
188 tracked_pointer_tags: FxHashSet::default(),
189 tracked_alloc_ids: FxHashSet::default(),
190 track_alloc_accesses: false,
191 data_race_detector: true,
192 weak_memory_emulation: true,
193 genmc_mode: false,
194 track_outdated_loads: false,
195 cmpxchg_weak_failure_rate: 0.8, measureme_out: None,
197 backtrace_style: BacktraceStyle::Short,
198 provenance_mode: ProvenanceMode::Default,
199 mute_stdout_stderr: false,
200 preemption_rate: 0.01, report_progress: None,
202 retag_fields: RetagFields::Yes,
203 native_lib: vec![],
204 native_lib_enable_tracing: false,
205 gc_interval: 10_000,
206 num_cpus: 1,
207 page_size: None,
208 collect_leak_backtraces: true,
209 address_reuse_rate: 0.5,
210 address_reuse_cross_thread_rate: 0.1,
211 fixed_scheduling: false,
212 force_intrinsic_fallback: false,
213 float_nondet: true,
214 }
215 }
216}
217
218#[derive(Debug)]
220enum MainThreadState<'tcx> {
221 GlobalCtors {
222 ctor_state: global_ctor::GlobalCtorState<'tcx>,
223 entry_id: DefId,
225 entry_type: MiriEntryFnType,
226 argc: ImmTy<'tcx>,
228 argv: ImmTy<'tcx>,
229 },
230 Running,
231 TlsDtors(tls::TlsDtorsState<'tcx>),
232 Yield {
233 remaining: u32,
234 },
235 Done,
236}
237
238impl<'tcx> MainThreadState<'tcx> {
239 fn on_main_stack_empty(
240 &mut self,
241 this: &mut MiriInterpCx<'tcx>,
242 ) -> InterpResult<'tcx, Poll<()>> {
243 use MainThreadState::*;
244 match self {
245 GlobalCtors { ctor_state, entry_id, entry_type, argc, argv } => {
246 match ctor_state.on_stack_empty(this)? {
247 Poll::Pending => {} Poll::Ready(()) => {
249 call_main(this, *entry_id, *entry_type, argc.clone(), argv.clone())?;
250 *self = Running;
251 }
252 }
253 }
254 Running => {
255 *self = TlsDtors(Default::default());
256 }
257 TlsDtors(state) =>
258 match state.on_stack_empty(this)? {
259 Poll::Pending => {} Poll::Ready(()) => {
261 if this.machine.data_race.as_genmc_ref().is_some() {
262 *self = Done;
265 } else {
266 if this.machine.preemption_rate > 0.0 {
269 *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN };
272 } else {
273 *self = Done;
276 }
277 }
278 }
279 },
280 Yield { remaining } =>
281 match remaining.checked_sub(1) {
282 None => *self = Done,
283 Some(new_remaining) => {
284 *remaining = new_remaining;
285 this.yield_active_thread();
286 }
287 },
288 Done => {
289 let ret_place = this.machine.main_fn_ret_place.clone().unwrap();
291 let exit_code = this.read_target_isize(&ret_place)?;
292 let exit_code = i32::try_from(exit_code).unwrap_or(if exit_code >= 0 {
295 i32::MAX
296 } else {
297 i32::MIN
298 });
299 this.terminate_active_thread(TlsAllocAction::Leak)?;
302
303 throw_machine_stop!(TerminationInfo::Exit { code: exit_code, leak_check: true });
305 }
306 }
307 interp_ok(Poll::Pending)
308 }
309}
310
311pub fn create_ecx<'tcx>(
314 tcx: TyCtxt<'tcx>,
315 entry_id: DefId,
316 entry_type: MiriEntryFnType,
317 config: &MiriConfig,
318 genmc_ctx: Option<Rc<GenmcCtx>>,
319) -> InterpResult<'tcx, InterpCx<'tcx, MiriMachine<'tcx>>> {
320 let typing_env = ty::TypingEnv::fully_monomorphized();
321 let layout_cx = LayoutCx::new(tcx, typing_env);
322 let mut ecx = InterpCx::new(
323 tcx,
324 rustc_span::DUMMY_SP,
325 typing_env,
326 MiriMachine::new(config, layout_cx, genmc_ctx),
327 );
328
329 let sentinel =
331 helpers::try_resolve_path(tcx, &["core", "ascii", "escape_default"], Namespace::ValueNS);
332 if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
333 tcx.dcx().fatal(
334 "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
335 Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
336 );
337 }
338
339 let argc =
341 ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
342 let argv = {
343 let mut argvs = Vec::<Immediate<Provenance>>::with_capacity(config.args.len());
345 for arg in config.args.iter() {
346 let size = u64::try_from(arg.len()).unwrap().strict_add(1);
348 let arg_type = Ty::new_array(tcx, tcx.types.u8, size);
349 let arg_place =
350 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
351 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr(), size)?;
352 ecx.mark_immutable(&arg_place);
353 argvs.push(arg_place.to_ref(&ecx));
354 }
355 let u8_ptr_type = Ty::new_imm_ptr(tcx, tcx.types.u8);
357 let u8_ptr_ptr_type = Ty::new_imm_ptr(tcx, u8_ptr_type);
358 let argvs_layout =
359 ecx.layout_of(Ty::new_array(tcx, u8_ptr_type, u64::try_from(argvs.len()).unwrap()))?;
360 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
361 for (arg, idx) in argvs.into_iter().zip(0..) {
362 let place = ecx.project_index(&argvs_place, idx)?;
363 ecx.write_immediate(arg, &place)?;
364 }
365 ecx.mark_immutable(&argvs_place);
366 {
368 let argc_place =
369 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
370 ecx.write_immediate(*argc, &argc_place)?;
371 ecx.mark_immutable(&argc_place);
372 ecx.machine.argc = Some(argc_place.ptr());
373
374 let argv_place =
375 ecx.allocate(ecx.layout_of(u8_ptr_ptr_type)?, MiriMemoryKind::Machine.into())?;
376 ecx.write_pointer(argvs_place.ptr(), &argv_place)?;
377 ecx.mark_immutable(&argv_place);
378 ecx.machine.argv = Some(argv_place.ptr());
379 }
380 if tcx.sess.target.os == "windows" {
382 let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
384
385 let cmd_type =
386 Ty::new_array(tcx, tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
387 let cmd_place =
388 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
389 ecx.machine.cmd_line = Some(cmd_place.ptr());
390 for (&c, idx) in cmd_utf16.iter().zip(0..) {
392 let place = ecx.project_index(&cmd_place, idx)?;
393 ecx.write_scalar(Scalar::from_u16(c), &place)?;
394 }
395 ecx.mark_immutable(&cmd_place);
396 }
397 let imm = argvs_place.to_ref(&ecx);
398 let layout = ecx.layout_of(u8_ptr_ptr_type)?;
399 ImmTy::from_immediate(imm, layout)
400 };
401
402 MiriMachine::late_init(&mut ecx, config, {
404 let mut main_thread_state = MainThreadState::GlobalCtors {
405 entry_id,
406 entry_type,
407 argc,
408 argv,
409 ctor_state: global_ctor::GlobalCtorState::default(),
410 };
411
412 Box::new(move |m| main_thread_state.on_main_stack_empty(m))
416 })?;
417
418 interp_ok(ecx)
419}
420
421fn call_main<'tcx>(
423 ecx: &mut MiriInterpCx<'tcx>,
424 entry_id: DefId,
425 entry_type: MiriEntryFnType,
426 argc: ImmTy<'tcx>,
427 argv: ImmTy<'tcx>,
428) -> InterpResult<'tcx, ()> {
429 let tcx = ecx.tcx();
430
431 let entry_instance = ty::Instance::mono(tcx, entry_id);
433
434 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
436 ecx.machine.main_fn_ret_place = Some(ret_place.clone());
437
438 match entry_type {
440 MiriEntryFnType::Rustc(EntryFnType::Main { .. }) => {
441 let start_id = tcx.lang_items().start_fn().unwrap_or_else(|| {
442 tcx.dcx().fatal("could not find start lang item");
443 });
444 let main_ret_ty = tcx.fn_sig(entry_id).no_bound_vars().unwrap().output();
445 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
446 let start_instance = ty::Instance::try_resolve(
447 tcx,
448 ecx.typing_env(),
449 start_id,
450 tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]),
451 )
452 .unwrap()
453 .unwrap();
454
455 let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance));
456
457 let sigpipe = rustc_session::config::sigpipe::DEFAULT;
460
461 ecx.call_function(
462 start_instance,
463 ExternAbi::Rust,
464 &[
465 ImmTy::from_scalar(
466 Scalar::from_pointer(main_ptr, ecx),
467 ecx.machine.layouts.const_raw_ptr,
469 ),
470 argc,
471 argv,
472 ImmTy::from_uint(sigpipe, ecx.machine.layouts.u8),
473 ],
474 Some(&ret_place),
475 ReturnContinuation::Stop { cleanup: true },
476 )?;
477 }
478 MiriEntryFnType::MiriStart => {
479 ecx.call_function(
480 entry_instance,
481 ExternAbi::Rust,
482 &[argc, argv],
483 Some(&ret_place),
484 ReturnContinuation::Stop { cleanup: true },
485 )?;
486 }
487 }
488
489 interp_ok(())
490}
491
492pub fn eval_entry<'tcx>(
496 tcx: TyCtxt<'tcx>,
497 entry_id: DefId,
498 entry_type: MiriEntryFnType,
499 config: &MiriConfig,
500 genmc_ctx: Option<Rc<GenmcCtx>>,
501) -> Option<i32> {
502 let ignore_leaks = config.ignore_leaks;
504
505 if let Some(genmc_ctx) = &genmc_ctx {
506 genmc_ctx.handle_execution_start();
507 }
508
509 let mut ecx = match create_ecx(tcx, entry_id, entry_type, config, genmc_ctx).report_err() {
510 Ok(v) => v,
511 Err(err) => {
512 let (kind, backtrace) = err.into_parts();
513 backtrace.print_backtrace();
514 panic!("Miri initialization error: {kind:?}")
515 }
516 };
517
518 let res: thread::Result<InterpResult<'_, !>> =
520 panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
521 let res = res.unwrap_or_else(|panic_payload| {
522 ecx.handle_ice();
523 panic::resume_unwind(panic_payload)
524 });
525 let Err(err) = res.report_err();
528
529 let (return_code, leak_check) = report_error(&ecx, err)?;
531
532 if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref()
534 && let Err(error) = genmc_ctx.handle_execution_end(&ecx)
535 {
536 tcx.dcx().err(format!("GenMC returned an error: \"{error}\""));
538 return None;
539 }
540
541 if leak_check && !ignore_leaks {
545 if !ecx.have_all_terminated() {
547 tcx.dcx().err("the main thread terminated without waiting for all remaining threads");
548 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
549 return None;
550 }
551 info!("Additional static roots: {:?}", ecx.machine.static_roots);
553 let leaks = ecx.take_leaked_allocations(|ecx| &ecx.machine.static_roots);
554 if !leaks.is_empty() {
555 report_leaks(&ecx, leaks);
556 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
557 return None;
560 }
561 }
562 Some(return_code)
563}
564
565fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
576where
577 I: Iterator<Item = T>,
578 T: AsRef<str>,
579{
580 let mut cmd = {
582 let arg0 = if let Some(arg0) = args.next() {
583 arg0
584 } else {
585 return vec![0];
586 };
587 let arg0 = arg0.as_ref();
588 if arg0.contains('"') {
589 panic!("argv[0] cannot contain a doublequote (\") character");
590 } else {
591 let mut s = String::new();
593 s.push('"');
594 s.push_str(arg0);
595 s.push('"');
596 s
597 }
598 };
599
600 for arg in args {
602 let arg = arg.as_ref();
603 cmd.push(' ');
604 if arg.is_empty() {
605 cmd.push_str("\"\"");
606 } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
607 cmd.push_str(arg);
609 } else {
610 cmd.push('"');
617 let mut chars = arg.chars().peekable();
618 loop {
619 let mut nslashes = 0;
620 while let Some(&'\\') = chars.peek() {
621 chars.next();
622 nslashes += 1;
623 }
624
625 match chars.next() {
626 Some('"') => {
627 cmd.extend(iter::repeat_n('\\', nslashes * 2 + 1));
628 cmd.push('"');
629 }
630 Some(c) => {
631 cmd.extend(iter::repeat_n('\\', nslashes));
632 cmd.push(c);
633 }
634 None => {
635 cmd.extend(iter::repeat_n('\\', nslashes * 2));
636 break;
637 }
638 }
639 }
640 cmd.push('"');
641 }
642 }
643
644 if cmd.contains('\0') {
645 panic!("interior null in command line arguments");
646 }
647 cmd.encode_utf16().chain(iter::once(0)).collect()
648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653 #[test]
654 #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
655 fn windows_argv0_panic_on_quote() {
656 args_to_utf16_command_string(["\""].iter());
657 }
658 #[test]
659 fn windows_argv0_no_escape() {
660 let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
662 [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
663 ));
664 assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
665 }
666}