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