Skip to main content

miri/
eval.rs

1//! Main evaluator loop and setting up the initial stack frame.
2
3use 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
36/// Finds the entry point Miri should execute.
37///
38/// Public because this is used by Priroda.
39pub 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    // Look for a symbol in the local crate named `miri_start`, and treat that as the entry point.
44    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
86/// When the program exits, we will yield to any other thread that is ready to execute.
87/// But we must only do that a finite number of times, or a background thread running `loop {}`
88/// will hang the program.
89const THREAD_YIELDS_AT_EXIT: u32 = 256;
90
91/// Configuration needed to spawn a Miri instance.
92#[derive(Clone)]
93pub struct MiriConfig {
94    /// The host environment snapshot to use as basis for what is provided to the interpreted program.
95    /// (This is still subject to isolation as well as `forwarded_env_vars`.)
96    pub env: Vec<(OsString, OsString)>,
97    /// Determine if validity checking is enabled.
98    pub validation: ValidationMode,
99    /// Determines if Stacked Borrows or Tree Borrows is enabled.
100    pub borrow_tracker: Option<BorrowTrackerMethod>,
101    /// Controls alignment checking.
102    pub check_alignment: AlignmentCheck,
103    /// Action for an op requiring communication with the host.
104    pub isolated_op: IsolatedOp,
105    /// Determines if memory leaks should be ignored.
106    pub ignore_leaks: bool,
107    /// Environment variables that should always be forwarded from the host.
108    pub forwarded_env_vars: Vec<String>,
109    /// Additional environment variables that should be set in the interpreted program.
110    pub set_env_vars: FxHashMap<String, String>,
111    /// Command-line arguments passed to the interpreted program.
112    pub args: Vec<String>,
113    /// The binary we pretend to be.
114    pub current_exe: Option<PathBuf>,
115    /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
116    pub seed: Option<u64>,
117    /// The stacked borrows pointer ids to report about.
118    pub tracked_pointer_tags: FxHashSet<BorTag>,
119    /// The allocation ids to report about.
120    pub tracked_alloc_ids: FxHashSet<AllocId>,
121    /// For the tracked alloc ids, also report read/write accesses.
122    pub track_alloc_accesses: bool,
123    /// Determine if data race detection should be enabled.
124    pub data_race_detector: bool,
125    /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled.
126    pub weak_memory_emulation: bool,
127    /// Determine if we are running in GenMC mode and with which settings. In GenMC mode, Miri will explore multiple concurrent executions of the given program.
128    pub genmc_config: Option<GenmcConfig>,
129    /// Track when an outdated (weak memory) load happens.
130    pub track_outdated_loads: bool,
131    /// Rate of spurious failures for compare_exchange_weak atomic operations,
132    /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
133    pub cmpxchg_weak_failure_rate: f64,
134    /// If `Some`, enable the `measureme` profiler, writing results to a file
135    /// with the specified prefix.
136    pub measureme_out: Option<String>,
137    /// Which style to use for printing backtraces.
138    pub backtrace_style: BacktraceStyle,
139    /// Which provenance to use for int2ptr casts.
140    pub provenance_mode: ProvenanceMode,
141    /// Whether to ignore any output by the program. This is helpful when debugging miri
142    /// as its messages don't get intermingled with the program messages.
143    pub mute_stdout_stderr: bool,
144    /// The probability of the active thread being preempted at the end of each basic block.
145    pub preemption_rate: f64,
146    /// Report the current instruction being executed every N basic blocks.
147    pub report_progress: Option<u32>,
148    /// The location of the shared object files to load when calling external functions
149    pub native_lib: Vec<PathBuf>,
150    /// Whether to enable the new native lib tracing system.
151    pub native_lib_enable_tracing: bool,
152    /// Run a garbage collector for BorTags every N basic blocks.
153    pub gc_interval: u32,
154    /// The number of CPUs to be reported by miri.
155    pub num_cpus: u32,
156    /// Requires Miri to emulate pages of a certain size.
157    pub page_size: Option<u64>,
158    /// Whether to collect a backtrace when each allocation is created, just in case it leaks.
159    pub collect_leak_backtraces: bool,
160    /// Probability for address reuse.
161    pub address_reuse_rate: f64,
162    /// Probability for address reuse across threads.
163    pub address_reuse_cross_thread_rate: f64,
164    /// Round Robin scheduling with no preemption.
165    pub fixed_scheduling: bool,
166    /// Whether floating-point operations can behave non-deterministically.
167    pub float_nondet: bool,
168    /// Whether floating-point operations can have a non-deterministic rounding error.
169    pub float_rounding_error: FloatRoundingErrorMode,
170    /// Whether Miri artificially introduces short reads/writes on file descriptors.
171    pub short_fd_operations: bool,
172    /// A list of crates that are considered user-relevant.
173    pub user_relevant_crates: Vec<String>,
174    /// Whether to error when encountering an unknown weak symbol, `dlsym`, or syscall.
175    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, // 80%
200            measureme_out: None,
201            backtrace_style: BacktraceStyle::Short,
202            provenance_mode: ProvenanceMode::Default,
203            mute_stdout_stderr: false,
204            preemption_rate: 0.01, // 1%
205            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/// A state machine that's run when the program is exiting.
231#[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 => {} // just keep going
259                    Poll::Ready(()) => {
260                        if ecx.machine.data_race.as_genmc_ref().is_some() {
261                            // In GenMC mode, we don't yield at the end of the main thread. Instead,
262                            // the `GenmcCtx` will ensure that unfinished threads get a chance to
263                            // run at this point.
264                            self.state = Done;
265                        } else {
266                            // Give background threads a chance to finish by yielding the main
267                            // thread a couple of times.
268                            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                // Terminate this thread in the scheduler.
282                ecx.terminate_active_thread(/* for_exit */ true)?;
283
284                // We cannot come back.
285                self.state = Unreachable;
286
287                // In GenMC mode, we do not immediately stop execution on exit.
288                if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref() {
289                    // If there's no error, execution will continue (on another thread).
290                    genmc_ctx.handle_exit(
291                        ecx.machine.threads.active_thread(),
292                        self.exit_code,
293                        self.exit_type,
294                    )?;
295                } else {
296                    // Stop interpreter loop.
297                    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/// The state of the main thread. Implementation detail of `on_main_stack_empty`.
310#[derive(Debug)]
311enum MainThreadState<'tcx> {
312    GlobalCtors {
313        ctor_state: global_ctor::GlobalCtorState<'tcx>,
314        /// The main function to call.
315        entry_id: DefId,
316        entry_type: MiriEntryFnType,
317        /// Arguments passed to `main`.
318        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 => {} // just keep going
335                    Poll::Ready(()) => {
336                        call_main(ecx, *entry_id, *entry_type, argc.clone(), argv.clone())?;
337                        *self = Running;
338                    }
339                }
340            }
341            Running => {
342                // Main code is done, the program is exiting.
343
344                // This is like a call to `exit`. Ensure `exit` gets called at most once.
345                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                // Figure out exit code.
351                let ret_place = ecx.machine.main_fn_ret_place.clone().unwrap();
352                let exit_code = ecx.read_target_isize(&ret_place)?;
353                // Rust uses `isize` but the underlying type of an exit code is `i32`.
354                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                // This is a sink state, we stay here forever.
363                return state.on_stack_empty(ecx);
364            }
365        }
366        interp_ok(Poll::Pending)
367    }
368}
369
370/// Returns a freshly created `InterpCx`.
371/// Public because this is also used by `priroda`.
372pub 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    // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore. However,
389    // if the current crate is #![no_core] it's fine to be missing the usual items from libcore.
390    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    // Compute argc and argv from `config.args`.
405    let argc =
406        ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
407    let argv = {
408        // Put each argument in memory, collect pointers.
409        let mut argvs =
410            Vec::<Immediate<Provenance>>::with_capacity(config.args.len().strict_add(1));
411        for arg in config.args.iter() {
412            // Make space for `0` terminator.
413            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        // Add trailing null.
422        argvs.push(Immediate::Scalar(Scalar::null_ptr(&ecx)));
423        // Make an array with all these pointers, in the Miri memory.
424        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        // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`, and for the GC to see them.
435        {
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        // Store command line as UTF-16 for Windows `GetCommandLineW`.
449        if tcx.sess.target.os == Os::Windows {
450            // Construct a command string with all the arguments.
451            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            // Store the UTF-16 string. We just allocated so we know the bounds are fine.
459            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    // Some parts of initialization require a full `InterpCx`.
471    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        // Cannot capture anything GC-relevant here.
481        // `argc` and `argv` *are* GC_relevant, but they also get stored in `machine.argc` and
482        // `machine.argv` so we are good.
483        Box::new(move |m| main_thread_state.on_main_stack_empty(m))
484    })?;
485
486    interp_ok(ecx)
487}
488
489// Call the entry function.
490fn 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    // Setup first stack frame.
500    let entry_instance = ty::Instance::mono(tcx, entry_id);
501
502    // Return place (in static memory so that it does not count as leak).
503    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    // Call start function.
507    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            // Always using DEFAULT is okay since we don't support signals in Miri anyway.
528            // (This means we are effectively ignoring `-Zon-broken-pipe`.)
529            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
561/// Evaluates the entry function specified by `entry_id`.
562/// Returns `Ok(())` if program execution completed with exit code 0.
563/// Returns `Err(code)` if an evaluation error occurred or the program returned a non-0 exit code.
564pub 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    // Copy setting before we move `config`.
572    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    // Perform the main execution.
584    let res: thread::Result<InterpResult<'_, !>> =
585        panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
586    let res = res.unwrap_or_else(|panic_payload| {
587        // rustc "handles" some errors by unwinding with FatalErrorMarker
588        // (after emitting suitable diagnostics), so do not treat those as ICEs.
589        if !panic_payload.is::<FatalErrorMarker>() {
590            ecx.handle_ice();
591        }
592        panic::resume_unwind(panic_payload)
593    });
594    // Obtain the result of the execution. This is always an `Err`, but that doesn't necessarily
595    // indicate an error.
596    let Err(res) = res.report_err();
597
598    // Error reporting: if we survive all checks, we return the exit code the program gave us.
599    'miri_error: {
600        // Show diagnostic, if any.
601        let Some((return_code, leak_check)) = report_result(&ecx, res) else {
602            break 'miri_error;
603        };
604
605        // If we get here there was no fatal error -- yet.
606        // Possibly check for memory leaks.
607        if leak_check && !ignore_leaks {
608            // Check for thread leaks.
609            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            // Check for memory leaks.
616            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                // Ignore the provided return code - let the reported error
622                // determine the return code.
623                break 'miri_error;
624            }
625        }
626
627        // The interpreter has not reported an error.
628        // (There could still be errors in the session if there are other interpreters.)
629        return match NonZeroI32::new(return_code) {
630            None => Ok(()),
631            Some(return_code) => Err(return_code),
632        };
633    }
634
635    // The interpreter reported an error.
636    assert!(tcx.dcx().has_errors().is_some());
637    Err(NonZeroI32::new(rustc_driver::EXIT_FAILURE).unwrap())
638}
639
640/// Turns an array of arguments into a Windows command line string.
641///
642/// The string will be UTF-16 encoded and NUL terminated.
643///
644/// Panics if the zeroth argument contains the `"` character because doublequotes
645/// in `argv[0]` cannot be encoded using the standard command line parsing rules.
646///
647/// Further reading:
648/// * [Parsing C++ command-line arguments](https://docs.microsoft.com/en-us/cpp/cpp/main-function-command-line-args?view=msvc-160#parsing-c-command-line-arguments)
649/// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
650fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
651where
652    I: Iterator<Item = T>,
653    T: AsRef<str>,
654{
655    // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
656    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            // Always surround argv[0] with quotes.
665            let mut s = String::new();
666            s.push('"');
667            s.push_str(arg0);
668            s.push('"');
669            s
670        }
671    };
672
673    // Build the other arguments.
674    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            // No quote, tab, or space -- no escaping required.
681            cmd.push_str(arg);
682        } else {
683            // Spaces and tabs are escaped by surrounding them in quotes.
684            // Quotes are themselves escaped by using backslashes when in a
685            // quoted block.
686            // Backslashes only need to be escaped when one or more are directly
687            // followed by a quote. Otherwise they are taken literally.
688
689            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        // Ensure that a trailing backslash in argv[0] is not escaped.
734        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}