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, 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::concurrency::thread::TlsAllocAction;
26use crate::diagnostics::report_leaks;
27use crate::helpers::is_no_core;
28use crate::shims::{global_ctor, tls};
29use crate::*;
30
31#[derive(Copy, Clone, Debug)]
32pub enum MiriEntryFnType {
33    MiriStart,
34    Rustc(EntryFnType),
35}
36
37/// Finds the entry point Miri should execute.
38///
39/// Public because this is used by Priroda.
40pub fn entry_fn(tcx: TyCtxt<'_>) -> (DefId, MiriEntryFnType) {
41    if let Some((def_id, entry_type)) = tcx.entry_fn(()) {
42        return (def_id, MiriEntryFnType::Rustc(entry_type));
43    }
44    // Look for a symbol in the local crate named `miri_start`, and treat that as the entry point.
45    let sym = tcx.exported_non_generic_symbols(LOCAL_CRATE).iter().find_map(|(sym, _)| {
46        if sym.symbol_name_for_local_instance(tcx).name == "miri_start" { Some(sym) } else { None }
47    });
48    if let Some(ExportedSymbol::NonGeneric(id)) = sym {
49        let start_def_id = id.expect_local();
50        let start_span = tcx.def_span(start_def_id);
51
52        let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig_safe_rust_abi(
53            [tcx.types.isize, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))],
54            tcx.types.isize,
55        ));
56
57        let correct_func_sig = check_function_signature(
58            tcx,
59            ObligationCause::new(start_span, start_def_id, ObligationCauseCode::Misc),
60            *id,
61            expected_sig,
62        )
63        .is_ok();
64
65        if correct_func_sig {
66            (*id, MiriEntryFnType::MiriStart)
67        } else {
68            tcx.dcx().fatal(
69                "`miri_start` must have the following signature:\n\
70                fn miri_start(argc: isize, argv: *const *const u8) -> isize",
71            );
72        }
73    } else {
74        tcx.dcx().fatal(
75            "Miri can only run programs that have a main function.\n\
76            Alternatively, you can export a `miri_start` function:\n\
77            \n\
78            #[cfg(miri)]\n\
79            #[unsafe(no_mangle)]\n\
80            fn miri_start(argc: isize, argv: *const *const u8) -> isize {\
81            \n    // Call the actual start function that your project implements, based on your target's conventions.\n\
82            }"
83        );
84    }
85}
86
87/// When the main thread would exit, we will yield to any other thread that is ready to execute.
88/// But we must only do that a finite number of times, or a background thread running `loop {}`
89/// will hang the program.
90const MAIN_THREAD_YIELDS_AT_SHUTDOWN: u32 = 256;
91
92/// Configuration needed to spawn a Miri instance.
93#[derive(Clone)]
94pub struct MiriConfig {
95    /// The host environment snapshot to use as basis for what is provided to the interpreted program.
96    /// (This is still subject to isolation as well as `forwarded_env_vars`.)
97    pub env: Vec<(OsString, OsString)>,
98    /// Determine if validity checking is enabled.
99    pub validation: ValidationMode,
100    /// Determines if Stacked Borrows or Tree Borrows is enabled.
101    pub borrow_tracker: Option<BorrowTrackerMethod>,
102    /// Controls alignment checking.
103    pub check_alignment: AlignmentCheck,
104    /// Action for an op requiring communication with the host.
105    pub isolated_op: IsolatedOp,
106    /// Determines if memory leaks should be ignored.
107    pub ignore_leaks: bool,
108    /// Environment variables that should always be forwarded from the host.
109    pub forwarded_env_vars: Vec<String>,
110    /// Additional environment variables that should be set in the interpreted program.
111    pub set_env_vars: FxHashMap<String, String>,
112    /// Command-line arguments passed to the interpreted program.
113    pub args: Vec<String>,
114    /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
115    pub seed: Option<u64>,
116    /// The stacked borrows pointer ids to report about.
117    pub tracked_pointer_tags: FxHashSet<BorTag>,
118    /// The allocation ids to report about.
119    pub tracked_alloc_ids: FxHashSet<AllocId>,
120    /// For the tracked alloc ids, also report read/write accesses.
121    pub track_alloc_accesses: bool,
122    /// Determine if data race detection should be enabled.
123    pub data_race_detector: bool,
124    /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled.
125    pub weak_memory_emulation: bool,
126    /// 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.
127    pub genmc_config: Option<GenmcConfig>,
128    /// Track when an outdated (weak memory) load happens.
129    pub track_outdated_loads: bool,
130    /// Rate of spurious failures for compare_exchange_weak atomic operations,
131    /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
132    pub cmpxchg_weak_failure_rate: f64,
133    /// If `Some`, enable the `measureme` profiler, writing results to a file
134    /// with the specified prefix.
135    pub measureme_out: Option<String>,
136    /// Which style to use for printing backtraces.
137    pub backtrace_style: BacktraceStyle,
138    /// Which provenance to use for int2ptr casts.
139    pub provenance_mode: ProvenanceMode,
140    /// Whether to ignore any output by the program. This is helpful when debugging miri
141    /// as its messages don't get intermingled with the program messages.
142    pub mute_stdout_stderr: bool,
143    /// The probability of the active thread being preempted at the end of each basic block.
144    pub preemption_rate: f64,
145    /// Report the current instruction being executed every N basic blocks.
146    pub report_progress: Option<u32>,
147    /// The location of the shared object files to load when calling external functions
148    pub native_lib: Vec<PathBuf>,
149    /// Whether to enable the new native lib tracing system.
150    pub native_lib_enable_tracing: bool,
151    /// Run a garbage collector for BorTags every N basic blocks.
152    pub gc_interval: u32,
153    /// The number of CPUs to be reported by miri.
154    pub num_cpus: u32,
155    /// Requires Miri to emulate pages of a certain size.
156    pub page_size: Option<u64>,
157    /// Whether to collect a backtrace when each allocation is created, just in case it leaks.
158    pub collect_leak_backtraces: bool,
159    /// Probability for address reuse.
160    pub address_reuse_rate: f64,
161    /// Probability for address reuse across threads.
162    pub address_reuse_cross_thread_rate: f64,
163    /// Round Robin scheduling with no preemption.
164    pub fixed_scheduling: bool,
165    /// Whether floating-point operations can behave non-deterministically.
166    pub float_nondet: bool,
167    /// Whether floating-point operations can have a non-deterministic rounding error.
168    pub float_rounding_error: FloatRoundingErrorMode,
169    /// Whether Miri artificially introduces short reads/writes on file descriptors.
170    pub short_fd_operations: bool,
171    /// A list of crates that are considered user-relevant.
172    pub user_relevant_crates: Vec<String>,
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_config: None,
194            track_outdated_loads: false,
195            cmpxchg_weak_failure_rate: 0.8, // 80%
196            measureme_out: None,
197            backtrace_style: BacktraceStyle::Short,
198            provenance_mode: ProvenanceMode::Default,
199            mute_stdout_stderr: false,
200            preemption_rate: 0.01, // 1%
201            report_progress: None,
202            native_lib: vec![],
203            native_lib_enable_tracing: false,
204            gc_interval: 10_000,
205            num_cpus: 1,
206            page_size: None,
207            collect_leak_backtraces: true,
208            address_reuse_rate: 0.5,
209            address_reuse_cross_thread_rate: 0.1,
210            fixed_scheduling: false,
211            float_nondet: true,
212            float_rounding_error: FloatRoundingErrorMode::Random,
213            short_fd_operations: true,
214            user_relevant_crates: vec![],
215        }
216    }
217}
218
219/// The state of the main thread. Implementation detail of `on_main_stack_empty`.
220#[derive(Debug)]
221enum MainThreadState<'tcx> {
222    GlobalCtors {
223        ctor_state: global_ctor::GlobalCtorState<'tcx>,
224        /// The main function to call.
225        entry_id: DefId,
226        entry_type: MiriEntryFnType,
227        /// Arguments passed to `main`.
228        argc: ImmTy<'tcx>,
229        argv: ImmTy<'tcx>,
230    },
231    Running,
232    TlsDtors(tls::TlsDtorsState<'tcx>),
233    Yield {
234        remaining: u32,
235    },
236    Done,
237}
238
239impl<'tcx> MainThreadState<'tcx> {
240    fn on_main_stack_empty(
241        &mut self,
242        this: &mut MiriInterpCx<'tcx>,
243    ) -> InterpResult<'tcx, Poll<()>> {
244        use MainThreadState::*;
245        match self {
246            GlobalCtors { ctor_state, entry_id, entry_type, argc, argv } => {
247                match ctor_state.on_stack_empty(this)? {
248                    Poll::Pending => {} // just keep going
249                    Poll::Ready(()) => {
250                        call_main(this, *entry_id, *entry_type, argc.clone(), argv.clone())?;
251                        *self = Running;
252                    }
253                }
254            }
255            Running => {
256                *self = TlsDtors(Default::default());
257            }
258            TlsDtors(state) =>
259                match state.on_stack_empty(this)? {
260                    Poll::Pending => {} // just keep going
261                    Poll::Ready(()) => {
262                        if this.machine.data_race.as_genmc_ref().is_some() {
263                            // In GenMC mode, we don't yield at the end of the main thread.
264                            // Instead, the `GenmcCtx` will ensure that unfinished threads get a chance to run at this point.
265                            *self = Done;
266                        } else {
267                            // Give background threads a chance to finish by yielding the main thread a
268                            // couple of times -- but only if we would also preempt threads randomly.
269                            if this.machine.preemption_rate > 0.0 {
270                                // There is a non-zero chance they will yield back to us often enough to
271                                // make Miri terminate eventually.
272                                *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN };
273                            } else {
274                                // The other threads did not get preempted, so no need to yield back to
275                                // them.
276                                *self = Done;
277                            }
278                        }
279                    }
280                },
281            Yield { remaining } =>
282                match remaining.checked_sub(1) {
283                    None => *self = Done,
284                    Some(new_remaining) => {
285                        *remaining = new_remaining;
286                        this.yield_active_thread();
287                    }
288                },
289            Done => {
290                // Figure out exit code.
291                let ret_place = this.machine.main_fn_ret_place.clone().unwrap();
292                let exit_code = this.read_target_isize(&ret_place)?;
293                // Rust uses `isize` but the underlying type of an exit code is `i32`.
294                // Do a saturating cast.
295                let exit_code = i32::try_from(exit_code).unwrap_or(if exit_code >= 0 {
296                    i32::MAX
297                } else {
298                    i32::MIN
299                });
300                // Deal with our thread-local memory. We do *not* want to actually free it, instead we consider TLS
301                // to be like a global `static`, so that all memory reached by it is considered to "not leak".
302                this.terminate_active_thread(TlsAllocAction::Leak)?;
303
304                // In GenMC mode, we do not immediately stop execution on main thread exit.
305                if let Some(genmc_ctx) = this.machine.data_race.as_genmc_ref() {
306                    // If there's no error, execution will continue (on another thread).
307                    genmc_ctx.handle_exit(
308                        ThreadId::MAIN_THREAD,
309                        exit_code,
310                        crate::concurrency::ExitType::MainThreadFinish,
311                    )?;
312                } else {
313                    // Stop interpreter loop.
314                    throw_machine_stop!(TerminationInfo::Exit {
315                        code: exit_code,
316                        leak_check: true
317                    });
318                }
319            }
320        }
321        interp_ok(Poll::Pending)
322    }
323}
324
325/// Returns a freshly created `InterpCx`.
326/// Public because this is also used by `priroda`.
327pub fn create_ecx<'tcx>(
328    tcx: TyCtxt<'tcx>,
329    entry_id: DefId,
330    entry_type: MiriEntryFnType,
331    config: &MiriConfig,
332    genmc_ctx: Option<Rc<GenmcCtx>>,
333) -> InterpResult<'tcx, InterpCx<'tcx, MiriMachine<'tcx>>> {
334    let typing_env = ty::TypingEnv::fully_monomorphized();
335    let layout_cx = LayoutCx::new(tcx, typing_env);
336    let mut ecx = InterpCx::new(
337        tcx,
338        rustc_span::DUMMY_SP,
339        typing_env,
340        MiriMachine::new(config, layout_cx, genmc_ctx),
341    );
342
343    // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore. However,
344    // if the current crate is #![no_core] it's fine to be missing the usual items from libcore.
345    if !is_no_core(tcx) {
346        let sentinel = helpers::try_resolve_path(
347            tcx,
348            &["core", "ascii", "escape_default"],
349            Namespace::ValueNS,
350        );
351        if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
352            tcx.dcx().fatal(
353                "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing.\n\
354                Note that directly invoking the `miri` binary is not supported; please use `cargo miri` instead."
355            );
356        }
357    }
358
359    // Compute argc and argv from `config.args`.
360    let argc =
361        ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
362    let argv = {
363        // Put each argument in memory, collect pointers.
364        let mut argvs = Vec::<Immediate<Provenance>>::with_capacity(config.args.len());
365        for arg in config.args.iter() {
366            // Make space for `0` terminator.
367            let size = u64::try_from(arg.len()).unwrap().strict_add(1);
368            let arg_type = Ty::new_array(tcx, tcx.types.u8, size);
369            let arg_place =
370                ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
371            ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr(), size)?;
372            ecx.mark_immutable(&arg_place);
373            argvs.push(arg_place.to_ref(&ecx));
374        }
375        // Make an array with all these pointers, in the Miri memory.
376        let u8_ptr_type = Ty::new_imm_ptr(tcx, tcx.types.u8);
377        let u8_ptr_ptr_type = Ty::new_imm_ptr(tcx, u8_ptr_type);
378        let argvs_layout =
379            ecx.layout_of(Ty::new_array(tcx, u8_ptr_type, u64::try_from(argvs.len()).unwrap()))?;
380        let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
381        for (arg, idx) in argvs.into_iter().zip(0..) {
382            let place = ecx.project_index(&argvs_place, idx)?;
383            ecx.write_immediate(arg, &place)?;
384        }
385        ecx.mark_immutable(&argvs_place);
386        // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`, and for the GC to see them.
387        {
388            let argc_place =
389                ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
390            ecx.write_immediate(*argc, &argc_place)?;
391            ecx.mark_immutable(&argc_place);
392            ecx.machine.argc = Some(argc_place.ptr());
393
394            let argv_place =
395                ecx.allocate(ecx.layout_of(u8_ptr_ptr_type)?, MiriMemoryKind::Machine.into())?;
396            ecx.write_pointer(argvs_place.ptr(), &argv_place)?;
397            ecx.mark_immutable(&argv_place);
398            ecx.machine.argv = Some(argv_place.ptr());
399        }
400        // Store command line as UTF-16 for Windows `GetCommandLineW`.
401        if tcx.sess.target.os == Os::Windows {
402            // Construct a command string with all the arguments.
403            let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
404
405            let cmd_type =
406                Ty::new_array(tcx, tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
407            let cmd_place =
408                ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
409            ecx.machine.cmd_line = Some(cmd_place.ptr());
410            // Store the UTF-16 string. We just allocated so we know the bounds are fine.
411            for (&c, idx) in cmd_utf16.iter().zip(0..) {
412                let place = ecx.project_index(&cmd_place, idx)?;
413                ecx.write_scalar(Scalar::from_u16(c), &place)?;
414            }
415            ecx.mark_immutable(&cmd_place);
416        }
417        let imm = argvs_place.to_ref(&ecx);
418        let layout = ecx.layout_of(u8_ptr_ptr_type)?;
419        ImmTy::from_immediate(imm, layout)
420    };
421
422    // Some parts of initialization require a full `InterpCx`.
423    MiriMachine::late_init(&mut ecx, config, {
424        let mut main_thread_state = MainThreadState::GlobalCtors {
425            entry_id,
426            entry_type,
427            argc,
428            argv,
429            ctor_state: global_ctor::GlobalCtorState::default(),
430        };
431
432        // Cannot capture anything GC-relevant here.
433        // `argc` and `argv` *are* GC_relevant, but they also get stored in `machine.argc` and
434        // `machine.argv` so we are good.
435        Box::new(move |m| main_thread_state.on_main_stack_empty(m))
436    })?;
437
438    interp_ok(ecx)
439}
440
441// Call the entry function.
442fn call_main<'tcx>(
443    ecx: &mut MiriInterpCx<'tcx>,
444    entry_id: DefId,
445    entry_type: MiriEntryFnType,
446    argc: ImmTy<'tcx>,
447    argv: ImmTy<'tcx>,
448) -> InterpResult<'tcx, ()> {
449    let tcx = ecx.tcx();
450
451    // Setup first stack frame.
452    let entry_instance = ty::Instance::mono(tcx, entry_id);
453
454    // Return place (in static memory so that it does not count as leak).
455    let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
456    ecx.machine.main_fn_ret_place = Some(ret_place.clone());
457
458    // Call start function.
459    match entry_type {
460        MiriEntryFnType::Rustc(EntryFnType::Main { .. }) => {
461            let entry_sig = tcx.fn_sig(entry_id).no_bound_vars().unwrap();
462            let main_ret_ty = entry_sig.output();
463            let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
464
465            let start_id = tcx.lang_items().start_fn().unwrap_or_else(|| {
466                tcx.dcx().fatal("could not find start lang item");
467            });
468            let start_instance = ty::Instance::try_resolve(
469                tcx,
470                ecx.typing_env(),
471                start_id,
472                tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]),
473            )
474            .unwrap()
475            .unwrap();
476
477            let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance));
478
479            // Always using DEFAULT is okay since we don't support signals in Miri anyway.
480            // (This means we are effectively ignoring `-Zon-broken-pipe`.)
481            let sigpipe = rustc_session::config::sigpipe::DEFAULT;
482
483            ecx.call_function(
484                start_instance,
485                ExternAbi::Rust,
486                &[
487                    ImmTy::from_scalar(
488                        Scalar::from_pointer(main_ptr, ecx),
489                        ecx.layout_of(Ty::new_fn_ptr(tcx, entry_sig)).unwrap(),
490                    ),
491                    argc,
492                    argv,
493                    ImmTy::from_uint(sigpipe, ecx.machine.layouts.u8),
494                ],
495                Some(&ret_place),
496                ReturnContinuation::Stop { cleanup: true },
497            )?;
498        }
499        MiriEntryFnType::MiriStart => {
500            ecx.call_function(
501                entry_instance,
502                ExternAbi::Rust,
503                &[argc, argv],
504                Some(&ret_place),
505                ReturnContinuation::Stop { cleanup: true },
506            )?;
507        }
508    }
509
510    interp_ok(())
511}
512
513/// Evaluates the entry function specified by `entry_id`.
514/// Returns `Ok(())` if program execution completed with exit code 0.
515/// Returns `Err(code)` if an evaluation error occurred or the program returned a non-0 exit code.
516pub fn eval_entry<'tcx>(
517    tcx: TyCtxt<'tcx>,
518    entry_id: DefId,
519    entry_type: MiriEntryFnType,
520    config: &MiriConfig,
521    genmc_ctx: Option<Rc<GenmcCtx>>,
522) -> Result<(), NonZeroI32> {
523    // Copy setting before we move `config`.
524    let ignore_leaks = config.ignore_leaks;
525
526    let mut ecx = match create_ecx(tcx, entry_id, entry_type, config, genmc_ctx).report_err() {
527        Ok(v) => v,
528        Err(err) => {
529            let (kind, backtrace) = err.into_parts();
530            backtrace.print_backtrace();
531            panic!("Miri initialization error: {kind:?}")
532        }
533    };
534
535    // Perform the main execution.
536    let res: thread::Result<InterpResult<'_, !>> =
537        panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
538    let res = res.unwrap_or_else(|panic_payload| {
539        // rustc "handles" some errors by unwinding with FatalErrorMarker
540        // (after emitting suitable diagnostics), so do not treat those as ICEs.
541        if !panic_payload.is::<FatalErrorMarker>() {
542            ecx.handle_ice();
543        }
544        panic::resume_unwind(panic_payload)
545    });
546    // Obtain the result of the execution. This is always an `Err`, but that doesn't necessarily
547    // indicate an error.
548    let Err(res) = res.report_err();
549
550    // Error reporting: if we survive all checks, we return the exit code the program gave us.
551    'miri_error: {
552        // Show diagnostic, if any.
553        let Some((return_code, leak_check)) = report_result(&ecx, res) else {
554            break 'miri_error;
555        };
556
557        // If we get here there was no fatal error -- yet.
558        // Possibly check for memory leaks.
559        if leak_check && !ignore_leaks {
560            // Check for thread leaks.
561            if !ecx.have_all_terminated() {
562                tcx.dcx()
563                    .err("the main thread terminated without waiting for all remaining threads");
564                tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
565                break 'miri_error;
566            }
567            // Check for memory leaks.
568            info!("Additional static roots: {:?}", ecx.machine.static_roots);
569            let leaks = ecx.take_leaked_allocations(|ecx| &ecx.machine.static_roots);
570            if !leaks.is_empty() {
571                report_leaks(&ecx, leaks);
572                tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
573                // Ignore the provided return code - let the reported error
574                // determine the return code.
575                break 'miri_error;
576            }
577        }
578
579        // The interpreter has not reported an error.
580        // (There could still be errors in the session if there are other interpreters.)
581        return match NonZeroI32::new(return_code) {
582            None => Ok(()),
583            Some(return_code) => Err(return_code),
584        };
585    }
586
587    // The interpreter reported an error.
588    assert!(tcx.dcx().has_errors().is_some());
589    Err(NonZeroI32::new(rustc_driver::EXIT_FAILURE).unwrap())
590}
591
592/// Turns an array of arguments into a Windows command line string.
593///
594/// The string will be UTF-16 encoded and NUL terminated.
595///
596/// Panics if the zeroth argument contains the `"` character because doublequotes
597/// in `argv[0]` cannot be encoded using the standard command line parsing rules.
598///
599/// Further reading:
600/// * [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)
601/// * [The C/C++ Parameter Parsing Rules](https://daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULES)
602fn args_to_utf16_command_string<I, T>(mut args: I) -> Vec<u16>
603where
604    I: Iterator<Item = T>,
605    T: AsRef<str>,
606{
607    // Parse argv[0]. Slashes aren't escaped. Literal double quotes are not allowed.
608    let mut cmd = {
609        let Some(arg0) = args.next() else {
610            return vec![0];
611        };
612        let arg0 = arg0.as_ref();
613        if arg0.contains('"') {
614            panic!("argv[0] cannot contain a doublequote (\") character");
615        } else {
616            // Always surround argv[0] with quotes.
617            let mut s = String::new();
618            s.push('"');
619            s.push_str(arg0);
620            s.push('"');
621            s
622        }
623    };
624
625    // Build the other arguments.
626    for arg in args {
627        let arg = arg.as_ref();
628        cmd.push(' ');
629        if arg.is_empty() {
630            cmd.push_str("\"\"");
631        } else if !arg.bytes().any(|c| matches!(c, b'"' | b'\t' | b' ')) {
632            // No quote, tab, or space -- no escaping required.
633            cmd.push_str(arg);
634        } else {
635            // Spaces and tabs are escaped by surrounding them in quotes.
636            // Quotes are themselves escaped by using backslashes when in a
637            // quoted block.
638            // Backslashes only need to be escaped when one or more are directly
639            // followed by a quote. Otherwise they are taken literally.
640
641            cmd.push('"');
642            let mut chars = arg.chars().peekable();
643            loop {
644                let mut nslashes = 0;
645                while let Some(&'\\') = chars.peek() {
646                    chars.next();
647                    nslashes += 1;
648                }
649
650                match chars.next() {
651                    Some('"') => {
652                        cmd.extend(iter::repeat_n('\\', nslashes * 2 + 1));
653                        cmd.push('"');
654                    }
655                    Some(c) => {
656                        cmd.extend(iter::repeat_n('\\', nslashes));
657                        cmd.push(c);
658                    }
659                    None => {
660                        cmd.extend(iter::repeat_n('\\', nslashes * 2));
661                        break;
662                    }
663                }
664            }
665            cmd.push('"');
666        }
667    }
668
669    if cmd.contains('\0') {
670        panic!("interior null in command line arguments");
671    }
672    cmd.encode_utf16().chain(iter::once(0)).collect()
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    #[test]
679    #[should_panic(expected = "argv[0] cannot contain a doublequote (\") character")]
680    fn windows_argv0_panic_on_quote() {
681        args_to_utf16_command_string(["\""].iter());
682    }
683    #[test]
684    fn windows_argv0_no_escape() {
685        // Ensure that a trailing backslash in argv[0] is not escaped.
686        let cmd = String::from_utf16_lossy(&args_to_utf16_command_string(
687            [r"C:\Program Files\", "arg1", "arg 2", "arg \" 3"].iter(),
688        ));
689        assert_eq!(cmd.trim_end_matches('\0'), r#""C:\Program Files\" arg1 "arg 2" "arg \" 3""#);
690    }
691}