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