std\sys\process/
windows.rs

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