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