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