]> git.lizzy.rs Git - rust.git/blob - library/std/src/sys/windows/process.rs
Rollup merge of #106273 - notriddle:notriddle/source-content-overflow, r=GuillaumeGomez
[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::env;
9 use crate::env::consts::{EXE_EXTENSION, EXE_SUFFIX};
10 use crate::ffi::{OsStr, OsString};
11 use crate::fmt;
12 use crate::io::{self, Error, ErrorKind};
13 use crate::mem;
14 use crate::num::NonZeroI32;
15 use crate::os::windows::ffi::{OsStrExt, OsStringExt};
16 use crate::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, FromRawHandle, IntoRawHandle};
17 use crate::path::{Path, PathBuf};
18 use crate::ptr;
19 use crate::sync::Mutex;
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::process::{CommandEnv, CommandEnvs};
30 use crate::sys_common::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 pub(crate) 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     Pipe(AnonPipe),
176     Handle(Handle),
177 }
178
179 pub struct StdioPipes {
180     pub stdin: Option<AnonPipe>,
181     pub stdout: Option<AnonPipe>,
182     pub stderr: Option<AnonPipe>,
183 }
184
185 impl Command {
186     pub fn new(program: &OsStr) -> Command {
187         Command {
188             program: program.to_os_string(),
189             args: Vec::new(),
190             env: Default::default(),
191             cwd: None,
192             flags: 0,
193             detach: false,
194             stdin: None,
195             stdout: None,
196             stderr: None,
197             force_quotes_enabled: false,
198         }
199     }
200
201     pub fn arg(&mut self, arg: &OsStr) {
202         self.args.push(Arg::Regular(arg.to_os_string()))
203     }
204     pub fn env_mut(&mut self) -> &mut CommandEnv {
205         &mut self.env
206     }
207     pub fn cwd(&mut self, dir: &OsStr) {
208         self.cwd = Some(dir.to_os_string())
209     }
210     pub fn stdin(&mut self, stdin: Stdio) {
211         self.stdin = Some(stdin);
212     }
213     pub fn stdout(&mut self, stdout: Stdio) {
214         self.stdout = Some(stdout);
215     }
216     pub fn stderr(&mut self, stderr: Stdio) {
217         self.stderr = Some(stderr);
218     }
219     pub fn creation_flags(&mut self, flags: u32) {
220         self.flags = flags;
221     }
222
223     pub fn force_quotes(&mut self, enabled: bool) {
224         self.force_quotes_enabled = enabled;
225     }
226
227     pub fn raw_arg(&mut self, command_str_to_append: &OsStr) {
228         self.args.push(Arg::Raw(command_str_to_append.to_os_string()))
229     }
230
231     pub fn get_program(&self) -> &OsStr {
232         &self.program
233     }
234
235     pub fn get_args(&self) -> CommandArgs<'_> {
236         let iter = self.args.iter();
237         CommandArgs { iter }
238     }
239
240     pub fn get_envs(&self) -> CommandEnvs<'_> {
241         self.env.iter()
242     }
243
244     pub fn get_current_dir(&self) -> Option<&Path> {
245         self.cwd.as_ref().map(|cwd| Path::new(cwd))
246     }
247
248     pub fn spawn(
249         &mut self,
250         default: Stdio,
251         needs_stdin: bool,
252     ) -> io::Result<(Process, StdioPipes)> {
253         let maybe_env = self.env.capture_if_changed();
254
255         let child_paths = if let Some(env) = maybe_env.as_ref() {
256             env.get(&EnvKey::new("PATH")).map(|s| s.as_os_str())
257         } else {
258             None
259         };
260         let program = resolve_exe(&self.program, || env::var_os("PATH"), child_paths)?;
261         // Case insensitive "ends_with" of UTF-16 encoded ".bat" or ".cmd"
262         let is_batch_file = matches!(
263             program.len().checked_sub(5).and_then(|i| program.get(i..)),
264             Some([46, 98 | 66, 97 | 65, 116 | 84, 0] | [46, 99 | 67, 109 | 77, 100 | 68, 0])
265         );
266         let (program, mut cmd_str) = if is_batch_file {
267             (
268                 command_prompt()?,
269                 args::make_bat_command_line(
270                     &args::to_user_path(program)?,
271                     &self.args,
272                     self.force_quotes_enabled,
273                 )?,
274             )
275         } else {
276             let cmd_str = make_command_line(&self.program, &self.args, self.force_quotes_enabled)?;
277             (program, cmd_str)
278         };
279         cmd_str.push(0); // add null terminator
280
281         // stolen from the libuv code.
282         let mut flags = self.flags | c::CREATE_UNICODE_ENVIRONMENT;
283         if self.detach {
284             flags |= c::DETACHED_PROCESS | c::CREATE_NEW_PROCESS_GROUP;
285         }
286
287         let (envp, _data) = make_envp(maybe_env)?;
288         let (dirp, _data) = make_dirp(self.cwd.as_ref())?;
289         let mut pi = zeroed_process_information();
290
291         // Prepare all stdio handles to be inherited by the child. This
292         // currently involves duplicating any existing ones with the ability to
293         // be inherited by child processes. Note, however, that once an
294         // inheritable handle is created, *any* spawned child will inherit that
295         // handle. We only want our own child to inherit this handle, so we wrap
296         // the remaining portion of this spawn in a mutex.
297         //
298         // For more information, msdn also has an article about this race:
299         // https://support.microsoft.com/kb/315939
300         static CREATE_PROCESS_LOCK: Mutex<()> = Mutex::new(());
301
302         let _guard = CREATE_PROCESS_LOCK.lock();
303
304         let mut pipes = StdioPipes { stdin: None, stdout: None, stderr: None };
305         let null = Stdio::Null;
306         let default_stdin = if needs_stdin { &default } else { &null };
307         let stdin = self.stdin.as_ref().unwrap_or(default_stdin);
308         let stdout = self.stdout.as_ref().unwrap_or(&default);
309         let stderr = self.stderr.as_ref().unwrap_or(&default);
310         let stdin = stdin.to_handle(c::STD_INPUT_HANDLE, &mut pipes.stdin)?;
311         let stdout = stdout.to_handle(c::STD_OUTPUT_HANDLE, &mut pipes.stdout)?;
312         let stderr = stderr.to_handle(c::STD_ERROR_HANDLE, &mut pipes.stderr)?;
313
314         let mut si = zeroed_startupinfo();
315         si.cb = mem::size_of::<c::STARTUPINFO>() as c::DWORD;
316
317         // If at least one of stdin, stdout or stderr are set (i.e. are non null)
318         // then set the `hStd` fields in `STARTUPINFO`.
319         // Otherwise skip this and allow the OS to apply its default behaviour.
320         // This provides more consistent behaviour between Win7 and Win8+.
321         let is_set = |stdio: &Handle| !stdio.as_raw_handle().is_null();
322         if is_set(&stderr) || is_set(&stdout) || is_set(&stdin) {
323             si.dwFlags |= c::STARTF_USESTDHANDLES;
324             si.hStdInput = stdin.as_raw_handle();
325             si.hStdOutput = stdout.as_raw_handle();
326             si.hStdError = stderr.as_raw_handle();
327         }
328
329         unsafe {
330             cvt(c::CreateProcessW(
331                 program.as_ptr(),
332                 cmd_str.as_mut_ptr(),
333                 ptr::null_mut(),
334                 ptr::null_mut(),
335                 c::TRUE,
336                 flags,
337                 envp,
338                 dirp,
339                 &mut si,
340                 &mut pi,
341             ))
342         }?;
343
344         unsafe {
345             Ok((
346                 Process {
347                     handle: Handle::from_raw_handle(pi.hProcess),
348                     main_thread_handle: Handle::from_raw_handle(pi.hThread),
349                 },
350                 pipes,
351             ))
352         }
353     }
354
355     pub fn output(&mut self) -> io::Result<(ExitStatus, Vec<u8>, Vec<u8>)> {
356         let (proc, pipes) = self.spawn(Stdio::MakePipe, false)?;
357         crate::sys_common::process::wait_with_output(proc, pipes)
358     }
359 }
360
361 impl fmt::Debug for Command {
362     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
363         self.program.fmt(f)?;
364         for arg in &self.args {
365             f.write_str(" ")?;
366             match arg {
367                 Arg::Regular(s) => s.fmt(f),
368                 Arg::Raw(s) => f.write_str(&s.to_string_lossy()),
369             }?;
370         }
371         Ok(())
372     }
373 }
374
375 // Resolve `exe_path` to the executable name.
376 //
377 // * If the path is simply a file name then use the paths given by `search_paths` to find the executable.
378 // * Otherwise use the `exe_path` as given.
379 //
380 // This function may also append `.exe` to the name. The rationale for doing so is as follows:
381 //
382 // It is a very strong convention that Windows executables have the `exe` extension.
383 // In Rust, it is common to omit this extension.
384 // Therefore this functions first assumes `.exe` was intended.
385 // It falls back to the plain file name if a full path is given and the extension is omitted
386 // or if only a file name is given and it already contains an extension.
387 fn resolve_exe<'a>(
388     exe_path: &'a OsStr,
389     parent_paths: impl FnOnce() -> Option<OsString>,
390     child_paths: Option<&OsStr>,
391 ) -> io::Result<Vec<u16>> {
392     // Early return if there is no filename.
393     if exe_path.is_empty() || path::has_trailing_slash(exe_path) {
394         return Err(io::const_io_error!(
395             io::ErrorKind::InvalidInput,
396             "program path has no file name",
397         ));
398     }
399     // Test if the file name has the `exe` extension.
400     // This does a case-insensitive `ends_with`.
401     let has_exe_suffix = if exe_path.len() >= EXE_SUFFIX.len() {
402         exe_path.bytes()[exe_path.len() - EXE_SUFFIX.len()..]
403             .eq_ignore_ascii_case(EXE_SUFFIX.as_bytes())
404     } else {
405         false
406     };
407
408     // If `exe_path` is an absolute path or a sub-path then don't search `PATH` for it.
409     if !path::is_file_name(exe_path) {
410         if has_exe_suffix {
411             // The application name is a path to a `.exe` file.
412             // Let `CreateProcessW` figure out if it exists or not.
413             return path::maybe_verbatim(Path::new(exe_path));
414         }
415         let mut path = PathBuf::from(exe_path);
416
417         // Append `.exe` if not already there.
418         path = path::append_suffix(path, EXE_SUFFIX.as_ref());
419         if let Some(path) = program_exists(&path) {
420             return Ok(path);
421         } else {
422             // It's ok to use `set_extension` here because the intent is to
423             // remove the extension that was just added.
424             path.set_extension("");
425             return path::maybe_verbatim(&path);
426         }
427     } else {
428         ensure_no_nuls(exe_path)?;
429         // From the `CreateProcessW` docs:
430         // > If the file name does not contain an extension, .exe is appended.
431         // Note that this rule only applies when searching paths.
432         let has_extension = exe_path.bytes().contains(&b'.');
433
434         // Search the directories given by `search_paths`.
435         let result = search_paths(parent_paths, child_paths, |mut path| {
436             path.push(&exe_path);
437             if !has_extension {
438                 path.set_extension(EXE_EXTENSION);
439             }
440             program_exists(&path)
441         });
442         if let Some(path) = result {
443             return Ok(path);
444         }
445     }
446     // If we get here then the executable cannot be found.
447     Err(io::const_io_error!(io::ErrorKind::NotFound, "program not found"))
448 }
449
450 // Calls `f` for every path that should be used to find an executable.
451 // Returns once `f` returns the path to an executable or all paths have been searched.
452 fn search_paths<Paths, Exists>(
453     parent_paths: Paths,
454     child_paths: Option<&OsStr>,
455     mut exists: Exists,
456 ) -> Option<Vec<u16>>
457 where
458     Paths: FnOnce() -> Option<OsString>,
459     Exists: FnMut(PathBuf) -> Option<Vec<u16>>,
460 {
461     // 1. Child paths
462     // This is for consistency with Rust's historic behaviour.
463     if let Some(paths) = child_paths {
464         for path in env::split_paths(paths).filter(|p| !p.as_os_str().is_empty()) {
465             if let Some(path) = exists(path) {
466                 return Some(path);
467             }
468         }
469     }
470
471     // 2. Application path
472     if let Ok(mut app_path) = env::current_exe() {
473         app_path.pop();
474         if let Some(path) = exists(app_path) {
475             return Some(path);
476         }
477     }
478
479     // 3 & 4. System paths
480     // SAFETY: This uses `fill_utf16_buf` to safely call the OS functions.
481     unsafe {
482         if let Ok(Some(path)) = super::fill_utf16_buf(
483             |buf, size| c::GetSystemDirectoryW(buf, size),
484             |buf| exists(PathBuf::from(OsString::from_wide(buf))),
485         ) {
486             return Some(path);
487         }
488         #[cfg(not(target_vendor = "uwp"))]
489         {
490             if let Ok(Some(path)) = super::fill_utf16_buf(
491                 |buf, size| c::GetWindowsDirectoryW(buf, size),
492                 |buf| exists(PathBuf::from(OsString::from_wide(buf))),
493             ) {
494                 return Some(path);
495             }
496         }
497     }
498
499     // 5. Parent paths
500     if let Some(parent_paths) = parent_paths() {
501         for path in env::split_paths(&parent_paths).filter(|p| !p.as_os_str().is_empty()) {
502             if let Some(path) = exists(path) {
503                 return Some(path);
504             }
505         }
506     }
507     None
508 }
509
510 /// Check if a file exists without following symlinks.
511 fn program_exists(path: &Path) -> Option<Vec<u16>> {
512     unsafe {
513         let path = path::maybe_verbatim(path).ok()?;
514         // Getting attributes using `GetFileAttributesW` does not follow symlinks
515         // and it will almost always be successful if the link exists.
516         // There are some exceptions for special system files (e.g. the pagefile)
517         // but these are not executable.
518         if c::GetFileAttributesW(path.as_ptr()) == c::INVALID_FILE_ATTRIBUTES {
519             None
520         } else {
521             Some(path)
522         }
523     }
524 }
525
526 impl Stdio {
527     fn to_handle(&self, stdio_id: c::DWORD, pipe: &mut Option<AnonPipe>) -> io::Result<Handle> {
528         match *self {
529             Stdio::Inherit => match stdio::get_handle(stdio_id) {
530                 Ok(io) => unsafe {
531                     let io = Handle::from_raw_handle(io);
532                     let ret = io.duplicate(0, true, c::DUPLICATE_SAME_ACCESS);
533                     io.into_raw_handle();
534                     ret
535                 },
536                 // If no stdio handle is available, then propagate the null value.
537                 Err(..) => unsafe { Ok(Handle::from_raw_handle(ptr::null_mut())) },
538             },
539
540             Stdio::MakePipe => {
541                 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
542                 let pipes = pipe::anon_pipe(ours_readable, true)?;
543                 *pipe = Some(pipes.ours);
544                 Ok(pipes.theirs.into_handle())
545             }
546
547             Stdio::Pipe(ref source) => {
548                 let ours_readable = stdio_id != c::STD_INPUT_HANDLE;
549                 pipe::spawn_pipe_relay(source, ours_readable, true).map(AnonPipe::into_handle)
550             }
551
552             Stdio::Handle(ref handle) => handle.duplicate(0, true, c::DUPLICATE_SAME_ACCESS),
553
554             // Open up a reference to NUL with appropriate read/write
555             // permissions as well as the ability to be inherited to child
556             // processes (as this is about to be inherited).
557             Stdio::Null => {
558                 let size = mem::size_of::<c::SECURITY_ATTRIBUTES>();
559                 let mut sa = c::SECURITY_ATTRIBUTES {
560                     nLength: size as c::DWORD,
561                     lpSecurityDescriptor: ptr::null_mut(),
562                     bInheritHandle: 1,
563                 };
564                 let mut opts = OpenOptions::new();
565                 opts.read(stdio_id == c::STD_INPUT_HANDLE);
566                 opts.write(stdio_id != c::STD_INPUT_HANDLE);
567                 opts.security_attributes(&mut sa);
568                 File::open(Path::new("NUL"), &opts).map(|file| file.into_inner())
569             }
570         }
571     }
572 }
573
574 impl From<AnonPipe> for Stdio {
575     fn from(pipe: AnonPipe) -> Stdio {
576         Stdio::Pipe(pipe)
577     }
578 }
579
580 impl From<File> for Stdio {
581     fn from(file: File) -> Stdio {
582         Stdio::Handle(file.into_inner())
583     }
584 }
585
586 ////////////////////////////////////////////////////////////////////////////////
587 // Processes
588 ////////////////////////////////////////////////////////////////////////////////
589
590 /// A value representing a child process.
591 ///
592 /// The lifetime of this value is linked to the lifetime of the actual
593 /// process - the Process destructor calls self.finish() which waits
594 /// for the process to terminate.
595 pub struct Process {
596     handle: Handle,
597     main_thread_handle: Handle,
598 }
599
600 impl Process {
601     pub fn kill(&mut self) -> io::Result<()> {
602         cvt(unsafe { c::TerminateProcess(self.handle.as_raw_handle(), 1) })?;
603         Ok(())
604     }
605
606     pub fn id(&self) -> u32 {
607         unsafe { c::GetProcessId(self.handle.as_raw_handle()) as u32 }
608     }
609
610     pub fn main_thread_handle(&self) -> BorrowedHandle<'_> {
611         self.main_thread_handle.as_handle()
612     }
613
614     pub fn wait(&mut self) -> io::Result<ExitStatus> {
615         unsafe {
616             let res = c::WaitForSingleObject(self.handle.as_raw_handle(), c::INFINITE);
617             if res != c::WAIT_OBJECT_0 {
618                 return Err(Error::last_os_error());
619             }
620             let mut status = 0;
621             cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
622             Ok(ExitStatus(status))
623         }
624     }
625
626     pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
627         unsafe {
628             match c::WaitForSingleObject(self.handle.as_raw_handle(), 0) {
629                 c::WAIT_OBJECT_0 => {}
630                 c::WAIT_TIMEOUT => {
631                     return Ok(None);
632                 }
633                 _ => return Err(io::Error::last_os_error()),
634             }
635             let mut status = 0;
636             cvt(c::GetExitCodeProcess(self.handle.as_raw_handle(), &mut status))?;
637             Ok(Some(ExitStatus(status)))
638         }
639     }
640
641     pub fn handle(&self) -> &Handle {
642         &self.handle
643     }
644
645     pub fn into_handle(self) -> Handle {
646         self.handle
647     }
648 }
649
650 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
651 pub struct ExitStatus(c::DWORD);
652
653 impl ExitStatus {
654     pub fn exit_ok(&self) -> Result<(), ExitStatusError> {
655         match NonZeroDWORD::try_from(self.0) {
656             /* was nonzero */ Ok(failure) => Err(ExitStatusError(failure)),
657             /* was zero, couldn't convert */ Err(_) => Ok(()),
658         }
659     }
660     pub fn code(&self) -> Option<i32> {
661         Some(self.0 as i32)
662     }
663 }
664
665 /// Converts a raw `c::DWORD` to a type-safe `ExitStatus` by wrapping it without copying.
666 impl From<c::DWORD> for ExitStatus {
667     fn from(u: c::DWORD) -> ExitStatus {
668         ExitStatus(u)
669     }
670 }
671
672 impl fmt::Display for ExitStatus {
673     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674         // Windows exit codes with the high bit set typically mean some form of
675         // unhandled exception or warning. In this scenario printing the exit
676         // code in decimal doesn't always make sense because it's a very large
677         // and somewhat gibberish number. The hex code is a bit more
678         // recognizable and easier to search for, so print that.
679         if self.0 & 0x80000000 != 0 {
680             write!(f, "exit code: {:#x}", self.0)
681         } else {
682             write!(f, "exit code: {}", self.0)
683         }
684     }
685 }
686
687 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
688 pub struct ExitStatusError(c::NonZeroDWORD);
689
690 impl Into<ExitStatus> for ExitStatusError {
691     fn into(self) -> ExitStatus {
692         ExitStatus(self.0.into())
693     }
694 }
695
696 impl ExitStatusError {
697     pub fn code(self) -> Option<NonZeroI32> {
698         Some((u32::from(self.0) as i32).try_into().unwrap())
699     }
700 }
701
702 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
703 pub struct ExitCode(c::DWORD);
704
705 impl ExitCode {
706     pub const SUCCESS: ExitCode = ExitCode(EXIT_SUCCESS as _);
707     pub const FAILURE: ExitCode = ExitCode(EXIT_FAILURE as _);
708
709     #[inline]
710     pub fn as_i32(&self) -> i32 {
711         self.0 as i32
712     }
713 }
714
715 impl From<u8> for ExitCode {
716     fn from(code: u8) -> Self {
717         ExitCode(c::DWORD::from(code))
718     }
719 }
720
721 impl From<u32> for ExitCode {
722     fn from(code: u32) -> Self {
723         ExitCode(c::DWORD::from(code))
724     }
725 }
726
727 fn zeroed_startupinfo() -> c::STARTUPINFO {
728     c::STARTUPINFO {
729         cb: 0,
730         lpReserved: ptr::null_mut(),
731         lpDesktop: ptr::null_mut(),
732         lpTitle: ptr::null_mut(),
733         dwX: 0,
734         dwY: 0,
735         dwXSize: 0,
736         dwYSize: 0,
737         dwXCountChars: 0,
738         dwYCountCharts: 0,
739         dwFillAttribute: 0,
740         dwFlags: 0,
741         wShowWindow: 0,
742         cbReserved2: 0,
743         lpReserved2: ptr::null_mut(),
744         hStdInput: ptr::null_mut(),
745         hStdOutput: ptr::null_mut(),
746         hStdError: ptr::null_mut(),
747     }
748 }
749
750 fn zeroed_process_information() -> c::PROCESS_INFORMATION {
751     c::PROCESS_INFORMATION {
752         hProcess: ptr::null_mut(),
753         hThread: ptr::null_mut(),
754         dwProcessId: 0,
755         dwThreadId: 0,
756     }
757 }
758
759 // Produces a wide string *without terminating null*; returns an error if
760 // `prog` or any of the `args` contain a nul.
761 fn make_command_line(argv0: &OsStr, args: &[Arg], force_quotes: bool) -> io::Result<Vec<u16>> {
762     // Encode the command and arguments in a command line string such
763     // that the spawned process may recover them using CommandLineToArgvW.
764     let mut cmd: Vec<u16> = Vec::new();
765
766     // Always quote the program name so CreateProcess to avoid ambiguity when
767     // the child process parses its arguments.
768     // Note that quotes aren't escaped here because they can't be used in arg0.
769     // But that's ok because file paths can't contain quotes.
770     cmd.push(b'"' as u16);
771     cmd.extend(argv0.encode_wide());
772     cmd.push(b'"' as u16);
773
774     for arg in args {
775         cmd.push(' ' as u16);
776         args::append_arg(&mut cmd, arg, force_quotes)?;
777     }
778     Ok(cmd)
779 }
780
781 // Get `cmd.exe` for use with bat scripts, encoded as a UTF-16 string.
782 fn command_prompt() -> io::Result<Vec<u16>> {
783     let mut system: Vec<u16> = super::fill_utf16_buf(
784         |buf, size| unsafe { c::GetSystemDirectoryW(buf, size) },
785         |buf| buf.into(),
786     )?;
787     system.extend("\\cmd.exe".encode_utf16().chain([0]));
788     Ok(system)
789 }
790
791 fn make_envp(maybe_env: Option<BTreeMap<EnvKey, OsString>>) -> io::Result<(*mut c_void, Vec<u16>)> {
792     // On Windows we pass an "environment block" which is not a char**, but
793     // rather a concatenation of null-terminated k=v\0 sequences, with a final
794     // \0 to terminate.
795     if let Some(env) = maybe_env {
796         let mut blk = Vec::new();
797
798         // If there are no environment variables to set then signal this by
799         // pushing a null.
800         if env.is_empty() {
801             blk.push(0);
802         }
803
804         for (k, v) in env {
805             ensure_no_nuls(k.os_string)?;
806             blk.extend(k.utf16);
807             blk.push('=' as u16);
808             blk.extend(ensure_no_nuls(v)?.encode_wide());
809             blk.push(0);
810         }
811         blk.push(0);
812         Ok((blk.as_mut_ptr() as *mut c_void, blk))
813     } else {
814         Ok((ptr::null_mut(), Vec::new()))
815     }
816 }
817
818 fn make_dirp(d: Option<&OsString>) -> io::Result<(*const u16, Vec<u16>)> {
819     match d {
820         Some(dir) => {
821             let mut dir_str: Vec<u16> = ensure_no_nuls(dir)?.encode_wide().collect();
822             dir_str.push(0);
823             Ok((dir_str.as_ptr(), dir_str))
824         }
825         None => Ok((ptr::null(), Vec::new())),
826     }
827 }
828
829 pub struct CommandArgs<'a> {
830     iter: crate::slice::Iter<'a, Arg>,
831 }
832
833 impl<'a> Iterator for CommandArgs<'a> {
834     type Item = &'a OsStr;
835     fn next(&mut self) -> Option<&'a OsStr> {
836         self.iter.next().map(|arg| match arg {
837             Arg::Regular(s) | Arg::Raw(s) => s.as_ref(),
838         })
839     }
840     fn size_hint(&self) -> (usize, Option<usize>) {
841         self.iter.size_hint()
842     }
843 }
844
845 impl<'a> ExactSizeIterator for CommandArgs<'a> {
846     fn len(&self) -> usize {
847         self.iter.len()
848     }
849     fn is_empty(&self) -> bool {
850         self.iter.is_empty()
851     }
852 }
853
854 impl<'a> fmt::Debug for CommandArgs<'a> {
855     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
856         f.debug_list().entries(self.iter.clone()).finish()
857     }
858 }