std\sys\pal\windows/
process.rs

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