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