]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/process.rs
Rollup merge of #93613 - crlf0710:rename_to_async_iter, r=yaahc
[rust.git] / library / std / src / sys / windows / process.rs
1 #![unstable(feature = "process_internals", issue = "none")]
2
3 #[cfg(test)]
4 mod tests;
5
6 use crate::cmp;
7 use crate::collections::BTreeMap;
8 use crate::convert::{TryFrom, TryInto};
9 use crate::env;
10 use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX};
11 use crate::ffi::{OsStr, OsString};
12 use crate::fmt;
13 use crate::io::{self, Error, ErrorKind};
14 use crate::mem;
15 use crate::num::NonZeroI32;
16 use crate::os::windows::ffi::{OsStrExt, OsStringExt};
17 use crate::os::windows::io::{AsRawHandle, FromRawHandle, IntoRawHandle};
18 use crate::path::{Path, PathBuf};
19 use crate::ptr;
20 use crate::sys::c;
21 use crate::sys::c::NonZeroDWORD;
22 use crate::sys::fs::{File, OpenOptions};
23 use crate::sys::handle::Handle;
24 use crate::sys::path;
25 use crate::sys::pipe::{self, AnonPipe};
26 use crate::sys::stdio;
27 use crate::sys::{cvt, to_u16s};
28 use crate::sys_common::mutex::StaticMutex;
29 use crate::sys_common::process::{CommandEnv, CommandEnvs};
30 use crate::sys_common::{AsInner, IntoInner};
31
32 use libc::{c_void, EXIT_FAILURE, EXIT_SUCCESS};
33
34 ////////////////////////////////////////////////////////////////////////////////
35 // Command
36 ////////////////////////////////////////////////////////////////////////////////
37
38 #[derive(Clone, Debug, Eq)]
39 #[doc(hidden)]
40 pub struct EnvKey {
41     os_string: OsString,
42     // This stores a UTF-16 encoded string to workaround the mismatch between
43     // Rust's OsString (WTF-8) and the Windows API string type (UTF-16).
44     // Normally converting on every API call is acceptable but here
45     // `c::CompareStringOrdinal` will be called for every use of `==`.
46     utf16: Vec<u16>,
47 }
48
49 impl EnvKey {
50     fn new<T: Into<OsString>>(key: T) -> Self {
51         EnvKey::from(key.into())
52     }
53 }
54
55 // Comparing Windows environment variable keys[1] are behaviourally the
56 // composition of two operations[2]:
57 //
58 // 1. Case-fold both strings. This is done using a language-independent
59 // uppercase mapping that's unique to Windows (albeit based on data from an
60 // older Unicode spec). It only operates on individual UTF-16 code units so
61 // surrogates are left unchanged. This uppercase mapping can potentially change
62 // between Windows versions.
63 //
64 // 2. Perform an ordinal comparison of the strings. A comparison using ordinal
65 // is just a comparison based on the numerical value of each UTF-16 code unit[3].
66 //
67 // Because the case-folding mapping is unique to Windows and not guaranteed to
68 // be stable, we ask the OS to compare the strings for us. This is done by
69 // calling `CompareStringOrdinal`[4] with `bIgnoreCase` set to `TRUE`.
70 //
71 // [1] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call
72 // [2] https://docs.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#stringtoupper-and-stringtolower
73 // [3] https://docs.microsoft.com/en-us/dotnet/api/system.stringcomparison?view=net-5.0#System_StringComparison_Ordinal
74 // [4] https://docs.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-comparestringordinal
75 impl Ord for EnvKey {
76     fn cmp(&self, other: &Self) -> cmp::Ordering {
77         unsafe {
78             let result = c::CompareStringOrdinal(
79                 self.utf16.as_ptr(),
80                 self.utf16.len() as _,
81                 other.utf16.as_ptr(),
82                 other.utf16.len() as _,
83                 c::TRUE,
84             );
85             match result {
86                 c::CSTR_LESS_THAN => cmp::Ordering::Less,
87                 c::CSTR_EQUAL => cmp::Ordering::Equal,
88                 c::CSTR_GREATER_THAN => cmp::Ordering::Greater,
89                 // `CompareStringOrdinal` should never fail so long as the parameters are correct.
90                 _ => panic!("comparing environment keys failed: {}", Error::last_os_error()),
91             }
92         }
93     }
94 }
95 impl PartialOrd for EnvKey {
96     fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
97         Some(self.cmp(other))
98     }
99 }
100 impl PartialEq for EnvKey {
101     fn eq(&self, other: &Self) -> bool {
102         if self.utf16.len() != other.utf16.len() {
103             false
104         } else {
105             self.cmp(other) == cmp::Ordering::Equal
106         }
107     }
108 }
109 impl PartialOrd<str> for EnvKey {
110     fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
111         Some(self.cmp(&EnvKey::new(other)))
112     }
113 }
114 impl PartialEq<str> for EnvKey {
115     fn eq(&self, other: &str) -> bool {
116         if self.os_string.len() != other.len() {
117             false
118         } else {
119             self.cmp(&EnvKey::new(other)) == cmp::Ordering::Equal
120         }
121     }
122 }
123
124 // Environment variable keys should preserve their original case even though
125 // they are compared using a caseless string mapping.
126 impl From<OsString> for EnvKey {
127     fn from(k: OsString) -> Self {
128         EnvKey { utf16: k.encode_wide().collect(), os_string: k }
129     }
130 }
131
132 impl From<EnvKey> for OsString {
133     fn from(k: EnvKey) -> Self {
134         k.os_string
135     }
136 }
137
138 impl From<&OsStr> for EnvKey {
139     fn from(k: &OsStr) -> Self {
140         Self::from(k.to_os_string())
141     }
142 }
143
144 impl AsRef<OsStr> for EnvKey {
145     fn as_ref(&self) -> &OsStr {
146         &self.os_string
147     }
148 }
149
150 fn ensure_no_nuls<T: AsRef<OsStr>>(str: T) -> io::Result<T> {
151     if str.as_ref().encode_wide().any(|b| b == 0) {
152         Err(io::const_io_error!(ErrorKind::InvalidInput, "nul byte found in provided data"))
153     } else {
154         Ok(str)
155     }
156 }
157
158 pub struct Command {
159     program: OsString,
160     args: Vec<Arg>,
161     env: CommandEnv,
162     cwd: Option<OsString>,
163     flags: u32,
164     detach: bool, // not currently exposed in std::process
165     stdin: Option<Stdio>,
166     stdout: Option<Stdio>,
167     stderr: Option<Stdio>,
168     force_quotes_enabled: bool,
169 }
170
171 pub enum Stdio {
172     Inherit,
173     Null,
174     MakePipe,
175     Handle(Handle),
176 }
177
178 pub struct StdioPipes {
179     pub stdin: Option<AnonPipe>,
180     pub stdout: Option<AnonPipe>,
181     pub stderr: Option<AnonPipe>,
182 }
183
184 #[derive(Debug)]
185 enum Arg {
186     /// Add quotes (if needed)
187     Regular(OsString),
188     /// Append raw string without quoting
189     Raw(OsString),
190 }
191
192 impl Command {
193     pub fn new(program: &OsStr) -> Command {
194         Command {
195             program: program.to_os_string(),
196             args: Vec::new(),
197             env: Default::default(),
198             cwd: None,
199             flags: 0,
200             detach: false,
201             stdin: None,
202             stdout: None,
203             stderr: None,
204             force_quotes_enabled: false,
205         }
206     }
207
208     pub fn arg(&mut self, arg: &OsStr) {
209         self.args.push(Arg::Regular(arg.to_os_string()))
210     }
211     pub fn env_mut(&mut self) -> &mut CommandEnv {
212         &mut self.env
213     }
214     pub fn cwd(&mut self, dir: &OsStr) {
215         self.cwd = Some(dir.to_os_string())
216     }
217     pub fn stdin(&mut self, stdin: Stdio) {
218         self.stdin = Some(stdin);
219     }
220     pub fn stdout(&mut self, stdout: Stdio) {
221         self.stdout = Some(stdout);
222     }
223     pub fn stderr(&mut self, stderr: Stdio) {
224         self.stderr = Some(stderr);
225     }
226     pub fn creation_flags(&mut self, flags: u32) {
227         self.flags = flags;
228     }
229
230     pub fn force_quotes(&mut self, enabled: bool) {
231         self.force_quotes_enabled = enabled;
232     }
233
234     pub fn raw_arg(&mut self, command_str_to_append: &OsStr) {
235         self.args.push(Arg::Raw(command_str_to_append.to_os_string()))
236     }
237
238     pub fn get_program(&self) -> &OsStr {
239         &self.program
240     }
241
242     pub fn get_args(&self) -> CommandArgs<'_> {
243         let iter = self.args.iter();
244         CommandArgs { iter }
245     }
246
247     pub fn get_envs(&self) -> CommandEnvs<'_> {
248         self.env.iter()
249     }
250
251     pub fn get_current_dir(&self) -> Option<&Path> {
252         self.cwd.as_ref().map(|cwd| Path::new(cwd))
253     }
254
255     pub fn spawn(
256         &mut self,
257         default: Stdio,
258         needs_stdin: bool,
259     ) -> io::Result<(Process, StdioPipes)> {
260         let maybe_env = self.env.capture_if_changed();
261
262         let mut si = zeroed_startupinfo();
263         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
264         si.dwFlags = c::STARTF_USESTDHANDLES;
265
266         let child_paths = if let Some(env) = maybe_env.as_ref() {
267             env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
268         } else {
269             None
270         };
271         let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
272         let mut cmd_str =
273             make_command_line(program.as_os_str(), &self.args, self.force_quotes_enabled)?;
274         cmd_str.push(0); // add null terminator
275
276         // stolen from the libuv code.
277         let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
278         if self.detach {
279             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
280         }
281
282         let (envp, _data) = make_envp(maybe_env)?;
283         let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
284         let mut pi = zeroed_process_information();
285
286         // Prepare all stdio handles to be inherited by the child. This
287         // currently involves duplicating any existing ones with the ability to
288         // be inherited by child processes. Note, however, that once an
289         // inheritable handle is created, *any* spawned child will inherit that
290         // handle. We only want our own child to inherit this handle, so we wrap
291         // the remaining portion of this spawn in a mutex.
292         //
293         // For more information, msdn also has an article about this race:
294         // https://support.microsoft.com/kb/315939
295         static CREATE_PROCESS_LOCK: StaticMutex = StaticMutex::new();
296
297         let _guard = unsafe { CREATE_PROCESS_LOCK.lock() };
298
299         let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
300         let null = Stdio::Null;
301         let default_stdin = if needs_stdin { &default } else { &null };
302         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
303         let stdout = self.stdout.as_ref().unwrap_or(&default);
304         let stderr = self.stderr.as_ref().unwrap_or(&default);
305         let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
306         let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
307         let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
308         si.hStdInput = stdin.as_raw_handle();
309         si.hStdOutput = stdout.as_raw_handle();
310         si.hStdError = stderr.as_raw_handle();
311
312         let program = to_u16s(&program)?;
313         unsafe {
314             cvt(c::CreateProcessW(
315                 program.as_ptr(),
316                 cmd_str.as_mut_ptr(),
317                 ptr::null_mut(),
318                 ptr::null_mut(),
319                 c::TRUE,
320                 flags,
321                 envp,
322                 dirp,
323                 &mut si,
324                 &mut pi,
325             ))
326         }?;
327
328         // We close the thread handle because we don't care about keeping
329         // the thread id valid, and we aren't keeping the thread handle
330         // around to be able to close it later.
331         unsafe {
332             drop(Handle::from_raw_handle(pi.hThread));
333
334             Ok((Process { handle: Handle::from_raw_handle(pi.hProcess) }, pipes))
335         }
336     }
337 }
338
339 impl fmt::Debug for Command {
340     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
341         self.program.fmt(f)?;
342         for arg in &self.args {
343             f.write_str(" ")?;
344             match arg {
345                 Arg::Regular(s) => s.fmt(f),
346                 Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
347             }?;
348         }
349         Ok(())
350     }
351 }
352
353 // Resolve `exe_path` to the executable name.
354 //
355 // * If the path is simply a file name then use the paths given by `search_paths` to find the executable.
356 // * Otherwise use the `exe_path` as given.
357 //
358 // This function may also append `.exe` to the name. The rationale for doing so is as follows:
359 //
360 // It is a very strong convention that Windows executables have the `exe` extension.
361 // In Rust, it is common to omit this extension.
362 // Therefore this functions first assumes `.exe` was intended.
363 // It falls back to the plain file name if a full path is given and the extension is omitted
364 // or if only a file name is given and it already contains an extension.
365 fn resolve_exe<'a>(
366     exe_path: &'a OsStr,
367     parent_paths: impl FnOnce() -> Option<OsString>,
368     child_paths: Option<&OsStr>,
369 ) -> io::Result<PathBuf> {
370     // Early return if there is no filename.
371     if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
372         return Err(io::const_io_error!(
373             io::ErrorKind::InvalidInput,
374             "program path has no file name",
375         ));
376     }
377     // Test if the file name has the `exe` extension.
378     // This does a case-insensitive `ends_with`.
379     let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
380         exe_path.bytes()[exe_path.len() - EXE_SUFFIX.len()..]
381             .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
382     } else {
383         false
384     };
385
386     // If `exe_path` is an absolute path or a sub-path then don't search `PATH` for it.
387     if !path::is_file_name(exe_path) {
388         if has_exe_suffix {
389             // The application name is a path to a `.exe` file.
390             // Let `CreateProcessW` figure out if it exists or not.
391             return Ok(exe_path.into());
392         }
393         let mut path = PathBuf::from(exe_path);
394
395         // Append `.exe` if not already there.
396         path = path::append_suffix(path, EXE_SUFFIX.as_ref());
397         if program_exists(&path) {
398             return Ok(path);
399         } else {
400             // It's ok to use `set_extension` here because the intent is to
401             // remove the extension that was just added.
402             path.set_extension("");
403             return Ok(path);
404         }
405     } else {
406         ensure_no_nuls(exe_path)?;
407         // From the `CreateProcessW` docs:
408         // > If the file name does not contain an extension, .exe is appended.
409         // Note that this rule only applies when searching paths.
410         let has_extension = exe_path.bytes().contains(&b'.');
411
412         // Search the directories given by `search_paths`.
413         let result = search_paths(parent_paths, child_paths, |mut path| {
414             path.push(&exe_path);
415             if !has_extension {
416                 path.set_extension(EXE_EXTENSION);
417             }
418             if program_exists(&path) { Some(path) } else { None }
419         });
420         if let Some(path) = result {
421             return Ok(path);
422         }
423     }
424     // If we get here then the executable cannot be found.
425     Err(io::const_io_error!(io::ErrorKind::NotFound, "program not found"))
426 }
427
428 // Calls `f` for every path that should be used to find an executable.
429 // Returns once `f` returns the path to an executable or all paths have been searched.
430 fn search_paths<Paths, Exists>(
431     parent_paths: Paths,
432     child_paths: Option<&OsStr>,
433     mut exists: Exists,
434 ) -> Option<PathBuf>
435 where
436     Paths: FnOnce() -> Option<OsString>,
437     Exists: FnMut(PathBuf) -> Option<PathBuf>,
438 {
439     // 1. Child paths
440     // This is for consistency with Rust's historic behaviour.
441     if let Some(paths) = child_paths {
442         for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
443             if let Some(path) = exists(path) {
444                 return Some(path);
445             }
446         }
447     }
448
449     // 2. Application path
450     if let Ok(mut app_path) = env::current_exe() {
451         app_path.pop();
452         if let Some(path) = exists(app_path) {
453             return Some(path);
454         }
455     }
456
457     // 3 & 4. System paths
458     // SAFETY: This uses `fill_utf16_buf` to safely call the OS functions.
459     unsafe {
460         if let Ok(Some(path)) = super::fill_utf16_buf(
461             |buf, size| c::GetSystemDirectoryW(buf, size),
462             |buf| exists(PathBuf::from(OsString::from_wide(buf))),
463         ) {
464             return Some(path);
465         }
466         #[cfg(not(target_vendor = "uwp"))]
467         {
468             if let Ok(Some(path)) = super::fill_utf16_buf(
469                 |buf, size| c::GetWindowsDirectoryW(buf, size),
470                 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
471             ) {
472                 return Some(path);
473             }
474         }
475     }
476
477     // 5. Parent paths
478     if let Some(parent_paths) = parent_paths() {
479         for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
480             if let Some(path) = exists(path) {
481                 return Some(path);
482             }
483         }
484     }
485     None
486 }
487
488 /// Check if a file exists without following symlinks.
489 fn program_exists(path: &Path) -> bool {
490     unsafe {
491         to_u16s(path)
492             .map(|path| {
493                 // Getting attributes using `GetFileAttributesW` does not follow symlinks
494                 // and it will almost always be successful if the link exists.
495                 // There are some exceptions for special system files (e.g. the pagefile)
496                 // but these are not executable.
497                 c::GetFileAttributesW(path.as_ptr()) != c::INVALID_FILE_ATTRIBUTES
498             })
499             .unwrap_or(false)
500     }
501 }
502
503 impl Stdio {
504     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
505         match *self {
506             // If no stdio handle is available, then inherit means that it
507             // should still be unavailable so propagate the
508             // INVALID_HANDLE_VALUE.
509             Stdio::Inherit => match stdio::get_handle(stdio_id) {
510                 Ok(io) => unsafe {
511                     let io = Handle::from_raw_handle(io);
512                     let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
513                     io.into_raw_handle();
514                     ret
515                 },
516                 Err(..) => unsafe { Ok(Handle::from_raw_handle(c::INVALID_HANDLE_VALUE)) },
517             },
518
519             Stdio::MakePipe => {
520                 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
521                 let pipes = pipe::anon_pipe(ours_readable, true)?;
522                 *pipe = Some(pipes.ours);
523                 Ok(pipes.theirs.into_handle())
524             }
525
526             Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
527
528             // Open up a reference to NUL with appropriate read/write
529             // permissions as well as the ability to be inherited to child
530             // processes (as this is about to be inherited).
531             Stdio::Null => {
532                 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
533                 let mut sa = c::SECURITY_ATTRIBUTES {
534                     nLength: size as c::DWORD,
535                     lpSecurityDescriptor: ptr::null_mut(),
536                     bInheritHandle: 1,
537                 };
538                 let mut opts = OpenOptions::new();
539                 opts.read(stdio_id == c::STD_INPUT_HANDLE);
540                 opts.write(stdio_id != c::STD_INPUT_HANDLE);
541                 opts.security_attributes(&mut sa);
542                 File::open(Path::new("NUL"), &opts).map(|file| file.into_inner())
543             }
544         }
545     }
546 }
547
548 impl From<AnonPipe> for Stdio {
549     fn from(pipe: AnonPipe) -> Stdio {
550         Stdio::Handle(pipe.into_handle())
551     }
552 }
553
554 impl From<File> for Stdio {
555     fn from(file: File) -> Stdio {
556         Stdio::Handle(file.into_inner())
557     }
558 }
559
560 ////////////////////////////////////////////////////////////////////////////////
561 // Processes
562 ////////////////////////////////////////////////////////////////////////////////
563
564 /// A value representing a child process.
565 ///
566 /// The lifetime of this value is linked to the lifetime of the actual
567 /// process - the Process destructor calls self.finish() which waits
568 /// for the process to terminate.
569 pub struct Process {
570     handle: Handle,
571 }
572
573 impl Process {
574     pub fn kill(&mut self) -> io::Result<()> {
575         cvt(unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) })?;
576         Ok(())
577     }
578
579     pub fn id(&self) -> u32 {
580         unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
581     }
582
583     pub fn wait(&mut self) -> io::Result<ExitStatus> {
584         unsafe {
585             let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
586             if res != c::WAIT_OBJECT_0 {
587                 return Err(Error::last_os_error());
588             }
589             let mut status = 0;
590             cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
591             Ok(ExitStatus(status))
592         }
593     }
594
595     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
596         unsafe {
597             match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
598                 c::WAIT_OBJECT_0 => {}
599                 c::WAIT_TIMEOUT => {
600                     return Ok(None);
601                 }
602                 _ => return Err(io::Error::last_os_error()),
603             }
604             let mut status = 0;
605             cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
606             Ok(Some(ExitStatus(status)))
607         }
608     }
609
610     pub fn handle(&self) -> &Handle {
611         &self.handle
612     }
613
614     pub fn into_handle(self) -> Handle {
615         self.handle
616     }
617 }
618
619 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
620 pub struct ExitStatus(c::DWORD);
621
622 impl ExitStatus {
623     pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
624         match NonZeroDWORD::try_from(self.0) {
625             /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
626             /* was zero, couldn't convert */ Err(_) => Ok(()),
627         }
628     }
629     pub fn code(&self) -> Option<i32> {
630         Some(self.0 as i32)
631     }
632 }
633
634 /// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
635 impl From<c::DWORD> for ExitStatus {
636     fn from(u: c::DWORD) -> ExitStatus {
637         ExitStatus(u)
638     }
639 }
640
641 impl fmt::Display for ExitStatus {
642     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643         // Windows exit codes with the high bit set typically mean some form of
644         // unhandled exception or warning. In this scenario printing the exit
645         // code in decimal doesn't always make sense because it's a very large
646         // and somewhat gibberish number. The hex code is a bit more
647         // recognizable and easier to search for, so print that.
648         if self.0 & 0x80000000 != 0 {
649             write!(f, "exit code: {:#x}", self.0)
650         } else {
651             write!(f, "exit code: {}", self.0)
652         }
653     }
654 }
655
656 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
657 pub struct ExitStatusError(c::NonZeroDWORD);
658
659 impl Into<ExitStatus> for ExitStatusError {
660     fn into(self) -> ExitStatus {
661         ExitStatus(self.0.into())
662     }
663 }
664
665 impl ExitStatusError {
666     pub fn code(self) -> Option<NonZeroI32> {
667         Some((u32::from(self.0) as i32).try_into().unwrap())
668     }
669 }
670
671 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
672 pub struct ExitCode(c::DWORD);
673
674 impl ExitCode {
675     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
676     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
677
678     #[inline]
679     pub fn as_i32(&self) -> i32 {
680         self.0 as i32
681     }
682 }
683
684 impl From<u8> for ExitCode {
685     fn from(code: u8) -> Self {
686         ExitCode(c::DWORD::from(code))
687     }
688 }
689
690 fn zeroed_startupinfo() -> c::STARTUPINFO {
691     c::STARTUPINFO {
692         cb: 0,
693         lpReserved: ptr::null_mut(),
694         lpDesktop: ptr::null_mut(),
695         lpTitle: ptr::null_mut(),
696         dwX: 0,
697         dwY: 0,
698         dwXSize: 0,
699         dwYSize: 0,
700         dwXCountChars: 0,
701         dwYCountCharts: 0,
702         dwFillAttribute: 0,
703         dwFlags: 0,
704         wShowWindow: 0,
705         cbReserved2: 0,
706         lpReserved2: ptr::null_mut(),
707         hStdInput: c::INVALID_HANDLE_VALUE,
708         hStdOutput: c::INVALID_HANDLE_VALUE,
709         hStdError: c::INVALID_HANDLE_VALUE,
710     }
711 }
712
713 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
714     c::PROCESS_INFORMATION {
715         hProcess: ptr::null_mut(),
716         hThread: ptr::null_mut(),
717         dwProcessId: 0,
718         dwThreadId: 0,
719     }
720 }
721
722 enum Quote {
723     // Every arg is quoted
724     Always,
725     // Whitespace and empty args are quoted
726     Auto,
727     // Arg appended without any changes (#29494)
728     Never,
729 }
730
731 // Produces a wide string *without terminating null*; returns an error if
732 // `prog` or any of the `args` contain a nul.
733 fn make_command_line(prog: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
734     // Encode the command and arguments in a command line string such
735     // that the spawned process may recover them using CommandLineToArgvW.
736     let mut cmd: Vec<u16> = Vec::new();
737
738     // CreateFileW has special handling for .bat and .cmd files, which means we
739     // need to add an extra pair of quotes surrounding the whole command line
740     // so they are properly passed on to the script.
741     // See issue #91991.
742     let is_batch_file = Path::new(prog)
743         .extension()
744         .map(|ext| ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("bat"))
745         .unwrap_or(false);
746     if is_batch_file {
747         cmd.push(b'"' as u16);
748     }
749
750     // Always quote the program name so CreateProcess doesn't interpret args as
751     // part of the name if the binary wasn't found first time.
752     append_arg(&mut cmd, prog, Quote::Always)?;
753     for arg in args {
754         cmd.push(' ' as u16);
755         let (arg, quote) = match arg {
756             Arg::Regular(arg) => (arg, if force_quotes { Quote::Always } else { Quote::Auto }),
757             Arg::Raw(arg) => (arg, Quote::Never),
758         };
759         append_arg(&mut cmd, arg, quote)?;
760     }
761     if is_batch_file {
762         cmd.push(b'"' as u16);
763     }
764     return Ok(cmd);
765
766     fn append_arg(cmd: &mut Vec<u16>, arg: &OsStr, quote: Quote) -> io::Result<()> {
767         // If an argument has 0 characters then we need to quote it to ensure
768         // that it actually gets passed through on the command line or otherwise
769         // it will be dropped entirely when parsed on the other end.
770         ensure_no_nuls(arg)?;
771         let arg_bytes = &arg.as_inner().inner.as_inner();
772         let (quote, escape) = match quote {
773             Quote::Always => (true, true),
774             Quote::Auto => {
775                 (arg_bytes.iter().any(|c| *c == b' ' || *c == b'\t') || arg_bytes.is_empty(), true)
776             }
777             Quote::Never => (false, false),
778         };
779         if quote {
780             cmd.push('"' as u16);
781         }
782
783         let mut backslashes: usize = 0;
784         for x in arg.encode_wide() {
785             if escape {
786                 if x == '\\' as u16 {
787                     backslashes += 1;
788                 } else {
789                     if x == '"' as u16 {
790                         // Add n+1 backslashes to total 2n+1 before internal '"'.
791                         cmd.extend((0..=backslashes).map(|_| '\\' as u16));
792                     }
793                     backslashes = 0;
794                 }
795             }
796             cmd.push(x);
797         }
798
799         if quote {
800             // Add n backslashes to total 2n before ending '"'.
801             cmd.extend((0..backslashes).map(|_| '\\' as u16));
802             cmd.push('"' as u16);
803         }
804         Ok(())
805     }
806 }
807
808 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
809     // On Windows we pass an "environment block" which is not a char**, but
810     // rather a concatenation of null-terminated k=v\0 sequences, with a final
811     // \0 to terminate.
812     if let Some(env) = maybe_env {
813         let mut blk = Vec::new();
814
815         // If there are no environment variables to set then signal this by
816         // pushing a null.
817         if env.is_empty() {
818             blk.push(0);
819         }
820
821         for (k, v) in env {
822             ensure_no_nuls(k.os_string)?;
823             blk.extend(k.utf16);
824             blk.push('=' as u16);
825             blk.extend(ensure_no_nuls(v)?.encode_wide());
826             blk.push(0);
827         }
828         blk.push(0);
829         Ok((blk.as_mut_ptr() as *mut c_void, blk))
830     } else {
831         Ok((ptr::null_mut(), Vec::new()))
832     }
833 }
834
835 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
836     match d {
837         Some(dir) => {
838             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
839             dir_str.push(0);
840             Ok((dir_str.as_ptr(), dir_str))
841         }
842         None => Ok((ptr::null(), Vec::new())),
843     }
844 }
845
846 pub struct CommandArgs<'a> {
847     iter: crate::slice::Iter<'a, Arg>,
848 }
849
850 impl<'a> Iterator for CommandArgs<'a> {
851     type Item = &'a OsStr;
852     fn next(&mut self) -> Option<&'a OsStr> {
853         self.iter.next().map(|arg| match arg {
854             Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
855         })
856     }
857     fn size_hint(&self) -> (usize, Option<usize>) {
858         self.iter.size_hint()
859     }
860 }
861
862 impl<'a> ExactSizeIterator for CommandArgs<'a> {
863     fn len(&self) -> usize {
864         self.iter.len()
865     }
866     fn is_empty(&self) -> bool {
867         self.iter.is_empty()
868     }
869 }
870
871 impl<'a> fmt::Debug for CommandArgs<'a> {
872     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
873         f.debug_list().entries(self.iter.clone()).finish()
874     }
875 }