1use std::ffi::{OsStr, OsString};
4use std::num::NonZeroI32;
5use std::panic::{self, AssertUnwindSafe};
6use std::path::PathBuf;
7use std::rc::Rc;
8use std::task::Poll;
9use std::{iter, mem, thread};
10
11use rustc_abi::ExternAbi;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13use rustc_errors::FatalErrorMarker;
14use rustc_hir::def::Namespace;
15use rustc_hir::def_id::{DefId, LOCAL_CRATE};
16use rustc_hir_analysis::check::check_function_signature;
17use rustc_middle::middle::exported_symbols::ExportedSymbol;
18use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
19use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutCx};
20use rustc_middle::ty::{self, Ty, TyCtxt};
21use rustc_session::config::EntryFnType;
22use rustc_target::spec::Os;
23
24use crate::concurrency::GenmcCtx;
25use crate::diagnostics::report_leaks;
26use crate::helpers::is_no_core;
27use crate::shims::{global_ctor, tls};
28use crate::*;
29
30#[derive(Copy, Clone, Debug)]
31pub enum MiriEntryFnType {
32 MiriStart,
33 Rustc(EntryFnType),
34}
35
36pub fn entry_fn(tcx: TyCtxt<'_>) -> (DefId, MiriEntryFnType) {
40 if let Some((def_id, entry_type)) = tcx.entry_fn(()) {
41 return (def_id, MiriEntryFnType::Rustc(entry_type));
42 }
43 let sym = tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().find_map(|(sym, _)| {
45 if sym.symbol_name_for_local_instance(tcx).name == "miri_start" { Some(sym) } else { None }
46 });
47 if let Some(ExportedSymbol::NonGeneric(id)) = sym {
48 let start_def_id = id.expect_local();
49 let start_span = tcx.def_span(start_def_id);
50
51 let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig_safe_rust_abi(
52 [tcx.types.isize, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))],
53 tcx.types.isize,
54 ));
55
56 let correct_func_sig = check_function_signature(
57 tcx,
58 ObligationCause::new(start_span, start_def_id, ObligationCauseCode::Misc),
59 *id,
60 expected_sig,
61 )
62 .is_ok();
63
64 if correct_func_sig {
65 (*id, MiriEntryFnType::MiriStart)
66 } else {
67 tcx.dcx().fatal(
68 "`miri_start` must have the following signature:\n\
69 fn miri_start(argc: isize, argv: *const *const u8) -> isize",
70 );
71 }
72 } else {
73 tcx.dcx().fatal(
74 "Miri can only run programs that have a main function.\n\
75 Alternatively, you can export a `miri_start` function:\n\
76 \n\
77 #[cfg(miri)]\n\
78 #[unsafe(no_mangle)]\n\
79 fn miri_start(argc: isize, argv: *const *const u8) -> isize {\
80 \n // Call the actual start function that your project implements, based on your target's conventions.\n\
81 }"
82 );
83 }
84}
85
86const THREAD_YIELDS_AT_EXIT: u32 = 256;
90
91#[derive(Clone)]
93pub struct MiriConfig {
94 pub env: Vec<(OsString, OsString)>,
97 pub validation: ValidationMode,
99 pub borrow_tracker: Option<BorrowTrackerMethod>,
101 pub check_alignment: AlignmentCheck,
103 pub isolated_op: IsolatedOp,
105 pub ignore_leaks: bool,
107 pub forwarded_env_vars: Vec<String>,
109 pub set_env_vars: FxHashMap<String, String>,
111 pub args: Vec<String>,
113 pub current_exe: Option<PathBuf>,
115 pub seed: Option<u64>,
117 pub tracked_pointer_tags: FxHashSet<BorTag>,
119 pub tracked_alloc_ids: FxHashSet<AllocId>,
121 pub track_alloc_accesses: bool,
123 pub data_race_detector: bool,
125 pub weak_memory_emulation: bool,
127 pub genmc_config: Option<GenmcConfig>,
129 pub track_outdated_loads: bool,
131 pub cmpxchg_weak_failure_rate: f64,
134 pub measureme_out: Option<String>,
137 pub backtrace_style: BacktraceStyle,
139 pub provenance_mode: ProvenanceMode,
141 pub mute_stdout_stderr: bool,
144 pub preemption_rate: f64,
146 pub report_progress: Option<u32>,
148 pub native_lib: Vec<PathBuf>,
150 pub native_lib_enable_tracing: bool,
152 pub gc_interval: u32,
154 pub num_cpus: u32,
156 pub page_size: Option<u64>,
158 pub collect_leak_backtraces: bool,
160 pub address_reuse_rate: f64,
162 pub address_reuse_cross_thread_rate: f64,
164 pub fixed_scheduling: bool,
166 pub float_nondet: bool,
168 pub float_rounding_error: FloatRoundingErrorMode,
170 pub short_fd_operations: bool,
172 pub user_relevant_crates: Vec<String>,
174 pub error_on_unknown_optional_symbols: bool,
176}
177
178impl Default for MiriConfig {
179 fn default() -> MiriConfig {
180 MiriConfig {
181 env: vec![],
182 validation: ValidationMode::Shallow,
183 borrow_tracker: Some(BorrowTrackerMethod::StackedBorrows),
184 check_alignment: AlignmentCheck::Int,
185 isolated_op: IsolatedOp::Reject(RejectOpWith::Abort),
186 ignore_leaks: false,
187 forwarded_env_vars: vec![],
188 set_env_vars: FxHashMap::default(),
189 args: vec![],
190 current_exe: None,
191 seed: None,
192 tracked_pointer_tags: FxHashSet::default(),
193 tracked_alloc_ids: FxHashSet::default(),
194 track_alloc_accesses: false,
195 data_race_detector: true,
196 weak_memory_emulation: true,
197 genmc_config: None,
198 track_outdated_loads: false,
199 cmpxchg_weak_failure_rate: 0.8, measureme_out: None,
201 backtrace_style: BacktraceStyle::Short,
202 provenance_mode: ProvenanceMode::Default,
203 mute_stdout_stderr: false,
204 preemption_rate: 0.01, report_progress: None,
206 native_lib: vec![],
207 native_lib_enable_tracing: false,
208 gc_interval: 10_000,
209 num_cpus: 1,
210 page_size: None,
211 collect_leak_backtraces: true,
212 address_reuse_rate: 0.5,
213 address_reuse_cross_thread_rate: 0.1,
214 fixed_scheduling: false,
215 float_nondet: true,
216 float_rounding_error: FloatRoundingErrorMode::Random,
217 short_fd_operations: true,
218 user_relevant_crates: vec![],
219 error_on_unknown_optional_symbols: false,
220 }
221 }
222}
223
224#[derive(Clone, Copy, Debug)]
225pub enum ExitType {
226 MainThreadFinish,
227 ExitCalled,
228}
229
230#[derive(Debug)]
232pub struct ProgramExitHandler<'tcx> {
233 state: ProgramExitState<'tcx>,
234 exit_code: i32,
235 exit_type: ExitType,
236}
237#[derive(Debug)]
238enum ProgramExitState<'tcx> {
239 TlsDtors(tls::TlsDtorsState<'tcx>),
240 Yield { remaining: u32 },
241 Done,
242 Unreachable,
243}
244
245impl<'tcx> ProgramExitHandler<'tcx> {
246 pub fn new(exit_code: i32, exit_type: ExitType) -> Self {
247 Self {
248 state: ProgramExitState::TlsDtors(tls::TlsDtorsState::new_for_exit()),
249 exit_code,
250 exit_type,
251 }
252 }
253 pub fn on_stack_empty(&mut self, ecx: &mut MiriInterpCx<'tcx>) -> InterpResult<'tcx, Poll<()>> {
254 use ProgramExitState::*;
255 match &mut self.state {
256 TlsDtors(state) =>
257 match state.on_stack_empty(ecx)? {
258 Poll::Pending => {} Poll::Ready(()) => {
260 if ecx.machine.data_race.as_genmc_ref().is_some() {
261 self.state = Done;
265 } else {
266 self.state = Yield { remaining: THREAD_YIELDS_AT_EXIT };
269 }
270 }
271 },
272 Yield { remaining } =>
273 match remaining.checked_sub(1) {
274 None => self.state = Done,
275 Some(new_remaining) => {
276 *remaining = new_remaining;
277 ecx.yield_active_thread();
278 }
279 },
280 Done => {
281 ecx.terminate_active_thread(true)?;
283
284 self.state = Unreachable;
286
287 if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() {
289 genmc_ctx.handle_exit(
291 ecx.machine.threads.active_thread(),
292 self.exit_code,
293 self.exit_type,
294 )?;
295 } else {
296 throw_machine_stop!(TerminationInfo::Exit {
298 exit_code: self.exit_code,
299 leak_check: matches!(self.exit_type, ExitType::MainThreadFinish),
300 });
301 }
302 }
303 Unreachable => unreachable!(),
304 }
305 interp_ok(Poll::Pending)
306 }
307}
308
309#[derive(Debug)]
311enum MainThreadState<'tcx> {
312 GlobalCtors {
313 ctor_state: global_ctor::GlobalCtorState<'tcx>,
314 entry_id: DefId,
316 entry_type: MiriEntryFnType,
317 argc: ImmTy<'tcx>,
319 argv: ImmTy<'tcx>,
320 },
321 Running,
322 Exiting(ProgramExitHandler<'tcx>),
323}
324
325impl<'tcx> MainThreadState<'tcx> {
326 fn on_main_stack_empty(
327 &mut self,
328 ecx: &mut MiriInterpCx<'tcx>,
329 ) -> InterpResult<'tcx, Poll<()>> {
330 use MainThreadState::*;
331 match self {
332 GlobalCtors { ctor_state, entry_id, entry_type, argc, argv } => {
333 match ctor_state.on_stack_empty(ecx)? {
334 Poll::Pending => {} Poll::Ready(()) => {
336 call_main(ecx, *entry_id, *entry_type, argc.clone(), argv.clone())?;
337 *self = Running;
338 }
339 }
340 }
341 Running => {
342 let old_exit = mem::replace(&mut ecx.machine.exit_called, true);
346 if old_exit {
347 throw_ub_format!("`exit` called more than once");
348 }
349
350 let ret_place = ecx.machine.main_fn_ret_place.clone().unwrap();
352 let exit_code = ecx.read_target_isize(&ret_place)?;
353 let Ok(exit_code) = i32::try_from(exit_code) else {
355 throw_ub_format!(
356 "lang_start item return an exit code that does not fit into `i32`"
357 );
358 };
359 *self = Exiting(ProgramExitHandler::new(exit_code, ExitType::MainThreadFinish));
360 }
361 Exiting(state) => {
362 return state.on_stack_empty(ecx);
364 }
365 }
366 interp_ok(Poll::Pending)
367 }
368}
369
370pub fn create_ecx<'tcx>(
373 tcx: TyCtxt<'tcx>,
374 entry_id: DefId,
375 entry_type: MiriEntryFnType,
376 config: &MiriConfig,
377 genmc_ctx: Option<Rc<GenmcCtx>>,
378) -> InterpResult<'tcx, InterpCx<'tcx, MiriMachine<'tcx>>> {
379 let typing_env = ty::TypingEnv::fully_monomorphized();
380 let layout_cx = LayoutCx::new(tcx, typing_env);
381 let mut ecx = InterpCx::new(
382 tcx,
383 rustc_span::DUMMY_SP,
384 typing_env,
385 MiriMachine::new(config, layout_cx, genmc_ctx),
386 );
387
388 if !is_no_core(tcx) {
391 let sentinel = helpers::try_resolve_path(
392 tcx,
393 &["core", "ascii", "escape_default"],
394 Namespace::ValueNS,
395 );
396 if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
397 tcx.dcx().fatal(
398 "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing.\n\
399 Note that directly invoking the `miri` binary is not supported; please use `cargo miri` instead."
400 );
401 }
402 }
403
404 let argc =
406 ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
407 let argv = {
408 let mut argvs =
410 Vec::<Immediate<Provenance>>::with_capacity(config.args.len().strict_add(1));
411 for arg in config.args.iter() {
412 let size = u64::try_from(arg.len()).unwrap().strict_add(1);
414 let arg_type = Ty::new_array(tcx, tcx.types.u8, size);
415 let arg_place =
416 ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
417 ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr(), size)?;
418 ecx.mark_immutable(&arg_place);
419 argvs.push(arg_place.to_ref(&ecx));
420 }
421 argvs.push(Immediate::Scalar(Scalar::null_ptr(&ecx)));
423 let u8_ptr_type = Ty::new_imm_ptr(tcx, tcx.types.u8);
425 let u8_ptr_ptr_type = Ty::new_imm_ptr(tcx, u8_ptr_type);
426 let argvs_layout =
427 ecx.layout_of(Ty::new_array(tcx, u8_ptr_type, u64::try_from(argvs.len()).unwrap()))?;
428 let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
429 for (arg, idx) in argvs.into_iter().zip(0..) {
430 let place = ecx.project_index(&argvs_place, idx)?;
431 ecx.write_immediate(arg, &place)?;
432 }
433 ecx.mark_immutable(&argvs_place);
434 {
436 let argc_place =
437 ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
438 ecx.write_immediate(*argc, &argc_place)?;
439 ecx.mark_immutable(&argc_place);
440 ecx.machine.argc = Some(argc_place.ptr());
441
442 let argv_place =
443 ecx.allocate(ecx.layout_of(u8_ptr_ptr_type)?, MiriMemoryKind::Machine.into())?;
444 ecx.write_pointer(argvs_place.ptr(), &argv_place)?;
445 ecx.mark_immutable(&argv_place);
446 ecx.machine.argv = Some(argv_place.ptr());
447 }
448 if tcx.sess.target.os == Os::Windows {
450 let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
452
453 let cmd_type =
454 Ty::new_array(tcx, tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
455 let cmd_place =
456 ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
457 ecx.machine.cmd_line = Some(cmd_place.ptr());
458 for (&c, idx) in cmd_utf16.iter().zip(0..) {
460 let place = ecx.project_index(&cmd_place, idx)?;
461 ecx.write_scalar(Scalar::from_u16(c), &place)?;
462 }
463 ecx.mark_immutable(&cmd_place);
464 }
465 let imm = argvs_place.to_ref(&ecx);
466 let layout = ecx.layout_of(u8_ptr_ptr_type)?;
467 ImmTy::from_immediate(imm, layout)
468 };
469
470 MiriMachine::late_init(&mut ecx, config, {
472 let mut main_thread_state = MainThreadState::GlobalCtors {
473 entry_id,
474 entry_type,
475 argc,
476 argv,
477 ctor_state: global_ctor::GlobalCtorState::default(),
478 };
479
480 Box::new(move |m| main_thread_state.on_main_stack_empty(m))
484 })?;
485
486 interp_ok(ecx)
487}
488
489fn call_main<'tcx>(
491 ecx: &mut MiriInterpCx<'tcx>,
492 entry_id: DefId,
493 entry_type: MiriEntryFnType,
494 argc: ImmTy<'tcx>,
495 argv: ImmTy<'tcx>,
496) -> InterpResult<'tcx, ()> {
497 let tcx = ecx.tcx();
498
499 let entry_instance = ty::Instance::mono(tcx, entry_id);
501
502 let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
504 ecx.machine.main_fn_ret_place = Some(ret_place.clone());
505
506 match entry_type {
508 MiriEntryFnType::Rustc(EntryFnType::Main { .. }) => {
509 let entry_sig = tcx.fn_sig(entry_id).no_bound_vars().unwrap();
510 let main_ret_ty = entry_sig.output();
511 let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
512
513 let start_id = tcx.lang_items().start_fn().unwrap_or_else(|| {
514 tcx.dcx().fatal("could not find start lang item");
515 });
516 let start_instance = ty::Instance::try_resolve(
517 tcx,
518 ecx.typing_env(),
519 start_id,
520 tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]),
521 )
522 .unwrap()
523 .unwrap();
524
525 let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance));
526
527 let sigpipe = rustc_session::config::sigpipe::DEFAULT;
530
531 ecx.call_function(
532 start_instance,
533 ExternAbi::Rust,
534 &[
535 ImmTy::from_scalar(
536 Scalar::from_pointer(main_ptr, ecx),
537 ecx.layout_of(Ty::new_fn_ptr(tcx, entry_sig)).unwrap(),
538 ),
539 argc,
540 argv,
541 ImmTy::from_uint(sigpipe, ecx.machine.layouts.u8),
542 ],
543 Some(&ret_place),
544 ReturnContinuation::Stop { cleanup: true },
545 )?;
546 }
547 MiriEntryFnType::MiriStart => {
548 ecx.call_function(
549 entry_instance,
550 ExternAbi::Rust,
551 &[argc, argv],
552 Some(&ret_place),
553 ReturnContinuation::Stop { cleanup: true },
554 )?;
555 }
556 }
557
558 interp_ok(())
559}
560
561pub fn eval_entry<'tcx>(
565 tcx: TyCtxt<'tcx>,
566 entry_id: DefId,
567 entry_type: MiriEntryFnType,
568 config: &MiriConfig,
569 genmc_ctx: Option<Rc<GenmcCtx>>,
570) -> Result<(), NonZeroI32> {
571 let ignore_leaks = config.ignore_leaks;
573
574 let mut ecx = match create_ecx(tcx, entry_id, entry_type, config, genmc_ctx).report_err() {
575 Ok(v) => v,
576 Err(err) => {
577 let (kind, backtrace) = err.into_parts();
578 backtrace.print_backtrace();
579 panic!("Miri initialization error: {kind:?}")
580 }
581 };
582
583 let res: thread::Result<InterpResult<'_, !>> =
585 panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
586 let res = res.unwrap_or_else(|panic_payload| {
587 if !panic_payload.is::<FatalErrorMarker>() {
590 ecx.handle_ice();
591 }
592 panic::resume_unwind(panic_payload)
593 });
594 let Err(res) = res.report_err();
597
598 'miri_error: {
600 let Some((return_code, leak_check)) = report_result(&ecx, res) else {
602 break 'miri_error;
603 };
604
605 if leak_check && !ignore_leaks {
608 if !ecx.have_all_terminated() {
610 tcx.dcx()
611 .err("the main thread terminated without waiting for all remaining threads");
612 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
613 break 'miri_error;
614 }
615 info!("Additional static roots: {:?}", ecx.machine.static_roots);
617 let leaks = ecx.take_leaked_allocations(|ecx| &ecx.machine.static_roots);
618 if !leaks.is_empty() {
619 report_leaks(&ecx, leaks);
620 tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
621 break 'miri_error;
624 }
625 }
626
627 return match NonZeroI32::new(return_code) {
630 None => Ok(()),
631 Some(return_code) => Err(return_code),
632 };
633 }
634
635 assert!(tcx.dcx().has_errors().is_some());
637 Err(NonZeroI32::new(rustc_driver::EXIT_FAILURE).unwrap())
638}
639
640fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
651where
652 I: Iterator<Item = T>,
653 T: AsRef<str>,
654{
655 let mut cmd = {
657 let Some(arg0) = args.next() else {
658 return vec![0];
659 };
660 let arg0 = arg0.as_ref();
661 if arg0.contains('"') {
662 panic!("argv[0] cannot contain a doublequote (\") character");
663 } else {
664 let mut s = String::new();
666 s.push('"');
667 s.push_str(arg0);
668 s.push('"');
669 s
670 }
671 };
672
673 for arg in args {
675 let arg = arg.as_ref();
676 cmd.push(' ');
677 if arg.is_empty() {
678 cmd.push_str("\"\"");
679 } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
680 cmd.push_str(arg);
682 } else {
683 cmd.push('"');
690 let mut chars = arg.chars().peekable();
691 loop {
692 let mut nslashes = 0;
693 while let Some(&'\\') = chars.peek() {
694 chars.next();
695 nslashes += 1;
696 }
697
698 match chars.next() {
699 Some('"') => {
700 cmd.extend(iter::repeat_n('\\', nslashes * 2 + 1));
701 cmd.push('"');
702 }
703 Some(c) => {
704 cmd.extend(iter::repeat_n('\\', nslashes));
705 cmd.push(c);
706 }
707 None => {
708 cmd.extend(iter::repeat_n('\\', nslashes * 2));
709 break;
710 }
711 }
712 }
713 cmd.push('"');
714 }
715 }
716
717 if cmd.contains('\0') {
718 panic!("interior null in command line arguments");
719 }
720 cmd.encode_utf16().chain(iter::once(0)).collect()
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726 #[test]
727 #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
728 fn windows_argv0_panic_on_quote() {
729 args_to_utf16_command_string(["\""].iter());
730 }
731 #[test]
732 fn windows_argv0_no_escape() {
733 let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
735 [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
736 ));
737 assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
738 }
739}