miri/
eval.rs

1//! Main evaluator loop and setting up the initial stack frame.
2
3use std::ffi::{OsStr, OsString};
4use std::panic::{self, AssertUnwindSafe};
5use std::path::PathBuf;
6use std::rc::Rc;
7use std::task::Poll;
8use std::{iter, thread};
9
10use rustc_abi::ExternAbi;
11use rustc_data_structures::fx::{FxHashMap, FxHashSet};
12use rustc_hir::def::Namespace;
13use rustc_hir::def_id::DefId;
14use rustc_middle::ty::layout::LayoutCx;
15use rustc_middle::ty::{self, Ty, TyCtxt};
16use rustc_session::config::EntryFnType;
17
18use crate::concurrency::GenmcCtx;
19use crate::concurrency::thread::TlsAllocAction;
20use crate::diagnostics::report_leaks;
21use crate::shims::tls;
22use crate::*;
23
24#[derive(Copy, Clone, Debug)]
25pub enum MiriEntryFnType {
26    MiriStart,
27    Rustc(EntryFnType),
28}
29
30/// When the main thread would exit, we will yield to any other thread that is ready to execute.
31/// But we must only do that a finite number of times, or a background thread running `loop {}`
32/// will hang the program.
33const MAIN_THREAD_YIELDS_AT_SHUTDOWN: u32 = 256;
34
35#[derive(Copy, Clone, Debug, PartialEq)]
36pub enum AlignmentCheck {
37    /// Do not check alignment.
38    None,
39    /// Check alignment "symbolically", i.e., using only the requested alignment for an allocation and not its real base address.
40    Symbolic,
41    /// Check alignment on the actual physical integer address.
42    Int,
43}
44
45#[derive(Copy, Clone, Debug, PartialEq)]
46pub enum RejectOpWith {
47    /// Isolated op is rejected with an abort of the machine.
48    Abort,
49
50    /// If not Abort, miri returns an error for an isolated op.
51    /// Following options determine if user should be warned about such error.
52    /// Do not print warning about rejected isolated op.
53    NoWarning,
54
55    /// Print a warning about rejected isolated op, with backtrace.
56    Warning,
57
58    /// Print a warning about rejected isolated op, without backtrace.
59    WarningWithoutBacktrace,
60}
61
62#[derive(Copy, Clone, Debug, PartialEq)]
63pub enum IsolatedOp {
64    /// Reject an op requiring communication with the host. By
65    /// default, miri rejects the op with an abort. If not, it returns
66    /// an error code, and prints a warning about it. Warning levels
67    /// are controlled by `RejectOpWith` enum.
68    Reject(RejectOpWith),
69
70    /// Execute op requiring communication with the host, i.e. disable isolation.
71    Allow,
72}
73
74#[derive(Debug, Copy, Clone, PartialEq, Eq)]
75pub enum BacktraceStyle {
76    /// Prints a terser backtrace which ideally only contains relevant information.
77    Short,
78    /// Prints a backtrace with all possible information.
79    Full,
80    /// Prints only the frame that the error occurs in.
81    Off,
82}
83
84#[derive(Debug, Copy, Clone, PartialEq, Eq)]
85pub enum ValidationMode {
86    /// Do not perform any kind of validation.
87    No,
88    /// Validate the interior of the value, but not things behind references.
89    Shallow,
90    /// Fully recursively validate references.
91    Deep,
92}
93
94/// Configuration needed to spawn a Miri instance.
95#[derive(Clone)]
96pub struct MiriConfig {
97    /// The host environment snapshot to use as basis for what is provided to the interpreted program.
98    /// (This is still subject to isolation as well as `forwarded_env_vars`.)
99    pub env: Vec<(OsString, OsString)>,
100    /// Determine if validity checking is enabled.
101    pub validation: ValidationMode,
102    /// Determines if Stacked Borrows or Tree Borrows is enabled.
103    pub borrow_tracker: Option<BorrowTrackerMethod>,
104    /// Controls alignment checking.
105    pub check_alignment: AlignmentCheck,
106    /// Action for an op requiring communication with the host.
107    pub isolated_op: IsolatedOp,
108    /// Determines if memory leaks should be ignored.
109    pub ignore_leaks: bool,
110    /// Environment variables that should always be forwarded from the host.
111    pub forwarded_env_vars: Vec<String>,
112    /// Additional environment variables that should be set in the interpreted program.
113    pub set_env_vars: FxHashMap<String, String>,
114    /// Command-line arguments passed to the interpreted program.
115    pub args: Vec<String>,
116    /// The seed to use when non-determinism or randomness are required (e.g. ptr-to-int cast, `getrandom()`).
117    pub seed: Option<u64>,
118    /// The stacked borrows pointer ids to report about.
119    pub tracked_pointer_tags: FxHashSet<BorTag>,
120    /// The allocation ids to report about.
121    pub tracked_alloc_ids: FxHashSet<AllocId>,
122    /// For the tracked alloc ids, also report read/write accesses.
123    pub track_alloc_accesses: bool,
124    /// Determine if data race detection should be enabled.
125    pub data_race_detector: bool,
126    /// Determine if weak memory emulation should be enabled. Requires data race detection to be enabled.
127    pub weak_memory_emulation: bool,
128    /// Determine if we are running in GenMC mode. In this mode, Miri will explore multiple concurrent executions of the given program.
129    pub genmc_mode: bool,
130    /// Track when an outdated (weak memory) load happens.
131    pub track_outdated_loads: bool,
132    /// Rate of spurious failures for compare_exchange_weak atomic operations,
133    /// between 0.0 and 1.0, defaulting to 0.8 (80% chance of failure).
134    pub cmpxchg_weak_failure_rate: f64,
135    /// If `Some`, enable the `measureme` profiler, writing results to a file
136    /// with the specified prefix.
137    pub measureme_out: Option<String>,
138    /// Which style to use for printing backtraces.
139    pub backtrace_style: BacktraceStyle,
140    /// Which provenance to use for int2ptr casts.
141    pub provenance_mode: ProvenanceMode,
142    /// Whether to ignore any output by the program. This is helpful when debugging miri
143    /// as its messages don't get intermingled with the program messages.
144    pub mute_stdout_stderr: bool,
145    /// The probability of the active thread being preempted at the end of each basic block.
146    pub preemption_rate: f64,
147    /// Report the current instruction being executed every N basic blocks.
148    pub report_progress: Option<u32>,
149    /// Whether Stacked Borrows and Tree Borrows retagging should recurse into fields of datatypes.
150    pub retag_fields: RetagFields,
151    /// The location of the shared object files to load when calling external functions
152    pub native_lib: Vec<PathBuf>,
153    /// Whether to enable the new native lib tracing system.
154    pub native_lib_enable_tracing: bool,
155    /// Run a garbage collector for BorTags every N basic blocks.
156    pub gc_interval: u32,
157    /// The number of CPUs to be reported by miri.
158    pub num_cpus: u32,
159    /// Requires Miri to emulate pages of a certain size.
160    pub page_size: Option<u64>,
161    /// Whether to collect a backtrace when each allocation is created, just in case it leaks.
162    pub collect_leak_backtraces: bool,
163    /// Probability for address reuse.
164    pub address_reuse_rate: f64,
165    /// Probability for address reuse across threads.
166    pub address_reuse_cross_thread_rate: f64,
167    /// Round Robin scheduling with no preemption.
168    pub fixed_scheduling: bool,
169    /// Always prefer the intrinsic fallback body over the native Miri implementation.
170    pub force_intrinsic_fallback: bool,
171    /// Whether floating-point operations can behave non-deterministically.
172    pub float_nondet: bool,
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_mode: false,
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            retag_fields: RetagFields::Yes,
203            native_lib: vec![],
204            native_lib_enable_tracing: false,
205            gc_interval: 10_000,
206            num_cpus: 1,
207            page_size: None,
208            collect_leak_backtraces: true,
209            address_reuse_rate: 0.5,
210            address_reuse_cross_thread_rate: 0.1,
211            fixed_scheduling: false,
212            force_intrinsic_fallback: false,
213            float_nondet: true,
214        }
215    }
216}
217
218/// The state of the main thread. Implementation detail of `on_main_stack_empty`.
219#[derive(Default, Debug)]
220enum MainThreadState<'tcx> {
221    #[default]
222    Running,
223    TlsDtors(tls::TlsDtorsState<'tcx>),
224    Yield {
225        remaining: u32,
226    },
227    Done,
228}
229
230impl<'tcx> MainThreadState<'tcx> {
231    fn on_main_stack_empty(
232        &mut self,
233        this: &mut MiriInterpCx<'tcx>,
234    ) -> InterpResult<'tcx, Poll<()>> {
235        use MainThreadState::*;
236        match self {
237            Running => {
238                *self = TlsDtors(Default::default());
239            }
240            TlsDtors(state) =>
241                match state.on_stack_empty(this)? {
242                    Poll::Pending => {} // just keep going
243                    Poll::Ready(()) => {
244                        if this.machine.data_race.as_genmc_ref().is_some() {
245                            // In GenMC mode, we don't yield at the end of the main thread.
246                            // Instead, the `GenmcCtx` will ensure that unfinished threads get a chance to run at this point.
247                            *self = Done;
248                        } else {
249                            // Give background threads a chance to finish by yielding the main thread a
250                            // couple of times -- but only if we would also preempt threads randomly.
251                            if this.machine.preemption_rate > 0.0 {
252                                // There is a non-zero chance they will yield back to us often enough to
253                                // make Miri terminate eventually.
254                                *self = Yield { remaining: MAIN_THREAD_YIELDS_AT_SHUTDOWN };
255                            } else {
256                                // The other threads did not get preempted, so no need to yield back to
257                                // them.
258                                *self = Done;
259                            }
260                        }
261                    }
262                },
263            Yield { remaining } =>
264                match remaining.checked_sub(1) {
265                    None => *self = Done,
266                    Some(new_remaining) => {
267                        *remaining = new_remaining;
268                        this.yield_active_thread();
269                    }
270                },
271            Done => {
272                // Figure out exit code.
273                let ret_place = this.machine.main_fn_ret_place.clone().unwrap();
274                let exit_code = this.read_target_isize(&ret_place)?;
275                // Rust uses `isize` but the underlying type of an exit code is `i32`.
276                // Do a saturating cast.
277                let exit_code = i32::try_from(exit_code).unwrap_or(if exit_code >= 0 {
278                    i32::MAX
279                } else {
280                    i32::MIN
281                });
282                // Deal with our thread-local memory. We do *not* want to actually free it, instead we consider TLS
283                // to be like a global `static`, so that all memory reached by it is considered to "not leak".
284                this.terminate_active_thread(TlsAllocAction::Leak)?;
285
286                // Stop interpreter loop.
287                throw_machine_stop!(TerminationInfo::Exit { code: exit_code, leak_check: true });
288            }
289        }
290        interp_ok(Poll::Pending)
291    }
292}
293
294/// Returns a freshly created `InterpCx`.
295/// Public because this is also used by `priroda`.
296pub fn create_ecx<'tcx>(
297    tcx: TyCtxt<'tcx>,
298    entry_id: DefId,
299    entry_type: MiriEntryFnType,
300    config: &MiriConfig,
301    genmc_ctx: Option<Rc<GenmcCtx>>,
302) -> InterpResult<'tcx, InterpCx<'tcx, MiriMachine<'tcx>>> {
303    let typing_env = ty::TypingEnv::fully_monomorphized();
304    let layout_cx = LayoutCx::new(tcx, typing_env);
305    let mut ecx = InterpCx::new(
306        tcx,
307        rustc_span::DUMMY_SP,
308        typing_env,
309        MiriMachine::new(config, layout_cx, genmc_ctx),
310    );
311
312    // Some parts of initialization require a full `InterpCx`.
313    MiriMachine::late_init(&mut ecx, config, {
314        let mut state = MainThreadState::default();
315        // Cannot capture anything GC-relevant here.
316        Box::new(move |m| state.on_main_stack_empty(m))
317    })?;
318
319    // Make sure we have MIR. We check MIR for some stable monomorphic function in libcore.
320    let sentinel =
321        helpers::try_resolve_path(tcx, &["core", "ascii", "escape_default"], Namespace::ValueNS);
322    if !matches!(sentinel, Some(s) if tcx.is_mir_available(s.def.def_id())) {
323        tcx.dcx().fatal(
324            "the current sysroot was built without `-Zalways-encode-mir`, or libcore seems missing. \
325            Use `cargo miri setup` to prepare a sysroot that is suitable for Miri."
326        );
327    }
328
329    // Setup first stack frame.
330    let entry_instance = ty::Instance::mono(tcx, entry_id);
331
332    // First argument is constructed later, because it's skipped for `miri_start.`
333
334    // Second argument (argc): length of `config.args`.
335    let argc =
336        ImmTy::from_int(i64::try_from(config.args.len()).unwrap(), ecx.machine.layouts.isize);
337    // Third argument (`argv`): created from `config.args`.
338    let argv = {
339        // Put each argument in memory, collect pointers.
340        let mut argvs = Vec::<Immediate<Provenance>>::with_capacity(config.args.len());
341        for arg in config.args.iter() {
342            // Make space for `0` terminator.
343            let size = u64::try_from(arg.len()).unwrap().strict_add(1);
344            let arg_type = Ty::new_array(tcx, tcx.types.u8, size);
345            let arg_place =
346                ecx.allocate(ecx.layout_of(arg_type)?, MiriMemoryKind::Machine.into())?;
347            ecx.write_os_str_to_c_str(OsStr::new(arg), arg_place.ptr(), size)?;
348            ecx.mark_immutable(&arg_place);
349            argvs.push(arg_place.to_ref(&ecx));
350        }
351        // Make an array with all these pointers, in the Miri memory.
352        let u8_ptr_type = Ty::new_imm_ptr(tcx, tcx.types.u8);
353        let u8_ptr_ptr_type = Ty::new_imm_ptr(tcx, u8_ptr_type);
354        let argvs_layout =
355            ecx.layout_of(Ty::new_array(tcx, u8_ptr_type, u64::try_from(argvs.len()).unwrap()))?;
356        let argvs_place = ecx.allocate(argvs_layout, MiriMemoryKind::Machine.into())?;
357        for (arg, idx) in argvs.into_iter().zip(0..) {
358            let place = ecx.project_index(&argvs_place, idx)?;
359            ecx.write_immediate(arg, &place)?;
360        }
361        ecx.mark_immutable(&argvs_place);
362        // Store `argc` and `argv` for macOS `_NSGetArg{c,v}`.
363        {
364            let argc_place =
365                ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
366            ecx.write_immediate(*argc, &argc_place)?;
367            ecx.mark_immutable(&argc_place);
368            ecx.machine.argc = Some(argc_place.ptr());
369
370            let argv_place =
371                ecx.allocate(ecx.layout_of(u8_ptr_ptr_type)?, MiriMemoryKind::Machine.into())?;
372            ecx.write_pointer(argvs_place.ptr(), &argv_place)?;
373            ecx.mark_immutable(&argv_place);
374            ecx.machine.argv = Some(argv_place.ptr());
375        }
376        // Store command line as UTF-16 for Windows `GetCommandLineW`.
377        {
378            // Construct a command string with all the arguments.
379            let cmd_utf16: Vec<u16> = args_to_utf16_command_string(config.args.iter());
380
381            let cmd_type =
382                Ty::new_array(tcx, tcx.types.u16, u64::try_from(cmd_utf16.len()).unwrap());
383            let cmd_place =
384                ecx.allocate(ecx.layout_of(cmd_type)?, MiriMemoryKind::Machine.into())?;
385            ecx.machine.cmd_line = Some(cmd_place.ptr());
386            // Store the UTF-16 string. We just allocated so we know the bounds are fine.
387            for (&c, idx) in cmd_utf16.iter().zip(0..) {
388                let place = ecx.project_index(&cmd_place, idx)?;
389                ecx.write_scalar(Scalar::from_u16(c), &place)?;
390            }
391            ecx.mark_immutable(&cmd_place);
392        }
393        let imm = argvs_place.to_ref(&ecx);
394        let layout = ecx.layout_of(u8_ptr_ptr_type)?;
395        ImmTy::from_immediate(imm, layout)
396    };
397
398    // Return place (in static memory so that it does not count as leak).
399    let ret_place = ecx.allocate(ecx.machine.layouts.isize, MiriMemoryKind::Machine.into())?;
400    ecx.machine.main_fn_ret_place = Some(ret_place.clone());
401    // Call start function.
402
403    match entry_type {
404        MiriEntryFnType::Rustc(EntryFnType::Main { .. }) => {
405            let start_id = tcx.lang_items().start_fn().unwrap_or_else(|| {
406                tcx.dcx().fatal("could not find start lang item");
407            });
408            let main_ret_ty = tcx.fn_sig(entry_id).no_bound_vars().unwrap().output();
409            let main_ret_ty = main_ret_ty.no_bound_vars().unwrap();
410            let start_instance = ty::Instance::try_resolve(
411                tcx,
412                typing_env,
413                start_id,
414                tcx.mk_args(&[ty::GenericArg::from(main_ret_ty)]),
415            )
416            .unwrap()
417            .unwrap();
418
419            let main_ptr = ecx.fn_ptr(FnVal::Instance(entry_instance));
420
421            // Always using DEFAULT is okay since we don't support signals in Miri anyway.
422            // (This means we are effectively ignoring `-Zon-broken-pipe`.)
423            let sigpipe = rustc_session::config::sigpipe::DEFAULT;
424
425            ecx.call_function(
426                start_instance,
427                ExternAbi::Rust,
428                &[
429                    ImmTy::from_scalar(
430                        Scalar::from_pointer(main_ptr, &ecx),
431                        // FIXME use a proper fn ptr type
432                        ecx.machine.layouts.const_raw_ptr,
433                    ),
434                    argc,
435                    argv,
436                    ImmTy::from_uint(sigpipe, ecx.machine.layouts.u8),
437                ],
438                Some(&ret_place),
439                ReturnContinuation::Stop { cleanup: true },
440            )?;
441        }
442        MiriEntryFnType::MiriStart => {
443            ecx.call_function(
444                entry_instance,
445                ExternAbi::Rust,
446                &[argc, argv],
447                Some(&ret_place),
448                ReturnContinuation::Stop { cleanup: true },
449            )?;
450        }
451    }
452
453    interp_ok(ecx)
454}
455
456/// Evaluates the entry function specified by `entry_id`.
457/// Returns `Some(return_code)` if program execution completed.
458/// Returns `None` if an evaluation error occurred.
459pub fn eval_entry<'tcx>(
460    tcx: TyCtxt<'tcx>,
461    entry_id: DefId,
462    entry_type: MiriEntryFnType,
463    config: &MiriConfig,
464    genmc_ctx: Option<Rc<GenmcCtx>>,
465) -> Option<i32> {
466    // Copy setting before we move `config`.
467    let ignore_leaks = config.ignore_leaks;
468
469    if let Some(genmc_ctx) = &genmc_ctx {
470        genmc_ctx.handle_execution_start();
471    }
472
473    let mut ecx = match create_ecx(tcx, entry_id, entry_type, config, genmc_ctx).report_err() {
474        Ok(v) => v,
475        Err(err) => {
476            let (kind, backtrace) = err.into_parts();
477            backtrace.print_backtrace();
478            panic!("Miri initialization error: {kind:?}")
479        }
480    };
481
482    // Perform the main execution.
483    let res: thread::Result<InterpResult<'_, !>> =
484        panic::catch_unwind(AssertUnwindSafe(|| ecx.run_threads()));
485    let res = res.unwrap_or_else(|panic_payload| {
486        ecx.handle_ice();
487        panic::resume_unwind(panic_payload)
488    });
489    // `Ok` can never happen; the interpreter loop always exits with an "error"
490    // (but that "error" might be just "regular program termination").
491    let Err(err) = res.report_err();
492
493    // Show diagnostic, if any.
494    let (return_code, leak_check) = report_error(&ecx, err)?;
495
496    // We inform GenMC that the execution is complete.
497    if let Some(genmc_ctx) = ecx.machine.data_race.as_genmc_ref()
498        && let Err(error) = genmc_ctx.handle_execution_end(&ecx)
499    {
500        // FIXME(GenMC): Improve error reporting.
501        tcx.dcx().err(format!("GenMC returned an error: \"{error}\""));
502        return None;
503    }
504
505    // If we get here there was no fatal error.
506
507    // Possibly check for memory leaks.
508    if leak_check && !ignore_leaks {
509        // Check for thread leaks.
510        if !ecx.have_all_terminated() {
511            tcx.dcx().err("the main thread terminated without waiting for all remaining threads");
512            tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
513            return None;
514        }
515        // Check for memory leaks.
516        info!("Additional static roots: {:?}", ecx.machine.static_roots);
517        let leaks = ecx.take_leaked_allocations(|ecx| &ecx.machine.static_roots);
518        if !leaks.is_empty() {
519            report_leaks(&ecx, leaks);
520            tcx.dcx().note("set `MIRIFLAGS=-Zmiri-ignore-leaks` to disable this check");
521            // Ignore the provided return code - let the reported error
522            // determine the return code.
523            return None;
524        }
525    }
526    Some(return_code)
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}