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