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