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