Skip to main content

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