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